repo_id
stringclasses 205
values | file_path
stringlengths 33
141
| content
stringlengths 1
307k
| __index_level_0__
int64 0
0
|
---|---|---|---|
/home/johnshepherd/drake/examples/hydroelastic | /home/johnshepherd/drake/examples/hydroelastic/python_ball_paddle/contact_sim_demo.py | """
This is an example for using hydroelastic contact model through pydrake.
It reads two simple SDFormat files of a compliant hydroelastic ball and
a compliant hydroelastic paddle.
The ball is dropped on an edge of the paddle and bounces off.
"""
import argparse
import numpy as np
from pydrake.math import RigidTransform
from pydrake.math import RollPitchYaw
from pydrake.multibody.parsing import Parser
from pydrake.multibody.plant import AddMultibodyPlant
from pydrake.multibody.plant import MultibodyPlantConfig
from pydrake.systems.analysis import ApplySimulatorConfig
from pydrake.systems.analysis import Simulator
from pydrake.systems.analysis import SimulatorConfig
from pydrake.systems.analysis import PrintSimulatorStatistics
from pydrake.systems.framework import DiagramBuilder
from pydrake.systems.primitives import VectorLogSink
from pydrake.visualization import AddDefaultVisualization
def make_ball_paddle(contact_model, contact_surface_representation,
time_step):
multibody_plant_config = \
MultibodyPlantConfig(
time_step=time_step,
contact_model=contact_model,
contact_surface_representation=contact_surface_representation)
# We pose the paddle, so that its top surface is on World's X-Y plane.
# Intuitively we push it down 1 cm because the box is 2 cm thick.
p_WPaddle_fixed = RigidTransform(RollPitchYaw(0, 0, 0),
np.array([0, 0, -0.01]))
builder = DiagramBuilder()
plant, scene_graph = AddMultibodyPlant(multibody_plant_config, builder)
parser = Parser(plant)
paddle_sdf_url = \
"package://drake/examples/hydroelastic/python_ball_paddle/paddle.sdf"
(paddle,) = parser.AddModels(url=paddle_sdf_url)
plant.WeldFrames(
frame_on_parent_F=plant.world_frame(),
frame_on_child_M=plant.GetFrameByName("paddle", paddle),
X_FM=p_WPaddle_fixed
)
ball_sdf_url = \
"package://drake/examples/hydroelastic/python_ball_paddle/ball.sdf"
parser.AddModels(url=ball_sdf_url)
# TODO(DamrongGuoy): Let users override hydroelastic modulus, dissipation,
# and resolution hint from the two SDF files above.
plant.Finalize()
AddDefaultVisualization(builder=builder)
nx = plant.num_positions() + plant.num_velocities()
state_logger = builder.AddSystem(VectorLogSink(nx))
builder.Connect(plant.get_state_output_port(),
state_logger.get_input_port())
diagram = builder.Build()
return diagram, plant, state_logger
def simulate_diagram(diagram, ball_paddle_plant, state_logger,
ball_init_position, ball_init_velocity,
simulation_time, target_realtime_rate):
q_init_val = np.array([
1, 0, 0, 0, ball_init_position[0], ball_init_position[1],
ball_init_position[2]
])
v_init_val = np.hstack((np.zeros(3), ball_init_velocity))
qv_init_val = np.concatenate((q_init_val, v_init_val))
simulator_config = SimulatorConfig(
target_realtime_rate=target_realtime_rate,
publish_every_time_step=True)
simulator = Simulator(diagram)
ApplySimulatorConfig(simulator_config, simulator)
plant_context = diagram.GetSubsystemContext(ball_paddle_plant,
simulator.get_context())
ball_paddle_plant.SetPositionsAndVelocities(plant_context,
qv_init_val)
simulator.get_mutable_context().SetTime(0)
state_log = state_logger.FindMutableLog(simulator.get_mutable_context())
state_log.Clear()
simulator.Initialize()
simulator.AdvanceTo(boundary_time=simulation_time)
PrintSimulatorStatistics(simulator)
return state_log.sample_times(), state_log.data()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--simulation_time", type=float, default=0.5,
help="Desired duration of the simulation in seconds. "
"Default 0.5.")
parser.add_argument(
"--contact_model", type=str, default="hydroelastic_with_fallback",
help="Contact model. Options are: 'point', 'hydroelastic', "
"'hydroelastic_with_fallback'. "
"Default 'hydroelastic_with_fallback'")
parser.add_argument(
"--contact_surface_representation", type=str, default="polygon",
help="Contact-surface representation for hydroelastics. "
"Options are: 'triangle' or 'polygon'. Default 'polygon'.")
parser.add_argument(
"--time_step", type=float, default=0.001,
help="The fixed time step period (in seconds) of discrete updates "
"for the multibody plant modeled as a discrete system. "
"If zero, we will use an integrator for a continuous system. "
"Non-negative. Default 0.001.")
parser.add_argument(
"--ball_initial_position", nargs=3, metavar=('x', 'y', 'z'),
default=[0, 0, 0.1],
help="Ball's initial position: x, y, z (in meters) in World frame. "
"Default: 0 0 0.1")
parser.add_argument(
"--target_realtime_rate", type=float, default=1.0,
help="Target realtime rate. Default 1.0.")
args = parser.parse_args()
diagram, ball_paddle_plant, state_logger = make_ball_paddle(
args.contact_model, args.contact_surface_representation,
args.time_step)
time_samples, state_samples = simulate_diagram(
diagram, ball_paddle_plant, state_logger,
np.array(args.ball_initial_position),
np.array([0., 0., 0.]),
args.simulation_time, args.target_realtime_rate)
print("\nFinal state variables:")
print(state_samples[:, -1])
| 0 |
/home/johnshepherd/drake/examples/hydroelastic | /home/johnshepherd/drake/examples/hydroelastic/ball_plate/make_ball_plate_plant.cc | #include "drake/examples/hydroelastic/ball_plate/make_ball_plate_plant.h"
#include <string>
#include <utility>
#include "drake/geometry/proximity_properties.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/multibody/tree/multibody_tree_indexes.h"
#include "drake/multibody/tree/uniform_gravity_field_element.h"
namespace drake {
namespace examples {
namespace ball_plate {
using geometry::AddContactMaterial;
using geometry::AddCompliantHydroelasticProperties;
using geometry::ProximityProperties;
using geometry::Sphere;
using multibody::CoulombFriction;
using multibody::MultibodyPlant;
using multibody::RigidBody;
using multibody::SpatialInertia;
using math::RigidTransformd;
using math::RotationMatrixd;
using Eigen::Vector3d;
namespace {
// Add tiny visual cylinders on the ±x,y,z axes of the ball to appreciate
// its rotation.
void AddTinyVisualCylinders(const RigidBody<double>& ball, double radius,
MultibodyPlant<double>* plant) {
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.05 * 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;
// Let S be the sphere's frame (at its center) and C be the cylinder's
// frame (at its center). The goal is to get Cz (frame C's z axis)
// aligned with p_SC, with Cx and Cy arbitrary.
// @return X_SC the pose of the spot cylinder given p_SC.
auto spot_pose = [](const Vector3<double>& p_SC) {
return RigidTransformd(
RotationMatrixd::MakeFromOneVector(p_SC, 2 /*z*/), p_SC);
};
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);
}
} // namespace
void AddBallPlateBodies(
double radius, double mass, double hydroelastic_modulus,
double dissipation, const CoulombFriction<double>& surface_friction,
double resolution_hint_factor, MultibodyPlant<double>* plant) {
DRAKE_DEMAND(plant != nullptr);
// Add the ball. Let B be the ball's frame (at its center). The ball's
// center of mass Bcm is coincident with Bo.
const RigidBody<double>& ball = plant->AddRigidBody(
"Ball", SpatialInertia<double>::SolidSphereWithMass(mass, radius));
// Set up mechanical properties of the ball.
ProximityProperties ball_props;
AddContactMaterial(dissipation, {} /* point stiffness */, surface_friction,
&ball_props);
AddCompliantHydroelasticProperties(radius * resolution_hint_factor,
hydroelastic_modulus, &ball_props);
plant->RegisterCollisionGeometry(ball, RigidTransformd::Identity(),
Sphere(radius), "collision",
std::move(ball_props));
const Vector4<double> orange(1.0, 0.55, 0.0, 0.2);
plant->RegisterVisualGeometry(ball, RigidTransformd::Identity(),
Sphere(radius), "visual", orange);
AddTinyVisualCylinders(ball, radius, plant);
// Add the dinner plate.
drake::multibody::Parser parser(plant);
parser.AddModelsFromUrl("package://drake_models/dishes/plate_8in.sdf");
// Add the floor. Assume the frame named "Floor" is in the SDFormat file.
parser.AddModelsFromUrl(
"package://drake/examples/hydroelastic/ball_plate/floor.sdf");
plant->WeldFrames(plant->world_frame(), plant->GetFrameByName("Floor"),
RigidTransformd::Identity());
// Gravity acting in the -z direction.
plant->mutable_gravity_field().set_gravity_vector(Vector3d{0, 0, -9.81});
}
} // namespace ball_plate
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples/hydroelastic | /home/johnshepherd/drake/examples/hydroelastic/ball_plate/ball_plate_run_dynamics.cc | #include <memory>
#include <gflags/gflags.h>
#include "drake/common/drake_assert.h"
#include "drake/examples/hydroelastic/ball_plate/make_ball_plate_plant.h"
#include "drake/geometry/scene_graph.h"
#include "drake/multibody/plant/multibody_plant_config.h"
#include "drake/multibody/plant/multibody_plant_config_functions.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"
DEFINE_double(simulation_time, 0.4,
"Desired duration of the simulation in seconds.");
// See MultibodyPlantConfig for the valid strings of contact_model.
DEFINE_string(contact_model, "hydroelastic",
"Contact model. Options are: 'point', 'hydroelastic', "
"'hydroelastic_with_fallback'.");
// See MultibodyPlantConfig for the valid strings of contact surface
// representation.
DEFINE_string(contact_surface_representation, "polygon",
"Contact-surface representation for hydroelastics. "
"Options are: 'triangle' or 'polygon'. Default is 'polygon'.");
DEFINE_double(hydroelastic_modulus, 3.0e4,
"Hydroelastic modulus of the ball, [Pa].");
DEFINE_double(resolution_hint_factor, 0.3,
"This scaling factor, [unitless], multiplied by the radius of "
"the ball gives the target edge length of the mesh of the ball "
"on the surface of its hydroelastic representation. The smaller "
"number gives a finer mesh with more tetrahedral elements.");
DEFINE_double(dissipation, 3.0,
"Hunt & Crossley dissipation, [s/m], for the ball");
DEFINE_double(friction_coefficient, 0.3,
"coefficient for both static and dynamic friction, [unitless], "
"of the ball.");
DEFINE_double(mbp_dt, 0.001,
"The fixed time step period (in seconds) of discrete updates "
"for the multibody plant modeled as a discrete system. "
"Strictly positive.");
// Ball's initial spatial velocity.
DEFINE_double(vx, 0,
"Ball's initial translational velocity in the x-axis in m/s.");
DEFINE_double(vy, 0.0,
"Ball's initial translational velocity in the y-axis in m/s.");
DEFINE_double(vz, -7.0,
"Ball's initial translational velocity in the z-axis in m/s.");
DEFINE_double(wx, 0.0,
"Ball's initial angular velocity in the x-axis in degrees/s.");
DEFINE_double(wy, -10.0,
"Ball's initial angular velocity in the y-axis in degrees/s.");
DEFINE_double(wz, 0.0,
"Ball's initial angular velocity in the z-axis in degrees/s.");
// Ball's initial pose.
DEFINE_double(z0, 0.15, "Ball's initial position in the z-axis.");
DEFINE_double(x0, 0.10, "Ball's initial position in the x-axis.");
namespace drake {
namespace examples {
namespace ball_plate {
namespace {
using Eigen::Vector3d;
using drake::math::RigidTransformd;
using drake::multibody::CoulombFriction;
using drake::multibody::SpatialVelocity;
int do_main() {
systems::DiagramBuilder<double> builder;
multibody::MultibodyPlantConfig config;
// We allow only discrete systems.
DRAKE_DEMAND(FLAGS_mbp_dt > 0.0);
config.time_step = FLAGS_mbp_dt;
config.penetration_allowance = 0.001;
config.contact_model = FLAGS_contact_model;
config.contact_surface_representation = FLAGS_contact_surface_representation;
auto [plant, scene_graph] = AddMultibodyPlant(config, &builder);
// Ball's parameters.
const double radius = 0.05; // m
const double mass = 0.1; // kg
AddBallPlateBodies(
radius, mass, FLAGS_hydroelastic_modulus, FLAGS_dissipation,
CoulombFriction<double>{
// static friction (unused in discrete systems)
FLAGS_friction_coefficient,
// dynamic friction
FLAGS_friction_coefficient},
FLAGS_resolution_hint_factor, &plant);
plant.Finalize();
DRAKE_DEMAND(plant.num_velocities() == 12);
DRAKE_DEMAND(plant.num_positions() == 14);
visualization::AddDefaultVisualization(&builder);
auto diagram = builder.Build();
auto simulator = MakeSimulatorFromGflags(*diagram);
// Set the ball's initial pose.
systems::Context<double>& plant_context =
plant.GetMyMutableContextFromRoot(&simulator->get_mutable_context());
plant.SetFreeBodyPose(
&plant_context, plant.GetBodyByName("Ball"),
math::RigidTransformd{Vector3d(FLAGS_x0, 0.0, FLAGS_z0)});
plant.SetFreeBodySpatialVelocity(
&plant_context, plant.GetBodyByName("Ball"),
SpatialVelocity<double>{
M_PI / 180.0 * Vector3d(FLAGS_wx, FLAGS_wy, FLAGS_wz),
Vector3d(FLAGS_vx, FLAGS_vy, FLAGS_vz)});
simulator->AdvanceTo(FLAGS_simulation_time);
systems::PrintSimulatorStatistics(*simulator);
return 0;
}
} // namespace
} // namespace ball_plate
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
gflags::SetUsageMessage(R"""(
This is an example of using the hydroelastic contact model with a non-convex
collision geometry loaded from an SDFormat file of a dinner plate. The ball,
the plate, and the floor are compliant, rigid, and compliant hydroelastic
respectively. Hence, The plate-ball, ball-floor, and plate-floor contacts are
rigid-compliant, compliant-compliant, and rigid-compliant respectively. The
hydroelastic contact model can work with non-convex shapes accurately without
resorting to their convex hulls. Launch meldis before running this example.
See the README.md file for more information.)""");
FLAGS_simulator_publish_every_time_step = true;
FLAGS_simulator_target_realtime_rate = 0.1;
gflags::ParseCommandLineFlags(&argc, &argv, true);
return drake::examples::ball_plate::do_main();
}
| 0 |
/home/johnshepherd/drake/examples/hydroelastic | /home/johnshepherd/drake/examples/hydroelastic/ball_plate/make_ball_plate_plant.h | #pragma once
#include <memory>
#include "drake/geometry/scene_graph.h"
#include "drake/multibody/plant/multibody_plant.h"
namespace drake {
namespace examples {
namespace ball_plate {
/** This function modifies a MultibodyPlant by adding a ball falling on a dinner
plate. The plate and floor are read from sdf files but the ball is
constructed programmatically.
@param[in] radius
The radius (meters) of the ball.
@param[in] mass
The mass (kg) of the ball.
@param[in] hydroelastic_modulus
The hydroelastic modulus (Pa) of the ball.
@param[in] dissipation
The Hunt & Crossley dissipation constant (s/m) for the ball.
@param[in] surface_friction
The Coulomb's law coefficients (unitless) of friction of the ball.
@param[in] resolution_hint_factor
This scaling factor (unitless) multiplied by the radius of the ball
gives the target edge length of the mesh on the surface of the ball.
The smaller number gives a finer mesh with more tetrahedral elements.
@param[in,out] plant
The bodies will be added here.
@pre `plant` is not null.
See also
https://drake.mit.edu/doxygen_cxx/group__hydroelastic__user__guide.html
*/
void AddBallPlateBodies(
double radius, double mass, double hydroelastic_modulus,
double dissipation,
const multibody::CoulombFriction<double>& surface_friction,
double resolution_hint_factor,
multibody::MultibodyPlant<double>* plant);
} // namespace ball_plate
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples/hydroelastic | /home/johnshepherd/drake/examples/hydroelastic/ball_plate/BUILD.bazel | load("//tools/lint:lint.bzl", "add_lint_tests")
load(
"//tools/skylark:drake_cc.bzl",
"drake_cc_binary",
"drake_cc_library",
)
package(default_visibility = ["//visibility:private"])
filegroup(
name = "models",
srcs = [
"floor.sdf",
],
visibility = ["//:__pkg__"],
)
drake_cc_library(
name = "make_ball_plate_plant",
srcs = [
"make_ball_plate_plant.cc",
],
hdrs = [
"make_ball_plate_plant.h",
],
data = [
":models",
"@drake_models//:dishes",
],
deps = [
"//common:default_scalars",
"//geometry:geometry_ids",
"//geometry:scene_graph",
"//math:geometric_transform",
"//multibody/parsing",
"//multibody/plant",
],
)
drake_cc_binary(
name = "ball_plate_run_dynamics",
srcs = ["ball_plate_run_dynamics.cc"],
add_test_rule = 1,
test_rule_args = [
"--simulation_time=0.1",
"--simulator_target_realtime_rate=0.0",
],
deps = [
":make_ball_plate_plant",
"//common:add_text_logging_gflags",
"//systems/analysis:simulator",
"//systems/analysis:simulator_gflags",
"//systems/analysis:simulator_print_stats",
"//systems/framework:diagram",
"//visualization:visualization_config_functions",
"@gflags",
],
)
add_lint_tests(enable_clang_format_lint = False)
| 0 |
/home/johnshepherd/drake/examples/hydroelastic | /home/johnshepherd/drake/examples/hydroelastic/ball_plate/floor.sdf | <?xml version="1.0"?>
<sdf version="1.7">
<model name="Floor">
<!--
We use a 30x30x5-cm rectangular block to represent the compliant floor on
which the dinner plate is placed. We set the hydroelastic modulus of the
floor to be rather small to showcase the contact surface from the
substantial penetration of the dinner plate into the floor.
-->
<link name="Floor">
<pose>0 0 0 0 0 0</pose>
<inertial>
<pose>0 0 0 0 0 0</pose>
<mass>0.1</mass>
<inertia>
<ixx>0.000770833</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>0.000770833</iyy>
<iyz>0</iyz>
<izz>0.0015</izz>
</inertia>
</inertial>
<visual name="visual">
<pose>0 0 -2.5e-2 0 0 0</pose>
<geometry>
<box>
<size>3.0e-1 3.0e-1 5.0e-2</size>
</box>
</geometry>
<material>
<diffuse>0.5 0.5 0.7 0.2</diffuse>
</material>
</visual>
<collision name="collision">
<pose>0 0 -2.5e-2 0 0 0</pose>
<geometry>
<box>
<size>3.0e-1 3.0e-1 5.0e-2</size>
</box>
</geometry>
<drake:proximity_properties>
<drake:compliant_hydroelastic/>
<drake:hydroelastic_modulus> 3.0e4 </drake:hydroelastic_modulus>
<drake:mesh_resolution_hint> 1.0 </drake:mesh_resolution_hint>
<drake:mu_dynamic> 0.3 </drake:mu_dynamic>
<drake:mu_static> 0.3 </drake:mu_static>
<drake:hunt_crossley_dissipation>
3.0
</drake:hunt_crossley_dissipation>
</drake:proximity_properties>
</collision>
</link>
</model>
</sdf>
| 0 |
/home/johnshepherd/drake/examples/hydroelastic | /home/johnshepherd/drake/examples/hydroelastic/ball_plate/README.md | <h1>Rolling ball on a dinner plate on a floor</h1>
This is an example for using hydroelastic contact model with a non-convex
geometry loaded from an SDFormat file of a dinner plate.
The ball, the plate, and the floor are compliant, rigid, and compliant
hydroelastic. The plate-ball, ball-floor, and plate-floor contacts are
rigid-compliant, compliant-compliant, and rigid-compliant.
Hydroelastic contact model can work with non-convex shapes accurately
without resorting to their convex hulls.
In the source code, this example shows how to set up bodies by loading SDFormat
files and also calling C++ APIs.
![ball_plate](../../../multibody/hydroelastics/images/drake-vis-01.png)
<h2>Preliminary step: start the visualizer </h2>
```
bazel run //tools:meldis -- --open-window &
```
<h2>Run with Hydroelastic</h2>
By default, this example uses hydroelastic contact model.
It is intentionally run at 0.1 realtime rate, so we can appreciate dynamics
in the visualization. Otherwise, the simulation is too fast for human eyes.
```
bazel run //examples/hydroelastic/ball_plate:ball_plate_run_dynamics
```
If it's too fast to see, you can slow it down further like this:
```
bazel run //examples/hydroelastic/ball_plate:ball_plate_run_dynamics \
-- --simulator_target_realtime_rate=0.01
```
<h2>Spin the ball</h2>
We want to see dynamics of the ball-plate and the plate-floor contacts.
We use zero for the friction coefficients (`--friction_coefficient`) to make
it very slippery.
We use a very large initial angular velocity of the ball (`--wz`; `w` for `ω`)
around its Z-axis to make it spin very fast.
```
bazel run //examples/hydroelastic/ball_plate:ball_plate_run_dynamics \
-- --friction_coefficient=0 --simulation_time=2.5 \
--simulator_target_realtime_rate=0.1 \
--wz=10000
```
The example command above intentionally specifies very low real-time rate of
0.1, so we can see it easier.
On a good computer, it can run at real-time rate about 1.0.
<h2>Use polygon or triangle contact surfaces</h2>
By default, this example uses polygon contact surfaces. The option
`--contact_surface_representation=triangle` specifies triangle contact surfaces:
```
bazel run //examples/hydroelastic/ball_plate:ball_plate_run_dynamics \
-- --simulator_target_realtime_rate=0.01 \
--contact_surface_representation=triangle
```
<h2>Run with point contact model</h2>
```
bazel run //examples/hydroelastic/ball_plate:ball_plate_run_dynamics \
-- --contact_model=point --simulation_time=120.0 \
--simulator_target_realtime_rate=1.0
```
The option `--contact_model=point` selects the point contact model.
Notice the unphysical oscillation of the dinner plate that does not
dissipate energy despite the very long simulated time specified by
`--simulation_time=120.0`.
Compared to hydroelastic contact, the point contact has to pick one
point from each contact patch.
Since the contact patch between the dinner plate and the floor is quite large,
the chosen point keeps oscillating on the patch.
The option `--simulator_target_realtime_rate=1.0` slows it down enough for
human eyes to see.
<h2>Other Options</h2>
There are other command-line options that you can use. Use `--help` to see
the list. For example, you can set Hunt & Crossley dissipation of the ball,
friction coefficient of the ball, initial position and velocity of the ball,
etc.
```
bazel run //examples/hydroelastic/ball_plate:ball_plate_run_dynamics \
-- --help
```
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/allegro_hand/allegro_lcm.h | #pragma once
/// @file
/// This file contains classes dealing with sending/receiving LCM messages
/// related to the allegro hand.
#include <memory>
#include <utility>
#include <vector>
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/examples/allegro_hand/allegro_common.h"
#include "drake/lcmt_allegro_command.hpp"
#include "drake/lcmt_allegro_status.hpp"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace examples {
namespace allegro_hand {
const double kHardwareStatusPeriod = 0.003;
/// Handles lcmt_allegro_command messages from a LcmSubscriberSystem.
/// Has two output ports: one for the commanded position for each joint along
/// with a zero velocity for each joint, and another for commanded additional
/// feedforward joint torque. The joint torque command is currently not used.
///
/// @system
/// name: AllegroCommandReceiver
/// input_ports:
/// - u0
/// output_ports:
/// - y0
/// - y1
/// @endsystem
///
/// Port `u0` accepts command messages. Ports `y0` and `y1` emit commanded
/// position and feedforward torque, respectively.
class AllegroCommandReceiver : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(AllegroCommandReceiver)
AllegroCommandReceiver(int num_joints = kAllegroNumJoints,
double lcm_period = kHardwareStatusPeriod);
/// Sets the initial position of the controlled hand prior to any
/// commands being received. @param x contains the starting position.
/// This position will be the commanded position (with zero
/// velocity) until a position message is received. If this
/// function is not called, the open hand pose will be the zero
/// configuration.
void set_initial_position(systems::Context<double>* context,
const Eigen::Ref<const VectorX<double>>& x) const;
const systems::OutputPort<double>& get_commanded_state_output_port() const {
return this->get_output_port(state_output_port_);
}
const systems::OutputPort<double>& get_commanded_torque_output_port() const {
return this->get_output_port(torque_output_port_);
}
double lcm_period() const {
return lcm_period_;
}
private:
void CopyStateToOutput(const systems::Context<double>& context, int start_idx,
int length,
systems::BasicVector<double>* output) const;
void UpdateDiscreteVariables(
const systems::Context<double>& context,
systems::DiscreteValues<double>* discrete_state) const;
int state_output_port_ = 0;
int torque_output_port_ = 0;
const int num_joints_ = 16;
const double lcm_period_;
};
/// Creates and outputs lcmt_allegro_status messages.
///
/// This system has three vector-valued input ports, one for the plant's
/// current state, one for the most recently received position command, and one
/// for the most recently received joint torque command.
/// The state and command ports contain a position and velocity for each joint,
/// which is supposed to be in the order of thumb(4)-index(4)-middle(4)-ring(4).
///
/// This system has one abstract valued output port that contains a
/// Value object templated on type `lcmt_allegro_status`. Note that
/// this system does not actually send this message on an LCM channel. To send
/// the message, the output of this system should be connected to an input port
/// of a systems::lcm::LcmPublisherSystem that accepts a Value object
/// templated on type `lcmt_allegro_status`.
///
/// @system
/// name: AllegroStatusSender
/// input_ports:
/// - u0
/// - u1
/// - u2
/// output_ports:
/// - y0
/// @endsystem
///
/// Ports `u0`, `u1`, and `u2` accept state, commanded position, and commanded
/// torque, respectively. Port `y0` emits status messages.
///
/// This system is presently only used in simulation.
class AllegroStatusSender : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(AllegroStatusSender)
explicit AllegroStatusSender(int num_joints = kAllegroNumJoints);
const systems::InputPort<double>& get_command_input_port() const {
return this->get_input_port(command_input_port_);
}
const systems::InputPort<double>& get_state_input_port() const {
return this->get_input_port(state_input_port_);
}
const systems::InputPort<double>& get_commanded_torque_input_port() const {
return this->get_input_port(command_torque_input_port_);
}
private:
// This is the calculator method for the output port.
void OutputStatus(const systems::Context<double>& context,
lcmt_allegro_status* output) const;
int command_input_port_ = 0;
int state_input_port_ = 0;
int command_torque_input_port_ = 0;
const int num_joints_ = 16;
};
} // namespace allegro_hand
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/allegro_hand/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 = "allegro_common",
srcs = ["allegro_common.cc"],
hdrs = ["allegro_common.h"],
visibility = ["//examples/allegro_hand/joint_control:__pkg__"],
deps = [
"//lcmtypes:allegro",
"//multibody/plant",
],
)
drake_cc_library(
name = "allegro_lcm",
srcs = ["allegro_lcm.cc"],
hdrs = ["allegro_lcm.h"],
visibility = ["//examples/allegro_hand/joint_control:__pkg__"],
deps = [
":allegro_common",
"//lcmtypes:allegro",
"//systems/framework:leaf_system",
],
)
drake_cc_binary(
name = "run_allegro_constant_load_demo",
srcs = ["run_allegro_constant_load_demo.cc"],
data = [
"@drake_models//:allegro_hand_description",
],
deps = [
"//common:add_text_logging_gflags",
"//lcm",
"//multibody/parsing",
"//multibody/plant",
"//systems/analysis:simulator",
"//systems/primitives:constant_vector_source",
"//visualization:visualization_config_functions",
"@gflags",
],
)
# === test/ ===
drake_cc_googletest(
name = "allegro_lcm_test",
deps = [
":allegro_common",
":allegro_lcm",
"//common/test_utilities:eigen_matrix_compare",
"//systems/framework",
],
)
drake_cc_googletest(
name = "parse_test",
data = [
"@drake_models//:allegro_hand_description",
],
deps = [
"//common:find_resource",
"//multibody/parsing",
"//multibody/plant",
],
)
add_lint_tests(enable_clang_format_lint = False)
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/allegro_hand/allegro_common.cc | #include "drake/examples/allegro_hand/allegro_common.h"
#include <iostream>
namespace drake {
namespace examples {
namespace allegro_hand {
const double AllegroHandMotionState::velocity_thresh_ = 0.07;
using drake::multibody::JointIndex;
using drake::multibody::MultibodyPlant;
void SetPositionControlledGains(double pid_frequency, double Ieff,
Eigen::VectorXd* Kp, Eigen::VectorXd* Ki,
Eigen::VectorXd* Kd) {
// Each finger joint with PID control is equivalent to a spring mass system
// with mass Ieff, spring constant gain_prop, and damping coefficient
// gain_der.
// pid_frequency is the desired (angular, rad/sec) frequency of the PID
// controlled joint. In this regard, this parameter specifies the desired time
// scale of the effective system.
// Therefore we use the harmonic oscillator expressions to obtain the PID
// gains given pid_frequency and Ieff:
// pid_frequency² = gain_prop / Ieff
// 2 * pid_frequency * zeta = gain_der / Ieff
const double gain_prop = pid_frequency * pid_frequency * Ieff;
const double zeta = 0.4;
const double gain_der = 2.0 * pid_frequency * Ieff * zeta;
std::cout << "PID frequency [Hz]: " << pid_frequency << std::endl;
std::cout << "Kp [Nm/rad]: " << gain_prop << std::endl;
std::cout << "Kd [Nms/rad]: " << gain_der << std::endl;
*Kp = Eigen::VectorXd::Ones(kAllegroNumJoints) * gain_prop;
*Kd = Eigen::VectorXd::Constant(Kp->size(), gain_der);
(*Kp)[0] *= 1.6; // The thumb is slightly more massive.
*Ki = Eigen::VectorXd::Zero(kAllegroNumJoints);
}
std::vector<std::string> GetPreferredJointOrdering() {
std::vector<std::string> joint_name_mapping;
// Thumb finger
joint_name_mapping.push_back("joint_12");
joint_name_mapping.push_back("joint_13");
joint_name_mapping.push_back("joint_14");
joint_name_mapping.push_back("joint_15");
// Index finger
joint_name_mapping.push_back("joint_0");
joint_name_mapping.push_back("joint_1");
joint_name_mapping.push_back("joint_2");
joint_name_mapping.push_back("joint_3");
// Middle finger
joint_name_mapping.push_back("joint_4");
joint_name_mapping.push_back("joint_5");
joint_name_mapping.push_back("joint_6");
joint_name_mapping.push_back("joint_7");
// Ring finger
joint_name_mapping.push_back("joint_8");
joint_name_mapping.push_back("joint_9");
joint_name_mapping.push_back("joint_10");
joint_name_mapping.push_back("joint_11");
return joint_name_mapping;
}
void GetControlPortMapping(
const MultibodyPlant<double>& plant,
MatrixX<double>* Sx, MatrixX<double>* Sy) {
// Retrieve the list of finger joints in a user-defined ordering.
const std::vector<std::string> joints_in_preferred_order =
GetPreferredJointOrdering();
// Make a list of the same joints but by JointIndex.
std::vector<JointIndex> joint_index_mapping;
for (const auto& joint_name : joints_in_preferred_order) {
joint_index_mapping.push_back(plant.GetJointByName(joint_name).index());
}
*Sx = plant.MakeStateSelectorMatrix(joint_index_mapping);
*Sy = plant.MakeActuatorSelectorMatrix(joint_index_mapping);
}
AllegroHandMotionState::AllegroHandMotionState()
: finger_num_(allegro_num_joints_ / 4),
is_joint_stuck_(allegro_num_joints_),
is_finger_stuck_(finger_num_) {}
void AllegroHandMotionState::Update(
const lcmt_allegro_status& allegro_state_msg) {
const lcmt_allegro_status status = allegro_state_msg;
const double* ptr = &(status.joint_velocity_estimated[0]);
const Eigen::ArrayXd joint_velocity =
Eigen::Map<const Eigen::ArrayXd>(ptr, allegro_num_joints_);
const Eigen::ArrayXd torque_command = Eigen::Map<const Eigen::ArrayXd>(
&(status.joint_torque_commanded[0]), allegro_num_joints_);
is_joint_stuck_ = joint_velocity.abs() < velocity_thresh_;
// Detect whether the joint is moving in the opposite direction of the
// command. If yes, it is most likely the joint is stuck.
Eigen::Array<bool, Eigen::Dynamic, 1> motor_reverse =
(joint_velocity * torque_command) < -0.001;
is_joint_stuck_ += motor_reverse;
is_finger_stuck_.setZero();
if (is_joint_stuck_.segment<4>(0).all()) is_finger_stuck_(0) = true;
if (is_joint_stuck_.segment<3>(5).all()) is_finger_stuck_(1) = true;
if (is_joint_stuck_.segment<3>(9).all()) is_finger_stuck_(2) = true;
if (is_joint_stuck_.segment<3>(13).all()) is_finger_stuck_(3) = true;
if (motor_reverse.segment<3>(5).any()) is_finger_stuck_(1) = true;
if (motor_reverse.segment<3>(9).any()) is_finger_stuck_(2) = true;
if (motor_reverse.segment<3>(13).any()) is_finger_stuck_(3) = true;
}
Eigen::Vector4d AllegroHandMotionState::FingerGraspJointPosition(
int finger_index) const {
Eigen::Vector4d position;
// The numbers corresponds to the joint positions when the hand grasps a
// medium size object, such as the mug. The final positions of the joints
// are usually larger than the preset values, so that the fingers continuously
// apply force on the object.
if (finger_index == 0)
position << 1.396, 0.85, 0, 1.3;
else if (finger_index == 1)
position << 0.08, 0.9, 0.75, 1.5;
else if (finger_index == 2)
position << 0.1, 0.9, 0.75, 1.5;
else
position << 0.12, 0.9, 0.75, 1.5;
return position;
}
Eigen::Vector4d AllegroHandMotionState::FingerOpenJointPosition(
int finger_index) const {
Eigen::Vector4d position;
// The preset position of the joints when the hand is open. The thumb joints
// are not at 0 positions, so that it starts from the lower limit, and faces
// upward.
position.setZero();
if (finger_index == 0) position << 0.263, 1.1, 0, 0;
return position;
}
} // namespace allegro_hand
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/allegro_hand/run_allegro_constant_load_demo.cc | /// @file
///
/// This demo sets up a simple dynamic simulation for the Allegro hand using
/// the multi-body library. A single, constant torque is applied to all joints
/// and defined by a command-line parameter. This demo also allows to specify
/// whether the right or left hand is simulated.
#include <gflags/gflags.h>
#include "drake/common/drake_assert.h"
#include "drake/geometry/scene_graph.h"
#include "drake/lcm/drake_lcm.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/multibody/plant/multibody_plant.h"
#include "drake/multibody/tree/revolute_joint.h"
#include "drake/multibody/tree/uniform_gravity_field_element.h"
#include "drake/multibody/tree/weld_joint.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"
#include "drake/visualization/visualization_config_functions.h"
namespace drake {
namespace examples {
namespace allegro_hand {
using drake::multibody::MultibodyPlant;
DEFINE_double(constant_load, 0, "the constant load on each joint, Unit [Nm]."
"Suggested load is in the order of 0.01 Nm. When input value"
"equals to 0 (default), the program runs a passive simulation.");
DEFINE_double(simulation_time, 5,
"Desired duration of the simulation in seconds");
DEFINE_bool(use_right_hand, true,
"Which hand to model: true for right hand or false for left hand");
DEFINE_double(max_time_step, 1.0e-4,
"Simulation time step used for integrator.");
DEFINE_bool(add_gravity, true, "Indicator for whether terrestrial gravity"
" (9.81 m/s²) is included or not.");
DEFINE_double(target_realtime_rate, 1,
"Desired rate relative to real time. See documentation for "
"Simulator::set_target_realtime_rate() for details.");
void DoMain() {
DRAKE_DEMAND(FLAGS_simulation_time > 0);
systems::DiagramBuilder<double> builder;
auto [plant, scene_graph] =
multibody::AddMultibodyPlantSceneGraph(&builder, FLAGS_max_time_step);
std::string hand_url;
if (FLAGS_use_right_hand) {
hand_url = "package://drake_models/"
"allegro_hand_description/sdf/allegro_hand_description_right.sdf";
} else {
hand_url = "package://drake_models/"
"allegro_hand_description/sdf/allegro_hand_description_left.sdf";
}
multibody::Parser(&plant).AddModelsFromUrl(hand_url);
// Weld the hand to the world frame
const auto& joint_hand_root = plant.GetBodyByName("hand_root");
plant.AddJoint<multibody::WeldJoint>("weld_hand", plant.world_body(),
std::nullopt, joint_hand_root, std::nullopt,
math::RigidTransformd::Identity());
if (!FLAGS_add_gravity) {
plant.mutable_gravity_field().set_gravity_vector(
Eigen::Vector3d::Zero());
}
// Now the model is complete.
plant.Finalize();
DRAKE_DEMAND(plant.num_actuators() == 16);
DRAKE_DEMAND(plant.num_actuated_dofs() == 16);
// constant force input
VectorX<double> constant_load_value = VectorX<double>::Ones(
plant.num_actuators()) * FLAGS_constant_load;
auto constant_source =
builder.AddSystem<systems::ConstantVectorSource<double>>(
constant_load_value);
constant_source->set_name("constant_source");
builder.Connect(constant_source->get_output_port(),
plant.get_actuation_input_port());
visualization::AddDefaultVisualization(&builder);
std::unique_ptr<systems::Diagram<double>> 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());
// Initialize joint angle. 3 joints on the index, middle and ring fingers
// are set to some arbitrary values.
const multibody::RevoluteJoint<double>& joint_finger_1_root =
plant.GetJointByName<multibody::RevoluteJoint>("joint_1");
joint_finger_1_root.set_angle(&plant_context, 0.5);
const multibody::RevoluteJoint<double>& joint_finger_2_middle =
plant.GetJointByName<multibody::RevoluteJoint>("joint_6");
joint_finger_2_middle.set_angle(&plant_context, -0.1);
const multibody::RevoluteJoint<double>& joint_finger_3_tip =
plant.GetJointByName<multibody::RevoluteJoint>("joint_11");
joint_finger_3_tip.set_angle(&plant_context, 0.5);
// Set up simulator.
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);
}
} // namespace allegro_hand
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
gflags::SetUsageMessage(
"A simple dynamic simulation for the Allegro hand moving under constant"
" torques.");
gflags::ParseCommandLineFlags(&argc, &argv, true);
drake::examples::allegro_hand::DoMain();
return 0;
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/allegro_hand/allegro_common.h | #pragma once
#include <map>
#include <string>
#include <vector>
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/lcmt_allegro_status.hpp"
#include "drake/multibody/plant/multibody_plant.h"
namespace drake {
namespace examples {
namespace allegro_hand {
constexpr int kAllegroNumJoints = 16;
/// Set the feedback gains for the simulated position control
void SetPositionControlledGains(double pid_frequency, double Ieff,
Eigen::VectorXd* Kp, Eigen::VectorXd* Ki,
Eigen::VectorXd* Kd);
/// Creates selector matrices which extract state xₛ in a known order from the
/// plant's full x (`xₛ = Sx⋅x`) and promote the controller's ordered yₛ into
/// the full plant's input actuation (`u = Su⋅uₛ`).
/// The matrices are used to initialize the PID controller for the hand.
/// @see MultibodyPlant::MakeStateSelectorMatrix(),
/// MultibodyPlant::MakeActuatorSelectorMatrix() for detailed definitions for
/// the selector matrices.
/// @see systems::controllers::PidController for documentation on how these
/// selector matrices are used in the PID controller.
/// @param Sx the matrix to match the output state of the plant into the state
/// of the finger joints in the desired order.
/// @param Sy the matrix to match the output torque for the hand joint
/// actuators in the desired order into the input actuation of the plant.
void GetControlPortMapping(
const multibody::MultibodyPlant<double>& plant,
MatrixX<double>* Sx, MatrixX<double>* Sy);
/// Defines the desired ordering of the finger joints by name. The fingers are
/// ordered as [thumb, index, middle, ring] and the joints of each finger are
/// ordered from most proximal to most distal (relative to the palm).
std::vector<std::string> GetPreferredJointOrdering();
/// Detecting the state of the fingers: whether the joints are moving, or
/// reached the destination, or got stuck by external collisions in the midway.
/// The class uses only the hand status from the MBP as the input, and calculate
/// the state according to the position, velocity, and command position of each
/// joint. The class also contains two commonly used pre-set joint state for
/// opening the hand and closing the hand for grasping.
class AllegroHandMotionState {
public:
DRAKE_DEFAULT_COPY_AND_MOVE_AND_ASSIGN(AllegroHandMotionState)
AllegroHandMotionState();
/// Update the states of the joints and fingers upon receiving the new
/// message about hand staties.
void Update(const lcmt_allegro_status& allegro_state_msg);
/// Pre-set joint positions for grasping objects and open hands.
/// @param finger_index: the index of the fingers whose joint values are in
/// request.
Eigen::Vector4d FingerGraspJointPosition(int finger_index) const;
Eigen::Vector4d FingerOpenJointPosition(int finger_index) const;
/// Returns true when the finger is stuck, which means the joints on the
/// finger stops moving or back driving, regardless of it having reached the
/// target position or not.
bool IsFingerStuck(int finger_index) const {
return is_finger_stuck_(finger_index);
}
bool IsAllFingersStuck() const { return is_finger_stuck_.all(); }
/// Return whether any of the fingers, other than the thumb, is stuck.
bool IsAnyHighFingersStuck() const {
return is_finger_stuck_.segment<3>(1).any();
}
private:
int allegro_num_joints_{kAllegroNumJoints};
int finger_num_{0};
Eigen::Array<bool, Eigen::Dynamic, 1> is_joint_stuck_;
Eigen::Array<bool, Eigen::Dynamic, 1> is_finger_stuck_;
/// The velocity threshold under which the joint is considered not moving.
static const double velocity_thresh_;
};
} // namespace allegro_hand
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/allegro_hand/allegro_lcm.cc | #include "drake/examples/allegro_hand/allegro_lcm.h"
#include <utility>
#include <vector>
#include "drake/common/drake_assert.h"
namespace drake {
namespace examples {
namespace allegro_hand {
using systems::BasicVector;
using systems::Context;
using systems::DiscreteValues;
using systems::DiscreteUpdateEvent;
AllegroCommandReceiver::AllegroCommandReceiver(int num_joints,
double lcm_period)
: num_joints_(num_joints), lcm_period_(lcm_period) {
DRAKE_THROW_UNLESS(lcm_period > 0);
this->DeclareAbstractInputPort(
systems::kUseDefaultName,
Value<lcmt_allegro_command>{});
state_output_port_ =
this->DeclareVectorOutputPort(
systems::kUseDefaultName, num_joints_ * 2,
[this](const Context<double>& c, BasicVector<double>* o) {
this->CopyStateToOutput(c, 0, num_joints_ * 2, o);
})
.get_index();
torque_output_port_ =
this->DeclareVectorOutputPort(
systems::kUseDefaultName, num_joints_,
[this](const Context<double>& c, BasicVector<double>* o) {
this->CopyStateToOutput(c, num_joints_ * 2, num_joints_, o);
})
.get_index();
this->DeclarePeriodicDiscreteUpdateEvent(
lcm_period_, 0.0, &AllegroCommandReceiver::UpdateDiscreteVariables);
// State + torque
this->DeclareDiscreteState(num_joints_ * 3);
}
void AllegroCommandReceiver::set_initial_position(
Context<double>* context,
const Eigen::Ref<const VectorX<double>>& x) const {
auto state_value = context->get_mutable_discrete_state(0).get_mutable_value();
DRAKE_ASSERT(x.size() == num_joints_);
state_value.setZero();
state_value.head(num_joints_) = x;
}
void AllegroCommandReceiver::UpdateDiscreteVariables(
const Context<double>& context,
DiscreteValues<double>* discrete_state) const {
const AbstractValue* input = this->EvalAbstractInput(context, 0);
DRAKE_ASSERT(input != nullptr);
const auto& command = input->get_value<lcmt_allegro_command>();
BasicVector<double>& state = discrete_state->get_mutable_vector(0);
auto state_value = state.get_mutable_value();
// If we're using a default constructed message (haven't received
// a command yet), keep using the initial state.
if (command.num_joints != 0) {
DRAKE_DEMAND(command.num_joints == num_joints_);
VectorX<double> new_positions(num_joints_);
for (int i = 0; i < command.num_joints; ++i) {
new_positions(i) = command.joint_position[i];
}
state_value.segment(num_joints_, num_joints_).setZero();
state_value.head(num_joints_) = new_positions;
}
// If the message does not contain torque commands, set torque command to
// zeros.
if (command.num_torques == 0) {
state_value.tail(num_joints_).setZero();
} else {
DRAKE_DEMAND(command.num_torques == num_joints_);
for (int i = 0; i < num_joints_; i++)
state_value[2 * num_joints_ + i] = command.joint_torque[i];
}
}
void AllegroCommandReceiver::CopyStateToOutput(
const Context<double>& context, int start_idx, int length,
BasicVector<double>* output) const {
Eigen::VectorBlock<VectorX<double>> output_vec = output->get_mutable_value();
output_vec =
context.get_discrete_state(0).get_value().segment(start_idx, length);
}
AllegroStatusSender::AllegroStatusSender(int num_joints)
: num_joints_(num_joints) {
// Commanded state.
command_input_port_ = this->DeclareInputPort(
systems::kUseDefaultName, systems::kVectorValued, num_joints_ * 2)
.get_index();
// Measured state.
state_input_port_ = this->DeclareInputPort(
systems::kUseDefaultName, systems::kVectorValued, num_joints_ * 2)
.get_index();
// Commanded torque.
command_torque_input_port_ = this->DeclareInputPort(
systems::kUseDefaultName, systems::kVectorValued, num_joints_)
.get_index();
this->DeclareAbstractOutputPort(systems::kUseDefaultName,
&AllegroStatusSender::OutputStatus);
}
void AllegroStatusSender::OutputStatus(const Context<double>& context,
lcmt_allegro_status* output) const {
lcmt_allegro_status& status = *output;
status.utime = context.get_time() * 1e6;
const systems::BasicVector<double>* command =
this->EvalVectorInput(context, 0);
const systems::BasicVector<double>* state = this->EvalVectorInput(context, 1);
const systems::BasicVector<double>* commanded_torque =
this->EvalVectorInput(context, 2);
status.num_joints = num_joints_;
status.joint_position_measured.resize(num_joints_, 0);
status.joint_velocity_estimated.resize(num_joints_, 0);
status.joint_position_commanded.resize(num_joints_, 0);
status.joint_torque_commanded.resize(num_joints_, 0);
for (int i = 0; i < num_joints_; ++i) {
status.joint_position_measured[i] = state->GetAtIndex(i);
status.joint_velocity_estimated[i] = state->GetAtIndex(i + num_joints_);
status.joint_position_commanded[i] = command->GetAtIndex(i);
status.joint_torque_commanded[i] = commanded_torque->GetAtIndex(i);
}
}
} // namespace allegro_hand
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples/allegro_hand | /home/johnshepherd/drake/examples/allegro_hand/joint_control/run_twisting_mug.cc | /// @file
///
/// This file set up an example about control the allegro hand based on
/// position. In the program, the hand firstly grasps on a mug, and then twsits
/// it repeatedly. The program presently only runs on simulation, with the file
/// allegro_single_object_simulation.cc which creates the simulation environment
/// for the hand and object. This program reads from LCM about the state of the
/// hands, and process command the positions of the finger joints through LCM.
/// It also uses the velocity states of the fingers to decide whether the hand
/// has finished the current motion, either by reaching the target position or
/// get stuck by collisions.
#include <iostream>
#include "lcm/lcm-cpp.hpp"
#include <Eigen/Dense>
#include <gflags/gflags.h>
#include "drake/examples/allegro_hand/allegro_common.h"
#include "drake/examples/allegro_hand/allegro_lcm.h"
#include "drake/lcmt_allegro_command.hpp"
#include "drake/lcmt_allegro_status.hpp"
DEFINE_int32(max_cycles, 1000'000'000, "Stop after this many twists.");
namespace drake {
namespace examples {
namespace allegro_hand {
namespace {
const char* const kLcmStatusChannel = "ALLEGRO_STATUS";
const char* const kLcmCommandChannel = "ALLEGRO_COMMAND";
class PositionCommander {
public:
PositionCommander() {
lcm_.subscribe(kLcmStatusChannel, &PositionCommander::HandleStatus,
this);
}
void Run() {
allegro_command_.num_joints = kAllegroNumJoints;
allegro_command_.joint_position.resize(kAllegroNumJoints, 0.);
allegro_command_.num_torques = 0;
allegro_command_.joint_torque.resize(0);
flag_moving = true;
Eigen::VectorXd target_joint_position(kAllegroNumJoints);
target_joint_position.setZero();
MovetoPositionUntilStuck(target_joint_position);
// close thumb
target_joint_position(0) = 1.396;
target_joint_position(1) = 0.3;
MovetoPositionUntilStuck(target_joint_position);
// close other fingers
target_joint_position.segment<4>(0) =
hand_state_.FingerGraspJointPosition(0);
target_joint_position.segment<4>(4) =
hand_state_.FingerGraspJointPosition(1);
target_joint_position.segment<4>(8) =
hand_state_.FingerGraspJointPosition(2);
target_joint_position.segment<4>(12) =
hand_state_.FingerGraspJointPosition(3);
MovetoPositionUntilStuck(target_joint_position);
std::cout << "Hand is closed. \n";
while (0 == lcm_.handleTimeout(10)) {
}
// Record the joint position q when the fingers are close and gripping the
// object
Eigen::VectorXd close_hand_joint_position = Eigen::Map<Eigen::VectorXd>(
&(allegro_status_.joint_position_measured[0]), kAllegroNumJoints);
// twisting the cup repeatedly
for (int cycle = 0; cycle < FLAGS_max_cycles; ++cycle) {
target_joint_position = close_hand_joint_position;
// The middle finger works as a pivot finger for the rotation, and exert
// a little force to maintain the stabilization of the mug, which is
// realized by adding some extra pushing motion towards the balance
// position. Eigen::Vector3d(1, 1, 0.5) is a number based on experience
// to keep the finger position, and 0.1 is the coefficient related to
// the extra force to apply.
target_joint_position.segment<3>(9) +=
(0.1 * Eigen::Vector3d(1, 1, 0.5));
// The thumb works as another pivot finger, and is expected to exert a
// large force in order to keep stabilization.
target_joint_position.segment<4>(0) =
hand_state_.FingerGraspJointPosition(0);
// The index finger works as the actuating finger, where (1, 0.3, 0.5) is
// the portion of the joint motion for actuating the mug rotation, 0.6 is
// the coefficient to determine how much the rotation should be.
target_joint_position.segment<3>(5) +=
(0.6 * Eigen::Vector3d(1, 0.3, 0.5));
MovetoPositionUntilStuck(target_joint_position);
target_joint_position = close_hand_joint_position;
target_joint_position.segment<3>(9) +=
(0.1 * Eigen::Vector3d(1, 1, 0.5));
target_joint_position.segment<4>(0) =
hand_state_.FingerGraspJointPosition(0);
// The ring finger works as the actuating finger now to rotate the mug in
// the opposite direction.
target_joint_position.segment<3>(13) +=
(0.6 * Eigen::Vector3d(1, 0.3, 0.5));
MovetoPositionUntilStuck(target_joint_position);
}
}
private:
void PublishPositionCommand(
const Eigen::VectorXd& target_joint_position) {
Eigen::VectorXd::Map(&allegro_command_.joint_position[0],
kAllegroNumJoints) = target_joint_position;
lcm_.publish(kLcmCommandChannel, &allegro_command_);
}
void MovetoPositionUntilStuck(
const Eigen::VectorXd& target_joint_position) {
PublishPositionCommand(target_joint_position);
// A time delay at the initial moving stage so that the noisy data from the
// hand motion is filtered.
for (int i = 0; i < 60; i++) {
while (0 == lcm_.handleTimeout(10) || allegro_status_.utime == -1) {
}
}
// wait until the fingers are stuck, or stop moving.
while (flag_moving) {
while (0 == lcm_.handleTimeout(10) || allegro_status_.utime == -1) {
}
}
}
void HandleStatus(const ::lcm::ReceiveBuffer*, const std::string&,
const lcmt_allegro_status* status) {
allegro_status_ = *status;
hand_state_.Update(allegro_status_);
flag_moving = !hand_state_.IsAllFingersStuck();
}
::lcm::LCM lcm_;
lcmt_allegro_status allegro_status_;
lcmt_allegro_command allegro_command_;
AllegroHandMotionState hand_state_;
bool flag_moving = true;
};
int do_main() {
PositionCommander runner;
runner.Run();
return 0;
}
} // namespace
} // namespace allegro_hand
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
return drake::examples::allegro_hand::do_main();
}
| 0 |
/home/johnshepherd/drake/examples/allegro_hand | /home/johnshepherd/drake/examples/allegro_hand/joint_control/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_binary(
name = "allegro_single_object_simulation",
srcs = ["allegro_single_object_simulation.cc"],
data = [
":simple_mug.sdf",
"@drake_models//:allegro_hand_description",
],
deps = [
"//common:add_text_logging_gflags",
"//examples/allegro_hand:allegro_common",
"//examples/allegro_hand:allegro_lcm",
"//lcmtypes:allegro",
"//math:geometric_transform",
"//multibody/parsing",
"//multibody/plant",
"//multibody/plant:contact_results_to_lcm",
"//systems/analysis:simulator",
"//systems/analysis:simulator_gflags",
"//systems/controllers:pid_controller",
"//systems/framework:diagram",
"//systems/lcm:lcm_pubsub_system",
"//systems/primitives:matrix_gain",
"//visualization",
"@gflags",
],
)
drake_cc_binary(
name = "run_twisting_mug",
srcs = ["run_twisting_mug.cc"],
deps = [
"//examples/allegro_hand:allegro_common",
"//examples/allegro_hand:allegro_lcm",
"//lcmtypes:allegro",
"@gflags",
"@lcm",
],
)
drake_py_unittest(
name = "run_twisting_mug_test",
timeout = "moderate",
allow_network = ["lcm:meshcat"],
args = select({
"//tools/cc_toolchain:debug": ["--compilation_mode=dbg"],
"//conditions:default": ["--compilation_mode=opt"],
}),
data = [
":allegro_single_object_simulation",
":run_twisting_mug",
],
flaky = True,
deps = [
"@rules_python//python/runfiles",
],
)
add_lint_tests(enable_clang_format_lint = False)
| 0 |
/home/johnshepherd/drake/examples/allegro_hand | /home/johnshepherd/drake/examples/allegro_hand/joint_control/README.md | # Allegro Hand - Joint Control Example
The following shows a simple multiprocess setup where a simulation is run in
one process, and a simple open-loop finger-gaiting controller is run in another
process. No time synchronization is performed between the controller and the
simulator, so real-time rates may affect the resultant behavior.
This should run for a quite a few finger gaits, and remain stable in the sense
that the joint-level controllers do not cause the simulation to become unstable
in a numerical sense. Eventually, the mug may come loose, which is expected for
this simple controller setup.
Open a visualizer window
```
bazel run //tools:meldis -- --open-window &
```
To run the following example:
```sh
bazel build //examples/allegro_hand/joint_control/...
```
Run each of the following lines in separate terminals:
```sh
bazel-bin/examples/allegro_hand/joint_control/allegro_single_object_simulation \
--simulator_target_realtime_rate=1.0
bazel-bin/examples/allegro_hand/joint_control/run_twisting_mug
```
| 0 |
/home/johnshepherd/drake/examples/allegro_hand | /home/johnshepherd/drake/examples/allegro_hand/joint_control/simple_mug.sdf | <?xml version="1.0"?>
<sdf version="1.7">
<model name="simple_mug">
<link name="simple_mug">
<inertial>
<pose>0.01 0 0.05 0 0 0</pose>
<mass>0.094</mass>
<inertia>
<ixx>0.000156</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>0.000156</iyy>
<iyz>0</iyz>
<izz>0.00015</izz>
</inertia>
</inertial>
<collision name="main_body_collision">
<pose>0 0 0.05 0 0 0</pose>
<geometry>
<cylinder>
<length>0.13</length>
<radius>0.04</radius>
</cylinder>
</geometry>
<surface>
<friction>
<ode>
<mu>0.9</mu>
<mu2>0.5</mu2>
</ode>
</friction>
</surface>
</collision>
<collision name="mug_handle_collision">
<pose>0.055 0 0.05 0 0 0</pose>
<geometry>
<box>
<size>0.03 0.02 0.08</size>
</box>
</geometry>
</collision>
<visual name="main_body_visual">
<pose>0 0 0.05 0 0 0</pose>
<geometry>
<cylinder>
<length>0.13</length>
<radius>0.04</radius>
</cylinder>
</geometry>
</visual>
<visual name="mug_handle_visual">
<pose>0.055 0 0.05 0 0 0</pose>
<geometry>
<box>
<size>0.03 0.02 0.08</size>
</box>
</geometry>
</visual>
</link>
</model>
</sdf>
| 0 |
/home/johnshepherd/drake/examples/allegro_hand | /home/johnshepherd/drake/examples/allegro_hand/joint_control/allegro_single_object_simulation.cc | /// @file
///
/// This file set up a simulation environment of an allegro hand and an object.
/// The system is designed for position control of the hand, with a PID
/// controller to control the output torque. The system communicate with the
/// external program through LCM system, with a publisher to publish the
/// current state of the hand, and a subscriber to read the posiiton commands
/// of the finger joints.
#include <gflags/gflags.h>
#include "drake/common/drake_assert.h"
#include "drake/examples/allegro_hand/allegro_common.h"
#include "drake/examples/allegro_hand/allegro_lcm.h"
#include "drake/lcmt_allegro_command.hpp"
#include "drake/lcmt_allegro_status.hpp"
#include "drake/math/rotation_matrix.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/multibody/plant/contact_results.h"
#include "drake/multibody/plant/contact_results_to_lcm.h"
#include "drake/multibody/plant/multibody_plant.h"
#include "drake/multibody/tree/uniform_gravity_field_element.h"
#include "drake/multibody/tree/weld_joint.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/analysis/simulator_gflags.h"
#include "drake/systems/controllers/pid_controller.h"
#include "drake/systems/framework/diagram.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/matrix_gain.h"
#include "drake/visualization/visualization_config_functions.h"
namespace drake {
namespace examples {
namespace allegro_hand {
namespace {
using math::RigidTransformd;
using math::RollPitchYawd;
using multibody::JointActuator;
using multibody::JointActuatorIndex;
using multibody::ModelInstanceIndex;
using multibody::MultibodyPlant;
DEFINE_double(simulation_time, std::numeric_limits<double>::infinity(),
"Desired duration of the simulation in seconds");
DEFINE_bool(use_right_hand, true,
"Which hand to model: true for right hand or false for left hand");
DEFINE_bool(add_gravity, false,
"Whether adding gravity (9.81 m/s^2) in the simulation");
DEFINE_double(
mbp_discrete_update_period, 1.0e-2,
"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_double(gear_ratio, 369.0,
"The gear ratio of each actuator, dimensionless.");
DEFINE_double(
rotor_inertia, 1.0e-6,
"Estimated rotor inertia for the rotor of each actuator, in [kg⋅m²]. If "
"zero the effect of reflected inertia is not modeled.");
DEFINE_double(
pid_frequency, 10.0,
"This frequency determines the time scale of the PID controller.");
// Modeling the Allegro hand with and without reflected inertia.
// The default command line parameters are set to model an Allegro hand that
// includes the effect of reflected inertia due to the high gear ratio of the
// actuators.
// In these notes we provide recommended values of the parameters for when
// reflected inertia is not modeled. Notice in particular that we need to reduce
// the time step significantly.
//
// When reflected inertia is not modeled we recommend:
// rotor_inertia = 0.0.
// mbp_discrete_update_period = 1.5e-4 sec.
// pid_frequency = 30 Hz.
void DoMain() {
DRAKE_DEMAND(FLAGS_simulation_time > 0);
systems::DiagramBuilder<double> builder;
auto lcm = builder.AddSystem<systems::lcm::LcmInterfaceSystem>();
auto [plant, scene_graph] = multibody::AddMultibodyPlantSceneGraph(
&builder, FLAGS_mbp_discrete_update_period);
std::string hand_model_url;
if (FLAGS_use_right_hand) {
hand_model_url =
"package://drake_models/"
"allegro_hand_description/sdf/allegro_hand_description_right.sdf";
} else {
hand_model_url =
"package://drake_models/"
"allegro_hand_description/sdf/allegro_hand_description_left.sdf";
}
const std::string object_model_url =
"package://drake/examples/allegro_hand/joint_control/simple_mug.sdf";
multibody::Parser parser(&plant);
parser.AddModelsFromUrl(hand_model_url);
parser.AddModelsFromUrl(object_model_url);
// Weld the hand to the world frame
const auto& joint_hand_root = plant.GetBodyByName("hand_root");
plant.AddJoint<multibody::WeldJoint>("weld_hand", plant.world_body(),
std::nullopt,
joint_hand_root,
std::nullopt,
RigidTransformd::Identity());
// Model gear ratio and rotor inertia at each finger. In order to model the
// effect of reflected inertia, we need to have the gear ratio and rotor
// inertia of the actuators. We know from the Allegro hand's specs that the
// gear ratio is ρ = 369. More details in
// http://wiki.wonikrobotics.com/AllegroHandWiki/index.php/Allegro_Hand_Overview
// We do not know the exact motor used in the actuator.
// However we only need an approximate estimate of the rotor inertia. What we
// know from the Allegro hand's specs:
// 1. High gear ratio of ρ = 369.
// 2. maximum actuator torque: 0.7 Nm, i.e. 0.7/369 = 1.9 mN⋅m at the motor.
// That is, the stall torque of the motor is in the order of 1.9 mN⋅m.
// 3. From drawings, we see the finger has a cross section of about 20 mm
// wide. Therefore the diameter of the motor should be Ø ≲ 20 mm.
// 4. The hand's power requirement is 7.5 V and at 5 A (minimum). Therefore at
// a minimum it runs at 37 Watts. For 16 actuators, we estimate motors of
// about 2 Watts.
// 5. Max. joint speed of 0.11 sec/60° or 91 RPM. Thus the motor speed is
// about 33500 RPM.
//
// We looked at brushed DC motors from Maxon at
// https://www.maxongroup.com/maxon/view/product/
// For motors in the range 14-16 mm in diameter, 2.5 W, we find that RPM and
// stall torque are in the right order of magnitude.
// We also find that most of them have a rotor inertia of about 1 g⋅cm².
//
// This information then lead us to the following actuator parameters:
// - Gear ratio ρ = 369.
// - Rotor inertia Iᵣ = 1×10⁻⁶ kg⋅m².
//
// This allow us to estimate the reflected inertia as:
// - Irefl = ρ²⋅Iᵣ = 0.14 kg⋅m².
//
// As a reference, the mass of a finger is 0.17 kg. Each finger has phalanges
// of about 5 cm length. Therefore we estimate their rotational inertia as
// that for a rod about its end (1/3⋅m⋅ℓ²) at about 4.7×10⁻⁵ kg⋅m². That's
// 3000 times smaller than the reflected inertia!.
// That is, the effective inertia of the joint is 0.14 kg⋅m².
// We the estimate the time it'd take to move the joint a full revolution from
// zero velocity when applying the maximum torque of 0.7 Nm.
// We obtain t = sqrt(2θ/ẇ) = 1.6 secs, which seems consistent with
// experience.
// Rotor inertia in kg⋅m².
DRAKE_DEMAND(FLAGS_rotor_inertia >= 0.0);
DRAKE_DEMAND(FLAGS_gear_ratio >= 1.0);
const double rotor_inertia = FLAGS_rotor_inertia;
// Gear ratio, dimensionless.
const double gear_ratio = FLAGS_gear_ratio;
const double reflected_inertia = rotor_inertia * gear_ratio * gear_ratio;
// We expect all fingers to be actuated.
DRAKE_DEMAND(plant.num_actuators() == 16);
// N.B. This change MUST be performed before Finalize() in order to take
// effect.
for (JointActuatorIndex actuator_index : plant.GetJointActuatorIndices()) {
JointActuator<double>& actuator =
plant.get_mutable_joint_actuator(actuator_index);
actuator.set_default_rotor_inertia(rotor_inertia);
actuator.set_default_gear_ratio(gear_ratio);
}
if (!FLAGS_add_gravity) {
plant.mutable_gravity_field().set_gravity_vector(
Eigen::Vector3d::Zero());
}
// Finished building the plant
plant.Finalize();
// Visualization
visualization::AddDefaultVisualization(&builder);
// Estimate rotational inertia for an average finger of mass 0.17/3 kg (0.17
// is the mass of one finger) and length 5 cm. We estimate it using the
// rotational inertia for a rod about its end, i.e. I = 1/3⋅m⋅ℓ².
const double mass_finger = 0.17 / 3.0;
const double length_finger = 0.05;
const double Ifinger = mass_finger / 3.0 * length_finger * length_finger;
// Approximate effective finger inertia.
const double Ieff = Ifinger + reflected_inertia;
// PID controller for position control of the finger joints
VectorX<double> kp, kd, ki;
MatrixX<double> Sx, Sy;
GetControlPortMapping(plant, &Sx, &Sy);
SetPositionControlledGains(FLAGS_pid_frequency, Ieff, &kp, &ki, &kd);
auto& hand_controller = *builder.AddSystem<
systems::controllers::PidController>(Sx, Sy, kp, ki, kd);
builder.Connect(plant.get_state_output_port(),
hand_controller.get_input_port_estimated_state());
builder.Connect(hand_controller.get_output_port_control(),
plant.get_actuation_input_port());
// Create an output port of the continuous state from the plant that only
// output the status of the hand finger joints related DOFs, and put them in
// the pre-defined order that is easy for understanding.
const auto& hand_status_converter =
*builder.AddSystem<systems::MatrixGain<double>>(Sx);
builder.Connect(plant.get_state_output_port(),
hand_status_converter.get_input_port());
const auto& hand_output_torque_converter =
*builder.AddSystem<systems::MatrixGain<double>>(Sy);
builder.Connect(hand_controller.get_output_port_control(),
hand_output_torque_converter.get_input_port());
// Create the command subscriber and status publisher for the hand.
const double kLcmPeriod = examples::allegro_hand::kHardwareStatusPeriod;
auto& hand_command_sub = *builder.AddSystem(
systems::lcm::LcmSubscriberSystem::Make<lcmt_allegro_command>(
"ALLEGRO_COMMAND", lcm));
hand_command_sub.set_name("hand_command_subscriber");
auto& hand_command_receiver =
*builder.AddSystem<AllegroCommandReceiver>(kAllegroNumJoints, kLcmPeriod);
hand_command_receiver.set_name("hand_command_receiver");
auto& hand_status_pub = *builder.AddSystem(
systems::lcm::LcmPublisherSystem::Make<lcmt_allegro_status>(
"ALLEGRO_STATUS", lcm, kLcmPeriod /* publish period */));
hand_status_pub.set_name("hand_status_publisher");
auto& status_sender =
*builder.AddSystem<AllegroStatusSender>(kAllegroNumJoints);
status_sender.set_name("status_sender");
builder.Connect(hand_command_sub.get_output_port(),
hand_command_receiver.get_input_port(0));
builder.Connect(hand_command_receiver.get_commanded_state_output_port(),
hand_controller.get_input_port_desired_state());
builder.Connect(hand_status_converter.get_output_port(),
status_sender.get_state_input_port());
builder.Connect(hand_command_receiver.get_output_port(0),
status_sender.get_command_input_port());
builder.Connect(hand_output_torque_converter.get_output_port(),
status_sender.get_commanded_torque_input_port());
builder.Connect(status_sender.get_output_port(0),
hand_status_pub.get_input_port());
// Now the model is complete.
std::unique_ptr<systems::Diagram<double>> diagram = builder.Build();
// Create a context for this system:
std::unique_ptr<systems::Context<double>> diagram_context =
diagram->CreateDefaultContext();
diagram->SetDefaultContext(diagram_context.get());
// Set the position of object
const multibody::RigidBody<double>& hand = plant.GetBodyByName("hand_root");
systems::Context<double>& plant_context =
diagram->GetMutableSubsystemContext(plant, diagram_context.get());
// Initialize the mug pose to be right in the middle between the fingers.
const multibody::RigidBody<double>& mug = plant.GetBodyByName("simple_mug");
const Eigen::Vector3d& p_WHand =
plant.EvalBodyPoseInWorld(plant_context, hand).translation();
RigidTransformd X_WM(
RollPitchYawd(M_PI / 2, 0, 0),
p_WHand + Eigen::Vector3d(0.095, 0.062, 0.095));
plant.SetFreeBodyPose(&plant_context, mug, X_WM);
// set the initial command for the hand
hand_command_receiver.set_initial_position(
&diagram->GetMutableSubsystemContext(hand_command_receiver,
diagram_context.get()),
VectorX<double>::Zero(plant.num_actuators()));
// Set up simulator.
auto simulator =
MakeSimulatorFromGflags(*diagram, std::move(diagram_context));
simulator->AdvanceTo(FLAGS_simulation_time);
}
} // namespace
} // namespace allegro_hand
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
gflags::SetUsageMessage(
"A simple dynamic simulation for the Allegro hand moving under constant"
" torques.");
gflags::ParseCommandLineFlags(&argc, &argv, true);
drake::examples::allegro_hand::DoMain();
return 0;
}
| 0 |
/home/johnshepherd/drake/examples/allegro_hand/joint_control | /home/johnshepherd/drake/examples/allegro_hand/joint_control/test/run_twisting_mug_test.py | """Simple regression test that the twisting_mug demo can perform at least one
twist.
"""
import hashlib
import os
import subprocess
import sys
import time
import unittest
from python.runfiles import Create as CreateRunfiles
def _unique_lcm_url(path):
"""Returns a unique LCM url given a path."""
rand = [int(c) for c in hashlib.sha256(path.encode("utf8")).digest()]
return "udpm://239.{:d}.{:d}.{:d}:{:d}?ttl=0".format(
rand[0], rand[1], rand[2], 20000 + rand[3])
class TestRunTwistingMug(unittest.TestCase):
def _find_resource(self, basename):
respath = f"drake/examples/allegro_hand/joint_control/{basename}"
runfiles = CreateRunfiles()
result = runfiles.Rlocation(respath)
self.assertTrue(result, respath)
self.assertTrue(os.path.exists(result), respath)
return result
def setUp(self):
self._test_tmpdir = os.environ["TEST_TMPDIR"]
# Find the two binaries under test.
self._sim = self._find_resource("allegro_single_object_simulation")
self._control = self._find_resource("run_twisting_mug")
# Let the sim and controller talk to (only) each other.
self._env = dict(**os.environ)
self._env["LCM_DEFAULT_URL"] = _unique_lcm_url(self._test_tmpdir)
def test_only_sim(self):
subprocess.run([
self._sim, "--simulation_time=0.01"],
env=self._env, cwd=self._test_tmpdir, check=True)
@unittest.skipIf(
"--compilation_mode=dbg" in sys.argv,
"This test is prohibitively slow in Debug builds.")
def test_sim_and_control(self):
# Run both the simulator and controller.
sim_process = subprocess.Popen([
self._sim, "--simulation_time=30"],
env=self._env, cwd=self._test_tmpdir)
control_process = subprocess.Popen([
self._control, "--max_cycles=1"],
env=self._env, cwd=self._test_tmpdir)
# Wait until one of them exits. Nominally the first to exit will be
# the controller, once it finishes one twist.
child_processes = [sim_process, control_process]
while all([x.poll() is None for x in child_processes]):
time.sleep(0.1)
self.assertEqual(sim_process.returncode, None)
self.assertEqual(control_process.returncode, 0)
# Silence "subprocess is still running" warnings.
sim_process.kill()
control_process.kill()
sim_process.wait(timeout=10.0)
control_process.wait(timeout=10.0)
| 0 |
/home/johnshepherd/drake/examples/allegro_hand | /home/johnshepherd/drake/examples/allegro_hand/test/allegro_lcm_test.cc | #include "drake/examples/allegro_hand/allegro_lcm.h"
#include <Eigen/Dense>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/examples/allegro_hand/allegro_common.h"
#include "drake/lcmt_allegro_command.hpp"
#include "drake/lcmt_allegro_status.hpp"
#include "drake/systems/framework/context.h"
namespace drake {
namespace examples {
namespace allegro_hand {
GTEST_TEST(AllegroLcmTest, AllegroCommandReceiver) {
AllegroCommandReceiver dut;
std::unique_ptr<systems::Context<double>> context =
dut.CreateDefaultContext();
std::unique_ptr<systems::SystemOutput<double>> output =
dut.AllocateOutput();
// Check that the commanded pose starts out at zero, and that we can
// set a different initial position.
Eigen::VectorXd expected = Eigen::VectorXd::Zero(kAllegroNumJoints * 2);
dut.CalcOutput(*context, output.get());
const double tol = 1e-5;
EXPECT_TRUE(CompareMatrices(
expected, output->get_vector_data(0)->value(),
tol, MatrixCompareType::absolute));
Eigen::VectorXd position(kAllegroNumJoints);
position << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1,
1.2, 1.3, 1.4, 1.5, 1.6;
dut.set_initial_position(context.get(), position);
dut.CalcOutput(*context, output.get());
EXPECT_TRUE(CompareMatrices(
position, output->get_vector_data(0)->value()
.head(kAllegroNumJoints),
tol, MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(
expected.tail(kAllegroNumJoints),
output->get_vector_data(0)->value().tail(kAllegroNumJoints),
tol, MatrixCompareType::absolute));
Eigen::VectorXd delta(kAllegroNumJoints);
delta << 0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009,
0.010, 0.011, 0.012, 0.013, 0.014, 0.015, 0.016;
lcmt_allegro_command command{};
command.num_joints = kAllegroNumJoints;
command.joint_position.resize(kAllegroNumJoints);
for (int i = 0; i < kAllegroNumJoints; i++) {
command.joint_position[i] = position(i) + delta(i);
}
dut.get_input_port(0).FixValue(context.get(), command);
// Manually trigger the discrete update event.
context->SetDiscreteState(dut.EvalUniquePeriodicDiscreteUpdate(*context));
dut.CalcOutput(*context, output.get());
EXPECT_TRUE(CompareMatrices(
position + delta,
output->get_vector_data(0)->value().head(kAllegroNumJoints),
tol, MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(
VectorX<double>::Zero(kAllegroNumJoints),
output->get_vector_data(0)->value().tail(kAllegroNumJoints),
tol, MatrixCompareType::absolute));
EXPECT_TRUE(CompareMatrices(
VectorX<double>::Zero(kAllegroNumJoints),
output->get_vector_data(1)->value(),
tol, MatrixCompareType::absolute));
}
GTEST_TEST(AllegroLcmTest, AllegroStatusSenderTest) {
AllegroStatusSender dut;
std::unique_ptr<systems::Context<double>>
context = dut.CreateDefaultContext();
std::unique_ptr<systems::SystemOutput<double>> output =
dut.AllocateOutput();
Eigen::VectorXd position(kAllegroNumJoints);
position << 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1,
1.2, 1.3, 1.4, 1.5, 1.6;
Eigen::VectorXd command = Eigen::VectorXd::Zero(kAllegroNumJoints * 2);
command.head(kAllegroNumJoints) = position * 0.5;
dut.get_command_input_port().FixValue(context.get(), command);
Eigen::VectorXd state = Eigen::VectorXd::Zero(kAllegroNumJoints * 2);
state.head(kAllegroNumJoints) = position;
state.tail(kAllegroNumJoints) << 1.6, 1.5, 1.4, 1.3, 1.2, 1.1, 1.0, 0.9, 0.8,
0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1;
dut.get_state_input_port().FixValue(context.get(), state);
Eigen::VectorXd torque = Eigen::VectorXd::Zero(kAllegroNumJoints);
torque << 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.1,
2.2, 2.3, 2.4, 2.5, 2.6;;
dut.get_commanded_torque_input_port().FixValue(context.get(), torque);
dut.CalcOutput(*context, output.get());
lcmt_allegro_status status =
output->get_data(0)->get_value<lcmt_allegro_status>();
ASSERT_EQ(status.num_joints, kAllegroNumJoints);
for (int i = 0; i < kAllegroNumJoints; i++) {
EXPECT_EQ(status.joint_position_commanded[i], command(i));
EXPECT_EQ(status.joint_position_measured[i], state(i));
EXPECT_EQ(status.joint_velocity_estimated[i], state(
i + kAllegroNumJoints));
EXPECT_EQ(status.joint_torque_commanded[i], torque(i));
}
}
} // namespace allegro_hand
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples/allegro_hand | /home/johnshepherd/drake/examples/allegro_hand/test/parse_test.cc | #include <string>
#include <fmt/format.h>
#include <gtest/gtest.h>
#include "drake/common/find_resource.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/multibody/plant/multibody_plant.h"
namespace drake {
namespace manipulation {
namespace {
using multibody::ModelInstanceIndex;
using multibody::MultibodyPlant;
using multibody::Parser;
class ParseTest : public testing::TestWithParam<std::string> {};
TEST_P(ParseTest, Quantities) {
const std::string file_extension = GetParam();
const std::string url_right =
fmt::format("package://drake_models/allegro_hand_description/{}/"
"allegro_hand_description_right.{}",
file_extension, file_extension);
const std::string url_left =
fmt::format("package://drake_models/allegro_hand_description/{}/"
"allegro_hand_description_left.{}",
file_extension, file_extension);
MultibodyPlant<double> plant(0.0);
Parser parser(&plant);
const ModelInstanceIndex right_hand_index =
parser.AddModelsFromUrl(url_right).at(0);
const ModelInstanceIndex left_hand_index =
parser.AddModelsFromUrl(url_left).at(0);
plant.Finalize();
// MultibodyPlant always creates at least two model instances, one for the
// world and one for a default model instance for unspecified modeling
// elements. Finally, there is a model instance for each hand in an SDF file
EXPECT_EQ(plant.num_model_instances(), 4);
EXPECT_EQ(plant.num_actuators(), 2 * 16);
if (file_extension == "sdf") {
EXPECT_EQ(plant.num_joints(), 2 * 16 + 2); // + 2 for floating body joints
EXPECT_EQ(plant.num_bodies(), 2 * 17 + 1); // + 1 for world
} else {
EXPECT_EQ(plant.num_joints(), 2 * 21 + 2); // + 2 for floating body joints
EXPECT_EQ(plant.num_bodies(), 2 * 22 + 1); // + 1 for world
}
// 16 for finger joints, 7 for the free moving hand in the space
EXPECT_EQ(plant.num_positions(right_hand_index), 23);
EXPECT_EQ(plant.num_velocities(right_hand_index), 22);
EXPECT_EQ(plant.num_positions(left_hand_index), 23);
EXPECT_EQ(plant.num_velocities(left_hand_index), 22);
}
INSTANTIATE_TEST_SUITE_P(Both, ParseTest, testing::Values("sdf", "urdf"));
} // namespace
} // namespace manipulation
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/planar_gripper.sdf | <?xml version="1.0"?>
<!-- =================================================================================== -->
<!-- | This document was autogenerated by xacro from planar_gripper.xacro | -->
<!-- | EDITING THIS FILE BY HAND IS NOT RECOMMENDED | -->
<!-- =================================================================================== -->
<sdf version="1.7">
<model name="planar_gripper">
<link name="finger1_base">
<visual name="base_visual">
<geometry>
<box>
<size>0.08 0.08 0.008</size>
</box>
</geometry>
<material>
<diffuse>0.1 0.1 0.1 1</diffuse>
</material>
</visual>
</link>
<link name="finger1_link1">
<inertial>
<pose>0 0 -0.0425 0 0 0</pose>
<mass>0.1</mass>
<inertia>
<ixx>0.0083</ixx>
<iyy>0.0083</iyy>
<izz>5e-7</izz>
<ixy>0</ixy>
<ixz>0</ixz>
<iyz>0</iyz>
</inertia>
</inertial>
<visual name="link1_visual">
<pose>0 0 -0.0425 0 0 0</pose>
<geometry>
<cylinder>
<length>0.085</length>
<radius>0.011</radius>
</cylinder>
</geometry>
<material>
<diffuse>1 0 0 1</diffuse>
</material>
</visual>
<visual name="link1_joint_visual">
<pose>0 0 -0.085 0 0 0</pose>
<geometry>
<sphere>
<radius>0.0132</radius>
</sphere>
</geometry>
<material>
<diffuse>.1 .1 .1 1</diffuse>
</material>
</visual>
</link>
<joint name="finger1_BaseJoint" type="revolute">
<child>finger1_link1</child>
<parent>finger1_base</parent>
<axis>
<xyz expressed_in="__model__">1 0 0</xyz>
<limit>
<!-- Drake parses a zero effort joint as an un-actuated joint. -->
<effort>75</effort>
<lower>-1.57</lower>
<upper>1.57</upper>
</limit>
<dynamics>
<damping>0.1</damping>
</dynamics>
</axis>
</joint>
<link name="finger1_link2">
<!-- The origin of the link2 frame is located at the MidJoint. -->
<pose>0 0 -0.085 0 0 0</pose>
<inertial>
<pose>0 0 -0.0299 0 0 0</pose>
<mass>0.1</mass>
<inertia>
<ixx>0.0083</ixx>
<iyy>0.0083</iyy>
<izz>5e-7</izz>
<ixy>0</ixy>
<ixz>0</ixz>
<iyz>0</iyz>
</inertia>
</inertial>
<visual name="link2_visual">
<pose>0 0 -0.02 0 0 0</pose>
<geometry>
<cylinder>
<length>0.04</length>
<radius>0.011</radius>
</cylinder>
</geometry>
<material>
<diffuse>1 0 0 1</diffuse>
</material>
</visual>
<!--The link 2 collision element extends up to (but not including) the
sphere fingertip-->
<collision name="link2_collision">
<pose>0 0 -0.0299 0 0 0</pose>
<geometry>
<box>
<size> 0.022 0.022 0.0598 </size>
</box>
</geometry>
</collision>
<visual name="sensor_visual">
<pose>0 0 -0.0425 0 0 0</pose>
<geometry>
<box>
<size>0.02 0.02 0.005</size>
</box>
</geometry>
<material>
<diffuse>.8 .8 .8 1</diffuse>
</material>
</visual>
</link>
<joint name="finger1_MidJoint" type="revolute">
<parent>finger1_link1</parent>
<child>finger1_link2</child>
<!-- Pose X_CJ of the joint frame J in the frame C of the child link -->
<axis>
<xyz expressed_in="__model__">1 0 0</xyz>
<limit>
<effort>75</effort>
<lower>-1.57</lower>
<upper>1.57</upper>
</limit>
<dynamics>
<damping>0.1</damping>
</dynamics>
</axis>
</joint>
<!-- The tip link's mass/inertia values are already included in link 2,
which welds to this link. Hence, the values here are set to be
(effectively) zero. Note: This fingertip link and its corresponding
weld joint allows us to sense forces via MBP's reaction forces
output port. -->
<link name="finger1_tip_link">
<pose>0 0 -0.13 0 0 0</pose>
<inertial>
<pose>0 0 -0.0074 0 0 0</pose>
<mass>1e-7</mass>
<inertia>
<ixx>1e-7</ixx>
<iyy>1e-7</iyy>
<izz>1e-7</izz>
<ixy>0</ixy>
<ixz>0</ixz>
<iyz>0</iyz>
</inertia>
</inertial>
<visual name="tip_adapter_visual">
<pose>0 0 -0.00565 0 0 0</pose>
<geometry>
<cylinder>
<length>0.0113</length>
<radius>0.0145</radius>
</cylinder>
</geometry>
<material>
<diffuse>.3 .3 .3 1</diffuse>
</material>
</visual>
<visual name="tip_cylinder_visual">
<pose>0 0 -0.01305 0 0 0</pose>
<geometry>
<cylinder>
<length>0.0035</length>
<radius>0.01</radius>
</cylinder>
</geometry>
<material>
<diffuse>.3 .3 .3 1</diffuse>
</material>
</visual>
<visual name="tip_sphere_visual">
<pose>0 0 -0.0263 0 0 0</pose>
<geometry>
<sphere>
<radius>0.015</radius>
</sphere>
</geometry>
<material>
<diffuse>1 1 1 1</diffuse>
</material>
</visual>
<collision name="tip_sphere_collision">
<pose>0 0 -0.0263 0 0 0</pose>
<geometry>
<sphere>
<radius>0.015</radius>
</sphere>
</geometry>
</collision>
</link>
<joint name="finger1_sensor_weldjoint" type="fixed">
<parent>finger1_link2</parent>
<child>finger1_tip_link</child>
</joint>
<link name="finger2_base">
<visual name="base_visual">
<geometry>
<box>
<size>0.08 0.08 0.008</size>
</box>
</geometry>
<material>
<diffuse>0.1 0.1 0.1 1</diffuse>
</material>
</visual>
</link>
<link name="finger2_link1">
<inertial>
<pose>0 0 -0.0425 0 0 0</pose>
<mass>0.1</mass>
<inertia>
<ixx>0.0083</ixx>
<iyy>0.0083</iyy>
<izz>5e-7</izz>
<ixy>0</ixy>
<ixz>0</ixz>
<iyz>0</iyz>
</inertia>
</inertial>
<visual name="link1_visual">
<pose>0 0 -0.0425 0 0 0</pose>
<geometry>
<cylinder>
<length>0.085</length>
<radius>0.011</radius>
</cylinder>
</geometry>
<material>
<diffuse>1 0 0 1</diffuse>
</material>
</visual>
<visual name="link1_joint_visual">
<pose>0 0 -0.085 0 0 0</pose>
<geometry>
<sphere>
<radius>0.0132</radius>
</sphere>
</geometry>
<material>
<diffuse>.1 .1 .1 1</diffuse>
</material>
</visual>
</link>
<joint name="finger2_BaseJoint" type="revolute">
<child>finger2_link1</child>
<parent>finger2_base</parent>
<axis>
<xyz expressed_in="__model__">1 0 0</xyz>
<limit>
<!-- Drake parses a zero effort joint as an un-actuated joint. -->
<effort>75</effort>
<lower>-1.57</lower>
<upper>1.57</upper>
</limit>
<dynamics>
<damping>0.1</damping>
</dynamics>
</axis>
</joint>
<link name="finger2_link2">
<!-- The origin of the link2 frame is located at the MidJoint. -->
<pose>0 0 -0.085 0 0 0</pose>
<inertial>
<pose>0 0 -0.0299 0 0 0</pose>
<mass>0.1</mass>
<inertia>
<ixx>0.0083</ixx>
<iyy>0.0083</iyy>
<izz>5e-7</izz>
<ixy>0</ixy>
<ixz>0</ixz>
<iyz>0</iyz>
</inertia>
</inertial>
<visual name="link2_visual">
<pose>0 0 -0.02 0 0 0</pose>
<geometry>
<cylinder>
<length>0.04</length>
<radius>0.011</radius>
</cylinder>
</geometry>
<material>
<diffuse>1 0 0 1</diffuse>
</material>
</visual>
<!--The link 2 collision element extends up to (but not including) the
sphere fingertip-->
<collision name="link2_collision">
<pose>0 0 -0.0299 0 0 0</pose>
<geometry>
<box>
<size> 0.022 0.022 0.0598 </size>
</box>
</geometry>
</collision>
<visual name="sensor_visual">
<pose>0 0 -0.0425 0 0 0</pose>
<geometry>
<box>
<size>0.02 0.02 0.005</size>
</box>
</geometry>
<material>
<diffuse>.8 .8 .8 1</diffuse>
</material>
</visual>
</link>
<joint name="finger2_MidJoint" type="revolute">
<parent>finger2_link1</parent>
<child>finger2_link2</child>
<!-- Pose X_CJ of the joint frame J in the frame C of the child link -->
<axis>
<xyz expressed_in="__model__">1 0 0</xyz>
<limit>
<effort>75</effort>
<lower>-1.57</lower>
<upper>1.57</upper>
</limit>
<dynamics>
<damping>0.1</damping>
</dynamics>
</axis>
</joint>
<!-- The tip link's mass/inertia values are already included in link 2,
which welds to this link. Hence, the values here are set to be
(effectively) zero. Note: This fingertip link and its corresponding
weld joint allows us to sense forces via MBP's reaction forces
output port. -->
<link name="finger2_tip_link">
<pose>0 0 -0.13 0 0 0</pose>
<inertial>
<pose>0 0 -0.0074 0 0 0</pose>
<mass>1e-7</mass>
<inertia>
<ixx>1e-7</ixx>
<iyy>1e-7</iyy>
<izz>1e-7</izz>
<ixy>0</ixy>
<ixz>0</ixz>
<iyz>0</iyz>
</inertia>
</inertial>
<visual name="tip_adapter_visual">
<pose>0 0 -0.00565 0 0 0</pose>
<geometry>
<cylinder>
<length>0.0113</length>
<radius>0.0145</radius>
</cylinder>
</geometry>
<material>
<diffuse>.3 .3 .3 1</diffuse>
</material>
</visual>
<visual name="tip_cylinder_visual">
<pose>0 0 -0.01305 0 0 0</pose>
<geometry>
<cylinder>
<length>0.0035</length>
<radius>0.01</radius>
</cylinder>
</geometry>
<material>
<diffuse>.3 .3 .3 1</diffuse>
</material>
</visual>
<visual name="tip_sphere_visual">
<pose>0 0 -0.0263 0 0 0</pose>
<geometry>
<sphere>
<radius>0.015</radius>
</sphere>
</geometry>
<material>
<diffuse>1 1 1 1</diffuse>
</material>
</visual>
<collision name="tip_sphere_collision">
<pose>0 0 -0.0263 0 0 0</pose>
<geometry>
<sphere>
<radius>0.015</radius>
</sphere>
</geometry>
</collision>
</link>
<joint name="finger2_sensor_weldjoint" type="fixed">
<parent>finger2_link2</parent>
<child>finger2_tip_link</child>
</joint>
<link name="finger3_base">
<visual name="base_visual">
<geometry>
<box>
<size>0.08 0.08 0.008</size>
</box>
</geometry>
<material>
<diffuse>0.1 0.1 0.1 1</diffuse>
</material>
</visual>
</link>
<link name="finger3_link1">
<inertial>
<pose>0 0 -0.0425 0 0 0</pose>
<mass>0.1</mass>
<inertia>
<ixx>0.0083</ixx>
<iyy>0.0083</iyy>
<izz>5e-7</izz>
<ixy>0</ixy>
<ixz>0</ixz>
<iyz>0</iyz>
</inertia>
</inertial>
<visual name="link1_visual">
<pose>0 0 -0.0425 0 0 0</pose>
<geometry>
<cylinder>
<length>0.085</length>
<radius>0.011</radius>
</cylinder>
</geometry>
<material>
<diffuse>1 0 0 1</diffuse>
</material>
</visual>
<visual name="link1_joint_visual">
<pose>0 0 -0.085 0 0 0</pose>
<geometry>
<sphere>
<radius>0.0132</radius>
</sphere>
</geometry>
<material>
<diffuse>.1 .1 .1 1</diffuse>
</material>
</visual>
</link>
<joint name="finger3_BaseJoint" type="revolute">
<child>finger3_link1</child>
<parent>finger3_base</parent>
<axis>
<xyz expressed_in="__model__">1 0 0</xyz>
<limit>
<!-- Drake parses a zero effort joint as an un-actuated joint. -->
<effort>75</effort>
<lower>-1.57</lower>
<upper>1.57</upper>
</limit>
<dynamics>
<damping>0.1</damping>
</dynamics>
</axis>
</joint>
<link name="finger3_link2">
<!-- The origin of the link2 frame is located at the MidJoint. -->
<pose>0 0 -0.085 0 0 0</pose>
<inertial>
<pose>0 0 -0.0299 0 0 0</pose>
<mass>0.1</mass>
<inertia>
<ixx>0.0083</ixx>
<iyy>0.0083</iyy>
<izz>5e-7</izz>
<ixy>0</ixy>
<ixz>0</ixz>
<iyz>0</iyz>
</inertia>
</inertial>
<visual name="link2_visual">
<pose>0 0 -0.02 0 0 0</pose>
<geometry>
<cylinder>
<length>0.04</length>
<radius>0.011</radius>
</cylinder>
</geometry>
<material>
<diffuse>1 0 0 1</diffuse>
</material>
</visual>
<!--The link 2 collision element extends up to (but not including) the
sphere fingertip-->
<collision name="link2_collision">
<pose>0 0 -0.0299 0 0 0</pose>
<geometry>
<box>
<size> 0.022 0.022 0.0598 </size>
</box>
</geometry>
</collision>
<visual name="sensor_visual">
<pose>0 0 -0.0425 0 0 0</pose>
<geometry>
<box>
<size>0.02 0.02 0.005</size>
</box>
</geometry>
<material>
<diffuse>.8 .8 .8 1</diffuse>
</material>
</visual>
</link>
<joint name="finger3_MidJoint" type="revolute">
<parent>finger3_link1</parent>
<child>finger3_link2</child>
<!-- Pose X_CJ of the joint frame J in the frame C of the child link -->
<axis>
<xyz expressed_in="__model__">1 0 0</xyz>
<limit>
<effort>75</effort>
<lower>-1.57</lower>
<upper>1.57</upper>
</limit>
<dynamics>
<damping>0.1</damping>
</dynamics>
</axis>
</joint>
<!-- The tip link's mass/inertia values are already included in link 2,
which welds to this link. Hence, the values here are set to be
(effectively) zero. Note: This fingertip link and its corresponding
weld joint allows us to sense forces via MBP's reaction forces
output port. -->
<link name="finger3_tip_link">
<pose>0 0 -0.13 0 0 0</pose>
<inertial>
<pose>0 0 -0.0074 0 0 0</pose>
<mass>1e-7</mass>
<inertia>
<ixx>1e-7</ixx>
<iyy>1e-7</iyy>
<izz>1e-7</izz>
<ixy>0</ixy>
<ixz>0</ixz>
<iyz>0</iyz>
</inertia>
</inertial>
<visual name="tip_adapter_visual">
<pose>0 0 -0.00565 0 0 0</pose>
<geometry>
<cylinder>
<length>0.0113</length>
<radius>0.0145</radius>
</cylinder>
</geometry>
<material>
<diffuse>.3 .3 .3 1</diffuse>
</material>
</visual>
<visual name="tip_cylinder_visual">
<pose>0 0 -0.01305 0 0 0</pose>
<geometry>
<cylinder>
<length>0.0035</length>
<radius>0.01</radius>
</cylinder>
</geometry>
<material>
<diffuse>.3 .3 .3 1</diffuse>
</material>
</visual>
<visual name="tip_sphere_visual">
<pose>0 0 -0.0263 0 0 0</pose>
<geometry>
<sphere>
<radius>0.015</radius>
</sphere>
</geometry>
<material>
<diffuse>1 1 1 1</diffuse>
</material>
</visual>
<collision name="tip_sphere_collision">
<pose>0 0 -0.0263 0 0 0</pose>
<geometry>
<sphere>
<radius>0.015</radius>
</sphere>
</geometry>
</collision>
</link>
<joint name="finger3_sensor_weldjoint" type="fixed">
<parent>finger3_link2</parent>
<child>finger3_tip_link</child>
</joint>
</model>
</sdf>
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/planar_brick.sdf | <?xml version="1.0"?>
<sdf version="1.7">
<model name="brick">
<link name="brick_base"/>
<link name="brick_dummy_link1">
<inertial>
<mass>1e-10</mass>
<inertia>
<ixx>1e-10</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>1e-10</iyy>
<iyz>0</iyz>
<izz>1e-10</izz>
</inertia>
</inertial>
</link>
<joint name="brick_translate_y_joint" type="prismatic">
<child> brick_dummy_link1 </child>
<parent> brick_base </parent>
<axis>
<xyz> 0 1 0 </xyz>
<limit>
<!-- Drake parses a zero effort joint as an un-actuated joint. -->
<effort> 0 </effort>
</limit>
</axis>
</joint>
<link name="brick_dummy_link2">
<inertial>
<mass>1e-10</mass>
<inertia>
<ixx>1e-10</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>1e-10</iyy>
<iyz>0</iyz>
<izz>1e-10</izz>
</inertia>
</inertial>
</link>
<joint name="brick_translate_z_joint" type="prismatic">
<child> brick_dummy_link2 </child>
<parent> brick_dummy_link1 </parent>
<axis>
<xyz> 0 0 1 </xyz>
<limit>
<!-- Drake parses a zero effort joint as an un-actuated joint. -->
<effort> 0 </effort>
</limit>
</axis>
</joint>
<link name="brick_link">
<inertial>
<mass>0.028</mass>
<inertia>
<ixx>1.17e-5</ixx>
<ixy>0</ixy>
<ixz>0</ixz>
<iyy>1.9e-5</iyy>
<iyz>0</iyz>
<izz>1.9e-5</izz>
</inertia>
</inertial>
<visual name="brick_visual_1">
<pose>0 0 0.025 0 0 0</pose>
<geometry>
<box>
<size>0.07 0.1 0.05</size>
</box>
</geometry>
<material>
<diffuse>0 0.8 0 1.0</diffuse>
</material>
</visual>
<visual name="brick_visual_2">
<pose>0 0 -0.025 0 0 0</pose>
<geometry>
<box>
<size>0.07 0.1 0.05</size>
</box>
</geometry>
<material>
<diffuse>0 0 0.8 1.0</diffuse>
</material>
</visual>
<collision name="box_collision">
<geometry>
<box>
<size>0.07 0.1 0.1</size>
</box>
</geometry>
</collision>
<collision name="sphere1_collision">
<pose>-0.035 0.05 0.05 0 0 0</pose>
<geometry>
<sphere>
<radius>.0001</radius>
</sphere>
</geometry>
</collision>
<collision name="sphere2_collision">
<pose>-0.035 -0.05 0.05 0 0 0</pose>
<geometry>
<sphere>
<radius>.0001</radius>
</sphere>
</geometry>
</collision>
<collision name="sphere3_collision">
<pose>-0.035 0.05 -0.05 0 0 0</pose>
<geometry>
<sphere>
<radius>.0001</radius>
</sphere>
</geometry>
</collision>
<collision name="sphere4_collision">
<pose>-0.035 -0.05 -0.05 0 0 0</pose>
<geometry>
<sphere>
<radius>.0001</radius>
</sphere>
</geometry>
</collision>
</link>
<joint name="brick_revolute_x_joint" type="revolute">
<child> brick_link </child>
<parent> brick_dummy_link2 </parent>
<axis>
<xyz> 1 0 0 </xyz>
<limit>
<!-- Drake parses a zero effort joint as an un-actuated joint. -->
<effort> 0 </effort>
</limit>
</axis>
</joint>
</model>
</sdf>
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/planar_gripper.xacro | <?xml version="1.0"?>
<sdf xmlns:xacro="http://www.ros.org/wiki/xacro" version="1.7">
<model name="planar_gripper">
<!-- Link mass and inertia values are guesses (currently), calculated using
a uniform rod model, rotating about its center of mass. -->
<xacro:property name="base_dim" value=".08"/>
<xacro:property name="l1_length" value="0.085"/>
<xacro:property name="l1_radius" value="0.011"/>
<xacro:property name="l1_mass" value="0.1"/>
<xacro:property name="l1_inertia" value="0.0083"/>
<xacro:property name="l2_length" value="0.040"/>
<xacro:property name="l2_radius" value="0.011"/>
<xacro:property name="l2_mass" value="0.1"/>
<xacro:property name="l2_inertia" value="0.0083"/>
<xacro:property name="sensor_length" value="0.005"/>
<xacro:property name="sensor_width" value="0.02"/>
<xacro:property name="tip_adapter_length" value="0.0113"/>
<xacro:property name="tip_adapter_radius" value="0.0145"/>
<xacro:property name="tip_cylinder_length" value="0.0035"/>
<xacro:property name="tip_cylinder_radius" value="0.01"/>
<xacro:property name="tip_sphere_radius" value="0.015"/>
<xacro:macro name="finger" params="fnum">
<link name="finger${fnum}_base">
<visual name="base_visual">
<geometry>
<box>
<size>${base_dim} ${base_dim} ${base_dim/10}</size>
</box>
</geometry>
<material>
<diffuse>0.1 0.1 0.1 1</diffuse>
</material>
</visual>
</link>
<link name="finger${fnum}_link1">
<inertial>
<pose>0 0 -${l1_length/2} 0 0 0</pose>
<mass>${l1_mass}</mass>
<inertia>
<ixx>${l1_inertia}</ixx>
<iyy>${l1_inertia}</iyy>
<izz>5e-7</izz>
<ixy>0</ixy>
<ixz>0</ixz>
<iyz>0</iyz>
</inertia>
</inertial>
<visual name="link1_visual">
<pose>0 0 -${l1_length/2} 0 0 0</pose>
<geometry>
<cylinder>
<length>${l1_length}</length>
<radius>${l1_radius}</radius>
</cylinder>
</geometry>
<material>
<diffuse>1 0 0 1</diffuse>
</material>
</visual>
<visual name="link1_joint_visual">
<pose>0 0 -${l1_length} 0 0 0</pose>
<geometry>
<sphere>
<radius>${l1_radius*1.2}</radius>
</sphere>
</geometry>
<material>
<diffuse>.1 .1 .1 1</diffuse>
</material>
</visual>
</link>
<joint name="finger${fnum}_BaseJoint" type="revolute">
<child>finger${fnum}_link1</child>
<parent>finger${fnum}_base</parent>
<axis>
<xyz expressed_in="__model__">1 0 0</xyz>
<limit>
<!-- Drake parses a zero effort joint as an un-actuated joint. -->
<effort>75</effort>
<lower>-1.57</lower>
<upper>1.57</upper>
</limit>
<dynamics>
<damping>0.1</damping>
</dynamics>
</axis>
</joint>
<link name="finger${fnum}_link2">
<!-- The origin of the link2 frame is located at the MidJoint. -->
<pose>0 0 -${l1_length} 0 0 0</pose>
<inertial>
<pose>0 0 -${(l2_length + sensor_length + tip_adapter_length + tip_cylinder_length)/2} 0 0 0</pose>
<mass>${l2_mass}</mass>
<inertia>
<ixx>${l2_inertia}</ixx>
<iyy>${l2_inertia}</iyy>
<izz>5e-7</izz>
<ixy>0</ixy>
<ixz>0</ixz>
<iyz>0</iyz>
</inertia>
</inertial>
<visual name="link2_visual">
<pose>0 0 -${l2_length/2} 0 0 0</pose>
<geometry>
<cylinder>
<length>${l2_length}</length>
<radius>${l2_radius}</radius>
</cylinder>
</geometry>
<material>
<diffuse>1 0 0 1</diffuse>
</material>
</visual>
<!--The link 2 collision element extends up to (but not including) the
sphere fingertip-->
<collision name="link2_collision">
<pose>0 0 -${(l2_length + sensor_length + tip_adapter_length + tip_cylinder_length)/2} 0 0 0</pose>
<geometry>
<box>
<size> ${2 * l2_radius} ${2 * l2_radius} ${l2_length + sensor_length + tip_adapter_length + tip_cylinder_length} </size>
</box>
</geometry>
<material>
<diffuse>1 0 1 1</diffuse>
</material>
</collision>
<visual name="sensor_visual">
<pose>0 0 -${l2_length + sensor_length/2.0} 0 0 0</pose>
<geometry>
<box>
<size>${sensor_width} ${sensor_width} ${sensor_length}</size>
</box>
</geometry>
<material>
<diffuse>.8 .8 .8 1</diffuse>
</material>
</visual>
</link>
<joint name="finger${fnum}_MidJoint" type="revolute">
<parent>finger${fnum}_link1</parent>
<child>finger${fnum}_link2</child>
<!-- Pose X_CJ of the joint frame J in the frame C of the child link -->
<axis>
<xyz expressed_in="__model__">1 0 0</xyz>
<limit>
<effort>75</effort>
<lower>-1.57</lower>
<upper>1.57</upper>
</limit>
<dynamics>
<damping>0.1</damping>
</dynamics>
</axis>
</joint>
<!-- The tip link's mass/inertia values are already included in link 2,
which welds to this link. Hence, the values here are set to be
(effectively) zero. Note: This fingertip link and its corresponding
weld joint allows us to sense forces via MBP's reaction forces
output port. -->
<link name="finger${fnum}_tip_link">
<pose>0 0 -${l1_length + l2_length + sensor_length} 0 0 0</pose>
<inertial>
<pose>0 0 -${(tip_adapter_length + tip_cylinder_length)/2} 0 0 0</pose>
<mass>1e-7</mass>
<inertia>
<ixx>1e-7</ixx>
<iyy>1e-7</iyy>
<izz>1e-7</izz>
<ixy>0</ixy>
<ixz>0</ixz>
<iyz>0</iyz>
</inertia>
</inertial>
<visual name="tip_adapter_visual">
<pose>0 0 -${tip_adapter_length/2} 0 0 0</pose>
<geometry>
<cylinder>
<length>${tip_adapter_length}</length>
<radius>${tip_adapter_radius}</radius>
</cylinder>
</geometry>
<material>
<diffuse>.3 .3 .3 1</diffuse>
</material>
</visual>
<visual name="tip_cylinder_visual">
<pose>0 0 -${tip_adapter_length + tip_cylinder_length/2} 0 0 0</pose>
<geometry>
<cylinder>
<length>${tip_cylinder_length}</length>
<radius>${tip_cylinder_radius}</radius>
</cylinder>
</geometry>
<material>
<diffuse>.3 .3 .3 1</diffuse>
</material>
</visual>
<visual name="tip_sphere_visual">
<pose>0 0 -${tip_adapter_length + tip_sphere_radius} 0 0 0</pose>
<geometry>
<sphere>
<radius>${tip_sphere_radius}</radius>
</sphere>
</geometry>
<material>
<diffuse>1 1 1 1</diffuse>
</material>
</visual>
<collision name="tip_sphere_collision">
<pose>0 0 -${tip_adapter_length + tip_sphere_radius} 0 0 0</pose>
<geometry>
<sphere>
<radius>${tip_sphere_radius}</radius>
</sphere>
</geometry>
<material>
<diffuse>1 1 1 1</diffuse>
</material>
</collision>
</link>
<joint name="finger${fnum}_sensor_weldjoint" type="fixed">
<parent>finger${fnum}_link2</parent>
<child>finger${fnum}_tip_link</child>
</joint>
</xacro:macro>
<xacro:finger fnum="1"/>
<xacro:finger fnum="2"/>
<xacro:finger fnum="3"/>
</model>
</sdf>
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/brick_static_equilibrium_constraint.h | #pragma once
#include <utility>
#include <vector>
#include "drake/examples/planar_gripper/gripper_brick.h"
#include "drake/multibody/plant/multibody_plant.h"
#include "drake/solvers/constraint.h"
#include "drake/solvers/mathematical_program.h"
namespace drake {
namespace examples {
namespace planar_gripper {
/** Given the set of contacts between the fingertips and the brick, impose the
* static equilibrium as a nonlinear constraint, that the total force/torque
* applied on the brick is 0. The decision variables are (q, f_Cb_B) where q is
* the generalized position, and f_Cb_B are the contact force (y, z) component
* applied to the point Cb on the brick, expressed in the brick frame B.
* The constraint are
*
* 0 = R_BW * m * g_W + ∑ᵢ f_Cbi_B
* 0 = ∑ᵢp_Cbi_B.cross(f_Cbi_B)
* Notice that since the gripper/brick system is planar, the first equation is
* only on the (y, z) component of the total force, and the second equation is
* only on the x component of the torque.
*
* The constraint evaluates the right-hand side of the two equations above.
*/
class BrickStaticEquilibriumNonlinearConstraint : public solvers::Constraint {
public:
BrickStaticEquilibriumNonlinearConstraint(
const GripperBrickHelper<double>& gripper_brick_system,
std::vector<std::pair<Finger, BrickFace>> finger_face_contacts,
systems::Context<double>* plant_mutable_context);
private:
template<typename T>
void DoEvalGeneric(const Eigen::Ref<const VectorX<T>> &x,
VectorX<T> *y) const;
void DoEval(const Eigen::Ref<const Eigen::VectorXd> &x,
Eigen::VectorXd *y) const;
void DoEval(const Eigen::Ref<const AutoDiffVecXd> &x, AutoDiffVecXd *y) const;
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>> &,
VectorX<symbolic::Expression> *) const;
const GripperBrickHelper<double>& gripper_brick_system_;
double brick_mass_;
std::vector<std::pair<Finger, BrickFace>> finger_face_contacts_;
systems::Context<double> *plant_mutable_context_;
};
/**
* Given the assignment of contacts between fingers and faces, add the following
* constraints/variables to the program:
* 1. Decision variables representing the finger contact force on the brick,
* expressed in the brick frame.
* 2. The static equilibrium constraint ensuring that the total wrench on the
* brick is 0.
* 3. The constraint that the contact force is within a friction cone.
*/
Matrix2X<symbolic::Variable> AddBrickStaticEquilibriumConstraint(
const GripperBrickHelper<double>& gripper_brick_system,
const std::vector<std::pair<Finger, BrickFace>>& finger_face_contacts,
const Eigen::Ref<const VectorX<symbolic::Variable>>& q_vars,
systems::Context<double>* plant_mutable_context,
solvers::MathematicalProgram* prog);
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/run_planar_gripper_trajectory_publisher.cc | /// @file
///
/// Implements a trajectory publisher for the planar gripper simulation by
/// interpolating a sequence of joint poses (keyframes) for the fingers, where
/// each keyframe represents a static-equilibrium condition for the brick (i.e.,
/// the net wrench on the brick is zero). This publisher communicates with the
/// simulator via LCM (publishing a desired state) and generates a sequenced
/// playback of position keyframes at an arbitrarily set speed, configured via
/// the flag `keyframe_dt`.
///
/// @Note: The keyframes contained in `postures.txt` are strictly for simulating
/// the vertical case. Using these keyframes to simulate the horizontal
/// case may cause the simulation to fail.
#include <memory>
#include <gflags/gflags.h>
#include "drake/common/drake_assert.h"
#include "drake/examples/planar_gripper/planar_gripper_common.h"
#include "drake/examples/planar_gripper/planar_gripper_lcm.h"
#include "drake/lcm/drake_lcm.h"
#include "drake/lcmt_planar_gripper_command.hpp"
#include "drake/lcmt_planar_gripper_status.hpp"
#include "drake/multibody/parsing/parser.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"
#include "drake/systems/primitives/constant_vector_source.h"
#include "drake/systems/primitives/trajectory_source.h"
namespace drake {
namespace examples {
namespace planar_gripper {
namespace {
DEFINE_double(keyframe_dt, 0.1,
"Defines a uniform time step between `break` points in our "
"spline interpolator (see PiecewisePolynomial::Pchip), where "
"each keyframe corresponds to a `knot` point. Note that keyframe "
"data in postures.txt contains static equilibrium poses and we "
"play these back at an arbitrary speed for this simulation.");
const char* const kLcmStatusChannel = "PLANAR_GRIPPER_STATUS";
const char* const kLcmCommandChannel = "PLANAR_GRIPPER_COMMAND";
int DoMain() {
lcm::DrakeLcm lcm;
systems::DiagramBuilder<double> builder;
// Create the controlled plant. Contains only the fingers (no brick). Used
// (only) to extract joint velocity ordering.
const std::string gripper_url =
"package://drake/examples/planar_gripper/planar_gripper.sdf";
MultibodyPlant<double> control_plant(0.0);
multibody::Parser(&control_plant).AddModelsFromUrl(gripper_url);
WeldGripperFrames<double>(&control_plant);
control_plant.Finalize();
const int num_fingers = 3;
const int num_joints = num_fingers * 2;
// We'll directly fix the input to the status receiver later from our lcm
// subscriber.
auto status_decoder = builder.AddSystem<GripperStatusDecoder>();
auto command_pub = builder.AddSystem(
systems::lcm::LcmPublisherSystem::Make<lcmt_planar_gripper_command>(
kLcmCommandChannel, &lcm));
auto command_encoder = builder.AddSystem<GripperCommandEncoder>();
// Parse the keyframes from a file.
const std::string keyframe_path =
"drake/examples/planar_gripper/postures.txt";
MatrixX<double> keyframes;
std::map<std::string, int> finger_joint_name_to_row_index_map;
std::tie(keyframes, finger_joint_name_to_row_index_map) =
ParseKeyframes(keyframe_path);
keyframes = ReorderKeyframesForPlant(control_plant, keyframes,
&finger_joint_name_to_row_index_map);
// Here we assume the gripper frame G is aligned with the world frame W, e.g.,
// as given by calling WeldGripperFrames(). We enforce this by checking here.
DRAKE_DEMAND(
X_WGripper().IsExactlyEqualTo(math::RigidTransform<double>::Identity()));
// Creates the time vector for the plan interpolator.
Eigen::VectorXd times = Eigen::VectorXd::Zero(keyframes.cols());
for (int i = 1; i < keyframes.cols(); ++i) {
times(i) = i * FLAGS_keyframe_dt;
}
const auto pp =
trajectories::PiecewisePolynomial<double>::CubicShapePreserving(
times, keyframes);
auto state_src = builder.AddSystem<systems::TrajectorySource<double>>(
pp, 1 /* with one derivative */);
VectorX<double> torques(num_joints); torques.setZero();
auto torques_src = builder.AddSystem<systems::ConstantVectorSource>(torques);
builder.Connect(state_src->get_output_port(),
command_encoder->get_state_input_port());
builder.Connect(torques_src->get_output_port(),
command_encoder->get_torques_input_port());
builder.Connect(command_encoder->get_output_port(0),
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));
// Wait for the first message.
drake::log()->info("Waiting for first lcmt_planar_gripper_status");
lcm::Subscriber<lcmt_planar_gripper_status> status_sub(&lcm,
kLcmStatusChannel);
LcmHandleSubscriptionsUntil(&lcm, [&]() { return status_sub.count() > 0; });
const lcmt_planar_gripper_status& first_status = status_sub.message();
DRAKE_DEMAND(first_status.num_fingers == 0 ||
first_status.num_fingers == num_fingers);
VectorX<double> q0 = VectorX<double>::Zero(num_joints);
for (int i = 0; i < first_status.num_fingers; ++i) {
int st_index = i * 2;
q0(st_index) = first_status.finger_status[i].joint_position[0];
q0(st_index + 1) = first_status.finger_status[i].joint_position[1];
}
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_decoder, &diagram_context);
auto& status_value = status_decoder->get_input_port(0).FixValue(
&status_context, first_status);
// Run forever, using the lcmt_planar_gripper_status message to dictate when
// simulation time advances.
drake::log()->info("Trajectory publisher started.");
while (true) {
// Wait for an lcmt_planar_gripper_status message.
status_sub.clear();
LcmHandleSubscriptionsUntil(&lcm, [&]() { return status_sub.count() > 0; });
// Write the lcmt_planar_gripper_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_planar_gripper_command (via the command_pub system
// within the diagram).
diagram->ForcedPublish(diagram_context);
}
// We should never reach here.
return EXIT_FAILURE;
}
} // namespace
} // namespace planar_gripper
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
return drake::examples::planar_gripper::DoMain();
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/planar_gripper_common.h | #pragma once
#include <map>
#include <string>
#include <utility>
#include "drake/multibody/plant/multibody_plant.h"
namespace drake {
namespace examples {
namespace planar_gripper {
using drake::multibody::MultibodyPlant;
using Eigen::Vector3d;
constexpr int kNumFingers = 3;
constexpr int kNumJoints = kNumFingers * 2;
// The planar-gripper coordinate frame G (with origin Go) and finger layout are
// defined as follows (assuming all finger joint angles are set to zero):
//
// F1_base F2_base
// \ +Gz /
// \ | /
// \ | /
// ● | ●
// Go----+Gy
// ●
// |
// |
// |
// F3_base
//
// The gripper frame's Y and Z axes are denote Gy and Gz, respectively. When the
// planar-gripper is welded via WeldGripperFrames(), the coordinate frame G
// perfectly coincides with the world coordinate frame W.
/**
* Welds each finger's base frame to the world. The planar-gripper is made up of
* three 2-DOF fingers, whose bases are fixed equidistant along the perimeter of
* a circle. The origin (Go) of the planar gripper is located at the center of
* the workspace, i.e., if all joints are set to zero and all fingers are
* pointing inwards, the origin is the point that is equidistant to all
* fingertips. This method welds the planar-gripper such that all motion lies in
* the Y-Z plane (in frame G). Note: The planar gripper frame G perfectly
* coincides with the world coordinate frame W when welded via this method.
* @param plant The plant containing the planar-gripper.
* @tparam_double_only
*/
template <typename T>
void WeldGripperFrames(MultibodyPlant<T>* plant);
/**
* Parses a text file containing keyframe joint positions for the planar gripper
* and the planar brick (the object being manipulated).
* @param[in] name The file name to parse.
* @param[out] brick_initial_pose A vector containing the initial brick pose,
* expressed in the gripper frame G.
* @return A std::pair containing a matrix of finger joint position keyframes
* (each matrix column represents a single keyframe containing values for all
* joint positions) and a std::map containing the mapping between each finger
* joint name and the corresponding row index in the keyframe matrix containing
* the data for that joint.
* @pre The file should begin with a header row that indicates the joint
* ordering for keyframes. Header names should consist of three finger base
* joints, three finger mid joints, and three brick joints (9 total):
* {finger1_BaseJoint, finger2_BaseJoint, finger3_BaseJoint, finger1_MidJoint,
* finger2_MidJoint, finger3_MindJoint, brick_translate_y_joint,
* brick_translate_z_joint, brick_revolute_x_joint}. Note that brick
* translations should be expressed in the planar-gripper frame G. Names may
* appear in any order. Each row (keyframe) following the header should contain
* the same number of values as indicated in the header. All entries should be
* white space delimited and the file should end in a newline character. The
* behavior of parsing is undefined if these conditions are not met.
*/
std::pair<MatrixX<double>, std::map<std::string, int>> ParseKeyframes(
const std::string& name, EigenPtr<Vector3<double>> brick_initial_pose =
EigenPtr<Vector3<double>>(nullptr));
/**
* Reorders the joint keyframe matrix data contained in `keyframes` such that
* joint keyframes (rows) are ordered according to the `plant`'s joint velocity
* index ordering, making it compatible with the inverse dynamics controller's
* desired state input port ordering. The incoming `plant` is the MultibodyPlant
* used for inverse dynamics control, i.e., the "control plant". The number of
* planar-gripper joints `kNumJoints` must exactly match plant.num_positions().
* @param[in] plant The MultibodyPlant providing the velocity index ordering.
* @param[in] keyframes The planar gripper keyframes.
* @param[out] finger_joint_name_to_row_index_map A std::map which contains the
* incoming joint name to row index ordering. This map is updated to reflect the
* new keyframe reordering.
* @return A MatrixX containing the reordered keyframes.
* @throw If the number of keyframe rows does not match the size of
* `finger_joint_name_to_row_index_map`
* @throw If the number of keyframe rows does not match the number of
* planar-gripper joints.
* @throw If `kNumJoints` does not exactly match plant.num_positions().
*/
MatrixX<double> ReorderKeyframesForPlant(
const MultibodyPlant<double>& plant,
const MatrixX<double> keyframes,
std::map<std::string, int>* finger_joint_name_to_row_index_map);
/// Returns the planar gripper frame G's transform w.r.t. the world frame W.
const math::RigidTransformd X_WGripper();
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/BUILD.bazel | load("//tools/install:install.bzl", "install")
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 = "planar_gripper_common",
srcs = ["planar_gripper_common.cc"],
hdrs = ["planar_gripper_common.h"],
deps = [
"//common:find_resource",
"//multibody/plant",
"//systems/lcm:lcm_interface_system",
],
)
drake_cc_library(
name = "planar_gripper_lcm",
srcs = ["planar_gripper_lcm.cc"],
hdrs = ["planar_gripper_lcm.h"],
deps = [
"//lcmtypes:planar_gripper",
"//systems/framework:leaf_system",
],
)
drake_cc_library(
name = "planar_manipuland_lcm",
srcs = ["planar_manipuland_lcm.cc"],
hdrs = ["planar_manipuland_lcm.h"],
deps = [
"//lcmtypes:planar_manipuland_status",
"//systems/framework:event_collection",
"//systems/framework:leaf_system",
],
)
drake_cc_library(
name = "brick_static_equilibrium_constraint",
srcs = ["brick_static_equilibrium_constraint.cc"],
hdrs = ["brick_static_equilibrium_constraint.h"],
deps = [
":gripper_brick",
":gripper_brick_planning_constraint_helper",
"//math:autodiff",
"//multibody/inverse_kinematics:kinematic_evaluators",
"//multibody/plant",
"//solvers:constraint",
"//solvers:mathematical_program",
],
)
drake_cc_library(
name = "gripper_brick",
srcs = ["gripper_brick.cc"],
hdrs = ["gripper_brick.h"],
data = [
":models",
],
deps = [
"//examples/planar_gripper:planar_gripper_common",
"//geometry:drake_visualizer",
"//multibody/parsing",
"//multibody/plant",
"//systems/analysis:simulator",
"//systems/framework:diagram",
],
)
drake_cc_binary(
name = "run_planar_gripper_trajectory_publisher",
srcs = ["run_planar_gripper_trajectory_publisher.cc"],
data = [
":models",
"//examples/planar_gripper:postures.txt",
],
deps = [
":planar_gripper_common",
":planar_gripper_lcm",
"//lcm",
"//multibody/parsing",
"//systems/analysis:simulator",
"//systems/lcm:lcm_pubsub_system",
"//systems/primitives:constant_vector_source",
"//systems/primitives:trajectory_source",
"@gflags",
],
)
drake_cc_binary(
name = "planar_gripper_simulation",
srcs = ["planar_gripper_simulation.cc"],
add_test_rule = 1,
data = [
":models",
"//examples/planar_gripper:postures.txt",
],
test_rule_args = [
"--simulation_time=0.1",
"--target_realtime_rate=0",
],
deps = [
":planar_gripper_common",
":planar_gripper_lcm",
"//geometry:drake_visualizer",
"//multibody/parsing",
"//multibody/plant",
"//multibody/plant:contact_results_to_lcm",
"//systems/analysis:simulator",
"//systems/controllers:inverse_dynamics_controller",
"//systems/framework:diagram",
"@gflags",
],
)
drake_cc_library(
name = "gripper_brick_planning_constraint_helper",
srcs = ["gripper_brick_planning_constraint_helper.cc"],
hdrs = ["gripper_brick_planning_constraint_helper.h"],
deps = [
":gripper_brick",
"//multibody/inverse_kinematics:kinematic_evaluators",
"//solvers:mathematical_program",
],
)
drake_cc_googletest(
name = "gripper_brick_test",
deps = [
":gripper_brick",
"//common/test_utilities:eigen_matrix_compare",
],
)
drake_cc_googletest(
name = "brick_static_equilibrium_constraint_test",
deps = [
":brick_static_equilibrium_constraint",
"//common/test_utilities:eigen_matrix_compare",
"//math:compute_numerical_gradient",
],
)
drake_cc_googletest(
name = "gripper_brick_planning_constraint_helper_test",
deps = [
":gripper_brick_planning_constraint_helper",
"//solvers:solve",
],
)
drake_cc_googletest(
name = "planar_manipuland_lcm_test",
deps = [
":planar_manipuland_lcm",
"//systems/framework:diagram",
"//systems/framework:diagram_builder",
],
)
drake_cc_googletest(
name = "planar_gripper_lcm_test",
deps = [
":planar_gripper_lcm",
"//systems/framework:diagram",
"//systems/framework:diagram_builder",
],
)
drake_cc_googletest(
name = "planar_gripper_common_test",
data = [
":models",
],
deps = [
":planar_gripper_common",
"//common/test_utilities:eigen_matrix_compare",
"//multibody/parsing",
"//multibody/plant",
],
)
add_lint_tests(enable_clang_format_lint = False)
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/brick_static_equilibrium_constraint.cc | #include "drake/examples/planar_gripper/brick_static_equilibrium_constraint.h"
#include <memory>
#include "drake/examples/planar_gripper/gripper_brick_planning_constraint_helper.h"
#include "drake/math/autodiff.h"
#include "drake/math/autodiff_gradient.h"
#include "drake/multibody/inverse_kinematics/kinematic_evaluator_utilities.h"
namespace drake {
namespace examples {
namespace planar_gripper {
BrickStaticEquilibriumNonlinearConstraint::
BrickStaticEquilibriumNonlinearConstraint(
const GripperBrickHelper<double>& gripper_brick_system,
std::vector<std::pair<Finger, BrickFace>> finger_face_contacts,
systems::Context<double>* plant_mutable_context)
: solvers::Constraint(
3, // planar case, only constrain the (y, z) component
// of the force, and x component of the torque.
gripper_brick_system.plant().num_positions() +
finger_face_contacts.size() * 2,
Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero()),
gripper_brick_system_{gripper_brick_system},
finger_face_contacts_(std::move(finger_face_contacts)),
plant_mutable_context_(plant_mutable_context) {
brick_mass_ = gripper_brick_system_.plant()
.GetBodyByName("brick_link")
.default_mass();
}
template <typename T>
void BrickStaticEquilibriumNonlinearConstraint::DoEvalGeneric(
const Eigen::Ref<const VectorX<T>>& x, VectorX<T>* y) const {
// y = [R_WBᵀ * mg + ∑ᵢ f_Cbi_B]
// [∑ᵢp_Cbi_B.cross(f_Cbi_B)]
using std::cos;
using std::sin;
y->resize(3);
const auto& plant = gripper_brick_system_.plant();
multibody::internal::UpdateContextConfiguration(
plant_mutable_context_, plant, x.head(plant.num_positions()));
const T theta = x(gripper_brick_system_.brick_revolute_x_position_index());
const T sin_theta = sin(theta);
const T cos_theta = cos(theta);
Matrix2<T> R_WB;
R_WB << cos_theta, -sin_theta, sin_theta, cos_theta;
// Compute R_WBᵀ * mg, the gravitational force expressed in the brick frame.
const Vector2<T> f_B =
R_WB.transpose() *
Eigen::Vector2d(
0,
-brick_mass_ *
multibody::UniformGravityFieldElement<double>::kDefaultStrength);
y->template head<2>() = f_B;
(*y)(2) = T(0);
for (int i = 0; i < static_cast<int>(finger_face_contacts_.size()); ++i) {
// Compute ∑ᵢ f_Cbi_B.
y->template head<2>() +=
x.template segment<2>(plant.num_positions() + i * 2); // f_Cbi_B
// Compute the fingertip contact point Cb in the brick frame.
// We first compute finger tip (sphere center) position in the brick frame.
const Vector3<T> p_BFingertip = ComputeFingerTipInBrickFrame(
gripper_brick_system_, finger_face_contacts_[i].first,
*plant_mutable_context_, x.head(plant.num_positions()));
// p_BCb is to shift p_BFingertip along the face inward normal direction by
// finger tip sphere radius.
Vector2<T> p_BCb = p_BFingertip.template tail<2>();
switch (finger_face_contacts_[i].second) {
case BrickFace::kPosY: {
p_BCb(0) -= T(gripper_brick_system_.finger_tip_radius());
break;
}
case BrickFace::kNegY: {
p_BCb(0) += T(gripper_brick_system_.finger_tip_radius());
break;
}
case BrickFace::kPosZ: {
p_BCb(1) -= T(gripper_brick_system_.finger_tip_radius());
break;
}
case BrickFace::kNegZ: {
p_BCb(1) += T(gripper_brick_system_.finger_tip_radius());
break;
}
}
// Now compute the torque about the COM
(*y)(2) += p_BCb(0) * x(plant.num_positions() + 2 * i + 1) -
p_BCb(1) * x(plant.num_positions() + 2 * i);
}
}
void BrickStaticEquilibriumNonlinearConstraint::DoEval(
const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const {
DoEvalGeneric<double>(x, y);
}
void BrickStaticEquilibriumNonlinearConstraint::DoEval(
const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const {
DoEvalGeneric<AutoDiffXd>(x, y);
}
void BrickStaticEquilibriumNonlinearConstraint::DoEval(
const Eigen::Ref<const VectorX<symbolic::Variable>>&,
VectorX<symbolic::Expression>*) const {
throw std::runtime_error(
"BrickStaticEquilibriumNonlinearConstraint::DoEval does not support "
"symbolic computation.");
}
Eigen::Matrix<symbolic::Variable, 2, Eigen::Dynamic>
AddBrickStaticEquilibriumConstraint(
const GripperBrickHelper<double>& gripper_brick_system,
const std::vector<std::pair<Finger, BrickFace>>& finger_face_contacts,
const Eigen::Ref<const VectorX<symbolic::Variable>>& q_vars,
systems::Context<double>* plant_mutable_context,
solvers::MathematicalProgram* prog) {
const int num_contacts = static_cast<int>(finger_face_contacts.size());
const auto f_Cb_B =
prog->NewContinuousVariables<2, Eigen::Dynamic>(2, num_contacts);
const auto& plant = gripper_brick_system.plant();
// Now add the nonlinear constraint that the total wrench is 0.
VectorX<symbolic::Variable> nonlinear_constraint_bound_vars(
plant.num_positions() + 2 * num_contacts);
nonlinear_constraint_bound_vars.head(plant.num_positions()) = q_vars;
for (int i = 0; i < num_contacts; ++i) {
nonlinear_constraint_bound_vars.segment<2>(plant.num_positions() + 2 * i) =
f_Cb_B.col(i);
}
prog->AddConstraint(
std::make_shared<BrickStaticEquilibriumNonlinearConstraint>(
gripper_brick_system, finger_face_contacts, plant_mutable_context),
nonlinear_constraint_bound_vars);
// Add the linear constraint that the contact force is within the friction
// cone.
for (int i = 0; i < num_contacts; ++i) {
const double friction_cone_shrink_factor = 1;
AddFrictionConeConstraint(gripper_brick_system,
finger_face_contacts[i].first,
finger_face_contacts[i].second, f_Cb_B,
friction_cone_shrink_factor, prog);
}
return f_Cb_B;
}
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/planar_gripper_simulation.cc | /// @file
///
/// This demo simulates a planar-gripper (three two-degree-of-freedom fingers
/// moving in a plane) which reorients a brick through contact-interactions.
///
/// This simulation can be configured to run in one of two control modes:
/// position control or torque control. In position control mode, desired state
/// is communicated via LCM and fed into a trajectory tracking
/// InverseDynamicsController. In torque control mode, desired torques are
/// communicated via LCM but are instead directly fed into the actuation input
/// port of the MBP. The control mode can be configured by setting the flag
/// `use_position_control` to true (default) for position control mode, and
/// setting it to false for torque control mode.
///
/// The planar-gripper coordinate frame is illustrated in
/// `planar_gripper_common.h`. Users have the option to either orient the
/// gravity vector to point along the -Gz axis, i.e., simulating the case when
/// the planar-gripper is stood up vertically, or have gravity point along the
/// -Gx axis, i.e., simulating the case when the planar-gripper is laid down
/// flat on the floor.
///
/// To support the vertical case (gravity acting along -Gz) in hardware, we use
/// a plexiglass lid (ceiling) that is opposite the planar-gripper floor in
/// order to keep the brick's motion constrained to the Gy-Gz plane. That is,
/// when the lid is closed the brick is "squeezed" between the ceiling and floor
/// and is physically fixed in the Gx-axis due to contact with these surfaces.
/// For simulation, we mimic this contact interaction by fixing the amount by
/// which the brick geometry penetrates the floor geometry (without considering
/// the ceiling), and can specify this penetration depth via the flag
/// `brick_floor_penetration'. To enforce zero contact between the brick and
/// floor, set this flag to zero.
///
/// For the horizontal case in hardware, gravity (acting along -Gx) keeps the
/// brick's motion constrained to lie in the Gy-Gz plane (no ceiling required),
/// and therefore the plexiglass lid is left open. This means surface contact
/// only occurs between the brick and the floor. In simulation, we define an
/// additional prismatic degree of freedom for the brick along the Gx axis, such
/// that the brick's position along Gx is determined by gravitational and floor
/// contact forces acting on the brick. In this case, the
/// `brick_floor_penetration` flag specifies only the initial brick/floor
/// penetration depth.
///
/// @Note: The keyframes contained in `postures.txt` are strictly for simulating
/// the vertical case. Using these keyframes to simulate the horizontal
/// case may cause the simulation to fail.
// TODO(rcory) Include a README.md that explains the use cases for this
// example.
#include <memory>
#include <gflags/gflags.h>
#include "drake/common/drake_assert.h"
#include "drake/common/trajectories/piecewise_polynomial.h"
#include "drake/examples/planar_gripper/planar_gripper_common.h"
#include "drake/examples/planar_gripper/planar_gripper_lcm.h"
#include "drake/geometry/drake_visualizer.h"
#include "drake/geometry/scene_graph.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/multibody/plant/contact_results_to_lcm.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/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"
namespace drake {
namespace examples {
namespace planar_gripper {
namespace {
using geometry::SceneGraph;
using multibody::ConnectContactResultsToDrakeVisualizer;
using multibody::JointActuatorIndex;
using multibody::ModelInstanceIndex;
using multibody::MultibodyPlant;
using multibody::Parser;
using multibody::PrismaticJoint;
using multibody::RevoluteJoint;
using Eigen::Vector3d;
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, 4.5,
"Desired duration of the simulation in seconds.");
DEFINE_double(time_step, 1e-3,
"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.");
DEFINE_double(penetration_allowance, 1e-3,
"The contact penetration allowance.");
DEFINE_double(floor_coef_static_friction, 0.5,
"The floor's coefficient of static friction");
DEFINE_double(floor_coef_kinetic_friction, 0.5,
"The floor's coefficient of kinetic friction");
DEFINE_double(brick_floor_penetration, 1e-5,
"Determines how much the brick should penetrate the floor "
"(in meters). When simulating the vertical case this penetration "
"distance will remain fixed.");
DEFINE_string(orientation, "vertical",
"The orientation of the planar gripper. Options are {vertical, "
"horizontal}.");
DEFINE_bool(visualize_contacts, false,
"Visualize contacts in Meldis.");
DEFINE_bool(
use_position_control, true,
"If true (default) we simulate position control via inverse dynamics "
"control. If false we actuate torques directly.");
/// Adds a floor to the simulation, modeled as a thin cylinder.
void AddFloor(MultibodyPlant<double>* plant,
const SceneGraph<double>& scene_graph) {
// Get info for the brick from the SceneGraph inspector. This is used to
// determine placement of the floor in order to achieve the specified
// brick/floor penetration.
const geometry::SceneGraphInspector<double>& inspector =
scene_graph.model_inspector();
// The brick model includes four small sphere collisions at the bottom four
// corners of the box collision. These four spheres (and not the box) are
// intended to make contact with the floor. Here we extract the height of
// these spheres in order to weld the floor at the appropriate height, such
// that the initial box/floor penetration is given by the flag
// brick_floor_penetration.
const geometry::Shape& sphere_shape =
inspector.GetShape(inspector.GetGeometryIdByName(
plant->GetBodyFrameIdOrThrow(
plant->GetBodyByName("brick_link").index()),
geometry::Role::kProximity, "brick::sphere1_collision"));
const double sphere_radius =
dynamic_cast<const geometry::Sphere&>(sphere_shape).radius();
const math::RigidTransformd X_WS =
inspector.GetPoseInFrame(inspector.GetGeometryIdByName(
plant->GetBodyFrameIdOrThrow(
plant->GetBodyByName("brick_link").index()),
geometry::Role::kProximity, "brick::sphere1_collision"));
const double kFloorHeight = 0.001;
const double kSphereTipXOffset = X_WS.translation()(0) - sphere_radius;
const drake::multibody::CoulombFriction<double> coef_friction_floor(
FLAGS_floor_coef_static_friction, FLAGS_floor_coef_kinetic_friction);
const math::RigidTransformd X_WF(
Eigen::AngleAxisd(M_PI_2, Vector3d::UnitY()),
Vector3d(kSphereTipXOffset - (kFloorHeight / 2.0) +
FLAGS_brick_floor_penetration, 0, 0));
const Vector4<double> black(0.2, 0.2, 0.2, 1.0);
plant->RegisterVisualGeometry(plant->world_body(), X_WF,
geometry::Cylinder(.125, kFloorHeight),
"FloorVisualGeometry", black);
plant->RegisterCollisionGeometry(
plant->world_body(), X_WF, geometry::Cylinder(.125, kFloorHeight),
"FloorCollisionGeometry", coef_friction_floor);
}
/// Reorders the generalized force output vector of the ID controller
/// (internally using a control plant with only the gripper) to match the
/// actuation input ordering for the full simulation plant (containing gripper
/// and brick).
class GeneralizedForceToActuationOrdering : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(GeneralizedForceToActuationOrdering);
explicit GeneralizedForceToActuationOrdering(
const MultibodyPlant<double>& plant)
: Binv_(plant.MakeActuationMatrix().inverse()) {
this->DeclareVectorInputPort("tau", plant.num_actuators());
this->DeclareVectorOutputPort(
"u", plant.num_actuators(),
&GeneralizedForceToActuationOrdering::remap_output);
}
void remap_output(const systems::Context<double>& context,
systems::BasicVector<double>* output_vector) const {
Eigen::VectorBlock<VectorX<double>> output_value =
output_vector->get_mutable_value();
const VectorX<double>& input_value =
this->EvalVectorInput(context, 0)->value();
output_value.setZero();
output_value = Binv_ * input_value;
}
private:
const MatrixX<double> Binv_;
};
/// A system whose input port takes in MBP joint reaction forces and whose
/// outputs correspond to the (planar-only) forces felt at the force sensor,
/// for all three fingers (i.e., fy and fz). Because the task is planar, we
/// ignore any forces/torques not acting in the y-z plane.
class ForceSensorEvaluator : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ForceSensorEvaluator);
explicit ForceSensorEvaluator(const MultibodyPlant<double>& plant) {
const int num_sensors = 3;
for (int i = 1; i <= num_sensors; i++) {
std::string joint_name =
"finger" + std::to_string(i) + "_sensor_weldjoint";
sensor_joint_indices_.push_back(
plant.GetJointByName<multibody::WeldJoint>(joint_name).index());
}
this->DeclareAbstractInputPort(
"spatial_forces_in",
Value<std::vector<multibody::SpatialForce<double>>>())
.get_index();
this->DeclareVectorOutputPort("force_sensors_out", num_sensors * 2,
&ForceSensorEvaluator::CalcOutput)
.get_index();
}
void CalcOutput(const drake::systems::Context<double>& context,
drake::systems::BasicVector<double>* output) const {
const std::vector<multibody::SpatialForce<double>>& spatial_vec =
this->get_input_port(0)
.Eval<std::vector<multibody::SpatialForce<double>>>(context);
auto output_value = output->get_mutable_value();
// Force sensor (fy, fz) values, measured in the "tip_link" frame.
output_value.head<2>() =
spatial_vec[sensor_joint_indices_[0]].translational().tail(2);
output_value.segment<2>(2) =
spatial_vec[sensor_joint_indices_[1]].translational().tail(2);
output_value.tail<2>() =
spatial_vec[sensor_joint_indices_[2]].translational().tail(2);
}
private:
std::vector<multibody::JointIndex> sensor_joint_indices_;
};
int DoMain() {
systems::DiagramBuilder<double> builder;
auto [plant, scene_graph] =
multibody::AddMultibodyPlantSceneGraph(&builder, FLAGS_time_step);
// Make and add the planar_gripper model.
const std::string gripper_url =
"package://drake/examples/planar_gripper/planar_gripper.sdf";
const ModelInstanceIndex gripper_index =
Parser(&plant).AddModelsFromUrl(gripper_url).at(0);
WeldGripperFrames<double>(&plant);
// Adds the brick to be manipulated.
const std::string brick_url =
"package://drake/examples/planar_gripper/planar_brick.sdf";
Parser(&plant).AddModelsFromUrl(brick_url);
// When the planar-gripper is welded via WeldGripperFrames(), motion always
// lies in the world Y-Z plane (because the planar-gripper frame is aligned
// with the world frame). Therefore, gravity can either point along the world
// -Z axis (vertical case), or world -X axis (horizontal case).
Vector3d gravity;
if (FLAGS_orientation == "vertical") {
const multibody::Frame<double>& brick_base_frame =
plant.GetFrameByName("brick_base");
plant.WeldFrames(plant.world_frame(), brick_base_frame);
gravity = Vector3d(
0, 0, -multibody::UniformGravityFieldElement<double>::kDefaultStrength);
} else if (FLAGS_orientation == "horizontal") {
plant.AddJoint<PrismaticJoint>(
"brick_translate_x_joint",
plant.world_body(), std::nullopt,
plant.GetBodyByName("brick_base"), std::nullopt,
Vector3d::UnitX());
gravity = Vector3d(
-multibody::UniformGravityFieldElement<double>::kDefaultStrength, 0, 0);
} else {
throw std::logic_error("Unrecognized 'orientation' flag.");
}
// Create the controlled plant. Contains only the fingers (no bricks).
MultibodyPlant<double> control_plant(FLAGS_time_step);
Parser(&control_plant).AddModelsFromUrl(gripper_url);
WeldGripperFrames<double>(&control_plant);
// Adds a thin floor that can provide friction against the brick.
AddFloor(&plant, scene_graph);
// Finalize the simulation and control plants.
plant.Finalize();
control_plant.Finalize();
plant.set_penetration_allowance(FLAGS_penetration_allowance);
plant.mutable_gravity_field().set_gravity_vector(gravity);
control_plant.mutable_gravity_field().set_gravity_vector(gravity);
systems::lcm::LcmInterfaceSystem* lcm =
builder.AddSystem<systems::lcm::LcmInterfaceSystem>();
auto command_sub = builder.AddSystem(
systems::lcm::LcmSubscriberSystem::Make<
drake::lcmt_planar_gripper_command>("PLANAR_GRIPPER_COMMAND", lcm));
auto command_decoder = builder.AddSystem<GripperCommandDecoder>();
builder.Connect(command_sub->get_output_port(),
command_decoder->get_input_port(0));
// The planar gripper "command" LCM message contains entries for both desired
// state and desired torque. However, the boolean gflag `use_position_control`
// ultimately controls whether the diagram is wired for position control mode
// (desired torques are ignored) or torque control mode (desired state is
// ignored).
if (FLAGS_use_position_control) {
// Create the gains for the inverse dynamics controller. These gains were
// chosen arbitrarily.
Vector<double, kNumJoints> Kp, Kd, Ki;
Kp.setConstant(1500); Kd.setConstant(500); Ki.setConstant(500);
auto id_controller =
builder.AddSystem<systems::controllers::InverseDynamicsController>(
control_plant, Kp, Ki, Kd, false);
// Connect the ID controller.
builder.Connect(plant.get_state_output_port(gripper_index),
id_controller->get_input_port_estimated_state());
builder.Connect(command_decoder->get_state_output_port(),
id_controller->get_input_port_desired_state());
// The inverse dynamics controller internally uses a "controlled plant",
// which contains the gripper model *only* (i.e., no brick). Therefore, its
// output must be re-mapped to the actuation input of the full "simulation
// plant", which contains both gripper and brick. The system
// GeneralizedForceToActuationOrdering fills this role.
auto force_to_actuation =
builder.AddSystem<GeneralizedForceToActuationOrdering>(control_plant);
builder.Connect(id_controller->get_output_port_control(),
force_to_actuation->get_input_port());
builder.Connect(force_to_actuation->get_output_port(0),
plant.get_actuation_input_port(gripper_index));
} else { // Use torque control.
builder.Connect(command_decoder->get_torques_output_port(),
plant.get_actuation_input_port());
}
geometry::DrakeVisualizerd::AddToBuilder(&builder, scene_graph, lcm);
// Publish contact results for visualization.
if (FLAGS_visualize_contacts) {
ConnectContactResultsToDrakeVisualizer(&builder, plant, scene_graph, lcm);
}
// Publish planar gripper status via LCM.
auto status_pub = builder.AddSystem(
systems::lcm::LcmPublisherSystem::Make<drake::lcmt_planar_gripper_status>(
"PLANAR_GRIPPER_STATUS", lcm, kGripperLcmStatusPeriod));
auto status_encoder = builder.AddSystem<GripperStatusEncoder>();
builder.Connect(plant.get_state_output_port(gripper_index),
status_encoder->get_state_input_port());
auto force_sensor_evaluator = builder.AddSystem<ForceSensorEvaluator>(plant);
builder.Connect(plant.get_reaction_forces_output_port(),
force_sensor_evaluator->get_input_port(0));
builder.Connect(force_sensor_evaluator->get_output_port(0),
status_encoder->get_force_input_port());
builder.Connect(status_encoder->get_output_port(0),
status_pub->get_input_port());
auto diagram = builder.Build();
// Extract the initial gripper and brick poses by parsing the keyframe file.
// The brick's pose consists of {y_position, z_position, x_rotation_angle}.
const std::string keyframe_path =
"drake/examples/planar_gripper/postures.txt";
MatrixX<double> keyframes;
std::map<std::string, int> finger_joint_name_to_row_index_map;
Vector3<double> brick_initial_2D_pose_G;
std::tie(keyframes, finger_joint_name_to_row_index_map) =
ParseKeyframes(keyframe_path, &brick_initial_2D_pose_G);
keyframes = ReorderKeyframesForPlant(control_plant, keyframes,
&finger_joint_name_to_row_index_map);
// Create the initial condition vector. Set initial joint velocities to zero.
VectorX<double> gripper_initial_conditions =
VectorX<double>::Zero(kNumJoints * 2);
gripper_initial_conditions.head(kNumJoints) =
keyframes.block(0, 0, kNumJoints, 1);
// 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());
systems::Simulator<double> simulator(*diagram, std::move(diagram_context));
systems::Context<double>& simulator_context = simulator.get_mutable_context();
command_decoder->set_initial_position(
&diagram->GetMutableSubsystemContext(*command_decoder,
&simulator_context),
gripper_initial_conditions.head(kNumJoints));
// All fingers consist of two joints: a base joint and a mid joint.
// Set the initial finger joint positions.
for (int i = 0; i < kNumFingers; i++) {
std::string finger = "finger" + std::to_string(i + 1);
const RevoluteJoint<double>& base_pin =
plant.GetJointByName<RevoluteJoint>(finger + "_BaseJoint");
const RevoluteJoint<double>& mid_pin =
plant.GetJointByName<RevoluteJoint>(finger + "_MidJoint");
int base_index = finger_joint_name_to_row_index_map[finger + "_BaseJoint"];
int mid_index = finger_joint_name_to_row_index_map[finger + "_MidJoint"];
base_pin.set_angle(&plant_context, gripper_initial_conditions(base_index));
mid_pin.set_angle(&plant_context, gripper_initial_conditions(mid_index));
}
// Set the brick's initial conditions.
const PrismaticJoint<double>& y_translate =
plant.GetJointByName<PrismaticJoint>("brick_translate_y_joint");
const PrismaticJoint<double>& z_translate =
plant.GetJointByName<PrismaticJoint>("brick_translate_z_joint");
const RevoluteJoint<double>& x_revolute =
plant.GetJointByName<RevoluteJoint>("brick_revolute_x_joint");
y_translate.set_translation(&plant_context, brick_initial_2D_pose_G(0));
z_translate.set_translation(&plant_context, brick_initial_2D_pose_G(1));
x_revolute.set_angle(&plant_context, brick_initial_2D_pose_G(2));
simulator.set_target_realtime_rate(FLAGS_target_realtime_rate);
simulator.Initialize();
simulator.AdvanceTo(FLAGS_simulation_time);
return 0;
}
} // namespace
} // namespace planar_gripper
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
gflags::SetUsageMessage("A simple planar gripper example.");
gflags::ParseCommandLineFlags(&argc, &argv, true);
return drake::examples::planar_gripper::DoMain();
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/planar_manipuland_lcm.h | #pragma once
/// @file
/// This file contains classes dealing with sending/receiving
/// LCM messages related to the planar manipuland.
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/lcmt_planar_manipuland_status.hpp"
#include "drake/systems/framework/event_status.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace examples {
namespace planar_gripper {
// This should be the update frequency of the mocap system.
constexpr double kPlanarManipulandStatusPeriod = 0.010;
/// Handles lcmt_planar_manipuland_status messages from a LcmSubscriberSystem.
///
/// This system has one abstract valued input port which expects a
/// Value object templated on type `lcmt_planar_manipuland_status`.
///
/// This system has one vector valued output port which reports
/// measured pose (y, z, theta) and velocity (ydot, zdot, thetadot) of the
/// manipuland.
///
/// All ports will continue to output their initial state (typically
/// zero) until a message is received.
///
/// @system
/// name: PlanarManipulandStatusDecoder
/// input_ports:
/// - manipuland_state
/// output_ports:
/// - y0
/// @endsystem
class PlanarManipulandStatusDecoder : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PlanarManipulandStatusDecoder)
PlanarManipulandStatusDecoder();
~PlanarManipulandStatusDecoder() {}
private:
void OutputStatus(const systems::Context<double>& context,
systems::BasicVector<double>* output) const;
/// Event handler of the periodic discrete state update.
systems::EventStatus UpdateDiscreteState(
const systems::Context<double>& context,
systems::DiscreteValues<double>* discrete_state) const;
};
/**
* Creates and outputs lcmt_planar_manipuland_status messages.
*
* This system has one vector-valued input port containing the current pose
* (y, z, theta) and velocity (ẏ, ż, thetadot) of the manipuland, in the order
* (y, z, theta, ydot, zdot, thetadot).
*
* This system has one abstract valued output port that contains a Value object
* templated on type `lcmt_planar_manipuland_status`. Note that this system
* does NOT actually send this message on an LCM channel. To send the message,
* the output of this system should be connected to an input port of a
* systems::lcm::LcmPublisherSystem that accepts a Value object templated on
* type `lcmt_planar_manipuland_status`.
*
* @system
* name: PlanarManipulandStatusEncoder
* input_ports:
* - u0
* output_ports:
* - y0
* @endsystem
*/
class PlanarManipulandStatusEncoder : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PlanarManipulandStatusEncoder)
PlanarManipulandStatusEncoder();
private:
// This is the calculator method for the output port.
void OutputStatus(const systems::Context<double>& context,
lcmt_planar_manipuland_status* output) const;
};
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/README.md | # Planar Gripper Example
This directory contains an example for simulating a planar-gripper
(three two-degree-of-freedom fingers moving in a plane) which reorients a brick
through contact interactions.
## 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 example in this directory
```
bazel build //examples/planar_gripper/...
```
## Example
### Run Trajectory Publisher
```
bazel-bin/examples/planar_gripper/run_planar_gripper_trajectory_publisher
```
Sends desired joint positions over LCM. Requires a suitable LCM based
simulator (such as the example in this directory) listening for
`lcmt_planar_gripper_command` messages and publishing
`lcmt_planar_gripper_status` messages. If successful, the program will
display `Waiting for first lcmt_planar_gripper_status`, indicating it is
waiting for the simulation to start publishing status messages.
### Simulation
Run the following example of an (LCM based) simulation of a planar-gripper:
```
bazel-bin/examples/planar_gripper/planar_gripper_simulation
```
This simulates a planar-gripper with a position-based inverse dynamics
controller (by default), communicating via LCM.
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/planar_gripper_lcm.cc | #include "drake/examples/planar_gripper/planar_gripper_lcm.h"
#include <vector>
#include "drake/common/drake_assert.h"
#include "drake/lcmt_planar_gripper_command.hpp"
#include "drake/lcmt_planar_gripper_status.hpp"
namespace drake {
namespace examples {
namespace planar_gripper {
using systems::BasicVector;
using systems::Context;
using systems::DiscreteValues;
using systems::DiscreteUpdateEvent;
GripperCommandDecoder::GripperCommandDecoder(int num_fingers) :
num_fingers_(num_fingers), num_joints_(num_fingers * 2) {
this->DeclareAbstractInputPort(
"lcmt_planar_gripper_command",
Value<lcmt_planar_gripper_command>{});
state_output_port_ = &this->DeclareVectorOutputPort(
"state", num_joints_ * 2, &GripperCommandDecoder::OutputStateCommand);
torques_output_port_ = &this->DeclareVectorOutputPort(
"torques", num_joints_, &GripperCommandDecoder::OutputTorqueCommand);
this->DeclarePeriodicDiscreteUpdateEvent(
kGripperLcmStatusPeriod, 0., &GripperCommandDecoder::UpdateDiscreteState);
// Register a forced discrete state update event. It is added for unit test,
// or for potential users who require forced updates.
this->DeclareForcedDiscreteUpdateEvent(
&GripperCommandDecoder::UpdateDiscreteState);
// Discrete state holds pos, vel, torque.
this->DeclareDiscreteState(num_joints_ * 3);
}
void GripperCommandDecoder::set_initial_position(
Context<double>* context,
const Eigen::Ref<const VectorX<double>> pos) const {
// The Discrete state consists of positions, velocities, torques.
auto state_value =
context->get_mutable_discrete_state(0).get_mutable_value();
DRAKE_ASSERT(pos.size() == num_joints_);
// Set the initial positions.
state_value.head(num_joints_) = pos;
// Set the initial velocities and torques to zero.
state_value.tail(num_joints_ * 2) = VectorX<double>::Zero(num_joints_ * 2);
}
systems::EventStatus GripperCommandDecoder::UpdateDiscreteState(
const Context<double>& context,
DiscreteValues<double>* discrete_state) const {
const AbstractValue* input = this->EvalAbstractInput(context, 0);
DRAKE_ASSERT(input != nullptr);
const auto& command = input->get_value<lcmt_planar_gripper_command>();
// If we're using a default constructed message (haven't received
// a command yet), keep using the initial state.
auto state_value = discrete_state->get_mutable_value(0);
auto positions = state_value.head(num_joints_);
auto velocities = state_value.segment(num_joints_, num_joints_);
auto torques = state_value.tail(num_joints_);
DRAKE_DEMAND(command.num_fingers == 0 || command.num_fingers == num_fingers_);
for (int i = 0; i < command.num_fingers; ++i) {
const lcmt_planar_gripper_finger_command& fcommand =
command.finger_command[i];
const int st_index = 2 * i;
positions(st_index) = fcommand.joint_position[0];
positions(st_index + 1) = fcommand.joint_position[1];
velocities(st_index) = fcommand.joint_velocity[0];
velocities(st_index + 1) = fcommand.joint_velocity[1];
torques(st_index) = fcommand.joint_torque[0];
torques(st_index + 1) = fcommand.joint_torque[1];
}
return systems::EventStatus::Succeeded();
}
void GripperCommandDecoder::OutputStateCommand(
const Context<double>& context, BasicVector<double>* output) const {
Eigen::VectorBlock<VectorX<double>> output_vec = output->get_mutable_value();
output_vec = context.get_discrete_state(0).value().head(num_joints_ * 2);
}
void GripperCommandDecoder::OutputTorqueCommand(
const Context<double>& context, BasicVector<double>* output) const {
Eigen::VectorBlock<VectorX<double>> output_vec =
output->get_mutable_value();
output_vec = context.get_discrete_state(0).get_value().tail(num_joints_);
}
GripperCommandEncoder::GripperCommandEncoder(int num_fingers) :
num_fingers_(num_fingers), num_joints_(num_fingers * 2) {
state_input_port_ =
&this->DeclareInputPort("state", systems::kVectorValued, num_joints_ * 2);
torques_input_port_ =
&this->DeclareInputPort("torque", systems::kVectorValued, num_joints_);
this->DeclareAbstractOutputPort("lcmt_gripper_command",
&GripperCommandEncoder::OutputCommand);
}
void GripperCommandEncoder::OutputCommand(
const Context<double>& context,
lcmt_planar_gripper_command* command) const {
command->utime = static_cast<int64_t>(context.get_time() * 1e6);
const systems::BasicVector<double>* state_input =
this->EvalVectorInput(context, 0);
const systems::BasicVector<double>* torque_input =
this->EvalVectorInput(context, 1);
command->num_fingers = num_fingers_;
command->finger_command.resize(num_fingers_);
for (int i = 0; i < num_fingers_; ++i) {
const int st_index = 2 * i;
lcmt_planar_gripper_finger_command& fcommand =
command->finger_command[i];
fcommand.joint_position[0] = state_input->GetAtIndex(st_index);
fcommand.joint_position[1] = state_input->GetAtIndex(st_index + 1);
fcommand.joint_velocity[0] =
state_input->GetAtIndex(num_joints_ + st_index);
fcommand.joint_velocity[1] =
state_input->GetAtIndex(num_joints_ + st_index + 1);
fcommand.joint_torque[0] = torque_input->GetAtIndex(st_index);
fcommand.joint_torque[1] = torque_input->GetAtIndex(st_index + 1);
}
}
GripperStatusDecoder::GripperStatusDecoder(int num_fingers)
: num_fingers_(num_fingers),
num_joints_(num_fingers * 2),
num_tip_forces_(num_fingers * 2) {
state_output_port_ = &this->DeclareVectorOutputPort(
"state", num_joints_ * 2, &GripperStatusDecoder::OutputStateStatus);
force_output_port_ =
&this->DeclareVectorOutputPort("fingertip_force", num_tip_forces_,
&GripperStatusDecoder::OutputForceStatus);
this->DeclareAbstractInputPort("lcmt_planar_gripper_status",
Value<lcmt_planar_gripper_status>{});
// Discrete state includes: {state, fingertip_force(y,z)}.
this->DeclareDiscreteState((num_joints_* 2) + (num_fingers_ * 2));
this->DeclarePeriodicDiscreteUpdateEvent(
kGripperLcmStatusPeriod, 0., &GripperStatusDecoder::UpdateDiscreteState);
// Register a forced discrete state update event. It is added for unit test,
// or for potential users who require forced updates.
this->DeclareForcedDiscreteUpdateEvent(
&GripperStatusDecoder::UpdateDiscreteState);
}
systems::EventStatus GripperStatusDecoder::UpdateDiscreteState(
const Context<double>& context,
DiscreteValues<double>* discrete_state) const {
const AbstractValue* input = this->EvalAbstractInput(context, 0);
DRAKE_ASSERT(input != nullptr);
const auto& status = input->get_value<lcmt_planar_gripper_status>();
auto state_value = discrete_state->get_mutable_value(0);
auto positions = state_value.head(num_joints_);
auto velocities = state_value.segment(num_joints_, num_joints_);
auto tip_forces = state_value.tail(num_fingers_ * 2);
DRAKE_DEMAND(status.num_fingers == 0 || status.num_fingers == num_fingers_);
for (int i = 0; i < status.num_fingers; ++i) {
const int st_index = 2 * i;
const lcmt_planar_gripper_finger_status& fstatus = status.finger_status[i];
positions(st_index) = fstatus.joint_position[0];
positions(st_index + 1) = fstatus.joint_position[1];
velocities(st_index) = fstatus.joint_velocity[0];
velocities(st_index + 1) = fstatus.joint_velocity[1];
tip_forces(st_index) = fstatus.fingertip_force.fy;
tip_forces(st_index + 1) = fstatus.fingertip_force.fz;
}
return systems::EventStatus::Succeeded();
}
void GripperStatusDecoder::OutputStateStatus(
const Context<double>& context, BasicVector<double>* output) const {
Eigen::VectorBlock<VectorX<double>> output_vec = output->get_mutable_value();
output_vec = context.get_discrete_state(0).value().head(num_joints_ * 2);
}
void GripperStatusDecoder::OutputForceStatus(
const Context<double>& context, BasicVector<double>* output) const {
Eigen::VectorBlock<VectorX<double>> output_vec = output->get_mutable_value();
output_vec = context.get_discrete_state(0).value().tail(num_fingers_ * 2);
}
GripperStatusEncoder::GripperStatusEncoder(int num_fingers)
: num_fingers_(num_fingers),
num_joints_(num_fingers * 2),
num_tip_forces_(num_fingers * 2) {
state_input_port_ =
&this->DeclareInputPort("state", systems::kVectorValued, num_joints_ * 2);
force_input_port_ = &this->DeclareInputPort(
"fingertip_force", systems::kVectorValued, num_tip_forces_);
this->DeclareAbstractOutputPort("lcmt_gripper_status",
&GripperStatusEncoder::OutputStatus);
}
void GripperStatusEncoder::OutputStatus(
const Context<double>& context, lcmt_planar_gripper_status* status) const {
status->utime = static_cast<int64_t>(context.get_time() * 1e6);
const systems::BasicVector<double>* state_input =
this->EvalVectorInput(context, 0);
const VectorX<double>& state_value = state_input->value();
const systems::BasicVector<double>* force_input =
this->EvalVectorInput(context, 1);
const VectorX<double>& force_value = force_input->value();
status->num_fingers = num_fingers_;
status->finger_status.resize(num_fingers_);
for (int i = 0; i < num_fingers_; ++i) {
const int st_index = 2 * i;
lcmt_planar_gripper_finger_status& fstatus = status->finger_status[i];
fstatus.joint_position[0] = state_value(st_index);
fstatus.joint_position[1] = state_value(st_index + 1);
fstatus.joint_velocity[0] =
state_value(num_joints_ + st_index);
fstatus.joint_velocity[1] =
state_value(num_joints_ + st_index + 1);
fstatus.fingertip_force.timestamp =
static_cast<int64_t>(context.get_time() * 1e3);
fstatus.fingertip_force.fy = force_value(st_index);
fstatus.fingertip_force.fz = force_value(st_index + 1);
// For the planar gripper, these are all zero.
fstatus.fingertip_force.fx = 0;
fstatus.fingertip_force.tx = 0;
fstatus.fingertip_force.ty = 0;
fstatus.fingertip_force.tz = 0;
}
}
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/gripper_brick.cc | #include "drake/examples/planar_gripper/gripper_brick.h"
#include "drake/examples/planar_gripper/planar_gripper_common.h"
#include "drake/geometry/drake_visualizer.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/diagram_builder.h"
namespace drake {
namespace examples {
namespace planar_gripper {
std::string to_string(Finger finger) {
switch (finger) {
case Finger::kFinger1: {
return "finger 1";
}
case Finger::kFinger2: {
return "finger 2";
}
case Finger::kFinger3: {
return "finger 3";
}
default:
throw std::runtime_error("Finger not valid.");
}
}
template <typename T>
void AddDrakeVisualizer(systems::DiagramBuilder<T>*,
const geometry::SceneGraph<T>&) {
// Disabling visualization for non-double scalar type T.
}
template <>
void AddDrakeVisualizer<double>(
systems::DiagramBuilder<double>* builder,
const geometry::SceneGraph<double>& scene_graph) {
geometry::DrakeVisualizerd::AddToBuilder(builder, scene_graph);
}
template <typename T>
void InitializeDiagramSimulator(const systems::Diagram<T>&) {}
template <>
void InitializeDiagramSimulator<double>(
const systems::Diagram<double>& diagram) {
systems::Simulator<double>(diagram).Initialize();
}
template <typename T>
std::unique_ptr<systems::Diagram<T>> ConstructDiagram(
multibody::MultibodyPlant<T>** plant,
geometry::SceneGraph<T>** scene_graph) {
systems::DiagramBuilder<T> builder;
std::tie(*plant, *scene_graph) =
multibody::AddMultibodyPlantSceneGraph(&builder, 0.0);
const std::string gripper_url =
"package://drake/examples/planar_gripper/planar_gripper.sdf";
multibody::Parser parser(*plant, *scene_graph);
parser.AddModelsFromUrl(gripper_url);
examples::planar_gripper::WeldGripperFrames(*plant);
const std::string brick_url =
"package://drake/examples/planar_gripper/planar_brick.sdf";
parser.AddModelsFromUrl(brick_url);
(*plant)->WeldFrames((*plant)->world_frame(),
(*plant)->GetFrameByName("brick_base"),
math::RigidTransformd());
(*plant)->Finalize();
AddDrakeVisualizer<T>(&builder, **scene_graph);
return builder.Build();
}
template <typename T>
GripperBrickHelper<T>::GripperBrickHelper() {
diagram_ = ConstructDiagram<T>(&plant_, &scene_graph_);
InitializeDiagramSimulator(*diagram_);
const geometry::SceneGraphInspector<T>& inspector =
scene_graph_->model_inspector();
for (int i = 0; i < 3; ++i) {
finger_tip_sphere_geometry_ids_[i] = inspector.GetGeometryIdByName(
plant_->GetBodyFrameIdOrThrow(
plant_
->GetBodyByName("finger" + std::to_string(i + 1) + "_tip_link")
.index()),
geometry::Role::kProximity, "planar_gripper::tip_sphere_collision");
}
const geometry::Shape& fingertip_shape =
inspector.GetShape(finger_tip_sphere_geometry_ids_[0]);
finger_tip_radius_ =
dynamic_cast<const geometry::Sphere&>(fingertip_shape).radius();
const multibody::Frame<double>& l2_frame =
plant_->GetBodyByName("finger1_link2").body_frame();
const multibody::Frame<double>& tip_frame =
plant_->GetBodyByName("finger1_tip_link").body_frame();
math::RigidTransform<double> X_L2LTip = plant_->CalcRelativeTransform(
*(plant_->CreateDefaultContext()), l2_frame, tip_frame);
p_L2Fingertip_ =
X_L2LTip * inspector.GetPoseInFrame(finger_tip_sphere_geometry_ids_[0])
.translation();
const geometry::Shape& brick_shape =
inspector.GetShape(inspector.GetGeometryIdByName(
plant_->GetBodyFrameIdOrThrow(
plant_->GetBodyByName("brick_link").index()),
geometry::Role::kProximity, "brick::box_collision"));
brick_size_ = dynamic_cast<const geometry::Box&>(brick_shape).size();
for (int i = 0; i < 3; ++i) {
finger_base_position_indices_[i] =
plant_->GetJointByName("finger" + std::to_string(i + 1) + "_BaseJoint")
.position_start();
finger_mid_position_indices_[i] =
plant_->GetJointByName("finger" + std::to_string(i + 1) + "_MidJoint")
.position_start();
finger_link2_frames_[i] =
&(plant_->GetFrameByName("finger" + std::to_string(i + 1) + "_link2"));
}
brick_translate_y_position_index_ =
plant_->GetJointByName("brick_translate_y_joint").position_start();
brick_translate_z_position_index_ =
plant_->GetJointByName("brick_translate_z_joint").position_start();
brick_revolute_x_position_index_ =
plant_->GetJointByName("brick_revolute_x_joint").position_start();
brick_frame_ = &(plant_->GetFrameByName("brick_link"));
}
template <typename T>
const multibody::Frame<double>& GripperBrickHelper<T>::finger_link2_frame(
Finger finger) const {
switch (finger) {
case Finger::kFinger1: {
return *(finger_link2_frames_[0]);
}
case Finger::kFinger2: {
return *(finger_link2_frames_[1]);
}
case Finger::kFinger3: {
return *(finger_link2_frames_[2]);
}
default:
throw std::invalid_argument("finger_link2_frame(), unknown finger.");
}
}
template <typename T>
int GripperBrickHelper<T>::finger_base_position_index(Finger finger) const {
switch (finger) {
case Finger::kFinger1:
return finger_base_position_indices_[0];
case Finger::kFinger2:
return finger_base_position_indices_[1];
case Finger::kFinger3:
return finger_base_position_indices_[2];
default:
throw std::invalid_argument(
"finger_base_position_index(): unknown finger");
}
}
template <typename T>
int GripperBrickHelper<T>::finger_mid_position_index(Finger finger) const {
switch (finger) {
case Finger::kFinger1:
return finger_mid_position_indices_[0];
case Finger::kFinger2:
return finger_mid_position_indices_[1];
case Finger::kFinger3:
return finger_mid_position_indices_[2];
default:
throw std::invalid_argument(
"finger_mid_position_index(): unknown finger");
}
}
template <typename T>
geometry::GeometryId GripperBrickHelper<T>::finger_tip_sphere_geometry_id(
Finger finger) const {
switch (finger) {
case Finger::kFinger1: {
return finger_tip_sphere_geometry_ids_[0];
}
case Finger::kFinger2: {
return finger_tip_sphere_geometry_ids_[1];
}
case Finger::kFinger3: {
return finger_tip_sphere_geometry_ids_[2];
}
default: {
throw std::invalid_argument(
"finger_tip_sphere_geometry_id(): unknown finger.");
}
}
}
template <typename T>
multibody::CoulombFriction<T>
GripperBrickHelper<T>::GetFingerTipBrickCoulombFriction(Finger finger) const {
const geometry::ProximityProperties& brick_props =
*scene_graph_->model_inspector().GetProximityProperties(
plant_->GetCollisionGeometriesForBody(brick_frame().body())[0]);
const geometry::ProximityProperties& finger_props =
*scene_graph_->model_inspector().GetProximityProperties(
finger_tip_sphere_geometry_id(finger));
const multibody::CoulombFriction<T>& brick_friction =
brick_props.GetProperty<multibody::CoulombFriction<T>>(
"material", "coulomb_friction");
const multibody::CoulombFriction<T>& finger_tip_friction =
finger_props.GetProperty<multibody::CoulombFriction<T>>(
"material", "coulomb_friction");
return multibody::CalcContactFrictionFromSurfaceProperties(
brick_friction, finger_tip_friction);
}
// Explicit instantiation
template class GripperBrickHelper<double>;
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/gripper_brick.h | #pragma once
#include <array>
#include <memory>
#include <string>
#include "drake/geometry/scene_graph.h"
#include "drake/multibody/plant/multibody_plant.h"
#include "drake/systems/framework/diagram.h"
namespace drake {
namespace examples {
namespace planar_gripper {
enum class Finger {
kFinger1,
kFinger2,
kFinger3,
};
std::string to_string(Finger finger);
enum class BrickFace {
kPosZ,
kNegZ,
kPosY,
kNegY,
};
/**
* The helper class that contains the diagram of the planar gripper (3 planar
* fingers) with a brick.
*/
template <typename T>
class GripperBrickHelper {
public:
GripperBrickHelper();
const systems::Diagram<T>& diagram() const { return *diagram_; }
systems::Diagram<T>* get_mutable_diagram() { return diagram_.get(); }
const multibody::MultibodyPlant<T>& plant() const { return *plant_; }
multibody::MultibodyPlant<T>* get_mutable_plant() { return plant_; }
/** The index of the base joint for a given finger in MultibodyPlant. */
int finger_base_position_index(Finger finger) const;
/** The index of the middle joint for a given finger in MultibodyPlant. */
int finger_mid_position_index(Finger finger) const;
int brick_translate_y_position_index() const {
return brick_translate_y_position_index_;
}
int brick_translate_z_position_index() const {
return brick_translate_z_position_index_;
}
int brick_revolute_x_position_index() const {
return brick_revolute_x_position_index_;
}
/** Position of the finger tip sphere center "Tip" in the finger_link2 frame.
*/
Eigen::Vector3d p_L2Fingertip() const { return p_L2Fingertip_; }
const multibody::Frame<double>& brick_frame() const { return *brick_frame_; }
const multibody::Frame<double>& finger_link2_frame(Finger finger) const;
double finger_tip_radius() const { return finger_tip_radius_; }
Eigen::Vector3d brick_size() const { return brick_size_; }
/**
* Return the orientation of link 2. Notice that since the finger only moves
* in the planar surface, the orientation can be represented by the rotation
* angle around the world x axis.
*/
template <typename U>
U CalcFingerLink2Orientation(Finger finger, const U& base_joint_angle,
const U& middle_joint_angle) const {
// base_theta is the yaw angle to weld the finger base. Keep the values
// synchronized with WeldGripperFrames() in planar_gripper_common.h. The
// test in gripper_brick_test.cc guarantees that base_theta is synchronized.
double base_theta;
switch (finger) {
case Finger::kFinger1: {
base_theta = 1.0 / 3 * M_PI;
break;
}
case Finger::kFinger2: {
base_theta = -1.0 / 3 * M_PI;
break;
}
case Finger::kFinger3: {
base_theta = M_PI;
break;
}
default: { throw std::runtime_error("Unknown finger."); }
}
return base_theta + base_joint_angle + middle_joint_angle;
}
geometry::GeometryId finger_tip_sphere_geometry_id(Finger finger) const;
geometry::GeometryId brick_geometry_id() const {
return plant_->GetCollisionGeometriesForBody(brick_frame().body())[0];
}
multibody::CoulombFriction<T> GetFingerTipBrickCoulombFriction(
Finger finger) const;
private:
std::unique_ptr<systems::Diagram<T>> diagram_;
multibody::MultibodyPlant<T>* plant_;
geometry::SceneGraph<T>* scene_graph_;
static constexpr int kNumFingers{3};
std::array<int, kNumFingers> finger_base_position_indices_;
std::array<int, kNumFingers> finger_mid_position_indices_;
int brick_translate_y_position_index_;
int brick_translate_z_position_index_;
int brick_revolute_x_position_index_;
const multibody::Frame<double>* brick_frame_;
std::array<const multibody::Frame<double>*, kNumFingers>
finger_link2_frames_;
std::array<geometry::GeometryId, kNumFingers>
finger_tip_sphere_geometry_ids_;
Eigen::Vector3d p_L2Fingertip_;
double finger_tip_radius_;
Eigen::Vector3d brick_size_;
};
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/planar_gripper_common.cc | #include "drake/examples/planar_gripper/planar_gripper_common.h"
#include <fstream>
#include <map>
#include <string>
#include <utility>
#include <vector>
#include "drake/common/drake_assert.h"
#include "drake/common/find_resource.h"
#include "drake/multibody/plant/multibody_plant.h"
namespace drake {
namespace examples {
namespace planar_gripper {
using drake::math::RigidTransformd;
using drake::math::RollPitchYawd;
using drake::multibody::MultibodyPlant;
using Eigen::Vector3d;
template <typename T>
void WeldGripperFrames(MultibodyPlant<T>* plant) {
// The finger base links are all welded a fixed distance from the gripper
// frame's origin (Go), lying on the gripper frame's Y-Z plane. We denote the
// gripper frame's Y and Z axes as Gy and Gz.
const double kGripperOriginToBaseDistance = 0.201;
const double kFinger1Angle = M_PI / 3.0;
const double kFinger2Angle = -M_PI / 3.0;
const double kFinger3Angle = M_PI;
// Note: Before welding and with all finger joint angles being zero, all
// finger base links sit at the world origin with the finger pointing along
// the world -Z axis.
// We align the planar gripper coordinate frame G with the world frame W.
const RigidTransformd X_WG = X_WGripper();
// Weld the first finger. Finger base links are arranged equidistant along the
// perimeter of a circle. The first finger is welded kFinger1Angle radians
// from the +Gz-axis. Frames F1, F2, F3 correspond to the base link finger
// frames.
RigidTransformd X_GF1 =
RigidTransformd(Eigen::AngleAxisd(kFinger1Angle, Vector3d::UnitX()),
Vector3d(0, 0, 0)) *
RigidTransformd(math::RotationMatrixd(),
Vector3d(0, 0, kGripperOriginToBaseDistance));
const multibody::Frame<T>& finger1_base_frame =
plant->GetFrameByName("finger1_base");
plant->WeldFrames(plant->world_frame(), finger1_base_frame, X_WG * X_GF1);
// Weld the second finger. The second finger is welded kFinger2Angle radians
// from the +Gz-axis.
RigidTransformd X_GF2 =
RigidTransformd(Eigen::AngleAxisd(kFinger2Angle, Vector3d::UnitX()),
Vector3d(0, 0, 0)) *
RigidTransformd(math::RotationMatrixd(),
Vector3d(0, 0, kGripperOriginToBaseDistance));
const multibody::Frame<T>& finger2_base_frame =
plant->GetFrameByName("finger2_base");
plant->WeldFrames(plant->world_frame(), finger2_base_frame, X_WG * X_GF2);
// Weld the 3rd finger. The third finger is welded kFinger3Angle radians from
// the +Gz-axis.
RigidTransformd X_GF3 =
RigidTransformd(Eigen::AngleAxisd(kFinger3Angle, Vector3d::UnitX()),
Vector3d(0, 0, 0)) *
RigidTransformd(math::RotationMatrixd(),
Vector3d(0, 0, kGripperOriginToBaseDistance));
const multibody::Frame<T>& finger3_base_frame =
plant->GetFrameByName("finger3_base");
plant->WeldFrames(plant->world_frame(), finger3_base_frame, X_WG * X_GF3);
}
// Explicit instantiations.
template void WeldGripperFrames(MultibodyPlant<double>* plant);
/// Build a keyframe matrix for joints in joint_ordering by extracting the
/// appropriate columns from all_keyframes. The interpretation of columns in
/// joint_keyframes are ordered as in joint_ordering.
/// @pre There are as many strings in headers as there are columns in
/// all_keyframes.
/// @pre Every string in joint_ordering is expected to be unique.
/// @pre Every string in joint_ordering is expected to be found in headers.
MatrixX<double> MakeKeyframes(MatrixX<double> all_keyframes,
std::vector<std::string> joint_ordering,
std::vector<std::string> headers) {
// First find the columns in the keyframe data for just the joints in
// joint_ordering.
std::map<std::string, int> joint_name_to_col_index_map;
for (const auto& header_name : joint_ordering) {
auto match_it = std::find(headers.begin(), headers.end(), header_name);
DRAKE_DEMAND(match_it != headers.end());
joint_name_to_col_index_map[header_name] = match_it - headers.begin();
}
// Now create the keyframe matrix.
const int keyframe_count = all_keyframes.rows();
const int kNumFingerJoints = joint_ordering.size();
MatrixX<double> joint_keyframes(keyframe_count, kNumFingerJoints);
for (int i = 0; i < kNumFingerJoints; ++i) {
const std::string& joint_name = joint_ordering[i];
const int all_keyframe_col_index = joint_name_to_col_index_map[joint_name];
joint_keyframes.block(0, i, keyframe_count, 1) =
all_keyframes.block(0, all_keyframe_col_index, keyframe_count, 1);
}
return joint_keyframes;
}
std::pair<MatrixX<double>, std::map<std::string, int>> ParseKeyframes(
const std::string& name, EigenPtr<Vector3<double>> brick_initial_pose) {
const std::string keyframe_path = FindResourceOrThrow(name);
std::fstream file;
file.open(keyframe_path, std::fstream::in);
DRAKE_DEMAND(file.is_open());
// Count the number of lines in the file.
std::string line;
int line_count = 0;
while (!std::getline(file, line).eof()) {
line_count++;
}
const int keyframe_count = line_count - 1;
drake::log()->info("Found {} keyframes", keyframe_count);
// Get the file headers.
file.clear();
file.seekg(0);
std::getline(file, line);
std::stringstream sstream(line);
std::vector<std::string> headers;
std::string token;
while (sstream >> token) {
headers.push_back(token);
}
// Make sure we read the correct number of headers.
const int kNumHeaders = 9;
if (headers.size() != kNumHeaders) {
throw std::runtime_error(
"Unexpected number of headers found in keyframe input file.");
}
// Extract all keyframes (finger and brick)
MatrixX<double> all_keyframes(keyframe_count, headers.size());
for (int i = 0; i < all_keyframes.rows(); ++i) {
for (int j = 0; j < all_keyframes.cols(); ++j) {
file >> all_keyframes(i, j);
}
}
// Find the columns in the keyframe data for just the finger joints and
// create the corresponding keyframe matrix.
std::vector<std::string> finger_joint_ordering = {
"finger1_BaseJoint", "finger2_BaseJoint", "finger3_BaseJoint",
"finger1_MidJoint", "finger2_MidJoint", "finger3_MidJoint"};
MatrixX<double> finger_joint_keyframes =
MakeKeyframes(all_keyframes, finger_joint_ordering, headers);
// Find the columns in the keyframe data for just the brick joints and create
// the corresponding keyframe matrix. Note: Only the first keyframe is used to
// set the brick's initial position. All other brick keyframe data is unused.
std::vector<std::string> brick_joint_ordering = {"brick_translate_y_joint",
"brick_translate_z_joint",
"brick_revolute_x_joint"};
std::map<std::string, int> brick_joint_name_to_col_index_map;
MatrixX<double> brick_joint_keyframes =
MakeKeyframes(all_keyframes, brick_joint_ordering, headers);
// Set the brick's initial pose (expressed in the gripper frame G).
if (brick_initial_pose != EigenPtr<Vector3<double>>(nullptr)) {
(*brick_initial_pose)(0) = brick_joint_keyframes(0, 0); // y-translate
(*brick_initial_pose)(1) = brick_joint_keyframes(0, 1); // z-translate
(*brick_initial_pose)(2) = brick_joint_keyframes(0, 2); // x-revolute
}
finger_joint_keyframes.transposeInPlace();
// Create the finger joint name to row index map.
std::map<std::string, int> finger_joint_name_to_row_index_map;
for (size_t i = 0; i < finger_joint_ordering.size(); i++) {
finger_joint_name_to_row_index_map[finger_joint_ordering[i]] = i;
}
return std::make_pair(finger_joint_keyframes,
finger_joint_name_to_row_index_map);
}
MatrixX<double> ReorderKeyframesForPlant(
const MultibodyPlant<double>& plant, const MatrixX<double> keyframes,
std::map<std::string, int>* finger_joint_name_to_row_index_map) {
DRAKE_DEMAND(finger_joint_name_to_row_index_map != nullptr);
if (static_cast<int>(finger_joint_name_to_row_index_map->size()) !=
keyframes.rows()) {
throw std::runtime_error(
"The number of keyframe rows must match the size of "
"finger_joint_name_to_row_index_map.");
}
if (keyframes.rows() != kNumJoints) {
throw std::runtime_error(
"The number of keyframe rows must match the number of planar-gripper "
"joints");
}
if (plant.num_positions() != kNumJoints) {
throw std::runtime_error(
"The number of plant positions must exactly match the number of "
"planar-gripper joints.");
}
std::map<std::string, int> original_map = *finger_joint_name_to_row_index_map;
MatrixX<double> reordered_keyframes(keyframes);
for (auto iter = original_map.begin(); iter != original_map.end(); ++iter) {
auto joint_vel_start_index =
plant.GetJointByName(iter->first).velocity_start();
reordered_keyframes.row(joint_vel_start_index) =
keyframes.row(iter->second);
(*finger_joint_name_to_row_index_map)[iter->first] = joint_vel_start_index;
}
return reordered_keyframes;
}
const RigidTransformd X_WGripper() {
return math::RigidTransformd::Identity();
}
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/gripper_brick_planning_constraint_helper.h | #pragma once
#include "drake/examples/planar_gripper/gripper_brick.h"
#include "drake/solvers/mathematical_program.h"
/// @file
/// This file contains the utility function to add constraint in gripper/brick
/// motion planning.
namespace drake {
namespace examples {
namespace planar_gripper {
/**
* Adds the friction cone as linear constraints on the contact force f_Cb_B (the
* contact force applied on the brick contact point Cb, expressed in the brick
* frame B). Notice that since the example is planar, we can write this friction
* cone as linear constraints, as opposed to the general nonlinear constraint in
* StaticFrictionConeConstraint.
* @param gripper_brick The planar gripper system manipulating a brick.
* @param finger The finger in contact with the brick face.
* @param brick_face The contact facet on the brick.
* @param f_Cb_B The contact force applied on the brick contact point Cb,
* expressed in the brick frame B.
* @param friction_cone_shrink_factor The factor to shrink the friction
* coefficient mu in the planning.
* @param prog The program to which the constraint is added.
*/
template <typename T>
void AddFrictionConeConstraint(
const GripperBrickHelper<T>& gripper_brick, Finger finger,
BrickFace brick_face,
const Eigen::Ref<const Vector2<symbolic::Variable>>& f_Cb_B,
double friction_cone_shrink_factor, solvers::MathematicalProgram* prog);
/**
* Add the kinematic constraint that the finger tip (the sphere collision
* geometry in the tip of the finger) is in contact with a shrunk region on the
* brick face.
* @param gripper_brick_system The gripper brick system on which the constraint
* is imposed.
* @param finger The finger in contact.
* @param brick_face The face of the brick in contact.
* @param prog The program to which the constraint is added.
* @param q_vars The variable for the configuration.
* @param plant_context The context containing the value of q_vars.
* @param face_shrink_factor A factor to determine the shrunk region on each
* face. If face_shrink_factor = 1, then the region includes the whole face,
* 0 < face_shrink_factor < 1 corresponds to the scaled region of the face,
* if face_shrink_factor = 0, then the region shrinks to the singleton centroid.
* @param depth The penetration depth between the finger tip sphere and the
* brick.
*/
void AddFingerTipInContactWithBrickFaceConstraint(
const GripperBrickHelper<double>& gripper_brick_system, Finger finger,
BrickFace brick_face, solvers::MathematicalProgram* prog,
const Eigen::Ref<const VectorX<symbolic::Variable>>& q_vars,
systems::Context<double>* plant_context, double face_shrink_factor,
double depth);
Eigen::Vector3d ComputeFingerTipInBrickFrame(
const GripperBrickHelper<double>& gripper_brick, const Finger finger,
const systems::Context<double>& plant_context,
const Eigen::Ref<const Eigen::VectorXd>& q);
Vector3<AutoDiffXd> ComputeFingerTipInBrickFrame(
const GripperBrickHelper<double>& gripper_brick, const Finger finger,
const systems::Context<double>& plant_context,
const Eigen::Ref<const AutoDiffVecXd>& q);
/**
* Impose a kinematic constraint which prohibits the fingertip sphere from
* sliding on the brick's face. That is, the fingertip sphere is only allowed to
* roll on the brick's surface. Note that zero rolling (i.e., sticking) is also
* allowed.
* @param gripper_brick Contains the gripper brick diagram.
* @param finger The finger that should not slide.
* @param face The brick face that the finger sticks to (or rolls on).
* @param rolling_angle_bound The non-negative bound on the rolling angle (in
* radians).
* @param prog The optimization program to which the constraint is added.
* @param from_context The context that contains the posture of the plant,
* before rolling occurs.
* @param to_context The context that contains the posture of the plant, after
* rolling occurs.
* @param q_from The variable representing the "from" posture.
* @param q_to The variable representing the "to" posture.
*/
void AddFingerNoSlidingConstraint(
const GripperBrickHelper<double>& gripper_brick, Finger finger,
BrickFace face, double rolling_angle_bound,
solvers::MathematicalProgram* prog, systems::Context<double>* from_context,
systems::Context<double>* to_context,
const Eigen::Ref<const VectorX<symbolic::Variable>>& q_from,
const Eigen::Ref<const VectorX<symbolic::Variable>>& q_to,
double face_shrink_factor, double depth);
/**
* Impose the kinematic constraint that the finger can only roll (or stick)
* starting from a given fixed posture. The angle of the finger is defined as
* the pitch angle of the finger link 2 (about +x axis). The change of finger
* angles from the starting posture to the ending posture is limited to be
* within rolling_angle_upper and rolling_angle_lower. If you want to impose
* sticking contact (no rolling), then set rolling_angle_lower =
* rolling_angle_upper = 0.
* @param gripper_brick Contains the gripper brick diagram.
* @param finger The finger that should not slide.
* @param face The brick face that the finger sticks to (or rolls on).
* @param rolling_angle_lower The lower bound on the rolling angle.
* @param rolling_angle_upper The upper bound on the rolling angle.
* @param prog The optimization program to which the constraint is added.
* @param from_context The context containing posture, from which the finger
* should stick to (or roll).
* @param to_context The context that contains the value of the posture after
* rolling (sticking).
* @param q_to The variable representing the "to" posture.
* @param face_shrink_factor A factor < 1, indicates the region on the face that
* the finger can roll within.
*/
void AddFingerNoSlidingFromFixedPostureConstraint(
const GripperBrickHelper<double>& gripper_brick, Finger finger,
BrickFace face, double rolling_angle_lower, double rolling_angle_upper,
solvers::MathematicalProgram* prog,
const systems::Context<double>& from_fixed_context,
systems::Context<double>* to_context,
const Eigen::Ref<const VectorX<symbolic::Variable>>& q_to,
double face_shrink_factor, double depth);
namespace internal {
/**
* Impose the constraint that the finger rolls along the line (coinciding with
* the face).
* The formulation of the constraint is
*
* p_translation_to - p_translation_from - radius * (θ_to - θ_from) = 0
* where θ_to and θ_from are the pitch angle of the finger tip in the "from"
* and "to" postures respectively.
* The variables are (q_from, q_to).
* This constraint only has 1 row. It only constrains that in the tangential
* direction along the brick surface, the translation of the finger tip matches
* with the rolling angle. This constraint does NOT constrain that in the
* normal direction, the finger remains in contact. The user should impose
* the constraint in the normal direction separately.
*/
class FingerNoSlidingConstraint : public solvers::Constraint {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(FingerNoSlidingConstraint)
FingerNoSlidingConstraint(const GripperBrickHelper<double>* gripper_brick,
Finger finger, BrickFace face,
systems::Context<double>* from_context,
systems::Context<double>* to_context);
~FingerNoSlidingConstraint() override {}
private:
template <typename T>
void DoEvalGeneric(const Eigen::Ref<const VectorX<T>>& x,
VectorX<T>* y) const;
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override;
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override;
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&,
VectorX<symbolic::Expression>*) const override {
throw std::runtime_error(
"FingerNoSlidingConstraint::Eval doesn't support symbolic variables.");
}
const GripperBrickHelper<double>* gripper_brick_;
Finger finger_;
BrickFace face_;
systems::Context<double>* from_context_;
systems::Context<double>* to_context_;
};
/**
* Same as FingerNoSlidingConstraint, except the "from posture" is fixed, so the
* decision variables are only q_to.
*/
class FingerNoSlidingFromFixedPostureConstraint : public solvers::Constraint {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(FingerNoSlidingFromFixedPostureConstraint)
FingerNoSlidingFromFixedPostureConstraint(
const GripperBrickHelper<double>* gripper_brick, Finger finger,
BrickFace face, const systems::Context<double>* from_context,
systems::Context<double>* to_context);
~FingerNoSlidingFromFixedPostureConstraint() override {}
private:
template <typename T>
void DoEvalGeneric(const Eigen::Ref<const VectorX<T>>& x,
VectorX<T>* y) const;
void DoEval(const Eigen::Ref<const Eigen::VectorXd>& x,
Eigen::VectorXd* y) const override;
void DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const override;
void DoEval(const Eigen::Ref<const VectorX<symbolic::Variable>>&,
VectorX<symbolic::Expression>*) const override {
throw std::runtime_error(
"FingerNoSlidingConstraint::Eval doesn't support symbolic variables.");
}
private:
const GripperBrickHelper<double>* gripper_brick_;
Finger finger_;
BrickFace face_;
const systems::Context<double>* from_context_;
systems::Context<double>* to_context_;
};
} // namespace internal
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/gripper_brick_planning_constraint_helper.cc | #include "drake/examples/planar_gripper/gripper_brick_planning_constraint_helper.h"
#include <limits>
#include <memory>
#include "drake/math/autodiff_gradient.h"
#include "drake/multibody/inverse_kinematics/kinematic_evaluator_utilities.h"
#include "drake/multibody/inverse_kinematics/position_constraint.h"
namespace drake {
namespace examples {
namespace planar_gripper {
template <typename T>
void AddFrictionConeConstraint(
const GripperBrickHelper<T>& gripper_brick_system, const Finger finger,
const BrickFace brick_face,
const Eigen::Ref<const Vector2<symbolic::Variable>>& f_Cb_B,
double friction_cone_shrink_factor, solvers::MathematicalProgram* prog) {
const multibody::CoulombFriction<double> combined_friction =
gripper_brick_system.GetFingerTipBrickCoulombFriction(finger);
const double mu =
combined_friction.static_friction() * friction_cone_shrink_factor;
switch (brick_face) {
case BrickFace::kNegY: {
prog->AddLinearConstraint(f_Cb_B(0) >= 0);
prog->AddLinearConstraint(f_Cb_B(1) <= mu * f_Cb_B(0));
prog->AddLinearConstraint(f_Cb_B(1) >= -mu * f_Cb_B(0));
break;
}
case BrickFace::kNegZ: {
prog->AddLinearConstraint(f_Cb_B(1) >= 0);
prog->AddLinearConstraint(f_Cb_B(0) <= mu * f_Cb_B(1));
prog->AddLinearConstraint(f_Cb_B(0) >= -mu * f_Cb_B(1));
break;
}
case BrickFace::kPosY: {
prog->AddLinearConstraint(f_Cb_B(0) <= 0);
prog->AddLinearConstraint(f_Cb_B(1) <= -mu * f_Cb_B(0));
prog->AddLinearConstraint(f_Cb_B(1) >= mu * f_Cb_B(0));
break;
}
case BrickFace::kPosZ: {
prog->AddLinearConstraint(f_Cb_B(1) <= 0);
prog->AddLinearConstraint(f_Cb_B(0) <= -mu * f_Cb_B(1));
prog->AddLinearConstraint(f_Cb_B(0) >= mu * f_Cb_B(1));
break;
}
}
}
void AddFingerTipInContactWithBrickFaceConstraint(
const GripperBrickHelper<double>& gripper_brick_system, Finger finger,
BrickFace brick_face, solvers::MathematicalProgram* prog,
const Eigen::Ref<const VectorX<symbolic::Variable>>& q_vars,
systems::Context<double>* plant_context, double face_shrink_factor,
double depth) {
const multibody::Frame<double>& finger_link2 =
gripper_brick_system.finger_link2_frame(finger);
// position of finger tip in the finger link 2 farme (F2).
const Eigen::Vector3d p_L2Fingertip = gripper_brick_system.p_L2Fingertip();
const multibody::Frame<double>& brick = gripper_brick_system.brick_frame();
const Eigen::Vector3d brick_size = gripper_brick_system.brick_size();
Eigen::Vector3d p_BFingertip_lower = -brick_size * face_shrink_factor / 2;
Eigen::Vector3d p_BFingertip_upper = brick_size * face_shrink_factor / 2;
const double finger_tip_radius = gripper_brick_system.finger_tip_radius();
switch (brick_face) {
case BrickFace::kPosZ: {
p_BFingertip_lower(2) = brick_size(2) / 2 + finger_tip_radius - depth;
p_BFingertip_upper(2) = brick_size(2) / 2 + finger_tip_radius - depth;
break;
}
case BrickFace::kNegZ: {
p_BFingertip_lower(2) = -brick_size(2) / 2 - finger_tip_radius + depth;
p_BFingertip_upper(2) = -brick_size(2) / 2 - finger_tip_radius + depth;
break;
}
case BrickFace::kPosY: {
p_BFingertip_lower(1) = brick_size(1) / 2 + finger_tip_radius - depth;
p_BFingertip_upper(1) = brick_size(1) / 2 + finger_tip_radius - depth;
break;
}
case BrickFace::kNegY: {
p_BFingertip_lower(1) = -brick_size(1) / 2 - finger_tip_radius + depth;
p_BFingertip_upper(1) = -brick_size(1) / 2 - finger_tip_radius + depth;
break;
}
}
auto constraint = prog->AddConstraint(
std::make_shared<multibody::PositionConstraint>(
&(gripper_brick_system.plant()), brick, p_BFingertip_lower,
p_BFingertip_upper, finger_link2, p_L2Fingertip, plant_context),
q_vars);
constraint.evaluator()->set_description(to_string(finger) +
"_tip_in_contact");
}
Eigen::Vector3d ComputeFingerTipInBrickFrame(
const GripperBrickHelper<double>& gripper_brick, const Finger finger,
const systems::Context<double>& plant_context,
const Eigen::Ref<const Eigen::VectorXd>&) {
Eigen::Vector3d p_BFingertip;
gripper_brick.plant().CalcPointsPositions(
plant_context, gripper_brick.finger_link2_frame(finger),
gripper_brick.p_L2Fingertip(), gripper_brick.brick_frame(),
&p_BFingertip);
return p_BFingertip;
}
Vector3<AutoDiffXd> ComputeFingerTipInBrickFrame(
const GripperBrickHelper<double>& gripper_brick, const Finger finger,
const systems::Context<double>& plant_context,
const Eigen::Ref<const AutoDiffVecXd>& q) {
Eigen::Vector3d p_BFingertip;
gripper_brick.plant().CalcPointsPositions(
plant_context, gripper_brick.finger_link2_frame(finger),
gripper_brick.p_L2Fingertip(), gripper_brick.brick_frame(),
&p_BFingertip);
Eigen::Matrix3Xd Jv_BF2_B(3, gripper_brick.plant().num_positions());
gripper_brick.plant().CalcJacobianTranslationalVelocity(
plant_context, multibody::JacobianWrtVariable::kQDot,
gripper_brick.finger_link2_frame(finger), gripper_brick.p_L2Fingertip(),
gripper_brick.brick_frame(), gripper_brick.brick_frame(), &Jv_BF2_B);
return math::InitializeAutoDiff(
p_BFingertip, Jv_BF2_B * math::ExtractGradient(q));
}
namespace internal {
FingerNoSlidingConstraint::FingerNoSlidingConstraint(
const GripperBrickHelper<double>* gripper_brick, Finger finger,
BrickFace face, systems::Context<double>* from_context,
systems::Context<double>* to_context)
: solvers::Constraint(1 /* number of constraint */,
2 * gripper_brick->plant()
.num_positions(), // Number of variables,
// the variables are q_to
// and q_from.
Vector1d(0), Vector1d(0),
"finger_no_sliding_constraint"),
gripper_brick_(gripper_brick),
finger_(finger),
face_(face),
from_context_(from_context),
to_context_(to_context) {}
template <typename T>
void FingerNoSlidingConstraint::DoEvalGeneric(
const Eigen::Ref<const VectorX<T>>& x, VectorX<T>* y) const {
y->resize(1);
const int nq = gripper_brick_->plant().num_positions();
const auto& q_from = x.head(nq);
const auto& q_to = x.tail(nq);
multibody::internal::UpdateContextConfiguration(
from_context_, gripper_brick_->plant(), q_from);
multibody::internal::UpdateContextConfiguration(
to_context_, gripper_brick_->plant(), q_to);
const Vector3<T> p_BTip_from = ComputeFingerTipInBrickFrame(
*gripper_brick_, finger_, *from_context_, x.head(nq));
const Vector3<T> p_BTip_to = ComputeFingerTipInBrickFrame(
*gripper_brick_, finger_, *to_context_, x.tail(nq));
const T theta_from = gripper_brick_->CalcFingerLink2Orientation(
finger_, T(q_from(gripper_brick_->finger_base_position_index(finger_))),
T(q_from(gripper_brick_->finger_mid_position_index(finger_))));
const T theta_to = gripper_brick_->CalcFingerLink2Orientation(
finger_, T(q_to(gripper_brick_->finger_base_position_index(finger_))),
T(q_to(gripper_brick_->finger_mid_position_index(finger_))));
switch (face_) {
case BrickFace::kPosY:
case BrickFace::kNegY: {
// rolling with positive delta_theta about x axis causes positive
// translation along the z axis.
(*y)(0) = p_BTip_to(2) - p_BTip_from(2) -
gripper_brick_->finger_tip_radius() * (theta_to - theta_from);
break;
}
case BrickFace::kPosZ:
case BrickFace::kNegZ: {
// rolling with positive delta_theta about x axis causes negative
// translation along the y axis.
(*y)(0) = -(p_BTip_to(1) - p_BTip_from(1)) -
gripper_brick_->finger_tip_radius() * (theta_to - theta_from);
break;
}
}
}
void FingerNoSlidingConstraint::DoEval(
const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const {
DoEvalGeneric<double>(x, y);
}
void FingerNoSlidingConstraint::DoEval(const Eigen::Ref<const AutoDiffVecXd>& x,
AutoDiffVecXd* y) const {
DoEvalGeneric<AutoDiffXd>(x, y);
}
} // namespace internal
void AddFingerNoSlidingConstraint(
const GripperBrickHelper<double>& gripper_brick, Finger finger,
BrickFace face, double rolling_angle_bound,
solvers::MathematicalProgram* prog, systems::Context<double>* from_context,
systems::Context<double>* to_context,
const Eigen::Ref<const VectorX<symbolic::Variable>>& q_from,
const Eigen::Ref<const VectorX<symbolic::Variable>>& q_to,
double face_shrink_factor, double depth) {
AddFingerTipInContactWithBrickFaceConstraint(gripper_brick, finger, face,
prog, q_to, to_context,
face_shrink_factor, depth);
auto constraint = prog->AddConstraint(
std::make_shared<internal::FingerNoSlidingConstraint>(
&gripper_brick, finger, face, from_context, to_context),
{q_from, q_to});
constraint.evaluator()->set_description(to_string(finger) + "no_sliding");
const symbolic::Expression theta_from =
gripper_brick.CalcFingerLink2Orientation<symbolic::Expression>(
finger, q_from(gripper_brick.finger_base_position_index(finger)),
q_from(gripper_brick.finger_mid_position_index(finger)));
const symbolic::Expression theta_to =
gripper_brick.CalcFingerLink2Orientation<symbolic::Expression>(
finger, q_to(gripper_brick.finger_base_position_index(finger)),
q_to(gripper_brick.finger_mid_position_index(finger)));
prog->AddLinearConstraint(theta_from - theta_to, -rolling_angle_bound,
rolling_angle_bound);
}
namespace internal {
FingerNoSlidingFromFixedPostureConstraint::
FingerNoSlidingFromFixedPostureConstraint(
const GripperBrickHelper<double>* gripper_brick, Finger finger,
BrickFace face, const systems::Context<double>* from_context,
systems::Context<double>* to_context)
: solvers::Constraint(1, gripper_brick->plant().num_positions(),
Vector1d(0), Vector1d(0),
"finger_no_sliding_from_fixed_posture"),
gripper_brick_{gripper_brick},
finger_{finger},
face_{face},
from_context_{from_context},
to_context_{to_context} {}
template <typename T>
void FingerNoSlidingFromFixedPostureConstraint::DoEvalGeneric(
const Eigen::Ref<const VectorX<T>>& x, VectorX<T>* y) const {
y->resize(1);
multibody::internal::UpdateContextConfiguration(to_context_,
gripper_brick_->plant(), x);
Eigen::VectorXd q_from = gripper_brick_->plant().GetPositions(*from_context_);
const auto& q_to = x;
const Vector3<double> p_BTip_from = ComputeFingerTipInBrickFrame(
*gripper_brick_, finger_, *from_context_, q_from);
const Vector3<T> p_BTip_to =
ComputeFingerTipInBrickFrame(*gripper_brick_, finger_, *to_context_, x);
const T theta_from = gripper_brick_->CalcFingerLink2Orientation(
finger_, T(q_from(gripper_brick_->finger_base_position_index(finger_))),
T(q_from(gripper_brick_->finger_mid_position_index(finger_))));
const T theta_to = gripper_brick_->CalcFingerLink2Orientation(
finger_, T(q_to(gripper_brick_->finger_base_position_index(finger_))),
T(q_to(gripper_brick_->finger_mid_position_index(finger_))));
switch (face_) {
case BrickFace::kPosY:
case BrickFace::kNegY: {
// rolling with positive delta_theta about x axis causes positive
// translation along the z axis.
(*y)(0) = p_BTip_to(2) - p_BTip_from(2) -
gripper_brick_->finger_tip_radius() * (theta_to - theta_from);
break;
}
case BrickFace::kPosZ:
case BrickFace::kNegZ: {
// rolling with positive delta_theta about x axis causes negative
// translation along the y axis.
(*y)(0) = -(p_BTip_to(1) - p_BTip_from(1)) -
gripper_brick_->finger_tip_radius() * (theta_to - theta_from);
break;
}
}
}
void FingerNoSlidingFromFixedPostureConstraint::DoEval(
const Eigen::Ref<const Eigen::VectorXd>& x, Eigen::VectorXd* y) const {
DoEvalGeneric<double>(x, y);
}
void FingerNoSlidingFromFixedPostureConstraint::DoEval(
const Eigen::Ref<const AutoDiffVecXd>& x, AutoDiffVecXd* y) const {
DoEvalGeneric<AutoDiffXd>(x, y);
}
} // namespace internal
void AddFingerNoSlidingFromFixedPostureConstraint(
const GripperBrickHelper<double>& gripper_brick, Finger finger,
BrickFace face, double rolling_angle_lower, double rolling_angle_upper,
solvers::MathematicalProgram* prog,
const systems::Context<double>& from_context,
systems::Context<double>* to_context,
const Eigen::Ref<const VectorX<symbolic::Variable>>& q_to,
double face_shrink_factor, double depth) {
AddFingerTipInContactWithBrickFaceConstraint(gripper_brick, finger, face,
prog, q_to, to_context,
face_shrink_factor, depth);
const Eigen::VectorXd& q_from =
gripper_brick.plant().GetPositions(from_context);
prog->AddConstraint(
std::make_shared<internal::FingerNoSlidingFromFixedPostureConstraint>(
&gripper_brick, finger, face, &from_context, to_context),
{q_to});
const double theta_from = gripper_brick.CalcFingerLink2Orientation<double>(
finger, q_from(gripper_brick.finger_base_position_index(finger)),
q_from(gripper_brick.finger_mid_position_index(finger)));
const symbolic::Expression theta_to =
gripper_brick.CalcFingerLink2Orientation<symbolic::Expression>(
finger, q_to(gripper_brick.finger_base_position_index(finger)),
q_to(gripper_brick.finger_mid_position_index(finger)));
prog->AddLinearConstraint(theta_from - theta_to, rolling_angle_lower,
rolling_angle_upper);
}
template void AddFrictionConeConstraint<double>(
const GripperBrickHelper<double>&, Finger, BrickFace,
const Eigen::Ref<const Vector2<symbolic::Variable>>&, double,
solvers::MathematicalProgram*);
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/planar_gripper_lcm.h | #pragma once
/// @file
/// This file contains classes dealing with sending/receiving
/// LCM messages related to the planar gripper.
/// TODO(rcory) Create doxygen system diagrams for the classes below.
///
/// All (q, v) state vectors in this file are of the format
/// (joint_positions, joint_velocities).
#include <memory>
#include <vector>
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/lcmt_planar_gripper_command.hpp"
#include "drake/lcmt_planar_gripper_status.hpp"
#include "drake/systems/framework/event_status.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace examples {
namespace planar_gripper {
using systems::OutputPort;
using systems::InputPort;
// By default the planar gripper has 3 fingers.
constexpr int kGripperDefaultNumFingers = 3;
// This is rather arbitrary, for now.
// TODO(rcory) Refine this value once the planner comes online.
constexpr double kGripperLcmStatusPeriod = 0.010;
/// Handles lcmt_planar_gripper_command messages from a LcmSubscriberSystem.
///
/// This system has one abstract valued input port which expects a
/// Value object templated on type `lcmt_planar_gripper_command`.
///
/// This system has two output ports. The first reports the commanded position
/// and velocity for all joints, and the second reports the commanded joint
/// torques.
///
/// @system
/// name: GripperCommandDecoder
/// input_ports:
/// - lcmt_planar_gripper_command
/// output_ports:
/// - state
/// - torques
/// @endsystem
class GripperCommandDecoder : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(GripperCommandDecoder)
/// Constructor.
/// @param num_fingers The total number of fingers used on the planar-gripper.
explicit GripperCommandDecoder(int num_fingers = kGripperDefaultNumFingers);
/// Sets the initial position of the controlled gripper prior to any
/// commands being received. @p x contains the starting position.
/// This position will be the commanded position (with zero
/// velocity) until a position message is received. If this
/// function is not called, the starting position will be the zero
/// configuration.
void set_initial_position(
systems::Context<double>* context,
const Eigen::Ref<const VectorX<double>> x) const;
const systems::OutputPort<double>& get_state_output_port() const {
DRAKE_DEMAND(state_output_port_ != nullptr);
return *state_output_port_;
}
const systems::OutputPort<double>& get_torques_output_port() const {
DRAKE_DEMAND(torques_output_port_ != nullptr);
return *torques_output_port_;
}
private:
void OutputStateCommand(const systems::Context<double>& context,
systems::BasicVector<double>* output) const;
void OutputTorqueCommand(const systems::Context<double>& context,
systems::BasicVector<double>* output) const;
/// Event handler of the periodic discrete state update.
systems::EventStatus UpdateDiscreteState(
const systems::Context<double>& context,
systems::DiscreteValues<double>* discrete_state) const;
const int num_fingers_;
const int num_joints_;
const OutputPort<double>* state_output_port_{};
const OutputPort<double>* torques_output_port_{};
};
/// Creates and outputs lcmt_planar_gripper_command messages.
///
/// This system has two vector-valued input ports containing the
/// desired position and velocity in the first port, and commanded torque on the
/// second port.
///
/// This system has one abstract valued output port that contains a
/// Value object templated on type `lcmt_planar_gripper_command`. Note
/// that this system does not actually send this message on an LCM
/// channel. To send the message, the output of this system should be
/// connected to an input port of a systems::lcm::LcmPublisherSystem
/// that accepts a Value object templated on type
/// `lcmt_planar_gripper_command`.
///
/// @system
/// name: GripperCommandEncoder
/// input_ports:
/// - state
/// - torque
/// output_ports:
/// - lcmt_gripper_command
/// @endsystem
class GripperCommandEncoder : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(GripperCommandEncoder)
/// Constructor.
/// @param num_joints The total number of fingers used on the planar-gripper.
explicit GripperCommandEncoder(int num_fingers = kGripperDefaultNumFingers);
const systems::InputPort<double>& get_state_input_port() const {
DRAKE_DEMAND(state_input_port_ != nullptr);
return *state_input_port_;
}
const systems::InputPort<double>& get_torques_input_port() const {
DRAKE_DEMAND(torques_input_port_ != nullptr);
return *torques_input_port_;
}
private:
void OutputCommand(const systems::Context<double>& context,
lcmt_planar_gripper_command* output) const;
const int num_fingers_;
const int num_joints_;
const InputPort<double>* state_input_port_{};
const InputPort<double>* torques_input_port_{};
};
/// Handles lcmt_planar_gripper_status messages from a LcmSubscriberSystem.
///
/// This system has one abstract valued input port which expects a
/// Value object templated on type `lcmt_planar_gripper_status`.
///
/// This system has two vector valued output ports which report
/// measured position and velocity (state) as well as fingertip forces (fy, fz).
///
/// All ports will continue to output their initial state (typically
/// zero) until a message is received.
///
/// @system
/// name: GripperStatusDecoder
/// input_ports:
/// - lcmt_planar_gripper_status
/// output_ports:
/// - state
/// - fingertip_force
/// @endsystem
class GripperStatusDecoder : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(GripperStatusDecoder)
/// Constructor.
/// @param num_fingers The total number of fingers used on the planar-gripper.
explicit GripperStatusDecoder(int num_fingers = kGripperDefaultNumFingers);
const systems::OutputPort<double>& get_state_output_port() const {
DRAKE_DEMAND(state_output_port_ != nullptr);
return *state_output_port_;
}
const systems::OutputPort<double>& get_force_output_port() const {
DRAKE_DEMAND(force_output_port_ != nullptr);
return *force_output_port_;
}
private:
void OutputStateStatus(const systems::Context<double>& context,
systems::BasicVector<double>* output) const;
void OutputForceStatus(const systems::Context<double>& context,
systems::BasicVector<double>* output) const;
/// Event handler of the periodic discrete state update.
systems::EventStatus UpdateDiscreteState(
const systems::Context<double>& context,
systems::DiscreteValues<double>* discrete_state) const;
const int num_fingers_;
const int num_joints_;
const int num_tip_forces_;
const OutputPort<double>* state_output_port_{};
const OutputPort<double>* force_output_port_{};
};
/// Creates and outputs lcmt_planar_gripper_status messages.
///
/// This system has two vector-valued input ports containing the
/// current position and velocity (state) as well as fingertip forces (fy, fz).
///
/// This system has one abstract valued output port that contains a
/// Value object templated on type `lcmt_planar_gripper_status`. Note that this
/// system does not actually send this message on an LCM channel. To send the
/// message, the output of this system should be connected to an input port of
/// a systems::lcm::LcmPublisherSystem that accepts a
/// Value object templated on type `lcmt_planar_gripper_status`.
///
/// @system
/// name: GripperStatusEncoder
/// input_ports:
/// - state
/// - fingertip_force
/// output_ports:
/// - lcmt_gripper_status
/// @endsystem
class GripperStatusEncoder : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(GripperStatusEncoder)
/// Constructor.
/// @param num_joints The total number of fingers used on the planar-gripper.
explicit GripperStatusEncoder(int num_fingers = kGripperDefaultNumFingers);
const systems::InputPort<double>& get_state_input_port() const {
DRAKE_DEMAND(state_input_port_ != nullptr);
return *state_input_port_;
}
const systems::InputPort<double>& get_force_input_port() const {
DRAKE_DEMAND(force_input_port_ != nullptr);
return *force_input_port_;
}
private:
// This is the calculator method for the output port.
void OutputStatus(const systems::Context<double>& context,
lcmt_planar_gripper_status* output) const;
const int num_fingers_;
const int num_joints_;
const int num_tip_forces_;
const InputPort<double>* state_input_port_{};
const InputPort<double>* force_input_port_{};
};
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/postures.txt | finger1_BaseJoint finger3_BaseJoint finger2_BaseJoint brick_translate_y_joint finger1_MidJoint finger3_MidJoint finger2_MidJoint brick_translate_z_joint brick_revolute_x_joint
-0.277611 0.947974 0.281503 0.00731802 -0.0613293 -1.21373 0.201025 -0.0197339 -0.454859
-0.269673 0.910182 0.405141 0.0309428 -0.0593174 -1.40873 0.287732 -0.0284596 -0.533185
-0.133853 0.941109 0.4007 0.030101 0.0186572 -1.46184 0.289061 -0.0298918 -0.505579
0.00196145 0.971331 0.396288 0.0292945 0.0966332 -1.5149 0.290285 -0.0313847 -0.477094
0.132659 1.03136 0.357395 0.0222541 0.169267 -1.54556 0.273119 -0.0313523 -0.421529
0.185826 1.11105 0.265292 0.00655931 0.194396 -1.5272 0.22557 -0.0283626 -0.311532
0.190299 1.15236 0.172821 -0.00714246 0.191832 -1.50221 0.174626 -0.0247317 -0.178606
0.19477 1.15522 0.0880207 -0.0170786 0.189278 -1.48771 0.125161 -0.0210321 -0.0325206
0.116951 1.11109 0.00472986 -0.0236464 0.140194 -1.46735 0.0751527 -0.0166597 0.128985
0.116951 1.11109 0.00472986 -0.0236464 0.140194 -1.46735 0.0751527 -0.0166597 0.128985
-0.0253097 1.1223 -0.0670218 -0.017091 0.27584 -1.71845 0.204993 -0.0261754 0.312237
-0.166354 0.865046 -0.142261 -0.00568356 0.356888 -1.7954 0.271537 -0.0346336 0.625051
-0.240174 0.587686 -0.204645 0.00157876 0.417172 -1.6061 0.285589 -0.0336073 0.829699
-0.2854 0.348528 -0.261236 0.0070414 0.472251 -1.3306 0.287115 -0.0291123 0.983925
-0.314024 0.13511 -0.310518 0.0111027 0.524778 -1.01456 0.284874 -0.0234165 1.09853
-0.333547 -0.0650533 -0.350138 0.0138037 0.57474 -0.677123 0.282752 -0.0180523 1.17622
-0.333547 -0.0650533 -0.350138 0.0138037 0.57474 -0.677123 0.282752 -0.0180523 1.17622
-0.489193 -0.0308421 -0.398642 0.00476261 0.518795 -0.719448 0.307468 -0.0297853 1.39221
-0.628134 0.0461484 -0.389456 -0.0092609 0.467926 -0.726971 0.36116 -0.0368821 1.58054
-0.766611 0.15684 -0.312372 -0.0284347 0.415596 -0.701647 0.449222 -0.0414238 1.75159
-0.743176 0.120924 -0.140453 -0.0237236 0.443066 -0.692901 0.53058 -0.0401788 1.71713
-0.669704 0.0494368 -0.0189003 -0.0124995 0.491331 -0.693819 0.569463 -0.0370902 1.6157
-0.595167 -0.00887763 0.102651 -0.00309783 0.538204 -0.686012 0.608345 -0.0331663 1.50639
-0.47047 -0.0652458 0.0663562 0.00764218 0.589488 -0.665343 0.547076 -0.0254742 1.33271
-0.47047 -0.0652458 0.0663562 0.00764218 0.589488 -0.665343 0.547076 -0.0254742 1.33271
-0.515986 -0.115995 -0.0186288 0.00567815 0.598861 -0.867366 0.640571 -0.0255934 1.41113
-0.545602 -0.0320728 -0.109774 0.00426735 0.59672 -1.00281 0.739614 -0.0247586 1.48568
-0.570529 0.0518471 -0.205571 0.00299411 0.596439 -1.13826 0.83514 -0.0230506 1.56072
-0.588776 0.148169 -0.305076 0.00204971 0.597088 -1.26628 0.927501 -0.0204856 1.6347
-0.599897 0.256905 -0.407805 0.00154208 0.598957 -1.38684 1.01677 -0.0170986 1.707
-0.605025 0.365649 -0.514435 0.00145489 0.603402 -1.5074 1.10218 -0.0128832 1.77885
-0.57084 0.64812 -0.535754 0.00400668 0.579418 -1.39006 1.16196 -0.0119789 1.76396
-0.57084 0.64812 -0.535754 0.00400668 0.579418 -1.39006 1.16196 -0.0119789 1.76396
-0.594883 0.60271 -0.57248 -0.000818635 0.532276 -1.33086 1.0868 -0.0110231 1.87635
-0.604265 0.549921 -0.591056 -0.00475384 0.487929 -1.25025 1.00044 -0.00939497 1.96936
-0.603516 0.492773 -0.595965 -0.00783172 0.446332 -1.15783 0.910094 -0.00747789 2.04672
-0.59592 0.432979 -0.590804 -0.0102075 0.406849 -1.05849 0.818756 -0.00548634 2.11188
-0.583638 0.371516 -0.578022 -0.0120287 0.368871 -0.954745 0.727655 -0.0035396 2.16722
-0.568117 0.308971 -0.559255 -0.0134133 0.331915 -0.847959 0.63731 -0.00170859 2.21431
-0.550369 0.245715 -0.535623 -0.0144532 0.295613 -0.738961 0.547945 -3.91581e-05 2.25418
-0.531127 0.181992 -0.507908 -0.0152193 0.259681 -0.628283 0.459655 0.00143686 2.28755
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/planar_gripper/planar_manipuland_lcm.cc | #include "drake/examples/planar_gripper/planar_manipuland_lcm.h"
namespace drake {
namespace examples {
namespace planar_gripper {
PlanarManipulandStatusDecoder::PlanarManipulandStatusDecoder() {
this->DeclareVectorOutputPort(systems::kUseDefaultName, 6,
&PlanarManipulandStatusDecoder::OutputStatus);
this->DeclareAbstractInputPort("manipuland_state",
Value<lcmt_planar_manipuland_status>{});
this->DeclareDiscreteState(6);
this->DeclarePeriodicDiscreteUpdateEvent(
kPlanarManipulandStatusPeriod, 0.,
&PlanarManipulandStatusDecoder::UpdateDiscreteState);
// Register a forced discrete state update event. It is added for unit test,
// or for potential users who require forced updates.
this->DeclareForcedDiscreteUpdateEvent(
&PlanarManipulandStatusDecoder::UpdateDiscreteState);
}
systems::EventStatus PlanarManipulandStatusDecoder::UpdateDiscreteState(
const systems::Context<double>& context,
systems::DiscreteValues<double>* discrete_state) const {
const AbstractValue* input = this->EvalAbstractInput(context, 0);
DRAKE_ASSERT(input != nullptr);
const auto& status = input->get_value<lcmt_planar_manipuland_status>();
auto state_value = discrete_state->get_mutable_value(0);
state_value(0) = status.position[0];
state_value(1) = status.position[1];
state_value(2) = status.theta;
state_value(3) = status.velocity[0];
state_value(4) = status.velocity[1];
state_value(5) = status.thetadot;
return systems::EventStatus::Succeeded();
}
void PlanarManipulandStatusDecoder::OutputStatus(
const systems::Context<double>& context,
systems::BasicVector<double>* output) const {
Eigen::VectorBlock<VectorX<double>> output_vec = output->get_mutable_value();
output_vec = context.get_discrete_state(0).value();
}
PlanarManipulandStatusEncoder::PlanarManipulandStatusEncoder() {
this->DeclareInputPort(systems::kUseDefaultName, systems::kVectorValued, 6);
this->DeclareAbstractOutputPort(
systems::kUseDefaultName,
&PlanarManipulandStatusEncoder::OutputStatus);
}
void PlanarManipulandStatusEncoder::OutputStatus(
const systems::Context<double>& context,
lcmt_planar_manipuland_status* output) const {
output->utime = context.get_time() * 1e6;
const systems::BasicVector<double>* input = this->EvalVectorInput(context, 0);
output->position[0] = input->GetAtIndex(0);
output->position[1] = input->GetAtIndex(1);
output->theta = input->GetAtIndex(2);
output->velocity[0] = input->GetAtIndex(3);
output->velocity[1] = input->GetAtIndex(4);
output->thetadot = input->GetAtIndex(5);
}
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples/planar_gripper | /home/johnshepherd/drake/examples/planar_gripper/test/gripper_brick_test.cc | #include "drake/examples/planar_gripper/gripper_brick.h"
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
namespace drake {
namespace examples {
namespace planar_gripper {
GTEST_TEST(GripperBrickHelperTest, Test) {
GripperBrickHelper<double> dut;
EXPECT_TRUE(CompareMatrices(dut.p_L2Fingertip(),
Eigen::Vector3d(0, 0, -0.0713), 1E-16));
EXPECT_EQ(dut.finger_tip_radius(), 0.015);
EXPECT_TRUE(
CompareMatrices(dut.brick_size(), Eigen::Vector3d(0.07, 0.1, 0.1)));
auto diagram_context = dut.diagram().CreateDefaultContext();
systems::Context<double>* plant_mutable_context =
&(dut.diagram().GetMutableSubsystemContext(dut.plant(),
diagram_context.get()));
Eigen::VectorXd q(9);
// Set q to arbitrary values.
q << 0.2, 0.4, 0.6, 0.9, 1.2, 1.4, 1.6, 1.8, 2;
dut.plant().SetPositions(plant_mutable_context, q);
// Now evaluate the pose of link 2 for each finger.
for (Finger finger : {Finger::kFinger1, Finger::kFinger2, Finger::kFinger3}) {
const auto X_WLink2 = dut.plant().CalcRelativeTransform(
*plant_mutable_context, dut.plant().world_frame(),
dut.finger_link2_frame(finger));
const Eigen::AngleAxis<double> angle_axis =
X_WLink2.rotation().ToAngleAxis();
const double theta = dut.CalcFingerLink2Orientation(
finger, q(dut.finger_base_position_index(finger)),
q(dut.finger_mid_position_index(finger)));
if (angle_axis.axis().dot(Eigen::Vector3d::UnitX()) > 1 - 1E-14) {
EXPECT_NEAR(std::fmod(theta - angle_axis.angle(), 2 * M_PI), 0, 1E-14);
} else if (angle_axis.axis().dot(-Eigen::Vector3d::UnitX()) > 1 - 1E-14) {
EXPECT_NEAR(std::fmod(theta + angle_axis.angle(), 2 * M_PI), 0, 1E-14);
} else {
throw std::runtime_error("The rotation axis should be x axis.");
}
}
}
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples/planar_gripper | /home/johnshepherd/drake/examples/planar_gripper/test/gripper_brick_planning_constraint_helper_test.cc | #include "drake/examples/planar_gripper/gripper_brick_planning_constraint_helper.h"
#include <gtest/gtest.h>
#include "drake/solvers/solve.h"
namespace drake {
namespace examples {
namespace planar_gripper {
GTEST_TEST(AddFrictionConeConstraintTest, Test) {
GripperBrickHelper<double> gripper_brick;
solvers::MathematicalProgram prog;
auto f_Cb_B = prog.NewContinuousVariables<2>();
const double friction_cone_shrink_factor = 1;
AddFrictionConeConstraint(gripper_brick, Finger::kFinger2, BrickFace::kNegY,
f_Cb_B, friction_cone_shrink_factor, &prog);
auto check_force_in_cone = [&prog, &f_Cb_B](const Eigen::Vector2d& f_Cb_B_val,
bool is_in_cone) {
bool is_satisfied = true;
for (const auto& binding : prog.GetAllConstraints()) {
Eigen::VectorXd bound_var_val(binding.variables().rows());
for (int i = 0; i < bound_var_val.rows(); ++i) {
for (int j = 0; j < 2; ++j) {
if (binding.variables()(i).get_id() == f_Cb_B(j).get_id()) {
bound_var_val(i) = f_Cb_B_val(j);
}
}
}
if (!binding.evaluator()->CheckSatisfied(bound_var_val)) {
is_satisfied = false;
break;
}
}
EXPECT_EQ(is_satisfied, is_in_cone);
};
const multibody::CoulombFriction<double> combined_friction =
gripper_brick.GetFingerTipBrickCoulombFriction(Finger::kFinger2);
const double mu = combined_friction.static_friction();
// Test a force that points in the neg Y direction. This force is not in the
// friction cone.
check_force_in_cone(Eigen::Vector2d(-1, 0), false);
// Test a force that points to the pos Y direction. This force is in the
// friction cone.
check_force_in_cone(Eigen::Vector2d(1, 0), true);
check_force_in_cone(Eigen::Vector2d(1, 2 * mu), false);
check_force_in_cone(Eigen::Vector2d(1, 0.9 * mu), true);
}
GTEST_TEST(AddFingerTipInContactWithBrickFaceTest, Test) {
GripperBrickHelper<double> gripper_brick;
solvers::MathematicalProgram prog;
auto diagram_context = gripper_brick.diagram().CreateDefaultContext();
systems::Context<double>* plant_context =
&(gripper_brick.diagram().GetMutableSubsystemContext(
gripper_brick.plant(), diagram_context.get()));
auto q_vars =
prog.NewContinuousVariables(gripper_brick.plant().num_positions());
const double depth = 2e-3;
AddFingerTipInContactWithBrickFaceConstraint(gripper_brick, Finger::kFinger2,
BrickFace::kNegY, &prog, q_vars,
plant_context, 0.8, depth);
const auto result = solvers::Solve(prog);
EXPECT_TRUE(result.is_success());
const Eigen::VectorXd q_sol = result.GetSolution(q_vars);
gripper_brick.plant().SetPositions(plant_context, q_sol);
Eigen::Vector3d p_BFingertip;
gripper_brick.plant().CalcPointsPositions(
*plant_context, gripper_brick.finger_link2_frame(Finger::kFinger2),
gripper_brick.p_L2Fingertip(), gripper_brick.brick_frame(),
&p_BFingertip);
EXPECT_LE(p_BFingertip(2), 0.4 * gripper_brick.brick_size()(2) + 1E-5);
EXPECT_GE(p_BFingertip(2), -0.4 * gripper_brick.brick_size()(2) - 1E-5);
EXPECT_NEAR(p_BFingertip(1) + gripper_brick.finger_tip_radius(),
-0.5 * gripper_brick.brick_size()(1) + depth, 1E-5);
}
GTEST_TEST(TestAddFingerNoSlidingConstraint, Test) {
GripperBrickHelper<double> gripper_brick;
const Finger finger{Finger::kFinger1};
const BrickFace face{BrickFace::kNegZ};
solvers::MathematicalProgram prog;
auto q_from =
prog.NewContinuousVariables(gripper_brick.plant().num_positions());
auto q_to =
prog.NewContinuousVariables(gripper_brick.plant().num_positions());
auto diagram_context_from = gripper_brick.diagram().CreateDefaultContext();
auto diagram_context_to = gripper_brick.diagram().CreateDefaultContext();
systems::Context<double>* plant_context_from =
&(gripper_brick.diagram().GetMutableSubsystemContext(
gripper_brick.plant(), diagram_context_from.get()));
systems::Context<double>* plant_context_to =
&(gripper_brick.diagram().GetMutableSubsystemContext(
gripper_brick.plant(), diagram_context_to.get()));
const double face_shrink_factor{0.8};
const double depth{0.001};
AddFingerTipInContactWithBrickFaceConstraint(
gripper_brick, finger, face, &prog, q_from, plant_context_from,
face_shrink_factor, depth);
const double rolling_angle_bound{0.1 * M_PI};
AddFingerNoSlidingConstraint(gripper_brick, finger, face, rolling_angle_bound,
&prog, plant_context_from, plant_context_to,
q_from, q_to, face_shrink_factor, depth);
// Now solve the problem.
const auto result = solvers::Solve(prog);
EXPECT_TRUE(result.is_success());
// Make sure both "from" posture and "to" postures are in contact with the
// brick face.
auto check_finger_in_contact =
[&gripper_brick, depth, &result, face_shrink_factor](
const VectorX<symbolic::Variable>& q,
systems::Context<double>* plant_context) -> math::RigidTransformd {
const Eigen::VectorXd q_sol = result.GetSolution(q);
gripper_brick.plant().SetPositions(plant_context, q_sol);
const math::RigidTransform<double> X_BL2 =
gripper_brick.plant().CalcRelativeTransform(
*plant_context, gripper_brick.brick_frame(),
gripper_brick.finger_link2_frame(finger));
const Eigen::Vector3d p_BTip = X_BL2 * gripper_brick.p_L2Fingertip();
const Eigen::Vector3d brick_size = gripper_brick.brick_size();
EXPECT_NEAR(p_BTip(2),
-brick_size(2) / 2 - gripper_brick.finger_tip_radius() + depth,
1E-4);
EXPECT_GE(p_BTip(1), -brick_size(1) / 2 * face_shrink_factor - 1E-4);
EXPECT_LE(p_BTip(1), brick_size(1) / 2 * face_shrink_factor + 1E-4);
return X_BL2;
};
const math::RigidTransformd X_BL2_from =
check_finger_in_contact(q_from, plant_context_from);
const math::RigidTransformd X_BL2_to =
check_finger_in_contact(q_to, plant_context_to);
// Check the orientation difference between "from" posture and "to" posture.
const Eigen::AngleAxisd angle_axis =
(X_BL2_from.rotation().inverse() * X_BL2_to.rotation()).ToAngleAxis();
double theta;
if (angle_axis.axis().dot(Eigen::Vector3d::UnitX()) > 1 - 1E-4) {
theta = angle_axis.angle();
} else if (angle_axis.axis().dot(-Eigen::Vector3d::UnitX()) > 1 - 1E-4) {
theta = -angle_axis.angle();
} else {
throw std::runtime_error("The axis should be either x axis or -x axis.");
}
EXPECT_GE(theta, -rolling_angle_bound - 1E-5);
EXPECT_LE(theta, rolling_angle_bound + 1E-5);
const Eigen::Vector3d p_BFingertip_from =
X_BL2_from * gripper_brick.p_L2Fingertip();
const Eigen::Vector3d p_BFingertip_to =
X_BL2_to * gripper_brick.p_L2Fingertip();
EXPECT_NEAR(p_BFingertip_to(1) - p_BFingertip_from(1),
-gripper_brick.finger_tip_radius() * theta, 1E-5);
}
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples/planar_gripper | /home/johnshepherd/drake/examples/planar_gripper/test/planar_manipuland_lcm_test.cc | #include "drake/examples/planar_gripper/planar_manipuland_lcm.h"
#include <gtest/gtest.h>
#include "drake/systems/framework/diagram.h"
#include "drake/systems/framework/diagram_builder.h"
namespace drake {
namespace examples {
namespace planar_gripper {
GTEST_TEST(PlanarManipulandLcmTest, PlanarManipulandStatusPassthroughTest) {
systems::DiagramBuilder<double> builder;
auto status_encoder = builder.AddSystem<PlanarManipulandStatusEncoder>();
auto status_decoder = builder.AddSystem<PlanarManipulandStatusDecoder>();
builder.Connect(status_decoder->get_output_port(0),
status_encoder->get_input_port(0));
builder.ExportInput(status_decoder->get_input_port(0));
builder.ExportOutput(status_encoder->get_output_port(0));
auto diagram = builder.Build();
std::unique_ptr<systems::Context<double>> context =
diagram->CreateDefaultContext();
std::unique_ptr<systems::SystemOutput<double>> output =
diagram->AllocateOutput();
lcmt_planar_manipuland_status status{};
status.position[0] = 0.1;
status.position[1] = 0.2;
status.theta = 0.3;
status.velocity[0] = 0.4;
status.velocity[1] = 0.5;
status.thetadot = 0.6;
diagram->get_input_port(0).FixValue(context.get(), status);
std::unique_ptr<systems::DiscreteValues<double>> update =
diagram->AllocateDiscreteVariables();
update->SetFrom(context->get_mutable_discrete_state());
diagram->CalcForcedDiscreteVariableUpdate(*context, update.get());
context->get_mutable_discrete_state().SetFrom(*update);
diagram->CalcOutput(*context, output.get());
lcmt_planar_manipuland_status status_out =
output->get_data(0)->get_value<lcmt_planar_manipuland_status>();
EXPECT_DOUBLE_EQ(status.position[0], status_out.position[0]);
EXPECT_DOUBLE_EQ(status.position[1], status_out.position[1]);
EXPECT_DOUBLE_EQ(status.theta, status_out.theta);
EXPECT_DOUBLE_EQ(status.velocity[0], status_out.velocity[0]);
EXPECT_DOUBLE_EQ(status.velocity[1], status_out.velocity[1]);
EXPECT_DOUBLE_EQ(status.thetadot, status_out.thetadot);
}
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples/planar_gripper | /home/johnshepherd/drake/examples/planar_gripper/test/planar_gripper_common_test.cc | #include "drake/examples/planar_gripper/planar_gripper_common.h"
#include <gtest/gtest.h>
#include "drake/common/find_resource.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/multibody/plant/multibody_plant.h"
namespace drake {
namespace examples {
namespace planar_gripper {
GTEST_TEST(ReorderKeyframesTest, Test) {
const int kNumKeyframes = 4;
MatrixX<double> keyframes = MatrixX<double>::Zero(kNumJoints, kNumKeyframes);
VectorX<double> unit_row = VectorX<double>::Ones(kNumKeyframes);
// Create an arbitrary keyframe matrix.
for (int i = 0; i < keyframes.rows(); i++) {
keyframes.row(i) = unit_row * i;
}
// Set an arbitrary row ordering for the above keyframes.
std::map<std::string, int> finger_joint_name_to_row_index_map;
finger_joint_name_to_row_index_map["finger1_BaseJoint"] = 3;
finger_joint_name_to_row_index_map["finger2_BaseJoint"] = 2;
finger_joint_name_to_row_index_map["finger3_BaseJoint"] = 4;
finger_joint_name_to_row_index_map["finger1_MidJoint"] = 0;
finger_joint_name_to_row_index_map["finger3_MidJoint"] = 5;
finger_joint_name_to_row_index_map["finger2_MidJoint"] = 1;
// Create the plant which defines the ordering.
const std::string gripper_url =
"package://drake/examples/planar_gripper/planar_gripper.sdf";
MultibodyPlant<double> plant(0.0);
multibody::Parser(&plant).AddModelsFromUrl(gripper_url);
WeldGripperFrames(&plant);
plant.Finalize();
// Reorder the keyframes and save the new results.
std::map<std::string, int> finger_joint_name_to_row_index_map_new =
finger_joint_name_to_row_index_map;
auto keyframes_new = ReorderKeyframesForPlant(
plant, keyframes, &finger_joint_name_to_row_index_map_new);
DRAKE_DEMAND(keyframes.rows() == keyframes_new.rows() &&
keyframes.cols() == keyframes_new.cols());
DRAKE_DEMAND(finger_joint_name_to_row_index_map.size() ==
finger_joint_name_to_row_index_map_new.size());
// Get the velocity index ordering.
std::map<std::string, int> finger_joint_name_to_vel_index_ordering =
finger_joint_name_to_row_index_map;
for (auto iter = finger_joint_name_to_vel_index_ordering.begin();
iter != finger_joint_name_to_vel_index_ordering.end(); iter++) {
iter->second = plant.GetJointByName(iter->first).velocity_start();
}
// Make sure the keyframes were ordered correctly.
for (auto iter = finger_joint_name_to_vel_index_ordering.begin();
iter != finger_joint_name_to_vel_index_ordering.end(); iter++) {
EXPECT_TRUE(CompareMatrices(
keyframes_new.row(iter->second),
keyframes.row(finger_joint_name_to_row_index_map[iter->first])));
}
// Test throw when keyframe rows and joint name to row map size don't match.
MatrixX<double> bad_rows_keyframes = /* adds one extra row */
MatrixX<double>::Zero(kNumJoints + 1, kNumKeyframes);
EXPECT_THROW(ReorderKeyframesForPlant(plant, bad_rows_keyframes,
&finger_joint_name_to_row_index_map),
std::runtime_error);
// Test throw when keyframe rows and joint name to row map size match, but
// keyframe rows does not match number of planar-gripper joints.
std::map<std::string, int> bad_finger_joint_name_to_row_index_map =
finger_joint_name_to_row_index_map;
bad_finger_joint_name_to_row_index_map["finger1_ExtraJoint"] = 6;
EXPECT_THROW(
ReorderKeyframesForPlant(plant, bad_rows_keyframes,
&bad_finger_joint_name_to_row_index_map),
std::runtime_error);
// Test throw when plant positions don't match number of expected planar
// gripper joints.
MultibodyPlant<double> bad_plant(0.0);
multibody::Parser(&bad_plant).AddModelsFromUrl(gripper_url);
WeldGripperFrames(&bad_plant);
const std::string brick_url =
"package://drake/examples/planar_gripper/planar_brick.sdf";
multibody::Parser(&bad_plant).AddModelsFromUrl(brick_url);
bad_plant.Finalize();
EXPECT_THROW(
ReorderKeyframesForPlant(bad_plant, keyframes,
&finger_joint_name_to_row_index_map_new),
std::runtime_error);
}
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples/planar_gripper | /home/johnshepherd/drake/examples/planar_gripper/test/planar_gripper_lcm_test.cc | #include "drake/examples/planar_gripper/planar_gripper_lcm.h"
#include <gtest/gtest.h>
#include "drake/lcmt_planar_gripper_command.hpp"
#include "drake/lcmt_planar_gripper_status.hpp"
#include "drake/systems/framework/context.h"
#include "drake/systems/framework/diagram.h"
#include "drake/systems/framework/diagram_builder.h"
namespace drake {
namespace examples {
namespace planar_gripper {
namespace {
constexpr int kNumFingers = 1;
// Test that encoding and decoding perform inverse operations by setting some
// values, encoding them, decoding them, and then verifying we get back what we
// put in.
GTEST_TEST(GripperLcmTest, GripperCommandPassthroughTest) {
systems::DiagramBuilder<double> builder;
auto command_encoder = builder.AddSystem<GripperCommandEncoder>(kNumFingers);
auto command_decoder = builder.AddSystem<GripperCommandDecoder>(kNumFingers);
builder.Connect(command_decoder->get_state_output_port(),
command_encoder->get_state_input_port());
builder.Connect(command_decoder->get_torques_output_port(),
command_encoder->get_torques_input_port());
builder.ExportInput(command_decoder->get_input_port(0));
const systems::OutputPortIndex command_enc_output =
builder.ExportOutput(command_encoder->get_output_port(0));
auto diagram = builder.Build();
std::unique_ptr<systems::Context<double>> context =
diagram->CreateDefaultContext();
lcmt_planar_gripper_command command{};
command.num_fingers = kNumFingers;
command.finger_command.resize(kNumFingers);
auto &fcommand_in = command.finger_command[0];
fcommand_in.joint_position[0] = 0.1;
fcommand_in.joint_position[1] = 0.2;
fcommand_in.joint_velocity[0] = 0.3;
fcommand_in.joint_velocity[1] = 0.4;
fcommand_in.joint_torque[0] = 0.5;
fcommand_in.joint_torque[1] = 0.6;
diagram->get_input_port(0).FixValue(context.get(), command);
std::unique_ptr<systems::DiscreteValues<double>> update =
diagram->AllocateDiscreteVariables();
update->SetFrom(context->get_mutable_discrete_state());
diagram->CalcForcedDiscreteVariableUpdate(*context, update.get());
context->get_mutable_discrete_state().SetFrom(*update);
lcmt_planar_gripper_command command_out =
diagram->get_output_port(command_enc_output)
.Eval<lcmt_planar_gripper_command>(*context);
auto& fcommand_out = command_out.finger_command[0];
ASSERT_EQ(command.num_fingers, command_out.num_fingers);
ASSERT_EQ(fcommand_in.joint_position[0], fcommand_out.joint_position[0]);
ASSERT_EQ(fcommand_in.joint_position[1], fcommand_out.joint_position[1]);
ASSERT_EQ(fcommand_in.joint_velocity[0], fcommand_out.joint_velocity[0]);
ASSERT_EQ(fcommand_in.joint_velocity[1], fcommand_out.joint_velocity[1]);
ASSERT_EQ(fcommand_in.joint_torque[0], fcommand_out.joint_torque[0]);
ASSERT_EQ(fcommand_in.joint_torque[1], fcommand_out.joint_torque[1]);
}
// Test that encoding and decoding perform inverse operations by setting some
// values, encoding them, decoding them, and then verifying we get back what we
// put in.
GTEST_TEST(GripperLcmTest, GripperStatusPassthroughTest) {
systems::DiagramBuilder<double> builder;
auto status_encoder = builder.AddSystem<GripperStatusEncoder>(kNumFingers);
auto status_decoder = builder.AddSystem<GripperStatusDecoder>(kNumFingers);
builder.Connect(status_decoder->get_state_output_port(),
status_encoder->get_state_input_port());
builder.Connect(status_decoder->get_force_output_port(),
status_encoder->get_force_input_port());
builder.ExportInput(status_decoder->get_input_port(0));
const systems::OutputPortIndex status_enc_output =
builder.ExportOutput(status_encoder->get_output_port(0));
auto diagram = builder.Build();
std::unique_ptr<systems::Context<double>> context =
diagram->CreateDefaultContext();
lcmt_planar_gripper_status status{};
status.num_fingers = kNumFingers;
status.finger_status.resize(kNumFingers);
auto &fstatus_in = status.finger_status[0];
fstatus_in.joint_position[0] = 0.1;
fstatus_in.joint_position[1] = 0.2;
fstatus_in.joint_velocity[0] = 0.3;
fstatus_in.joint_velocity[1] = 0.4;
fstatus_in.fingertip_force.fx = 0;
fstatus_in.fingertip_force.fy = 0.5;
fstatus_in.fingertip_force.fz = 0.6;
diagram->get_input_port(0).FixValue(context.get(), status);
std::unique_ptr<systems::DiscreteValues<double>> update =
diagram->AllocateDiscreteVariables();
update->SetFrom(context->get_mutable_discrete_state());
diagram->CalcForcedDiscreteVariableUpdate(*context, update.get());
context->get_mutable_discrete_state().SetFrom(*update);
lcmt_planar_gripper_status status_out =
diagram->get_output_port(status_enc_output)
.Eval<lcmt_planar_gripper_status>(*context);
auto& fstatus_out = status_out.finger_status[0];
ASSERT_EQ(fstatus_in.joint_position[0], fstatus_out.joint_position[0]);
ASSERT_EQ(fstatus_in.joint_position[1], fstatus_out.joint_position[1]);
ASSERT_EQ(fstatus_in.joint_velocity[0], fstatus_out.joint_velocity[0]);
ASSERT_EQ(fstatus_in.joint_velocity[1], fstatus_out.joint_velocity[1]);
ASSERT_EQ(fstatus_in.fingertip_force.fx, fstatus_out.fingertip_force.fx);
ASSERT_EQ(fstatus_in.fingertip_force.fy, fstatus_out.fingertip_force.fy);
ASSERT_EQ(fstatus_in.fingertip_force.fz, fstatus_out.fingertip_force.fz);
}
} // namespace
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples/planar_gripper | /home/johnshepherd/drake/examples/planar_gripper/test/brick_static_equilibrium_constraint_test.cc | #include "drake/examples/planar_gripper/brick_static_equilibrium_constraint.h"
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/math/autodiff_gradient.h"
#include "drake/math/compute_numerical_gradient.h"
namespace drake {
namespace examples {
namespace planar_gripper {
GTEST_TEST(BrickStaticEquilibriumNonlinearConstraint, TestEval) {
GripperBrickHelper<double> gripper_brick_system;
std::vector<std::pair<Finger, BrickFace>> finger_face_contacts;
finger_face_contacts.emplace_back(Finger::kFinger1, BrickFace::kPosZ);
finger_face_contacts.emplace_back(Finger::kFinger3, BrickFace::kPosY);
auto diagram_context = gripper_brick_system.diagram().CreateDefaultContext();
const auto& plant = gripper_brick_system.plant();
systems::Context<double>* plant_mutable_context =
&(gripper_brick_system.diagram().GetMutableSubsystemContext(
gripper_brick_system.plant(), diagram_context.get()));
BrickStaticEquilibriumNonlinearConstraint constraint(
gripper_brick_system, finger_face_contacts, plant_mutable_context);
EXPECT_EQ(constraint.num_outputs(), 3);
EXPECT_EQ(constraint.num_vars(), plant.num_positions() + 2 * 2);
EXPECT_TRUE(
CompareMatrices(constraint.lower_bound(), Eigen::Vector3d::Zero()));
EXPECT_TRUE(
CompareMatrices(constraint.upper_bound(), Eigen::Vector3d::Zero()));
// Test Eval for an arbitrary x.
Eigen::VectorXd x(13);
x << 0.1, 0.3, 0.3, -0.4, -1.2, 0.5, 1.3, -0.2, 1.8, 2.5, -0.4, -0.2, -0.6;
Eigen::VectorXd y;
constraint.Eval(x, &y);
Eigen::Matrix<double, 9, 1> q = x.head<9>();
plant.SetPositions(plant_mutable_context, q);
const math::RigidTransform<double> X_BW = plant.CalcRelativeTransform(
*plant_mutable_context, gripper_brick_system.brick_frame(),
plant.world_frame());
Eigen::Vector3d y_expected;
y_expected.head<2>() =
x.segment<2>(9) + x.segment<2>(11) +
(X_BW.rotation() *
Eigen::Vector3d(
0, 0,
-gripper_brick_system.brick_frame().body().default_mass() *
multibody::UniformGravityFieldElement<double>::kDefaultStrength))
.tail<2>();
Eigen::Vector3d total_torque(0, 0, 0);
Eigen::Vector3d p_BFingertip0;
plant.CalcPointsPositions(
*plant_mutable_context,
gripper_brick_system.finger_link2_frame(finger_face_contacts[0].first),
gripper_brick_system.p_L2Fingertip(), gripper_brick_system.brick_frame(),
&p_BFingertip0);
Eigen::Vector3d p_BC0 = p_BFingertip0;
p_BC0(2) -= gripper_brick_system.finger_tip_radius();
Eigen::Vector3d p_BFingertip1;
plant.CalcPointsPositions(
*plant_mutable_context,
gripper_brick_system.finger_link2_frame(finger_face_contacts[1].first),
gripper_brick_system.p_L2Fingertip(), gripper_brick_system.brick_frame(),
&p_BFingertip1);
Eigen::Vector3d p_BC1 = p_BFingertip1;
p_BC1(1) -= gripper_brick_system.finger_tip_radius();
total_torque += p_BC0.cross(Eigen::Vector3d(0, x(9), x(10))) +
p_BC1.cross(Eigen::Vector3d(0, x(11), x(12)));
y_expected(2) = total_torque(0);
EXPECT_TRUE(CompareMatrices(y, y_expected, 1E-10));
// Now check Eval with autodiff.
auto x_ad = math::InitializeAutoDiff(x);
AutoDiffVecXd y_autodiff;
constraint.Eval(x_ad, &y_autodiff);
std::function<void(const Eigen::Ref<const Eigen::VectorXd>&,
Eigen::VectorXd*)>
evaluator = [&constraint](const Eigen::Ref<const Eigen::VectorXd>& x_val,
Eigen::VectorXd* y_val) {
return constraint.Eval(x_val, y_val);
};
const auto J = math::ComputeNumericalGradient(evaluator, x);
EXPECT_TRUE(CompareMatrices(math::ExtractGradient(y_autodiff), J, 1E-5));
}
} // namespace planar_gripper
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/mass_spring_cloth/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 = "cloth_spring_model",
srcs = [
"cloth_spring_model.cc",
],
hdrs = [
"cloth_spring_model.h",
],
deps = [
":cloth_spring_model_params",
"//common:essential",
"//systems/framework:leaf_system",
],
)
drake_cc_library(
name = "cloth_spring_model_geometry",
srcs = ["cloth_spring_model_geometry.cc"],
hdrs = ["cloth_spring_model_geometry.h"],
deps = [
":cloth_spring_model",
":cloth_spring_model_params",
"//geometry:geometry_roles",
"//geometry:scene_graph",
"//math:geometric_transform",
"//systems/framework:diagram_builder",
"//systems/framework:leaf_system",
],
)
drake_cc_library(
name = "cloth_spring_model_params",
srcs = ["cloth_spring_model_params.cc"],
hdrs = ["cloth_spring_model_params.h"],
deps = [
"//common:dummy_value",
"//common:essential",
"//common:name_value",
"//common/symbolic:expression",
"//systems/framework:vector",
],
)
drake_cc_binary(
name = "run_cloth_spring_model",
srcs = [
"run_cloth_spring_model.cc",
],
deps = [
":cloth_spring_model",
":cloth_spring_model_geometry",
"//common:add_text_logging_gflags",
"//geometry:meshcat_visualizer",
"//systems/analysis:simulator_gflags",
"//systems/framework:diagram",
],
)
drake_cc_googletest(
name = "cloth_spring_model_test",
deps = [
":cloth_spring_model",
"//systems/analysis:simulator",
],
)
add_lint_tests(enable_clang_format_lint = False)
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/mass_spring_cloth/cloth_spring_model.cc | #include "drake/examples/mass_spring_cloth/cloth_spring_model.h"
#include "drake/common/eigen_types.h"
namespace drake {
namespace examples {
namespace mass_spring_cloth {
template <typename T>
ClothSpringModel<T>::ClothSpringModel(int nx, int ny, T h, double dt)
: nx_(nx),
ny_(ny),
num_particles_(nx * ny),
h_(h),
dt_(dt),
bottom_left_corner_(0),
top_left_corner_(ny_ - 1),
H_(3 * num_particles_, 3 * num_particles_) {
systems::BasicVector<T> initial_state = InitializePositionAndVelocity();
if (dt > 0) {
// Discrete system.
// Adding 3*N positions and 3*N velocities.
this->DeclareDiscreteState(initial_state);
this->DeclareVectorOutputPort("particle_positions", 3 * num_particles_,
&ClothSpringModel::CopyDiscreteStateOut);
this->DeclarePeriodicDiscreteUpdateEvent(
dt_, 0., &ClothSpringModel::UpdateDiscreteState);
} else {
// Continuous system.
// Adding 3*N positions and 3*N velocities.
this->DeclareContinuousState(initial_state, 3 * num_particles_,
3 * num_particles_, 0);
// A 3*N dimensional output vector for positions.
this->DeclareVectorOutputPort(systems::kUseDefaultName, 3 * num_particles_,
&ClothSpringModel::CopyContinuousStateOut);
}
param_index_ = this->DeclareNumericParameter(ClothSpringModelParams<T>());
BuildConnectingSprings(true);
// As in symbolic assembly, we allocate for the nonzero entries in the H
// matrix now that we know the sparsity pattern.
if (dt > 0) {
// The H matrix is organized into num_particles * num_particles blocks of 3
// * 3 sub-matrices. The ij-th 3*3 sub-matrix consists of M_ij (mass matrix)
// and ∂f_i/∂v_j (damping force derivative). M_ij is a diagonal matrix with
// the mass of each particle on the diagonal. If there exists a spring
// connecting particles i and j, the blocks
// ∂f_i/∂v_i,∂f_j/∂v_j,∂f_i/∂v_j,and ∂f_j/∂v_i will contain nonzero entries.
VectorX<int> num_nonzero_entries =
VectorX<int>::Ones(3 * num_particles_) * 3;
for (const Spring& s : springs_) {
for (int d = 0; d < 3; ++d) {
num_nonzero_entries[3 * s.particle0 + d] += 3;
num_nonzero_entries[3 * s.particle1 + d] += 3;
}
}
H_.reserve(num_nonzero_entries);
H_.setZero();
// CG is guaranteed to converge when iteration reaches the number of DOFs.
// It usually takes far fewer iterations to converge.
set_linear_solve_max_iterations(num_particles_ * 3);
// Set the default accuracy for the linear solve.
set_linear_solve_accuracy();
}
}
template <typename T>
systems::BasicVector<T> ClothSpringModel<T>::InitializePositionAndVelocity()
const {
// Each particle has 6 state variables, 3 for positions, 3 for velocities.
VectorX<T> state_values(6 * num_particles_);
auto q = state_values.head(3 * num_particles_);
auto v = state_values.tail(3 * num_particles_);
for (int i = 0; i < nx_; ++i) {
for (int j = 0; j < ny_; ++j) {
int particle_index = i * ny_ + j;
/* The particles are ordered in the following fashion:
+y
^
┊
┊ny-1 2ny-1 nx*ny-1
●━━━━━━━●━━┄┄┄┄━━●━━━━━━━●
┃ ┃ ┃ ┃
┃ny-2 ┃2ny-2 ┃ ┃
●━━━━━━━●━━┄┄┄┄━━●━━━━━━━●
┃ ┃ ┃ ┃
┊ ┊ ┊ ┊
┊ ┊ ┊ ┊
┃ ┃ ┃ ┃
┃1 ┃ny+1 ┃ ┃
●━━━━━━━●━━┄┄┄┄━━●━━━━━━━●
┃ ┃ ┃ ┃
┃0 ┃ny ┃ ┃(nx-1)*ny
┄┄●━━━━━━━●━━┄┄┄┄━━●━━━━━━━●┄┄┄┄┄┄┄┄┄> +x
┊
Note that we replaced nx_/ny_ with nx/ny in the diagram above for more
readability.
*/
this->set_particle_state(particle_index, {i * h_, j * h_, 0.0}, &q);
this->set_particle_state(particle_index, {0.0, 0.0, 0.0}, &v);
}
}
return systems::BasicVector<T>(state_values);
}
template <typename T>
void ClothSpringModel<T>::BuildConnectingSprings(bool use_shearing_springs) {
const int num_stretching_springs = (nx_ - 1) * ny_ + (ny_ - 1) * nx_;
const int num_shearing_springs =
use_shearing_springs ? (nx_ - 1) * (ny_ - 1) * 2 : 0;
springs_.resize(num_stretching_springs + num_shearing_springs);
int ns = 0;
// Build springs in the y-direction.
for (int i = 0; i < nx_; ++i) {
for (int j = 0; j < ny_ - 1; ++j) {
const int p = i * ny_ + j;
springs_[ns++] = Spring{p, p + 1, h_};
}
}
// Build springs in the x-direction.
for (int i = 0; i < nx_ - 1; ++i) {
for (int j = 0; j < ny_; ++j) {
const int p = i * ny_ + j;
springs_[ns++] = Spring{p, p + ny_, h_};
}
}
if (use_shearing_springs) {
for (int i = 0; i < nx_ - 1; ++i) {
for (int j = 0; j < ny_ - 1; ++j) {
// For each particle p, build diagonal and anti-diagonal springs for the
// cell that p is on the bottom-left corner of.
/*
| p+1 | p+ny+1
────•───────•────
| \ / |
| X |
| / \ |
────•───────•────
| p | p+ny
*/
const int p = i * ny_ + j;
springs_[ns++] = Spring{p, p + ny_ + 1, std::sqrt(2) * h_};
springs_[ns++] = Spring{p + 1, p + ny_, std::sqrt(2) * h_};
}
}
}
}
template <typename T>
void ClothSpringModel<T>::CopyContinuousStateOut(
const systems::Context<T>& context, systems::BasicVector<T>* output) const {
output->SetFrom(context.get_continuous_state().get_generalized_position());
}
template <typename T>
void ClothSpringModel<T>::CopyDiscreteStateOut(
const systems::Context<T>& context, systems::BasicVector<T>* output) const {
const systems::BasicVector<T>& discrete_state_vector =
context.get_discrete_state(0);
output->SetFromVector(
discrete_state_vector.value().head(3 * num_particles_));
}
template <typename T>
void ClothSpringModel<T>::DoCalcTimeDerivatives(
const systems::Context<T>& context,
systems::ContinuousState<T>* derivatives) const {
const systems::VectorBase<T>& v =
context.get_continuous_state().get_generalized_velocity();
systems::VectorBase<T>& qdot =
derivatives->get_mutable_generalized_position();
qdot.SetFrom(v);
systems::VectorBase<T>& vdot =
derivatives->get_mutable_generalized_velocity();
// Store spring force in vdot and then divide by mass to get acceleration.
VectorX<T> tmp_vdot = VectorX<T>::Zero(vdot.size());
AccumulateContinuousSpringForce(context, &tmp_vdot);
const ClothSpringModelParams<T>& p = GetParameters(context);
const T mass_per_particle = p.mass() / static_cast<T>(num_particles_);
// Mass of each particle must be positive.
DRAKE_THROW_UNLESS(mass_per_particle > 0);
for (int i = 0; i < vdot.size(); ++i) {
tmp_vdot[i] /= mass_per_particle;
}
// Apply gravity to acceleration.
const Vector3<T> gravity{0, 0, p.gravity()};
for (int i = 0; i < num_particles_; ++i) {
accumulate_particle_state(i, gravity, &tmp_vdot);
}
ApplyDirichletBoundary(&tmp_vdot);
vdot.SetFromVector(tmp_vdot);
}
template <typename T>
void ClothSpringModel<T>::UpdateDiscreteState(
const systems::Context<T>& context,
systems::DiscreteValues<T>* next_states) const {
const VectorX<T>& current_state_values = context.get_discrete_state().value();
const auto& q_n = current_state_values.head(3 * num_particles_);
const auto& v_n = current_state_values.tail(3 * num_particles_);
// v_hat is the velocity of the particles after adding the effect of the
// explicit elastic and gravity forces.
VectorX<T> v_hat(v_n);
const ClothSpringModelParams<T>& p = GetParameters(context);
// Add contribution of gravity to v_hat.
const Vector3<T> gravity_dv{0, 0, p.gravity() * dt_};
for (int i = 0; i < num_particles_; ++i) {
accumulate_particle_state(i, gravity_dv, &v_hat);
}
// Add the contribution of explicit spring elastic force to v_hat.
VectorX<T> elastic_force = VectorX<T>::Zero(v_hat.size());
AccumulateElasticForce(p, q_n, &elastic_force);
T mass_per_particle = p.mass() / static_cast<T>(num_particles_);
v_hat += elastic_force * dt_ / mass_per_particle;
ApplyDirichletBoundary(&v_hat);
// dv is the change in velocity contributed by the implicit damping force.
// Freezing q to be q_n, the momentum equation
//
// M * dv = f(vⁿ⁺¹) * dt
//
// is equivalent to
//
// M * dv = (f(v_hat) + ∂f/∂v(v_hat) * dv) * dt
// because the damping force is linear in v. Moving terms, we end up with
// (M - ∂f/∂v(v_hat)) * dv = f(v_hat) * dt,
// which we abbreviate as H * dv = f * dt.
VectorX<T> dv = VectorX<T>::Zero(v_hat.size());
VectorX<T> damping_force = VectorX<T>::Zero(v_hat.size());
AccumulateDampingForce(p, q_n, v_hat, &damping_force);
CalcDiscreteDv(p, q_n, &damping_force, &dv);
// Write v_hat + dv into the velocity at the next time step.
Eigen::VectorBlock<VectorX<T>> next_state_values =
next_states->get_mutable_value();
auto next_q = next_state_values.head(3 * num_particles_);
auto next_v = next_state_values.tail(3 * num_particles_);
next_v = v_hat + dv;
// Apply BC again to prevent numerical drift.
ApplyDirichletBoundary(&next_v);
// Update position using velocity at time n+1.
next_q = q_n + dt_ * next_v;
}
template <typename T>
void ClothSpringModel<T>::AccumulateContinuousSpringForce(
const systems::Context<T>& context, EigenPtr<VectorX<T>> forces) const {
DRAKE_DEMAND(forces != nullptr);
const VectorX<T> continuous_states =
context.get_continuous_state().CopyToVector();
const auto& q = continuous_states.head(num_positions());
const auto& v = continuous_states.segment(num_positions(), num_velocities());
const ClothSpringModelParams<T>& p = GetParameters(context);
AccumulateElasticForce(p, q, forces);
AccumulateDampingForce(p, q, v, forces);
}
template <typename T>
void ClothSpringModel<T>::AccumulateElasticForce(
const ClothSpringModelParams<T>& param,
const Eigen::Ref<const VectorX<T>>& q,
EigenPtr<VectorX<T>> elastic_force) const {
DRAKE_DEMAND(elastic_force != nullptr);
for (const Spring& s : springs_) {
// Get the positions of the two particles connected by the spring.
const int p0 = s.particle0;
const int p1 = s.particle1;
const Vector3<T> p_WP0 = particle_state(p0, q);
const Vector3<T> p_WP1 = particle_state(p1, q);
const Vector3<T> p_P0P1_W = p_WP1 - p_WP0;
const T spring_length = p_P0P1_W.norm();
ThrowIfInvalidSpringLength(spring_length, s.rest_length);
const Vector3<T> n = p_P0P1_W / spring_length;
// If the n is the unit vector point from P0 to P1,
// the spring elastic force = k * (current_length - rest_length) * n
const Vector3<T> f = param.k() * (spring_length - s.rest_length) * n;
accumulate_particle_state(p0, f, elastic_force);
accumulate_particle_state(p1, -f, elastic_force);
}
}
template <typename T>
void ClothSpringModel<T>::AccumulateDampingForce(
const ClothSpringModelParams<T>& param,
const Eigen::Ref<const VectorX<T>>& q,
const Eigen::Ref<const VectorX<T>>& v,
EigenPtr<VectorX<T>> damping_force) const {
DRAKE_DEMAND(damping_force != nullptr);
for (const Spring& s : springs_) {
// Get the positions and velocities of the two particles connected by
// the spring.
const int p0 = s.particle0;
const int p1 = s.particle1;
const Vector3<T> p_WP0 = particle_state(p0, q);
const Vector3<T> p_WP1 = particle_state(p1, q);
const Vector3<T> v_WP0 = particle_state(p0, v);
const Vector3<T> v_WP1 = particle_state(p1, v);
const Vector3<T> p_P0P1_W = p_WP1 - p_WP0;
const T spring_length = p_P0P1_W.norm();
ThrowIfInvalidSpringLength(spring_length, s.rest_length);
const Vector3<T> n = p_P0P1_W / spring_length;
// If the n is the unit vector point from q0 to q1,
// the damping force = (damping coefficient * velocity difference)
// projected in the direction of n.
const Vector3<T> f = param.d() * (v_WP1 - v_WP0).dot(n) * n;
accumulate_particle_state(p0, f, damping_force);
accumulate_particle_state(p1, -f, damping_force);
}
}
template <typename T>
void ClothSpringModel<T>::CalcDiscreteDv(const ClothSpringModelParams<T>& param,
const VectorX<T>& q, VectorX<T>* f,
VectorX<T>* dv) const {
DRAKE_DEMAND(q.size() == dv->size());
DRAKE_DEMAND(q.size() == f->size());
const T mass_per_particle = param.mass() / static_cast<T>(num_particles_);
// Here we construct the H matrix. Take extreme care to overwrite the stale
// data from the previous time step. Initialize the diagonal of the matrix to
// be mass_per_particle.
for (int i = 0; i < num_particles_; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 3; ++k) {
H_.coeffRef(3 * i + j, 3 * i + k) =
(j == k) ? mass_per_particle : T(0.0);
}
}
}
// Add in the contribution from damping force differential.
for (const Spring& s : springs_) {
// Get the positions of the two particles connected by the spring.
const int p0 = s.particle0;
const int p1 = s.particle1;
const Vector3<T> p_WP0 = particle_state(p0, q);
const Vector3<T> p_WP1 = particle_state(p1, q);
const Vector3<T> p_P0P1_W = p_WP1 - p_WP0;
const T spring_length = p_P0P1_W.norm();
ThrowIfInvalidSpringLength(spring_length, s.rest_length);
const Vector3<T> n = p_P0P1_W / spring_length;
// If the n is the unit vector point from q0 to q1,
// the spring elastic force = elastic stiffness * (length - restlength) *
// n, and damping force = (damping coefficient * velocity difference)
// projected in the direction of n.
const Matrix3<T> minus_damping_force_derivative =
param.d() * dt_ * n * n.transpose();
// H_ is a sparse matrix. If it were a DenseMatrix, these for loops would
// be equivalent to:
// H_.block<3,3>(3*p0, 3*p0) += minus_damping_force_derivative;
// H_.block<3,3>(3*p1, 3*p1) += minus_damping_force_derivative;
// H_.block<3,3>(3*p0, 3*p1) = -minus_damping_force_derivative;
// H_.block<3,3>(3*p1, 3*p0) = -minus_damping_force_derivative;
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 3; ++k) {
// The diagonal blocks get contribution from multiple springs. We can
// safely add to the diagonal blocks because they were reset earlier.
H_.coeffRef(3 * p0 + j, 3 * p0 + k) +=
minus_damping_force_derivative(j, k);
H_.coeffRef(3 * p1 + j, 3 * p1 + k) +=
minus_damping_force_derivative(j, k);
// Do not add in the off-diagonal terms involving fixed particles.
if (p0 != bottom_left_corner_ && p0 != top_left_corner_ &&
p1 != bottom_left_corner_ && p1 != top_left_corner_) {
// Each off-diagonal block only gets contribution from a single
// spring. It's important to overwrite the value from previous
// time-step.
H_.coeffRef(3 * p1 + j, 3 * p0 + k) =
-minus_damping_force_derivative(j, k);
H_.coeffRef(3 * p0 + j, 3 * p1 + k) =
-minus_damping_force_derivative(j, k);
}
}
}
}
// Set the blocks in H corresponding to the particles subject to boundary
// condition to the identity matrix.
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 3; ++k) {
H_.coeffRef(3 * bottom_left_corner_ + j, 3 * bottom_left_corner_ + k) =
(j == k) ? 1.0 : 0.0;
H_.coeffRef(3 * top_left_corner_ + j, 3 * top_left_corner_ + k) =
(j == k) ? 1.0 : 0.0;
}
}
// Set the right-hand-side entries corresponding to particles subject to
// boundary conditions to zero.
set_particle_state(bottom_left_corner_, {0.0, 0.0, 0.0}, f);
set_particle_state(top_left_corner_, {0.0, 0.0, 0.0}, f);
cg_.compute(H_);
(*dv) = cg_.solve((*f) * dt_);
DRAKE_THROW_UNLESS(cg_.info() == Eigen::ComputationInfo::Success);
}
template <typename T>
void ClothSpringModel<T>::ThrowIfInvalidSpringLength(
const T& spring_length, const T& rest_length) const {
constexpr double kRelativeTolerance =
10 * std::numeric_limits<double>::epsilon();
constexpr char prefix[] =
"Two particles are nearly coincident; the simulation reached an "
"invalid state.";
constexpr char postfix[] = "Try simulating a less energetic condition.";
if (spring_length < kRelativeTolerance * rest_length) {
if (dt_ > 0) {
throw std::runtime_error(
fmt::format("{} Current discrete time step ({} s) may be too "
"large. Try a smaller value. If that does not work, {}",
prefix, dt_, postfix));
} else {
throw std::runtime_error(fmt::format("{} {}", prefix, postfix));
}
}
}
template class ClothSpringModel<double>;
} // namespace mass_spring_cloth
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/mass_spring_cloth/README.md | Mass Spring Cloth Example
================================================================================
This example demonstrates the dynamics of a cloth modeled as a collection of
particles connected by springs. The cloth, fixed at two corners and
initially horizontal, drapes down and swings under gravity. The purpose of this
example is to demonstrate the ability of Drake to enable simulation of
customized dynamical systems through user-defined time derivative update for
continuous systems and discrete states update for discrete systems. Note that
this example is a particle system connected by springs whose parameters are
tuned to exhibit cloth-like behaviors without considerations of environmental
forces or collisions and contact. In particular, it does not indicate that Drake
supports cloth simulation at this point.
The system runs in discrete mode when the time step `dt` is set to be positive,
and it runs in continuous mode when the time step `dt` is set to be zero or
negative. As the discrete and the continuous mode share many common features, we
implement them in a single system to minimize code duplication. Alternatively,
one could implement them as two separate systems.
The mass-spring model is adapted from [Provot 1995]. The discrete time
integration scheme follows that of [Bridson, 2005].
The following instructions assume Drake was
[built using bazel](https://drake.mit.edu/bazel.html?highlight=bazel).
All instructions assume that you are launching from the `drake` workspace
directory.
```
cd drake
```
Prerequisites
-------------
Ensure that you have the demo built:
```
bazel build //examples/mass_spring_cloth:run_cloth_spring_model
```
Mass Spring Cloth Simulation
---------------------
Launch the mass spring cloth simulation
```
bazel-bin/examples/mass_spring_cloth/run_cloth_spring_model
```
Navigate web browser to the hosted URL displayed in the console to visualize
the demo with MeshCat. Note that, unlike many other visualizers, one cannot
open the MeshCat visualizer until this server is running.
The discrete mode is run by default. Since the discrete solver uses a
conditionally stable time integration scheme. Using too large a `dt`
may lead to instability. Usually, you will need to decrease `dt` when you:
1. increase the elastic stiffness, or
2. decrease `h`, or
3. decrease the mass of the particles.
To switch to the continuous mode, add the flag `--dt=0`. The number
of particles in the x-direction and the y-direction can be configured
with the flag `--nx` and `--ny` respectively, and the separation
between particles can be set with the flag `--h`. Use `--help` to
get the full list of flags.
References
-------------------------------------------------
- [Bridson, 2005] Bridson, Robert, Sebastian
Marino, and Ronald Fedkiw. "Simulation of clothing with folds and wrinkles."
ACM SIGGRAPH 2005 Courses. 2005.
- [Provot 1995] Provot, Xavier.
"Deformation constraints in a mass-spring model to describe rigid cloth
behaviour." Graphics interface. Canadian Information Processing Society, 1995.
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/mass_spring_cloth/cloth_spring_model_params.cc | #include "drake/examples/mass_spring_cloth/cloth_spring_model_params.h"
namespace drake {
namespace examples {
namespace mass_spring_cloth {
const int ClothSpringModelParamsIndices::kNumCoordinates;
const int ClothSpringModelParamsIndices::kMass;
const int ClothSpringModelParamsIndices::kK;
const int ClothSpringModelParamsIndices::kD;
const int ClothSpringModelParamsIndices::kGravity;
const std::vector<std::string>&
ClothSpringModelParamsIndices::GetCoordinateNames() {
static const drake::never_destroyed<std::vector<std::string>> coordinates(
std::vector<std::string>{
"mass",
"k",
"d",
"gravity",
});
return coordinates.access();
}
} // namespace mass_spring_cloth
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/mass_spring_cloth/cloth_spring_model_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 mass_spring_cloth {
/// Describes the row indices of a ClothSpringModelParams.
struct ClothSpringModelParamsIndices {
/// The total number of rows (coordinates).
static const int kNumCoordinates = 4;
// The index of each individual coordinate.
static const int kMass = 0;
static const int kK = 1;
static const int kD = 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, `ClothSpringModelParamsIndices::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 ClothSpringModelParams final : public drake::systems::BasicVector<T> {
public:
/// An abbreviation for our row index constants.
typedef ClothSpringModelParamsIndices K;
/// Default constructor. Sets all rows to their default value:
/// @arg @c mass defaults to 1.0 kg.
/// @arg @c k defaults to 100.0 N/m.
/// @arg @c d defaults to 10 Ns/m.
/// @arg @c gravity defaults to -9.81 m/s^2.
ClothSpringModelParams()
: drake::systems::BasicVector<T>(K::kNumCoordinates) {
this->set_mass(1.0);
this->set_k(100.0);
this->set_d(10);
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
//@{
ClothSpringModelParams(const ClothSpringModelParams& other)
: drake::systems::BasicVector<T>(other.values()) {}
ClothSpringModelParams(ClothSpringModelParams&& other) noexcept
: drake::systems::BasicVector<T>(std::move(other.values())) {}
ClothSpringModelParams& operator=(const ClothSpringModelParams& other) {
this->values() = other.values();
return *this;
}
ClothSpringModelParams& operator=(ClothSpringModelParams&& 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(symbolic::Variable("mass"));
this->set_k(symbolic::Variable("k"));
this->set_d(symbolic::Variable("d"));
this->set_gravity(symbolic::Variable("gravity"));
}
[[nodiscard]] ClothSpringModelParams<T>* DoClone() const final {
return new ClothSpringModelParams;
}
/// @name Getters and Setters
//@{
/// Mass of the entire system.
/// @note @c mass is expressed in units of kg.
/// @note @c mass has a limited domain of [0.001, +Inf].
const T& mass() const {
ThrowIfEmpty();
return this->GetAtIndex(K::kMass);
}
/// Setter that matches mass().
void set_mass(const T& mass) {
ThrowIfEmpty();
this->SetAtIndex(K::kMass, mass);
}
/// Fluent setter that matches mass().
/// Returns a copy of `this` with mass set to a new value.
[[nodiscard]] ClothSpringModelParams<T> with_mass(const T& mass) const {
ClothSpringModelParams<T> result(*this);
result.set_mass(mass);
return result;
}
/// Elastic stiffness of the springs.
/// @note @c k is expressed in units of N/m.
/// @note @c k has a limited domain of [0.0, +Inf].
const T& k() const {
ThrowIfEmpty();
return this->GetAtIndex(K::kK);
}
/// Setter that matches k().
void set_k(const T& k) {
ThrowIfEmpty();
this->SetAtIndex(K::kK, k);
}
/// Fluent setter that matches k().
/// Returns a copy of `this` with k set to a new value.
[[nodiscard]] ClothSpringModelParams<T> with_k(const T& k) const {
ClothSpringModelParams<T> result(*this);
result.set_k(k);
return result;
}
/// Damping coefficient of the springs.
/// @note @c d is expressed in units of Ns/m.
/// @note @c d has a limited domain of [0.0, +Inf].
const T& d() const {
ThrowIfEmpty();
return this->GetAtIndex(K::kD);
}
/// Setter that matches d().
void set_d(const T& d) {
ThrowIfEmpty();
this->SetAtIndex(K::kD, d);
}
/// Fluent setter that matches d().
/// Returns a copy of `this` with d set to a new value.
[[nodiscard]] ClothSpringModelParams<T> with_d(const T& d) const {
ClothSpringModelParams<T> result(*this);
result.set_d(d);
return result;
}
/// Gravitational constant.
/// @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]] ClothSpringModelParams<T> with_gravity(const T& gravity) const {
ClothSpringModelParams<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& mass_ref = this->GetAtIndex(K::kMass);
a->Visit(drake::MakeNameValue("mass", &mass_ref));
T& k_ref = this->GetAtIndex(K::kK);
a->Visit(drake::MakeNameValue("k", &k_ref));
T& d_ref = this->GetAtIndex(K::kD);
a->Visit(drake::MakeNameValue("d", &d_ref));
T& gravity_ref = this->GetAtIndex(K::kGravity);
a->Visit(drake::MakeNameValue("gravity", &gravity_ref));
}
/// See ClothSpringModelParamsIndices::GetCoordinateNames().
static const std::vector<std::string>& GetCoordinateNames() {
return ClothSpringModelParamsIndices::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());
result = result && (mass() >= T(0.001));
result = result && !isnan(k());
result = result && (k() >= T(0.0));
result = result && !isnan(d());
result = result && (d() >= 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::kMass) = 0.001;
(*lower)(K::kK) = 0.0;
(*lower)(K::kD) = 0.0;
(*lower)(K::kGravity) = 0.0;
}
private:
void ThrowIfEmpty() const {
if (this->values().size() == 0) {
throw std::out_of_range(
"The ClothSpringModelParams vector has been moved-from; "
"accessor methods may no longer be used");
}
}
};
} // namespace mass_spring_cloth
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/mass_spring_cloth/cloth_spring_model.h | #pragma once
#include <limits>
#include <vector>
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/examples/mass_spring_cloth/cloth_spring_model_params.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace examples {
namespace mass_spring_cloth {
/** A system that models a rectangular piece of cloth using as a model a
structured grid of springs and dampers. All quantities are expressed in the
world frame unless otherwise noted. The system consists of nx-by-ny mass
particles with neighboring particles separated by a distance of h meters. The
rectangular grid initially lies in the z=0 plane and is fixed at two corners at
(0,0,0) and (0, Ly, 0), where Ly is the side length of the cloth in the
y-direction and is equal to (ny-1)*h. Shearing springs are added to penalize
shearing modes. The model is described in detail in [Provot 1995].
The system has three physical parameters:
- __k__: elastic stiffness of the springs in the unit of N/m, measures the
elastic force generated by the spring per unit displacement from the rest
length.
- __d__: damping coefficient of the springs in the unit of Ns/m, measures the
damping force generated by the spring per unit relative velocity of the two
particles connected by the spring.
- __gravity__: the gravitational constant, a (usually negative) scalar. The
gravity experienced by the particles is (0,0,gravity).
The dynamics of the system is described by:
q̇ = v,
Mv̇ = fe(q) + fd(q, v),
where `fe` contains the elastic spring force and `fd` contains the
dissipation terms.
When the system is integrated discretely, the elastic force and gravity are
integrated explicitly while the damping force is integrated implicitly. In
particular, the discretization reads:
Mv̂ = Mvⁿ + dt*fe(qⁿ),
Mvⁿ⁺¹ = Mv̂ + dt*fd(qⁿ, vⁿ⁺¹),
qⁿ⁺¹ = qⁿ + dt*vⁿ⁺¹.
which is first order accurate, but similar in spirit to the scheme in [Bridson,
2005]. One should be careful not to take too large a time step when using the
discrete system because it is conditionally stable, and large time steps can
lead to an unstable numerical solution.
Note that the spring energy is finite and thus the particles can overlap in
certain scenarios. For both the discrete and the continuous system, when two
particles overlap, the state is invalid and the system will throw a
`std::runtime_error` and cause the program to crash.
The system has a single output port that provides the positions of the
particles. The 3*i-th, 3*i+1-th, and 3*i+2-th entry describe the position of
the i-th particle.
Beware that this class is not thread-safe as it contains mutable data storing
the state of the discrete solver. This mutable data has no effect on the
simulation results and therefore it is not part of the system's states.
@system
name: ClothSpringModel
output_ports:
- particle_positions
@endsystem
<h3>References</h3>
- [Bridson, 2005] Bridson, Robert, Sebastian
Marino, and Ronald Fedkiw. "Simulation of clothing with folds and wrinkles."
ACM SIGGRAPH 2005 Courses. 2005.
- [Provot 1995] Provot, Xavier.
"Deformation constraints in a mass-spring model to describe rigid cloth
behaviour." Graphics interface. Canadian Information Processing Society, 1995.
*/
template <typename T>
class ClothSpringModel final : public systems::LeafSystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ClothSpringModel)
/** Creates a rectangular cloth with a grid of nx by ny particles.
@param[in] nx The number of particles in the x-direction.
@param[in] ny The number of particles in the y-direction.
@param[in] h The spacing (in meters) between neighboring particles.
@param[in] dt The duration (in seconds) of the discrete solver's time step.
If dt <= 0, the continuous solver will be used.
@pre @p nx > 0.
@pre @p ny > 0.
@pre @p h > 0.
*/
ClothSpringModel(int nx, int ny, T h, double dt);
/** This returns nx * ny. */
int num_particles() const { return num_particles_; }
T h() const { return h_; }
/** For discrete mode only: set the max number of iterations for the Conjugate
Gradient solve for the implicit damping force. It has no effect on
continuous mode. */
void set_linear_solve_max_iterations(int max_iterations) {
cg_.setMaxIterations(max_iterations);
}
/** For discrete mode only: set the accuracy for the Conjugate Gradient solve
for the implicit damping force. It has no effect on continuous mode.
@param[in] accuracy The unit-less permissible relative error on velocity
update. */
void set_linear_solve_accuracy(T accuracy = 0.0001) {
cg_.setTolerance(accuracy);
}
private:
struct Spring {
// Indices of the two particles connected by the spring.
int particle0{};
int particle1{};
T rest_length{};
};
/* This function extracts the position/velocity/force corresponding to the
particle indexed with particle_index from the vector of that quantity.
All per-particle quantities are elements of R³ and are aligned in each of
the quantity vectors.*/
static Vector3<T> particle_state(int particle_index,
const Eigen::Ref<const VectorX<T>>& vec) {
const int p_index = particle_index * 3;
return Vector3<T>{vec[p_index], vec[p_index + 1], vec[p_index + 2]};
}
/* The setter corresponding to particle_state. Set position/velocity/force the
particle indexed with particle_index to the state parameter.
All per-particle quantities are elements of R³ and are aligned in each of
the quantity vectors.*/
static void set_particle_state(int particle_index, const Vector3<T>& state,
EigenPtr<VectorX<T>> vec) {
DRAKE_ASSERT(vec != nullptr);
const int p_index = particle_index * 3;
(*vec)[p_index] = state(0);
(*vec)[p_index + 1] = state(1);
(*vec)[p_index + 2] = state(2);
}
/* Similar to set_particle_state, but add state into the corresponding
position in vec without zeroing out the old value.
All per-particle quantities are elements of R³ and are aligned in each of
the quantity vectors.*/
static void accumulate_particle_state(int particle_index,
const Vector3<T>& state,
EigenPtr<VectorX<T>> vec) {
DRAKE_ASSERT(vec != nullptr);
const int p_index = particle_index * 3;
(*vec)[p_index] += state(0);
(*vec)[p_index + 1] += state(1);
(*vec)[p_index + 2] += state(2);
}
/* Initialize the positions of the particles to be in a rectangular grid of
nx-by-ny particles with neighboring particles separated by h. The velocities
are initialized to zero. */
systems::BasicVector<T> InitializePositionAndVelocity() const;
/* TODO(xuchenhan-tri) Expose the use_shearing_springs parameter in the
constructor to give the user the ability to toggle the configuration. */
/* Generates the connectivity of the mesh of springs. */
void BuildConnectingSprings(bool use_shearing_springs);
void CopyContinuousStateOut(const systems::Context<T>& context,
systems::BasicVector<T>* output) const;
void CopyDiscreteStateOut(const systems::Context<T>& context,
systems::BasicVector<T>* output) const;
void DoCalcTimeDerivatives(
const systems::Context<T>& context,
systems::ContinuousState<T>* derivatives) const override;
void UpdateDiscreteState(const systems::Context<T>& context,
systems::DiscreteValues<T>* next_states) const;
/* Calculates the spring (elastic and damping combined) forces given the
context. This is only used for computing forces in the continuous
integration. The values contained in forces should be set to zero outside
this function if fresh values are required. */
void AccumulateContinuousSpringForce(const systems::Context<T>& context,
EigenPtr<VectorX<T>> forces) const;
const ClothSpringModelParams<T>& GetParameters(
const systems::Context<T>& context) const {
return this->template GetNumericParameter<ClothSpringModelParams>(
context, param_index_);
}
/* Calculates the elastic force from springs given the positions of the
particles and add to the output elastic_force. The values contained in
elastic_force should be set to zero outside this function if fresh values
are required. */
void AccumulateElasticForce(const ClothSpringModelParams<T>& param,
const Eigen::Ref<const VectorX<T>>& q,
EigenPtr<VectorX<T>> elastic_force) const;
/* Calculates the damping force from springs given the positions and
velocities of the particles and add to the output damping_force. The values
contained in damping_force should be set to zero outside this function if
fresh values are required. */
void AccumulateDampingForce(const ClothSpringModelParams<T>& param,
const Eigen::Ref<const VectorX<T>>& q,
const Eigen::Ref<const VectorX<T>>& v,
EigenPtr<VectorX<T>> damping_force) const;
/* Calculates the change in discrete velocity, dv = vⁿ⁺¹ - v̂, induced by the
implicit damping force, where v̂ is the velocity after the contribution of
elastic and gravity forces are added. This function overwrites the values
in dv.
CalcDiscreteDv solves the equation
M * dv = f(qⁿ, vⁿ⁺¹) * dt,
where f is the damping force, which is equivalent to
M * dv = (f(qⁿ, v̂) + ∂f/∂v(qⁿ, v̂) * dv) * dt,
because damping force is linear in v. Moving terms we end up with
(M - ∂f/∂v(qⁿ, v̂)) * dv = f(qⁿ, v̂) * dt
which we abbreviate as
H * dv = f * dt.
@pre q, f, and dv must be of the same size.
*/
void CalcDiscreteDv(const ClothSpringModelParams<T>& param,
const VectorX<T>& q, VectorX<T>* f, VectorX<T>* dv) const;
/*
Apply Dirichlet boundary conditions to the two corners of the rectangular
grid.
*/
void ApplyDirichletBoundary(EigenPtr<VectorX<T>> state) const {
set_particle_state(bottom_left_corner_, {0, 0, 0}, state);
set_particle_state(top_left_corner_, {0, 0, 0}, state);
}
/* Customized throw to prevent invalid configuration of springs. */
void ThrowIfInvalidSpringLength(const T& spring_length,
const T& rest_length) const;
/* Return the number of degrees of freedoms corresponding to positions. */
int num_positions() const { return num_particles_ * 3; }
/* Return the number of degrees of freedoms corresponding to velocities. */
int num_velocities() const { return num_particles_ * 3; }
/* Number of particles in the x direction. */
const int nx_{};
/* Number of particles in the y direction.*/
const int ny_{};
/* Total number of mass particles.*/
const int num_particles_{};
/* The distance between neighboring particles.*/
const T h_{};
/* The time period between discrete updates.*/
const T dt_{};
/* The index of the fixed particle at the bottom-left corner of the grid.*/
const int bottom_left_corner_{};
/* The index of the fixed particle at the top-left corner of the grid.*/
const int top_left_corner_{};
/* The starting index of the parameters of this system.*/
int param_index_{};
/* A list of springs in the system. Indexing does not matter here.*/
std::vector<Spring> springs_;
/* Pre-allocated H matrix to prevent reallocations.*/
mutable Eigen::SparseMatrix<T> H_;
/* We use a CG solver for the symmetric positive definite matrix in the linear
solve. We use the Lower|Upper flag for better performance per Eigen Doc:
https://eigen.tuxfamily.org/dox/classEigen_1_1ConjugateGradient.html
*/
mutable Eigen::ConjugateGradient<Eigen::SparseMatrix<double>,
Eigen::Lower | Eigen::Upper>
cg_;
};
} // namespace mass_spring_cloth
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/mass_spring_cloth/run_cloth_spring_model.cc | /*
@brief A discrete mass-spring system example.
*/
#include <cstdlib>
#include <limits>
#include <memory>
#include <gflags/gflags.h>
#include "drake/examples/mass_spring_cloth/cloth_spring_model.h"
#include "drake/examples/mass_spring_cloth/cloth_spring_model_geometry.h"
#include "drake/geometry/meshcat_visualizer.h"
#include "drake/geometry/scene_graph.h"
#include "drake/systems/analysis/simulator_gflags.h"
#include "drake/systems/framework/diagram.h"
#include "drake/systems/framework/diagram_builder.h"
DEFINE_int32(nx, 20, "Number of particles in the x direction");
DEFINE_int32(ny, 20, "Number of particles in the y direction");
DEFINE_double(h, 0.05, "Separation between neighboring particles");
DEFINE_double(dt, 0.01,
"Time step size for system. Discrete time stepping "
"scheme described in Bridson et.al. will be used if dt > 0. The "
"discrete scheme runs faster but is not error controlled. If dt "
"<= 0, the system will be continuous");
DEFINE_double(simulation_time, std::numeric_limits<double>::infinity(),
"How long to simulate the system");
namespace drake {
namespace examples {
namespace mass_spring_cloth {
namespace {
int DoMain() {
systems::DiagramBuilder<double> builder;
auto* cloth_spring_model = builder.AddSystem<ClothSpringModel<double>>(
FLAGS_nx, FLAGS_ny, FLAGS_h, FLAGS_dt);
auto* scene_graph = builder.AddSystem<geometry::SceneGraph>();
ClothSpringModelGeometry::AddToBuilder(&builder, *cloth_spring_model,
scene_graph);
geometry::MeshcatVisualizerd::AddToBuilder(
&builder, *scene_graph, std::make_shared<geometry::Meshcat>());
auto diagram = builder.Build();
auto context = diagram->CreateDefaultContext();
auto simulator = MakeSimulatorFromGflags(*diagram, std::move(context));
simulator->AdvanceTo(FLAGS_simulation_time);
return 0;
}
} // namespace
} // namespace mass_spring_cloth
} // namespace examples
} // namespace drake
int main(int argc, char** argv) {
gflags::SetUsageMessage(
"A simple demonstration of a cloth modeled as a mass-spring system");
// Build the diagram for a visualized mass-spring system.
gflags::ParseCommandLineFlags(&argc, &argv, true);
return drake::examples::mass_spring_cloth::DoMain();
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/mass_spring_cloth/cloth_spring_model_geometry.h | #pragma once
#include <vector>
#include "drake/examples/mass_spring_cloth/cloth_spring_model.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 mass_spring_cloth {
/** Expresses a ClothSpringModel's visualization geometry to a SceneGraph. This
visualization takes the particle_positions output from ClothSpringModel.
@system
name: ClothSpringModelGeometry
input_ports:
- particle_positions
output_ports:
- geometry_pose
@endsystem
The visualization shows the particles as spheres without any visualization of
the springs.
This class has no public constructor; instead use the AddToBuilder() static
method to create and add it to a DiagramBuilder directly.
*/
class ClothSpringModelGeometry final : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ClothSpringModelGeometry);
/** Creates, adds, and connects a ClothSpringModelGeometry system into the
given `builder`. Both the `cloth_spring_model` and `scene_graph` systems
must have been added to the given `builder` already.
The `scene_graph` pointer is not retained by the %ClothSpringModelGeometry
system. The return value pointer is an alias of the new
%ClothSpringModelGeometry system that is owned by the `builder`.
@throws std::exception if @p cloth_spring_model or @p scene_graph is not
already added to the given @p builder.
*/
static const ClothSpringModelGeometry& AddToBuilder(
systems::DiagramBuilder<double>* builder,
const ClothSpringModel<double>& cloth_spring_model,
geometry::SceneGraph<double>* scene_graph);
private:
ClothSpringModelGeometry(geometry::SceneGraph<double>* scene_graph,
int num_particles, double h);
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 identifier for each particle's frame.
std::vector<geometry::FrameId> frame_ids_;
// Number of particles.
int num_particles_{};
double particle_radius_{};
};
} // namespace mass_spring_cloth
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/mass_spring_cloth/cloth_spring_model_geometry.cc | #include "drake/examples/mass_spring_cloth/cloth_spring_model_geometry.h"
#include <memory>
#include <utility>
#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"
namespace drake {
namespace examples {
namespace mass_spring_cloth {
using Eigen::Vector3d;
using Eigen::Vector4d;
const ClothSpringModelGeometry& ClothSpringModelGeometry::AddToBuilder(
systems::DiagramBuilder<double>* builder,
const ClothSpringModel<double>& cloth_spring_model,
geometry::SceneGraph<double>* scene_graph) {
DRAKE_THROW_UNLESS(builder != nullptr);
DRAKE_THROW_UNLESS(scene_graph != nullptr);
auto cloth_spring_model_geometry = builder->AddSystem(
std::unique_ptr<ClothSpringModelGeometry>(new ClothSpringModelGeometry(
scene_graph, cloth_spring_model.num_particles(),
cloth_spring_model.h())));
builder->Connect(cloth_spring_model.get_output_port(0),
cloth_spring_model_geometry->get_input_port(0));
builder->Connect(cloth_spring_model_geometry->get_output_port(0),
scene_graph->get_source_pose_port(
cloth_spring_model_geometry->source_id_));
return *cloth_spring_model_geometry;
}
ClothSpringModelGeometry::ClothSpringModelGeometry(
geometry::SceneGraph<double>* scene_graph, int num_particles, double h)
: num_particles_(num_particles),
// We set particle radius to be 80% of the gap between particles for
// pleasing visual effects.
particle_radius_(h * 0.8) {
DRAKE_THROW_UNLESS(scene_graph != nullptr);
source_id_ = scene_graph->RegisterSource();
this->DeclareInputPort("particle_positions", systems::kVectorValued,
num_particles * 3);
this->DeclareAbstractOutputPort(
"geometry_pose", &ClothSpringModelGeometry::OutputGeometryPose);
frame_ids_.resize(num_particles);
for (int i = 0; i < num_particles; ++i) {
frame_ids_[i] = scene_graph->RegisterFrame(
source_id_, geometry::GeometryFrame("particle" + std::to_string(i)));
// Attach a sphere to the frame for simple visualization of the particles.
const geometry::GeometryId id = scene_graph->RegisterGeometry(
source_id_, frame_ids_[i],
std::make_unique<geometry::GeometryInstance>(
math::RigidTransformd::Identity(),
std::make_unique<geometry::Sphere>(particle_radius_),
"sphere_visual"));
scene_graph->AssignRole(
source_id_, id,
geometry::MakePhongIllustrationProperties(Vector4d(1, 0, 1, 1)));
}
}
void ClothSpringModelGeometry::OutputGeometryPose(
const systems::Context<double>& context,
geometry::FramePoseVector<double>* poses) const {
for (int i = 0; i < num_particles_; ++i) {
DRAKE_DEMAND(frame_ids_[i].is_valid());
}
const auto& input = get_input_port(0).Eval(context);
poses->clear();
// Set the frames to the positions of the particles.
for (int i = 0; i < static_cast<int>(frame_ids_.size()); ++i) {
const double x = input(3 * i);
const double y = input(3 * i + 1);
const double z = input(3 * i + 2);
const math::RigidTransformd pose(Vector3d(x, y, z));
poses->set_value(frame_ids_[i], pose);
}
}
} // namespace mass_spring_cloth
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples/mass_spring_cloth | /home/johnshepherd/drake/examples/mass_spring_cloth/test/cloth_spring_model_test.cc | #include "drake/examples/mass_spring_cloth/cloth_spring_model.h"
#include <gtest/gtest.h>
#include "drake/systems/analysis/simulator.h"
namespace drake {
namespace examples {
namespace mass_spring_cloth {
namespace {
class ContinuousClothSpringModelTest : public ::testing::Test {
protected:
void SetUp() override {
const int nx = 5;
const int ny = 5;
const double h = 0.05;
const double dt = -1; // Continuous system is run when dt <= 0.
dut_ = std::make_unique<ClothSpringModel<double>>(nx, ny, h, dt);
context_ = dut_->CreateDefaultContext();
}
std::unique_ptr<ClothSpringModel<double>> dut_; //< The device under test.
std::unique_ptr<systems::Context<double>> context_;
};
TEST_F(ContinuousClothSpringModelTest, Simulate) {
// Simulate to t_final = 0.01 and make sure sim does not crash.
const double t_final = 0.01;
drake::systems::Simulator<double> simulator(*dut_, std::move(context_));
simulator.Initialize();
simulator.AdvanceTo(t_final);
EXPECT_EQ(simulator.get_context().get_time(), t_final);
}
class DiscreteClothSpringModelTest : public ::testing::Test {
protected:
void SetUp() override {
const int nx = 5;
const int ny = 5;
const double h = 0.05;
const double dt = 0.01;
dut_ = std::make_unique<ClothSpringModel<double>>(nx, ny, h, dt);
context_ = dut_->CreateDefaultContext();
}
std::unique_ptr<ClothSpringModel<double>> dut_; // The device under test.
std::unique_ptr<systems::Context<double>> context_;
};
TEST_F(DiscreteClothSpringModelTest, Simulate) {
// Simulate to t_final = 10 time steps and make sure sim does not crash and
// that the solver is converging. Advance to a few time steps away from
// initial condition for a more non-trivial setup.
const double t_final = 0.1;
dut_->set_linear_solve_accuracy(std::numeric_limits<double>::epsilon());
drake::systems::Simulator<double> simulator(*dut_, std::move(context_));
simulator.Initialize();
simulator.AdvanceTo(t_final);
// The linear solver should converge even at the tight accuracy we set
// because the default max number of iterations is equal to the size of the
// linear system. Therefore the sim should not crash.
EXPECT_EQ(simulator.get_context().get_time(), t_final);
}
} // namespace
} // namespace mass_spring_cloth
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/manipulation_station/end_effector_teleop_dualshock4.py | """
Runs manipulation_station example with Sony DualShock4 Controller for
teleoperating the end effector.
"""
import argparse
from enum import Enum
import os
import pprint
import sys
from textwrap import dedent
import webbrowser
import numpy as np
from pydrake.common.value import Value
from pydrake.examples import (
ManipulationStation, ManipulationStationHardwareInterface,
CreateClutterClearingYcbObjectList, SchunkCollisionModel)
from pydrake.geometry import DrakeVisualizer, Meshcat, MeshcatVisualizer
from pydrake.math import RigidTransform, RollPitchYaw, RotationMatrix
from pydrake.multibody.inverse_kinematics import (
DifferentialInverseKinematicsIntegrator,
DifferentialInverseKinematicsParameters)
from pydrake.multibody.plant import MultibodyPlant
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import DiagramBuilder, LeafSystem
from pydrake.systems.primitives import FirstOrderLowPassFilter
# On macOS, our setup scripts do not provide pygame so we need to skip this
# program and its tests. On Ubuntu, we do expect to have pygame.
if sys.platform == "darwin":
try:
import pygame
from pygame.locals import *
except ImportError:
print("ERROR: missing pygame. "
"Please install pygame to use this example.")
sys.exit(0)
else:
import pygame
from pygame.locals import *
def initialize_joystick(joystick_id):
assert isinstance(joystick_id, (int, type(None)))
pygame.init()
try:
pygame.joystick.init()
if joystick_id is None:
count = pygame.joystick.get_count()
if count != 1:
raise RuntimeError(
f"joystick_id=None, but there are {count} joysticks "
f"plugged in. Please specify --joystick_id, or ensure "
f"that exactly 1 joystick is plugged in")
joystick_id = 0
joystick = pygame.joystick.Joystick(joystick_id)
joystick.init()
return joystick
except pygame.error as e:
raise Exception("Make sure dualshock 4 controller is connected. "
"Controller initialization failed "
f"with: {e}")
class DS4Buttons(Enum):
X_BUTTON = 0
O_BUTTON = 1
TRIANGLE_BUTTON = 2
SQUARE_BUTTON = 3
L1_BUTTON = 4
R1_BUTTON = 5
L2_BUTTON = 6
R2_BUTTON = 7
class DS4Axis(Enum):
LEFTJOY_UP_DOWN = 0
LEFTJOY_LEFT_RIGHT = 1
RIGHTJOY_LEFT_RIGHT = 2
RIGHTJOY_UP_DOWN = 3
def print_instructions():
instructions = '''\
END EFFECTOR CONTROL
-----------------------------------------
+/- x-axis - leftjoy left / right
+/- y-axis - leftjoy up / down
+/- roll - rightjoy up / down
+/- pitch - rightjoy left / right
+/- z-axis - l2 / r2
+/- yaw - l1 / r1
GRIPPER CONTROL
-----------------------------------------
open / close - square / circle (O)
-----------------------------------------
x button - quit
'''
print(dedent(instructions))
class TeleopDualShock4Manager:
def __init__(self, joystick):
self._joystick = joystick
self._axis_data = list()
self._button_data = list()
self._name = joystick.get_name()
print(f"Using Joystick: {self._name}")
for i in range(self._joystick.get_numbuttons()):
self._button_data.append(False)
for i in range(self._joystick.get_numaxes()):
self._axis_data.append(0.0)
def get_events(self):
for event in pygame.event.get():
if event.type == pygame.JOYAXISMOTION:
self._axis_data[event.axis] = round(event.value, 2)
if event.type == pygame.JOYBUTTONDOWN:
self._button_data[event.button] = True
if event.type == pygame.JOYBUTTONUP:
self._button_data[event.button] = False
events = dict()
# For example mappings, see:
# https://www.pygame.org/docs/ref/joystick.html#controller-mappings
if self._name == "Logitech Logitech Dual Action":
events[DS4Axis.LEFTJOY_LEFT_RIGHT] = self._axis_data[0]
events[DS4Axis.LEFTJOY_UP_DOWN] = self._axis_data[1]
events[DS4Axis.RIGHTJOY_LEFT_RIGHT] = self._axis_data[2]
events[DS4Axis.RIGHTJOY_UP_DOWN] = self._axis_data[3]
else:
events[DS4Axis.LEFTJOY_UP_DOWN] = self._axis_data[0]
events[DS4Axis.LEFTJOY_LEFT_RIGHT] = self._axis_data[1]
events[DS4Axis.RIGHTJOY_LEFT_RIGHT] = self._axis_data[3]
events[DS4Axis.RIGHTJOY_UP_DOWN] = self._axis_data[4]
events[DS4Buttons.X_BUTTON] = self._button_data[0]
events[DS4Buttons.O_BUTTON] = self._button_data[1]
events[DS4Buttons.SQUARE_BUTTON] = self._button_data[3]
events[DS4Buttons.L1_BUTTON] = self._button_data[4]
events[DS4Buttons.R1_BUTTON] = self._button_data[5]
events[DS4Buttons.L2_BUTTON] = self._button_data[6]
events[DS4Buttons.R2_BUTTON] = self._button_data[7]
# TODO(eric.cousineau): Replace `sys.exit` with a status to
# the Systems Framework.
if events[DS4Buttons.X_BUTTON]:
sys.exit(0)
return events
class DualShock4Teleop(LeafSystem):
def __init__(self, joystick):
LeafSystem.__init__(self)
# Note: Disable caching because the teleop manager has undeclared
# state.
self.DeclareVectorOutputPort(
"rpy_xyz", 6, self.DoCalcOutput).disable_caching_by_default()
self.DeclareVectorOutputPort(
"position", 1,
self.CalcPositionOutput).disable_caching_by_default()
self.DeclareVectorOutputPort("force_limit", 1,
self.CalcForceLimitOutput)
# Note: This timing affects the keyboard teleop performance. A larger
# time step causes more lag in the response.
self.DeclarePeriodicPublishEvent(1.0, 0.0, lambda _: None)
self.teleop_manager = TeleopDualShock4Manager(joystick)
self.roll = self.pitch = self.yaw = 0
self.x = self.y = self.z = 0
self.gripper_max = 0.107
self.gripper_min = 0.01
self.gripper_goal = self.gripper_max
def SetPose(self, pose):
"""
@param pose is a RigidTransform or else any type accepted by
RigidTransform's constructor
"""
tf = RigidTransform(pose)
self.SetRPY(RollPitchYaw(tf.rotation()))
self.SetXYZ(pose.translation())
def SetRPY(self, rpy):
"""
@param rpy is a RollPitchYaw object
"""
self.roll = rpy.roll_angle()
self.pitch = rpy.pitch_angle()
self.yaw = rpy.yaw_angle()
def SetXYZ(self, xyz):
"""
@param xyz is a 3 element vector of x, y, z.
"""
self.x = xyz[0]
self.y = xyz[1]
self.z = xyz[2]
def SetXyzFromEvents(self, events):
scale = 0.00005
delta_x = scale * events[DS4Axis.LEFTJOY_UP_DOWN]
delta_y = -scale * events[DS4Axis.LEFTJOY_LEFT_RIGHT]
delta_z = 0.0
if events[DS4Buttons.L2_BUTTON]:
delta_z += scale
if events[DS4Buttons.R2_BUTTON]:
delta_z -= scale
self.x += delta_x
self.y += delta_y
self.z += delta_z
def SetRpyFromEvents(self, events):
roll_scale = 0.0001
delta_roll = -roll_scale * events[DS4Axis.RIGHTJOY_LEFT_RIGHT]
self.roll = np.clip(self.roll + delta_roll,
a_min=-2*np.pi, a_max=2*np.pi)
pitch_scale = 0.0001
delta_pitch = pitch_scale * events[DS4Axis.RIGHTJOY_UP_DOWN]
self.pitch = np.clip(self.pitch + delta_pitch,
a_min=-2*np.pi, a_max=2*np.pi)
yaw_scale = 0.0003
if events[DS4Buttons.L1_BUTTON]:
self.yaw += yaw_scale
if events[DS4Buttons.R1_BUTTON]:
self.yaw -= yaw_scale
self.yaw = np.clip(self.yaw, a_min=-2*np.pi, a_max=2*np.pi)
def SetGripperFromEvents(self, events):
gripper_scale = 0.00005
self.gripper_goal += (gripper_scale * events[DS4Buttons.SQUARE_BUTTON])
self.gripper_goal -= (gripper_scale * events[DS4Buttons.O_BUTTON])
self.gripper_goal = np.clip(self.gripper_goal,
a_min=self.gripper_min,
a_max=self.gripper_max)
def CalcPositionOutput(self, context, output):
output.SetAtIndex(0, self.gripper_goal)
def CalcForceLimitOutput(self, context, output):
self._force_limit = 40
output.SetAtIndex(0, self._force_limit)
def DoCalcOutput(self, context, output):
events = self.teleop_manager.get_events()
self.SetXyzFromEvents(events)
self.SetRpyFromEvents(events)
self.SetGripperFromEvents(events)
output.SetAtIndex(0, self.roll)
output.SetAtIndex(1, self.pitch)
output.SetAtIndex(2, self.yaw)
output.SetAtIndex(3, self.x)
output.SetAtIndex(4, self.y)
output.SetAtIndex(5, self.z)
class ToPose(LeafSystem):
def __init__(self, grab_focus=True):
LeafSystem.__init__(self)
self.DeclareVectorInputPort("rpy_xyz", 6)
self.DeclareAbstractOutputPort(
"pose", lambda: Value(RigidTransform()),
self.DoCalcOutput)
def DoCalcOutput(self, context, output):
rpy_xyz = self.get_input_port().Eval(context)
output.set_value(RigidTransform(RollPitchYaw(rpy_xyz[:3]),
rpy_xyz[3:]))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--target_realtime_rate", type=float, default=1.0,
help="Desired rate relative to real time. See documentation for "
"Simulator::set_target_realtime_rate() for details.")
parser.add_argument(
"--duration", type=float, default=np.inf,
help="Desired duration of the simulation in seconds.")
parser.add_argument(
"--hardware", action='store_true',
help="Use the ManipulationStationHardwareInterface instead of an "
"in-process simulation.")
parser.add_argument(
"--joystick_id", type=int, default=None,
help="Joystick ID to use (0..N-1). If not specified, then only one "
"joystick must be plugged in, and that joystick will be used.")
parser.add_argument(
"--test", action='store_true',
help="Disable opening the gui window for testing.")
parser.add_argument(
"--time_step", type=float, default=0.005,
help="Time constant for the differential IK solver and first order"
"low pass filter applied to the teleop commands")
parser.add_argument(
"--velocity_limit_factor", type=float, default=1.0,
help="This value, typically between 0 and 1, further limits the "
"iiwa14 joint velocities. It multiplies each of the seven "
"pre-defined joint velocity limits. "
"Note: The pre-defined velocity limits are specified by "
"iiwa14_velocity_limits, found in this python file.")
parser.add_argument(
'--setup', type=str, default='manipulation_class',
help="The manipulation station setup to simulate. ",
choices=['manipulation_class', 'clutter_clearing'])
parser.add_argument(
'--schunk_collision_model', type=str, default='box',
help="The Schunk collision model to use for simulation. ",
choices=['box', 'box_plus_fingertip_spheres'])
parser.add_argument(
"--meshcat", action="store_true", default=False,
help="Enable visualization with meshcat.")
parser.add_argument(
"-w", "--open-window", dest="browser_new",
action="store_const", const=1, default=None,
help="Open the MeshCat display in a new browser window.")
args = parser.parse_args()
if (args.browser_new is not None) and (not args.meshcat):
parser.error(
"-w / --show-window is only valid in conjunction with --meshcat")
if args.test:
# Don't grab mouse focus during testing.
# See: https://stackoverflow.com/a/52528832/7829525
os.environ["SDL_VIDEODRIVER"] = "dummy"
builder = DiagramBuilder()
if args.hardware:
station = builder.AddSystem(ManipulationStationHardwareInterface())
station.Connect(wait_for_cameras=False)
else:
station = builder.AddSystem(ManipulationStation())
if args.schunk_collision_model == "box":
schunk_model = SchunkCollisionModel.kBox
elif args.schunk_collision_model == "box_plus_fingertip_spheres":
schunk_model = SchunkCollisionModel.kBoxPlusFingertipSpheres
# Initializes the chosen station type.
if args.setup == 'manipulation_class':
station.SetupManipulationClassStation(
schunk_model=schunk_model)
station.AddManipulandFromFile(
"drake_models/manipulation_station/061_foam_brick.sdf",
RigidTransform(RotationMatrix.Identity(), [0.6, 0, 0]))
elif args.setup == 'clutter_clearing':
station.SetupClutterClearingStation(
schunk_model=schunk_model)
ycb_objects = CreateClutterClearingYcbObjectList()
for model_file, X_WObject in ycb_objects:
station.AddManipulandFromFile(model_file, X_WObject)
station.Finalize()
query_port = station.GetOutputPort("query_object")
DrakeVisualizer.AddToBuilder(builder, query_port)
if args.meshcat:
meshcat = Meshcat()
MeshcatVisualizer.AddToBuilder(
builder=builder,
query_object_port=query_port,
meshcat=meshcat)
if args.setup == 'planar':
meshcat.Set2dRenderMode()
if args.browser_new is not None:
url = meshcat.web_url()
webbrowser.open(url=url, new=args.browser_new)
robot = station.get_controller_plant()
params = DifferentialInverseKinematicsParameters(robot.num_positions(),
robot.num_velocities())
params.set_time_step(args.time_step)
# True velocity limits for the IIWA14 (in rad/s, rounded down to the first
# decimal)
iiwa14_velocity_limits = np.array([1.4, 1.4, 1.7, 1.3, 2.2, 2.3, 2.3])
# Stay within a small fraction of those limits for this teleop demo.
factor = args.velocity_limit_factor
params.set_joint_velocity_limits((-factor*iiwa14_velocity_limits,
factor*iiwa14_velocity_limits))
differential_ik = builder.AddSystem(
DifferentialInverseKinematicsIntegrator(
robot, robot.GetFrameByName("iiwa_link_7"), args.time_step,
params))
builder.Connect(differential_ik.GetOutputPort("joint_positions"),
station.GetInputPort("iiwa_position"))
joystick = initialize_joystick(args.joystick_id)
teleop = builder.AddSystem(DualShock4Teleop(joystick))
filter_ = builder.AddSystem(
FirstOrderLowPassFilter(time_constant=args.time_step, size=6))
builder.Connect(teleop.get_output_port(0), filter_.get_input_port(0))
to_pose = builder.AddSystem(ToPose())
builder.Connect(filter_.get_output_port(0),
to_pose.get_input_port())
builder.Connect(to_pose.get_output_port(),
differential_ik.GetInputPort("X_WE_desired"))
builder.Connect(teleop.GetOutputPort("position"), station.GetInputPort(
"wsg_position"))
builder.Connect(teleop.GetOutputPort("force_limit"),
station.GetInputPort("wsg_force_limit"))
diagram = builder.Build()
simulator = Simulator(diagram)
# This is important to avoid duplicate publishes to the hardware interface:
simulator.set_publish_every_time_step(False)
station_context = diagram.GetMutableSubsystemContext(
station, simulator.get_mutable_context())
station.GetInputPort("iiwa_feedforward_torque").FixValue(
station_context, np.zeros(7))
# If the diagram is only the hardware interface, then we must advance it a
# little bit so that first LCM messages get processed. A simulated plant is
# already publishing correct positions even without advancing, and indeed
# we must not advance a simulated plant until the sliders and filters have
# been initialized to match the plant.
if args.hardware:
simulator.AdvanceTo(1e-6)
q0 = station.GetOutputPort("iiwa_position_measured").Eval(station_context)
differential_ik.get_mutable_parameters().set_nominal_joint_position(q0)
differential_ik.SetPositions(
differential_ik.GetMyMutableContextFromRoot(
simulator.get_mutable_context()), q0)
teleop.SetPose(
differential_ik.ForwardKinematics(
differential_ik.GetMyContextFromRoot(simulator.get_context())))
filter_.set_initial_output_value(
diagram.GetMutableSubsystemContext(
filter_, simulator.get_mutable_context()),
teleop.get_output_port(0).Eval(diagram.GetMutableSubsystemContext(
teleop, simulator.get_mutable_context())))
simulator.set_target_realtime_rate(args.target_realtime_rate)
print_instructions()
simulator.AdvanceTo(args.duration)
if __name__ == '__main__':
main()
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/manipulation_station/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",
"drake_py_library",
)
load("//tools/skylark:test_tags.bzl", "vtk_test_tags")
package(default_visibility = ["//visibility:private"])
drake_cc_library(
name = "manipulation_station",
srcs = [
"manipulation_station.cc",
],
hdrs = [
"manipulation_station.h",
],
data = [
"//examples/kuka_iiwa_arm:models",
"@drake_models//:iiwa_description",
"@drake_models//:manipulation_station",
"@drake_models//:realsense2_description",
"@drake_models//:wsg_50_description",
"@drake_models//:ycb",
],
visibility = ["//visibility:public"],
deps = [
"//common:find_resource",
"//geometry:scene_graph",
"//geometry/render_vtk",
"//manipulation/schunk_wsg:schunk_wsg_constants",
"//manipulation/schunk_wsg:schunk_wsg_position_controller",
"//math:geometric_transform",
"//multibody/parsing",
"//multibody/plant",
"//perception:depth_image_to_point_cloud",
"//systems/controllers:inverse_dynamics_controller",
"//systems/framework",
"//systems/primitives",
"//systems/sensors:rgbd_sensor",
],
)
drake_cc_library(
name = "manipulation_station_hardware_interface",
srcs = [
"manipulation_station_hardware_interface.cc",
],
hdrs = [
"manipulation_station_hardware_interface.h",
],
data = [
"@drake_models//:iiwa_description",
"@drake_models//:wsg_50_description",
],
visibility = ["//visibility:public"],
deps = [
"//lcm",
"//manipulation/kuka_iiwa:iiwa_command_sender",
"//manipulation/kuka_iiwa:iiwa_status_receiver",
"//manipulation/schunk_wsg:schunk_wsg_lcm",
"//multibody/parsing",
"//multibody/plant",
"//systems/framework",
"//systems/lcm",
"//systems/primitives",
"//systems/sensors:lcm_image_array_to_images",
],
)
drake_cc_binary(
name = "mock_station_simulation",
srcs = [
"mock_station_simulation.cc",
],
add_test_rule = 1,
test_rule_args = [
"--target_realtime_rate=0.0",
"--duration=0.1",
],
test_rule_tags = vtk_test_tags(),
deps = [
":manipulation_station",
"//geometry:drake_visualizer",
"//lcm",
"//manipulation/kuka_iiwa:iiwa_command_receiver",
"//manipulation/kuka_iiwa:iiwa_status_sender",
"//manipulation/schunk_wsg:schunk_wsg_lcm",
"//perception:point_cloud_to_lcm",
"//systems/analysis:simulator",
"//systems/lcm",
"//systems/sensors:image_to_lcm_image_array_t",
"@gflags",
],
)
drake_cc_binary(
name = "proof_of_life",
srcs = [
"proof_of_life.cc",
],
add_test_rule = 1,
test_rule_args = [
"--target_realtime_rate=0.0",
"--duration=0.1",
"--test",
],
test_rule_tags = vtk_test_tags(),
test_rule_timeout = "moderate",
deps = [
":manipulation_station",
"//geometry:drake_visualizer",
"//multibody/plant:contact_results_to_lcm",
"//systems/analysis:simulator",
"//systems/sensors:image_to_lcm_image_array_t",
"@gflags",
],
)
# Tests
drake_cc_googletest(
name = "manipulation_station_test",
# Frequently exceeds short timeout in coverage builds.
timeout = "moderate",
tags = vtk_test_tags(),
deps = [
":manipulation_station",
"//common/test_utilities:eigen_matrix_compare",
"//common/test_utilities:expect_no_throw",
"//geometry/test_utilities:dummy_render_engine",
],
)
drake_cc_googletest(
name = "manipulation_station_hardware_interface_test",
deps = [
":manipulation_station_hardware_interface",
"//systems/sensors:image",
],
)
# Python examples
drake_py_library(
name = "schunk_wsg_buttons",
srcs = ["schunk_wsg_buttons.py"],
deps = [
"//bindings/pydrake",
],
)
drake_py_binary(
name = "joint_teleop",
srcs = ["joint_teleop.py"],
add_test_rule = 1,
test_rule_args = [
"--target_realtime_rate=0.0",
"--duration=0.1",
"--test",
],
test_rule_tags = vtk_test_tags(),
test_rule_timeout = "moderate", # Frequently exceeds short timeout in dbg.
deps = [
":schunk_wsg_buttons",
"//bindings/pydrake",
],
)
drake_py_binary(
name = "end_effector_teleop_dualshock4",
srcs = ["end_effector_teleop_dualshock4.py"],
add_test_rule = 1,
test_rule_args = [
"--target_realtime_rate=0.0",
"--duration=0.1",
"--test",
],
# Disable testing for this module since it will fail on CI
# because it assumes that dualshock4 controller is connected.
test_rule_tags = vtk_test_tags() + ["manual"],
test_rule_timeout = "moderate", # Frequently exceeds short timeout in dbg.
deps = [
"//bindings/pydrake",
],
)
drake_py_binary(
name = "end_effector_teleop_mouse",
srcs = ["end_effector_teleop_mouse.py"],
add_test_rule = 1,
test_rule_args = [
"--target_realtime_rate=0.0",
"--duration=0.1",
"--test",
],
test_rule_tags = vtk_test_tags(),
test_rule_timeout = "moderate", # Frequently exceeds short timeout in dbg.
deps = [
"//bindings/pydrake",
],
)
drake_py_binary(
name = "end_effector_teleop_sliders",
srcs = ["end_effector_teleop_sliders.py"],
add_test_rule = 1,
test_rule_args = [
"--target_realtime_rate=0.0",
"--duration=0.1",
"--test",
],
test_rule_tags = vtk_test_tags(),
test_rule_timeout = "moderate", # Frequently exceeds short timeout in dbg.
deps = [
":schunk_wsg_buttons",
"//bindings/pydrake",
],
)
drake_py_binary(
name = "print_station_context",
srcs = ["print_station_context.py"],
add_test_rule = 1,
deps = [
"//bindings/pydrake",
],
)
add_lint_tests(enable_clang_format_lint = False)
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/manipulation_station/manipulation_station.h | #pragma once
#include <list>
#include <map>
#include <memory>
#include <optional>
#include <string>
#include <vector>
#include "drake/common/eigen_types.h"
#include "drake/geometry/render/render_engine.h"
#include "drake/geometry/scene_graph.h"
#include "drake/math/rigid_transform.h"
#include "drake/multibody/plant/multibody_plant.h"
#include "drake/systems/framework/diagram.h"
namespace drake {
namespace examples {
namespace manipulation_station {
/// Determines which sdf is loaded for the IIWA in the ManipulationStation.
enum class IiwaCollisionModel { kNoCollision, kBoxCollision };
/// Determines which schunk model is used for the ManipulationStation.
/// - kBox loads a model with a box collision geometry. This model is for those
/// who want simplified collision behavior.
/// - kBoxPlusFingertipSpheres loads a Schunk model with collision
/// spheres that models the indentations at tip of the fingers, in addition
/// to the box collision geometry on the fingers.
enum class SchunkCollisionModel { kBox, kBoxPlusFingertipSpheres };
/// Determines which manipulation station is simulated.
enum class Setup { kNone, kManipulationClass, kClutterClearing, kPlanarIiwa };
/// @defgroup manipulation_station_systems Manipulation Station
/// @{
/// @brief Systems related to the "manipulation station" used in the <a
/// href="https://manipulation.csail.mit.edu">MIT Intelligent Robot
/// Manipulation</a> class.
/// @ingroup example_systems
/// @}
/// A system that represents the complete manipulation station, including
/// exactly one robotic arm (a Kuka IIWA LWR), one gripper (a Schunk WSG 50),
/// and anything a user might want to load into the model.
/// SetupDefaultStation() provides the setup that is used in the MIT
/// Intelligent Robot Manipulation class, which includes the supporting
/// structure for IIWA and several RGBD cameras. Alternative Setup___()
/// methods are provided, as well.
///
/// @system
/// name: ManipulationStation
/// input_ports:
/// - iiwa_position
/// - iiwa_feedforward_torque (optional)
/// - wsg_position
/// - wsg_force_limit (optional)
/// - <b style="color:orange">applied_spatial_force (optional)</b>
/// output_ports:
/// - iiwa_position_commanded
/// - iiwa_position_measured
/// - iiwa_velocity_estimated
/// - iiwa_state_estimated
/// - iiwa_torque_commanded
/// - iiwa_torque_measured
/// - iiwa_torque_external
/// - wsg_state_measured
/// - wsg_force_measured
/// - camera_[NAME]_rgb_image
/// - camera_[NAME]_depth_image
/// - <b style="color:orange">camera_[NAME]_label_image</b>
/// - <b style="color:orange">camera_[NAME]_point_cloud</b>
/// - ...
/// - camera_[NAME]_rgb_image
/// - camera_[NAME]_depth_image
/// - <b style="color:orange">camera_[NAME]_label_image</b>
/// - <b style="color:orange">camera_[NAME]_point_cloud</b>
/// - <b style="color:orange">query_object</b>
/// - <b style="color:orange">contact_results</b>
/// - <b style="color:orange">plant_continuous_state</b>
/// - <b style="color:orange">geometry_poses</b>
/// @endsystem
///
/// Each pixel in the output image from `depth_image` is a 16bit unsigned
/// short in millimeters.
///
/// Note that outputs in <b style="color:orange">orange</b> are
/// available in the simulation, but not on the real robot. The distinction
/// between q_measured and v_estimated is because the Kuka FRI reports
/// positions directly, but we have estimated v in our code that wraps the
/// FRI.
///
/// @warning The "camera_[NAME]_point_cloud" data currently has registration
/// errors per issue https://github.com/RobotLocomotion/drake/issues/12125.
///
/// Consider the robot dynamics
/// M(q)vdot + C(q,v)v = τ_g(q) + τ_commanded + τ_joint_friction + τ_external,
/// where q == position, v == velocity, and τ == torque.
///
/// This model of the IIWA internal controller in the FRI software's
/// `JointImpedanceControlMode` is:
/// <pre>
/// τ_commanded = Mₑ(qₑ)vdot_desired + Cₑ(qₑ, vₑ)vₑ - τₑ_g(q) -
/// τₑ_joint_friction + τ_feedforward
/// vdot_desired = PID(q_commanded, qₑ, v_commanded, vₑ)
/// </pre>
/// where Mₑ, Cₑ, τₑ_g, and τₑ_friction terms are now (Kuka's) estimates of the
/// true model, qₑ and vₑ are measured/estimation, and v_commanded
/// must be obtained from an online (causal) derivative of q_commanded. The
/// result is
/// <pre>
/// M(q)vdot ≈ Mₑ(q)vdot_desired + τ_feedforward + τ_external,
/// </pre>
/// where the "approximately equal" comes from the differences due to the
/// estimated model/state.
///
/// The model implemented in this System assumes that M, C, and τ_friction
/// terms are perfect (except that they contain only a lumped mass
/// approximation of the gripper), and that the measured signals are
/// noise/bias free (e.g. q_measured = q, v_estimated = v, τ_measured =
/// τ_commanded). What remains for τ_external is the generalized forces due
/// to contact (note that they could also include the missing contributions
/// from the gripper fingers, which the controller assumes are welded).
/// @see lcmt_iiwa_status.lcm for additional details/documentation.
///
///
/// To add objects into the environment for the robot to manipulate, use,
/// e.g.:
/// @code
/// ManipulationStation<double> station;
/// Parser parser(&station.get_mutable_multibody_plant(),
/// &station.get_mutable_scene_graph());
/// parser.AddModels("my.sdf");
/// ...
/// // coming soon -- sugar API for adding additional objects.
/// station.Finalize()
/// @endcode
/// Note that you *must* call Finalize() before you can use this class as a
/// System.
///
/// @tparam_double_only
/// @ingroup manipulation_station_systems
template <typename T>
class ManipulationStation : public systems::Diagram<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ManipulationStation)
/// Construct the EMPTY station model.
///
/// @param time_step The time step used by MultibodyPlant<T>, and by the
/// discrete derivative used to approximate velocity from the position
/// command inputs.
explicit ManipulationStation(double time_step = 0.002);
/// Adds a default iiwa, wsg, two bins, and a camera, then calls
/// RegisterIiwaControllerModel() and RegisterWsgControllerModel() with
/// the appropriate arguments.
/// @note Must be called before Finalize().
/// @note Only one of the `Setup___()` methods should be called.
/// @param X_WCameraBody Transformation between the world and the camera body.
/// @param collision_model Determines which sdf is loaded for the IIWA.
/// @param schunk_model Determines which sdf is loaded for the Schunk.
void SetupClutterClearingStation(
const std::optional<const math::RigidTransformd>& X_WCameraBody = {},
IiwaCollisionModel collision_model = IiwaCollisionModel::kNoCollision,
SchunkCollisionModel schunk_model = SchunkCollisionModel::kBox);
/// Adds a default iiwa, wsg, cupboard, and 80/20 frame for the MIT
/// Intelligent Robot Manipulation class, then calls
/// RegisterIiwaControllerModel() and RegisterWsgControllerModel() with
/// the appropriate arguments.
/// @note Must be called before Finalize().
/// @note Only one of the `Setup___()` methods should be called.
/// @param collision_model Determines which sdf is loaded for the IIWA.
/// @param schunk_model Determines which sdf is loaded for the Schunk.
void SetupManipulationClassStation(
IiwaCollisionModel collision_model = IiwaCollisionModel::kNoCollision,
SchunkCollisionModel schunk_model = SchunkCollisionModel::kBox);
/// Adds a version of the iiwa with joints that would result in
/// out-of-plane rotations welded in a fixed orientation, reducing the
/// total degrees of freedom of the arm to 3. This arm lives in the X-Z
/// plane. Also adds the WSG planar gripper and two tables to form the
/// workspace. Note that additional floating base objects (aka
/// manipulands) will still potentially move in 3D.
/// @note Must be called before Finalize().
/// @note Only one of the `Setup___()` methods should be called.
/// @param schunk_model Determines which sdf is loaded for the Schunk.
void SetupPlanarIiwaStation(
SchunkCollisionModel schunk_model = SchunkCollisionModel::kBox);
/// Sets the default State for the chosen setup.
/// @param context A const reference to the ManipulationStation context.
/// @param state A pointer to the State of the ManipulationStation system.
/// @pre `state` must be the systems::State<T> object contained in
/// `station_context`.
void SetDefaultState(const systems::Context<T>& station_context,
systems::State<T>* state) const override;
/// Sets a random State for the chosen setup.
/// @param context A const reference to the ManipulationStation context.
/// @param state A pointer to the State of the ManipulationStation system.
/// @param generator is the random number generator.
/// @pre `state` must be the systems::State<T> object contained in
/// `station_context`.
void SetRandomState(const systems::Context<T>& station_context,
systems::State<T>* state,
RandomGenerator* generator) const override;
/// Notifies the ManipulationStation that the IIWA robot model instance can
/// be identified by @p iiwa_instance as well as necessary information to
/// reload model for the internal controller's use. Assumes @p iiwa_instance
/// has already been added to the MultibodyPlant.
/// Note, the current implementation only allows @p parent_frame to be the
/// world frame. The IIWA frame needs to directly contain @p child_frame.
/// Only call this with custom IIWA models (i.e. not calling
/// SetupDefaultStation()). Must be called before Finalize().
/// @param model_path Full path to the model file.
/// @param iiwa_instance Identifies the IIWA model.
/// @param parent_frame Identifies frame P (the parent frame) in the
/// MultibodyPlant that the IIWA model has been attached to.
/// @param child_frame_name Identifies frame C (the child frame) in the IIWA
/// model that is welded to frame P.
/// @param X_PC Transformation between frame P and C.
/// @throws If @p parent_frame is not the world frame.
// TODO(siyuan.feng@tri.global): throws meaningful errors earlier here,
// rather than in Finalize() if the arguments are inconsistent with the plant.
// TODO(siyuan.feng@tri.global): remove the assumption that parent frame has
// to be world.
// TODO(siyuan.feng@tri.global): Some of these information should be
// retrievable from the MultibodyPlant directly or MultibodyPlant should
// provide partial tree cloning.
// TODO(jwnimmer-tri) The model_path should be a package URL, not a filename.
void RegisterIiwaControllerModel(
const std::string& model_path,
const multibody::ModelInstanceIndex iiwa_instance,
const multibody::Frame<T>& parent_frame,
const multibody::Frame<T>& child_frame,
const math::RigidTransform<double>& X_PC);
/// Notifies the ManipulationStation that the WSG gripper model instance can
/// be identified by @p wsg_instance, as well as necessary information to
/// reload model for the internal controller's use. Assumes @p wsg_instance
/// has already been added to the MultibodyPlant. The IIWA model needs to
/// directly contain @p parent_frame, and the WSG model needs to directly
/// contain @p child_frame.
/// Only call this with custom WSG models (i.e. not calling
/// SetupDefaultStation()). Must be called before Finalize().
/// @param model_path Full path to the model file.
/// @param wsg_instance Identifies the WSG model.
/// @param parent_frame Identifies frame P (the parent frame) in the
/// MultibodyPlant that the WSG model has been attached to. Has to be part
/// of the IIWA model.
/// @param child_frame Identifies frame C (the child frame) in the WSG
/// model that is used welded to frame P.
/// @param X_PC Transformation between frame P and C.
// TODO(siyuan.feng@tri.global): Some of these information should be
// retrievable from the MultibodyPlant directly or MultibodyPlant should
// provide partial tree cloning.
// TODO(siyuan.feng@tri.global): throws meaningful errors earlier here,
// rather than in Finalize() if the arguments are inconsistent with the plant.
void RegisterWsgControllerModel(
const std::string& model_path,
const multibody::ModelInstanceIndex wsg_instance,
const multibody::Frame<T>& parent_frame,
const multibody::Frame<T>& child_frame,
const math::RigidTransform<double>& X_PC);
/// Registers an RGBD sensor. Must be called before Finalize().
/// @param name Name for the camera.
/// @param parent_frame The parent frame (frame P). The body that
/// @p parent_frame is attached to must have a corresponding
/// geometry::FrameId. Otherwise, an exception will be thrown in Finalize().
/// @param X_PCameraBody Transformation between frame P and the camera body.
/// see systems::sensors:::RgbdSensor for descriptions about how the
/// camera body, RGB, and depth image frames are related.
/// @param depth_camera Specification for the RGBD camera. The color render
/// camera is inferred from the depth_camera. The color camera will share the
/// RenderCameraCore and be configured to *not* show its window.
/// @pydrake_mkdoc_identifier{single_camera}
void RegisterRgbdSensor(
const std::string& name, const multibody::Frame<T>& parent_frame,
const math::RigidTransform<double>& X_PCameraBody,
const geometry::render::DepthRenderCamera& depth_camera);
/// Registers an RGBD sensor with uniquely characterized color/label and
/// depth cameras.
/// @pydrake_mkdoc_identifier{dual_camera}
void RegisterRgbdSensor(
const std::string& name, const multibody::Frame<T>& parent_frame,
const math::RigidTransform<double>& X_PCameraBody,
const geometry::render::ColorRenderCamera& color_camera,
const geometry::render::DepthRenderCamera& depth_camera);
/// Adds a single object for the robot to manipulate
/// @note Must be called before Finalize().
/// @param model_file The path to the .sdf model file of the object.
/// @param X_WObject The pose of the object in world frame.
void AddManipulandFromFile(const std::string& model_file,
const math::RigidTransform<double>& X_WObject);
// TODO(russt): Add scalar copy constructor etc once we support more
// scalar types than T=double. See #9573.
/// Users *must* call Finalize() after making any additions to the
/// multibody plant and before using this class in the Systems framework.
/// This should be called exactly once.
/// This assumes an IIWA and WSG have been added to the MultibodyPlant, and
/// RegisterIiwaControllerModel() and RegisterWsgControllerModel() have been
/// called.
///
/// @see multibody::MultibodyPlant<T>::Finalize()
void Finalize();
/// Finalizes the station with the option of specifying the renderers the
/// manipulation station uses. Calling this method with an empty map is
/// equivalent to calling Finalize(). See Finalize() for more details.
void Finalize(std::map<std::string,
std::unique_ptr<geometry::render::RenderEngine>>
render_engines);
/// Returns a reference to the main plant responsible for the dynamics of
/// the robot and the environment. This can be used to, e.g., add
/// additional elements into the world before calling Finalize().
const multibody::MultibodyPlant<T>& get_multibody_plant() const {
return *plant_;
}
/// Returns a mutable reference to the main plant responsible for the
/// dynamics of the robot and the environment. This can be used to, e.g.,
/// add additional elements into the world before calling Finalize().
multibody::MultibodyPlant<T>& get_mutable_multibody_plant() {
return *plant_;
}
/// Returns a reference to the SceneGraph responsible for all of the geometry
/// for the robot and the environment. This can be used to, e.g., add
/// additional elements into the world before calling Finalize().
const geometry::SceneGraph<T>& get_scene_graph() const {
return *scene_graph_;
}
/// Returns a mutable reference to the SceneGraph responsible for all of the
/// geometry for the robot and the environment. This can be used to, e.g.,
/// add additional elements into the world before calling Finalize().
geometry::SceneGraph<T>& get_mutable_scene_graph() { return *scene_graph_; }
/// Returns the name of the station's default renderer.
static std::string default_renderer_name() { return default_renderer_name_; }
/// Return a reference to the plant used by the inverse dynamics controller
/// (which contains only a model of the iiwa + equivalent mass of the
/// gripper).
const multibody::MultibodyPlant<T>& get_controller_plant() const {
return *owned_controller_plant_;
}
/// Gets the number of joints in the IIWA (only -- does not include the
/// gripper).
/// @pre must call one of the "setup" methods first to register an IIWA
/// model.
int num_iiwa_joints() const;
/// Convenience method for getting all of the joint angles of the Kuka IIWA.
/// This does not include the gripper.
VectorX<T> GetIiwaPosition(const systems::Context<T>& station_context) const;
/// Convenience method for setting all of the joint angles of the Kuka IIWA.
/// Also sets the position history in the velocity command generator.
/// @p q must have size num_iiwa_joints().
/// @pre `state` must be the systems::State<T> object contained in
/// `station_context`.
void SetIiwaPosition(const systems::Context<T>& station_context,
systems::State<T>* state,
const Eigen::Ref<const VectorX<T>>& q) const;
/// Convenience method for setting all of the joint angles of the Kuka IIWA.
/// Also sets the position history in the velocity command generator.
/// @p q must have size num_iiwa_joints().
void SetIiwaPosition(systems::Context<T>* station_context,
const Eigen::Ref<const VectorX<T>>& q) const {
SetIiwaPosition(*station_context, &station_context->get_mutable_state(), q);
}
/// Convenience method for getting all of the joint velocities of the Kuka
// IIWA. This does not include the gripper.
VectorX<T> GetIiwaVelocity(const systems::Context<T>& station_context) const;
/// Convenience method for setting all of the joint velocities of the Kuka
/// IIWA. @v must have size num_iiwa_joints().
/// @pre `state` must be the systems::State<T> object contained in
/// `station_context`.
void SetIiwaVelocity(const systems::Context<T>& station_context,
systems::State<T>* state,
const Eigen::Ref<const VectorX<T>>& v) const;
/// Convenience method for setting all of the joint velocities of the Kuka
/// IIWA. @v must have size num_iiwa_joints().
void SetIiwaVelocity(systems::Context<T>* station_context,
const Eigen::Ref<const VectorX<T>>& v) const {
SetIiwaVelocity(*station_context, &station_context->get_mutable_state(), v);
}
/// Convenience method for getting the position of the Schunk WSG. Note
/// that the WSG position is the signed distance between the two fingers
/// (not the state of the fingers individually).
T GetWsgPosition(const systems::Context<T>& station_context) const;
/// Convenience method for getting the velocity of the Schunk WSG.
T GetWsgVelocity(const systems::Context<T>& station_context) const;
/// Convenience method for setting the position of the Schunk WSG. Also
/// sets the position history in the velocity interpolator. Note that the
/// WSG position is the signed distance between the two fingers (not the
/// state of the fingers individually).
/// @pre `state` must be the systems::State<T> object contained in
/// `station_context`.
void SetWsgPosition(const systems::Context<T>& station_context,
systems::State<T>* state, const T& q) const;
/// Convenience method for setting the position of the Schunk WSG. Also
/// sets the position history in the velocity interpolator. Note that the
/// WSG position is the signed distance between the two fingers (not the
/// state of the fingers individually).
void SetWsgPosition(systems::Context<T>* station_context, const T& q) const {
SetWsgPosition(*station_context, &station_context->get_mutable_state(), q);
}
/// Convenience method for setting the velocity of the Schunk WSG.
/// @pre `state` must be the systems::State<T> object contained in
/// `station_context`.
void SetWsgVelocity(const systems::Context<T>& station_context,
systems::State<T>* state, const T& v) const;
/// Convenience method for setting the velocity of the Schunk WSG.
void SetWsgVelocity(systems::Context<T>* station_context, const T& v) const {
SetWsgVelocity(*station_context, &station_context->get_mutable_state(), v);
}
/// Returns a map from camera name to X_WCameraBody for all the static
/// (rigidly attached to the world body) cameras that have been registered.
///
/// <!-- TODO(EricCousineau-TRI) To simplify (and possibly modularize) this
/// class, frame kinematics should be handled by MbP frames, since that's
/// where they have the most relevance. Change in workflow would be:
/// - Add camera frame first to the tree;
/// - Add camera directly to frame (perhaps without offset, per #10247);
/// - Change this function to return frames, so that we aren't restricted to
/// fixed-scene cameras.
/// -->
std::map<std::string, math::RigidTransform<double>>
GetStaticCameraPosesInWorld() const;
/// Get the camera names / unique ids.
std::vector<std::string> get_camera_names() const;
/// Set the gains for the WSG controller.
/// @throws std::exception if Finalize() has been called.
void SetWsgGains(double kp, double kd);
/// Set the position gains for the IIWA controller.
/// @throws std::exception if Finalize() has been called.
void SetIiwaPositionGains(const VectorX<double>& kp) {
DRAKE_THROW_UNLESS(!plant_->is_finalized());
iiwa_kp_ = kp;
}
/// Set the velocity gains for the IIWA controller.
/// @throws std::exception if Finalize() has been called.
void SetIiwaVelocityGains(const VectorX<double>& kd) {
DRAKE_THROW_UNLESS(!plant_->is_finalized());
iiwa_kd_ = kd;
}
/// Set the integral gains for the IIWA controller.
/// @throws std::exception if Finalize() has been called.
void SetIiwaIntegralGains(const VectorX<double>& ki) {
DRAKE_THROW_UNLESS(!plant_->is_finalized());
iiwa_ki_ = ki;
}
private:
// Struct defined to store information about the how to parse and add a model.
struct ModelInformation {
/// This needs to have the full path. i.e. drake::FindResourceOrThrow(...)
std::string model_path;
multibody::ModelInstanceIndex model_instance;
const multibody::Frame<T>* parent_frame{};
const multibody::Frame<T>* child_frame{};
math::RigidTransform<double> X_PC{math::RigidTransform<double>::Identity()};
};
struct CameraInformation {
const multibody::Frame<T>* parent_frame{};
math::RigidTransform<double> X_PC{math::RigidTransform<double>::Identity()};
geometry::render::ColorRenderCamera color_camera{
{"", {2, 2, M_PI}, {0.1, 10}, {}}, // RenderCameraCore
false, // show_window
};
geometry::render::DepthRenderCamera depth_camera{
{"", {2, 2, M_PI}, {0.1, 10}, {}}, // RenderCameraCore
{0.1, 0.2}, // DepthRange
};
};
// Assumes iiwa_model_info_ and wsg_model_info_ have already being populated.
// Should only be called from Finalize().
void MakeIiwaControllerModel();
void AddDefaultIiwa(const IiwaCollisionModel collision_model);
void AddDefaultWsg(const SchunkCollisionModel schunk_model);
// These are only valid until Finalize() is called.
std::unique_ptr<multibody::MultibodyPlant<T>> owned_plant_;
std::unique_ptr<geometry::SceneGraph<T>> owned_scene_graph_;
// These are valid for the lifetime of this system.
std::unique_ptr<multibody::MultibodyPlant<T>> owned_controller_plant_;
multibody::MultibodyPlant<T>* plant_;
geometry::SceneGraph<T>* scene_graph_;
static constexpr const char* default_renderer_name_ =
"manip_station_renderer";
// Populated by RegisterIiwaControllerModel() and
// RegisterWsgControllerModel().
ModelInformation iiwa_model_;
ModelInformation wsg_model_;
// Store references to objects as *body* indices instead of model indices,
// because this is needed for MultibodyPlant::SetFreeBodyPose(), etc.
std::vector<multibody::BodyIndex> object_ids_;
std::vector<math::RigidTransform<T>> object_poses_;
// Registered camera related information.
std::map<std::string, CameraInformation> camera_information_;
// These are kp and kd gains for iiwa and wsg controllers.
VectorX<double> iiwa_kp_;
VectorX<double> iiwa_kd_;
VectorX<double> iiwa_ki_;
// TODO(siyuan.feng@tri.global): Need to tunes these better.
double wsg_kp_{200};
double wsg_kd_{5};
// Represents the manipulation station to simulate. This gets set in the
// corresponding station setup function (e.g.,
// SetupManipulationClassStation()), and informs how SetDefaultState()
// initializes the sim.
Setup setup_{Setup::kNone};
};
} // namespace manipulation_station
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/manipulation_station/joint_teleop.py | """
Runs the manipulation_station example with a meshcat joint slider ui for
directly tele-operating the joints. To have the meshcat server automatically
open in your browser, supply the --open-window flag; the joint sliders will be
accessible by clicking on "Open Controls" in the top right corner.
"""
import argparse
import sys
import webbrowser
import numpy as np
from pydrake.examples import (
CreateClutterClearingYcbObjectList, ManipulationStation,
ManipulationStationHardwareInterface)
from pydrake.geometry import DrakeVisualizer
from pydrake.multibody.meshcat import JointSliders
from pydrake.math import RigidTransform, RotationMatrix
from pydrake.systems.framework import DiagramBuilder
from pydrake.systems.analysis import Simulator
from pydrake.geometry import Meshcat, MeshcatVisualizer
from pydrake.systems.primitives import FirstOrderLowPassFilter, VectorLogSink
from examples.manipulation_station.schunk_wsg_buttons import SchunkWsgButtons
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--target_realtime_rate", type=float, default=1.0,
help="Desired rate relative to real time. See documentation for "
"Simulator::set_target_realtime_rate() for details.")
parser.add_argument(
"--duration", type=float, default=np.inf,
help="Desired duration of the simulation in seconds.")
parser.add_argument(
"--hardware", action='store_true',
help="Use the ManipulationStationHardwareInterface instead of an "
"in-process simulation.")
parser.add_argument(
"--test", action='store_true',
help="Disable opening the gui window for testing.")
parser.add_argument(
'--setup', type=str, default='manipulation_class',
help="The manipulation station setup to simulate. ",
choices=['manipulation_class', 'clutter_clearing', 'planar'])
parser.add_argument(
"-w", "--open-window", dest="browser_new",
action="store_const", const=1, default=None,
help="Open the MeshCat display in a new browser window.")
args = parser.parse_args()
builder = DiagramBuilder()
# NOTE: the meshcat instance is always created in order to create the
# teleop controls (joint sliders and open/close gripper button). When
# args.hardware is True, the meshcat server will *not* display robot
# geometry, but it will contain the joint sliders and open/close gripper
# button in the "Open Controls" tab in the top-right of the viewing server.
meshcat = Meshcat()
if args.hardware:
# TODO(russt): Replace this hard-coded camera serial number with a
# config file.
camera_ids = ["805212060544"]
station = builder.AddSystem(ManipulationStationHardwareInterface(
camera_ids))
station.Connect(wait_for_cameras=False)
else:
station = builder.AddSystem(ManipulationStation())
# Initializes the chosen station type.
if args.setup == 'manipulation_class':
station.SetupManipulationClassStation()
station.AddManipulandFromFile(
"drake_models/manipulation_station/061_foam_brick.sdf",
RigidTransform(RotationMatrix.Identity(), [0.6, 0, 0]))
elif args.setup == 'clutter_clearing':
station.SetupClutterClearingStation()
ycb_objects = CreateClutterClearingYcbObjectList()
for model_file, X_WObject in ycb_objects:
station.AddManipulandFromFile(model_file, X_WObject)
elif args.setup == 'planar':
station.SetupPlanarIiwaStation()
station.AddManipulandFromFile(
"drake_models/manipulation_station/061_foam_brick.sdf",
RigidTransform(RotationMatrix.Identity(), [0.6, 0, 0]))
station.Finalize()
geometry_query_port = station.GetOutputPort("geometry_query")
DrakeVisualizer.AddToBuilder(builder, geometry_query_port)
meshcat_visualizer = MeshcatVisualizer.AddToBuilder(
builder=builder,
query_object_port=geometry_query_port,
meshcat=meshcat)
if args.setup == 'planar':
meshcat.Set2dRenderMode()
if args.browser_new is not None:
url = meshcat.web_url()
webbrowser.open(url=url, new=args.browser_new)
teleop = builder.AddSystem(JointSliders(
meshcat=meshcat, plant=station.get_controller_plant()))
num_iiwa_joints = station.num_iiwa_joints()
filter = builder.AddSystem(FirstOrderLowPassFilter(
time_constant=2.0, size=num_iiwa_joints))
builder.Connect(teleop.get_output_port(0), filter.get_input_port(0))
builder.Connect(filter.get_output_port(0),
station.GetInputPort("iiwa_position"))
wsg_buttons = builder.AddSystem(SchunkWsgButtons(meshcat=meshcat))
builder.Connect(wsg_buttons.GetOutputPort("position"),
station.GetInputPort("wsg_position"))
builder.Connect(wsg_buttons.GetOutputPort("force_limit"),
station.GetInputPort("wsg_force_limit"))
# When in regression test mode, log our joint velocities to later check
# that they were sufficiently quiet.
if args.test:
iiwa_velocities = builder.AddSystem(VectorLogSink(num_iiwa_joints))
builder.Connect(station.GetOutputPort("iiwa_velocity_estimated"),
iiwa_velocities.get_input_port(0))
else:
iiwa_velocities = None
diagram = builder.Build()
simulator = Simulator(diagram)
# This is important to avoid duplicate publishes to the hardware interface:
simulator.set_publish_every_time_step(False)
station_context = diagram.GetMutableSubsystemContext(
station, simulator.get_mutable_context())
station.GetInputPort("iiwa_feedforward_torque").FixValue(
station_context, np.zeros(num_iiwa_joints))
# If the diagram is only the hardware interface, then we must advance it a
# little bit so that first LCM messages get processed. A simulated plant is
# already publishing correct positions even without advancing, and indeed
# we must not advance a simulated plant until the sliders and filters have
# been initialized to match the plant.
if args.hardware:
simulator.AdvanceTo(1e-6)
# Eval the output port once to read the initial positions of the IIWA.
q0 = station.GetOutputPort("iiwa_position_measured").Eval(
station_context)
teleop.SetPositions(q0)
filter.set_initial_output_value(diagram.GetMutableSubsystemContext(
filter, simulator.get_mutable_context()), q0)
simulator.set_target_realtime_rate(args.target_realtime_rate)
simulator.AdvanceTo(args.duration)
# Ensure that our initialization logic was correct, by inspecting our
# logged joint velocities.
if args.test:
iiwa_velocities_log = iiwa_velocities.FindLog(simulator.get_context())
for time, qdot in zip(iiwa_velocities_log.sample_times(),
iiwa_velocities_log.data().transpose()):
# TODO(jwnimmer-tri) We should be able to do better than a 40
# rad/sec limit, but that's the best we can enforce for now.
if qdot.max() > 0.1:
print(f"ERROR: large qdot {qdot} at time {time}")
sys.exit(1)
if __name__ == '__main__':
main()
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/manipulation_station/manipulation_station.cc | #include "drake/examples/manipulation_station/manipulation_station.h"
#include <list>
#include <memory>
#include <string>
#include <utility>
#include "drake/common/eigen_types.h"
#include "drake/common/find_resource.h"
#include "drake/geometry/render_vtk/factory.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_constants.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_position_controller.h"
#include "drake/math/rigid_transform.h"
#include "drake/math/rotation_matrix.h"
#include "drake/multibody/math/spatial_force.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/multibody/parsing/process_model_directives.h"
#include "drake/multibody/plant/externally_applied_spatial_force.h"
#include "drake/multibody/tree/multibody_forces.h"
#include "drake/multibody/tree/prismatic_joint.h"
#include "drake/multibody/tree/revolute_joint.h"
#include "drake/perception/depth_image_to_point_cloud.h"
#include "drake/systems/controllers/inverse_dynamics_controller.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/primitives/adder.h"
#include "drake/systems/primitives/constant_value_source.h"
#include "drake/systems/primitives/constant_vector_source.h"
#include "drake/systems/primitives/demultiplexer.h"
#include "drake/systems/primitives/discrete_derivative.h"
#include "drake/systems/primitives/linear_system.h"
#include "drake/systems/primitives/matrix_gain.h"
#include "drake/systems/primitives/pass_through.h"
#include "drake/systems/sensors/rgbd_sensor.h"
namespace drake {
namespace examples {
namespace manipulation_station {
using Eigen::Vector3d;
using Eigen::VectorXd;
using geometry::MakeRenderEngineVtk;
using geometry::RenderEngineVtkParams;
using geometry::SceneGraph;
using math::RigidTransform;
using math::RigidTransformd;
using math::RollPitchYaw;
using math::RotationMatrix;
using multibody::ExternallyAppliedSpatialForce;
using multibody::Joint;
using multibody::MultibodyForces;
using multibody::MultibodyPlant;
using multibody::PackageMap;
using multibody::PrismaticJoint;
using multibody::RevoluteJoint;
using multibody::RigidBody;
using multibody::SpatialForce;
using multibody::SpatialInertia;
namespace internal {
namespace {
// This system computes the generalized forces on the IIWA arm of the
// manipulation station resulting from externally applied spatial forces.
//
// @system
// name: ExternalGeneralizedForcesComputer
// input_ports:
// - multibody_state
// - applied_spatial_force
// output_ports:
// - applied_generalized_force
// @endsystem
class ExternalGeneralizedForcesComputer : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ExternalGeneralizedForcesComputer)
ExternalGeneralizedForcesComputer(
const multibody::MultibodyPlant<double>* plant, int iiwa_num_dofs)
: plant_(plant), iiwa_num_velocities_(iiwa_num_dofs) {
const auto& base_joint = plant_->GetJointByName("iiwa_joint_1");
iiwa_velocity_start_ = base_joint.velocity_start();
multibody_state_ =
this->DeclareVectorInputPort("multibody_state",
plant_->num_multibody_states())
.get_index();
applied_spatial_force_input_port_ =
this->DeclareAbstractInputPort(
"applied_spatial_force",
Value<std::vector<ExternallyAppliedSpatialForce<double>>>())
.get_index();
applied_generalized_force_output_port_ =
this->DeclareVectorOutputPort(
"applied_generalized_force", iiwa_num_dofs,
&ExternalGeneralizedForcesComputer::CalcGeneralizedForcesOutput)
.get_index();
}
private:
void CalcGeneralizedForcesOutput(
const drake::systems::Context<double>& context,
drake::systems::BasicVector<double>* output_vector) const {
const auto& qv = get_input_port(multibody_state_).Eval(context);
// TODO(amcastro-tri): Consider getting rid of this heap allocation. For
// instance, this could be placed into a cache entry in the context.
auto plant_context = plant_->CreateDefaultContext();
plant_->SetPositionsAndVelocities(plant_context.get(), qv);
const auto* applied_input = this->template EvalInputValue<
std::vector<ExternallyAppliedSpatialForce<double>>>(
context, applied_spatial_force_input_port_);
// Output will be zero if the port is not connected.
VectorXd generalized_forces(plant_->num_velocities());
generalized_forces.setZero();
// Generalized forces are zero if applied input is not connected.
if (applied_input) {
// Gather externally applied forces into a MultibodyForces object.
multibody::MultibodyForces<double> forces(*plant_);
for (const ExternallyAppliedSpatialForce<double>& a_force :
*applied_input) {
const RigidBody<double>& body = plant_->get_body(a_force.body_index);
// Get the pose for this body in the world frame.
const RigidTransform<double>& X_WB =
body.EvalPoseInWorld(*plant_context);
// Get the position vector from the body origin (Bo) to the point of
// force application (Bq), expressed in the world frame (W).
const Vector3<double> p_BoBq_W = X_WB.rotation() * a_force.p_BoBq_B;
// Shift the spatial force from Bq to Bo.
const SpatialForce<double> F_Bo_W = a_force.F_Bq_W.Shift(-p_BoBq_W);
// Add contribution.
body.AddInForceInWorld(context, F_Bo_W, &forces);
}
// Compute generalized forces for the particular configuration in
// `plant_context`.
plant_->CalcGeneralizedForces(*plant_context, forces,
&generalized_forces);
}
const auto iiwa_tau_external =
generalized_forces.segment(iiwa_velocity_start_, iiwa_num_velocities_);
output_vector->SetFromVector(iiwa_tau_external);
}
const multibody::MultibodyPlant<double>* plant_{nullptr};
int iiwa_num_velocities_{0};
int iiwa_velocity_start_{0};
systems::InputPortIndex multibody_state_;
systems::InputPortIndex applied_spatial_force_input_port_;
systems::OutputPortIndex applied_generalized_force_output_port_;
};
// Calculate the spatial inertia of the set S of bodies that make up the gripper
// about Go (the gripper frame's origin), expressed in the gripper frame G.
// The rigid bodies in set S consist of the gripper body G, the left finger, and
// the right finger. For this calculation, the sliding joints associated with
// the fingers are regarded as being in a "zero" configuration.
// @param[in] wsg_sdf_path path to sdf file that when parsed creates the model.
// @param[in] gripper_body_frame_name Name of the frame attached to the
// gripper's main body.
// @retval M_SGo_G spatial inertia of set S about Go, expressed in frame G.
SpatialInertia<double> CalcGripperSpatialInertia(
const std::string& wsg_sdf_path) {
// Set time_step to 1.0 since it is arbitrary, to quiet joint limit warnings.
MultibodyPlant<double> plant(1.0);
multibody::Parser parser(&plant);
parser.AddModels(wsg_sdf_path);
plant.Finalize();
// Create a default context which should contain a default state in which all
// joints/mobilizers have zero translation, zero rotation, zero velocity, etc.
auto context = plant.CreateDefaultContext();
// Get references to gripper frame, gripper body, and the two fingers.
const multibody::Frame<double>& gripper_frame =
plant.GetFrameByName("body"); // The gripper body's frame name is "body".
const multibody::RigidBody<double>& gripper_body =
plant.GetRigidBodyByName(gripper_frame.body().name());
const multibody::RigidBody<double>& left_finger =
plant.GetRigidBodyByName("left_finger");
const multibody::RigidBody<double>& right_finger =
plant.GetRigidBodyByName("right_finger");
// Form a vector with the BodyIndex for the gripper body and the two fingers.
std::vector<multibody::BodyIndex> body_indexes;
body_indexes.push_back(gripper_body.index());
body_indexes.push_back(left_finger.index());
body_indexes.push_back(right_finger.index());
// Calculate and return the spatial inertia of set S about Go, expressed in G.
const SpatialInertia<double> M_SGo_G =
plant.CalcSpatialInertia(*context, gripper_frame, body_indexes);
return M_SGo_G;
}
// TODO(russt): Get these from SDF instead of having them hard-coded (#10022).
void get_camera_poses(std::map<std::string, RigidTransform<double>>* pose_map) {
pose_map->emplace("0", RigidTransform<double>(
RollPitchYaw<double>(2.549607, 1.357609, 2.971679),
Vector3d(-0.228895, -0.452176, 0.486308)));
pose_map->emplace("1",
RigidTransform<double>(
RollPitchYaw<double>(2.617427, -1.336404, -0.170522),
Vector3d(-0.201813, 0.469259, 0.417045)));
pose_map->emplace("2",
RigidTransform<double>(
RollPitchYaw<double>(-2.608978, 0.022298, 1.538460),
Vector3d(0.786258, -0.048422, 1.043315)));
}
// TODO(rpoyner-tri): Consider alternatives to forcing the model name: either a
// breaking change to some other naming scheme, decoupling of renaming from
// parsing, etc.
// Load a SDF model and weld it to the MultibodyPlant.
// @param model_url URL to the model file.
// @param model_name Name of the added model instance.
// @param parent Frame P from the MultibodyPlant to which the new model is
// welded to.
// @param child_frame_name Defines frame C (the child frame), assumed to be
// present in the model being added.
// @param X_PC Transformation of frame C relative to frame P.
template <typename T>
multibody::ModelInstanceIndex AddAndWeldModelFrom(
const std::string& model_url, const std::string& model_name,
const multibody::Frame<T>& parent, const std::string& child_frame_name,
const RigidTransform<double>& X_PC, MultibodyPlant<T>* plant) {
DRAKE_THROW_UNLESS(!plant->HasModelInstanceNamed(model_name));
// We need to parse model_url into a plant model instance named model_name,
// ignoring the model name defined within the model_url file. We accomplish
// that by parsing the model first and then renaming it second. If the model
// name defined within the model_url file was already in use, the first step
// would throw; to avoid that, we must enable auto renaming during its parse.
multibody::Parser parser(plant);
parser.SetAutoRenaming(true);
const auto models = parser.AddModelsFromUrl(model_url);
DRAKE_THROW_UNLESS(models.size() == 1);
plant->RenameModelInstance(models[0], model_name);
const multibody::ModelInstanceIndex new_model = models[0];
const auto& child_frame = plant->GetFrameByName(child_frame_name, new_model);
plant->WeldFrames(parent, child_frame, X_PC);
return new_model;
}
std::pair<geometry::render::ColorRenderCamera,
geometry::render::DepthRenderCamera>
MakeD415CameraModel(const std::string& renderer_name) {
// Typical D415 intrinsics for 848 x 480 resolution, note that rgb and
// depth are slightly different (in both intrinsics and relative to the
// camera body frame).
// RGB:
// - w: 848, h: 480, fx: 616.285, fy: 615.778, ppx: 405.418, ppy: 232.864
// DEPTH:
// - w: 848, h: 480, fx: 645.138, fy: 645.138, ppx: 420.789, ppy: 239.13
// However, given that (a) these fixed constants will not always be true and
// (b) we do not have a quick RGBD registration algorithm in Drake, we will
// simply publish according to the RGB intrinsics and extrinsics.
const int kHeight = 480;
const int kWidth = 848;
// From color camera.
const systems::sensors::CameraInfo intrinsics{
kWidth, kHeight, 616.285, 615.778, 405.418, 232.864};
const RigidTransformd X_BC;
// This is not necessarily true, but we simplify this s.t. we don't have a
// lie for generating point clouds.
const RigidTransformd X_BD;
geometry::render::ColorRenderCamera color_camera{
{renderer_name,
intrinsics,
{0.01, 3.0} /* clipping_range */,
X_BC},
false};
geometry::render::DepthRenderCamera depth_camera{
{renderer_name,
intrinsics,
{0.01, 3.0} /* clipping_range */,
X_BD},
{0.1, 2.0} /* depth_range */};
return {color_camera, depth_camera};
}
} // namespace
} // namespace internal
template <typename T>
ManipulationStation<T>::ManipulationStation(double time_step)
: owned_plant_(std::make_unique<MultibodyPlant<T>>(time_step)),
owned_scene_graph_(std::make_unique<SceneGraph<T>>()),
// Given the controller does not compute accelerations, it is irrelevant
// whether the plant is continuous or discrete. We make it
// discrete to avoid warnings about joint limits.
owned_controller_plant_(std::make_unique<MultibodyPlant<T>>(1.0)) {
// This class holds the unique_ptrs explicitly for plant and scene_graph
// until Finalize() is called (when they are moved into the Diagram). Grab
// the raw pointers, which should stay valid for the lifetime of the Diagram.
plant_ = owned_plant_.get();
scene_graph_ = owned_scene_graph_.get();
plant_->RegisterAsSourceForSceneGraph(scene_graph_);
scene_graph_->set_name("scene_graph");
plant_->set_name("plant");
this->set_name("manipulation_station");
}
template <typename T>
void ManipulationStation<T>::AddManipulandFromFile(
const std::string& model_file, const RigidTransform<double>& X_WObject) {
multibody::Parser parser(plant_);
std::vector<multibody::ModelInstanceIndex> models;
if (model_file.starts_with("drake/") ||
model_file.starts_with("drake_models/")) {
models = parser.AddModelsFromUrl("package://" + model_file);
} else {
models = parser.AddModels(FindResourceOrThrow(model_file));
}
DRAKE_THROW_UNLESS(models.size() == 1);
const auto model_index = models[0];
const auto indices = plant_->GetBodyIndices(model_index);
// Only support single-body objects for now.
// Note: this could be generalized fairly easily... would just want to
// set default/random positions for the non-floating-base elements below.
DRAKE_DEMAND(indices.size() == 1);
object_ids_.push_back(indices[0]);
object_poses_.push_back(X_WObject);
}
template <typename T>
void ManipulationStation<T>::SetupClutterClearingStation(
const std::optional<const math::RigidTransform<double>>& X_WCameraBody,
IiwaCollisionModel collision_model, SchunkCollisionModel schunk_model) {
DRAKE_DEMAND(setup_ == Setup::kNone);
setup_ = Setup::kClutterClearing;
// Add the bins.
{
const std::string sdf_url =
"package://drake_models/manipulation_station/bin.sdf";
RigidTransform<double> X_WC(RotationMatrix<double>::MakeZRotation(M_PI_2),
Vector3d(-0.145, -0.63, 0.075));
internal::AddAndWeldModelFrom(sdf_url, "bin1", plant_->world_frame(),
"bin_base", X_WC, plant_);
X_WC = RigidTransform<double>(RotationMatrix<double>::MakeZRotation(M_PI),
Vector3d(0.5, -0.1, 0.075));
internal::AddAndWeldModelFrom(sdf_url, "bin2", plant_->world_frame(),
"bin_base", X_WC, plant_);
}
// Add the camera.
{
const auto& [color_camera, depth_camera] =
internal::MakeD415CameraModel(default_renderer_name_);
RegisterRgbdSensor("0", plant_->world_frame(),
X_WCameraBody.value_or(math::RigidTransform<double>(
math::RollPitchYaw<double>(-0.3, 0.8, 1.5),
Eigen::Vector3d(0, -1.5, 1.5))),
color_camera, depth_camera);
}
AddDefaultIiwa(collision_model);
AddDefaultWsg(schunk_model);
}
template <typename T>
void ManipulationStation<T>::SetupManipulationClassStation(
IiwaCollisionModel collision_model,
SchunkCollisionModel schunk_model) {
DRAKE_DEMAND(setup_ == Setup::kNone);
setup_ = Setup::kManipulationClass;
// Add the table and 80/20 workcell frame.
{
const double dx_table_center_to_robot_base = 0.3257;
const double dz_table_top_robot_base = 0.0127;
const std::string sdf_url =
"package://drake_models/manipulation_station/"
"amazon_table_simplified.sdf";
RigidTransform<double> X_WT(
Vector3d(dx_table_center_to_robot_base, 0, -dz_table_top_robot_base));
internal::AddAndWeldModelFrom(sdf_url, "table", plant_->world_frame(),
"amazon_table", X_WT, plant_);
}
// Add the cupboard.
{
const double dx_table_center_to_robot_base = 0.3257;
const double dz_table_top_robot_base = 0.0127;
const double dx_cupboard_to_table_center = 0.43 + 0.15;
const double dz_cupboard_to_table_center = 0.02;
const double cupboard_height = 0.815;
const std::string sdf_url =
"package://drake_models/manipulation_station/cupboard.sdf";
RigidTransform<double> X_WC(
RotationMatrix<double>::MakeZRotation(M_PI),
Vector3d(dx_table_center_to_robot_base + dx_cupboard_to_table_center, 0,
dz_cupboard_to_table_center + cupboard_height / 2.0 -
dz_table_top_robot_base));
internal::AddAndWeldModelFrom(sdf_url, "cupboard", plant_->world_frame(),
"cupboard_body", X_WC, plant_);
}
// Add the default iiwa/wsg models.
AddDefaultIiwa(collision_model);
AddDefaultWsg(schunk_model);
// Add default cameras.
{
std::map<std::string, RigidTransform<double>> camera_poses;
internal::get_camera_poses(&camera_poses);
const auto& [color_camera, depth_camera] =
internal::MakeD415CameraModel(default_renderer_name_);
for (const auto& camera_pair : camera_poses) {
RegisterRgbdSensor(camera_pair.first, plant_->world_frame(),
camera_pair.second, color_camera, depth_camera);
}
}
}
template <typename T>
void ManipulationStation<T>::SetupPlanarIiwaStation(
SchunkCollisionModel schunk_model) {
DRAKE_DEMAND(setup_ == Setup::kNone);
setup_ = Setup::kPlanarIiwa;
// Add the tables.
{
const std::string sdf_url =
"package://drake/examples/kuka_iiwa_arm/models/table/"
"extra_heavy_duty_table_surface_only_collision.sdf";
const double table_height = 0.7645;
internal::AddAndWeldModelFrom(
sdf_url, "robot_table", plant_->world_frame(), "link",
RigidTransform<double>(Vector3d(0, 0, -table_height)), plant_);
internal::AddAndWeldModelFrom(
sdf_url, "work_table", plant_->world_frame(), "link",
RigidTransform<double>(Vector3d(0.75, 0, -table_height)), plant_);
}
// Add planar iiwa model.
{
const std::string sdf_url =
"package://drake_models/iiwa_description/urdf/"
"planar_iiwa14_spheres_dense_elbow_collision.urdf";
const auto X_WI = RigidTransform<double>::Identity();
auto iiwa_instance = internal::AddAndWeldModelFrom(
sdf_url, "iiwa", plant_->world_frame(), "iiwa_link_0", X_WI, plant_);
RegisterIiwaControllerModel(
PackageMap{}.ResolveUrl(sdf_url), iiwa_instance, plant_->world_frame(),
plant_->GetFrameByName("iiwa_link_0", iiwa_instance), X_WI);
}
// Add the default wsg model.
AddDefaultWsg(schunk_model);
}
template <typename T>
int ManipulationStation<T>::num_iiwa_joints() const {
DRAKE_DEMAND(iiwa_model_.model_instance.is_valid());
return plant_->num_positions(iiwa_model_.model_instance);
}
template <typename T>
void ManipulationStation<T>::SetDefaultState(
const systems::Context<T>& station_context,
systems::State<T>* state) const {
// Call the base class method, to initialize all systems in this diagram.
systems::Diagram<T>::SetDefaultState(station_context, state);
T q0_gripper{0.1};
const auto& plant_context =
this->GetSubsystemContext(*plant_, station_context);
auto& plant_state = this->GetMutableSubsystemState(*plant_, state);
DRAKE_DEMAND(object_ids_.size() == object_poses_.size());
for (uint64_t i = 0; i < object_ids_.size(); i++) {
plant_->SetFreeBodyPose(plant_context, &plant_state,
plant_->get_body(object_ids_[i]), object_poses_[i]);
}
// Use SetIiwaPosition to make sure the controller state is initialized to
// the IIWA state.
SetIiwaPosition(station_context, state, GetIiwaPosition(station_context));
SetIiwaVelocity(station_context, state, VectorX<T>::Zero(num_iiwa_joints()));
SetWsgPosition(station_context, state, q0_gripper);
SetWsgVelocity(station_context, state, 0);
}
template <typename T>
void ManipulationStation<T>::SetRandomState(
const systems::Context<T>& station_context, systems::State<T>* state,
RandomGenerator* generator) const {
// Call the base class method, to initialize all systems in this diagram.
systems::Diagram<T>::SetRandomState(station_context, state, generator);
const auto& plant_context =
this->GetSubsystemContext(*plant_, station_context);
auto& plant_state = this->GetMutableSubsystemState(*plant_, state);
// Separate the objects by lifting them up in z (in a random order).
// TODO(russt): Replace this with an explicit projection into a statically
// stable configuration.
std::vector<multibody::BodyIndex> shuffled_object_ids(object_ids_);
std::shuffle(shuffled_object_ids.begin(), shuffled_object_ids.end(),
*generator);
double z_offset = 0.1;
for (const auto& body_index : shuffled_object_ids) {
math::RigidTransform<T> pose =
plant_->GetFreeBodyPose(plant_context, plant_->get_body(body_index));
pose.set_translation(pose.translation() + Vector3d{0, 0, z_offset});
z_offset += 0.1;
plant_->SetFreeBodyPose(plant_context, &plant_state,
plant_->get_body(body_index), pose);
}
// Use SetIiwaPosition to make sure the controller state is initialized to
// the IIWA state.
SetIiwaPosition(station_context, state, GetIiwaPosition(station_context));
SetIiwaVelocity(station_context, state, VectorX<T>::Zero(num_iiwa_joints()));
SetWsgPosition(station_context, state, GetWsgPosition(station_context));
SetWsgVelocity(station_context, state, 0);
}
template <typename T>
void ManipulationStation<T>::MakeIiwaControllerModel() {
// Build the controller's version of the plant, which only contains the
// IIWA and the equivalent inertia of the gripper.
multibody::Parser parser(owned_controller_plant_.get());
const auto models = parser.AddModels(iiwa_model_.model_path);
DRAKE_THROW_UNLESS(models.size() == 1);
const auto controller_iiwa_model = models[0];
owned_controller_plant_->WeldFrames(
owned_controller_plant_->world_frame(),
owned_controller_plant_->GetFrameByName(iiwa_model_.child_frame->name(),
controller_iiwa_model),
iiwa_model_.X_PC);
// Add a single body to represent the IIWA pendant's calibration of the
// gripper. The body of the WSG accounts for >90% of the total mass
// (according to the sdf)... and we don't believe our inertia calibration
// on the hardware to be so precise, so we simply ignore the inertia
// contribution from the fingers here.
const multibody::SpatialInertia<double> wsg_spatial_inertial =
internal::CalcGripperSpatialInertia(wsg_model_.model_path);
const multibody::RigidBody<T>& wsg_equivalent =
owned_controller_plant_->AddRigidBody(
"wsg_equivalent", controller_iiwa_model, wsg_spatial_inertial);
// TODO(siyuan.feng@tri.global): when we handle multiple IIWA and WSG, this
// part need to deal with the parent's (iiwa's) model instance id.
owned_controller_plant_->WeldFrames(
owned_controller_plant_->GetFrameByName(wsg_model_.parent_frame->name(),
controller_iiwa_model),
wsg_equivalent.body_frame(), wsg_model_.X_PC);
owned_controller_plant_->set_name("controller_plant");
}
template <typename T>
void ManipulationStation<T>::Finalize() {
Finalize({});
}
template <typename T>
void ManipulationStation<T>::Finalize(
std::map<std::string, std::unique_ptr<geometry::render::RenderEngine>>
render_engines) {
DRAKE_THROW_UNLESS(iiwa_model_.model_instance.is_valid());
DRAKE_THROW_UNLESS(wsg_model_.model_instance.is_valid());
MakeIiwaControllerModel();
// Note: This deferred diagram construction method/workflow exists because we
// - cannot finalize plant until all of my objects are added, and
// - cannot wire up my diagram until we have finalized the plant.
plant_->Finalize();
// Set plant properties that must occur after finalizing the plant.
VectorX<T> q0_iiwa(num_iiwa_joints());
switch (setup_) {
case Setup::kNone:
case Setup::kManipulationClass: {
// Set the initial positions of the IIWA to a comfortable configuration
// inside the workspace of the station.
q0_iiwa << 0, 0.6, 0, -1.75, 0, 1.0, 0;
std::uniform_real_distribution<symbolic::Expression> x(0.4, 0.65),
y(-0.35, 0.35), z(0, 0.05);
const Vector3<symbolic::Expression> xyz{x(), y(), z()};
for (const auto& body_index : object_ids_) {
const multibody::RigidBody<T>& body = plant_->get_body(body_index);
plant_->SetFreeBodyRandomTranslationDistribution(body, xyz);
plant_->SetFreeBodyRandomRotationDistributionToUniform(body);
}
break;
}
case Setup::kClutterClearing: {
// Set the initial positions of the IIWA to a configuration right above
// the picking bin.
q0_iiwa << -1.57, 0.1, 0, -1.2, 0, 1.6, 0;
std::uniform_real_distribution<symbolic::Expression> x(-.35, 0.05),
y(-0.8, -.55), z(0.3, 0.35);
const Vector3<symbolic::Expression> xyz{x(), y(), z()};
for (const auto& body_index : object_ids_) {
const multibody::RigidBody<T>& body = plant_->get_body(body_index);
plant_->SetFreeBodyRandomTranslationDistribution(body, xyz);
plant_->SetFreeBodyRandomRotationDistributionToUniform(body);
}
break;
}
case Setup::kPlanarIiwa: {
// Set initial positions of the IIWA, but now with only joints 2, 4,
// and 6.
q0_iiwa << 0.1, -1.2, 1.6;
std::uniform_real_distribution<symbolic::Expression> x(0.4, 0.8),
y(0, 0), z(0, 0.05);
const Vector3<symbolic::Expression> xyz{x(), y(), z()};
for (const auto& body_index : object_ids_) {
const multibody::RigidBody<T>& body = plant_->get_body(body_index);
plant_->SetFreeBodyRandomTranslationDistribution(body, xyz);
}
break;
}
}
// Set the iiwa default configuration.
const auto iiwa_joint_indices =
plant_->GetJointIndices(iiwa_model_.model_instance);
int q0_index = 0;
for (const auto& joint_index : iiwa_joint_indices) {
multibody::RevoluteJoint<T>* joint =
dynamic_cast<multibody::RevoluteJoint<T>*>(
&plant_->get_mutable_joint(joint_index));
// Note: iiwa_joint_indices includes the WeldJoint at the base. Only set
// the RevoluteJoints.
if (joint) {
joint->set_default_angle(q0_iiwa[q0_index++]);
}
}
systems::DiagramBuilder<T> builder;
builder.AddSystem(std::move(owned_plant_));
builder.AddSystem(std::move(owned_scene_graph_));
builder.Connect(
plant_->get_geometry_poses_output_port(),
scene_graph_->get_source_pose_port(plant_->get_source_id().value()));
builder.Connect(scene_graph_->get_query_output_port(),
plant_->get_geometry_query_input_port());
const int num_iiwa_positions =
plant_->num_positions(iiwa_model_.model_instance);
DRAKE_THROW_UNLESS(num_iiwa_positions ==
plant_->num_velocities(iiwa_model_.model_instance));
// Export the commanded positions via a PassThrough.
auto iiwa_position =
builder.template AddSystem<systems::PassThrough>(num_iiwa_positions);
builder.ExportInput(iiwa_position->get_input_port(), "iiwa_position");
builder.ExportOutput(iiwa_position->get_output_port(),
"iiwa_position_commanded");
// Export iiwa "state" outputs.
{
auto demux = builder.template AddSystem<systems::Demultiplexer>(
2 * num_iiwa_positions, num_iiwa_positions);
builder.Connect(plant_->get_state_output_port(iiwa_model_.model_instance),
demux->get_input_port(0));
builder.ExportOutput(demux->get_output_port(0), "iiwa_position_measured");
builder.ExportOutput(demux->get_output_port(1), "iiwa_velocity_estimated");
builder.ExportOutput(
plant_->get_state_output_port(iiwa_model_.model_instance),
"iiwa_state_estimated");
}
// Add the IIWA controller "stack".
{
owned_controller_plant_->Finalize();
auto check_gains = [](const VectorX<double>& gains, int size) {
return (gains.size() == size) && (gains.array() >= 0).all();
};
// Set default gains if.
if (iiwa_kp_.size() == 0) {
iiwa_kp_ = VectorXd::Constant(num_iiwa_positions, 100);
}
DRAKE_THROW_UNLESS(check_gains(iiwa_kp_, num_iiwa_positions));
if (iiwa_kd_.size() == 0) {
iiwa_kd_.resize(num_iiwa_positions);
for (int i = 0; i < num_iiwa_positions; i++) {
// Critical damping gains.
iiwa_kd_[i] = 2 * std::sqrt(iiwa_kp_[i]);
}
}
DRAKE_THROW_UNLESS(check_gains(iiwa_kd_, num_iiwa_positions));
if (iiwa_ki_.size() == 0) {
iiwa_ki_ = VectorXd::Constant(num_iiwa_positions, 1);
}
DRAKE_THROW_UNLESS(check_gains(iiwa_ki_, num_iiwa_positions));
// Add the inverse dynamics controller.
auto iiwa_controller = builder.template AddSystem<
systems::controllers::InverseDynamicsController>(
*owned_controller_plant_, iiwa_kp_, iiwa_ki_, iiwa_kd_, false);
iiwa_controller->set_name("iiwa_controller");
builder.Connect(plant_->get_state_output_port(iiwa_model_.model_instance),
iiwa_controller->get_input_port_estimated_state());
// Add in feedforward torque.
auto adder =
builder.template AddSystem<systems::Adder>(2, num_iiwa_positions);
builder.Connect(iiwa_controller->get_output_port_control(),
adder->get_input_port(0));
// Use a passthrough to make the port optional. (Will provide zero values
// if not connected).
auto torque_passthrough = builder.template AddSystem<systems::PassThrough>(
Eigen::VectorXd::Zero(num_iiwa_positions));
builder.Connect(torque_passthrough->get_output_port(),
adder->get_input_port(1));
builder.ExportInput(torque_passthrough->get_input_port(),
"iiwa_feedforward_torque");
builder.Connect(adder->get_output_port(), plant_->get_actuation_input_port(
iiwa_model_.model_instance));
// Approximate desired state command from a discrete derivative of the
// position command input port.
auto desired_state_from_position = builder.template AddSystem<
systems::StateInterpolatorWithDiscreteDerivative>(
num_iiwa_positions, plant_->time_step(),
true /* suppress_initial_transient */);
desired_state_from_position->set_name("desired_state_from_position");
builder.Connect(desired_state_from_position->get_output_port(),
iiwa_controller->get_input_port_desired_state());
builder.Connect(iiwa_position->get_output_port(),
desired_state_from_position->get_input_port());
// Export commanded torques:
builder.ExportOutput(adder->get_output_port(), "iiwa_torque_commanded");
builder.ExportOutput(adder->get_output_port(), "iiwa_torque_measured");
}
{
auto wsg_controller = builder.template AddSystem<
manipulation::schunk_wsg::SchunkWsgPositionController>(
manipulation::schunk_wsg::kSchunkWsgLcmStatusPeriod, wsg_kp_, wsg_kd_);
wsg_controller->set_name("wsg_controller");
builder.Connect(
wsg_controller->get_generalized_force_output_port(),
plant_->get_actuation_input_port(wsg_model_.model_instance));
builder.Connect(plant_->get_state_output_port(wsg_model_.model_instance),
wsg_controller->get_state_input_port());
builder.ExportInput(wsg_controller->get_desired_position_input_port(),
"wsg_position");
builder.ExportInput(wsg_controller->get_force_limit_input_port(),
"wsg_force_limit");
auto wsg_mbp_state_to_wsg_state = builder.template AddSystem(
manipulation::schunk_wsg::MakeMultibodyStateToWsgStateSystem<double>());
builder.Connect(plant_->get_state_output_port(wsg_model_.model_instance),
wsg_mbp_state_to_wsg_state->get_input_port());
builder.ExportOutput(wsg_mbp_state_to_wsg_state->get_output_port(),
"wsg_state_measured");
builder.ExportOutput(wsg_controller->get_grip_force_output_port(),
"wsg_force_measured");
}
// System to compute generalized forces due to externally applied spatial
// forces.
auto computer =
builder.template AddSystem<internal::ExternalGeneralizedForcesComputer>(
plant_, num_iiwa_positions);
builder.Connect(plant_->get_state_output_port(),
computer->GetInputPort("multibody_state"));
builder.ExportInput(computer->GetInputPort("applied_spatial_force"),
"applied_spatial_force");
// Connect the exported input to the plant's applied spatial force input as
// well.
builder.ConnectToSame(computer->GetInputPort("applied_spatial_force"),
plant_->get_applied_spatial_force_input_port());
// Adder to compute τ_external = τ_applied_spatial_force + τ_contact
systems::Adder<double>* external_forces_adder =
builder.template AddSystem<systems::Adder<double>>(2, num_iiwa_positions);
builder.Connect(plant_->get_generalized_contact_forces_output_port(
iiwa_model_.model_instance),
external_forces_adder->get_input_port(0));
builder.Connect(computer->GetOutputPort("applied_generalized_force"),
external_forces_adder->get_input_port(1));
// Export port for τ_external.
builder.ExportOutput(external_forces_adder->get_output_port(),
"iiwa_torque_external");
{ // RGB-D Cameras
if (render_engines.size() > 0) {
for (auto& pair : render_engines) {
scene_graph_->AddRenderer(pair.first, std::move(pair.second));
}
} else {
scene_graph_->AddRenderer(default_renderer_name_,
MakeRenderEngineVtk(RenderEngineVtkParams()));
}
for (const auto& [name, info] : camera_information_) {
std::string camera_name = "camera_" + name;
const std::optional<geometry::FrameId> parent_body_id =
plant_->GetBodyFrameIdIfExists(info.parent_frame->body().index());
DRAKE_THROW_UNLESS(parent_body_id.has_value());
const RigidTransform<double> X_PC =
info.parent_frame->GetFixedPoseInBodyFrame() * info.X_PC;
auto camera = builder.template AddSystem<systems::sensors::RgbdSensor>(
parent_body_id.value(), X_PC, info.color_camera, info.depth_camera);
builder.Connect(scene_graph_->get_query_output_port(),
camera->query_object_input_port());
auto depth_to_cloud = builder.template AddSystem<
perception::DepthImageToPointCloud>(
camera->depth_camera_info(),
systems::sensors::PixelType::kDepth16U,
0.001f /* depth camera is in mm */,
perception::pc_flags::kXYZs |
perception::pc_flags::kRGBs);
auto x_pc_system = builder.template AddSystem<
systems::ConstantValueSource>(Value<RigidTransformd>(X_PC));
builder.Connect(camera->color_image_output_port(),
depth_to_cloud->color_image_input_port());
builder.Connect(camera->depth_image_16U_output_port(),
depth_to_cloud->depth_image_input_port());
builder.Connect(x_pc_system->get_output_port(),
depth_to_cloud->camera_pose_input_port());
builder.ExportOutput(camera->color_image_output_port(),
camera_name + "_rgb_image");
builder.ExportOutput(camera->depth_image_16U_output_port(),
camera_name + "_depth_image");
builder.ExportOutput(camera->label_image_output_port(),
camera_name + "_label_image");
builder.ExportOutput(depth_to_cloud->point_cloud_output_port(),
camera_name + "_point_cloud");
}
}
builder.ExportOutput(scene_graph_->get_query_output_port(), "query_object");
builder.ExportOutput(scene_graph_->get_query_output_port(),
"geometry_query");
builder.ExportOutput(plant_->get_contact_results_output_port(),
"contact_results");
builder.ExportOutput(plant_->get_state_output_port(),
"plant_continuous_state");
// TODO(SeanCurtis-TRI) It seems with the scene graph query object port
// exported, this output port is superfluous/undesirable. This port
// contains the FramePoseVector that connects MBP to SG. Definitely better
// to simply rely on the query object output port.
builder.ExportOutput(plant_->get_geometry_poses_output_port(),
"geometry_poses");
builder.BuildInto(this);
}
template <typename T>
VectorX<T> ManipulationStation<T>::GetIiwaPosition(
const systems::Context<T>& station_context) const {
const auto& plant_context =
this->GetSubsystemContext(*plant_, station_context);
return plant_->GetPositions(plant_context, iiwa_model_.model_instance);
}
template <typename T>
void ManipulationStation<T>::SetIiwaPosition(
const drake::systems::Context<T>& station_context, systems::State<T>* state,
const Eigen::Ref<const drake::VectorX<T>>& q) const {
const int num_iiwa_positions =
plant_->num_positions(iiwa_model_.model_instance);
DRAKE_DEMAND(state != nullptr);
DRAKE_DEMAND(q.size() == num_iiwa_positions);
auto& plant_context = this->GetSubsystemContext(*plant_, station_context);
auto& plant_state = this->GetMutableSubsystemState(*plant_, state);
plant_->SetPositions(plant_context, &plant_state, iiwa_model_.model_instance,
q);
}
template <typename T>
VectorX<T> ManipulationStation<T>::GetIiwaVelocity(
const systems::Context<T>& station_context) const {
const auto& plant_context =
this->GetSubsystemContext(*plant_, station_context);
return plant_->GetVelocities(plant_context, iiwa_model_.model_instance);
}
template <typename T>
void ManipulationStation<T>::SetIiwaVelocity(
const drake::systems::Context<T>& station_context, systems::State<T>* state,
const Eigen::Ref<const drake::VectorX<T>>& v) const {
const int num_iiwa_velocities =
plant_->num_velocities(iiwa_model_.model_instance);
DRAKE_DEMAND(state != nullptr);
DRAKE_DEMAND(v.size() == num_iiwa_velocities);
auto& plant_context = this->GetSubsystemContext(*plant_, station_context);
auto& plant_state = this->GetMutableSubsystemState(*plant_, state);
plant_->SetVelocities(plant_context, &plant_state, iiwa_model_.model_instance,
v);
}
template <typename T>
T ManipulationStation<T>::GetWsgPosition(
const systems::Context<T>& station_context) const {
const auto& plant_context =
this->GetSubsystemContext(*plant_, station_context);
Vector2<T> positions =
plant_->GetPositions(plant_context, wsg_model_.model_instance);
return positions(1) - positions(0);
}
template <typename T>
T ManipulationStation<T>::GetWsgVelocity(
const systems::Context<T>& station_context) const {
const auto& plant_context =
this->GetSubsystemContext(*plant_, station_context);
Vector2<T> velocities =
plant_->GetVelocities(plant_context, wsg_model_.model_instance);
return velocities(1) - velocities(0);
}
template <typename T>
void ManipulationStation<T>::SetWsgPosition(
const drake::systems::Context<T>& station_context, systems::State<T>* state,
const T& q) const {
DRAKE_DEMAND(state != nullptr);
auto& plant_context = this->GetSubsystemContext(*plant_, station_context);
auto& plant_state = this->GetMutableSubsystemState(*plant_, state);
const Vector2<T> positions(-q / 2, q / 2);
plant_->SetPositions(plant_context, &plant_state, wsg_model_.model_instance,
positions);
}
template <typename T>
void ManipulationStation<T>::SetWsgVelocity(
const drake::systems::Context<T>& station_context, systems::State<T>* state,
const T& v) const {
DRAKE_DEMAND(state != nullptr);
auto& plant_context = this->GetSubsystemContext(*plant_, station_context);
auto& plant_state = this->GetMutableSubsystemState(*plant_, state);
const Vector2<T> velocities(-v / 2, v / 2);
plant_->SetVelocities(plant_context, &plant_state, wsg_model_.model_instance,
velocities);
}
// TODO(SeanCurtis-TRI) This method does not deserve the snake_case name.
// See https://drake.mit.edu/styleguide/cppguide.html#Function_Names
// Deprecate and rename.
template <typename T>
std::vector<std::string> ManipulationStation<T>::get_camera_names() const {
std::vector<std::string> names;
names.reserve(camera_information_.size());
for (const auto& info : camera_information_) {
names.emplace_back(info.first);
}
return names;
}
template <typename T>
void ManipulationStation<T>::SetWsgGains(const double kp, const double kd) {
DRAKE_THROW_UNLESS(!plant_->is_finalized());
DRAKE_THROW_UNLESS(kp >= 0 && kd >= 0);
wsg_kp_ = kp;
wsg_kd_ = kd;
}
template <typename T>
void ManipulationStation<T>::RegisterIiwaControllerModel(
const std::string& model_path,
const multibody::ModelInstanceIndex iiwa_instance,
const multibody::Frame<T>& parent_frame,
const multibody::Frame<T>& child_frame,
const RigidTransform<double>& X_PC) {
// TODO(siyuan.feng@tri.global): We really only just need to make sure
// the parent frame is a AnchoredFrame(i.e. there is a rigid kinematic path
// from it to the world), and record that X_WP. However, the computation to
// query X_WP given a partially constructed plant is not feasible at the
// moment, so we are forcing the parent frame to be the world instead.
DRAKE_THROW_UNLESS(parent_frame.name() == plant_->world_frame().name());
iiwa_model_.model_path = model_path;
iiwa_model_.parent_frame = &parent_frame;
iiwa_model_.child_frame = &child_frame;
iiwa_model_.X_PC = X_PC;
iiwa_model_.model_instance = iiwa_instance;
}
template <typename T>
void ManipulationStation<T>::RegisterWsgControllerModel(
const std::string& model_path,
const multibody::ModelInstanceIndex wsg_instance,
const multibody::Frame<T>& parent_frame,
const multibody::Frame<T>& child_frame,
const RigidTransform<double>& X_PC) {
wsg_model_.model_path = model_path;
wsg_model_.parent_frame = &parent_frame;
wsg_model_.child_frame = &child_frame;
wsg_model_.X_PC = X_PC;
wsg_model_.model_instance = wsg_instance;
}
template <typename T>
void ManipulationStation<T>::RegisterRgbdSensor(
const std::string& name, const multibody::Frame<T>& parent_frame,
const RigidTransform<double>& X_PC,
const geometry::render::DepthRenderCamera& depth_camera) {
RegisterRgbdSensor(
name, parent_frame, X_PC,
geometry::render::ColorRenderCamera(depth_camera.core(), false),
depth_camera);
}
template <typename T>
void ManipulationStation<T>::RegisterRgbdSensor(
const std::string& name, const multibody::Frame<T>& parent_frame,
const RigidTransform<double>& X_PC,
const geometry::render::ColorRenderCamera& color_camera,
const geometry::render::DepthRenderCamera& depth_camera) {
CameraInformation info;
info.parent_frame = &parent_frame;
info.X_PC = X_PC;
info.depth_camera = depth_camera;
info.color_camera = color_camera;
camera_information_[name] = info;
const std::string urdf_url =
"package://drake_models/realsense2_description/urdf/d415.urdf";
multibody::ModelInstanceIndex model_index = internal::AddAndWeldModelFrom(
urdf_url, name, parent_frame, "base_link", X_PC, plant_);
// Remove the perception properties -- the camera should not be visible to
// itself or else it obscures its own view. We only want the illustration
// properties so that the camera shows up in the visualizer.
const geometry::SourceId source_id = plant_->get_source_id().value();
for (const multibody::BodyIndex& body_index :
plant_->GetBodyIndices(model_index)) {
const multibody::RigidBody<T>& body = plant_->get_body(body_index);
for (const geometry::GeometryId& geometry_id :
plant_->GetVisualGeometriesForBody(body)) {
scene_graph_->RemoveRole(source_id, geometry_id,
geometry::Role::kPerception);
}
}
}
template <typename T>
std::map<std::string, RigidTransform<double>>
ManipulationStation<T>::GetStaticCameraPosesInWorld() const {
std::map<std::string, RigidTransform<double>> static_camera_poses;
for (const auto& info : camera_information_) {
const auto& frame_P = *info.second.parent_frame;
// TODO(siyuan.feng@tri.global): We really only just need to make sure
// the parent frame is a AnchoredFrame(i.e. there is a rigid kinematic path
// from it to the world). However, the computation to query X_WP given a
// partially constructed plant is not feasible at the moment, so we are
// looking for cameras that are directly attached to the world instead.
const bool is_anchored =
frame_P.body().index() == plant_->world_frame().body().index();
if (is_anchored) {
static_camera_poses.emplace(
info.first,
RigidTransform<double>(frame_P.GetFixedPoseInBodyFrame()) *
info.second.X_PC);
}
}
return static_camera_poses;
}
// Add default iiwa.
template <typename T>
void ManipulationStation<T>::AddDefaultIiwa(
const IiwaCollisionModel collision_model) {
std::string sdf_url;
switch (collision_model) {
case IiwaCollisionModel::kNoCollision:
sdf_url =
"package://drake_models/iiwa_description/sdf/"
"iiwa7_no_collision.sdf";
break;
case IiwaCollisionModel::kBoxCollision:
sdf_url =
"package://drake_models/iiwa_description/sdf/"
"iiwa7_with_box_collision.sdf";
break;
}
const auto X_WI = RigidTransform<double>::Identity();
auto iiwa_instance = internal::AddAndWeldModelFrom(
sdf_url, "iiwa", plant_->world_frame(), "iiwa_link_0", X_WI, plant_);
RegisterIiwaControllerModel(
PackageMap{}.ResolveUrl(sdf_url), iiwa_instance, plant_->world_frame(),
plant_->GetFrameByName("iiwa_link_0", iiwa_instance), X_WI);
}
// Add default wsg.
template <typename T>
void ManipulationStation<T>::AddDefaultWsg(
const SchunkCollisionModel schunk_model) {
std::string sdf_url;
switch (schunk_model) {
case SchunkCollisionModel::kBox:
sdf_url =
"package://drake_models/wsg_50_description/sdf/"
"schunk_wsg_50_no_tip.sdf";
break;
case SchunkCollisionModel::kBoxPlusFingertipSpheres:
sdf_url =
"package://drake_models/wsg_50_description/sdf/"
"schunk_wsg_50_with_tip.sdf";
break;
}
const multibody::Frame<T>& link7 =
plant_->GetFrameByName("iiwa_link_7", iiwa_model_.model_instance);
const RigidTransform<double> X_7G(RollPitchYaw<double>(M_PI_2, 0, M_PI_2),
Vector3d(0, 0, 0.114));
auto wsg_instance = internal::AddAndWeldModelFrom(sdf_url, "gripper", link7,
"body", X_7G, plant_);
RegisterWsgControllerModel(
PackageMap{}.ResolveUrl(sdf_url), wsg_instance, link7,
plant_->GetFrameByName("body", wsg_instance), X_7G);
}
} // namespace manipulation_station
} // namespace examples
} // namespace drake
// TODO(russt): Support at least NONSYMBOLIC_SCALARS. See #9573.
// (and don't forget to include default_scalars.h)
template class ::drake::examples::manipulation_station::ManipulationStation<
double>;
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/manipulation_station/end_effector_teleop_mouse.py | import argparse
import os
import sys
import webbrowser
import numpy as np
from pydrake.common.value import Value
from pydrake.examples import (
ManipulationStation, ManipulationStationHardwareInterface,
CreateClutterClearingYcbObjectList, SchunkCollisionModel)
from pydrake.geometry import DrakeVisualizer, Meshcat, MeshcatVisualizer
from pydrake.math import RigidTransform, RollPitchYaw, RotationMatrix
from pydrake.multibody.inverse_kinematics import (
DifferentialInverseKinematicsIntegrator,
DifferentialInverseKinematicsParameters)
from pydrake.multibody.plant import MultibodyPlant
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import DiagramBuilder, LeafSystem
from pydrake.systems.primitives import FirstOrderLowPassFilter
# On macOS, our setup scripts do not provide pygame so we need to skip this
# program and its tests. On Ubuntu, we do expect to have pygame.
if sys.platform == "darwin":
try:
import pygame
from pygame.locals import *
except ImportError:
print("ERROR: missing pygame. "
"Please install pygame to use this example.")
sys.exit(0)
else:
import pygame
from pygame.locals import *
def print_instructions():
print("")
print("END EFFECTOR CONTROL")
print("mouse left/right - move in the manipulation station's y/z plane")
print("mouse buttons - roll left/right")
print("w / s - move forward/back this y/z plane")
print("q / e - yaw left/right \
(also can use mouse side buttons)")
print("a / d - pitch up/down")
print("")
print("GRIPPER CONTROL")
print("mouse wheel - open/close gripper")
print("")
print("space - switch out of teleop mode")
print("enter - return to teleop mode (be sure you've")
print(" returned focus to the pygame app)")
print("escape - quit")
class TeleopMouseKeyboardManager():
def __init__(self, grab_focus=True):
pygame.init()
# We don't actually want a screen, but
# I can't get this to work without a tiny screen.
# Setting it to 1 pixel.
screen_size = 1
self.screen = pygame.display.set_mode((screen_size, screen_size))
self.side_button_back_DOWN = False
self.side_button_fwd_DOWN = False
if grab_focus:
self.grab_mouse_focus()
def grab_mouse_focus(self):
pygame.event.set_grab(True)
pygame.mouse.set_visible(False)
def release_mouse_focus(self):
pygame.event.set_grab(False)
pygame.mouse.set_visible(True)
def get_events(self):
mouse_wheel_up = mouse_wheel_down = False
for event in pygame.event.get():
if event.type == QUIT:
sys.exit(0)
elif event.type == KEYDOWN and event.key == K_ESCAPE:
sys.exit(0)
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 4:
mouse_wheel_up = True
if event.button == 5:
mouse_wheel_down = True
if event.button == 8:
self.side_button_back_DOWN = True
if event.button == 9:
self.side_button_fwd_DOWN = True
if event.type == pygame.MOUSEBUTTONUP:
if event.button == 8:
self.side_button_back_DOWN = False
if event.button == 9:
self.side_button_fwd_DOWN = False
keys = pygame.key.get_pressed()
delta_x, delta_y = pygame.mouse.get_rel()
left_mouse_button, _, right_mouse_button = pygame.mouse.get_pressed()
if keys[K_RETURN]:
self.grab_mouse_focus()
if keys[K_SPACE]:
self.release_mouse_focus()
events = dict()
events["delta_x"] = delta_x
events["delta_y"] = delta_y
events["w"] = keys[K_w]
events["a"] = keys[K_a]
events["s"] = keys[K_s]
events["d"] = keys[K_d]
events["r"] = keys[K_r]
events["q"] = keys[K_q]
events["e"] = keys[K_e]
events["mouse_wheel_up"] = mouse_wheel_up
events["mouse_wheel_down"] = mouse_wheel_down
events["left_mouse_button"] = left_mouse_button
events["right_mouse_button"] = right_mouse_button
events["side_button_back"] = self.side_button_back_DOWN
events["side_button_forward"] = self.side_button_fwd_DOWN
return events
class MouseKeyboardTeleop(LeafSystem):
def __init__(self, grab_focus=True):
LeafSystem.__init__(self)
# Note: Disable caching because the teleop_manager has undeclared
# state.
self.DeclareVectorOutputPort(
"rpy_xyz", 6, self.DoCalcOutput).disable_caching_by_default()
self.DeclareVectorOutputPort(
"position", 1,
self.CalcPositionOutput).disable_caching_by_default()
self.DeclareVectorOutputPort("force_limit", 1,
self.CalcForceLimitOutput)
# Note: This timing affects the keyboard teleop performance. A larger
# time step causes more lag in the response.
self.DeclarePeriodicPublishEvent(0.01, 0.0, lambda _: None)
self.teleop_manager = TeleopMouseKeyboardManager(grab_focus=grab_focus)
self.roll = self.pitch = self.yaw = 0
self.x = self.y = self.z = 0
self.gripper_max = 0.107
self.gripper_min = 0.01
self.gripper_goal = self.gripper_max
def SetPose(self, pose):
"""
@param pose is a RigidTransform or else any type accepted by
RigidTransform's constructor
"""
tf = RigidTransform(pose)
self.SetRPY(RollPitchYaw(tf.rotation()))
self.SetXYZ(pose.translation())
def SetRPY(self, rpy):
"""
@param rpy is a RollPitchYaw object
"""
self.roll = rpy.roll_angle()
self.pitch = rpy.pitch_angle()
self.yaw = rpy.yaw_angle()
def SetXYZ(self, xyz):
"""
@param xyz is a 3 element vector of x, y, z.
"""
self.x = xyz[0]
self.y = xyz[1]
self.z = xyz[2]
def SetXyzFromEvents(self, events):
scale_down = 0.0001
delta_x = events["delta_x"]*-scale_down
delta_y = events["delta_y"]*-scale_down
forward_scale = 0.00005
delta_forward = 0.0
if events["w"]:
delta_forward += forward_scale
if events["s"]:
delta_forward -= forward_scale
self.x += delta_forward
self.y += delta_x
self.z += delta_y
def SetRpyFromEvents(self, events):
roll_scale = 0.0003
if events["left_mouse_button"]:
self.roll += roll_scale
if events["right_mouse_button"]:
self.roll -= roll_scale
self.roll = np.clip(self.roll, a_min=-2*np.pi, a_max=2*np.pi)
yaw_scale = 0.0003
if events["side_button_back"] or events["q"]:
self.yaw += yaw_scale
if events["side_button_forward"] or events["e"]:
self.yaw -= yaw_scale
self.yaw = np.clip(self.yaw, a_min=-2*np.pi, a_max=2*np.pi)
pitch_scale = 0.0003
if events["d"]:
self.pitch += pitch_scale
if events["a"]:
self.pitch -= pitch_scale
self.pitch = np.clip(self.pitch, a_min=-2*np.pi, a_max=2*np.pi)
def SetGripperFromEvents(self, events):
gripper_scale = 0.01
if events["mouse_wheel_up"]:
self.gripper_goal += gripper_scale
if events["mouse_wheel_down"]:
self.gripper_goal -= gripper_scale
self.gripper_goal = np.clip(self.gripper_goal,
a_min=self.gripper_min,
a_max=self.gripper_max)
def CalcPositionOutput(self, context, output):
output.SetAtIndex(0, self.gripper_goal)
def CalcForceLimitOutput(self, context, output):
self._force_limit = 40
output.SetAtIndex(0, self._force_limit)
def DoCalcOutput(self, context, output):
events = self.teleop_manager.get_events()
self.SetXyzFromEvents(events)
self.SetRpyFromEvents(events)
self.SetGripperFromEvents(events)
output.SetAtIndex(0, self.roll)
output.SetAtIndex(1, self.pitch)
output.SetAtIndex(2, self.yaw)
output.SetAtIndex(3, self.x)
output.SetAtIndex(4, self.y)
output.SetAtIndex(5, self.z)
class ToPose(LeafSystem):
def __init__(self, grab_focus=True):
LeafSystem.__init__(self)
self.DeclareVectorInputPort("rpy_xyz", 6)
self.DeclareAbstractOutputPort(
"pose", lambda: Value(RigidTransform()),
self.DoCalcOutput)
def DoCalcOutput(self, context, output):
rpy_xyz = self.get_input_port().Eval(context)
output.set_value(RigidTransform(RollPitchYaw(rpy_xyz[:3]),
rpy_xyz[3:]))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--target_realtime_rate", type=float, default=1.0,
help="Desired rate relative to real time. See documentation for "
"Simulator::set_target_realtime_rate() for details.")
parser.add_argument(
"--duration", type=float, default=np.inf,
help="Desired duration of the simulation in seconds.")
parser.add_argument(
"--hardware", action='store_true',
help="Use the ManipulationStationHardwareInterface instead of an "
"in-process simulation.")
parser.add_argument(
"--test", action='store_true',
help="Disable opening the gui window for testing.")
parser.add_argument(
"--filter_time_const", type=float, default=0.005,
help="Time constant for the first order low pass filter applied to"
"the teleop commands")
parser.add_argument(
"--velocity_limit_factor", type=float, default=1.0,
help="This value, typically between 0 and 1, further limits the "
"iiwa14 joint velocities. It multiplies each of the seven "
"pre-defined joint velocity limits. "
"Note: The pre-defined velocity limits are specified by "
"iiwa14_velocity_limits, found in this python file.")
parser.add_argument(
'--setup', type=str, default='manipulation_class',
help="The manipulation station setup to simulate. ",
choices=['manipulation_class', 'clutter_clearing'])
parser.add_argument(
'--schunk_collision_model', type=str, default='box',
help="The Schunk collision model to use for simulation. ",
choices=['box', 'box_plus_fingertip_spheres'])
parser.add_argument(
"--meshcat", action="store_true", default=False,
help="Enable visualization with meshcat.")
parser.add_argument(
"-w", "--open-window", dest="browser_new",
action="store_const", const=1, default=None,
help="Open the MeshCat display in a new browser window.")
args = parser.parse_args()
if args.test:
# Don't grab mouse focus during testing.
grab_focus = False
# See: https://stackoverflow.com/a/52528832/7829525
os.environ["SDL_VIDEODRIVER"] = "dummy"
else:
grab_focus = True
builder = DiagramBuilder()
if args.hardware:
station = builder.AddSystem(ManipulationStationHardwareInterface())
station.Connect(wait_for_cameras=False)
else:
station = builder.AddSystem(ManipulationStation())
if args.schunk_collision_model == "box":
schunk_model = SchunkCollisionModel.kBox
elif args.schunk_collision_model == "box_plus_fingertip_spheres":
schunk_model = SchunkCollisionModel.kBoxPlusFingertipSpheres
# Initializes the chosen station type.
if args.setup == 'manipulation_class':
station.SetupManipulationClassStation(
schunk_model=schunk_model)
station.AddManipulandFromFile(
"drake_models/manipulation_station/061_foam_brick.sdf",
RigidTransform(RotationMatrix.Identity(), [0.6, 0, 0]))
elif args.setup == 'clutter_clearing':
station.SetupClutterClearingStation(
schunk_model=schunk_model)
ycb_objects = CreateClutterClearingYcbObjectList()
for model_file, X_WObject in ycb_objects:
station.AddManipulandFromFile(model_file, X_WObject)
station.Finalize()
query_port = station.GetOutputPort("query_object")
DrakeVisualizer.AddToBuilder(builder, query_port)
if args.meshcat:
meshcat = Meshcat()
meshcat_visualizer = MeshcatVisualizer.AddToBuilder(
builder=builder,
query_object_port=query_port,
meshcat=meshcat)
if args.setup == 'planar':
meshcat.Set2dRenderMode()
if args.browser_new is not None:
url = meshcat.web_url()
webbrowser.open(url=url, new=args.browser_new)
robot = station.get_controller_plant()
params = DifferentialInverseKinematicsParameters(robot.num_positions(),
robot.num_velocities())
time_step = 0.005
params.set_time_step(time_step)
# True velocity limits for the IIWA14 (in rad, rounded down to the first
# decimal)
iiwa14_velocity_limits = np.array([1.4, 1.4, 1.7, 1.3, 2.2, 2.3, 2.3])
# Stay within a small fraction of those limits for this teleop demo.
factor = args.velocity_limit_factor
params.set_joint_velocity_limits((-factor*iiwa14_velocity_limits,
factor*iiwa14_velocity_limits))
differential_ik = builder.AddSystem(
DifferentialInverseKinematicsIntegrator(
robot, robot.GetFrameByName("iiwa_link_7"), time_step, params))
builder.Connect(differential_ik.GetOutputPort("joint_positions"),
station.GetInputPort("iiwa_position"))
teleop = builder.AddSystem(MouseKeyboardTeleop(grab_focus=grab_focus))
filter_ = builder.AddSystem(
FirstOrderLowPassFilter(time_constant=args.filter_time_const, size=6))
builder.Connect(teleop.get_output_port(0), filter_.get_input_port(0))
to_pose = builder.AddSystem(ToPose())
builder.Connect(filter_.get_output_port(0),
to_pose.get_input_port())
builder.Connect(to_pose.get_output_port(),
differential_ik.GetInputPort("X_WE_desired"))
builder.Connect(teleop.GetOutputPort("position"), station.GetInputPort(
"wsg_position"))
builder.Connect(teleop.GetOutputPort("force_limit"),
station.GetInputPort("wsg_force_limit"))
diagram = builder.Build()
simulator = Simulator(diagram)
# This is important to avoid duplicate publishes to the hardware interface:
simulator.set_publish_every_time_step(False)
station_context = diagram.GetMutableSubsystemContext(
station, simulator.get_mutable_context())
station.GetInputPort("iiwa_feedforward_torque").FixValue(
station_context, np.zeros(7))
# If the diagram is only the hardware interface, then we must advance it a
# little bit so that first LCM messages get processed. A simulated plant is
# already publishing correct positions even without advancing, and indeed
# we must not advance a simulated plant until the sliders and filters have
# been initialized to match the plant.
if args.hardware:
simulator.AdvanceTo(1e-6)
q0 = station.GetOutputPort("iiwa_position_measured").Eval(station_context)
differential_ik.get_mutable_parameters().set_nominal_joint_position(q0)
differential_ik.SetPositions(
differential_ik.GetMyMutableContextFromRoot(
simulator.get_mutable_context()), q0)
teleop.SetPose(
differential_ik.ForwardKinematics(
differential_ik.GetMyContextFromRoot(simulator.get_context())))
filter_.set_initial_output_value(
diagram.GetMutableSubsystemContext(
filter_, simulator.get_mutable_context()),
teleop.get_output_port(0).Eval(diagram.GetMutableSubsystemContext(
teleop, simulator.get_mutable_context())))
simulator.set_target_realtime_rate(args.target_realtime_rate)
print_instructions()
simulator.AdvanceTo(args.duration)
if __name__ == '__main__':
main()
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/manipulation_station/schunk_wsg_buttons.py | from pydrake.systems.framework import LeafSystem
class SchunkWsgButtons(LeafSystem):
"""
Adds buttons to open/close the Schunk WSG gripper.
.. pydrake_system::
name: SchunkWsgButtons
output_ports:
- position
- max_force
"""
_BUTTON_NAME = "Open/Close Gripper"
"""The name of the button added to the meshcat UI."""
def __init__(self, meshcat, open_position=0.107, closed_position=0.002,
force_limit=40):
""""
Args:
open_position: Target position for the gripper when open.
closed_position: Target position for the gripper when closed.
**Warning**: closing to 0mm can smash the fingers
together and keep applying force even when no
object is grasped.
force_limit: Force limit to send to Schunk WSG controller.
"""
super().__init__()
self.meshcat = meshcat
self.DeclareVectorOutputPort("position", 1, self.CalcPositionOutput)
self.DeclareVectorOutputPort("force_limit", 1,
self.CalcForceLimitOutput)
self._open_button = meshcat.AddButton(self._BUTTON_NAME)
self._open_position = open_position
self._closed_position = closed_position
self._force_limit = force_limit
def CalcPositionOutput(self, context, output):
if self.meshcat.GetButtonClicks(name=self._BUTTON_NAME) % 2 == 0:
output.SetAtIndex(0, self._open_position)
else:
output.SetAtIndex(0, self._closed_position)
def CalcForceLimitOutput(self, context, output):
output.SetAtIndex(0, self._force_limit)
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/manipulation_station/README.md | Robotic Manipulation
====================
This directory contains a C++ implementation of the ManipulationStation Diagram
originally designed to support the Robotic Manipulation class at MIT.
Course website: https://manipulation.csail.mit.edu
The course no longer uses this C++ version; we now set up the
ManipulationStation completely in Python so that it is easier for students to
modify. That Python implementation can be found in the online notebooks
available from the course website linked above.
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/manipulation_station/proof_of_life.cc | #include <gflags/gflags.h>
#include "drake/common/eigen_types.h"
#include "drake/common/find_resource.h"
#include "drake/common/fmt_eigen.h"
#include "drake/common/is_approx_equal_abstol.h"
#include "drake/examples/manipulation_station/manipulation_station.h"
#include "drake/geometry/drake_visualizer.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/multibody/plant/contact_results_to_lcm.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/diagram.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/sensors/image_to_lcm_image_array_t.h"
namespace drake {
namespace examples {
namespace manipulation_station {
namespace {
// Simple example which simulates the manipulation station (and transmits
// visualization data for Meldis to display).
// TODO(russt): Replace this with a slightly more interesting minimal example
// (e.g. picking up an object) and perhaps a slightly more descriptive name.
using Eigen::VectorXd;
using math::RigidTransform;
using math::RollPitchYaw;
using math::RotationMatrix;
DEFINE_double(target_realtime_rate, 1.0,
"Playback speed. See documentation for "
"Simulator::set_target_realtime_rate() for details.");
DEFINE_double(duration, 4.0, "Simulation duration.");
DEFINE_bool(test, false, "Disable random initial conditions in test mode.");
DEFINE_string(setup, "clutter_clearing", "Manipulation Station setup option.");
int do_main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
systems::DiagramBuilder<double> builder;
// Create the "manipulation station".
auto station = builder.AddSystem<ManipulationStation>();
if (FLAGS_setup == "clutter_clearing") {
station->SetupClutterClearingStation(std::nullopt);
station->AddManipulandFromFile(
"drake_models/ycb/003_cracker_box.sdf",
RigidTransform<double>(RollPitchYaw<double>(-1.57, 0, 3),
Eigen::Vector3d(-0.3, -0.55, 0.36)));
} else if (FLAGS_setup == "manipulation_class") {
station->SetupManipulationClassStation();
station->AddManipulandFromFile(
"drake_models/manipulation_station/061_foam_brick.sdf",
RigidTransform<double>(RotationMatrix<double>::Identity(),
Eigen::Vector3d(0.6, 0, 0)));
} else if (FLAGS_setup == "planar") {
station->SetupPlanarIiwaStation();
station->AddManipulandFromFile(
"drake_models/manipulation_station/061_foam_brick.sdf",
RigidTransform<double>(RotationMatrix<double>::Identity(),
Eigen::Vector3d(0.6, 0, 0)));
} else {
throw std::domain_error(
"Unrecognized setup option. Options are "
"{manipulation_class, clutter_clearing}.");
}
station->Finalize();
geometry::DrakeVisualizerd::AddToBuilder(
&builder, station->GetOutputPort("query_object"));
multibody::ConnectContactResultsToDrakeVisualizer(
&builder, station->get_mutable_multibody_plant(),
station->get_scene_graph(), station->GetOutputPort("contact_results"));
auto image_to_lcm_image_array =
builder.template AddSystem<systems::sensors::ImageToLcmImageArrayT>();
image_to_lcm_image_array->set_name("converter");
for (const auto& name : station->get_camera_names()) {
const auto& cam_port =
image_to_lcm_image_array
->DeclareImageInputPort<systems::sensors::PixelType::kRgba8U>(
"camera_" + name);
builder.Connect(station->GetOutputPort("camera_" + name + "_rgb_image"),
cam_port);
}
auto image_array_lcm_publisher = builder.template AddSystem(
systems::lcm::LcmPublisherSystem::Make<lcmt_image_array>(
"DRAKE_RGBD_CAMERA_IMAGES", nullptr,
1.0 / 10 /* 10 fps publish period */));
image_array_lcm_publisher->set_name("rgbd_publisher");
builder.Connect(image_to_lcm_image_array->image_array_t_msg_output_port(),
image_array_lcm_publisher->get_input_port());
auto diagram = builder.Build();
systems::Simulator<double> simulator(*diagram);
auto& station_context = diagram->GetMutableSubsystemContext(
*station, &simulator.get_mutable_context());
// Position command should hold the arm at the initial state.
Eigen::VectorXd q0 = station->GetIiwaPosition(station_context);
station->GetInputPort("iiwa_position").FixValue(&station_context, q0);
// Zero feed-forward torque.
station->GetInputPort("iiwa_feedforward_torque")
.FixValue(&station_context, VectorXd::Zero(station->num_iiwa_joints()));
// Nominal WSG position is open.
station->GetInputPort("wsg_position").FixValue(&station_context, 0.1);
// Force limit at 40N.
station->GetInputPort("wsg_force_limit").FixValue(&station_context, 40.0);
if (!FLAGS_test) {
std::random_device rd;
RandomGenerator generator{rd()};
diagram->SetRandomContext(&simulator.get_mutable_context(), &generator);
}
simulator.set_target_realtime_rate(FLAGS_target_realtime_rate);
simulator.AdvanceTo(FLAGS_duration);
// Check that the arm is (very roughly) in the commanded position.
VectorXd q = station->GetIiwaPosition(station_context);
if (!is_approx_equal_abstol(q, q0, 1.e-3)) {
fmt::print("q is not sufficiently close to q0.\n");
fmt::print("q - q0 = {}\n", fmt_eigen((q - q0).transpose()));
return EXIT_FAILURE;
}
return 0;
}
} // namespace
} // namespace manipulation_station
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
return drake::examples::manipulation_station::do_main(argc, argv);
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/manipulation_station/end_effector_teleop_sliders.py | import argparse
from dataclasses import dataclass
import sys
import webbrowser
import numpy as np
from pydrake.common.value import Value
from pydrake.examples import (
ManipulationStation, ManipulationStationHardwareInterface,
CreateClutterClearingYcbObjectList, SchunkCollisionModel)
from pydrake.geometry import DrakeVisualizer, Meshcat, MeshcatVisualizer
from pydrake.math import RigidTransform, RollPitchYaw, RotationMatrix
from pydrake.multibody.inverse_kinematics import (
DifferentialInverseKinematicsIntegrator,
DifferentialInverseKinematicsParameters)
from pydrake.systems.analysis import Simulator
from pydrake.systems.framework import (DiagramBuilder, LeafSystem,
PublishEvent)
from pydrake.systems.lcm import LcmPublisherSystem
from pydrake.systems.primitives import FirstOrderLowPassFilter, VectorLogSink
from pydrake.systems.sensors import ImageToLcmImageArrayT, PixelType
from examples.manipulation_station.schunk_wsg_buttons import SchunkWsgButtons
from drake import lcmt_image_array
class EndEffectorTeleop(LeafSystem):
@dataclass
class SliderDefault:
"""Default values for the meshcat sliders."""
name: str
"""The name that is used to add / query values from."""
default: float
"""The initial value of the slider."""
_ROLL = SliderDefault("Roll", 0.0)
_PITCH = SliderDefault("Pitch", 0.0)
_YAW = SliderDefault("Yaw", 1.57)
_X = SliderDefault("X", 0.0)
_Y = SliderDefault("Y", 0.0)
_Z = SliderDefault("Z", 0.0)
def __init__(self, meshcat, planar=False):
"""
@param meshcat The already created pydrake.geometry.Meshcat instance.
@param planar if True, the GUI will not have Pitch, Yaw, or Y-axis
sliders and default values will be returned.
"""
LeafSystem.__init__(self)
# Note: Disable caching because meshcat's sliders have undeclared
# state.
self.DeclareVectorOutputPort(
"rpy_xyz", 6, self.DoCalcOutput).disable_caching_by_default()
self.meshcat = meshcat
self.planar = planar
# Rotation control sliders.
self.meshcat.AddSlider(
name=self._ROLL.name, min=-2.0 * np.pi, max=2.0 * np.pi, step=0.01,
value=self._ROLL.default)
if not self.planar:
self.meshcat.AddSlider(
name=self._PITCH.name, min=-2.0 * np.pi, max=2.0 * np.pi,
step=0.01, value=self._PITCH.default)
self.meshcat.AddSlider(
name=self._YAW.name, min=-2.0 * np.pi, max=2.0 * np.pi,
step=0.01, value=self._YAW.default)
# Position control sliders.
self.meshcat.AddSlider(
name=self._X.name, min=-0.6, max=0.8, step=0.01,
value=self._X.default)
if not self.planar:
self.meshcat.AddSlider(
name=self._Y.name, min=-0.8, max=0.3, step=0.01,
value=self._Y.default)
self.meshcat.AddSlider(
name=self._Z.name, min=0.0, max=1.1, step=0.01,
value=self._Z.default)
def SetPose(self, pose):
"""
@param pose is a RigidTransform or else any type accepted by
RigidTransform's constructor
"""
tf = RigidTransform(pose)
self.SetRPY(RollPitchYaw(tf.rotation()))
self.SetXYZ(tf.translation())
def SetRPY(self, rpy):
"""
@param rpy is a RollPitchYaw object
"""
self.meshcat.SetSliderValue(self._ROLL.name, rpy.roll_angle())
if not self.planar:
self.meshcat.SetSliderValue(self._PITCH.name, rpy.pitch_angle())
self.meshcat.SetSliderValue(self._YAW.name, rpy.yaw_angle())
def SetXYZ(self, xyz):
"""
@param xyz is a 3 element vector of x, y, z.
"""
self.meshcat.SetSliderValue(self._X.name, xyz[0])
if not self.planar:
self.meshcat.SetSliderValue(self._Y.name, xyz[1])
self.meshcat.SetSliderValue(self._Z.name, xyz[2])
def DoCalcOutput(self, context, output):
roll = self.meshcat.GetSliderValue(self._ROLL.name)
if not self.planar:
pitch = self.meshcat.GetSliderValue(self._PITCH.name)
yaw = self.meshcat.GetSliderValue(self._YAW.name)
else:
pitch = self._PITCH.default
yaw = self._YAW.default
x = self.meshcat.GetSliderValue(self._X.name)
if not self.planar:
y = self.meshcat.GetSliderValue(self._Y.name)
else:
y = self._Y.default
z = self.meshcat.GetSliderValue(self._Z.name)
output.SetAtIndex(0, roll)
output.SetAtIndex(1, pitch)
output.SetAtIndex(2, yaw)
output.SetAtIndex(3, x)
output.SetAtIndex(4, y)
output.SetAtIndex(5, z)
class ToPose(LeafSystem):
def __init__(self, grab_focus=True):
LeafSystem.__init__(self)
self.DeclareVectorInputPort("rpy_xyz", 6)
self.DeclareAbstractOutputPort(
"pose", lambda: Value(RigidTransform()),
self.DoCalcOutput)
def DoCalcOutput(self, context, output):
rpy_xyz = self.get_input_port().Eval(context)
output.set_value(RigidTransform(RollPitchYaw(rpy_xyz[:3]),
rpy_xyz[3:]))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--target_realtime_rate", type=float, default=1.0,
help="Desired rate relative to real time. See documentation for "
"Simulator::set_target_realtime_rate() for details.")
parser.add_argument(
"--duration", type=float, default=np.inf,
help="Desired duration of the simulation in seconds.")
parser.add_argument(
"--hardware", action='store_true',
help="Use the ManipulationStationHardwareInterface instead of an "
"in-process simulation.")
parser.add_argument(
"--test", action='store_true',
help="Disable opening the gui window for testing.")
parser.add_argument(
"--filter_time_const", type=float, default=0.1,
help="Time constant for the first order low pass filter applied to"
"the teleop commands")
parser.add_argument(
"--velocity_limit_factor", type=float, default=1.0,
help="This value, typically between 0 and 1, further limits the "
"iiwa14 joint velocities. It multiplies each of the seven "
"pre-defined joint velocity limits. "
"Note: The pre-defined velocity limits are specified by "
"iiwa14_velocity_limits, found in this python file.")
parser.add_argument(
'--setup', type=str, default='manipulation_class',
help="The manipulation station setup to simulate. ",
choices=['manipulation_class', 'clutter_clearing', 'planar'])
parser.add_argument(
'--schunk_collision_model', type=str, default='box',
help="The Schunk collision model to use for simulation. ",
choices=['box', 'box_plus_fingertip_spheres'])
parser.add_argument(
"-w", "--open-window", dest="browser_new",
action="store_const", const=1, default=None,
help=(
"Open the MeshCat display in a new browser window. NOTE: the "
"slider controls are available in the meshcat viewer by clicking "
"'Open Controls' in the top-right corner."))
args = parser.parse_args()
builder = DiagramBuilder()
# NOTE: the meshcat instance is always created in order to create the
# teleop controls (orientation sliders and open/close gripper button). When
# args.hardware is True, the meshcat server will *not* display robot
# geometry, but it will contain the joint sliders and open/close gripper
# button in the "Open Controls" tab in the top-right of the viewing server.
meshcat = Meshcat()
if args.hardware:
station = builder.AddSystem(ManipulationStationHardwareInterface())
station.Connect(wait_for_cameras=False)
else:
station = builder.AddSystem(ManipulationStation())
if args.schunk_collision_model == "box":
schunk_model = SchunkCollisionModel.kBox
elif args.schunk_collision_model == "box_plus_fingertip_spheres":
schunk_model = SchunkCollisionModel.kBoxPlusFingertipSpheres
# Initializes the chosen station type.
if args.setup == 'manipulation_class':
station.SetupManipulationClassStation(
schunk_model=schunk_model)
station.AddManipulandFromFile(
"drake_models/manipulation_station/061_foam_brick.sdf",
RigidTransform(RotationMatrix.Identity(), [0.6, 0, 0]))
elif args.setup == 'clutter_clearing':
station.SetupClutterClearingStation(
schunk_model=schunk_model)
ycb_objects = CreateClutterClearingYcbObjectList()
for model_file, X_WObject in ycb_objects:
station.AddManipulandFromFile(model_file, X_WObject)
elif args.setup == 'planar':
station.SetupPlanarIiwaStation(
schunk_model=schunk_model)
station.AddManipulandFromFile(
"drake_models/manipulation_station/061_foam_brick.sdf",
RigidTransform(RotationMatrix.Identity(), [0.6, 0, 0]))
station.Finalize()
# If using meshcat, don't render the cameras, since RgbdCamera
# rendering only works with Meldis (modulo #18862). Without this check,
# running this code in a docker container produces libGL errors.
geometry_query_port = station.GetOutputPort("geometry_query")
# Connect the meshcat visualizer.
meshcat_visualizer = MeshcatVisualizer.AddToBuilder(
builder=builder,
query_object_port=geometry_query_port,
meshcat=meshcat)
# Configure the planar visualization.
if args.setup == 'planar':
meshcat.Set2dRenderMode()
# Connect LCM visualization.
DrakeVisualizer.AddToBuilder(builder, geometry_query_port)
image_to_lcm_image_array = builder.AddSystem(
ImageToLcmImageArrayT())
image_to_lcm_image_array.set_name("converter")
for name in station.get_camera_names():
cam_port = (
image_to_lcm_image_array
.DeclareImageInputPort[PixelType.kRgba8U](
"camera_" + name))
builder.Connect(
station.GetOutputPort("camera_" + name + "_rgb_image"),
cam_port)
image_array_lcm_publisher = builder.AddSystem(
LcmPublisherSystem.Make(
channel="DRAKE_RGBD_CAMERA_IMAGES",
lcm_type=lcmt_image_array,
lcm=None,
publish_period=0.1,
use_cpp_serializer=True))
image_array_lcm_publisher.set_name("rgbd_publisher")
builder.Connect(
image_to_lcm_image_array.image_array_t_msg_output_port(),
image_array_lcm_publisher.get_input_port(0))
if args.browser_new is not None:
url = meshcat.web_url()
webbrowser.open(url=url, new=args.browser_new)
robot = station.get_controller_plant()
params = DifferentialInverseKinematicsParameters(robot.num_positions(),
robot.num_velocities())
time_step = 0.005
params.set_time_step(time_step)
# True velocity limits for the IIWA14 (in rad, rounded down to the first
# decimal)
iiwa14_velocity_limits = np.array([1.4, 1.4, 1.7, 1.3, 2.2, 2.3, 2.3])
if args.setup == 'planar':
# Extract the 3 joints that are not welded in the planar version.
iiwa14_velocity_limits = iiwa14_velocity_limits[1:6:2]
# The below constant is in body frame.
params.set_end_effector_velocity_gain([1, 0, 0, 0, 1, 1])
# Stay within a small fraction of those limits for this teleop demo.
factor = args.velocity_limit_factor
params.set_joint_velocity_limits(
(-factor * iiwa14_velocity_limits, factor * iiwa14_velocity_limits))
differential_ik = builder.AddSystem(
DifferentialInverseKinematicsIntegrator(
robot, robot.GetFrameByName("iiwa_link_7"), time_step, params))
builder.Connect(differential_ik.GetOutputPort("joint_positions"),
station.GetInputPort("iiwa_position"))
teleop = builder.AddSystem(EndEffectorTeleop(
meshcat, args.setup == 'planar'))
filter = builder.AddSystem(
FirstOrderLowPassFilter(time_constant=args.filter_time_const, size=6))
builder.Connect(teleop.get_output_port(0), filter.get_input_port(0))
to_pose = builder.AddSystem(ToPose())
builder.Connect(filter.get_output_port(0),
to_pose.get_input_port())
builder.Connect(to_pose.get_output_port(),
differential_ik.GetInputPort("X_WE_desired"))
wsg_buttons = builder.AddSystem(SchunkWsgButtons(meshcat=meshcat))
builder.Connect(wsg_buttons.GetOutputPort("position"),
station.GetInputPort("wsg_position"))
builder.Connect(wsg_buttons.GetOutputPort("force_limit"),
station.GetInputPort("wsg_force_limit"))
# When in regression test mode, log our joint velocities to later check
# that they were sufficiently quiet.
num_iiwa_joints = station.num_iiwa_joints()
if args.test:
iiwa_velocities = builder.AddSystem(VectorLogSink(num_iiwa_joints))
builder.Connect(station.GetOutputPort("iiwa_velocity_estimated"),
iiwa_velocities.get_input_port(0))
else:
iiwa_velocities = None
diagram = builder.Build()
simulator = Simulator(diagram)
# This is important to avoid duplicate publishes to the hardware interface:
simulator.set_publish_every_time_step(False)
station_context = diagram.GetMutableSubsystemContext(
station, simulator.get_mutable_context())
station.GetInputPort("iiwa_feedforward_torque").FixValue(
station_context, np.zeros(num_iiwa_joints))
# If the diagram is only the hardware interface, then we must advance it a
# little bit so that first LCM messages get processed. A simulated plant is
# already publishing correct positions even without advancing, and indeed
# we must not advance a simulated plant until the sliders and filters have
# been initialized to match the plant.
if args.hardware:
simulator.AdvanceTo(1e-6)
q0 = station.GetOutputPort("iiwa_position_measured").Eval(
station_context)
differential_ik.get_mutable_parameters().set_nominal_joint_position(q0)
differential_ik.SetPositions(
differential_ik.GetMyMutableContextFromRoot(
simulator.get_mutable_context()), q0)
teleop.SetPose(
differential_ik.ForwardKinematics(
differential_ik.GetMyContextFromRoot(simulator.get_context())))
filter.set_initial_output_value(
diagram.GetMutableSubsystemContext(
filter, simulator.get_mutable_context()),
teleop.get_output_port(0).Eval(diagram.GetMutableSubsystemContext(
teleop, simulator.get_mutable_context())))
simulator.set_target_realtime_rate(args.target_realtime_rate)
simulator.AdvanceTo(args.duration)
# Ensure that our initialization logic was correct, by inspecting our
# logged joint velocities.
if args.test:
iiwa_velocities_log = iiwa_velocities.FindLog(simulator.get_context())
for time, qdot in zip(iiwa_velocities_log.sample_times(),
iiwa_velocities_log.data().transpose()):
# TODO(jwnimmer-tri) We should be able to do better than a 40
# rad/sec limit, but that's the best we can enforce for now.
if qdot.max() > 0.1:
print(f"ERROR: large qdot {qdot} at time {time}")
sys.exit(1)
if __name__ == '__main__':
main()
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/manipulation_station/manipulation_station_hardware_interface.h | #pragma once
#include <memory>
#include <string>
#include <vector>
#include "drake/lcm/drake_lcm.h"
#include "drake/lcm/drake_lcm_interface.h"
#include "drake/multibody/plant/multibody_plant.h"
#include "drake/systems/framework/diagram.h"
#include "drake/systems/lcm/lcm_subscriber_system.h"
namespace drake {
namespace examples {
namespace manipulation_station {
/// A System that connects via message-passing to the hardware manipulation
/// station.
///
/// Note: Users must call Connect() after initialization.
///
/// @{
///
/// @system
/// name: ManipulationStationHardwareInterface
/// input_ports:
/// - iiwa_position
/// - iiwa_feedforward_torque
/// - wsg_position
/// - wsg_force_limit (optional)
/// output_ports:
/// - iiwa_position_commanded
/// - iiwa_position_measured
/// - iiwa_velocity_estimated
/// - iiwa_torque_commanded
/// - iiwa_torque_measured
/// - iiwa_torque_external
/// - wsg_state_measured
/// - wsg_force_measured
/// - camera_[NAME]_rgb_image
/// - camera_[NAME]_depth_image
/// - ...
/// - camera_[NAME]_rgb_image
/// - camera_[NAME]_depth_image
/// @endsystem
///
/// @ingroup manipulation_station_systems
/// @}
///
class ManipulationStationHardwareInterface : public systems::Diagram<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(ManipulationStationHardwareInterface)
/// Subscribes to an incoming camera message on the channel
/// DRAKE_RGBD_CAMERA_IMAGES_<camera_id>
/// where @p camera_name contains the names/unique ids, typically serial
/// numbers, and declares the output ports camera_%s_rgb_image and
/// camera_%s_depth_image, where %s is the camera name.
ManipulationStationHardwareInterface(
std::vector<std::string> camera_names = {});
/// Starts a thread to receive network messages, and blocks execution until
/// the first messages have been received.
void Connect(bool wait_for_cameras = true);
/// For parity with ManipulationStation, we maintain a MultibodyPlant of
/// the IIWA arm, with the lumped-mass equivalent spatial inertia of the
/// Schunk WSG gripper.
// TODO(russt): Actually add the equivalent mass of the WSG.
const multibody::MultibodyPlant<double>& get_controller_plant() const {
return *owned_controller_plant_;
}
const std::vector<std::string>& get_camera_names() const {
return camera_names_;
}
/// Gets the number of joints in the IIWA (only -- does not include the
/// gripper).
int num_iiwa_joints() const;
private:
std::unique_ptr<multibody::MultibodyPlant<double>> owned_controller_plant_;
std::unique_ptr<lcm::DrakeLcm> owned_lcm_;
systems::lcm::LcmSubscriberSystem* wsg_status_subscriber_;
systems::lcm::LcmSubscriberSystem* iiwa_status_subscriber_;
std::vector<systems::lcm::LcmSubscriberSystem*> camera_subscribers_;
const std::vector<std::string> camera_names_;
multibody::ModelInstanceIndex iiwa_model_instance_{};
};
} // namespace manipulation_station
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/manipulation_station/mock_station_simulation.cc | #include <limits>
#include <gflags/gflags.h>
#include "drake/common/eigen_types.h"
#include "drake/common/find_resource.h"
#include "drake/common/is_approx_equal_abstol.h"
#include "drake/examples/manipulation_station/manipulation_station.h"
#include "drake/geometry/drake_visualizer.h"
#include "drake/lcmt_iiwa_command.hpp"
#include "drake/lcmt_iiwa_status.hpp"
#include "drake/lcmt_point_cloud.hpp"
#include "drake/lcmt_schunk_wsg_command.hpp"
#include "drake/lcmt_schunk_wsg_status.hpp"
#include "drake/manipulation/kuka_iiwa/iiwa_command_receiver.h"
#include "drake/manipulation/kuka_iiwa/iiwa_status_sender.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_lcm.h"
#include "drake/math/rigid_transform.h"
#include "drake/math/rotation_matrix.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/perception/point_cloud_to_lcm.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/diagram.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/matrix_gain.h"
#include "drake/systems/sensors/image_to_lcm_image_array_t.h"
namespace drake {
namespace examples {
namespace manipulation_station {
namespace {
// Runs a simulation of the manipulation station plant as a stand-alone
// simulation which mocks the network inputs and outputs of the real robot
// station. This is a useful test in the transition from a single-process
// simulation to operating on the real robot hardware.
using Eigen::VectorXd;
DEFINE_double(target_realtime_rate, 1.0,
"Playback speed. See documentation for "
"Simulator::set_target_realtime_rate() for details.");
DEFINE_double(duration, std::numeric_limits<double>::infinity(),
"Simulation duration.");
DEFINE_string(setup, "manipulation_class",
"Manipulation station type to simulate. "
"Can be {manipulation_class, clutter_clearing}");
DEFINE_bool(publish_cameras, false,
"Whether to publish camera images to LCM");
DEFINE_bool(publish_point_cloud, false,
"Whether to publish point clouds to LCM. Note that per issue "
"https://github.com/RobotLocomotion/drake/issues/12125 the "
"simulated point cloud data will have registration errors.");
int do_main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
systems::DiagramBuilder<double> builder;
// Create the "manipulation station".
auto station = builder.AddSystem<ManipulationStation>();
if (FLAGS_setup == "manipulation_class") {
station->SetupManipulationClassStation();
station->AddManipulandFromFile(
"drake_models/manipulation_station/061_foam_brick.sdf",
math::RigidTransform<double>(math::RotationMatrix<double>::Identity(),
Eigen::Vector3d(0.6, 0, 0)));
} else if (FLAGS_setup == "clutter_clearing") {
station->SetupClutterClearingStation();
station->AddManipulandFromFile(
"drake_models/ycb/003_cracker_box.sdf",
math::RigidTransform<double>(math::RollPitchYaw<double>(-1.57, 0, 3),
Eigen::Vector3d(-0.3, -0.55, 0.36)));
} else {
throw std::domain_error(
"Unrecognized station type. Options are "
"{manipulation_class, clutter_clearing}.");
}
// TODO(russt): Load sdf objects specified at the command line. Requires
// #9747.
station->Finalize();
geometry::DrakeVisualizerd::AddToBuilder(
&builder, station->GetOutputPort("query_object"));
auto lcm = builder.AddSystem<systems::lcm::LcmInterfaceSystem>();
auto iiwa_command_subscriber = builder.AddSystem(
systems::lcm::LcmSubscriberSystem::Make<drake::lcmt_iiwa_command>(
"IIWA_COMMAND", lcm));
auto iiwa_command =
builder.AddSystem<manipulation::kuka_iiwa::IiwaCommandReceiver>();
builder.Connect(iiwa_command_subscriber->get_output_port(),
iiwa_command->get_message_input_port());
builder.Connect(station->GetOutputPort("iiwa_position_measured"),
iiwa_command->get_position_measured_input_port());
// Pull the positions out of the state.
builder.Connect(iiwa_command->get_commanded_position_output_port(),
station->GetInputPort("iiwa_position"));
builder.Connect(iiwa_command->get_commanded_torque_output_port(),
station->GetInputPort("iiwa_feedforward_torque"));
auto iiwa_status =
builder.AddSystem<manipulation::kuka_iiwa::IiwaStatusSender>();
builder.Connect(station->GetOutputPort("iiwa_position_commanded"),
iiwa_status->get_position_commanded_input_port());
builder.Connect(station->GetOutputPort("iiwa_position_measured"),
iiwa_status->get_position_measured_input_port());
builder.Connect(station->GetOutputPort("iiwa_velocity_estimated"),
iiwa_status->get_velocity_estimated_input_port());
builder.Connect(station->GetOutputPort("iiwa_torque_commanded"),
iiwa_status->get_torque_commanded_input_port());
builder.Connect(station->GetOutputPort("iiwa_torque_measured"),
iiwa_status->get_torque_measured_input_port());
builder.Connect(station->GetOutputPort("iiwa_torque_external"),
iiwa_status->get_torque_external_input_port());
auto iiwa_status_publisher = builder.AddSystem(
systems::lcm::LcmPublisherSystem::Make<drake::lcmt_iiwa_status>(
"IIWA_STATUS", lcm, 0.005 /* publish period */));
builder.Connect(iiwa_status->get_output_port(),
iiwa_status_publisher->get_input_port());
// Receive the WSG commands.
auto wsg_command_subscriber = builder.AddSystem(
systems::lcm::LcmSubscriberSystem::Make<drake::lcmt_schunk_wsg_command>(
"SCHUNK_WSG_COMMAND", lcm));
auto wsg_command =
builder.AddSystem<manipulation::schunk_wsg::SchunkWsgCommandReceiver>();
builder.Connect(wsg_command_subscriber->get_output_port(),
wsg_command->GetInputPort("command_message"));
builder.Connect(wsg_command->get_position_output_port(),
station->GetInputPort("wsg_position"));
builder.Connect(wsg_command->get_force_limit_output_port(),
station->GetInputPort("wsg_force_limit"));
// Publish the WSG status.
auto wsg_status =
builder.AddSystem<manipulation::schunk_wsg::SchunkWsgStatusSender>();
builder.Connect(station->GetOutputPort("wsg_state_measured"),
wsg_status->get_state_input_port());
builder.Connect(station->GetOutputPort("wsg_force_measured"),
wsg_status->get_force_input_port());
auto wsg_status_publisher = builder.AddSystem(
systems::lcm::LcmPublisherSystem::Make<drake::lcmt_schunk_wsg_status>(
"SCHUNK_WSG_STATUS", lcm, 0.05 /* publish period */));
builder.Connect(wsg_status->get_output_port(0),
wsg_status_publisher->get_input_port());
// Publish the camera outputs.
if (FLAGS_publish_cameras) {
auto image_encoder = builder.AddSystem<
systems::sensors::ImageToLcmImageArrayT>();
for (const auto& camera_name : station->get_camera_names()) {
// RGB
const std::string rgb_name = "camera_" + camera_name + "_rgb_image";
const auto& rgb_output = station->GetOutputPort(rgb_name);
const auto& rgb_input =
image_encoder->DeclareImageInputPort<
systems::sensors::PixelType::kRgba8U>(rgb_name);
builder.Connect(rgb_output, rgb_input);
// Depth
const std::string depth_name = "camera_" + camera_name + "_depth_image";
const auto& depth_output = station->GetOutputPort(depth_name);
const auto& depth_input =
image_encoder->DeclareImageInputPort<
systems::sensors::PixelType::kDepth16U>(depth_name);
builder.Connect(depth_output, depth_input);
}
const double fps = 30.0;
auto image_publisher = builder.AddSystem(
systems::lcm::LcmPublisherSystem::Make<drake::lcmt_image_array>(
"DRAKE_RGBD_CAMERA_IMAGES", lcm, 1.0 / fps));
builder.Connect(image_encoder->image_array_t_msg_output_port(),
image_publisher->get_input_port());
}
// Publish the point clouds.
if (FLAGS_publish_point_cloud) {
for (const auto& camera_name : station->get_camera_names()) {
const std::string cloud_name = "camera_" + camera_name + "_point_cloud";
auto cloud_encoder = builder.AddSystem<perception::PointCloudToLcm>();
const double fps = 5.0;
auto cloud_publisher = builder.AddSystem(
systems::lcm::LcmPublisherSystem::Make<drake::lcmt_point_cloud>(
"DRAKE_POINT_CLOUD_" + camera_name, lcm, 1.0 / fps));
builder.Connect(station->GetOutputPort(cloud_name),
cloud_encoder->get_input_port());
builder.Connect(cloud_encoder->get_output_port(),
cloud_publisher->get_input_port());
}
}
auto diagram = builder.Build();
systems::Simulator<double> simulator(*diagram);
simulator.set_publish_every_time_step(false);
simulator.set_target_realtime_rate(FLAGS_target_realtime_rate);
simulator.AdvanceTo(FLAGS_duration);
return 0;
}
} // namespace
} // namespace manipulation_station
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
return drake::examples::manipulation_station::do_main(argc, argv);
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/manipulation_station/manipulation_station_hardware_interface.cc | #include "drake/examples/manipulation_station/manipulation_station_hardware_interface.h"
#include <iostream>
#include <utility>
#include "drake/lcm/drake_lcm.h"
#include "drake/lcmt_iiwa_command.hpp"
#include "drake/lcmt_iiwa_status.hpp"
#include "drake/lcmt_image_array.hpp"
#include "drake/lcmt_schunk_wsg_command.hpp"
#include "drake/lcmt_schunk_wsg_status.hpp"
#include "drake/manipulation/kuka_iiwa/iiwa_command_sender.h"
#include "drake/manipulation/kuka_iiwa/iiwa_status_receiver.h"
#include "drake/manipulation/schunk_wsg/schunk_wsg_lcm.h"
#include "drake/multibody/parsing/parser.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/pass_through.h"
#include "drake/systems/sensors/lcm_image_array_to_images.h"
namespace drake {
namespace examples {
namespace manipulation_station {
using Eigen::Vector3d;
using multibody::MultibodyPlant;
using multibody::Parser;
// TODO(russt): Consider taking DrakeLcmInterface as an argument instead of
// (only) constructing one internally.
ManipulationStationHardwareInterface::ManipulationStationHardwareInterface(
std::vector<std::string> camera_names)
: owned_controller_plant_(std::make_unique<MultibodyPlant<double>>(0.0)),
owned_lcm_(new lcm::DrakeLcm()),
camera_names_(std::move(camera_names)) {
systems::DiagramBuilder<double> builder;
auto lcm = builder.AddSystem<systems::lcm::LcmInterfaceSystem>(
owned_lcm_.get());
// Publish IIWA command.
auto iiwa_command_sender =
builder.AddSystem<manipulation::kuka_iiwa::IiwaCommandSender>();
auto iiwa_command_publisher = builder.AddSystem(
systems::lcm::LcmPublisherSystem::Make<drake::lcmt_iiwa_command>(
"IIWA_COMMAND", lcm, 0.005
/* publish period: IIWA driver won't respond faster than 200Hz */));
builder.ExportInput(iiwa_command_sender->get_position_input_port(),
"iiwa_position");
builder.ExportInput(iiwa_command_sender->get_torque_input_port(),
"iiwa_feedforward_torque");
builder.Connect(iiwa_command_sender->get_output_port(),
iiwa_command_publisher->get_input_port());
// Receive IIWA status and populate the output ports.
auto iiwa_status_receiver =
builder.AddSystem<manipulation::kuka_iiwa::IiwaStatusReceiver>();
iiwa_status_subscriber_ = builder.AddSystem(
systems::lcm::LcmSubscriberSystem::Make<drake::lcmt_iiwa_status>(
"IIWA_STATUS", lcm));
builder.ExportOutput(
iiwa_status_receiver->get_position_commanded_output_port(),
"iiwa_position_commanded");
builder.ExportOutput(
iiwa_status_receiver->get_position_measured_output_port(),
"iiwa_position_measured");
builder.ExportOutput(
iiwa_status_receiver->get_velocity_estimated_output_port(),
"iiwa_velocity_estimated");
builder.ExportOutput(iiwa_status_receiver->get_torque_commanded_output_port(),
"iiwa_torque_commanded");
builder.ExportOutput(iiwa_status_receiver->get_torque_measured_output_port(),
"iiwa_torque_measured");
builder.ExportOutput(iiwa_status_receiver->get_torque_external_output_port(),
"iiwa_torque_external");
builder.Connect(iiwa_status_subscriber_->get_output_port(),
iiwa_status_receiver->get_input_port());
// Publish WSG command.
auto wsg_command_sender =
builder.AddSystem<manipulation::schunk_wsg::SchunkWsgCommandSender>();
auto wsg_command_publisher = builder.AddSystem(
systems::lcm::LcmPublisherSystem::Make<drake::lcmt_schunk_wsg_command>(
"SCHUNK_WSG_COMMAND", lcm, 0.05
/* publish period: Schunk driver won't respond faster than 20Hz */));
builder.ExportInput(wsg_command_sender->get_position_input_port(),
"wsg_position");
builder.ExportInput(wsg_command_sender->get_force_limit_input_port(),
"wsg_force_limit");
builder.Connect(wsg_command_sender->get_output_port(0),
wsg_command_publisher->get_input_port());
// Receive WSG status and populate the output ports.
auto wsg_status_receiver =
builder.AddSystem<manipulation::schunk_wsg::SchunkWsgStatusReceiver>();
wsg_status_subscriber_ = builder.AddSystem(
systems::lcm::LcmSubscriberSystem::Make<drake::lcmt_schunk_wsg_status>(
"SCHUNK_WSG_STATUS", lcm));
builder.ExportOutput(wsg_status_receiver->get_state_output_port(),
"wsg_state_measured");
builder.ExportOutput(wsg_status_receiver->get_force_output_port(),
"wsg_force_measured");
builder.Connect(wsg_status_subscriber_->get_output_port(),
wsg_status_receiver->get_input_port(0));
for (const std::string& name : camera_names_) {
auto camera_subscriber = builder.AddSystem(
systems::lcm::LcmSubscriberSystem::Make<lcmt_image_array>(
"DRAKE_RGBD_CAMERA_IMAGES_" + name, lcm));
auto array_to_images =
builder.AddSystem<systems::sensors::LcmImageArrayToImages>();
builder.Connect(camera_subscriber->get_output_port(),
array_to_images->image_array_t_input_port());
builder.ExportOutput(
array_to_images->color_image_output_port(),
"camera_" + name + "_rgb_image");
builder.ExportOutput(
array_to_images->depth_image_output_port(),
"camera_" + name + "_depth_image");
camera_subscribers_.push_back(camera_subscriber);
}
builder.BuildInto(this);
this->set_name("manipulation_station_hardware_interface");
// Build the controller's version of the plant, which only contains the
// IIWA and the equivalent inertia of the gripper.
const std::string iiwa_sdf_url =
"package://drake_models/iiwa_description/sdf/iiwa14_no_collision.sdf";
Parser parser(owned_controller_plant_.get());
iiwa_model_instance_ = parser.AddModelsFromUrl(iiwa_sdf_url).at(0);
// TODO(russt): Provide API for changing the base coordinates of the plant.
owned_controller_plant_->WeldFrames(owned_controller_plant_->world_frame(),
owned_controller_plant_->GetFrameByName(
"iiwa_link_0", iiwa_model_instance_),
math::RigidTransformd::Identity());
owned_controller_plant_->Finalize();
}
void ManipulationStationHardwareInterface::Connect(bool wait_for_cameras) {
drake::lcm::DrakeLcmInterface* const lcm = owned_lcm_.get();
auto wait_for_new_message = [lcm](const auto& lcm_sub) {
std::cout << "Waiting for " << lcm_sub.get_channel_name()
<< " message..." << std::flush;
const int orig_count = lcm_sub.GetInternalMessageCount();
LcmHandleSubscriptionsUntil(lcm, [&]() {
return lcm_sub.GetInternalMessageCount() > orig_count;
}, 10 /* timeout_millis */);
std::cout << "Received!" << std::endl;
};
wait_for_new_message(*iiwa_status_subscriber_);
wait_for_new_message(*wsg_status_subscriber_);
if (wait_for_cameras) {
for (const auto* sub : camera_subscribers_) {
wait_for_new_message(*sub);
}
}
}
int ManipulationStationHardwareInterface::num_iiwa_joints() const {
DRAKE_DEMAND(iiwa_model_instance_.is_valid());
return owned_controller_plant_->num_positions(iiwa_model_instance_);
}
} // namespace manipulation_station
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/manipulation_station/print_station_context.py | """
Provides some insight into the ManipulationStation model by printing out the
contents of its (default) Context.
"""
from pydrake.examples import ManipulationStation
def main():
station = ManipulationStation()
station.SetupManipulationClassStation()
station.Finalize()
context = station.CreateDefaultContext()
print(context)
if __name__ == '__main__':
main()
| 0 |
/home/johnshepherd/drake/examples/manipulation_station | /home/johnshepherd/drake/examples/manipulation_station/test/manipulation_station_test.cc | #include "drake/examples/manipulation_station/manipulation_station.h"
#include <map>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_no_throw.h"
#include "drake/geometry/test_utilities/dummy_render_engine.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/multibody/plant/externally_applied_spatial_force.h"
#include "drake/multibody/tree/revolute_joint.h"
#include "drake/systems/primitives/discrete_derivative.h"
#include "drake/systems/sensors/image.h"
namespace drake {
namespace examples {
namespace manipulation_station {
namespace {
using Eigen::Vector2d;
using Eigen::VectorXd;
using geometry::internal::DummyRenderEngine;
using math::RigidTransform;
using multibody::ExternallyAppliedSpatialForce;
using multibody::RevoluteJoint;
using multibody::SpatialForce;
using systems::BasicVector;
using systems::Context;
// Calculate the spatial inertia of the set S of bodies that make up the gripper
// about Go (the gripper frame's origin), expressed in the gripper frame G.
// The rigid bodies in set S consist of the gripper body G, the left finger, and
// the right finger. For this calculation, the sliding joints associated with
// the fingers are regarded as being in a "zero" configuration.
// @param[in] wsg_sdf_path path to sdf file that when parsed creates the model.
// @param[in] gripper_body_frame_name Name of the frame attached to the
// gripper's main body.
// @retval M_SGo_G spatial inertia of set S about Go, expressed in frame G.
// @note This function helps unit test the calculation of the gripper's spatial
// inertia done in CalcGripperSpatialInertia() in manipulation_station.cc.
multibody::SpatialInertia<double> MakeCompositeGripperInertia() {
// Set time_step to 1.0 since it is arbitrary, to quiet joint limit warnings.
multibody::MultibodyPlant<double> plant(1.0);
multibody::Parser parser(&plant);
parser.AddModelsFromUrl(
"package://drake_models/wsg_50_description/sdf/schunk_wsg_50_no_tip.sdf");
plant.Finalize();
const std::string gripper_body_frame_name = "body";
const auto& frame = plant.GetFrameByName(gripper_body_frame_name);
const auto& gripper_body = plant.GetRigidBodyByName(frame.body().name());
const auto& left_finger = plant.GetRigidBodyByName("left_finger");
const auto& right_finger = plant.GetRigidBodyByName("right_finger");
const auto& left_slider = plant.GetJointByName("left_finger_sliding_joint");
const auto& right_slider = plant.GetJointByName("right_finger_sliding_joint");
const multibody::SpatialInertia<double>& M_GGo_G =
gripper_body.default_spatial_inertia();
const multibody::SpatialInertia<double>& M_LLo_L =
left_finger.default_spatial_inertia();
const multibody::SpatialInertia<double>& M_RRo_R =
right_finger.default_spatial_inertia();
auto calc_finger_pose_in_gripper_frame =
[](const multibody::Joint<double>& slider) {
// Pose of the joint's parent frame P (attached on gripper body G) in the
// frame of the gripper G.
const RigidTransform<double> X_GP(
slider.frame_on_parent().GetFixedPoseInBodyFrame());
// Pose of the joint's child frame C (attached on the slider's finger body)
// in the frame of the slider's finger F.
const RigidTransform<double> X_FC(
slider.frame_on_child().GetFixedPoseInBodyFrame());
// When the slider's translational dof is zero, then P coincides with C.
// Therefore:
const RigidTransform<double> X_GF = X_GP * X_FC.inverse();
return X_GF;
};
// Pose of left finger L in gripper frame G when the slider's dof is zero.
const RigidTransform<double> X_GL(
calc_finger_pose_in_gripper_frame(left_slider));
// Pose of right finger R in gripper frame G when the slider's dof is zero.
const RigidTransform<double> X_GR(
calc_finger_pose_in_gripper_frame(right_slider));
// Helper to compute the spatial inertia of a finger F about the gripper's
// origin Go, expressed in G.
auto calc_finger_spatial_inertia_in_gripper_frame =
[](const multibody::SpatialInertia<double>& M_FFo_F,
const RigidTransform<double>& X_GF) {
const auto M_FFo_G = M_FFo_F.ReExpress(X_GF.rotation());
const auto p_FoGo_G = -X_GF.translation();
const auto M_FGo_G = M_FFo_G.Shift(p_FoGo_G);
return M_FGo_G;
};
// Shift and re-express in G frame the finger's spatial inertias.
const auto M_LGo_G =
calc_finger_spatial_inertia_in_gripper_frame(M_LLo_L, X_GL);
const auto M_RGo_G =
calc_finger_spatial_inertia_in_gripper_frame(M_RRo_R, X_GR);
// With everything about the same point Go and expressed in the same frame G,
// proceed to compose into composite body C:
// TODO(amcastro-tri): Implement operator+() in SpatialInertia.
multibody::SpatialInertia<double> M_CGo_G = M_GGo_G;
M_CGo_G += M_LGo_G;
M_CGo_G += M_RGo_G;
return M_CGo_G;
}
// Fixes the position of the gripper to the value currently stored in `context`.
// In addition, the force limit is set to 40 Newtons.
void FixGripper(const ManipulationStation<double>& station,
Context<double>* context) {
double wsg_position = station.GetWsgPosition(*context);
station.GetInputPort("wsg_position").FixValue(context, wsg_position);
station.GetInputPort("wsg_force_limit").FixValue(context, 40.);
}
// Sets the state of the manipulation station to store `iiwa_position` and
// `iiwa_velocity`. In addition, this method sets the state of the state
// interpolator used to generated the desired state to `iiwa_position` and
// `iiwa_velocity` to avoid jumps in the controller.
void SetState(const ManipulationStation<double>& station,
Context<double>* context, const VectorXd& iiwa_position,
const VectorXd& iiwa_velocity) {
station.SetIiwaPosition(context, iiwa_position);
station.SetIiwaVelocity(context, iiwa_velocity);
// Make sure that if a port is not connected, at least we fix it.
station.GetInputPort("iiwa_position").FixValue(context, iiwa_position);
station.GetInputPort("iiwa_feedforward_torque")
.FixValue(context, VectorXd::Zero(7));
FixGripper(station, context);
// Set desired position to actual position and the desired velocity to the
// actual velocity.
const auto& position_to_state = dynamic_cast<
const systems::StateInterpolatorWithDiscreteDerivative<double>&>(
station.GetSubsystemByName("desired_state_from_position"));
auto& position_to_state_context =
station.GetMutableSubsystemContext(position_to_state, context);
position_to_state.set_initial_state(&position_to_state_context, iiwa_position,
iiwa_velocity);
// Ensure that integral terms are zero.
context->get_mutable_continuous_state_vector().SetZero();
}
// Performs a discrete update of the system and returns the next time step
// velocities of the IIWA arm.
VectorXd GetNextIiwaVelocity(const ManipulationStation<double>& station,
const Context<double>& context) {
auto next_state = station.AllocateDiscreteVariables();
station.CalcForcedDiscreteVariableUpdate(context, next_state.get());
const auto& plant = station.get_multibody_plant();
const auto& base_joint = plant.GetJointByName("iiwa_joint_1");
const int iiwa_velocity_start =
plant.num_positions() + base_joint.velocity_start();
return station.GetSubsystemDiscreteValues(plant, *next_state).value()
.segment<7>(iiwa_velocity_start);
}
void ApplyExternalForceToManipulator(ManipulationStation<double>* station,
Context<double>* context) {
DRAKE_DEMAND(station != nullptr);
DRAKE_DEMAND(context != nullptr);
auto& plant = station->get_multibody_plant();
std::vector<ExternallyAppliedSpatialForce<double>> external_forces(1);
external_forces[0].F_Bq_W = SpatialForce<double>(
Vector3<double>::Zero(), Vector3<double>::UnitZ() * 10.);
external_forces[0].p_BoBq_B.setZero();
external_forces[0].body_index = plant.GetBodyByName("body").index();
station->GetInputPort("applied_spatial_force").FixValue(
context, external_forces);
}
GTEST_TEST(ManipulationStationTest, CheckPlantBasics) {
ManipulationStation<double> station(0.001);
station.SetupManipulationClassStation();
multibody::Parser parser(&station.get_mutable_multibody_plant(),
&station.get_mutable_scene_graph());
parser.AddModelsFromUrl(
"package://drake_models/manipulation_station/061_foam_brick.sdf");
station.Finalize();
auto& plant = station.get_multibody_plant();
EXPECT_EQ(plant.num_actuated_dofs(), 9); // 7 iiwa + 2 wsg.
auto context = station.CreateDefaultContext();
auto& plant_context = station.GetSubsystemContext(plant, *context);
VectorXd q = VectorXd::LinSpaced(7, 0.1, 0.7),
v = VectorXd::LinSpaced(7, 1.1, 1.7),
q_command = VectorXd::LinSpaced(7, 2.1, 2.7),
tau_ff = VectorXd::LinSpaced(7, 3.1, 3.7);
// Set positions and read them back out, multiple ways.
station.SetIiwaPosition(context.get(), q);
EXPECT_TRUE(CompareMatrices(q, station.GetIiwaPosition(*context)));
EXPECT_TRUE(CompareMatrices(q, station.GetOutputPort("iiwa_position_measured")
.Eval<BasicVector<double>>(*context)
.get_value()));
for (int i = 0; i < 7; i++) {
EXPECT_EQ(q(i), plant
.template GetJointByName<RevoluteJoint>(
"iiwa_joint_" + std::to_string(i + 1))
.get_angle(plant_context));
}
// Set velocities and read them back out, multiple ways.
station.SetIiwaVelocity(context.get(), v);
EXPECT_TRUE(CompareMatrices(v, station.GetIiwaVelocity(*context)));
EXPECT_TRUE(
CompareMatrices(v, station.GetOutputPort("iiwa_velocity_estimated")
.Eval<BasicVector<double>>(*context)
.get_value()));
for (int i = 0; i < 7; i++) {
EXPECT_EQ(v(i), plant
.template GetJointByName<RevoluteJoint>(
"iiwa_joint_" + std::to_string(i + 1))
.get_angular_rate(plant_context));
}
// Check position command pass through.
station.GetInputPort("iiwa_position").FixValue(context.get(), q_command);
EXPECT_TRUE(CompareMatrices(q_command,
station.GetOutputPort("iiwa_position_commanded")
.Eval<BasicVector<double>>(*context)
.get_value()));
// Check that the additional input port exists and is spelled correctly.
DRAKE_EXPECT_NO_THROW(station.GetInputPort("applied_spatial_force"));
// Confirm that iiwa_torque_commanded doesn't depend on applied_spatial_force.
ApplyExternalForceToManipulator(&station, context.get());
// Check feedforward_torque command.
VectorXd tau_with_no_ff = station.GetOutputPort("iiwa_torque_commanded")
.Eval<BasicVector<double>>(*context)
.get_value();
// Confirm that default values are zero.
station.GetInputPort("iiwa_feedforward_torque")
.FixValue(context.get(), VectorXd::Zero(7));
EXPECT_TRUE(CompareMatrices(tau_with_no_ff,
station.GetOutputPort("iiwa_torque_commanded")
.Eval<BasicVector<double>>(*context)
.get_value()));
station.GetInputPort("iiwa_feedforward_torque")
.FixValue(context.get(), tau_ff);
EXPECT_TRUE(CompareMatrices(tau_with_no_ff + tau_ff,
station.GetOutputPort("iiwa_torque_commanded")
.Eval<BasicVector<double>>(*context)
.get_value()));
FixGripper(station, context.get());
// Check iiwa_torque_commanded == iiwa_torque_measured.
EXPECT_TRUE(CompareMatrices(station.GetOutputPort("iiwa_torque_commanded")
.Eval<BasicVector<double>>(*context)
.get_value(),
station.GetOutputPort("iiwa_torque_measured")
.Eval<BasicVector<double>>(*context)
.get_value()));
// Check that the additional output ports exist and are spelled correctly.
DRAKE_EXPECT_NO_THROW(station.GetOutputPort("contact_results"));
DRAKE_EXPECT_NO_THROW(station.GetOutputPort("plant_continuous_state"));
// The station (manipulation station) has both a plant and a controller_plant.
// The controller plant has a "composite" rigid body whose spatial inertia is
// associated with the set S of bodies consisting of the gripper body G and
// the left and right fingers. The spatial inertia of the composite body is
// equal to the set S's spatial inertia about Go (body G's origin), expressed
// in G, where the fingers are regarded as being in a "zero" configuration.
// Verify the spatial inertia stored in the controller_plant matches the
// calculation returned by MakeCompositeGripperInertia().
const multibody::MultibodyPlant<double>& controller_plant =
station.get_controller_plant();
const multibody::RigidBody<double>& composite_gripper =
controller_plant.GetRigidBodyByName("wsg_equivalent");
const multibody::SpatialInertia<double> M_SGo_G_actual =
composite_gripper.default_spatial_inertia();
const multibody::SpatialInertia<double> M_SGo_G_expected =
MakeCompositeGripperInertia();
const Matrix6<double> M6_actual = M_SGo_G_actual.CopyToFullMatrix6();
const Matrix6<double> M6_expected = M_SGo_G_expected.CopyToFullMatrix6();
constexpr double ktol = 32 * std::numeric_limits<double>::epsilon();
EXPECT_TRUE(CompareMatrices(M6_actual, M6_expected, ktol));
}
// Verifies that port "iiwa_torque_external" reports zero torques (of the right
// size) when there is no contact and no applied spatial forces.
GTEST_TEST(ManipulationStationTest, CheckIiwaTorqueExternal) {
ManipulationStation<double> station(0.001);
station.SetupManipulationClassStation();
station.Finalize();
auto context = station.CreateDefaultContext();
FixGripper(station, context.get());
station.GetInputPort("iiwa_feedforward_torque")
.FixValue(context.get(), VectorXd::Zero(7));
// Check that iiwa_torque_external == 0 (no contact or applied_spatial_force).
EXPECT_TRUE(CompareMatrices(
station.GetOutputPort("iiwa_torque_external").Eval(*context),
VectorXd::Zero(7)));
// Check that iiwa_torque_external != 0 if spatial force is applied externally
const VectorXd iiwa_position = VectorXd::LinSpaced(7, 0.735, 0.983);
const VectorXd iiwa_velocity = VectorXd::Zero(7);
SetState(station, context.get(), iiwa_position, iiwa_velocity);
ApplyExternalForceToManipulator(&station, context.get());
EXPECT_FALSE(station.GetOutputPort("iiwa_torque_external")
.Eval<BasicVector<double>>(*context)
.get_value()
.isZero());
}
// Partially check M(q)vdot ≈ Mₑ(q)vdot_desired + τ_feedforward + τ_external
// by setting the right side to zero and confirming that vdot ≈ 0.
GTEST_TEST(ManipulationStationTest, CheckDynamics) {
const double kTimeStep = 0.002;
ManipulationStation<double> station(kTimeStep);
station.SetupManipulationClassStation();
station.Finalize();
// Set the state to arbitrary values of configuration and velocities.
auto context = station.CreateDefaultContext();
const VectorXd iiwa_position = VectorXd::LinSpaced(7, 0.735, 0.983);
const VectorXd iiwa_velocity = VectorXd::LinSpaced(7, -1.23, 0.456);
SetState(station, context.get(), iiwa_position, iiwa_velocity);
// Expect continuous state from the integral term in the PID from the
// inverse dynamics controller.
EXPECT_EQ(context->num_continuous_states(), 7);
// Check that iiwa_torque_external == 0 (no contact).
EXPECT_TRUE(station.GetOutputPort("iiwa_torque_external")
.Eval<BasicVector<double>>(*context)
.get_value()
.isZero());
const VectorXd next_velocity = GetNextIiwaVelocity(station, *context);
// Note: This tolerance could be much smaller if the wsg was not attached.
const double kTolerance = 1e-4; // rad/sec.
// Check that vdot ≈ 0 by checking that next velocity ≈ velocity.
EXPECT_TRUE(CompareMatrices(iiwa_velocity, next_velocity, kTolerance));
}
// Confirm that the velocity update results in the same velocities whenever we
// apply an equivalent, though different, set of inputs.
// We compare two cases:
// - Case 1: non-zero spatial forces and zero feedforward torques.
// - Case 2: zero spatial forces and feedforward torques equal to the
// generalized forces equivalent to the spatial forces from Case 1.
GTEST_TEST(ManipulationStationTest, CheckDynamicsUnderExternallyAppliedForce) {
const double kTimeStep = 0.002;
ManipulationStation<double> station(kTimeStep);
station.SetupManipulationClassStation();
station.Finalize();
// Set the state to arbitrary values of configuration and velocities.
auto context = station.CreateDefaultContext();
const VectorXd iiwa_position = VectorXd::LinSpaced(7, 0.735, 0.983);
const VectorXd zero_iiwa_velocity = VectorXd::Zero(7);
SetState(station, context.get(), iiwa_position, zero_iiwa_velocity);
// Case 1: Next velocities for a case with non-zero spatial forces and zero
// feedforward torques.
ApplyExternalForceToManipulator(&station, context.get());
station.GetInputPort("iiwa_feedforward_torque")
.FixValue(context.get(), VectorXd::Zero(7));
const VectorXd next_velocity_case1 = GetNextIiwaVelocity(station, *context);
// Evaluate total external torque (zero contact plus spatial forces).
const VectorXd tau_external =
station.GetOutputPort("iiwa_torque_external").Eval(*context);
// Case 2: Next velocities for a case with feedforward torques equivalent to
// the spatial forces from case 1 and zero spatial forces.
std::vector<ExternallyAppliedSpatialForce<double>> empty_forces;
station.GetInputPort("applied_spatial_force")
.FixValue(context.get(), empty_forces);
station.GetInputPort("iiwa_feedforward_torque")
.FixValue(context.get(), tau_external);
const VectorXd next_velocity_case2 = GetNextIiwaVelocity(station, *context);
const double kTolerance = std::numeric_limits<double>::epsilon();
EXPECT_TRUE(CompareMatrices(next_velocity_case1, next_velocity_case2,
kTolerance, MatrixCompareType::relative));
}
GTEST_TEST(ManipulationStationTest, CheckWsg) {
ManipulationStation<double> station(0.001);
station.SetupManipulationClassStation();
station.Finalize();
auto context = station.CreateDefaultContext();
const double q = 0.023;
const double v = 0.12;
station.SetWsgPosition(context.get(), q);
EXPECT_EQ(station.GetWsgPosition(*context), q);
station.SetWsgVelocity(context.get(), v);
EXPECT_EQ(station.GetWsgVelocity(*context), v);
EXPECT_TRUE(CompareMatrices(station.GetOutputPort("wsg_state_measured")
.Eval<BasicVector<double>>(*context)
.get_value(),
Vector2d(q, v)));
DRAKE_EXPECT_NO_THROW(station.GetOutputPort("wsg_force_measured"));
}
GTEST_TEST(ManipulationStationTest, CheckRGBDOutputs) {
ManipulationStation<double> station(0.001);
station.SetupManipulationClassStation();
station.Finalize();
auto context = station.CreateDefaultContext();
for (const auto& name : station.get_camera_names()) {
// Make sure the camera outputs can be evaluated, and are non-empty.
EXPECT_GE(station.GetOutputPort("camera_" + name + "_rgb_image")
.Eval<systems::sensors::ImageRgba8U>(*context)
.size(),
0);
EXPECT_GE(station.GetOutputPort("camera_" + name + "_depth_image")
.Eval<systems::sensors::ImageDepth16U>(*context)
.size(),
0);
EXPECT_GE(station.GetOutputPort("camera_" + name + "_label_image")
.Eval<systems::sensors::ImageLabel16I>(*context)
.size(),
0);
}
}
GTEST_TEST(ManipulationStationTest, CheckCollisionVariants) {
ManipulationStation<double> station1(0.002);
station1.SetupManipulationClassStation(IiwaCollisionModel::kNoCollision);
// In this variant, there are collision geometries from the world and the
// gripper, but not from the iiwa.
const int num_collisions =
station1.get_multibody_plant().num_collision_geometries();
ManipulationStation<double> station2(0.002);
station2.SetupManipulationClassStation(IiwaCollisionModel::kBoxCollision);
// Check for additional collision elements (one for each link, which includes
// the base).
EXPECT_EQ(station2.get_multibody_plant().num_collision_geometries(),
num_collisions + 8);
// The controlled model does not register with a scene graph, so has zero
// collisions.
EXPECT_EQ(station2.get_controller_plant().num_collision_geometries(), 0);
}
GTEST_TEST(ManipulationStationTest, AddManipulandFromFile) {
ManipulationStation<double> station(0.002);
const int num_base_instances =
station.get_multibody_plant().num_model_instances();
station.AddManipulandFromFile(
"drake_models/ycb/003_cracker_box.sdf",
math::RigidTransform<double>::Identity());
// Check that the cracker box was added.
EXPECT_EQ(station.get_multibody_plant().num_model_instances(),
num_base_instances + 1);
station.AddManipulandFromFile(
"drake_models/ycb/004_sugar_box.sdf",
math::RigidTransform<double>::Identity());
// Check that the sugar box was added.
EXPECT_EQ(station.get_multibody_plant().num_model_instances(),
num_base_instances + 2);
}
GTEST_TEST(ManipulationStationTest, SetupClutterClearingStation) {
ManipulationStation<double> station(0.002);
station.SetupClutterClearingStation(math::RigidTransform<double>::Identity(),
IiwaCollisionModel::kNoCollision);
station.Finalize();
// Make sure we get through the setup and initialization.
auto context = station.CreateDefaultContext();
// Check that domain randomization works.
RandomGenerator generator;
station.SetRandomContext(context.get(), &generator);
}
GTEST_TEST(ManipulationStationTest, SetupPlanarIiwaStation) {
ManipulationStation<double> station(0.002);
station.SetupPlanarIiwaStation();
station.Finalize();
// Make sure we get through the setup and initialization.
auto context = station.CreateDefaultContext();
// Check that domain randomization works.
RandomGenerator generator;
station.SetRandomContext(context.get(), &generator);
}
// Check that making many stations does not exhaust resources.
GTEST_TEST(ManipulationStationTest, MultipleInstanceTest) {
for (int i = 0; i < 20; ++i) {
ManipulationStation<double> station;
station.SetupManipulationClassStation();
station.Finalize();
}
}
GTEST_TEST(ManipulationStationTest, RegisterRgbdCameraTest) {
{
// Test default setup.
std::map<std::string, math::RigidTransform<double>> default_poses;
auto set_default_camera_poses = [&default_poses]() {
default_poses.emplace(
"0", math::RigidTransform<double>(
math::RollPitchYaw<double>(2.549607, 1.357609, 2.971679),
Eigen::Vector3d(-0.228895, -0.452176, 0.486308)));
default_poses.emplace(
"1", math::RigidTransform<double>(
math::RollPitchYaw<double>(2.617427, -1.336404, -0.170522),
Eigen::Vector3d(-0.201813, 0.469259, 0.417045)));
default_poses.emplace(
"2", math::RigidTransform<double>(
math::RollPitchYaw<double>(-2.608978, 0.022298, 1.538460),
Eigen::Vector3d(0.786258, -0.048422, 1.043315)));
};
ManipulationStation<double> dut;
dut.SetupManipulationClassStation();
std::map<std::string, math::RigidTransform<double>> camera_poses =
dut.GetStaticCameraPosesInWorld();
set_default_camera_poses();
EXPECT_EQ(camera_poses.size(), default_poses.size());
for (const auto& pair : camera_poses) {
auto found = default_poses.find(pair.first);
EXPECT_TRUE(found != default_poses.end());
EXPECT_TRUE(found->second.IsExactlyEqualTo(pair.second));
}
}
{
// Test registration to custom frames.
ManipulationStation<double> dut;
multibody::MultibodyPlant<double>& plant =
dut.get_mutable_multibody_plant();
geometry::render::DepthRenderCamera depth_camera{
{dut.default_renderer_name(), {640, 480, M_PI_4}, {0.05, 3.0}, {}},
{0.1, 2.0}};
const Eigen::Translation3d X_WF0(0, 0, 0.2);
const Eigen::Translation3d X_F0C0(0.3, 0.2, 0.0);
const auto& frame0 =
plant.AddFrame(std::make_unique<multibody::FixedOffsetFrame<double>>(
"frame0", plant.world_frame(), X_WF0));
dut.RegisterRgbdSensor("camera0", frame0, X_F0C0, depth_camera);
const Eigen::Translation3d X_F0F1(0, -0.1, 0.2);
const Eigen::Translation3d X_F1C1(-0.2, 0.2, 0.33);
const auto& frame1 =
plant.AddFrame(std::make_unique<multibody::FixedOffsetFrame<double>>(
"frame1", frame0, X_F0F1));
dut.RegisterRgbdSensor("camera1", frame1, X_F1C1, depth_camera);
std::map<std::string, math::RigidTransform<double>> camera_poses =
dut.GetStaticCameraPosesInWorld();
EXPECT_EQ(camera_poses.size(), 2);
EXPECT_TRUE(camera_poses.at("camera0").IsExactlyEqualTo(X_WF0 * X_F0C0));
EXPECT_TRUE(
camera_poses.at("camera1").IsExactlyEqualTo(X_WF0 * X_F0F1 * X_F1C1));
}
}
// Confirms initialization of renderers. With none specified, the default
// renderer is used. Otherwise, the user-specified renderers are provided.
GTEST_TEST(ManipulationStationTest, ConfigureRenderer) {
// Case: no user render engines specified; has renderer with default name.
{
ManipulationStation<double> dut;
dut.SetupManipulationClassStation();
dut.Finalize();
const auto& scene_graph = dut.get_scene_graph();
EXPECT_EQ(1, scene_graph.RendererCount());
EXPECT_TRUE(scene_graph.HasRenderer(dut.default_renderer_name()));
}
// Case: multiple user-specified render engines provided.
{
ManipulationStation<double> dut;
dut.SetupManipulationClassStation();
std::map<std::string, std::unique_ptr<geometry::render::RenderEngine>>
engines;
const std::string name1 = "engine1";
engines[name1] = std::make_unique<DummyRenderEngine>();
const std::string name2 = "engine2";
engines[name2] = std::make_unique<DummyRenderEngine>();
dut.Finalize(std::move(engines));
const auto& scene_graph = dut.get_scene_graph();
EXPECT_EQ(2, scene_graph.RendererCount());
EXPECT_TRUE(scene_graph.HasRenderer(name1));
EXPECT_TRUE(scene_graph.HasRenderer(name2));
EXPECT_FALSE(scene_graph.HasRenderer(dut.default_renderer_name()));
}
}
} // namespace
} // namespace manipulation_station
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples/manipulation_station | /home/johnshepherd/drake/examples/manipulation_station/test/manipulation_station_hardware_interface_test.cc | #include "drake/examples/manipulation_station/manipulation_station_hardware_interface.h" // noqa
#include <gtest/gtest.h>
#include "drake/systems/sensors/image.h"
namespace drake {
namespace examples {
namespace manipulation_station {
namespace {
using Eigen::VectorXd;
using systems::BasicVector;
GTEST_TEST(ManipulationStationHardwareInterfaceTest, CheckPorts) {
const int kNumIiwaDofs = 7;
const std::vector<std::string> camera_names = {"123", "456"};
ManipulationStationHardwareInterface station(camera_names);
auto context = station.CreateDefaultContext();
// Check sizes and names of the input ports.
station.GetInputPort("iiwa_position")
.FixValue(context.get(), VectorXd::Zero(kNumIiwaDofs));
station.GetInputPort("iiwa_feedforward_torque")
.FixValue(context.get(), VectorXd::Zero(kNumIiwaDofs));
station.GetInputPort("wsg_position").FixValue(context.get(), 0.);
station.GetInputPort("wsg_force_limit").FixValue(context.get(), 0.);
// Check sizes and names of the output ports.
EXPECT_EQ(station.GetOutputPort("iiwa_position_commanded")
.template Eval<BasicVector<double>>(*context)
.size(),
kNumIiwaDofs);
EXPECT_EQ(station.GetOutputPort("iiwa_position_measured")
.Eval<BasicVector<double>>(*context)
.size(),
kNumIiwaDofs);
EXPECT_EQ(station.GetOutputPort("iiwa_velocity_estimated")
.Eval<BasicVector<double>>(*context)
.size(),
kNumIiwaDofs);
EXPECT_EQ(station.GetOutputPort("iiwa_torque_commanded")
.Eval<BasicVector<double>>(*context)
.size(),
kNumIiwaDofs);
EXPECT_EQ(station.GetOutputPort("iiwa_torque_measured")
.Eval<BasicVector<double>>(*context)
.size(),
kNumIiwaDofs);
EXPECT_EQ(station.GetOutputPort("iiwa_torque_external")
.Eval<BasicVector<double>>(*context)
.size(),
kNumIiwaDofs);
EXPECT_EQ(station.GetOutputPort("wsg_state_measured")
.Eval<BasicVector<double>>(*context)
.size(),
2);
EXPECT_EQ(station.GetOutputPort("wsg_force_measured")
.Eval<BasicVector<double>>(*context)
.size(),
1);
// Camera outputs will be empty images since no messages have been received.
for (const std::string& name : camera_names) {
EXPECT_EQ(station.GetOutputPort("camera_" + name + "_rgb_image")
.Eval<systems::sensors::ImageRgba8U>(*context)
.size(),
0);
EXPECT_EQ(station.GetOutputPort("camera_" + name + "_depth_image")
.Eval<systems::sensors::ImageDepth32F>(*context)
.size(),
0);
}
// TODO(russt): Consider adding mock lcm tests. But doing so right now would
// require exposing DrakeLcmInterface when I've so far tried to hide it.
}
} // namespace
} // namespace manipulation_station
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/fibonacci/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 = "fibonacci_difference_equation",
hdrs = [
"fibonacci_difference_equation.h",
],
deps = [
"//common:essential",
"//systems/framework:leaf_system",
],
)
drake_cc_binary(
name = "run_fibonacci",
srcs = ["run_fibonacci.cc"],
deps = [
":fibonacci_difference_equation",
"//systems/analysis:simulator",
"//systems/primitives:vector_log_sink",
"@gflags",
],
)
# === test/ ===
drake_cc_googletest(
name = "fibonacci_difference_equation_test",
deps = [
":fibonacci_difference_equation",
"//systems/analysis:simulator",
"//systems/primitives:vector_log_sink",
],
)
add_lint_tests(enable_clang_format_lint = False)
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/fibonacci/run_fibonacci.cc | #include <iostream>
#include <gflags/gflags.h>
#include "drake/examples/fibonacci/fibonacci_difference_equation.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/primitives/vector_log_sink.h"
DEFINE_int32(steps, 10, "Length of Fibonacci sequence to generate.");
namespace drake {
namespace examples {
namespace fibonacci {
namespace {
// Use Drake's hybrid Simulator to produce the Fibonacci sequence up to
// the step number supplied on the command line (default 10).
int main(int argc, char* argv[]) {
// Handle the command line "steps" argument.
gflags::SetUsageMessage("usage: run_fibonacci [--steps=n]");
gflags::ParseCommandLineFlags(&argc, &argv, true);
// Build a Diagram containing the Fibonacci system and a data logger that
// samples the Fibonacci output port exactly at the update times.
systems::DiagramBuilder<double> builder;
auto fibonacci = builder.AddSystem<FibonacciDifferenceEquation>();
auto logger = LogVectorOutput(fibonacci->GetOutputPort("Fn"), &builder,
FibonacciDifferenceEquation::kPeriod);
auto diagram = builder.Build();
// Create a Simulator and use it to advance time until t=steps*h.
systems::Simulator<double> simulator(*diagram);
simulator.AdvanceTo(FLAGS_steps * FibonacciDifferenceEquation::kPeriod);
// Print out the contents of the log.
const auto& log = logger->FindLog(simulator.get_context());
for (int n = 0; n < log.sample_times().size(); ++n) {
const double t = log.sample_times()[n];
std::cout << n << ": " << log.data()(0, n)
<< " (t=" << t << ")\n";
}
return 0;
}
} // namespace
} // namespace fibonacci
} // namespace examples
} // namespace drake
int main(int argc, char **argv) {
return drake::examples::fibonacci::main(argc, argv);
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/fibonacci/fibonacci_difference_equation.h | #pragma once
#include <cmath>
#include "drake/systems/framework/event.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace examples {
namespace fibonacci {
/** A pure discrete system that generates the Fibonacci sequence F_n using
a difference equation.
@system
name: FibonacciDifferenceEquation
output_ports:
- Fn
@endsystem
In general, a discrete system has a difference equation (update function),
output function, and (for simulation) an initial value:
- _update_ function `x_{n+1} = f(n, x_n, u_n)`, and
- _output_ function `y_n = g(n, x_n, u_n)`, and
- `x_0 ≜ x_init`.
where x is a vector of discrete variables, u is a vector of external inputs,
and y is a vector of values that constitute the desired output of the discrete
system. The subscript indicates the value of these variables at step n, where
n is an integer 0, 1, 2, ... .
The Fibonacci sequence is defined by the second-order difference equation
```
F_{n+1} = F_n + F_{n-1}, with F₀ ≜ 0, F₁ ≜ 1,
```
which uses no input.
We can write this second order system as a pair of first-order difference
equations, using two state variables `x = {x[0], x[1]}` (we're using square
brackets for indexing the 2-element vector x, _not_ for step number!). In this
case x_n[0] holds F_n (the value of F at step n) while x_n[1] holds F_{n-1} (the
previous value, i.e. the value of F at step n-1). Here is the discrete system:
```
x_{n+1} = {x_n[0] + x_n[1], x_n[0]} // f()
y_n = x_n[0] // g()
x₀ ≜ {0, 1} // x_init
```
We want to show how to emulate this difference equation in Drake's hybrid
simulator, which advances a continuous time variable t rather than a discrete
step number n. To do that, we pick an arbitrary discrete period h, and show that
publishing at `t = n*h` produces the expected result
```
n 0 1 2 3 4 5 6 7 8
F_n 0 1 1 2 3 5 8 13 21 ...
```
See run_fibonacci.cc for the code required to output the above sequence.
*/
class FibonacciDifferenceEquation : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(FibonacciDifferenceEquation)
FibonacciDifferenceEquation() {
// Set default initial conditions to produce the above sequence.
DeclareDiscreteState(Eigen::Vector2d(0., 1.));
// Update to x_{n+1}, using a Drake "discrete update" event (occurs
// at the beginning of step n+1).
DeclarePeriodicDiscreteUpdateEvent(kPeriod, 0., // First update is at t=0.
&FibonacciDifferenceEquation::Update);
// Output y_n. This will be the Fibonacci element F_n if queried at `t=n*h`.
DeclareVectorOutputPort("Fn", 1, &FibonacciDifferenceEquation::Output);
}
/// Update period (in seconds) for the system.
static constexpr double kPeriod = 0.25; // Arbitrary, e.g. 0.1234 works too!
private:
// Update function x_{n+1} = f(n, x_n).
void Update(const systems::Context<double>& context,
systems::DiscreteValues<double>* xd) const {
const auto& x_n = context.get_discrete_state();
(*xd)[0] = x_n[0] + x_n[1];
(*xd)[1] = x_n[0];
}
// Returns the result of the output function y_n = g(n, x_n) when the output
// port is evaluated at t=n*h.
void Output(const systems::Context<double>& context,
systems::BasicVector<double>* result) const {
const double F_n = context.get_discrete_state()[0]; // x_n[0]
(*result)[0] = F_n;
}
};
} // namespace fibonacci
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples/fibonacci | /home/johnshepherd/drake/examples/fibonacci/test/fibonacci_difference_equation_test.cc | #include "drake/examples/fibonacci/fibonacci_difference_equation.h"
#include <gtest/gtest.h>
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/primitives/vector_log_sink.h"
namespace drake {
namespace examples {
namespace fibonacci {
namespace {
// Verify that we get the right sequence for one sequence length.
GTEST_TEST(Fibonacci, CheckSequence) {
systems::DiagramBuilder<double> builder;
auto fibonacci = builder.AddSystem<FibonacciDifferenceEquation>();
auto logger = builder.AddSystem<systems::VectorLogSink<double>>(
1, // Size of input.
FibonacciDifferenceEquation::kPeriod);
builder.Connect(fibonacci->GetOutputPort("Fn"), logger->GetInputPort("data"));
auto diagram = builder.Build();
systems::Simulator<double> simulator(*diagram);
const auto& log = logger->FindLog(simulator.get_context());
// Simulate forward to fibonacci(6): 0 1 1 2 3 5 8
simulator.AdvanceTo(6 * FibonacciDifferenceEquation::kPeriod);
Eigen::VectorXd expected(7);
expected << 0, 1, 1, 2, 3, 5, 8;
EXPECT_EQ(log.data().transpose(), expected);
}
} // namespace
} // namespace fibonacci
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/Pendulum.urdf | <?xml version="1.0"?>
<robot name="Pendulum">
<material name="green">
<color rgba=".3 .6 .4 1"/>
</material>
<material name="red">
<color rgba=".9 .1 0 1"/>
</material>
<material name="blue">
<color rgba="0 0 1 1"/>
</material>
<link drake_ignore="true" name="world">
<inertial>
<!-- drc-viewer needs this to have inertia to parse properly. Remove it when that bug is fixed. -->
<origin xyz="0 0 0"/>
<mass value="0.01"/>
<inertia ixx="0.01" ixy="0" ixz="0" iyy="0" iyz="0" izz="0"/>
</inertial>
</link>
<link name="base">
<inertial>
<origin rpy="0 0 0" xyz="0 0 .015"/>
<mass value="1"/>
<inertia ixx="0" ixy="0" ixz="0" iyy="0" iyz="0" izz="0"/>
</inertial>
<visual>
<origin xyz="0 0 .015"/>
<geometry>
<sphere radius=".015"/>
</geometry>
<material name="green"/>
</visual>
</link>
<joint name="base_weld" type="fixed">
<parent link="world"/>
<child link="base"/>
<origin xyz="0 0 1"/>
</joint>
<link name="arm">
<inertial>
<origin rpy="0 0 0" xyz="0 0 -.5"/>
<mass value="0.5"/>
<inertia ixx="0" ixy="0" ixz="0" iyy="0" iyz="0" izz="0"/>
</inertial>
<visual>
<origin rpy="0 0 0" xyz="0 0 -.375"/>
<geometry>
<cylinder length=".75" radius=".01"/>
</geometry>
<material name="red"/>
</visual>
<collision>
<origin rpy="0 0 0" xyz="0 0 -.375"/>
<geometry>
<cylinder length=".75" radius=".01"/>
</geometry>
</collision>
</link>
<joint name="theta" type="continuous">
<parent link="base"/>
<child link="arm"/>
<axis xyz="0 1 0"/>
<dynamics damping="0.1"/>
</joint>
<link name="arm_com">
<inertial>
<origin rpy="0 0 0" xyz="0 0 -0.5"/>
<mass value="0.5"/>
<inertia ixx="0" ixy="0" ixz="0" iyy="0" iyz="0" izz="0"/>
</inertial>
<visual>
<origin xyz="0 0 -.5"/>
<geometry>
<sphere radius=".025"/>
</geometry>
<material name="blue"/>
</visual>
<collision>
<origin xyz="0 0 -.5"/>
<geometry>
<sphere radius=".025"/>
</geometry>
</collision>
</link>
<joint name="arm_weld" type="fixed">
<parent link="arm"/>
<child link="arm_com"/>
</joint>
<transmission name="elbow_trans" type="SimpleTransmission">
<actuator name="tau"/>
<joint name="theta"/>
<mechanicalReduction>1</mechanicalReduction>
</transmission>
<gazebo reference="base">
<material>Gazebo/Green</material>
</gazebo>
<gazebo reference="arm">
<material>Gazebo/Red</material>
</gazebo>
<gazebo reference="arm_com">
<material>Gazebo/Blue</material>
</gazebo>
<gazebo>
<plugin filename="libgazebo_ros_pub_robot_state.so" name="gazebo_ros_pub_robot_controller">
<alwaysOn>true</alwaysOn>
<updateRate>100.0</updateRate>
<topicName>true_robot_state</topicName>
</plugin>
</gazebo>
</robot>
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/print_symbolic_dynamics.cc | #include <iostream>
#include "drake/common/symbolic/expression.h"
#include "drake/examples/pendulum/pendulum_plant.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/multibody/plant/multibody_plant.h"
// A simple example of extracting the symbolic dynamics of the pendulum system,
// and printing them to std::out.
using drake::symbolic::Expression;
using drake::symbolic::Variable;
using drake::multibody::MultibodyPlant;
using drake::multibody::Parser;
using drake::systems::System;
namespace drake {
namespace examples {
namespace pendulum {
namespace {
// Obtains the dynamics using PendulumPlant (a System that directly models the
// dynamics).
VectorX<Expression> PendulumPlantDynamics() {
// Load the Pendulum.urdf into a symbolic PendulumPlant.
PendulumPlant<Expression> symbolic_plant;
// Obtain the symbolic dynamics.
auto context = symbolic_plant.CreateDefaultContext();
symbolic_plant.get_input_port().FixValue(context.get(),
Expression(Variable("tau")));
context->get_mutable_continuous_state_vector().SetAtIndex(
0, Variable("theta"));
context->get_mutable_continuous_state_vector().SetAtIndex(
1, Variable("thetadot"));
const auto& derivatives = symbolic_plant.EvalTimeDerivatives(*context);
return derivatives.CopyToVector();
}
// Obtains the dynamics using MultibodyPlant configured to model a pendulum.
VectorX<Expression> MultibodyPlantDynamics() {
// Load the Pendulum.urdf into a symbolic MultibodyPlant.
const std::string pendulum_url =
"package://drake/examples/pendulum/Pendulum.urdf";
MultibodyPlant<double> plant(0.0);
Parser parser(&plant);
parser.AddModelsFromUrl(pendulum_url);
plant.Finalize();
auto symbolic_plant_ptr = System<double>::ToSymbolic(plant);
const MultibodyPlant<Expression>& symbolic_plant = *symbolic_plant_ptr;
// Obtain the symbolic dynamics.
auto context = symbolic_plant.CreateDefaultContext();
symbolic_plant.get_actuation_input_port().FixValue(
context.get(), Expression(Variable("tau")));
symbolic_plant.SetPositionsAndVelocities(
context.get(), Vector2<Expression>(
Variable("theta"), Variable("thetadot")));
const auto& derivatives = symbolic_plant.EvalTimeDerivatives(*context);
return derivatives.CopyToVector();
}
int main() {
std::cout << "PendulumPlantDynamics:\n";
auto dynamics = PendulumPlantDynamics();
std::cout << "d/dt theta = " << dynamics[0] << "\n";
std::cout << "d/dt thetadot = " << dynamics[1] << "\n";
std::cout << "\n";
std::cout << "MultibodyPlantDynamics:\n";
dynamics = MultibodyPlantDynamics();
std::cout << "d/dt theta = " << dynamics[0] << "\n";
std::cout << "d/dt thetadot = " << dynamics[1] << "\n";
return 0;
}
} // namespace
} // namespace pendulum
} // namespace examples
} // namespace drake
int main() {
return drake::examples::pendulum::main();
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/pendulum_input.cc | #include "drake/examples/pendulum/pendulum_input.h"
namespace drake {
namespace examples {
namespace pendulum {
const int PendulumInputIndices::kNumCoordinates;
const int PendulumInputIndices::kTau;
const std::vector<std::string>& PendulumInputIndices::GetCoordinateNames() {
static const drake::never_destroyed<std::vector<std::string>> coordinates(
std::vector<std::string>{
"tau",
});
return coordinates.access();
}
} // namespace pendulum
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/trajectory_optimization_simulation.cc | #include <iostream>
#include <memory>
#include <gflags/gflags.h>
#include "drake/common/is_approx_equal_abstol.h"
#include "drake/examples/pendulum/pendulum_geometry.h"
#include "drake/examples/pendulum/pendulum_plant.h"
#include "drake/geometry/drake_visualizer.h"
#include "drake/planning/trajectory_optimization/direct_collocation.h"
#include "drake/solvers/solve.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/controllers/pid_controlled_system.h"
#include "drake/systems/framework/diagram.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/primitives/trajectory_source.h"
using drake::solvers::SolutionResult;
namespace drake {
namespace examples {
namespace pendulum {
using planning::trajectory_optimization::DirectCollocation;
using trajectories::PiecewisePolynomial;
namespace {
DEFINE_double(target_realtime_rate, 1.0,
"Playback speed. See documentation for "
"Simulator::set_target_realtime_rate() for details.");
DEFINE_bool(ignore_solve_errors, false,
"Don't reflect the status of Solve() in the program's returncode. "
"Only crashes / exceptions will cause a non-zero returncode.");
int DoMain() {
auto pendulum = std::make_unique<PendulumPlant<double>>();
pendulum->set_name("pendulum");
auto context = pendulum->CreateDefaultContext();
const int kNumTimeSamples = 21;
const double kMinimumTimeStep = 0.2;
const double kMaximumTimeStep = 0.5;
DirectCollocation dircol(pendulum.get(), *context, kNumTimeSamples,
kMinimumTimeStep, kMaximumTimeStep);
auto& prog = dircol.prog();
dircol.AddEqualTimeIntervalsConstraints();
// TODO(russt): Add this constraint to PendulumPlant and get it automatically
// through DirectCollocation.
const double kTorqueLimit = 3.0; // N*m.
const solvers::VectorXDecisionVariable& u = dircol.input();
dircol.AddConstraintToAllKnotPoints(-kTorqueLimit <= u(0));
dircol.AddConstraintToAllKnotPoints(u(0) <= kTorqueLimit);
PendulumState<double> initial_state, final_state;
initial_state.set_theta(0.0);
initial_state.set_thetadot(0.0);
final_state.set_theta(M_PI);
final_state.set_thetadot(0.0);
prog.AddLinearConstraint(dircol.initial_state() == initial_state.value());
prog.AddLinearConstraint(dircol.final_state() == final_state.value());
const double R = 10; // Cost on input "effort".
dircol.AddRunningCost((R * u) * u);
const double timespan_init = 4;
auto traj_init_x = PiecewisePolynomial<double>::FirstOrderHold(
{0, timespan_init}, {initial_state.value(), final_state.value()});
dircol.SetInitialTrajectory(PiecewisePolynomial<double>(), traj_init_x);
const auto result = solvers::Solve(dircol.prog());
if (!result.is_success()) {
std::cerr << "Failed to solve optimization for the swing-up trajectory\n";
int returncode = 1;
if (FLAGS_ignore_solve_errors) {
returncode = 0;
}
return returncode;
}
systems::DiagramBuilder<double> builder;
const auto* pendulum_ptr = builder.AddSystem(std::move(pendulum));
const PiecewisePolynomial<double> pp_traj =
dircol.ReconstructInputTrajectory(result);
const PiecewisePolynomial<double> pp_xtraj =
dircol.ReconstructStateTrajectory(result);
auto input_trajectory = builder.AddSystem<systems::TrajectorySource>(pp_traj);
input_trajectory->set_name("input trajectory");
auto state_trajectory =
builder.AddSystem<systems::TrajectorySource>(pp_xtraj);
state_trajectory->set_name("state trajectory");
// The choices of PidController constants here are fairly arbitrary,
// but seem to effectively swing up the pendulum and hold it.
const double Kp = 10.0;
const double Ki = 0.0;
const double Kd = 1.0;
auto connect_result =
systems::controllers::PidControlledSystem<double>::ConnectController(
pendulum_ptr->get_input_port(), pendulum_ptr->get_state_output_port(),
Vector1d{Kp}, Vector1d{Ki}, Vector1d{Kd}, &builder);
builder.Connect(input_trajectory->get_output_port(),
connect_result.control_input_port);
builder.Connect(state_trajectory->get_output_port(),
connect_result.state_input_port);
auto scene_graph = builder.AddSystem<geometry::SceneGraph>();
PendulumGeometry::AddToBuilder(
&builder, pendulum_ptr->get_state_output_port(), scene_graph);
geometry::DrakeVisualizerd::AddToBuilder(&builder, *scene_graph);
auto diagram = builder.Build();
systems::Simulator<double> simulator(*diagram);
simulator.set_target_realtime_rate(FLAGS_target_realtime_rate);
simulator.Initialize();
simulator.AdvanceTo(pp_xtraj.end_time());
const auto& pendulum_state =
PendulumPlant<double>::get_state(diagram->GetSubsystemContext(
*pendulum_ptr, simulator.get_context()));
if (!is_approx_equal_abstol(pendulum_state.value(),
final_state.value(), 1e-3)) {
throw std::runtime_error("Did not reach trajectory target.");
}
return 0;
}
} // namespace
} // namespace pendulum
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
return drake::examples::pendulum::DoMain();
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/passive_simulation.cc | #include <gflags/gflags.h>
#include "drake/examples/pendulum/pendulum_geometry.h"
#include "drake/examples/pendulum/pendulum_plant.h"
#include "drake/geometry/drake_visualizer.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 pendulum {
namespace {
DEFINE_double(target_realtime_rate, 1.0,
"Playback speed. See documentation for "
"Simulator::set_target_realtime_rate() for details.");
int DoMain() {
systems::DiagramBuilder<double> builder;
auto source = builder.AddSystem<systems::ConstantVectorSource>(
PendulumInput<double>{}.with_tau(0.0));
source->set_name("source");
auto pendulum = builder.AddSystem<PendulumPlant>();
pendulum->set_name("pendulum");
builder.Connect(*source, *pendulum);
auto scene_graph = builder.AddSystem<geometry::SceneGraph>();
PendulumGeometry::AddToBuilder(
&builder, pendulum->get_state_output_port(), scene_graph);
geometry::DrakeVisualizerd::AddToBuilder(&builder, *scene_graph);
auto diagram = builder.Build();
systems::Simulator<double> simulator(*diagram);
systems::Context<double>& pendulum_context =
diagram->GetMutableSubsystemContext(*pendulum,
&simulator.get_mutable_context());
PendulumState<double>& state = pendulum->get_mutable_state(&pendulum_context);
state.set_theta(1.);
state.set_thetadot(0.);
const double initial_energy = pendulum->CalcTotalEnergy(pendulum_context);
simulator.set_target_realtime_rate(FLAGS_target_realtime_rate);
simulator.Initialize();
simulator.AdvanceTo(10);
const double final_energy = pendulum->CalcTotalEnergy(pendulum_context);
// Adds a numerical sanity test on total energy.
DRAKE_DEMAND(initial_energy > 2.0 * final_energy);
return 0;
}
} // namespace
} // namespace pendulum
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
return drake::examples::pendulum::DoMain();
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/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 = "pendulum_vector_types",
srcs = [
"pendulum_input.cc",
"pendulum_params.cc",
"pendulum_state.cc",
],
hdrs = [
"gen/pendulum_input.h",
"gen/pendulum_params.h",
"gen/pendulum_state.h",
"pendulum_input.h",
"pendulum_params.h",
"pendulum_state.h",
],
visibility = ["//visibility:public"],
deps = [
"//common:dummy_value",
"//common:essential",
"//common:name_value",
"//common/symbolic:expression",
"//systems/framework:vector",
],
)
drake_cc_library(
name = "pendulum_plant",
srcs = ["pendulum_plant.cc"],
hdrs = ["pendulum_plant.h"],
visibility = ["//visibility:public"],
deps = [
":pendulum_vector_types",
"//systems/framework:leaf_system",
],
)
drake_cc_library(
name = "pendulum_geometry",
srcs = ["pendulum_geometry.cc"],
hdrs = ["pendulum_geometry.h"],
visibility = ["//visibility:public"],
deps = [
":pendulum_plant",
":pendulum_vector_types",
"//geometry:geometry_roles",
"//geometry:scene_graph",
"//math:geometric_transform",
"//systems/framework:diagram_builder",
"//systems/framework:leaf_system",
],
)
drake_cc_binary(
name = "passive_simulation",
srcs = ["passive_simulation.cc"],
add_test_rule = 1,
data = [":models"],
test_rule_args = ["--target_realtime_rate=0.0"],
deps = [
":pendulum_geometry",
":pendulum_plant",
"//geometry:drake_visualizer",
"//systems/analysis:simulator",
"//systems/framework:diagram",
"//systems/primitives:constant_vector_source",
"@gflags",
],
)
drake_cc_binary(
name = "energy_shaping_simulation",
srcs = ["energy_shaping_simulation.cc"],
add_test_rule = 1,
data = [":models"],
test_rule_args = ["--target_realtime_rate=0.0"],
deps = [
":pendulum_geometry",
":pendulum_plant",
"//geometry:drake_visualizer",
"//systems/analysis:simulator",
"//systems/framework:diagram",
"//systems/framework:leaf_system",
"@gflags",
],
)
drake_cc_binary(
name = "lqr_simulation",
srcs = ["lqr_simulation.cc"],
add_test_rule = 1,
data = [":models"],
test_rule_args = ["--target_realtime_rate=0.0"],
deps = [
":pendulum_geometry",
":pendulum_plant",
"//common:is_approx_equal_abstol",
"//geometry:drake_visualizer",
"//systems/analysis:simulator",
"//systems/controllers:linear_quadratic_regulator",
"//systems/framework:diagram",
"//systems/framework:leaf_system",
"@gflags",
],
)
drake_cc_binary(
name = "trajectory_optimization_simulation",
srcs = ["trajectory_optimization_simulation.cc"],
add_test_rule = 1,
data = [":models"],
test_rule_args = ["--target_realtime_rate=0.0"] + select({
"@platforms//os:osx": [
# TODO(#20799) This started failing when OpenBLAS was upgraded.
# When we drop this nerf we should also drop the supporting
# `DEFINE_bool(ignore_solve_errors, ...)` in the program itself.
"--ignore_solve_errors",
],
"//conditions:default": [],
}),
# Non-deterministic IPOPT-related failures on macOS, see #10276.
test_rule_flaky = 1,
deps = [
":pendulum_geometry",
":pendulum_plant",
"//common:is_approx_equal_abstol",
"//geometry:drake_visualizer",
"//planning/trajectory_optimization:direct_collocation",
"//solvers:solve",
"//systems/analysis:simulator",
"//systems/controllers:pid_controlled_system",
"//systems/framework:diagram",
"//systems/primitives:trajectory_source",
"@gflags",
],
)
drake_cc_binary(
name = "print_symbolic_dynamics",
srcs = ["print_symbolic_dynamics.cc"],
add_test_rule = 1,
data = [":models"],
deps = [
":pendulum_plant",
"//common/symbolic:expression",
"//multibody/parsing",
"//multibody/plant",
],
)
drake_cc_binary(
name = "pendulum_parameters_derivatives",
srcs = ["pendulum_parameters_derivatives.cc"],
add_test_rule = 1,
deps = [
":pendulum_plant",
":pendulum_vector_types",
],
)
# === test/ ===
drake_cc_googletest(
name = "urdf_dynamics_test",
data = ["Pendulum.urdf"],
deps = [
":pendulum_plant",
"//common/test_utilities:eigen_matrix_compare",
"//multibody/parsing",
"//multibody/plant",
],
)
drake_cc_googletest(
name = "pendulum_geometry_test",
deps = [
":pendulum_geometry",
":pendulum_plant",
"//common/test_utilities:eigen_matrix_compare",
"//math:geometric_transform",
],
)
drake_cc_googletest(
name = "pendulum_plant_test",
deps = [
":pendulum_plant",
"//common:autodiff",
"//common/test_utilities:expect_no_throw",
],
)
add_lint_tests(enable_clang_format_lint = False)
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/pendulum_plant.h | #pragma once
#include "drake/examples/pendulum/pendulum_input.h"
#include "drake/examples/pendulum/pendulum_params.h"
#include "drake/examples/pendulum/pendulum_state.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace examples {
namespace pendulum {
/// A model of a simple pendulum
/// @f[ ml^2 \ddot\theta + b\dot\theta + mgl\sin\theta = \tau @f]
///
/// @system
/// name: PendulumPlant
/// input_ports:
/// - tau (optional)
/// output_ports:
/// - state
/// @endsystem
///
/// Note: If the tau input port is not connected, then the torque is
/// taken to be zero.
///
/// @tparam_default_scalar
template <typename T>
class PendulumPlant final : public systems::LeafSystem<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PendulumPlant);
/// Constructs a default plant.
PendulumPlant();
/// Scalar-converting copy constructor. See @ref system_scalar_conversion.
template <typename U>
explicit PendulumPlant(const PendulumPlant<U>&);
~PendulumPlant() final;
/// Returns the port to output state.
const systems::OutputPort<T>& get_state_output_port() const;
/// Calculates the kinetic + potential energy.
T CalcTotalEnergy(const systems::Context<T>& context) const;
/// Evaluates the input port and returns the scalar value of the commanded
/// torque. If the input port is not connected, then the torque is taken to
/// be zero.
T get_tau(const systems::Context<T>& context) const {
const systems::BasicVector<T>* u_vec = this->EvalVectorInput(context, 0);
return u_vec ? u_vec->GetAtIndex(0) : 0.0;
}
static const PendulumState<T>& get_state(
const systems::ContinuousState<T>& cstate) {
return dynamic_cast<const PendulumState<T>&>(cstate.get_vector());
}
static const PendulumState<T>& get_state(const systems::Context<T>& context) {
return get_state(context.get_continuous_state());
}
static PendulumState<T>& get_mutable_state(
systems::ContinuousState<T>* cstate) {
return dynamic_cast<PendulumState<T>&>(cstate->get_mutable_vector());
}
static PendulumState<T>& get_mutable_state(systems::Context<T>* context) {
return get_mutable_state(&context->get_mutable_continuous_state());
}
const PendulumParams<T>& get_parameters(
const systems::Context<T>& context) const {
return this->template GetNumericParameter<PendulumParams>(context, 0);
}
PendulumParams<T>& get_mutable_parameters(
systems::Context<T>* context) const {
return this->template GetMutableNumericParameter<PendulumParams>(
context, 0);
}
private:
void DoCalcTimeDerivatives(
const systems::Context<T>& context,
systems::ContinuousState<T>* derivatives) const final;
T DoCalcPotentialEnergy(const systems::Context<T>& context) const override;
T DoCalcKineticEnergy(const systems::Context<T>& context) const override;
};
} // namespace pendulum
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/pendulum_params.cc | #include "drake/examples/pendulum/pendulum_params.h"
namespace drake {
namespace examples {
namespace pendulum {
const int PendulumParamsIndices::kNumCoordinates;
const int PendulumParamsIndices::kMass;
const int PendulumParamsIndices::kLength;
const int PendulumParamsIndices::kDamping;
const int PendulumParamsIndices::kGravity;
const std::vector<std::string>& PendulumParamsIndices::GetCoordinateNames() {
static const drake::never_destroyed<std::vector<std::string>> coordinates(
std::vector<std::string>{
"mass",
"length",
"damping",
"gravity",
});
return coordinates.access();
}
} // namespace pendulum
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/pendulum_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 pendulum {
/// Expresses a PendulumPlants's geometry to a SceneGraph.
///
/// @system
/// name: PendulumGeometry
/// 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 PendulumGeometry final : public systems::LeafSystem<double> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(PendulumGeometry);
~PendulumGeometry() final;
/// Creates, adds, and connects a PendulumGeometry system into the given
/// `builder`. Both the `pendulum_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 %PendulumGeometry system.
/// The return value pointer is an alias of the new %PendulumGeometry system
/// that is owned by the `builder`.
static const PendulumGeometry* AddToBuilder(
systems::DiagramBuilder<double>* builder,
const systems::OutputPort<double>& pendulum_state_port,
geometry::SceneGraph<double>* scene_graph);
private:
explicit PendulumGeometry(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 pendulum (arm + point mass) frame.
geometry::FrameId frame_id_;
};
} // namespace pendulum
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/pendulum_geometry.cc | #include "drake/examples/pendulum/pendulum_geometry.h"
#include <memory>
#include <utility>
#include "drake/examples/pendulum/pendulum_params.h"
#include "drake/examples/pendulum/pendulum_state.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/rotation_matrix.h"
namespace drake {
namespace examples {
namespace pendulum {
using Eigen::Vector3d;
using Eigen::Vector4d;
using geometry::Box;
using geometry::Cylinder;
using geometry::GeometryFrame;
using geometry::GeometryId;
using geometry::GeometryInstance;
using geometry::MakePhongIllustrationProperties;
using geometry::PerceptionProperties;
using geometry::render::RenderLabel;
using geometry::Rgba;
using geometry::Sphere;
using std::make_unique;
const PendulumGeometry* PendulumGeometry::AddToBuilder(
systems::DiagramBuilder<double>* builder,
const systems::OutputPort<double>& pendulum_state_port,
geometry::SceneGraph<double>* scene_graph) {
DRAKE_THROW_UNLESS(builder != nullptr);
DRAKE_THROW_UNLESS(scene_graph != nullptr);
auto pendulum_geometry = builder->AddSystem(
std::unique_ptr<PendulumGeometry>(
new PendulumGeometry(scene_graph)));
builder->Connect(
pendulum_state_port,
pendulum_geometry->get_input_port(0));
builder->Connect(
pendulum_geometry->get_output_port(0),
scene_graph->get_source_pose_port(pendulum_geometry->source_id_));
return pendulum_geometry;
}
PendulumGeometry::PendulumGeometry(geometry::SceneGraph<double>* scene_graph) {
DRAKE_THROW_UNLESS(scene_graph != nullptr);
source_id_ = scene_graph->RegisterSource();
frame_id_ = scene_graph->RegisterFrame(source_id_, GeometryFrame("arm"));
this->DeclareVectorInputPort("state", PendulumState<double>());
this->DeclareAbstractOutputPort(
"geometry_pose", &PendulumGeometry::OutputGeometryPose);
// TODO(jwnimmer-tri) This registration fails to reflect any non-default
// parameters. Ideally, it should happen in an Initialize event that
// modifies the Context, or the output port should express the geometries
// themselves instead of just their poses, or etc.
const PendulumParams<double> params;
const double length = params.length();
const double mass = params.mass();
// The base.
{
GeometryId id = scene_graph->RegisterAnchoredGeometry(
source_id_, make_unique<GeometryInstance>(
math::RigidTransformd(Vector3d(0., 0., .025)),
make_unique<Box>(.05, 0.05, 0.05), "base"));
scene_graph->AssignRole(
source_id_, id,
MakePhongIllustrationProperties(Vector4d(.3, .6, .4, 1)));
PerceptionProperties perception;
perception.AddProperty("phong", "diffuse", Rgba{0.3, 0.6, 0.4, 1.0});
perception.AddProperty("label", "id", RenderLabel::kDontCare);
scene_graph->AssignRole(source_id_, id, perception);
}
// The arm.
{
GeometryId id = scene_graph->RegisterGeometry(
source_id_, frame_id_,
make_unique<GeometryInstance>(
math::RigidTransformd(Vector3d(0., 0., -length / 2.)),
make_unique<Cylinder>(0.01, length), "arm"));
scene_graph->AssignRole(
source_id_, id,
MakePhongIllustrationProperties(Vector4d(.9, .1, 0, 1)));
PerceptionProperties perception;
perception.AddProperty("phong", "diffuse", Rgba{0.9, 0.1, 0, 1.0});
perception.AddProperty("label", "id", RenderLabel::kDontCare);
scene_graph->AssignRole(source_id_, id, perception);
}
// The mass at the end of the arm.
{
GeometryId id = scene_graph->RegisterGeometry(
source_id_, frame_id_,
make_unique<GeometryInstance>(
math::RigidTransformd(Vector3d(0., 0., -length)),
make_unique<Sphere>(mass / 40.), "arm point mass"));
scene_graph->AssignRole(
source_id_, id, MakePhongIllustrationProperties(Vector4d(0, 0, 1, 1)));
PerceptionProperties perception;
perception.AddProperty("phong", "diffuse", Rgba{0, 0, 1, 1});
perception.AddProperty("label", "id", RenderLabel::kDontCare);
scene_graph->AssignRole(source_id_, id, perception);
}
}
PendulumGeometry::~PendulumGeometry() = default;
void PendulumGeometry::OutputGeometryPose(
const systems::Context<double>& context,
geometry::FramePoseVector<double>* poses) const {
DRAKE_DEMAND(frame_id_.is_valid());
const auto& input = get_input_port(0).Eval<PendulumState<double>>(context);
const double theta = input.theta();
const math::RigidTransformd pose(math::RotationMatrixd::MakeYRotation(theta));
*poses = {{frame_id_, pose}};
}
} // namespace pendulum
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/pendulum_plant.cc | #include "drake/examples/pendulum/pendulum_plant.h"
#include <cmath>
#include "drake/common/default_scalars.h"
namespace drake {
namespace examples {
namespace pendulum {
template <typename T>
PendulumPlant<T>::PendulumPlant()
: systems::LeafSystem<T>(systems::SystemTypeTag<PendulumPlant>{}) {
this->DeclareNumericParameter(PendulumParams<T>());
this->DeclareVectorInputPort("tau", PendulumInput<T>());
auto state_index = this->DeclareContinuousState(
PendulumState<T>(), 1 /* num_q */, 1 /* num_v */, 0 /* num_z */);
this->DeclareStateOutputPort("state", state_index);
}
template <typename T>
template <typename U>
PendulumPlant<T>::PendulumPlant(const PendulumPlant<U>&) : PendulumPlant() {}
template <typename T>
PendulumPlant<T>::~PendulumPlant() = default;
template <typename T>
const systems::OutputPort<T>& PendulumPlant<T>::get_state_output_port() const {
DRAKE_DEMAND(systems::LeafSystem<T>::num_output_ports() == 1);
return systems::LeafSystem<T>::get_output_port(0);
}
template <typename T>
T PendulumPlant<T>::CalcTotalEnergy(const systems::Context<T>& context) const {
return DoCalcPotentialEnergy(context) + DoCalcKineticEnergy(context);
}
// Compute the actual physics.
template <typename T>
void PendulumPlant<T>::DoCalcTimeDerivatives(
const systems::Context<T>& context,
systems::ContinuousState<T>* derivatives) const {
const PendulumState<T>& state = get_state(context);
const PendulumParams<T>& params = get_parameters(context);
PendulumState<T>& derivative_vector = get_mutable_state(derivatives);
derivative_vector.set_theta(state.thetadot());
derivative_vector.set_thetadot(
(get_tau(context) -
params.mass() * params.gravity() * params.length() * sin(state.theta()) -
params.damping() * state.thetadot()) /
(params.mass() * params.length() * params.length()));
}
template <typename T>
T PendulumPlant<T>::DoCalcPotentialEnergy(const systems::Context<T>& context)
const {
using std::cos;
const PendulumState<T>& state = get_state(context);
const PendulumParams<T>& params = get_parameters(context);
// Potential energy = -mgl cos θ.
return -params.mass() * params.gravity() * params.length() *
cos(state.theta());
}
template <typename T>
T PendulumPlant<T>::DoCalcKineticEnergy(const systems::Context<T>& context)
const {
using std::pow;
const PendulumState<T>& state = get_state(context);
const PendulumParams<T>& params = get_parameters(context);
// Kinetic energy = 1/2 m l² θ̇ ².
return 0.5 * params.mass() * pow(params.length() * state.thetadot(), 2);
}
} // namespace pendulum
} // namespace examples
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::examples::pendulum::PendulumPlant)
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/pendulum_state.cc | #include "drake/examples/pendulum/pendulum_state.h"
namespace drake {
namespace examples {
namespace pendulum {
const int PendulumStateIndices::kNumCoordinates;
const int PendulumStateIndices::kTheta;
const int PendulumStateIndices::kThetadot;
const std::vector<std::string>& PendulumStateIndices::GetCoordinateNames() {
static const drake::never_destroyed<std::vector<std::string>> coordinates(
std::vector<std::string>{
"theta",
"thetadot",
});
return coordinates.access();
}
} // namespace pendulum
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/lqr_simulation.cc | #include <gflags/gflags.h>
#include "drake/common/drake_assert.h"
#include "drake/common/is_approx_equal_abstol.h"
#include "drake/examples/pendulum/pendulum_geometry.h"
#include "drake/examples/pendulum/pendulum_plant.h"
#include "drake/geometry/drake_visualizer.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/controllers/linear_quadratic_regulator.h"
#include "drake/systems/framework/diagram.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace examples {
namespace pendulum {
namespace {
DEFINE_double(target_realtime_rate, 1.0,
"Playback speed. See documentation for "
"Simulator::set_target_realtime_rate() for details.");
int DoMain() {
systems::DiagramBuilder<double> builder;
auto pendulum = builder.AddSystem<PendulumPlant>();
pendulum->set_name("pendulum");
// Prepare to linearize around the vertical equilibrium point (with tau=0)
auto pendulum_context = pendulum->CreateDefaultContext();
auto& desired_state = pendulum->get_mutable_state(pendulum_context.get());
desired_state.set_theta(M_PI);
desired_state.set_thetadot(0);
pendulum->get_input_port().FixValue(
pendulum_context.get(), PendulumInput<double>{}.with_tau(0.0));
// Set up cost function for LQR: integral of 10*theta^2 + thetadot^2 + tau^2.
// The factor of 10 is heuristic, but roughly accounts for the unit conversion
// between angles and angular velocity (using the time constant, \sqrt{g/l},
// squared).
Eigen::MatrixXd Q(2, 2);
Q << 10, 0, 0, 1;
Eigen::MatrixXd R(1, 1);
R << 1;
auto controller =
builder.AddSystem(systems::controllers::LinearQuadraticRegulator(
*pendulum, *pendulum_context, Q, R));
controller->set_name("controller");
builder.Connect(pendulum->get_state_output_port(),
controller->get_input_port());
builder.Connect(controller->get_output_port(), pendulum->get_input_port());
auto scene_graph = builder.AddSystem<geometry::SceneGraph>();
PendulumGeometry::AddToBuilder(
&builder, pendulum->get_state_output_port(), scene_graph);
geometry::DrakeVisualizerd::AddToBuilder(&builder, *scene_graph);
auto diagram = builder.Build();
systems::Simulator<double> simulator(*diagram);
systems::Context<double>& sim_pendulum_context =
diagram->GetMutableSubsystemContext(*pendulum,
&simulator.get_mutable_context());
auto& state = pendulum->get_mutable_state(&sim_pendulum_context);
state.set_theta(M_PI + 0.1);
state.set_thetadot(0.2);
simulator.set_target_realtime_rate(FLAGS_target_realtime_rate);
simulator.Initialize();
simulator.AdvanceTo(10);
// Adds a numerical test to make sure we're stabilizing the fixed point.
DRAKE_DEMAND(is_approx_equal_abstol(state.value(),
desired_state.value(), 1e-3));
return 0;
}
} // namespace
} // namespace pendulum
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
return drake::examples::pendulum::DoMain();
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/pendulum_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 pendulum {
/// Describes the row indices of a PendulumState.
struct PendulumStateIndices {
/// The total number of rows (coordinates).
static const int kNumCoordinates = 2;
// The index of each individual coordinate.
static const int kTheta = 0;
static const int kThetadot = 1;
/// 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, `PendulumStateIndices::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 PendulumState final : public drake::systems::BasicVector<T> {
public:
/// An abbreviation for our row index constants.
typedef PendulumStateIndices K;
/// Default constructor. Sets all rows to their default value:
/// @arg @c theta defaults to 0.0 radians.
/// @arg @c thetadot defaults to 0.0 radians/sec.
PendulumState() : drake::systems::BasicVector<T>(K::kNumCoordinates) {
this->set_theta(0.0);
this->set_thetadot(0.0);
}
// Note: It's safe to implement copy and move because this class is final.
/// @name Implements CopyConstructible, CopyAssignable, MoveConstructible,
/// MoveAssignable
//@{
PendulumState(const PendulumState& other)
: drake::systems::BasicVector<T>(other.values()) {}
PendulumState(PendulumState&& other) noexcept
: drake::systems::BasicVector<T>(std::move(other.values())) {}
PendulumState& operator=(const PendulumState& other) {
this->values() = other.values();
return *this;
}
PendulumState& operator=(PendulumState&& 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_theta(symbolic::Variable("theta"));
this->set_thetadot(symbolic::Variable("thetadot"));
}
[[nodiscard]] PendulumState<T>* DoClone() const final {
return new PendulumState;
}
/// @name Getters and Setters
//@{
/// The angle of the pendulum.
/// @note @c theta is expressed in units of radians.
const T& theta() const {
ThrowIfEmpty();
return this->GetAtIndex(K::kTheta);
}
/// Setter that matches theta().
void set_theta(const T& theta) {
ThrowIfEmpty();
this->SetAtIndex(K::kTheta, theta);
}
/// Fluent setter that matches theta().
/// Returns a copy of `this` with theta set to a new value.
[[nodiscard]] PendulumState<T> with_theta(const T& theta) const {
PendulumState<T> result(*this);
result.set_theta(theta);
return result;
}
/// The angular velocity of the pendulum.
/// @note @c thetadot is expressed in units of radians/sec.
const T& thetadot() const {
ThrowIfEmpty();
return this->GetAtIndex(K::kThetadot);
}
/// Setter that matches thetadot().
void set_thetadot(const T& thetadot) {
ThrowIfEmpty();
this->SetAtIndex(K::kThetadot, thetadot);
}
/// Fluent setter that matches thetadot().
/// Returns a copy of `this` with thetadot set to a new value.
[[nodiscard]] PendulumState<T> with_thetadot(const T& thetadot) const {
PendulumState<T> result(*this);
result.set_thetadot(thetadot);
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& theta_ref = this->GetAtIndex(K::kTheta);
a->Visit(drake::MakeNameValue("theta", &theta_ref));
T& thetadot_ref = this->GetAtIndex(K::kThetadot);
a->Visit(drake::MakeNameValue("thetadot", &thetadot_ref));
}
/// See PendulumStateIndices::GetCoordinateNames().
static const std::vector<std::string>& GetCoordinateNames() {
return PendulumStateIndices::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(theta());
result = result && !isnan(thetadot());
return result;
}
private:
void ThrowIfEmpty() const {
if (this->values().size() == 0) {
throw std::out_of_range(
"The PendulumState vector has been moved-from; "
"accessor methods may no longer be used");
}
}
};
} // namespace pendulum
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/energy_shaping_simulation.cc | #include <cmath>
#include <gflags/gflags.h>
#include "drake/common/drake_assert.h"
#include "drake/examples/pendulum/pendulum_geometry.h"
#include "drake/examples/pendulum/pendulum_plant.h"
#include "drake/geometry/drake_visualizer.h"
#include "drake/systems/analysis/simulator.h"
#include "drake/systems/framework/diagram.h"
#include "drake/systems/framework/diagram_builder.h"
#include "drake/systems/framework/leaf_system.h"
namespace drake {
namespace examples {
namespace pendulum {
namespace {
DEFINE_double(target_realtime_rate, 1.0,
"Playback speed. See documentation for "
"Simulator::set_target_realtime_rate() for details.");
template <typename T>
class PendulumEnergyShapingController : public systems::LeafSystem<T> {
public:
explicit PendulumEnergyShapingController(const PendulumParams<T>& params) {
this->DeclareVectorInputPort(systems::kUseDefaultName, PendulumState<T>());
this->DeclareVectorOutputPort(systems::kUseDefaultName, PendulumInput<T>(),
&PendulumEnergyShapingController::CalcTau);
this->DeclareNumericParameter(params);
}
private:
void CalcTau(const systems::Context<T>& context,
PendulumInput<T>* output) const {
const auto* state =
this->template EvalVectorInput<PendulumState>(context, 0);
const PendulumParams<T>& params =
this->template GetNumericParameter<PendulumParams>(context, 0);
// Pendulum energy shaping from Section 3.5.2 of
// http://underactuated.csail.mit.edu/underactuated.html?chapter=3
using std::pow;
// Desired energy is slightly more than the energy at the top (want to pass
// through the upright with non-zero velocity).
const T desired_energy =
1.1 * params.mass() * params.gravity() * params.length();
// Current total energy (see PendulumPlant::CalcTotalEnergy).
const T current_energy =
0.5 * params.mass() * pow(params.length() * state->thetadot(), 2) -
params.mass() * params.gravity() * params.length() *
cos(state->theta());
const double kEnergyFeedbackGain = .1;
output->set_tau(params.damping() * state->thetadot() +
kEnergyFeedbackGain * state->thetadot() *
(desired_energy - current_energy));
}
};
int DoMain() {
PendulumParams<double> params;
systems::DiagramBuilder<double> builder;
auto pendulum = builder.AddSystem<PendulumPlant>();
pendulum->set_name("pendulum");
// Use default pendulum parameters in the controller (real controllers never
// get the true parameters).
auto controller = builder.AddSystem<PendulumEnergyShapingController>(
params);
controller->set_name("controller");
builder.Connect(pendulum->get_state_output_port(),
controller->get_input_port(0));
builder.Connect(controller->get_output_port(0), pendulum->get_input_port());
auto scene_graph = builder.AddSystem<geometry::SceneGraph>();
PendulumGeometry::AddToBuilder(
&builder, pendulum->get_state_output_port(), scene_graph);
geometry::DrakeVisualizerd::AddToBuilder(&builder, *scene_graph);
auto diagram = builder.Build();
systems::Simulator<double> simulator(*diagram);
systems::Context<double>& pendulum_context =
diagram->GetMutableSubsystemContext(*pendulum,
&simulator.get_mutable_context());
auto& state = pendulum->get_mutable_state(&pendulum_context);
// Desired energy is the total energy when the pendulum is at the upright.
state.set_theta(M_PI);
state.set_thetadot(0.0);
const double desired_energy = pendulum->CalcTotalEnergy(pendulum_context);
// Set initial conditions (near the bottom).
state.set_theta(0.1);
state.set_thetadot(0.2);
const double initial_energy = pendulum->CalcTotalEnergy(pendulum_context);
// Run the simulation.
simulator.set_target_realtime_rate(FLAGS_target_realtime_rate);
simulator.Initialize();
simulator.AdvanceTo(10);
// Compute the final (total) energy.
const double final_energy = pendulum->CalcTotalEnergy(pendulum_context);
// Adds a numerical test that we have successfully regulated the energy
// towards the desired energy level.
DRAKE_DEMAND(std::abs(final_energy - desired_energy) <
(0.5 * std::abs(initial_energy - desired_energy)));
return 0;
}
} // namespace
} // namespace pendulum
} // namespace examples
} // namespace drake
int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
return drake::examples::pendulum::DoMain();
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/pendulum_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 pendulum {
/// Describes the row indices of a PendulumParams.
struct PendulumParamsIndices {
/// The total number of rows (coordinates).
static const int kNumCoordinates = 4;
// The index of each individual coordinate.
static const int kMass = 0;
static const int kLength = 1;
static const int kDamping = 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, `PendulumParamsIndices::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 PendulumParams final : public drake::systems::BasicVector<T> {
public:
/// An abbreviation for our row index constants.
typedef PendulumParamsIndices K;
/// Default constructor. Sets all rows to their default value:
/// @arg @c mass defaults to 1.0 kg.
/// @arg @c length defaults to 0.5 m.
/// @arg @c damping defaults to 0.1 kg m^2/s.
/// @arg @c gravity defaults to 9.81 m/s^2.
PendulumParams() : drake::systems::BasicVector<T>(K::kNumCoordinates) {
this->set_mass(1.0);
this->set_length(0.5);
this->set_damping(0.1);
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
//@{
PendulumParams(const PendulumParams& other)
: drake::systems::BasicVector<T>(other.values()) {}
PendulumParams(PendulumParams&& other) noexcept
: drake::systems::BasicVector<T>(std::move(other.values())) {}
PendulumParams& operator=(const PendulumParams& other) {
this->values() = other.values();
return *this;
}
PendulumParams& operator=(PendulumParams&& 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(symbolic::Variable("mass"));
this->set_length(symbolic::Variable("length"));
this->set_damping(symbolic::Variable("damping"));
this->set_gravity(symbolic::Variable("gravity"));
}
[[nodiscard]] PendulumParams<T>* DoClone() const final {
return new PendulumParams;
}
/// @name Getters and Setters
//@{
/// The simple pendulum has a single point mass at the end of the arm.
/// @note @c mass is expressed in units of kg.
/// @note @c mass has a limited domain of [0.0, +Inf].
const T& mass() const {
ThrowIfEmpty();
return this->GetAtIndex(K::kMass);
}
/// Setter that matches mass().
void set_mass(const T& mass) {
ThrowIfEmpty();
this->SetAtIndex(K::kMass, mass);
}
/// Fluent setter that matches mass().
/// Returns a copy of `this` with mass set to a new value.
[[nodiscard]] PendulumParams<T> with_mass(const T& mass) const {
PendulumParams<T> result(*this);
result.set_mass(mass);
return result;
}
/// The length of the pendulum arm.
/// @note @c length is expressed in units of m.
/// @note @c length has a limited domain of [0.0, +Inf].
const T& length() const {
ThrowIfEmpty();
return this->GetAtIndex(K::kLength);
}
/// Setter that matches length().
void set_length(const T& length) {
ThrowIfEmpty();
this->SetAtIndex(K::kLength, length);
}
/// Fluent setter that matches length().
/// Returns a copy of `this` with length set to a new value.
[[nodiscard]] PendulumParams<T> with_length(const T& length) const {
PendulumParams<T> result(*this);
result.set_length(length);
return result;
}
/// The damping friction coefficient relating angular velocity to torque.
/// @note @c damping is expressed in units of kg m^2/s.
/// @note @c damping has a limited domain of [0.0, +Inf].
const T& damping() const {
ThrowIfEmpty();
return this->GetAtIndex(K::kDamping);
}
/// Setter that matches damping().
void set_damping(const T& damping) {
ThrowIfEmpty();
this->SetAtIndex(K::kDamping, damping);
}
/// Fluent setter that matches damping().
/// Returns a copy of `this` with damping set to a new value.
[[nodiscard]] PendulumParams<T> with_damping(const T& damping) const {
PendulumParams<T> result(*this);
result.set_damping(damping);
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]] PendulumParams<T> with_gravity(const T& gravity) const {
PendulumParams<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& mass_ref = this->GetAtIndex(K::kMass);
a->Visit(drake::MakeNameValue("mass", &mass_ref));
T& length_ref = this->GetAtIndex(K::kLength);
a->Visit(drake::MakeNameValue("length", &length_ref));
T& damping_ref = this->GetAtIndex(K::kDamping);
a->Visit(drake::MakeNameValue("damping", &damping_ref));
T& gravity_ref = this->GetAtIndex(K::kGravity);
a->Visit(drake::MakeNameValue("gravity", &gravity_ref));
}
/// See PendulumParamsIndices::GetCoordinateNames().
static const std::vector<std::string>& GetCoordinateNames() {
return PendulumParamsIndices::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());
result = result && (mass() >= T(0.0));
result = result && !isnan(length());
result = result && (length() >= T(0.0));
result = result && !isnan(damping());
result = result && (damping() >= 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::kMass) = 0.0;
(*lower)(K::kLength) = 0.0;
(*lower)(K::kDamping) = 0.0;
(*lower)(K::kGravity) = 0.0;
}
private:
void ThrowIfEmpty() const {
if (this->values().size() == 0) {
throw std::out_of_range(
"The PendulumParams vector has been moved-from; "
"accessor methods may no longer be used");
}
}
};
} // namespace pendulum
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/pendulum_parameters_derivatives.cc | #include <fmt/format.h>
#include "drake/common/eigen_types.h"
#include "drake/examples/pendulum/pendulum_input.h"
#include "drake/examples/pendulum/pendulum_params.h"
#include "drake/examples/pendulum/pendulum_plant.h"
#include "drake/examples/pendulum/pendulum_state.h"
// A simple example on how to take derivatives of the forward dynamics for a
// simple pendulum with respect to the mass parameter.
// The result gets printed to std::out.
namespace drake {
namespace examples {
namespace pendulum {
namespace {
int DoMain() {
// The plant and its context.
PendulumPlant<AutoDiffXd> system;
auto context = system.CreateDefaultContext();
system.get_input_port().FixValue(context.get(), AutoDiffXd(0.0));
// Retrieve the (mutable) state from context so that we can set it.
PendulumState<AutoDiffXd>& state =
PendulumPlant<AutoDiffXd>::get_mutable_state(context.get());
// An arbitrary state configuration around which we'll take derivatives with
// respect to the mass parameter.
state.set_theta(M_PI / 4.0);
state.set_thetadot(-1.0);
// Retrieve the (mutable) parameters so that we can set it.
PendulumParams<AutoDiffXd>& params =
system.get_mutable_parameters(context.get());
// Mass is our independent variable for this example and therefore we set its
// derivative to one.
// Note: all the other parameter values were set by PendulumParams's default
// constructor to be constants (i.e. their derivative with respect to the mass
// parameter is zero).
params.set_mass(AutoDiffXd(1.0, Vector1<double>::Constant(1.0)));
// Allocate and compute derivatives.
auto derivatives = system.AllocateTimeDerivatives();
system.CalcTimeDerivatives(*context, derivatives.get());
const PendulumState<AutoDiffXd>& xdot =
PendulumPlant<AutoDiffXd>::get_state(*derivatives);
// NOLINTNEXTLINE(build/namespaces) Usage documented by fmt library.
using namespace fmt::literals;
// Derivatives values
fmt::print("Forward dynamics, ẋ = [θ̇, ω̇]:\n");
fmt::print("θ̇ = {thetadot:8.4f}\n", "thetadot"_a = xdot.theta().value());
fmt::print("ω̇ = {omegadot:8.4f}\n", "omegadot"_a = xdot.thetadot().value());
// Partial derivative of xdot with respect to mass parameter.
fmt::print("Partial derivative of the forward dynamics with respect to mass, "
"i.e. ∂ẋ/∂m:\n");
// θ̇ is independent of the mass parameter. We verify this by checking the
// size of its vector of derivatives. Since we are using AutoDiffXd, we expect
// this size to be zero (a constant).
DRAKE_DEMAND(xdot.theta().derivatives().size() == 0);
fmt::print("∂θ̇/∂m = {:8.4f}\n", 0.0);
fmt::print("∂ω̇/∂m = {:8.4f}\n", xdot.thetadot().derivatives()[0]);
// Note: for the pendulum, forward dynamics is:
// ω̇ = (τ - bω)/(mℓ²) - g/ℓ⋅sin(θ), with:
// ℓ: length, in m.
// m: mass, in kg.
// b: dissipation, in N⋅m⋅s.
// τ: input torque, in N⋅m.
// g: acceleration of gravity, in m/s².
// Therefore the derivative of ω̇ with respect to m is:
// ∂ω̇/∂m = -(τ - bω)/(m²ℓ²).
return 0;
}
} // namespace
} // namespace pendulum
} // namespace examples
} // namespace drake
int main() {
return drake::examples::pendulum::DoMain();
}
| 0 |
/home/johnshepherd/drake/examples | /home/johnshepherd/drake/examples/pendulum/pendulum_input.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 pendulum {
/// Describes the row indices of a PendulumInput.
struct PendulumInputIndices {
/// The total number of rows (coordinates).
static const int kNumCoordinates = 1;
// The index of each individual coordinate.
static const int kTau = 0;
/// 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, `PendulumInputIndices::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 PendulumInput final : public drake::systems::BasicVector<T> {
public:
/// An abbreviation for our row index constants.
typedef PendulumInputIndices K;
/// Default constructor. Sets all rows to their default value:
/// @arg @c tau defaults to 0.0 Newton-meters.
PendulumInput() : drake::systems::BasicVector<T>(K::kNumCoordinates) {
this->set_tau(0.0);
}
// Note: It's safe to implement copy and move because this class is final.
/// @name Implements CopyConstructible, CopyAssignable, MoveConstructible,
/// MoveAssignable
//@{
PendulumInput(const PendulumInput& other)
: drake::systems::BasicVector<T>(other.values()) {}
PendulumInput(PendulumInput&& other) noexcept
: drake::systems::BasicVector<T>(std::move(other.values())) {}
PendulumInput& operator=(const PendulumInput& other) {
this->values() = other.values();
return *this;
}
PendulumInput& operator=(PendulumInput&& 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_tau(symbolic::Variable("tau"));
}
[[nodiscard]] PendulumInput<T>* DoClone() const final {
return new PendulumInput;
}
/// @name Getters and Setters
//@{
/// Torque at the joint.
/// @note @c tau is expressed in units of Newton-meters.
const T& tau() const {
ThrowIfEmpty();
return this->GetAtIndex(K::kTau);
}
/// Setter that matches tau().
void set_tau(const T& tau) {
ThrowIfEmpty();
this->SetAtIndex(K::kTau, tau);
}
/// Fluent setter that matches tau().
/// Returns a copy of `this` with tau set to a new value.
[[nodiscard]] PendulumInput<T> with_tau(const T& tau) const {
PendulumInput<T> result(*this);
result.set_tau(tau);
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& tau_ref = this->GetAtIndex(K::kTau);
a->Visit(drake::MakeNameValue("tau", &tau_ref));
}
/// See PendulumInputIndices::GetCoordinateNames().
static const std::vector<std::string>& GetCoordinateNames() {
return PendulumInputIndices::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(tau());
return result;
}
private:
void ThrowIfEmpty() const {
if (this->values().size() == 0) {
throw std::out_of_range(
"The PendulumInput vector has been moved-from; "
"accessor methods may no longer be used");
}
}
};
} // namespace pendulum
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples/pendulum | /home/johnshepherd/drake/examples/pendulum/gen/pendulum_state.h | #pragma once
#include "drake/examples/pendulum/pendulum_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/pendulum | /home/johnshepherd/drake/examples/pendulum/gen/pendulum_params.h | #pragma once
#include "drake/examples/pendulum/pendulum_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/pendulum | /home/johnshepherd/drake/examples/pendulum/gen/pendulum_input.h | #pragma once
#include "drake/examples/pendulum/pendulum_input.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/pendulum | /home/johnshepherd/drake/examples/pendulum/test/pendulum_plant_test.cc | #include "drake/examples/pendulum/pendulum_plant.h"
#include <gtest/gtest.h>
#include "drake/common/autodiff.h"
#include "drake/common/test_utilities/expect_no_throw.h"
namespace drake {
namespace examples {
namespace pendulum {
namespace {
GTEST_TEST(PendulumPlantTest, ToAutoDiff) {
// Construct the plant.
PendulumPlant<double> plant;
auto context = plant.CreateDefaultContext();
// Pretend the state has evolved due to simulation.
auto& xc = context->get_mutable_continuous_state_vector();
xc[0] = 42.0; // position
xc[1] = 76.0; // velocity
// Transmogrify the plant to autodiff.
std::unique_ptr<PendulumPlant<AutoDiffXd>> ad_plant =
systems::System<double>::ToAutoDiffXd(plant);
ASSERT_NE(nullptr, ad_plant);
// Construct a new context based on autodiff.
auto ad_context = ad_plant->CreateDefaultContext();
ad_context->SetTimeStateAndParametersFrom(*context);
auto& ad_xc = ad_context->get_mutable_continuous_state_vector();
EXPECT_EQ(42.0, ad_xc[0].value());
EXPECT_EQ(0, ad_xc[0].derivatives().size());
EXPECT_EQ(76.0, ad_xc[1].value());
EXPECT_EQ(0, ad_xc[1].derivatives().size());
// At this point, users could initialize the partials as they pleased.
}
GTEST_TEST(PendulumPlantTest, DirectFeedthrough) {
PendulumPlant<double> plant;
EXPECT_FALSE(plant.HasAnyDirectFeedthrough());
}
GTEST_TEST(PendulumPlantTest, CalcTotalEnergy) {
PendulumPlant<double> plant;
const auto context = plant.CreateDefaultContext();
const auto params = dynamic_cast<const PendulumParams<double>*>(
&context->get_numeric_parameter(0));
EXPECT_TRUE(params);
auto* state = dynamic_cast<PendulumState<double>*>(
&context->get_mutable_continuous_state_vector());
EXPECT_TRUE(state);
const double kTol = 1e-6;
// Energy at the bottom is -mgl.
state->set_theta(0.0);
state->set_thetadot(0.0);
EXPECT_NEAR(plant.CalcTotalEnergy(*context),
-params->mass() * params->gravity() * params->length(), kTol);
// Energy at the top is mgl.
state->set_theta(M_PI);
state->set_thetadot(0.0);
EXPECT_NEAR(plant.CalcTotalEnergy(*context),
params->mass() * params->gravity() * params->length(), kTol);
// Energy at horizontal is 1/2 m v^2.
state->set_theta(M_PI_2);
state->set_thetadot(1.0);
EXPECT_NEAR(plant.CalcTotalEnergy(*context),
0.5 * params->mass() * std::pow(params->length(), 2), kTol);
}
// Ensure that DoCalcTimeDerivatives succeeds even if the input port is
// disconnected.
GTEST_TEST(PendulumPlantTest, NoInput) {
const PendulumPlant<double> plant;
auto context = plant.CreateDefaultContext();
DRAKE_EXPECT_NO_THROW(plant.EvalTimeDerivatives(*context));
}
} // namespace
} // namespace pendulum
} // namespace examples
} // namespace drake
| 0 |
/home/johnshepherd/drake/examples/pendulum | /home/johnshepherd/drake/examples/pendulum/test/urdf_dynamics_test.cc | #include <memory>
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/examples/pendulum/pendulum_plant.h"
#include "drake/multibody/parsing/parser.h"
#include "drake/multibody/plant/multibody_plant.h"
namespace drake {
namespace examples {
namespace pendulum {
namespace {
GTEST_TEST(UrdfDynamicsTest, AllTests) {
multibody::MultibodyPlant<double> mbp(0.0);
multibody::Parser(&mbp).AddModelsFromUrl(
"package://drake/examples/pendulum/Pendulum.urdf");
mbp.Finalize();
PendulumPlant<double> p;
auto context_mbp = mbp.CreateDefaultContext();
auto context_p = p.CreateDefaultContext();
auto& u_mbp = mbp.get_actuation_input_port().FixValue(context_mbp.get(), 0.);
auto& u_p = p.get_input_port().FixValue(context_p.get(), 0.);
Eigen::Vector2d x;
Vector1d u;
auto xdot_mbp = mbp.AllocateTimeDerivatives();
auto xdot_p = p.AllocateTimeDerivatives();
for (int i = 0; i < 100; ++i) {
x = Eigen::Vector2d::Random();
u = Vector1d::Random();
context_mbp->get_mutable_continuous_state_vector().SetFromVector(x);
context_p->get_mutable_continuous_state_vector().SetFromVector(x);
u_mbp.GetMutableVectorData<double>()->SetFromVector(u);
u_p.GetMutableVectorData<double>()->SetFromVector(u);
mbp.CalcTimeDerivatives(*context_mbp, xdot_mbp.get());
p.CalcTimeDerivatives(*context_p, xdot_p.get());
EXPECT_TRUE(CompareMatrices(xdot_mbp->CopyToVector(),
xdot_p->CopyToVector(), 1e-8,
MatrixCompareType::absolute));
}
}
} // namespace
} // namespace pendulum
} // namespace examples
} // namespace drake
| 0 |