Example #1
0
def draw_map_gymd(map_name: str, output: AbsDirPath, style: str):
    try:
        from gym_duckietown.simulator import Simulator
    except ImportError:
        return

    sim = Simulator(
        map_name,
        enable_leds=True,
        domain_rand=False,
        num_tris_distractors=0,
        camera_width=640,
        camera_height=480,
        # distortion=True,
        color_ground=[0, 0.3, 0],  # green
        style=style,
    )

    sim.reset()

    logger.info("rendering obs")
    img = sim.render_obs()

    out = os.path.join(output, "cam.jpg")
    save_rgb_to_jpg(img, out)

    sim.cur_pos = [-100.0, -100.0, -100.0]
    from gym_duckietown.simulator import FrameBufferMemory

    td = FrameBufferMemory(width=1024, height=1024)
    # noinspection PyProtectedMember
    horiz = sim._render_img(
        width=td.width,
        height=td.height,
        multi_fbo=td.multi_fbo,
        final_fbo=td.final_fbo,
        img_array=td.img_array,
        top_down=True,
    )
    # img = sim.render("top_down")
    out = cast(FilePath, os.path.join(output, "top_down.jpg"))
    save_rgb_to_jpg(horiz, out)
Example #2
0
def make_scenario_main(args=None):
    setup_logging()
    parser = argparse.ArgumentParser()

    # parser.add_argument("--config", help="Configuration", required=True)
    parser.add_argument("-o",
                        "--output",
                        help="Destination directory",
                        required=True)
    parser.add_argument("-n",
                        "--num",
                        type=int,
                        help="Number of scenarios to generate",
                        required=True)
    parser.add_argument(
        "--styles",
        default="synthetic-F",
        help=
        "Draw preview in various styles, comma separated. (needs gym duckietown)",
    )

    parsed, rest = parser.parse_known_args(args=args)
    if parsed.styles == "all":
        styles = ["synthetic", "synthetic-F", "photos", "smooth"]
    else:
        styles = parsed.styles.split(",")
    for config in rest:
        basename = os.path.basename(config).split(".")[0]
        data = read_ustring_from_utf8_file(config)
        interpreted = yaml.load(data, Loader=yaml.Loader)
        n: int = parsed.num
        output: str = parsed.output
        params: ScenarioGenerationParam = object_from_ipce(
            interpreted, ScenarioGenerationParam, iedo=iedo)
        for i in range(n):
            scenario_name = f"{basename}-{i:03d}"
            yaml_str = _get_map_yaml(params.map_name)
            scenario = make_scenario(
                yaml_str=yaml_str,
                scenario_name=scenario_name,
                only_straight=params.only_straight,
                min_dist=params.min_dist,
                delta_y_m=params.delta_y_m,
                robots_npcs=params.robots_npcs,
                robots_parked=params.robots_parked,
                robots_pcs=params.robots_pcs,
                nduckies=params.nduckies,
                duckie_min_dist_from_other_duckie=params.
                duckie_min_dist_from_other_duckie,
                duckie_min_dist_from_robot=params.duckie_min_dist_from_robot,
                duckie_y_bounds=params.duckie_y_bounds,
                delta_theta_rad=np.deg2rad(params.theta_tol_deg),
                pc_robot_protocol=params.pc_robot_protocol,
                npc_robot_protocol=params.npc_robot_protocol,
                tree_density=params.tree_density,
                tree_min_dist=params.tree_min_dist,
            )

            # styles = ['smooth']
            for style in styles:
                try:
                    from gym_duckietown.simulator import Simulator
                except ImportError:
                    logger.warning(traceback.format_exc())
                    # noinspection PyUnusedLocal
                    Simulator = None
                else:
                    sim = Simulator(
                        "4way",
                        enable_leds=True,
                        domain_rand=False,
                        num_tris_distractors=0,
                        camera_width=640,
                        camera_height=480,
                        # distortion=True,
                        color_ground=[0, 0.3, 0],  # green
                        style=style,
                    )
                    logger.info("resetting")
                    sim.reset()
                    m = cast(
                        dw.MapFormat1,
                        yaml.load(scenario.environment, Loader=yaml.Loader))

                    if "objects" not in m:
                        m["objects"] = {}
                    obs: Dict[str, object] = m["objects"]

                    for robot_name, srobot in scenario.robots.items():
                        st = dw.SE2Transform.from_SE2(
                            pose_from_friendly(srobot.configuration.pose))

                        obs[robot_name] = dict(kind="duckiebot",
                                               pose=st.as_json_dict(),
                                               height=0.12,
                                               color=srobot.color)

                    for duckie_name, duckie in scenario.duckies.items():
                        st = dw.SE2Transform.from_SE2(
                            pose_from_friendly(duckie.pose))
                        obs[duckie_name] = dict(kind="duckie",
                                                pose=st.as_json_dict(),
                                                height=0.08,
                                                color=duckie.color)

                    sim._interpret_map(m)
                    sim.reset()
                    logger.info("rendering obs")
                    img = sim.render_obs()
                    out = os.path.join(output, scenario_name, style, "cam.png")
                    save_rgb_to_png(img, out)
                    out = os.path.join(output, scenario_name, style, "cam.jpg")
                    save_rgb_to_jpg(img, out)

                    sim.cur_pos = [-100.0, -100.0, -100.0]
                    from gym_duckietown.simulator import FrameBufferMemory

                    td = FrameBufferMemory(width=1024, height=1024)
                    horiz = sim._render_img(
                        width=td.width,
                        height=td.height,
                        multi_fbo=td.multi_fbo,
                        final_fbo=td.final_fbo,
                        img_array=td.img_array,
                        top_down=True,
                    )
                    # img = sim.render("top_down")
                    out = cast(
                        FilePath,
                        os.path.join(output, scenario_name, style,
                                     "top_down.jpg"))
                    save_rgb_to_jpg(horiz, out)
                    out = cast(
                        FilePath,
                        os.path.join(output, scenario_name, style,
                                     "top_down.png"))
                    save_rgb_to_png(horiz, out)

                    dw.Tile.style = style
                    dm = interpret_scenario(scenario)
                    output_dir = os.path.join(output, scenario_name, style)
                    dw.draw_static(dm, output_dir=output_dir)
                    export_gltf(dm, output_dir, background=False)

            scenario_struct = ipce_from_object(scenario, Scenario, ieso=ieso)
            scenario_yaml = yaml.dump(scenario_struct)
            filename = os.path.join(output, scenario_name, f"scenario.yaml")
            write_ustring_to_utf8_file(scenario_yaml, filename)
