Exemple #1
0
    def test_signal_logger(self):
        # Log the output of a simple diagram containing a constant
        # source and an integrator.
        builder = DiagramBuilder()
        kValue = 2.4
        source = builder.AddSystem(ConstantVectorSource([kValue]))
        kSize = 1
        integrator = builder.AddSystem(Integrator(kSize))
        logger = builder.AddSystem(SignalLogger(kSize))
        builder.Connect(source.get_output_port(0),
                        integrator.get_input_port(0))
        builder.Connect(integrator.get_output_port(0),
                        logger.get_input_port(0))

        # Add a redundant logger via the helper method.
        logger2 = LogOutput(integrator.get_output_port(0), builder)

        diagram = builder.Build()
        simulator = Simulator(diagram)

        simulator.StepTo(1)

        t = logger.sample_times()
        x = logger.data()

        self.assertTrue(t.shape[0] > 2)
        self.assertTrue(t.shape[0] == x.shape[1])
        self.assertAlmostEqual(x[0, -1], t[-1]*kValue, places=2)
        np.testing.assert_array_equal(x, logger2.data())

        logger.reset()
    def test_signal_logger(self):
        # Log the output of a simple diagram containing a constant
        # source and an integrator.
        builder = DiagramBuilder()
        kValue = 2.4
        source = builder.AddSystem(ConstantVectorSource([kValue]))
        kSize = 1
        integrator = builder.AddSystem(Integrator(kSize))
        logger = builder.AddSystem(SignalLogger(kSize))
        builder.Connect(source.get_output_port(0),
                        integrator.get_input_port(0))
        builder.Connect(integrator.get_output_port(0),
                        logger.get_input_port(0))

        # Add a redundant logger via the helper method.
        logger2 = LogOutput(integrator.get_output_port(0), builder)

        diagram = builder.Build()
        simulator = Simulator(diagram)

        simulator.StepTo(1)

        t = logger.sample_times()
        x = logger.data()

        self.assertTrue(t.shape[0] > 2)
        self.assertTrue(t.shape[0] == x.shape[1])
        self.assertAlmostEqual(x[0, -1], t[-1] * kValue, places=2)
        np.testing.assert_array_equal(x, logger2.data())

        logger.reset()
Exemple #3
0
def simulate(*, initial_state, controller_params, t_final, tape_period):
    """Simulates an Acrobot + Spong controller from the given initial state and
    parameters until the given final time.  Returns the state sampled at the
    given tape_period.
    """
    builder = DiagramBuilder()
    plant = builder.AddSystem(AcrobotPlant())
    controller = builder.AddSystem(AcrobotSpongController())

    builder.Connect(plant.get_output_port(0), controller.get_input_port(0))
    builder.Connect(controller.get_output_port(0), plant.get_input_port(0))
    state_logger = LogOutput(plant.get_output_port(0), builder)
    state_logger.set_publish_period(tape_period)

    diagram = builder.Build()
    simulator = Simulator(diagram)
    context = simulator.get_mutable_context()
    plant_context = diagram.GetMutableSubsystemContext(plant, context)
    controller_context = diagram.GetMutableSubsystemContext(
        controller, context)

    plant_context.SetContinuousState(initial_state)
    controller_context.get_mutable_numeric_parameter(0).SetFromVector(
        controller_params)

    simulator.AdvanceTo(t_final)

    x_tape = state_logger.data()
    return x_tape
Exemple #4
0
    def test_signal_logger(self):
        # Log the output of a simple diagram containing a constant
        # source and an integrator.
        builder = DiagramBuilder()
        kValue = 2.4
        source = builder.AddSystem(ConstantVectorSource([kValue]))
        kSize = 1
        integrator = builder.AddSystem(Integrator(kSize))
        logger_per_step = builder.AddSystem(SignalLogger(kSize))
        builder.Connect(source.get_output_port(0),
                        integrator.get_input_port(0))
        builder.Connect(integrator.get_output_port(0),
                        logger_per_step.get_input_port(0))

        # Add a redundant logger via the helper method.
        logger_per_step_2 = LogOutput(integrator.get_output_port(0), builder)

        # Add a periodic logger
        logger_periodic = builder.AddSystem(SignalLogger(kSize))
        kPeriod = 0.1
        logger_periodic.set_publish_period(kPeriod)
        builder.Connect(integrator.get_output_port(0),
                        logger_periodic.get_input_port(0))

        diagram = builder.Build()
        simulator = Simulator(diagram)
        kTime = 1.
        simulator.AdvanceTo(kTime)

        # Verify outputs of the every-step logger
        t = logger_per_step.sample_times()
        x = logger_per_step.data()

        self.assertTrue(t.shape[0] > 2)
        self.assertTrue(t.shape[0] == x.shape[1])
        self.assertAlmostEqual(x[0, -1], t[-1] * kValue, places=2)
        np.testing.assert_array_equal(x, logger_per_step_2.data())

        # Verify outputs of the periodic logger
        t = logger_periodic.sample_times()
        x = logger_periodic.data()
        # Should log exactly once every kPeriod, up to and including kTime.
        self.assertTrue(t.shape[0] == np.floor(kTime / kPeriod) + 1.)

        logger_per_step.reset()

        # Verify that t and x retain their values after systems are deleted.
        t_copy = t.copy()
        x_copy = x.copy()
        del builder
        del integrator
        del logger_periodic
        del logger_per_step
        del logger_per_step_2
        del diagram
        del simulator
        del source
        gc.collect()
        self.assertTrue((t == t_copy).all())
        self.assertTrue((x == x_copy).all())
Exemple #5
0
    def test_signal_logger(self):
        # Log the output of a simple diagram containing a constant
        # source and an integrator.
        builder = DiagramBuilder()
        kValue = 2.4
        source = builder.AddSystem(ConstantVectorSource([kValue]))
        kSize = 1
        integrator = builder.AddSystem(Integrator(kSize))
        logger_per_step = builder.AddSystem(SignalLogger(kSize))
        builder.Connect(source.get_output_port(0),
                        integrator.get_input_port(0))
        builder.Connect(integrator.get_output_port(0),
                        logger_per_step.get_input_port(0))

        # Add a redundant logger via the helper method.
        logger_per_step_2 = LogOutput(integrator.get_output_port(0), builder)

        # Add a periodic logger
        logger_periodic = builder.AddSystem(SignalLogger(kSize))
        kPeriod = 0.1
        logger_periodic.set_publish_period(kPeriod)
        builder.Connect(integrator.get_output_port(0),
                        logger_periodic.get_input_port(0))

        diagram = builder.Build()
        simulator = Simulator(diagram)
        kTime = 1.
        simulator.StepTo(kTime)

        # Verify outputs of the every-step logger
        t = logger_per_step.sample_times()
        x = logger_per_step.data()

        self.assertTrue(t.shape[0] > 2)
        self.assertTrue(t.shape[0] == x.shape[1])
        self.assertAlmostEqual(x[0, -1], t[-1]*kValue, places=2)
        np.testing.assert_array_equal(x, logger_per_step_2.data())

        # Verify outputs of the periodic logger
        t = logger_periodic.sample_times()
        x = logger_periodic.data()
        # Should log exactly once every kPeriod, up to and including kTime.
        self.assertTrue(t.shape[0] == np.floor(kTime / kPeriod) + 1.)

        logger_per_step.reset()
Exemple #6
0
def simulate():
    # Animate the resulting policy.
    builder = DiagramBuilder()
    plant = builder.AddSystem(DoubleIntegrator())

    vi_policy = builder.AddSystem(policy)
    builder.Connect(plant.get_output_port(0), vi_policy.get_input_port(0))
    builder.Connect(vi_policy.get_output_port(0), plant.get_input_port(0))
    diagram = builder.Build()
    simulator = Simulator(diagram)

    logger = LogOutput(plant.get_output_port(0), builder)
    logger.set_name("logger")

    simulator.get_mutable_context().SetContinuousState(env.reset())

    simulator.AdvanceTo(10. if get_ipython() is not None else 5.)

    return logger
