Example #1
0
    def __init__(self, meshcat_viz, draw_period=_DEFAULT_PUBLISH_PERIOD,
                 name="point_cloud", X_WP=Isometry3.Identity(),
                 default_rgb=[255., 255., 255.]):
        """
        Args:
            meshcat_viz: Either a native meshcat.Visualizer or a pydrake
                MeshcatVisualizer object.
            draw_period: The rate at which this class publishes to the
                visualizer.
            name: The string name of the meshcat object.
            X_WP: Pose of point cloud frame ``P`` in meshcat world frame ``W``.
                Default is identity.
            default_rgb: RGB value for published points if the PointCloud does
                not provide RGB values.
        """
        LeafSystem.__init__(self)

        self._meshcat_viz = _get_native_visualizer(meshcat_viz)
        self._X_WP = X_WP
        self._default_rgb = np.array(default_rgb)
        self._name = name

        self.set_name('meshcat_point_cloud_visualizer')
        self._DeclarePeriodicPublish(draw_period, 0.0)

        self._DeclareAbstractInputPort("point_cloud_P",
                                       AbstractValue.Make(mut.PointCloud()))
Example #2
0
 def __init__(self):
     LeafSystem.__init__(self)
     self.DeclareContinuousState(1)
     self.DeclareDiscreteState(2)
     self.DeclareAbstractState(model_value.Clone())
     self.DeclareAbstractParameter(model_value.Clone())
     self.DeclareNumericParameter(model_vector.Clone())
Example #3
0
    def __init__(self):
        LeafSystem.__init__(self)

        self.DeclareVectorInputPort("touchdown_angle", BasicVector(1))
        self.DeclareContinuousState(BasicVector(np.zeros(8)), 4, 4, 0)

        self.DeclareVectorOutputPort("state", BasicVector(8),
                                     self.CopyStateOut)

        # Parameters from Geyer05, p.23
        self.mass = 80.  # kg
        self.r0 = 1.  # m
        self.gravity = 9.81  # m/s^2
        # Define spring constant in terms of the dimensionless number.
        # Definition in section 2.4.3, values in figure 2.4.
        # Note: Geyer05 says 10.8 (which doesn't work? -- I get no fixed pts).
        dimensionless_spring_constant = 10.7
        self.stiffness = \
            dimensionless_spring_constant*self.mass*self.gravity/self.r0

        self.last_apex = None  # placeholder for writing return map result.

        self.touchdown_witness = self.MakeWitnessFunction(
            "touchdown", WitnessFunctionDirection.kPositiveThenNonPositive,
            self.foot_height, UnrestrictedUpdateEvent(self.touchdown))
        self.takeoff_witness = self.MakeWitnessFunction(
            "takeoff", WitnessFunctionDirection.kPositiveThenNonPositive,
            self.leg_compression, UnrestrictedUpdateEvent(self.takeoff))
        self.apex_witness = self.MakeWitnessFunction(
            "apex", WitnessFunctionDirection.kPositiveThenNonPositive,
            self.apex, PublishEvent(self.publish_apex))
Example #4
0
    def __init__(self, robot, frame_E, parameters, time_step):
        """
        @param robot is a reference to a MultibodyPlant.
        @param frame_E is a multibody::Frame on the robot.
        @param params is a DifferentialIKParams.
        @params time_step This system updates its state/outputs at discrete
                          periodic intervals defined with period @p time_step.
        """
        LeafSystem.__init__(self)
        self.robot = robot
        self.frame_E = frame_E
        self.parameters = parameters
        self.parameters.set_timestep(time_step)
        self.time_step = time_step
        # Note that this context is NOT the context of the DifferentialIK
        # system, but rather a context for the multibody plant that is used
        # to pass the configuration into the DifferentialInverseKinematics
        # methods.
        self.robot_context = robot.CreateDefaultContext()
        # Confirm that all velocities are zero (they will not be reset below).
        assert not self.robot.GetPositionsAndVelocities(
            self.robot_context)[-robot.num_velocities():].any()

        # Store the robot positions as state.
        self.DeclareDiscreteState(robot.num_positions())
        self.DeclarePeriodicDiscreteUpdate(time_step)

        # Desired pose of frame E in world frame.
        self.DeclareInputPort("rpy_xyz_desired",
                              PortDataType.kVectorValued, 6)

        # Provide the output as desired positions.
        self.DeclareVectorOutputPort("joint_position_desired", BasicVector(
            robot.num_positions()), self.CopyPositionOut)
Example #5
0
 def __init__(self):
     LeafSystem.__init__(self)
     self.called_publish = False
     self.called_feedthrough = False
     self.called_continuous = False
     self.called_discrete = False
     self.called_initialize = False
     self.called_per_step = False
     self.called_periodic = False
     self.called_getwitness = False
     self.called_witness = False
     self.called_guard = False
     self.called_reset = False
     # Ensure we have desired overloads.
     self.DeclarePeriodicPublish(1.0)
     self.DeclarePeriodicPublish(1.0, 0)
     self.DeclarePeriodicPublish(period_sec=1.0, offset_sec=0.)
     self.DeclarePeriodicDiscreteUpdate(
         period_sec=1.0, offset_sec=0.)
     self.DeclareInitializationEvent(
         event=PublishEvent(
             trigger_type=TriggerType.kInitialization,
             callback=self._on_initialize))
     self.DeclarePerStepEvent(
         event=PublishEvent(
             trigger_type=TriggerType.kPerStep,
             callback=self._on_per_step))
     self.DeclarePeriodicEvent(
         period_sec=1.0,
         offset_sec=0.0,
         event=PublishEvent(
             trigger_type=TriggerType.kPeriodic,
             callback=self._on_periodic))
     self.DeclareContinuousState(2)
     self.DeclareDiscreteState(1)
     # Ensure that we have inputs / outputs to call direct
     # feedthrough.
     self.DeclareInputPort(PortDataType.kVectorValued, 1)
     self.DeclareVectorInputPort(
         name="test_input", model_vector=BasicVector(1),
         random_type=None)
     self.DeclareVectorOutputPort(
         "noop", BasicVector(1), noop,
         prerequisites_of_calc=set([self.nothing_ticket()]))
     self.witness = self.MakeWitnessFunction(
         "witness", WitnessFunctionDirection.kCrossesZero,
         self._witness)
     self.reset_witness = self.MakeWitnessFunction(
         "reset", WitnessFunctionDirection.kCrossesZero,
         self._guard, UnrestrictedUpdateEvent(self._reset))