# Set seeds
args = get_ddpg_args_test()
seed(args.seed)

state_dim = env.get_features().shape[0]
action_dim = env.action_space.shape[0]
max_action = float(env.action_space.high[0])

# Initialize policy
policy = DDPG(state_dim, action_dim, max_action, net_type="dense")
policy.load("model", directory="./models", for_inference=True)

with torch.no_grad():
    while True:
        env.reset()
        obs = env.get_features()
        env.render()
        rewards = []
        while True:
            action = policy.predict(np.array(obs))
            _, rew, done, misc = env.step(action)
            obs = env.get_features()
            rewards.append(rew)
            env.render()

            try:
                lp = env.get_lane_pos2(env.cur_pos, env.cur_angle)
                dist = abs(lp.dist)
            except:
                dist = 0
Example #4
0
        img_msg.data = np.array(cv2.imencode('.jpg', image)[1]).tostring()

        self.pub_img.publish(img_msg)


if __name__ == '__main__':
    wrapper = RosWrapperNode(node_name='ros_wrapper_node')
    env = Simulator(
        seed=123,  # random seed
        map_name="loop_empty",
        max_steps=500001,  # we don't want the gym to reset itself
        domain_rand=0,
        camera_width=640,
        camera_height=480,
        accept_start_angle_deg=4,  # start close to straight
        full_transparency=True,
        distortion=True,
    )
    obs = env.reset()
    wrapper.publish_img(obs)

    while not rospy.is_shutdown():
        action = [wrapper.action_l, wrapper.action_r]
        obs, reward, done, _ = env.step(action)

        if done:
            obs = env.reset()

        wrapper.publish_img(obs)
        rospy.Rate(15).sleep()
Example #5
0
            # publish camera info to camera info topic
            self.info_pub.publish(CameraInfo())

            rate.sleep()


if __name__ == '__main__':
    # Initialise the simulator
    rospy.loginfo("Initialising simulator ...")
    env = Simulator(
        seed=123, # random seed
        map_name="loop_empty",
        max_steps=500001, # we don't want the gym to reset itself
        domain_rand=0,
        camera_width=640,
        camera_height=480,
        accept_start_angle_deg=4, # start close to straight
        full_transparency=True,
        distortion=True,
    )
    observation = env.reset()
    rospy.loginfo("Simulator initialised")

    # create the node
    rospy.loginfo("Initialising node ...")
    node = RosWrapperSimNode(node_name='ros_wrapper_sim_node')
    rospy.loginfo("Node initialised")

    # run node
    node.run()