Exemple #7
0
def build_manipulation_station(station):
    from underactuated.meshcat_visualizer import MeshcatVisualizer
    from .manipulation_station.manipulation_station_plan_runner import ManipStationPlanRunner

    builder = DiagramBuilder()
    builder.AddSystem(station)

    # Add plan runner.
    plan_runner = ManipStationPlanRunner(station=station)

    builder.AddSystem(plan_runner)
    builder.Connect(plan_runner.hand_setpoint_output_port,
                    station.GetInputPort("wsg_position"))
    builder.Connect(plan_runner.gripper_force_limit_output_port,
                    station.GetInputPort("wsg_force_limit"))

    demux = builder.AddSystem(Demultiplexer(14, 7))
    builder.Connect(
        plan_runner.GetOutputPort("iiwa_position_and_torque_command"),
        demux.get_input_port(0))
    builder.Connect(demux.get_output_port(0),
                    station.GetInputPort("iiwa_position"))
    builder.Connect(demux.get_output_port(1),
                    station.GetInputPort("iiwa_feedforward_torque"))
    builder.Connect(station.GetOutputPort("iiwa_position_measured"),
                    plan_runner.iiwa_position_input_port)
    builder.Connect(station.GetOutputPort("iiwa_velocity_estimated"),
                    plan_runner.iiwa_velocity_input_port)

    # Add meshcat visualizer
    plant = station.get_mutable_multibody_plant()
    scene_graph = station.get_mutable_scene_graph()
    viz = MeshcatVisualizer(scene_graph,
                            is_drawing_contact_force=True,
                            plant=plant)
    builder.AddSystem(viz)
    builder.Connect(station.GetOutputPort("pose_bundle"),
                    viz.GetInputPort("lcm_visualization"))
    builder.Connect(station.GetOutputPort("contact_results"),
                    viz.GetInputPort("contact_results"))

    # Add logger
    iiwa_position_command_log = LogOutput(demux.get_output_port(0), builder)
    iiwa_position_command_log._DeclarePeriodicPublish(0.005)

    iiwa_external_torque_log = LogOutput(
        station.GetOutputPort("iiwa_torque_external"), builder)
    iiwa_external_torque_log._DeclarePeriodicPublish(0.005)

    iiwa_position_measured_log = LogOutput(
        station.GetOutputPort("iiwa_position_measured"), builder)
    iiwa_position_measured_log._DeclarePeriodicPublish(0.005)

    wsg_state_log = LogOutput(station.GetOutputPort("wsg_state_measured"),
                              builder)
    wsg_state_log._DeclarePeriodicPublish(0.1)

    wsg_command_log = LogOutput(plan_runner.hand_setpoint_output_port, builder)
    wsg_command_log._DeclarePeriodicPublish(0.1)

    # build diagram
    diagram = builder.Build()
    viz.load()
    #time.sleep(2.0)
    #RenderSystemWithGraphviz(diagram)
    return diagram, plan_runner
Exemple #8
0
    def test_lcm_driven_loop(self):
        """Duplicates the test logic in `lcm_driven_loop_test.cc`."""
        lcm_url = "udpm://239.255.76.67:7669"
        t_start = 3.
        t_end = 10.

        def publish_loop():
            # Publishes a set of messages for the driven loop. This should be
            # run from a separate process.
            # N.B. Because of this, care should be taken not to share C++
            # objects between process boundaries.
            t = t_start
            while t <= t_end:
                message = header_t()
                message.utime = int(1e6 * t)
                lcm.Publish("TEST_LOOP", message.encode())
                time.sleep(0.1)
                t += 1

        class DummySys(LeafSystem):
            # Converts message to time in seconds.
            def __init__(self):
                LeafSystem.__init__(self)
                self.DeclareAbstractInputPort(
                    "header_t", AbstractValue.Make(header_t))
                self.DeclareVectorOutputPort(
                    BasicVector(1), self._calc_output)

            def _calc_output(self, context, output):
                message = self.EvalAbstractInput(context, 0).get_value()
                y = output.get_mutable_value()
                y[:] = message.utime / 1e6

        # Construct diagram for LcmDrivenLoop.
        lcm = DrakeLcm(lcm_url)
        utime = mut.PyUtimeMessageToSeconds(header_t)
        sub = mut.LcmSubscriberSystem.Make("TEST_LOOP", header_t, lcm)
        builder = DiagramBuilder()
        builder.AddSystem(sub)
        dummy = builder.AddSystem(DummySys())
        builder.Connect(sub.get_output_port(0), dummy.get_input_port(0))
        logger = LogOutput(dummy.get_output_port(0), builder)
        logger.set_forced_publish_only()
        diagram = builder.Build()
        dut = mut.LcmDrivenLoop(diagram, sub, None, lcm, utime)
        dut.set_publish_on_every_received_message(True)

        # N.B. Use `multiprocessing` instead of `threading` so that we may
        # avoid issues with GIL deadlocks.
        publish_proc = Process(target=publish_loop)
        publish_proc.start()
        # Initialize to first message.
        first_msg = dut.WaitForMessage()
        dut.get_mutable_context().SetTime(utime.GetTimeInSeconds(first_msg))
        # Run to desired amount. (Anything more will cause interpreter to
        # "freeze".)
        dut.RunToSecondsAssumingInitialized(t_end)
        publish_proc.join()

        # Check expected values.
        log_t_expected = np.array([4, 5, 6, 7, 8, 9])
        log_t = logger.sample_times()
        self.assertTrue(np.allclose(log_t_expected, log_t))
        log_y = logger.data()
        self.assertTrue(np.allclose(log_t_expected, log_y))
Exemple #9
0
def connect_plan_runner(builder, station, plan):
    from plan_runner.manipulation_station_plan_runner import ManipStationPlanRunner
    plan_list, gripper_setpoints = plan

    # Add plan runner.
    plan_runner = ManipStationPlanRunner(station, plan_list, gripper_setpoints)

    builder.AddSystem(plan_runner)
    builder.Connect(plan_runner.hand_setpoint_output_port,
                    station.GetInputPort("wsg_position"))
    builder.Connect(plan_runner.gripper_force_limit_output_port,
                    station.GetInputPort("wsg_force_limit"))

    demux = builder.AddSystem(Demultiplexer(14, 7))
    builder.Connect(
        plan_runner.GetOutputPort("iiwa_position_and_torque_command"),
        demux.get_input_port(0))
    builder.Connect(demux.get_output_port(0),
                    station.GetInputPort("iiwa_position"))
    builder.Connect(demux.get_output_port(1),
                    station.GetInputPort("iiwa_feedforward_torque"))
    builder.Connect(station.GetOutputPort("iiwa_position_measured"),
                    plan_runner.iiwa_position_input_port)
    builder.Connect(station.GetOutputPort("iiwa_velocity_estimated"),
                    plan_runner.iiwa_velocity_input_port)

    # Add logger
    iiwa_position_command_log = LogOutput(demux.get_output_port(0), builder)
    iiwa_position_command_log._DeclarePeriodicPublish(0.005)

    iiwa_external_torque_log = LogOutput(
        station.GetOutputPort("iiwa_torque_external"), builder)
    iiwa_external_torque_log._DeclarePeriodicPublish(0.005)

    iiwa_position_measured_log = LogOutput(
        station.GetOutputPort("iiwa_position_measured"), builder)
    iiwa_position_measured_log._DeclarePeriodicPublish(0.005)

    wsg_state_log = LogOutput(station.GetOutputPort("wsg_state_measured"),
                              builder)
    wsg_state_log._DeclarePeriodicPublish(0.1)

    wsg_command_log = LogOutput(plan_runner.hand_setpoint_output_port, builder)
    wsg_command_log._DeclarePeriodicPublish(0.1)

    return plan_runner
Exemple #10
0
# Parameters from Geyer05, Figure 2.4
# Note: Geyer uses angle of attack = 90 - touchdown_angle
touchdown_angle = np.deg2rad(30)
Etilde = 1.61

s = SLIPState(np.zeros(8))
s.z = 0.9
s.theta = touchdown_angle
s.r = 1
s.xdot = plant.apex_velocity_from_dimensionless_system_energy(Etilde, s.z)

viz = builder.AddSystem(SLIPVisualizer())
builder.Connect(plant.get_output_port(0), viz.get_input_port(0))

log = LogOutput(plant.get_output_port(0), builder)

command = builder.AddSystem(ConstantVectorSource([touchdown_angle]))
builder.Connect(command.get_output_port(0), plant.get_input_port(0))