Example #6
0
 def __init__(self):
     LeafSystem.__init__(self)
     self.called_publish = False
     self.called_continuous = False
     self.called_discrete = False
     self.called_initialize = False
     self.called_per_step = False
     self.called_periodic = False
     self.called_getwitness = False
     self.called_witness = False
     self.called_guard = False
     self.called_reset = False
     # Ensure we have desired overloads.
     self.DeclarePeriodicPublish(1.0)
     self.DeclarePeriodicPublish(1.0, 0)
     self.DeclarePeriodicPublish(period_sec=1.0, offset_sec=0.)
     self.DeclarePeriodicDiscreteUpdate(
         period_sec=1.0, offset_sec=0.)
     self.DeclareInitializationEvent(
         event=PublishEvent(
             trigger_type=TriggerType.kInitialization,
             callback=self._on_initialize))
     self.DeclarePerStepEvent(
         event=PublishEvent(
             trigger_type=TriggerType.kPerStep,
             callback=self._on_per_step))
     self.DeclarePeriodicEvent(
         period_sec=1.0,
         offset_sec=0.0,
         event=PublishEvent(
             trigger_type=TriggerType.kPeriodic,
             callback=self._on_periodic))
     self.DeclareContinuousState(2)
     self.DeclareDiscreteState(1)
     # Ensure that we have inputs / outputs to call direct
     # feedthrough.
     self.DeclareInputPort(PortDataType.kVectorValued, 1)
     self.DeclareVectorInputPort(
         name="test_input", model_vector=BasicVector(1),
         random_type=None)
     self.DeclareVectorOutputPort(
         "noop", BasicVector(1), noop,
         prerequisites_of_calc=set([self.nothing_ticket()]))
     self.witness = self.MakeWitnessFunction(
         "witness", WitnessFunctionDirection.kCrossesZero,
         self._witness)
     self.reset_witness = self.MakeWitnessFunction(
         "reset", WitnessFunctionDirection.kCrossesZero,
         self._guard, UnrestrictedUpdateEvent(self._reset))
Example #7
0
    def __init__(self,
                 window=None,
                 open_position=0.107,
                 closed_position=0.002,
                 force_limit=40,
                 update_period_sec=0.05):
        """"
        Args:
            window:          Optionally pass in a tkinter.Tk() object to add
                             these widgets to.  Default behavior is to create
                             a new window.
            update_period_sec: Specifies how often the window update() method
                             gets called.
            open_position:   Target position for the finger when open.
            closed_position: Target position for the gripper when closed.
            force_limit:     Force limit to send to Schunk WSG controller.
        """
        LeafSystem.__init__(self)
        self._DeclareVectorOutputPort("position", BasicVector(1),
                                      self.CalcPositionOutput)
        self._DeclareVectorOutputPort("force_limit", BasicVector(1),
                                      self.CalcForceLimitOutput)

        if window is None:
            self.window = tk.Tk()
            self.window.title(title)
        else:
            self.window = window

        # Schedule window updates in either case (new or existing window):
        self._DeclarePeriodicPublish(update_period_sec, 0.0)

        self._open_button = tk.Button(self.window,
                                      text="Open Gripper",
                                      state=tk.DISABLED,
                                      command=self.open)
        self._open_button.pack()
        self._close_button = tk.Button(self.window,
                                       text="Close Gripper",
                                       command=self.close)
        self._close_button.pack()

        self._open_state = True

        self._open_position = open_position
        self._closed_position = closed_position
        self._force_limit = force_limit

        self.window.bind("<space>", self._space_callback)
Example #8
0
 def __init__(self):
     LeafSystem.__init__(self)
     self.called_publish = False
     self.called_feedthrough = False
     self.called_discrete = False
     # Ensure we have desired overloads.
     self._DeclarePeriodicPublish(0.1)
     self._DeclarePeriodicPublish(0.1, 0)
     self._DeclarePeriodicPublish(period_sec=0.1, offset_sec=0.)
     self._DeclarePeriodicDiscreteUpdate(
         period_sec=0.1, offset_sec=0.)
     self._DeclareDiscreteState(1)
     # Ensure that we have inputs / outputs to call direct
     # feedthrough.
     self._DeclareInputPort(PortDataType.kVectorValued, 1)
     self._DeclareVectorOutputPort(BasicVector(1), noop)
Example #9
0
 def __init__(self):
     LeafSystem.__init__(self)
     self.called_publish = False
     self.called_feedthrough = False
     self.called_discrete = False
     # Ensure we have desired overloads.
     self._DeclarePeriodicPublish(0.1)
     self._DeclarePeriodicPublish(0.1, 0)
     self._DeclarePeriodicPublish(period_sec=0.1, offset_sec=0.)
     self._DeclarePeriodicDiscreteUpdate(
         period_sec=0.1, offset_sec=0.)
     self._DeclareDiscreteState(1)
     # Ensure that we have inputs / outputs to call direct
     # feedthrough.
     self._DeclareInputPort(PortDataType.kVectorValued, 1)
     self._DeclareVectorOutputPort(BasicVector(1), noop)
    def __init__(self, actuators, motor_gain=None):
        LeafSystem.__init__(self)
        self.num_actuators = len(actuators)
        self.actuators_init = np.ones(self.num_actuators) * 0.0
        if motor_gain is None:
            motor_gain = np.ones(self.num_actuators)

        assert motor_gain.shape == (self.num_actuators, )

        self.motor_gain = motor_gain
        self.robot_command_port_index = self._DeclareInputPort(
            'robot_command_port', PortDataType.kVectorValued,
            self.num_actuators).get_index()

        self.desired_effort_port_index = self._DeclareVectorOutputPort(
            BasicVector(self.num_actuators), self.OutputActuation).get_index()
Example #11
0
    def __init__(self,
                 draw_period=None,
                 facecolor=[1, 1, 1],
                 figsize=None,
                 ax=None,
                 show=None):
        LeafSystem.__init__(self)

        # To help avoid small simulation timesteps, we use a default period
        # that has an exact representation in binary floating point; see
        # drake#15021 for details.
        default_draw_period = 1. / 32

        self.set_name('pyplot_visualization')
        self.timestep = draw_period or default_draw_period
        self.DeclarePeriodicPublish(self.timestep, 0.0)

        if ax is None:
            self.fig = plt.figure(facecolor=facecolor, figsize=figsize)
            self.ax = plt.axes()
            self.fig.add_axes(self.ax)
        else:
            self.ax = ax
            self.fig = ax.get_figure()

        if show is None:
            show = (matplotlib.get_backend().lower() != 'template')
        self._show = show

        self.ax.axis('equal')
        self.ax.axis('off')

        if not show:
            # This is the preferred way to support the jupyter notebook
            # animation workflow and the `inline` backend grabbing an
            # extraneous render of the figure.
            plt.close(self.fig)

        self._is_recording = False
        self._recorded_contexts = []

        def on_initialize(context, event):
            if self._show:
                self.fig.show()

        self.DeclareInitializationEvent(event=PublishEvent(
            trigger_type=TriggerType.kInitialization, callback=on_initialize))
    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)
        self.DeclareVectorOutputPort("rpy_xyz", 6, self.DoCalcOutput)
        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)