class ROSWrapper(DTROS):
    '''
    Class that creates a wrapper between the duckietown simulator and the ROS
    interface of a fake robot simulated in the host. The node serves as interface
    for the following parts:
        - Subscribes to the wheels command topic and transforms it into actions in simulation
        - Publishes the rendered observations in the simulator to the camera image topic
    '''
    def __init__(self, node_name):
        # initialize the DTROS parent class
        super(ROSWrapper, self).__init__(node_name=node_name,
                                         node_type=NodeType.GENERIC)

        # construct rendered observation publisher
        self.camera_pub = rospy.Publisher('~/' + VEHICLE_NAME +
                                          '/camera_node/image/compressed',
                                          CompressedImage,
                                          queue_size=1)

        # Construct subscriber for wheel_cmd topic
        self.wheels_cmd_sub = rospy.Subscriber(
            '~/' + VEHICLE_NAME + '/wheels_driver_node/wheels_cmd',
            WheelsCmdStamped,
            self.wheels_cmd_cb,
            queue_size=1)

        # Initialize the simulator
        self.env = Simulator(
            seed=123,  # random seed
            map_name="loop_empty",
            max_steps=500001,  # we don't want the gym to reset itself
            domain_rand=0,
            camera_width=640,
            camera_height=480,
            accept_start_angle_deg=4,  # start close to straight
            full_transparency=True,
            distortion=True,
        )
        # Create action variable
        self.action = [0.0, 0.0]

    def wheels_cmd_cb(self, msg):
        '''
        Callback that maps wheel commands into actions in the simulator.

            Creates the simulated robot actions based on the received command
            through the main topic in the duckietown infrastructure.

            Args:
                msg (WheelsCmdStamped): Velocity command
        '''

        vel_left = msg.vel_left
        vel_right = msg.vel_right

        self.action = [vel_left, vel_right]

    def run(self):
        '''
        Continuously run the wrapper to map ROS interface with simulator.

            This method runs the node, and begins an iterative process where the
            image is retrieved from the simulator and published in the camera image topic,
            and the wheels command received by subscribing to the wheels_cmd topic is translated
            into actions executed in the simulator. The process iterates until the node is terminated

        '''

        while not rospy.is_shutdown():

            # Update the simulator
            # the action message is updated every time the wheels_cmd_cb is called
            # that is, every time a message arrives.
            observation, reward, done, misc = self.env.step(self.action)
            # Render the new state
            self.env.render()

            # Set again action to stop, in case no more messages are being received
            self.action = [0.0, 0.0]

            if done:
                # Reset the simulator when the robot goes out of the road.
                self.env.reset()

            # Transalte the observation into a CompressedImage message to publish it
            bgr_obs = cv2.cvtColor(observation, cv2.COLOR_RGB2BGR)
            bridge = CvBridge()
            img_msg = bridge.cv2_to_compressed_imgmsg(cvim=bgr_obs,
                                                      dst_format="jpg")

            # Publish the image in the /image/compressed topic
            self.camera_pub.publish(img_msg)