diagram = builder.Build()
simulator = Simulator(diagram)
context = simulator.get_mutable_context()
context.SetAccuracy(1e-10)

context.get_mutable_continuous_state_vector().SetFromVector(s[:])

simulator.set_target_realtime_rate(1.0)
simulator.AdvanceTo(0.6)

print("apex: " + str(plant.last_apex))
Exemple #11
0
    def RunSimulation(self,
                      plans_list,
                      gripper_setpoint_list,
                      extra_time=0,
                      real_time_rate=1.0,
                      q0_kuka=np.zeros(7)):
        '''
        Constructs a Diagram that sends commands to ManipulationStation.
        :param plans_list:
        :param gripper_setpoint_list:
        :param extra_time:
        :param real_time_rate:
        :param q0_kuka:
        :return:
        '''
        builder = DiagramBuilder()
        builder.AddSystem(self.station)

        # Add plan runner.
        plan_runner = ManipStationPlanRunner(
            station=self.station,
            kuka_plans=plans_list,
            gripper_setpoint_list=gripper_setpoint_list)

        builder.AddSystem(plan_runner)
        builder.Connect(plan_runner.hand_setpoint_output_port,
                        self.station.GetInputPort("wsg_position"))
        builder.Connect(plan_runner.gripper_force_limit_output_port,
                        self.station.GetInputPort("wsg_force_limit"))

        demux = builder.AddSystem(Demultiplexer(14, 7))
        builder.Connect(
            plan_runner.GetOutputPort("iiwa_position_and_torque_command"),
            demux.get_input_port(0))
        builder.Connect(demux.get_output_port(0),
                        self.station.GetInputPort("iiwa_position"))
        builder.Connect(demux.get_output_port(1),
                        self.station.GetInputPort("iiwa_feedforward_torque"))
        builder.Connect(self.station.GetOutputPort("iiwa_position_measured"),
                        plan_runner.iiwa_position_input_port)
        builder.Connect(self.station.GetOutputPort("iiwa_velocity_estimated"),
                        plan_runner.iiwa_velocity_input_port)

        # Add meshcat visualizer
        scene_graph = self.station.get_mutable_scene_graph()
        viz = MeshcatVisualizer(scene_graph,
                                is_drawing_contact_force=True,
                                plant=self.plant)
        self.viz = viz
        builder.AddSystem(viz)
        builder.Connect(self.station.GetOutputPort("pose_bundle"),
                        viz.GetInputPort("lcm_visualization"))
        builder.Connect(self.station.GetOutputPort("contact_results"),
                        viz.GetInputPort("contact_results"))

        # Add logger
        iiwa_position_command_log = LogOutput(demux.get_output_port(0),
                                              builder)
        iiwa_position_command_log._DeclarePeriodicPublish(0.005)

        iiwa_external_torque_log = LogOutput(
            self.station.GetOutputPort("iiwa_torque_external"), builder)
        iiwa_external_torque_log._DeclarePeriodicPublish(0.005)

        iiwa_position_measured_log = LogOutput(
            self.station.GetOutputPort("iiwa_position_measured"), builder)
        iiwa_position_measured_log._DeclarePeriodicPublish(0.005)

        wsg_state_log = LogOutput(
            self.station.GetOutputPort("wsg_state_measured"), builder)
        wsg_state_log._DeclarePeriodicPublish(0.1)

        wsg_command_log = LogOutput(plan_runner.hand_setpoint_output_port,
                                    builder)
        wsg_command_log._DeclarePeriodicPublish(0.1)

        # build diagram
        diagram = builder.Build()
        viz.load()
        time.sleep(2.0)
        RenderSystemWithGraphviz(diagram)

        # construct simulator
        simulator = Simulator(diagram)

        context = diagram.GetMutableSubsystemContext(
            self.station, simulator.get_mutable_context())

        # set initial state of the robot
        self.station.SetIiwaPosition(q0_kuka, context)
        self.station.SetIiwaVelocity(np.zeros(7), context)
        self.station.SetWsgPosition(0.05, context)
        self.station.SetWsgVelocity(0, context)

        # set initial hinge angles of the cupboard.
        # setting hinge angle to exactly 0 or 90 degrees will result in intermittent contact
        # with small contact forces between the door and the cupboard body.
        left_hinge_joint = self.plant.GetJointByName("left_door_hinge")
        left_hinge_joint.set_angle(
            context=self.station.GetMutableSubsystemContext(
                self.plant, context),
            angle=-0.001)

        right_hinge_joint = self.plant.GetJointByName("right_door_hinge")
        right_hinge_joint.set_angle(
            context=self.station.GetMutableSubsystemContext(
                self.plant, context),
            angle=0.001)

        # set initial pose of the object
        self.plant.tree().SetFreeBodyPoseOrThrow(
            self.plant.GetBodyByName(self.object_base_link_name, self.object),
            self.X_WObject,
            self.station.GetMutableSubsystemContext(self.plant, context))

        simulator.set_publish_every_time_step(False)
        simulator.set_target_realtime_rate(real_time_rate)
        simulator.Initialize()
        sim_duration = 0.
        for plan in plans_list:
            sim_duration += plan.get_duration() * 1.1
        sim_duration += extra_time
        print "simulation duration", sim_duration
        simulator.StepTo(sim_duration)

        return iiwa_position_command_log, \
               iiwa_position_measured_log, \
               iiwa_external_torque_log, \
               wsg_state_log, \
               wsg_command_log
Exemple #12
0
builder.Connect(hand_comms.get_output_port(), arm_hand_mux.get_input_port(1))

# builder.Connect(s_interp.get_output_port(), arm_hand_mux.get_input_port(0))
# builder.Connect(h_interp.get_output_port(), arm_hand_mux.get_input_port(1))

# arm_hand_mux.get_input_port(1).FixValue(np.array([0.0, 0.0, 0.0, 0.0]))
# Connect result of integrator to a derivative getter
s_interp = builder.AddSystem(StateInterpolatorWithDiscreteDerivative(9, time_step, True))
s_interp.set_name("s_interp")
builder.Connect(arm_hand_mux.get_output_port(), s_interp.get_input_port())
builder.Connect(s_interp.get_output_port(), inv_d_controller.GetInputPort("desired_state"))

# Connect inverse dynamics control into desired actuation of panda
builder.Connect(inv_d_controller.get_output_port_control(), plant.get_actuation_input_port())

logger = LogOutput(diff_inv_controller.get_output_port(), builder)

diagram = builder.Build()
diagram.set_name("pick_and_place")

simulator = Simulator(diagram)
sim_context = simulator.get_mutable_context()

plant_context = plant.GetMyMutableContextFromRoot(sim_context)
plant.SetPositions(plant_context, panda, desired_initial_state)
plant.SetFreeBodyPose(plant_context, plant.GetBodyByName("base_link", brick), X_O["initial"])