Example #13
0
    def __init__(self, log_file, publish_period=0.033333):
        LeafSystem.__init__(self)

        self.iter = 0
        self.set_name('ycb yaml log bbox publisher')
        self.publish_period = publish_period
        self.DeclarePeriodicPublish(self.publish_period, 0.0)

        self.bbox_bundle_output_port = \
            self.DeclareAbstractOutputPort(
                self.DoAllocBboxBundle,
                self.DoCalcAbstractOutput)

        # Load in log and prepare ordered list of the bundles
        # across time
        with open(log_file, "r") as f:
            log_yaml = yaml.load(f)

        self.colors_by_obj = log_yaml["colors"]
        self.sizes_by_obj = log_yaml["sizes"]
        self.bbox_bundle_times = []
        self.bbox_bundle_durations = []
        self.bbox_bundles = []
        for detection_event in log_yaml["detection_events"]:
            t = detection_event["t"]
            self.bbox_bundle_times.append(t)
            self.bbox_bundle_durations.append(detection_event["duration"])
            detected_objs = detection_event["detections"].keys()
            bbox_bundle = BoundingBoxBundle(len(detected_objs))
            for i, obj_name in enumerate(detected_objs):
                assert (obj_name in self.colors_by_obj.keys()
                        and obj_name in self.sizes_by_obj.keys())
                color_float = [
                    float(x) / 255. for x in self.colors_by_obj[obj_name]
                ]
                scale = [eval(x) for x in self.sizes_by_obj[obj_name]]
                bbox_bundle.set_bbox_attributes(
                    i,
                    scale=scale,
                    color=color_float,
                    pose=RigidTransform(
                        np.array(detection_event["detections"]
                                 [obj_name])).GetAsIsometry3())
            self.bbox_bundles.append((bbox_bundle))
        self.bbox_bundle_times = np.array(self.bbox_bundle_times)
        self.bbox_bundle_durations = np.array(self.bbox_bundle_durations)
Example #14
0
 def __init__(self, index):
     LeafSystem.__init__(self)
     num_q = 2
     num_v = 1
     num_z = 3
     num_state = num_q + num_v + num_z
     if index == 0:
         self._DeclareContinuousState(num_state_variables=num_state)
     elif index == 1:
         self._DeclareContinuousState(
             num_q=num_q, num_v=num_v, num_z=num_z)
     elif index == 2:
         self._DeclareContinuousState(BasicVector(num_state))
     elif index == 3:
         self._DeclareContinuousState(
             BasicVector(num_state),
             num_q=num_q, num_v=num_v, num_z=num_z)
Example #15
0
    def __init__(self, rb_tree):
        LeafSystem.__init__(self)
        self.rb_tree = rb_tree
        self.num_controlled_q_ = self.rb_tree.get_num_positions()

        # Input Port
        self.joint_state_results_port_index = self._DeclareInputPort(
            'joint_state_results_port', PortDataType.kVectorValued,
            self.num_controlled_q_ * 2).get_index()
        #         self.contact_results_port_index = self._DeclareAbstractInputPort('contact_results_port',
        #                                                                        AbstractValue.Make(ContactResults)).get_index()
        # Output Port
        self.lcm_message_port_index = self._DeclareAbstractOutputPort(
            'state_output_port',
            self._Allocator,
            self._OutputRobotState,
        ).get_index()
Example #16
0
    def __init__(self, grab_focus=True):
        LeafSystem.__init__(self)
        self.DeclareVectorOutputPort("rpy_xyz", 6, self.DoCalcOutput)
        self.DeclareVectorOutputPort("position", 1, self.CalcPositionOutput)
        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.DeclarePeriodicPublish(0.01, 0.0)

        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
Example #17
0
    def __init__(self,
                 meshcat_viz,
                 force_threshold=1e-2,
                 contact_force_scale=10,
                 plant=None,
                 contact_force_radius=0.01):
        """
        Args:
            meshcat_viz: A pydrake MeshcatVisualizer instance.
            force_threshold: contact forces whose norms are smaller than
                force_threshold are not displayed.
            contact_force_scale: a contact force with norm F (in Newtons) is
                displayed as a cylinder with length F/contact_force_scale
                (in meters).
            plant: the MultibodyPlant associated with meshcat_viz.scene_graph.
            contact_force_radius: sets the constant radius of the cylinder used
                to visualize the forces.
        """
        LeafSystem.__init__(self)
        assert plant is not None
        self._meshcat_viz = meshcat_viz
        self._force_threshold = force_threshold
        self._contact_force_scale = contact_force_scale
        self._plant = plant
        self._radius = contact_force_radius

        self.set_name('meshcat_contact_visualizer')
        self.DeclarePeriodicPublish(self._meshcat_viz.draw_period, 0.0)
        # Pose bundle (from SceneGraph) input port.
        self.DeclareAbstractInputPort("pose_bundle",
                                      AbstractValue.Make(PoseBundle(0)))
        # Contact results input port from MultibodyPlant
        self.DeclareAbstractInputPort("contact_results",
                                      AbstractValue.Make(ContactResults()))

        # Make force cylinders smaller at initialization.
        self._force_cylinder_radial_scale = 1.
        self._force_cylinder_longitudinal_scale = 100.

        # This system has undeclared states, see #4330.
        # - All contacts (previous and current), of type `_ContactState`.
        self._contacts = []
        # - Unique key for contacts in meshcat.
        self._contact_key_counter = 0
        # - Previous time at which contact was published.
        self._t_previous = 0.
Example #18
0
 def __init__(self, index):
     LeafSystem.__init__(self)
     num_q = 2
     num_v = 1
     num_z = 3
     num_state = num_q + num_v + num_z
     if index == 0:
         self._DeclareContinuousState(num_state_variables=num_state)
     elif index == 1:
         self._DeclareContinuousState(
             num_q=num_q, num_v=num_v, num_z=num_z)
     elif index == 2:
         self._DeclareContinuousState(BasicVector(num_state))
     elif index == 3:
         self._DeclareContinuousState(
             BasicVector(num_state),
             num_q=num_q, num_v=num_v, num_z=num_z)