Example #7
0
class MyROSWrapperNode(DTROS):
    def __init__(self, node_name):
        # initialize the DTROS parent class
        #color = rospy.get_param('~color')
        super(MyROSWrapperNode, self).__init__(node_name=node_name,
                                               node_type=NodeType.GENERIC)
        # construct Publisher and Subscriber
        self.pub = rospy.Publisher('/fakebot/camera_node/image/compressed',
                                   CompressedImage,
                                   queue_size=10)
        self.sub = rospy.Subscriber('/fakebot/wheels_driver_node/wheels_cmd',
                                    WheelsCmdStamped, self.callback)
        #self.sub = rospy.Subscriber('chatter', String, self.callback)
        self.iter = 0

        # create bag files:
        # self.bag = bag

        self.env = Simulator(
            seed=123,  # random seed
            map_name="loop_empty",
            max_steps=500001,  # we don't want the gym to reset itself
            domain_rand=0,
            camera_width=640,
            camera_height=480,
            accept_start_angle_deg=4,  # start close to straight
            full_transparency=True,
            distortion=True,
        )

        self.br = CvBridge()
        self.right_wheel = 0
        self.left_wheel = 0

    def callback(self, data):
        if data:
            # update wheel command to action
            self.right_wheel = data.vel_right
            self.left_wheel = data.vel_left

            action = [self.left_wheel, self.right_wheel]
            print("I got command:", action)
            observation, reward, done, misc = self.env.step(action)
            # env.render()

            # print("observation.shape:",observation.shape )
            # observation.shape: (480, 640, 3)
            # print("observation.type:", type(observation))
            # observation.type: <class 'numpy.ndarray'>

            # publish image to viewer
            # np_arr = np.fromstring(data.data, np.uint8)
            # img = cv2.imdecode(observation, cv2.IMREAD_COLOR)

            img = cv2.cvtColor(np.asarray(observation), cv2.COLOR_RGB2BGR)
            compressed_img_msg = self.br.cv2_to_compressed_imgmsg(
                img, dst_format='jpg')
            self.pub.publish(compressed_img_msg)

            if done:
                self.env.reset()
        else:
            rospy.loginfo("waiting for Publisher")
Example #8
0
class DuckiegymRosWrapperNode(DTROS):
    """
    Run a gym-duckietown simulator, redirect the simulator's image to a ros topic, redirect the wheel commands
    to simulator actions.
    """
    def __init__(self, node_name):
        super(DuckiegymRosWrapperNode,
              self).__init__(node_name=node_name, node_type=NodeType.GENERIC)

        self.action = [0, 0]  # wheel commands for simulator
        self.camera_info = self.load_camera_info(
            "/data/config/calibrations/camera_intrinsic/default.yaml")

        self.bridge = CvBridge()

        vehicle_name = os.environ.get("VEHICLE_NAME")
        image_topic = "/" + vehicle_name + "/camera_node/image/compressed"
        self.pub_img = rospy.Publisher(image_topic, CompressedImage)
        camera_info_topic = "/" + vehicle_name + "/camera_node/camera_info"
        self.pub_camera_info = rospy.Publisher(camera_info_topic, CameraInfo)
        wheels_cmd_topic = "/" + vehicle_name + "/wheels_driver_node/wheels_cmd"
        self.sub_wheels_cmd = rospy.Subscriber(wheels_cmd_topic,
                                               WheelsCmdStamped,
                                               self.callback_wheels_cmd,
                                               queue_size=1)

        self.sim = Simulator(
            seed=123,  # random seed
            map_name="loop_empty",
            max_steps=500001,  # we don't want the gym to reset itself
            domain_rand=0,
            camera_width=640,
            camera_height=480,
            accept_start_angle_deg=4,  # start close to straight
            full_transparency=True,
            distortion=False,
        )

    def run_simulator(self):
        """
        Main loop of this node, runs simulation loop and camera publishers.
        """
        while not rospy.is_shutdown():
            observation, reward, done, misc = self.sim.step(self.action)
            self.publish_camera_info()
            self.publish_camera_image(observation)
            self.sim.render()
            if done:
                self.sim.reset()

    def callback_wheels_cmd(self, msg):
        """
        Update action variable (parameter for simulator) on callback.
        """
        self.action = [msg.vel_left, msg.vel_right]

    def publish_camera_image(self, observation):
        """
        Publish simulated camera frame as CompressedImage message.
        """
        img = self.bridge.cv2_to_compressed_imgmsg(cv2.cvtColor(
            observation, cv2.COLOR_RGB2BGR),
                                                   dst_format="jpg")
        img.header.stamp = rospy.Time.now()
        self.pub_img.publish(img)

    def publish_camera_info(self):
        """
        Publish calibration info about camera.
        """
        self.camera_info.header.stamp = rospy.Time.now()
        self.pub_camera_info.publish(self.camera_info)

    def load_camera_info(self, filename):
        """
        Load calibration info about camera from config file.
        """
        with open(filename, 'r') as stream:
            calib_data = yaml.load(stream)
        cam_info = CameraInfo()
        cam_info.width = calib_data['image_width']
        cam_info.height = calib_data['image_height']
        cam_info.K = calib_data['camera_matrix']['data']
        cam_info.D = calib_data['distortion_coefficients']['data']
        cam_info.R = calib_data['rectification_matrix']['data']
        cam_info.P = calib_data['projection_matrix']['data']
        cam_info.distortion_model = calib_data['distortion_model']
        return cam_info