# integrator.GetMyContextFromRoot(simulator.get_mutable_context()) \
#     .get_mutable_continuous_state_vector() \
#     .SetFromVector(plant.GetPositions(plant_context, panda)[:7])
diff_inv_controller.SetPositions(
    def __init__(self):
        #import pdb; pdb.set_trace()
        # Create a block diagram containing our system.
        builder = DiagramBuilder()

        # add the two decoupled plants (x(s)=u/s^2;  y(s)=u/s^2)
        plant_x = builder.AddSystem(DoubleIntegrator())
        plant_y = builder.AddSystem(DoubleIntegrator())
        plant_x.set_name("double_integrator_x")
        plant_y.set_name("double_integrator_y")

        # add the controller, lead compensator for now just to stablize it
        controller_x = builder.AddSystem(
            Controller(tau_num=2., tau_den=.2, k=1.))
        controller_y = builder.AddSystem(
            Controller(tau_num=2., tau_den=.2, k=1.))
        controller_x.set_name("controller_x")
        controller_y.set_name("controller_y")

        # the perception's "Beam" model with the four sources of noise
        x_meas_fb = builder.AddSystem(Adder(num_inputs=4, size=1))
        x_meas_fb.set_name("x_fb")
        y_meas_fb = builder.AddSystem(Adder(num_inputs=4, size=1))
        y_meas_fb.set_name("y_fb")
        y_perception = builder.AddSystem(Adder(num_inputs=2, size=1))
        y_perception.set_name("range_measurment_y")
        neg_y_meas = builder.AddSystem(Gain(k=-1., size=1))
        neg_y_meas.set_name("neg_y_meas")
        wall_position = builder.AddSystem(ConstantVectorSource([Y_wall]))

        p_hit   = builder.AddSystem(RandomSource(distribution=RandomDistribution.kGaussian, num_outputs=2,\
                   sampling_interval_sec=0.01))
        p_hit.set_name("GaussionNoise(0,1)")
        p_short = builder.AddSystem(RandomSource(distribution=RandomDistribution.kExponential, num_outputs=2,\
                   sampling_interval_sec=0.01))
        p_short.set_name("ExponentialNoise(1)")
        #p_max   = builder.AddSystem(RandomSource(distribution=RandomDistribution.kUniform, num_outputs=1,\
        #										 sampling_interval_sec=0.01))
        p_rand  = builder.AddSystem(RandomSource(distribution=RandomDistribution.kUniform, num_outputs=2,\
                   sampling_interval_sec=0.01))
        p_rand.set_name("UniformNoise(0,1)")
        #import pdb; pdb.set_trace()
        p_hit_Dx = builder.AddSystem(Demultiplexer(size=2))
        p_hit_Dx.set_name('Dmux1')
        p_short_Dx = builder.AddSystem(Demultiplexer(size=2))
        p_short_Dx.set_name('Dmux2')
        p_rand_Dx = builder.AddSystem(Demultiplexer(size=2))
        p_rand_Dx.set_name('Dmux3')
        normgain_x = builder.AddSystem(Gain(k=normal_coeff, size=1))
        normgain_x.set_name("Sigma_x")
        normgain_y = builder.AddSystem(Gain(k=normal_coeff, size=1))
        normgain_y.set_name("Sigma_y")
        expgain_x = builder.AddSystem(Gain(k=exp_coeff, size=1))
        expgain_x.set_name("Exp_x")
        expgain_y = builder.AddSystem(Gain(k=exp_coeff, size=1))
        expgain_y.set_name("Exp_y")
        randgain_x = builder.AddSystem(Gain(k=rand_coeff, size=1))
        randgain_x.set_name("Rand_x")
        randgain_y = builder.AddSystem(Gain(k=rand_coeff, size=1))
        randgain_y.set_name("Rand_y")
        #maxgain_x = builder.AddSystem(Adder(num_inputs=2, size=1))
        #maxgain_x.set_name("Max_x")
        #maxgain_y = builder.AddSystem(Adder(num_inputs=2, size=1))
        #maxgain_y.set_name("Max_y")

        # the summation to get the error (closing the loop)
        summ_x = builder.AddSystem(Adder(num_inputs=2, size=1))
        summ_y = builder.AddSystem(Adder(num_inputs=2, size=1))
        summ_x.set_name("summation_x")
        summ_y.set_name("summation_y")
        neg_x = builder.AddSystem(Gain(k=-1., size=1))
        neg_y = builder.AddSystem(Gain(k=-1., size=1))
        neg_uy = builder.AddSystem(Gain(k=-1., size=1))
        neg_x.set_name("neg_x")
        neg_y.set_name("neg_y")
        neg_uy.set_name("neg_uy")

        # wire up all the blocks (summation to the controller to the plant ...)
        builder.Connect(summ_x.get_output_port(0),
                        controller_x.get_input_port(0))  # e_x
        builder.Connect(summ_y.get_output_port(0),
                        controller_y.get_input_port(0))  # e_y

        builder.Connect(controller_x.get_output_port(0),
                        plant_x.get_input_port(0))  # u_x
        builder.Connect(
            controller_y.get_output_port(0),
            neg_uy.get_input_port(0))  # u_y (to deal with directions)
        builder.Connect(neg_uy.get_output_port(0),
                        plant_y.get_input_port(0))  # u_y

        builder.Connect(
            plant_x.get_output_port(0),
            x_meas_fb.get_input_port(0))  # perception, nominal state meas
        builder.Connect(wall_position.get_output_port(0),
                        y_perception.get_input_port(0))  # perception
        builder.Connect(plant_y.get_output_port(0),
                        neg_y_meas.get_input_port(0))  # perception
        builder.Connect(neg_y_meas.get_output_port(0),
                        y_perception.get_input_port(1))  # perception, z meas
        builder.Connect(
            y_perception.get_output_port(0),
            y_meas_fb.get_input_port(0))  # perception, nominal state meas

        builder.Connect(p_hit.get_output_port(0),
                        p_hit_Dx.get_input_port(0))  # demux the noise
        builder.Connect(p_hit_Dx.get_output_port(0),
                        normgain_x.get_input_port(0))  # normalize Normal dist
        builder.Connect(normgain_x.get_output_port(0),
                        x_meas_fb.get_input_port(1))  # Normal dist
        builder.Connect(p_hit_Dx.get_output_port(1),
                        normgain_y.get_input_port(0))  # normalize Normal dist
        builder.Connect(normgain_y.get_output_port(0),
                        y_meas_fb.get_input_port(1))  # Normal dist

        builder.Connect(p_short.get_output_port(0),
                        p_short_Dx.get_input_port(0))  # demux the noise
        builder.Connect(p_short_Dx.get_output_port(0),
                        expgain_x.get_input_port(0))  # normalize Exp dist
        builder.Connect(expgain_x.get_output_port(0),
                        x_meas_fb.get_input_port(2))  # Exp dist
        builder.Connect(p_short_Dx.get_output_port(1),
                        expgain_y.get_input_port(0))  # normalize Exp dist
        builder.Connect(expgain_y.get_output_port(0),
                        y_meas_fb.get_input_port(2))  # Exp dist

        #builder.Connect(p_max.get_output_port(0), x_meas_fb.get_input_port(3)) # Uniform dist
        #builder.Connect(p_max.get_output_port(0), y_meas_fb.get_input_port(3)) # Uniform dist

        builder.Connect(p_rand.get_output_port(0),
                        p_rand_Dx.get_input_port(0))  # normalize Uniform dist
        builder.Connect(p_rand_Dx.get_output_port(0),
                        randgain_x.get_input_port(0))  # normalize Uniform dist
        builder.Connect(randgain_x.get_output_port(0),
                        x_meas_fb.get_input_port(3))  # Uniform dist
        builder.Connect(p_rand_Dx.get_output_port(1),
                        randgain_y.get_input_port(0))  # normalize Uniform dist
        builder.Connect(randgain_y.get_output_port(0),
                        y_meas_fb.get_input_port(3))  # Uniform dist

        builder.Connect(x_meas_fb.get_output_port(0),
                        neg_x.get_input_port(0))  # -x
        builder.Connect(y_meas_fb.get_output_port(0),
                        neg_y.get_input_port(0))  # -y
        builder.Connect(neg_x.get_output_port(0),
                        summ_x.get_input_port(1))  # r-x
        builder.Connect(neg_y.get_output_port(0),
                        summ_y.get_input_port(1))  # r-y

        # Make the desired_state input of the controller, an input to the diagram.
        builder.ExportInput(summ_x.get_input_port(0))
        builder.ExportInput(summ_y.get_input_port(0))

        # get telemetry
        logger_x = LogOutput(plant_x.get_output_port(0), builder)
        logger_noise_x = LogOutput(x_meas_fb.get_output_port(0), builder)
        logger_y = LogOutput(plant_y.get_output_port(0), builder)
        logger_noise_y = LogOutput(y_meas_fb.get_output_port(0), builder)
        logger_x.set_name("logger_x_state")
        logger_y.set_name("logger_y_state")
        logger_noise_x.set_name("x_state_meas")
        logger_noise_y.set_name("y_meas")

        # compile the system
        diagram = builder.Build()
        diagram.set_name("diagram")

        # Create the simulator, and simulate for 10 seconds.
        simulator = Simulator(diagram)
        context = simulator.get_mutable_context()

        # First we extract the subsystem context for the plant
        plant_context_x = diagram.GetMutableSubsystemContext(plant_x, context)
        plant_context_y = diagram.GetMutableSubsystemContext(plant_y, context)
        # Then we can set the pendulum state, which is (x, y).
        z0 = X_0
        plant_context_x.get_mutable_continuous_state_vector().SetFromVector(z0)
        z0 = Y_0
        plant_context_y.get_mutable_continuous_state_vector().SetFromVector(z0)

        # The diagram has a single input port (port index 0), which is the desired_state.
        context.FixInputPort(
            0,
            [X_d])  # here we assume no perception, closing feedback on state X
        context.FixInputPort(
            1, [Z_d])  #Z_y, keep 3m away, basically we want to be at Y=0

        # run the simulation
        simulator.AdvanceTo(10)
        t = logger_x.sample_times()
        #import pdb; pdb.set_trace()
        # Plot the results.
        plt.figure()
        plot_system_graphviz(diagram, max_depth=2)

        plt.figure()
        plt.plot(t, logger_noise_x.data().transpose(), label='x_state_meas')
        plt.plot(t, logger_noise_y.data().transpose(), label='y_meas (z(y))')
        plt.plot(t, logger_x.data().transpose(), label='x_state')
        plt.plot(t, logger_y.data().transpose(), label='y_state')
        plt.xlabel('t')
        plt.ylabel('x(t),y(t)')
        plt.legend()
        plt.show(block=True)
Exemple #14
0
    # y = x
    def CopyStateOut(self, context, output):
        x = context.get_continuous_state_vector().CopyToVector()
        output.SetFromVector(x)


continuous_system = SimpleContinuousTimeSystem()

# Simulation

# Create a simple block diagram containig our system
builder = DiagramBuilder()
# system = builder.AddSystem(SimpleContinuousTimeSystem())
system = builder.AddSystem(continuous_vector_system)
logger = LogOutput(system.get_output_port(0), builder)
diagram = builder.Build()

# Set the initial conditions, x(0)
context = diagram.CreateDefaultContext()
context.SetContinuousState([0.9])

# Create the simulator, and simulate for 10 seconds
simulator = Simulator(diagram, context)
simulator.AdvanceTo(10)

# Plot the results
plt.figure()
plt.plot(logger.sample_times(), logger.data().transpose())
plt.xlabel('t')
plt.ylabel('y(t)')
Exemple #15
0
    def RunRealRobot(self, plans_list, gripper_setpoint_list):
        '''
        Constructs a Diagram that sends commands to ManipulationStationHardwareInterface.
        :param plans_list:
        :param gripper_setpoint_list:
        :param extra_time:
        :param real_time_rate:
        :param q0_kuka:
        :return:
        '''
        builder = DiagramBuilder()
        camera_ids = ["805212060544"]
        station_hardware = ManipulationStationHardwareInterface(camera_ids)
        station_hardware.Connect(wait_for_cameras=False)
        builder.AddSystem(station_hardware)

        # Add plan runner
        # Add plan runner.
        plan_runner = ManipStationPlanRunner(
            station=self.station,
            kuka_plans=plans_list,
            gripper_setpoint_list=gripper_setpoint_list)

        builder.AddSystem(plan_runner)
        builder.Connect(plan_runner.hand_setpoint_output_port,
                        station_hardware.GetInputPort("wsg_position"))
        builder.Connect(plan_runner.gripper_force_limit_output_port,
                        station_hardware.GetInputPort("wsg_force_limit"))

        demux = builder.AddSystem(Demultiplexer(14, 7))
        builder.Connect(
            plan_runner.GetOutputPort("iiwa_position_and_torque_command"),
            demux.get_input_port(0))
        builder.Connect(demux.get_output_port(0),
                        station_hardware.GetInputPort("iiwa_position"))
        builder.Connect(
            demux.get_output_port(1),
            station_hardware.GetInputPort("iiwa_feedforward_torque"))
        builder.Connect(
            station_hardware.GetOutputPort("iiwa_position_measured"),
            plan_runner.iiwa_position_input_port)
        builder.Connect(
            station_hardware.GetOutputPort("iiwa_velocity_estimated"),
            plan_runner.iiwa_velocity_input_port)

        # Add logger
        iiwa_position_measured_log = LogOutput(
            station_hardware.GetOutputPort("iiwa_position_measured"), builder)
        iiwa_position_measured_log._DeclarePeriodicPublish(0.005)

        iiwa_external_torque_log = LogOutput(
            station_hardware.GetOutputPort("iiwa_torque_external"), builder)
        iiwa_external_torque_log._DeclarePeriodicPublish(0.005)

        wsg_state_log = LogOutput(
            station_hardware.GetOutputPort("wsg_state_measured"), builder)
        wsg_state_log._DecalrePeriodicPublish(0.1)

        wsg_command_log = LogOutput(plan_runner.hand_setpoint_output_port,
                                    builder)
        wsg_command_log._DeclarePeriodicPublish(0.1)

        # build diagram
        diagram = builder.Build()
        RenderSystemWithGraphviz(diagram)

        # construct simulator
        simulator = Simulator(diagram)

        simulator.set_target_realtime_rate(1.0)
        simulator.set_publish_every_time_step(False)

        sim_duration = 0.
        for plan in plans_list:
            sim_duration += plan.get_duration() * 1.1

        print "sending trajectories in 2 seconds..."
        time.sleep(1.0)
        print "sending trajectories in 1 second..."
        time.sleep(1.0)
        print "sending trajectories now!"
        simulator.StepTo(sim_duration)

        return iiwa_position_measured_log, iiwa_external_torque_log, wsg_state_log, wsg_command_log
Exemple #16
0
    def test_lcm_driven_loop(self):
        """Duplicates the test logic in `lcm_driven_loop_test.cc`."""
        lcm_url = "udpm://239.255.76.67:7669"
        t_start = 3.
        t_end = 10.

        def publish_loop():
            # Publishes a set of messages for the driven loop. This should be
            # run from a separate process.
            # N.B. Because of this, care should be taken not to share C++
            # objects between process boundaries.
            t = t_start
            while t <= t_end:
                message = header_t()
                message.utime = int(1e6 * t)
                lcm.Publish("TEST_LOOP", message.encode())
                time.sleep(0.1)
                t += 1

        class DummySys(LeafSystem):
            # Converts message to time in seconds.
            def __init__(self):
                LeafSystem.__init__(self)
                self.DeclareAbstractInputPort("header_t",
                                              AbstractValue.Make(header_t))
                self.DeclareVectorOutputPort(BasicVector(1), self._calc_output)

            def _calc_output(self, context, output):
                message = self.EvalAbstractInput(context, 0).get_value()
                y = output.get_mutable_value()
                y[:] = message.utime / 1e6

        # Construct diagram for LcmDrivenLoop.
        lcm = DrakeLcm(lcm_url)
        utime = mut.PyUtimeMessageToSeconds(header_t)
        sub = mut.LcmSubscriberSystem.Make("TEST_LOOP", header_t, lcm)
        builder = DiagramBuilder()
        builder.AddSystem(sub)
        dummy = builder.AddSystem(DummySys())
        builder.Connect(sub.get_output_port(0), dummy.get_input_port(0))
        logger = LogOutput(dummy.get_output_port(0), builder)
        logger.set_forced_publish_only()
        diagram = builder.Build()
        dut = mut.LcmDrivenLoop(diagram, sub, None, lcm, utime)
        dut.set_publish_on_every_received_message(True)

        # N.B. Use `multiprocessing` instead of `threading` so that we may
        # avoid issues with GIL deadlocks.
        publish_proc = Process(target=publish_loop)
        publish_proc.start()
        # Initialize to first message.
        first_msg = dut.WaitForMessage()
        dut.get_mutable_context().SetTime(utime.GetTimeInSeconds(first_msg))
        # Run to desired amount. (Anything more will cause interpreter to
        # "freeze".)
        dut.RunToSecondsAssumingInitialized(t_end)
        publish_proc.join()

        # Check expected values.
        log_t_expected = np.array([4, 5, 6, 7, 8, 9])
        log_t = logger.sample_times()
        self.assertTrue(np.allclose(log_t_expected, log_t))
        log_y = logger.data()
        self.assertTrue(np.allclose(log_t_expected, log_y))
Exemple #17
0
def simulate(builder, plant, position, regulator, x0, duration):
    """"Actually run simulation and return data."""
    # Set up plant and position
    builder.Connect(plant.get_output_port(0), position.get_input_port(0))
    controller = builder.AddSystem(regulator)
    builder.Connect(controller.get_output_port(0), plant.get_input_port(0))
    builder.Connect(plant.get_output_port(0), controller.get_input_port(0))

    # Set up logging
    plant_logger = LogOutput(plant.get_output_port(0), builder)
    position_logger = LogOutput(position.get_output_port(0), builder)
    diagram = builder.Build()
    context = diagram.CreateDefaultContext()
    context.SetContinuousState(x0)

    # Create the simulator and simulate
    simulator = Simulator(diagram, context)
    simulator.Initialize()
    print("Simulating...")
    simulator.AdvanceTo(duration)
    print("Simulation complete!")

    # Return data
    assert len(plant_logger.sample_times()) == len(
        position_logger.sample_times())
    for t1, t2 in zip(plant_logger.sample_times(),
                      position_logger.sample_times()):
        assert t1 == t2

    t = plant_logger.sample_times()
    r_data = plant_logger.data()[0, :]
    r_dot_data = plant_logger.data()[1, :]
    theta_dot_data = plant_logger.data()[2, :]
    phi_data = plant_logger.data()[3, :]
    phi_dot_data = plant_logger.data()[4, :]
    theta_data = position_logger.data()[0, :]

    return t, r_data, r_dot_data, theta_dot_data, phi_data, phi_dot_data, theta_data
    def RunSimulation(self, q0_iiwa, door_angles, plan_list,
                      gripper_setpoint_list,
                      extra_time=0, real_time_rate=1.0,
                      is_visualizing=True,
                      gripper_setpoint_initial=0.025):
        """
        Constructs a Diagram that sends commands to ManipulationStation.
        @param plan_list: A list of Plans to be executed.
        @param gripper_setpoint_list: A list of gripper setpoints. Each setpoint corresponds to a Plan.
        @param extra_time: the amount of time for which commands are sent,
            in addition to the sum of the durations of all plans.
        @param real_time_rate: 1.0 means realtime; 0 means as fast as possible.
        @param q0_iiwa: initial configuration of the robot.
        @param is_visualizing: if true, adds MeshcatVisualizer to the Diagram. It should be set to False
            when running tests.
        @param sim_duration: the duration of simulation in seconds. If unset, it is set to the sum of the durations of all
            plans in plan_list plus extra_time.
        @return: logs of robot configuration and MultibodyPlant, generated by simulation.
            Logs are SignalLogger systems, whose data can be accessed by SignalLogger.data().
        """
        builder = DiagramBuilder()
        builder.AddSystem(self.station)

        # Add plan runner.
        if is_visualizing:
            print_period=1.0
        else:
            print_period=np.inf

        plan_runner = IiwaPlanRunner(
            iiwa_plans=plan_list,
            gripper_setpoint_list=gripper_setpoint_list,
            print_period=print_period,
            gripper_setpoint_initial=gripper_setpoint_initial)
        self.plan_runner = plan_runner

        iiwa_position_command_log, iiwa_position_measured_log, \
        iiwa_external_torque_log, iiwa_velocity_estimated_log = \
            self.ConnectPortsAndAddLoggers(builder, self.station, plan_runner)

        plant_state_log = LogOutput(
            self.station.GetOutputPort("plant_continuous_state"), builder)
        plant_state_log.set_publish_period(0.01)

        if is_visualizing:
            # Add meshcat visualizer
            scene_graph = self.station.get_mutable_scene_graph()
            viz = MeshcatVisualizer(scene_graph,
                                    zmq_url="tcp://127.0.0.1:6000",
                                    frames_to_draw=self.frames_to_draw,
                                    frames_opacity=0.8)
            self.meshcat_vis = viz
            builder.AddSystem(viz)
            builder.Connect(self.station.GetOutputPort("pose_bundle"),
                            viz.GetInputPort("lcm_visualization"))

            contact_viz = MeshcatContactVisualizer(
                meshcat_viz=viz, plant=self.plant)
            builder.AddSystem(contact_viz)
            builder.Connect(
                self.station.GetOutputPort("pose_bundle"),
                contact_viz.GetInputPort("pose_bundle"))
            builder.Connect(
                self.station.GetOutputPort("contact_results"),
                contact_viz.GetInputPort("contact_results"))

        # build diagram
        diagram = builder.Build()
        self.diagram = diagram
        # RenderSystemWithGraphviz(diagram)

        # construct simulator
        simulator = Simulator(diagram)
        self.simulator = simulator

        context = diagram.GetMutableSubsystemContext(
            self.station, simulator.get_mutable_context())

        # set initial state of the robot
        self.station.SetIiwaPosition(context, q0_iiwa)
        self.station.SetIiwaVelocity(context, np.zeros(7))
        self.station.SetWsgPosition(context, 0.03)
        self.station.SetWsgVelocity(context, 0)

        # set initial hinge angles of the cupboard.
        # setting hinge angle to exactly 0 or 90 degrees will result in
        # intermittent contact with small contact forces between the door and
        # the cupboard body.
        left_hinge_joint = self.plant.GetJointByName("left_door_hinge")
        left_hinge_joint.set_angle(
            context=self.station.GetMutableSubsystemContext(
                self.plant, context),
            angle=door_angles[0])

        right_hinge_joint = self.plant.GetJointByName("right_door_hinge")
        right_hinge_joint.set_angle(
            context=self.station.GetMutableSubsystemContext(self.plant,
                                                            context),
            angle=door_angles[1])

        simulator.set_publish_every_time_step(False)
        simulator.set_target_realtime_rate(real_time_rate)

        # calculate starting time for all plans.
        t_plan = GetPlanStartingTimes(plan_list)
        sim_duration = t_plan[-1] + extra_time
        if is_visualizing:
            print("simulation duration", sim_duration)
            print("plan starting times\n", t_plan)

        self.SetInitialPlanRunnerState(plan_runner, simulator, diagram)
        simulator.Initialize()
        simulator.AdvanceTo(sim_duration)

        return (iiwa_position_command_log, iiwa_position_measured_log,
                iiwa_external_torque_log, iiwa_velocity_estimated_log,
                plant_state_log, t_plan)
    def ConnectPortsAndAddLoggers(builder, station, plan_runner):
        builder.AddSystem(plan_runner)
        builder.Connect(plan_runner.GetOutputPort("gripper_setpoint"),
                        station.GetInputPort("wsg_position"))
        builder.Connect(plan_runner.GetOutputPort("force_limit"),
                        station.GetInputPort("wsg_force_limit"))
        builder.Connect(plan_runner.GetOutputPort("iiwa_position_command"),
                        station.GetInputPort("iiwa_position"))
        builder.Connect(plan_runner.GetOutputPort("iiwa_torque_command"),
                        station.GetInputPort("iiwa_feedforward_torque"))

        builder.Connect(station.GetOutputPort("iiwa_position_measured"),
                        plan_runner.GetInputPort("iiwa_position"))
        builder.Connect(station.GetOutputPort("iiwa_position_commanded"),
                        plan_runner.GetInputPort("iiwa_position_cmd"))
        builder.Connect(station.GetOutputPort("iiwa_velocity_estimated"),
                        plan_runner.GetInputPort("iiwa_velocity"))
        builder.Connect(station.GetOutputPort("iiwa_torque_external"),
                        plan_runner.GetInputPort("iiwa_torque_external"))

        # Add loggers
        iiwa_position_command_log = LogOutput(
            plan_runner.GetOutputPort("iiwa_position_command"), builder)
        iiwa_position_command_log.set_publish_period(0.01)

        iiwa_external_torque_log = LogOutput(
            station.GetOutputPort("iiwa_torque_external"), builder)
        iiwa_external_torque_log.set_publish_period(0.01)

        iiwa_position_measured_log = LogOutput(
            station.GetOutputPort("iiwa_position_measured"), builder)
        iiwa_position_measured_log.set_publish_period(0.01)

        iiwa_velocity_estimated_log = LogOutput(
            station.GetOutputPort("iiwa_velocity_estimated"), builder)
        iiwa_velocity_estimated_log.set_publish_period(0.01)

        return (iiwa_position_command_log, iiwa_position_measured_log,
                iiwa_external_torque_log, iiwa_velocity_estimated_log)
Exemple #20
0
    def RunRealRobot(self, plans_list, gripper_setpoint_list):
        """
        Constructs a Diagram that sends commands to ManipulationStationHardwareInterface.
        @param plans_list: A list of Plans to be executed.
        @param gripper_setpoint_list: A list of gripper setpoints. Each setpoint corresponds to a Plan.
        @return: logs of robot configuration and torque, decoded from LCM messges sent by the robot's driver.
            Logs are SignalLogger systems, whose data can be accessed by SignalLogger.data().
        """
        builder = DiagramBuilder()
        camera_ids = ["805212060544"]
        station_hardware = ManipulationStationHardwareInterface(camera_ids)
        station_hardware.Connect(wait_for_cameras=False)
        builder.AddSystem(station_hardware)

        # Add plan runner
        # Add plan runner.
        plan_runner = ManipStationPlanRunner(
            station=self.station,
            kuka_plans=plans_list,
            gripper_setpoint_list=gripper_setpoint_list)

        builder.AddSystem(plan_runner)
        builder.Connect(plan_runner.hand_setpoint_output_port,
                        station_hardware.GetInputPort("wsg_position"))
        builder.Connect(plan_runner.gripper_force_limit_output_port,
                        station_hardware.GetInputPort("wsg_force_limit"))

        demux = builder.AddSystem(Demultiplexer(14, 7))
        builder.Connect(
            plan_runner.GetOutputPort("iiwa_position_and_torque_command"),
            demux.get_input_port(0))
        builder.Connect(demux.get_output_port(0),
                        station_hardware.GetInputPort("iiwa_position"))
        builder.Connect(
            demux.get_output_port(1),
            station_hardware.GetInputPort("iiwa_feedforward_torque"))
        builder.Connect(
            station_hardware.GetOutputPort("iiwa_position_measured"),
            plan_runner.iiwa_position_input_port)
        builder.Connect(
            station_hardware.GetOutputPort("iiwa_velocity_estimated"),
            plan_runner.iiwa_velocity_input_port)

        # Add logger
        iiwa_position_command_log = LogOutput(demux.get_output_port(0),
                                              builder)
        iiwa_position_command_log._DeclarePeriodicPublish(0.005)

        iiwa_position_measured_log = LogOutput(
            station_hardware.GetOutputPort("iiwa_position_measured"), builder)
        iiwa_position_measured_log._DeclarePeriodicPublish(0.005)

        iiwa_external_torque_log = LogOutput(
            station_hardware.GetOutputPort("iiwa_torque_external"), builder)
        iiwa_external_torque_log._DeclarePeriodicPublish(0.005)

        # build diagram
        diagram = builder.Build()
        # RenderSystemWithGraphviz(diagram)

        # construct simulator
        simulator = Simulator(diagram)

        simulator.set_target_realtime_rate(1.0)
        simulator.set_publish_every_time_step(False)

        sim_duration = 0.
        for plan in plans_list:
            sim_duration += plan.get_duration() * 1.1

        print "sending trajectories in 2 seconds..."
        time.sleep(1.0)
        print "sending trajectories in 1 second..."
        time.sleep(1.0)
        print "sending trajectories now!"
        simulator.StepTo(sim_duration)

        return iiwa_position_command_log, \
               iiwa_position_measured_log, iiwa_external_torque_log
    def RunRealRobot(
        self,
        plan_list,
        gripper_setpoint_list,
        sim_duration=None,
        extra_time=2.0,
        is_plan_runner_diagram=False,
    ):
        """
        Constructs a Diagram that sends commands to ManipulationStationHardwareInterface.
        @param plan_list: A list of Plans to be executed.
        @param gripper_setpoint_list: A list of gripper setpoints. Each setpoint corresponds to a Plan.
        @param sim_duration: the duration of simulation in seconds. If unset, it is set to the sum of the durations of
            all plans in plan_list plus extra_time.
        @param extra_time: the amount of time for which commands are sent, in addition to the duration of all plans.
        @param is_plan_runner_diagram: True: use the diagram version of PlanRunner; False: use the leaf version
            of PlanRunner.
        @return: logs of robot configuration and torque, decoded from LCM messges sent by the robot's driver.
            Logs are SignalLogger systems, whose data can be accessed by SignalLogger.data().
        """
        builder = DiagramBuilder()
        camera_ids = ["805212060544"]
        station_hardware = ManipulationStationHardwareInterface(camera_ids)
        station_hardware.Connect(wait_for_cameras=False)
        builder.AddSystem(station_hardware)

        # Add plan runner.
        if is_plan_runner_diagram:
            plan_runner, duration_multiplier = CreateManipStationPlanRunnerDiagram(
                kuka_plans=plan_list,
                gripper_setpoint_list=gripper_setpoint_list,
                print_period=0,
            )
        else:
            plan_runner = ManipStationPlanRunner(
                kuka_plans=plan_list,
                gripper_setpoint_list=gripper_setpoint_list,
                print_period=0,
            )
            duration_multiplier = plan_runner.kPlanDurationMultiplier

        builder.AddSystem(plan_runner)
        builder.Connect(plan_runner.GetOutputPort("gripper_setpoint"),
                        station_hardware.GetInputPort("wsg_position"))
        builder.Connect(plan_runner.GetOutputPort("force_limit"),
                        station_hardware.GetInputPort("wsg_force_limit"))
        builder.Connect(plan_runner.GetOutputPort("iiwa_position_command"),
                        station_hardware.GetInputPort("iiwa_position"))
        builder.Connect(
            plan_runner.GetOutputPort("iiwa_torque_command"),
            station_hardware.GetInputPort("iiwa_feedforward_torque"))

        builder.Connect(
            station_hardware.GetOutputPort("iiwa_position_measured"),
            plan_runner.GetInputPort("iiwa_position"))
        builder.Connect(
            station_hardware.GetOutputPort("iiwa_velocity_estimated"),
            plan_runner.GetInputPort("iiwa_velocity"))
        builder.Connect(station_hardware.GetOutputPort("iiwa_torque_external"),
                        plan_runner.GetInputPort("iiwa_torque_external"))

        # Add logger
        iiwa_position_command_log = LogOutput(
            plan_runner.GetOutputPort("iiwa_position_command"), builder)
        iiwa_position_command_log._DeclarePeriodicPublish(0.005)

        iiwa_position_measured_log = LogOutput(
            station_hardware.GetOutputPort("iiwa_position_measured"), builder)
        iiwa_position_measured_log._DeclarePeriodicPublish(0.005)

        iiwa_velocity_estimated_log = LogOutput(
            station_hardware.GetOutputPort("iiwa_velocity_estimated"), builder)
        iiwa_velocity_estimated_log._DeclarePeriodicPublish(0.005)

        iiwa_external_torque_log = LogOutput(
            station_hardware.GetOutputPort("iiwa_torque_external"), builder)
        iiwa_external_torque_log._DeclarePeriodicPublish(0.005)

        # build diagram
        diagram = builder.Build()
        # RenderSystemWithGraphviz(diagram)

        # construct simulator
        simulator = Simulator(diagram)
        self.simulator = simulator

        simulator.set_target_realtime_rate(1.0)
        simulator.set_publish_every_time_step(False)

        t_plan = GetPlanStartingTimes(plan_list, duration_multiplier)
        if sim_duration is None:
            sim_duration = t_plan[-1] + extra_time
        print "simulation duration", sim_duration
        print "plan starting times\n", t_plan

        print "sending trajectories in 2 seconds..."
        time.sleep(1.0)
        print "sending trajectories in 1 second..."
        time.sleep(1.0)
        print "sending trajectories now!"

        simulator.Initialize()
        self.SetInitialPlanRunnerState(plan_runner, simulator, diagram)
        simulator.StepTo(sim_duration)

        return iiwa_position_command_log, iiwa_position_measured_log, \
               iiwa_velocity_estimated_log, iiwa_external_torque_log, t_plan
    def RunSimulation(self,
                      plan_list,
                      gripper_setpoint_list,
                      extra_time=0,
                      real_time_rate=1.0,
                      q0_kuka=np.zeros(7),
                      is_visualizing=True,
                      sim_duration=None,
                      is_plan_runner_diagram=False):
        """
        Constructs a Diagram that sends commands to ManipulationStation.
        @param plan_list: A list of Plans to be executed.
        @param gripper_setpoint_list: A list of gripper setpoints. Each setpoint corresponds to a Plan.
        @param extra_time: the amount of time for which commands are sent,
            in addition to the sum of the durations of all plans.
        @param real_time_rate: 1.0 means realtime; 0 means as fast as possible.
        @param q0_kuka: initial configuration of the robot.
        @param is_visualizing: if true, adds MeshcatVisualizer to the Diagram. It should be set to False
            when running tests.
        @param sim_duration: the duration of simulation in seconds. If unset, it is set to the sum of the durations of all
            plans in plan_list plus extra_time.
        @param is_plan_runner_diagram: True: use the diagram version of PlanRunner; False: use the leaf version
            of PlanRunner.
        @return: logs of robot configuration and MultibodyPlant, generated by simulation.
            Logs are SignalLogger systems, whose data can be accessed by SignalLogger.data().
        """
        builder = DiagramBuilder()
        builder.AddSystem(self.station)

        # Add plan runner.
        if is_plan_runner_diagram:
            plan_runner, duration_multiplier = CreateManipStationPlanRunnerDiagram(
                kuka_plans=plan_list,
                gripper_setpoint_list=gripper_setpoint_list)
        else:
            plan_runner = ManipStationPlanRunner(
                kuka_plans=plan_list,
                gripper_setpoint_list=gripper_setpoint_list)
            duration_multiplier = plan_runner.kPlanDurationMultiplier

        self.plan_runner = plan_runner

        builder.AddSystem(plan_runner)
        builder.Connect(plan_runner.GetOutputPort("gripper_setpoint"),
                        self.station.GetInputPort("wsg_position"))
        builder.Connect(plan_runner.GetOutputPort("force_limit"),
                        self.station.GetInputPort("wsg_force_limit"))
        builder.Connect(plan_runner.GetOutputPort("iiwa_position_command"),
                        self.station.GetInputPort("iiwa_position"))
        builder.Connect(plan_runner.GetOutputPort("iiwa_torque_command"),
                        self.station.GetInputPort("iiwa_feedforward_torque"))

        builder.Connect(self.station.GetOutputPort("iiwa_position_measured"),
                        plan_runner.GetInputPort("iiwa_position"))
        builder.Connect(self.station.GetOutputPort("iiwa_velocity_estimated"),
                        plan_runner.GetInputPort("iiwa_velocity"))
        builder.Connect(self.station.GetOutputPort("iiwa_torque_external"),
                        plan_runner.GetInputPort("iiwa_torque_external"))

        # Add meshcat visualizer
        if is_visualizing:
            scene_graph = self.station.get_mutable_scene_graph()
            viz = MeshcatVisualizer(scene_graph,
                                    is_drawing_contact_force=True,
                                    plant=self.plant)
            builder.AddSystem(viz)
            builder.Connect(self.station.GetOutputPort("pose_bundle"),
                            viz.GetInputPort("lcm_visualization"))
            builder.Connect(self.station.GetOutputPort("contact_results"),
                            viz.GetInputPort("contact_results"))

        # Add logger
        iiwa_position_command_log = LogOutput(
            plan_runner.GetOutputPort("iiwa_position_command"), builder)
        iiwa_position_command_log._DeclarePeriodicPublish(0.005)

        iiwa_external_torque_log = LogOutput(
            self.station.GetOutputPort("iiwa_torque_external"), builder)
        iiwa_external_torque_log._DeclarePeriodicPublish(0.005)

        iiwa_position_measured_log = LogOutput(
            self.station.GetOutputPort("iiwa_position_measured"), builder)
        iiwa_position_measured_log._DeclarePeriodicPublish(0.005)

        plant_state_log = LogOutput(
            self.station.GetOutputPort("plant_continuous_state"), builder)
        plant_state_log._DeclarePeriodicPublish(0.005)

        # build diagram
        diagram = builder.Build()
        if is_visualizing:
            viz.load()
            time.sleep(2.0)
            RenderSystemWithGraphviz(diagram)

        # construct simulator
        simulator = Simulator(diagram)
        self.simulator = simulator

        context = diagram.GetMutableSubsystemContext(
            self.station, simulator.get_mutable_context())

        # set initial state of the robot
        self.station.SetIiwaPosition(q0_kuka, context)
        self.station.SetIiwaVelocity(np.zeros(7), context)
        self.station.SetWsgPosition(0.05, context)
        self.station.SetWsgVelocity(0, context)

        # set initial hinge angles of the cupboard.
        # setting hinge angle to exactly 0 or 90 degrees will result in intermittent contact
        # with small contact forces between the door and the cupboard body.
        left_hinge_joint = self.plant.GetJointByName("left_door_hinge")
        left_hinge_joint.set_angle(
            context=self.station.GetMutableSubsystemContext(
                self.plant, context),
            angle=-0.001)

        right_hinge_joint = self.plant.GetJointByName("right_door_hinge")
        right_hinge_joint.set_angle(
            context=self.station.GetMutableSubsystemContext(
                self.plant, context),
            angle=0.001)

        # set initial pose of the object
        if self.object_base_link_name is not None:
            self.plant.tree().SetFreeBodyPoseOrThrow(
                self.plant.GetBodyByName(self.object_base_link_name,
                                         self.object), self.X_WObject,
                self.station.GetMutableSubsystemContext(self.plant, context))

        simulator.set_publish_every_time_step(False)
        simulator.set_target_realtime_rate(real_time_rate)

        # calculate starting time for all plans.
        t_plan = GetPlanStartingTimes(plan_list, duration_multiplier)
        if sim_duration is None:
            sim_duration = t_plan[-1] + extra_time
        print "simulation duration", sim_duration
        print "plan starting times\n", t_plan

        simulator.Initialize()
        self.SetInitialPlanRunnerState(plan_runner, simulator, diagram)
        simulator.StepTo(sim_duration)

        return iiwa_position_command_log, iiwa_position_measured_log, \
            iiwa_external_torque_log, plant_state_log, t_plan
Exemple #23
0

options.visualization_callback = draw

policy, cost_to_go = FittedValueIteration(simulator, cost_function, state_grid,
                                          input_grid, timestep, options)

J = np.reshape(cost_to_go, Q.shape)
surf = ax.plot_surface(Q, Qdot, J, rstride=1, cstride=1, cmap=cm.jet)
Pi = np.reshape(policy.get_output_values(), Q.shape)
surf = ax2.plot_surface(Q, Qdot, Pi, rstride=1, cstride=1, cmap=cm.jet)

# animate the resulting policy.
builder = DiagramBuilder()
plant = builder.AddSystem(DoubleIntegrator())
logger = LogOutput(plant.get_output_port(0), builder)
vi_policy = builder.AddSystem(policy)
builder.Connect(vi_policy.get_output_port(0), plant.get_input_port(0))
builder.Connect(plant.get_output_port(0), vi_policy.get_input_port(0))

diagram = builder.Build()
simulator = Simulator(diagram)

state = simulator.get_mutable_context().SetContinuousState([-10.0, 0.0])

simulator.AdvanceTo(10.)

# Visualize the result as a video.
vis = DoubleIntegratorVisualizer()
ani = vis.animate(logger, repeat=True)
Exemple #24
0
# Parameters from Geyer05, Figure 2.4
# Note: Geyer uses angle of attack = 90 - touchdown_angle
touchdown_angle = np.deg2rad(30)
Etilde = 1.61

s = SLIPState(np.zeros(8))
s.z = 0.9
s.theta = touchdown_angle
s.r = 1
s.xdot = plant.apex_velocity_from_dimensionless_system_energy(Etilde, s.z)

viz = builder.AddSystem(SLIPVisualizer())
builder.Connect(plant.get_output_port(0), viz.get_input_port(0))

log = LogOutput(plant.get_output_port(0), builder)

command = builder.AddSystem(ConstantVectorSource([touchdown_angle]))
builder.Connect(command.get_output_port(0), plant.get_input_port(0))

diagram = builder.Build()
simulator = Simulator(diagram)
context = simulator.get_mutable_context()
context.SetAccuracy(1e-10)

context.get_mutable_continuous_state_vector().SetFromVector(s[:])

simulator.set_target_realtime_rate(1.0)
simulator.StepTo(0.6)

print("apex: " + str(plant.last_apex))