Example #19
0
    def __init__(self, arms, limit, timestep=0.005):
        LeafSystem.__init__(self)
        self.limit = limit
        self.timestep = timestep
        self.arms = arms

        self.target_input_ports = {}
        self.setpoint_output_ports = {}
        for arm in self.arms:
            self.target_input_ports[arm] = {}
            self.setpoint_output_ports[arm] = {}
            self.target_input_ports[arm][
                "position"] = self.DeclareVectorInputPort(
                    f"{arm}_target",
                    BasicVector(6),
                )
            self.target_input_ports[arm][
                "width"] = self.DeclareVectorInputPort(
                    f"{arm}_width_target",
                    BasicVector(1),
                )
        if "left" in self.arms:
            self.setpoint_output_ports["left"][
                "position"] = self.DeclareVectorOutputPort(
                    f"left_setpoint", BasicVector(6), self.DoCalcLeftOutput)
            self.setpoint_output_ports["left"][
                "width"] = self.DeclareVectorOutputPort(
                    f"left_width_setpoint", BasicVector(1),
                    self.DoCalcLeftWidthOutput)
        if "right" in self.arms:
            self.setpoint_output_ports["right"][
                "position"] = self.DeclareVectorOutputPort(
                    f"right_setpoint", BasicVector(6), self.DoCalcRightOutput)
            self.setpoint_output_ports["right"][
                "width"] = self.DeclareVectorOutputPort(
                    f"right_width_setpoint", BasicVector(1),
                    self.DoCalcRightWidthOutput)

        self.current_states = {}
        for arm in self.arms:
            self.current_states[arm] = {}
            self.current_states[arm]["position"] = self.DeclareDiscreteState(6)
            self.current_states[arm]["width"] = self.DeclareDiscreteState(1)

        self.DeclarePeriodicDiscreteUpdate(self.timestep)
Example #20
0
    def __init__(self, meshcat, slider_names):
        """
        An output port is created for each element in the list `slider_names`.
        Each element of `slider_names` must itself be an iterable collection
        (list, tuple, set, ...) of strings, with the names of sliders that have
        *already* been added to Meshcat via Meshcat.AddSlider().

        The same slider may be used in multiple ports.
        """
        LeafSystem.__init__(self)

        self._meshcat = meshcat
        self._sliders = slider_names
        for i, slider_iterable in enumerate(self._sliders):
            port = self.DeclareVectorOutputPort(
                f"slider_group_{i}", len(slider_iterable),
                partial(self.DoCalcOutput, port_index=i))
            port.disable_caching_by_default()
Example #21
0
    def __init__(self, window=None, open_position=0.107,
                 closed_position=0.002, force_limit=40,
                 update_period_sec=0.05):
        """"
        Args:
            window:          Optionally pass in a tkinter.Tk() object to add
                             these widgets to.  Default behavior is to create
                             a new window.
            update_period_sec: Specifies how often the window update() method
                             gets called.
            open_position:   Target position for the finger when open.
            closed_position: Target position for the gripper when closed.
            force_limit:     Force limit to send to Schunk WSG controller.
        """
        LeafSystem.__init__(self)
        self._DeclareVectorOutputPort("position", BasicVector(1),
                                      self.CalcPositionOutput)
        self._DeclareVectorOutputPort("force_limit", BasicVector(1),
                                      self.CalcForceLimitOutput)

        if window is None:
            self.window = tk.Tk()
            self.window.title(title)
        else:
            self.window = window

        # Schedule window updates in either case (new or existing window):
        self._DeclarePeriodicPublish(update_period_sec, 0.0)

        self._open_button = tk.Button(self.window, text="Open Gripper",
                                      state=tk.DISABLED,
                                      command=self.open)
        self._open_button.pack()
        self._close_button = tk.Button(self.window, text="Close Gripper",
                                       command=self.close)
        self._close_button.pack()

        self._open_state = True

        self._open_position = open_position
        self._closed_position = closed_position
        self._force_limit = force_limit

        self.window.bind("<space>", self._space_callback)
    def __init__(self, rb_tree):
        LeafSystem.__init__(self)
        self.rb_tree = rb_tree
        self.num_position = self.rb_tree.get_num_positions()
        self.num_controlled_q_ = self.rb_tree.get_num_actuators()

        self.n = 0

        # Input Port
        self.joint_state_results_port_index = self._DeclareInputPort(
            'joint_state_results_port', PortDataType.kVectorValued,
            self.num_position * 2).get_index()
        #         self.contact_results_port_index = self._DeclareAbstractInputPort('contact_results_port',
        #                                                                        AbstractValue.Make(ContactResults)).get_index()
        # Output Port

        self.joint_state_outport_index = self._DeclareVectorOutputPort(
            'state_output_port', BasicVector(self.num_controlled_q_ * 2),
            self._OutputRobotState).get_index()
Example #23
0
    def __init__(self, joystick):
        LeafSystem.__init__(self)
        self.DeclareVectorOutputPort("rpy_xyz", BasicVector(6),
                                     self.DoCalcOutput)
        self.DeclareVectorOutputPort("position", BasicVector(1),
                                     self.CalcPositionOutput)
        self.DeclareVectorOutputPort("force_limit", BasicVector(1),
                                     self.CalcForceLimitOutput)

        # Note: This timing affects the keyboard teleop performance. A larger
        #       time step causes more lag in the response.
        self.DeclarePeriodicPublish(1.0, 0.0)

        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
Example #24
0
    def __init__(self,
                 meshcat_viz,
                 force_threshold=1e-2,
                 contact_force_scale=10,
                 plant=None,
                 contact_force_radius=0.01):
        """
        Args:
            meshcat_viz: A pydrake MeshcatVisualizer instance.
            force_threshold: contact forces whose norms are smaller than
                force_threshold are not displayed.
            contact_force_scale: a contact force with norm F (in Newtons) is
                displayed as a cylinder with length F/contact_force_scale
                (in meters).
            plant: the MultibodyPlant associated with meshcat_viz.scene_graph.
            contact_force_radius: sets the constant radius of the cylinder used
                to visualize the forces.
        """
        LeafSystem.__init__(self)
        assert plant is not None
        self._meshcat_viz = meshcat_viz
        self._force_threshold = force_threshold
        self._contact_force_scale = contact_force_scale
        self._plant = plant
        self._radius = contact_force_radius

        self.set_name('meshcat_contact_visualizer')
        self.DeclarePeriodicPublish(self._meshcat_viz.draw_period, 0.0)

        # Pose bundle (from SceneGraph) input port.
        self.DeclareAbstractInputPort("pose_bundle",
                                      AbstractValue.Make(PoseBundle(0)))
        # Contact results input port from MultibodyPlant
        self.DeclareAbstractInputPort("contact_results",
                                      AbstractValue.Make(ContactResults()))

        # This system has undeclared states, see #4330.
        self._warned_pose_bundle_input_port_connected = False
        self._published_contacts = []

        # Zap any previous contact forces on this prefix
        vis = self._meshcat_viz.vis[self._meshcat_viz.prefix]["contact_forces"]
        vis.delete()
Example #25
0
    def __init__(self, scene_graph):
        LeafSystem.__init__(self)
        assert scene_graph

        mbp = MultibodyPlant(0.0)
        parser = Parser(mbp, scene_graph)
        model_id = parser.AddModelFromFile(
            FindResource("models/glider/glider.urdf"))
        mbp.Finalize()
        self.source_id = mbp.get_source_id()
        self.body_frame_id = mbp.GetBodyFrameIdOrThrow(
            mbp.GetBodyIndices(model_id)[0])
        self.elevator_frame_id = mbp.GetBodyFrameIdOrThrow(
            mbp.GetBodyIndices(model_id)[1])

        self.DeclareVectorInputPort("state", BasicVector(7))
        self.DeclareAbstractOutputPort(
            "geometry_pose", lambda: AbstractValue.Make(FramePoseVector()),
            self.OutputGeometryPose)
Example #26
0
    def __init__(self, station, control_period=0.005, print_period=0.5):
        LeafSystem.__init__(self)
        self.set_name("Iiwa Controller")

        self.current_plan = None

        # Stuff for iiwa control
        self.nu = 7
        self.print_period = print_period
        self.last_print_time = -print_period
        self.control_period = control_period

        # create a multibodyplant containing the robot only, which is used for
        # jacobian calculations.
        self.plant_iiwa = station.get_controller_plant()
        self.tree_iiwa = self.plant_iiwa.tree()
        self.context_iiwa = self.plant_iiwa.CreateDefaultContext()
        self.l7_frame = self.plant_iiwa.GetFrameByName('iiwa_link_7')

        # Declare iiwa_position/torque_command publishing rate
        self._DeclarePeriodicPublish(control_period)

        # iiwa position input port
        self.iiwa_position_input_port = \
            self._DeclareInputPort(
                "iiwa_position", PortDataType.kVectorValued, 7)

        # iiwa velocity input port
        self.iiwa_velocity_input_port = \
            self._DeclareInputPort(
                "iiwa_velocity", PortDataType.kVectorValued, 7)

        # plan abstract input port
        self.plan_input_port = \
            self._DeclareAbstractInputPort(
                "iiwa_plan", AbstractValue.Make(PlanBase()))

        # position and torque command output port
        # first 7 elements are position commands.
        # last 7 elements are torque commands.
        self.iiwa_position_command_output_port = \
            self._DeclareVectorOutputPort("iiwa_position_and_torque_command",
                                          BasicVector(self.nu*2), self._CalcIiwaCommand)
    def __init__(self, grab_focus=True):
        LeafSystem.__init__(self)
        self._DeclareVectorOutputPort("rpy_xyz", BasicVector(6),
                                      self._DoCalcOutput)
        self._DeclareVectorOutputPort("position", BasicVector(1),
                                      self.CalcPositionOutput)
        self._DeclareVectorOutputPort("force_limit", BasicVector(1),
                                      self.CalcForceLimitOutput)

        # Note: This timing affects the keyboard teleop performance. A larger
        #       time step causes more lag in the response.
        self._DeclarePeriodicPublish(0.01, 0.0)

        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
Example #28
0
    def __init__(self,
                 meshcat_viz,
                 force_threshold=1e-2,
                 contact_force_scale=10,
                 plant=None):
        """
        Args:
            meshcat_viz: a MeshcatVisualizer object.
            force_threshold: contact forces whose norms are smaller than
                force_threshold are not displayed.
            contact_force_scale: a contact force with norm F (in Newtons) is
                displayed as a cylinder with length F/contact_force_scale
                (in meters).
            plant: the MultibodyPlant associated with meshcat_viz.scene_graph.
        """
        LeafSystem.__init__(self)
        assert plant is not None
        self._meshcat_viz = meshcat_viz
        self._force_threshold = force_threshold
        self._contact_force_scale = contact_force_scale
        self._plant = plant

        self.set_name('meshcat_contact_visualizer')
        self._DeclarePeriodicPublish(self._meshcat_viz.draw_period, 0.0)
        # Pose bundle (from SceneGraph) input port.
        self._DeclareAbstractInputPort("pose_bundle",
                                       AbstractValue.Make(PoseBundle(0)))
        # Contact results input port from MultibodyPlant
        self._DeclareAbstractInputPort(
            "contact_results", AbstractValue.Make(ContactResults()))

        # Make force cylinders smaller at initialization.
        self._force_cylinder_radial_scale = 1.
        self._force_cylinder_longitudinal_scale = 100.

        # This system has undeclared states, see #4330.
        # - All contacts (previous and current), of type `_ContactState`.
        self._contacts = []
        # - Unique key for contacts in meshcat.
        self._contact_key_counter = 0
        # - Previous time at which contact was published.
        self._t_previous = 0.
Example #29
0
    def __init__(self, rbtree, kp, ki, kd):
        LeafSystem.__init__(self)
        self.rb_tree = rbtree
        self.num_controlled_q_ = self.rb_tree.get_num_actuators()

        self.kp = kp
        self.ki = ki
        self.kd = kd

        self.input_index_state = self._DeclareInputPort(
            'robot_state_port', PortDataType.kVectorValued,
            self.num_controlled_q_ * 2).get_index()

        self.input_index_desired_state = self._DeclareInputPort(
            'state_ref_port', PortDataType.kVectorValued,
            self.num_controlled_q_ * 2).get_index()

        self.robot_command_port_index = self._DeclareVectorOutputPort(
            BasicVector(self.num_controlled_q_),
            self._OutputCommand).get_index()
    def __init__(self, mbp, grab_period=0.1, symbol_logger=None):
        LeafSystem.__init__(self)

        self.mbp = mbp
        # Our version of MBP context, which we'll modify
        # in the publish method.
        self.mbp_context = mbp.CreateDefaultContext()

        # Object body names we care about
        self.body_names = ["blue_box", "red_box"]

        self.set_name('symbol_detection_system')
        self.DeclarePeriodicPublish(grab_period, 0.0)

        # Take robot state vector as input.
        self.DeclareVectorInputPort(
            "mbp_state_vector",
            BasicVector(mbp.num_positions() + mbp.num_velocities()))

        self._symbol_logger = symbol_logger
    def __init__(self, rbtree, kp, ki, kd):
        LeafSystem.__init__(self)
        self.rb_tree = rbtree
        self.num_controlled_q_ = self.rb_tree.get_num_actuators()

        self.kp = kp
        self.ki = ki
        self.kd = kd

        self.robot_state_port_index = self._DeclareAbstractInputPort(
            'robot_state_port', AbstractValue.Make(robot_state_t)).get_index()

        # self.state_ref_port_index = self._DeclareInputPort('State_Ref_Port', PortDataType.kVectorValued,
        #                                                    self.num_controlled_q_ * 2).get_index()

        self.robot_command_port_index = self._DeclareAbstractOutputPort(
            'robot_command_port',
            self._Allocator,
            self._OutputCommand,
        ).get_index()
Example #32
0
    def __init__(self, kuka_plans, gripper_setpoint_list, update_period=0.05):
        LeafSystem.__init__(self)
        self.set_name("Plan Scheduler")

        assert len(kuka_plans) == len(gripper_setpoint_list)

        # Add a zero order hold to hold the current position of the robot
        kuka_plans.insert(
            0, JointSpacePlanRelative(duration=3.0, delta_q=np.zeros(7)))
        gripper_setpoint_list.insert(0, 0.055)

        if len(kuka_plans) > 1:
            # Insert to the beginning of plan_list a plan that moves the robot from its
            # current position to plan_list[0].traj.value(0)
            kuka_plans.insert(
                1,
                JointSpacePlanGoToTarget(
                    duration=6.0,
                    q_target=kuka_plans[1].traj.value(0).flatten()))
            gripper_setpoint_list.insert(0, 0.055)

        self.gripper_setpoint_list = gripper_setpoint_list
        self.kuka_plans_list = kuka_plans

        self.current_plan = None
        self.current_gripper_setpoint = None
        self.current_plan_idx = 0

        # Output ports for plans and gripper setpoints
        self.iiwa_plan_output_port = self._DeclareAbstractOutputPort(
            "iiwa_plan", lambda: AbstractValue.Make(PlanBase()),
            self._GetCurrentPlan)

        self.hand_setpoint_output_port = \
            self._DeclareVectorOutputPort(
                "gripper_setpoint", BasicVector(1), self._CalcHandSetpointOutput)
        self.gripper_force_limit_output_port = \
            self._DeclareVectorOutputPort(
                "force_limit", BasicVector(1), self._CalcForceLimitOutput)

        self._DeclarePeriodicPublish(update_period)
Example #33
0
    def __init__(self):
        LeafSystem.__init__(self)

        self.DeclareVectorInputPort("u", BasicVector(4))
        self.DeclareContinuousState(BasicVector(np.zeros(14)), 7, 7, 0)

        self.DeclareVectorOutputPort("state", BasicVector(10),
                                     self.CopyStateOut)

        # Parameters from Geyer05, p.23
        self.mass = np.array([0.5, 0.5, 0.5, 0.5, 0.5])  # kg
        self.length = np.array([0.5, 0.5, 0.5, 0.5, 0.5])  # m
        self.gravity = 9.81  # m/s^2
        self.inertia = self.mass * self.length

        self.left_impact_witness = self.MakeWitnessFunction(
            "impact", WitnessFunctionDirection.kPositiveThenNonPositive,
            self.left_foot_height, UnrestrictedUpdateEvent(self.switch))
        self.right_impact_witness = self.MakeWitnessFunction(
            "impact", WitnessFunctionDirection.kPositiveThenNonPositive,
            self.right_foot_height, UnrestrictedUpdateEvent(self.switch))
Example #34
0
    def __init__(self, update_period=0.05):
        LeafSystem.__init__(self)
        self.set_name("Plan Scheduler")

        self.current_plan = None
        self.current_gripper_setpoint = None
        self.end_time = 0

        # Output ports for plans and gripper setpoints
        self.iiwa_plan_output_port = self._DeclareAbstractOutputPort(
            "iiwa_plan", lambda: AbstractValue.Make(PlanBase()),
            self._GetCurrentPlan)

        self.hand_setpoint_output_port = \
            self._DeclareVectorOutputPort(
                "gripper_setpoint", BasicVector(1), self._CalcHandSetpointOutput)
        self.gripper_force_limit_output_port = \
            self._DeclareVectorOutputPort(
                "force_limit", BasicVector(1), self._CalcForceLimitOutput)

        self._DeclarePeriodicPublish(update_period)
    def __init__(self, id_list, default_rgb=[255., 255., 255.]):
        """
        A system that takes in N point clouds of points Si in frame Ci, and N
        RigidTransforms from frame Ci to F, to put each point cloud in a common
        frame F. The system returns one point cloud combining all of the
        transformed point clouds. Each point cloud must have XYZs. RGBs are
        optional. If absent, those points will be the provided default color.

        @param id_list A list containing the string IDs of all of the point
            clouds. This is often the serial number of the camera they came
            from, such as "1" for a simulated camera or "805212060373" for a
            real camera.
        @param default_rgb A list of length 3 containing the RGB values to use
            in the absence of PointCloud.rgbs. Values should be between 0 and
            255. The default is white.
        """
        LeafSystem.__init__(self)

        self._point_cloud_ports = {}
        self._transform_ports = {}

        self._id_list = id_list

        self._default_rgb = np.array(default_rgb)

        output_fields = Fields(BaseField.kXYZs | BaseField.kRGBs)

        for id in self._id_list:
            self._point_cloud_ports[id] = self.DeclareAbstractInputPort(
                "point_cloud_CiSi_{}".format(id),
                AbstractValue.Make(PointCloud(fields=output_fields)))

            self._transform_ports[id] = self.DeclareAbstractInputPort(
                "X_FCi_{}".format(id),
                AbstractValue.Make(RigidTransform.Identity()))

        self.DeclareAbstractOutputPort("point_cloud_FS",
                                       lambda: AbstractValue.Make(
                                           PointCloud(fields=output_fields)),
                                       self.DoCalcOutput)
Example #36
0
    def __init__(self,
                 meshcat,
                 visible=Visible(),
                 min_range=MinRange(),
                 max_range=MaxRange(),
                 value=Value()):
        """
        Args:
            meshcat: A Meshcat instance.
            visible: An object with boolean elements for 'roll', 'pitch',
                     'yaw', 'x', 'y', 'z'; the intention is for this to be the
                     PoseSliders.Visible() namedtuple.  Defaults to all true.
            min_range, max_range, value: Objects with float values for 'roll',
                      'pitch', 'yaw', 'x', 'y', 'z'; the intention is for the
                      caller to use the PoseSliders.MinRange, MaxRange, and
                      Value namedtuples.  See those tuples for default values.
        """
        LeafSystem.__init__(self)
        port = self.DeclareAbstractOutputPort(
            "pose", lambda: AbstractValue.Make(RigidTransform()),
            self.DoCalcOutput)

        # The widgets themselves have undeclared state.  For now, we accept it,
        # and simply disable caching on the output port.
        # TODO(russt): consider implementing the more elaborate methods seen
        # in, e.g., LcmMessageSubscriber.
        port.disable_caching_by_default()

        self._meshcat = meshcat
        self._visible = visible
        self._value = list(value)

        for i in range(6):
            if visible[i]:
                meshcat.AddSlider(min=min_range[i],
                                  max=max_range[i],
                                  value=value[i],
                                  step=0.01,
                                  name=value._fields[i])
Example #37
0
    def __init__(self, plant):
        LeafSystem.__init__(self)
        self._plant = plant
        self._plant_context = plant.CreateDefaultContext()
        self._panda = plant.GetModelInstanceByName("panda")
        self._G = plant.GetBodyByName("panda_hand").body_frame()
        self._W = plant.world_frame()

        # Desired Rotational Velocity of gripper
        self.w_G_port = self.DeclareVectorInputPort("omega_WG", BasicVector(3))

        # Desired Translational Velocity of gripper
        self.v_G_port = self.DeclareVectorInputPort("v_WG", BasicVector(3))

        # Current configuration of the panda arm
        self.q_port = self.DeclareVectorInputPort("panda_position", BasicVector(9))

        # Output commanded velocity of arm
        self.DeclareVectorOutputPort("panda_velocity", BasicVector(7), self.CalcOutput)

        self.panda_start = plant.GetJointByName("panda_joint1").velocity_start()
        self.panda_end = plant.GetJointByName("panda_joint7").velocity_start()
Example #38
0
 def __init__(self):
     LeafSystem.__init__(self)
     self.called_publish = False
     self.called_feedthrough = False
     self.called_continuous = False
     self.called_discrete = False
     self.called_initialize = False
     self.called_per_step = False
     self.called_periodic = False
     # Ensure we have desired overloads.
     self._DeclarePeriodicPublish(1.0)
     self._DeclarePeriodicPublish(1.0, 0)
     self._DeclarePeriodicPublish(period_sec=1.0, offset_sec=0.)
     self._DeclarePeriodicDiscreteUpdate(
         period_sec=1.0, offset_sec=0.)
     self._DeclareInitializationEvent(
         event=PublishEvent(
             trigger_type=TriggerType.kInitialization,
             callback=self._on_initialize))
     self._DeclarePerStepEvent(
         event=PublishEvent(
             trigger_type=TriggerType.kPerStep,
             callback=self._on_per_step))
     self._DeclarePeriodicEvent(
         period_sec=1.0,
         offset_sec=0.0,
         event=PublishEvent(
             trigger_type=TriggerType.kPeriodic,
             callback=self._on_periodic))
     self._DeclareContinuousState(2)
     self._DeclareDiscreteState(1)
     # Ensure that we have inputs / outputs to call direct
     # feedthrough.
     self._DeclareInputPort(PortDataType.kVectorValued, 1)
     self._DeclareVectorInputPort(
         name="test_input", model_vector=BasicVector(1),
         random_type=None)
     self._DeclareVectorOutputPort(BasicVector(1), noop)
Example #39
0
 def __init__(self):
     LeafSystem.__init__(self)
     self.called_publish = False
     self.called_feedthrough = False
     self.called_continuous = False
     self.called_discrete = False
     self.called_initialize = False
     self.called_per_step = False
     self.called_periodic = False
     # Ensure we have desired overloads.
     self._DeclarePeriodicPublish(1.0)
     self._DeclarePeriodicPublish(1.0, 0)
     self._DeclarePeriodicPublish(period_sec=1.0, offset_sec=0.)
     self._DeclarePeriodicDiscreteUpdate(
         period_sec=1.0, offset_sec=0.)
     self._DeclareInitializationEvent(
         event=PublishEvent(
             trigger_type=TriggerType.kInitialization,
             callback=self._on_initialize))
     self._DeclarePerStepEvent(
         event=PublishEvent(
             trigger_type=TriggerType.kPerStep,
             callback=self._on_per_step))
     self._DeclarePeriodicEvent(
         period_sec=1.0,
         offset_sec=0.0,
         event=PublishEvent(
             trigger_type=TriggerType.kPeriodic,
             callback=self._on_periodic))
     self._DeclareContinuousState(2)
     self._DeclareDiscreteState(1)
     # Ensure that we have inputs / outputs to call direct
     # feedthrough.
     self._DeclareInputPort(PortDataType.kVectorValued, 1)
     self._DeclareVectorInputPort(
         name="test_input", model_vector=BasicVector(1),
         random_type=None)
     self._DeclareVectorOutputPort(BasicVector(1), noop)
Example #40
0
 def __init__(self):
     LeafSystem.__init__(self)
     self.called_publish = False
     self.called_feedthrough = False
     self.called_continuous = False
     self.called_discrete = False
     self.called_initialize = False
     # Ensure we have desired overloads.
     self._DeclarePeriodicPublish(0.1)
     self._DeclarePeriodicPublish(0.1, 0)
     self._DeclarePeriodicPublish(period_sec=0.1, offset_sec=0.)
     self._DeclarePeriodicDiscreteUpdate(
         period_sec=0.1, offset_sec=0.)
     self._DeclareInitializationEvent(
         event=PublishEvent(
             trigger_type=TriggerType.kInitialization,
             callback=self._on_initialize))
     self._DeclareContinuousState(2)
     self._DeclareDiscreteState(1)
     # Ensure that we have inputs / outputs to call direct
     # feedthrough.
     self._DeclareInputPort(PortDataType.kVectorValued, 1)
     self._DeclareVectorOutputPort(BasicVector(1), noop)
Example #41
0
    def __init__(self, arm_info, timestep=0.0005):
        LeafSystem.__init__(self)
        self.set_name("low_level_hand_controller")
        self.arm_info = arm_info
        self.previous_error = {}
        self.integral = {}
        self.desired_input_ports = {}
        self.estimated_input_ports = {}
        self.body_positions_input_port = self.DeclareAbstractInputPort(
            "body_positions", Value[List[RigidTransform]]())
        for arm in self.arm_info:
            self.desired_input_ports[arm] = self.DeclareVectorInputPort(
                f"{arm}_desired", BasicVector(6))
            self.previous_error[arm] = self.DeclareDiscreteState(6)
            self.integral[arm] = self.DeclareDiscreteState(6)

        self.DeclareAbstractOutputPort(
            f"spatial_forces_vector",
            lambda: Value[List[ExternallyAppliedSpatialForce]](),
            self.DoCalcAbstractOutput)
        self.kp = [100, 100, 100, 10000, 10000, 10000]
        self.ki = [0, 0, 0, 1, 1, 1]
        self.kd = [10, 10, 10, 10, 10, 10]
        self.timestep = timestep
Example #42
0
 def __init__(self):
     LeafSystem.__init__(self)
     self._DeclareContinuousState(1)
     self._DeclareDiscreteState(2)
Example #43
0
 def __init__(self, num_inputs, size):
     LeafSystem.__init__(self)
     for i in xrange(num_inputs):
         self._DeclareInputPort(PortDataType.kVectorValued, size)
     self._DeclareVectorOutputPort(BasicVector(size), self._calc_sum)
    def __init__(self):
        LeafSystem.__init__(self)
        self._DeclareVectorOutputPort("rpy_xyz", BasicVector(6),
                                      self._DoCalcOutput)

        # Note: This timing affects the keyboard teleop performance. A larger
        #       time step causes more lag in the response.
        self._DeclarePeriodicPublish(0.01, 0.0)

        self.window = tk.Tk()
        self.window.title("End-Effector TeleOp")

        self.roll = tk.Scale(self.window, from_=-2 * np.pi, to=2 * np.pi,
                             resolution=-1,
                             label="roll",
                             length=800,
                             orient=tk.HORIZONTAL)
        self.roll.pack()
        self.pitch = tk.Scale(self.window, from_=-2 * np.pi, to=2 * np.pi,
                              resolution=-1,
                              label="pitch",
                              length=800,
                              orient=tk.HORIZONTAL)
        self.pitch.pack()
        self.yaw = tk.Scale(self.window, from_=-2 * np.pi, to=2 * np.pi,
                            resolution=-1,
                            label="yaw",
                            length=800,
                            orient=tk.HORIZONTAL)
        self.yaw.pack()
        self.x = tk.Scale(self.window, from_=-0.6, to=0.8,
                          resolution=-1,
                          label="x",
                          length=800,
                          orient=tk.HORIZONTAL)
        self.x.pack()
        self.y = tk.Scale(self.window, from_=-0.8, to=0.3,
                          resolution=-1,
                          label="y",
                          length=800,
                          orient=tk.HORIZONTAL)
        self.y.pack()
        self.z = tk.Scale(self.window, from_=0, to=1.1,
                          resolution=-1,
                          label="z",
                          length=800,
                          orient=tk.HORIZONTAL)
        self.z.pack()

        # The key bindings below provide teleop functionality via the
        # keyboard, and are somewhat arbitrary (inspired by gaming
        # conventions). Note that in order for the keyboard bindings to
        # be active, the teleop slider window must be the active window.

        def update(scale, value):
            return lambda event: scale.set(scale.get() + value)

        # Delta displacements for motion via keyboard teleop.
        rotation_delta = 0.05  # rad
        position_delta = 0.01  # m

        # Linear motion key bindings.
        self.window.bind("<Up>", update(self.z, +position_delta))
        self.window.bind("<Down>", update(self.z, -position_delta))
        self.window.bind("<d>", update(self.y, +position_delta))
        self.window.bind("<a>", update(self.y, -position_delta))
        self.window.bind("<w>", update(self.x, +position_delta))
        self.window.bind("<s>", update(self.x, -position_delta))

        # Rotational motion key bindings.
        self.window.bind("<Control-d>", update(self.pitch, +rotation_delta))
        self.window.bind("<Control-a>", update(self.pitch, -rotation_delta))
        self.window.bind("<Control-w>", update(self.roll, +rotation_delta))
        self.window.bind("<Control-s>", update(self.roll, -rotation_delta))
        self.window.bind("<Control-Up>", update(self.yaw, +rotation_delta))
        self.window.bind("<Control-Down>", update(self.yaw, -rotation_delta))
Example #45
0
 def __init__(self, num_inputs, size):
     LeafSystem.__init__(self)
     for i in range(num_inputs):
         self.DeclareVectorInputPort(
             "input{}".format(i), BasicVector(size))
     self.DeclareVectorOutputPort("sum", BasicVector(size), self._calc_sum)
Example #46
0
 def __init__(self):
     LeafSystem.__init__(self)
     self.called_old_publish = False
     self.called_new_publish = False
Example #47
0
 def __init__(self):
     LeafSystem.__init__(self)
     self.called_publish = False
     # Check a non-overridable method
     with catch_drake_warnings(expected_count=1):
         self._DeclareVectorInputPort("x", BasicVector(1))
Example #48
0
    def __init__(self,
                 scene_graph,
                 draw_period=0.033333,
                 prefix="drake",
                 zmq_url="default",
                 open_browser=None):
        """
        Args:
            scene_graph: A SceneGraph object.
            draw_period: The rate at which this class publishes to the
                visualizer.
            prefix: Appears as the root of the tree structure in the meshcat
                data structure
            zmq_url: Optionally set a url to connect to the visualizer.
                Use zmp_url="default" to the value obtained by running a
                single `meshcat-server` in another terminal.
                Use zmp_url=None or zmq_url="new" to start a new server (as a
                child of this process); a new web browser will be opened (the
                url will also be printed to the console).
                Use e.g. zmq_url="tcp://127.0.0.1:6000" to specify a
                specific address.
            open_browser: Set to True to open the meshcat browser url in your
                default web browser.  The default value of None will open the
                browser iff a new meshcat server is created as a subprocess.
                Set to False to disable this.

        Note: This call will not return until it connects to the
              meshcat-server.
        """
        LeafSystem.__init__(self)

        self.set_name('meshcat_visualizer')
        self._DeclarePeriodicPublish(draw_period, 0.0)

        # Pose bundle (from SceneGraph) input port.
        self._DeclareAbstractInputPort("lcm_visualization",
                                       AbstractValue.Make(PoseBundle(0)))

        if zmq_url == "default":
            zmq_url = "tcp://127.0.0.1:6000"
        elif zmq_url == "new":
            zmq_url = None

        if zmq_url is None and open_browser is None:
            open_browser = True

        # Set up meshcat.
        self.prefix = prefix
        if zmq_url is not None:
            print("Connecting to meshcat-server at zmq_url=" + zmq_url + "...")
        self.vis = meshcat.Visualizer(zmq_url=zmq_url)
        print("Connected to meshcat-server.")
        self._scene_graph = scene_graph

        if open_browser:
            webbrowser.open(self.vis.url())

        def on_initialize(context, event):
            self.load()

        self._DeclareInitializationEvent(
            event=PublishEvent(
                trigger_type=TriggerType.kInitialization,
                callback=on_initialize))
Example #49
0
 def __init__(self):
     LeafSystem.__init__(self)
     self.DeclareAbstractInputPort(
         "header_t", AbstractValue.Make(header_t))
     self.DeclareVectorOutputPort(
         BasicVector(1), self._calc_output)
Example #50
0
 def __init__(self):
     LeafSystem.__init__(self)
     self._DeclareContinuousState(1)
     self._DeclareDiscreteState(2)
     self._DeclareAbstractState(model_value.Clone())
Example #51
0
 def __init__(self, num_inputs, size):
     LeafSystem.__init__(self)
     for i in range(num_inputs):
         self._DeclareInputPort(kUseDefaultName, PortDataType.kVectorValued,
                                size)
     self._DeclareVectorOutputPort("sum", BasicVector(size), self._calc_sum)