def useless_left_right_distance_printing(): # env = PGDriveEnv(dict(vehicle_config=dict(side_detector=dict(num_lasers=8)))) for steering in [-0.01, 0.01, -1, 1]: # for distance in [10, 50, 100]: env = PGDriveEnv( dict(map="SSSSSSSSSSS", vehicle_config=dict( side_detector=dict(num_lasers=0, distance=50)), use_render=False, fast=True)) try: for _ in range(100000000): o, r, d, i = env.step([steering, 1]) vehicle = env.vehicle l, r = vehicle.dist_to_left_side, vehicle.dist_to_right_side total_width = float( (vehicle.navigation.get_current_lane_num() + 1) * vehicle.navigation.get_current_lane_width()) print("Left {}, Right {}, Total {}. Clip Total {}".format( l / total_width, r / total_width, (l + r) / total_width, clip(l / total_width, 0, 1) + clip(r / total_width, 0, 1))) if d: break finally: env.close()
def default_config(cls) -> PGConfig: config = PGDriveEnv.default_config() # Set the internal environment run in 0.02s interval. config["decision_repeat"] = 1 # Speed reward_function is given for current state, so its magnitude need to be reduced original_action_repeat = PGDriveEnv.default_config()["decision_repeat"] config[ "speed_reward"] = config["speed_reward"] / original_action_repeat # Set the interval from 0.02s to 1s config.update( { "fixed_action_repeat": 0, "max_action_repeat": 50, "min_action_repeat": 1, "horizon": 5000, }, ) # default gamma for ORIGINAL primitive step! # Note that we will change this term since ORIGINAL primitive steps is not the internal step! # It still contains ORIGINAL_ACTION_STEP internal steps! # So we will modify this gamma to make sure it behaves like the one applied to ORIGINAL primitive steps. # config.add("gamma", 0.99) return config
def __init__(self, env_config): self.ray = import_ray() assert self.ray is not None, "Please install ray via: pip install ray " \ "if you wish to use multiple PGDrive in single process." # Temporary environment tmp = PGDriveEnv(env_config) self.action_space = tmp.action_space self.observation_space = tmp.observation_space self.reward_range = tmp.reward_range tmp.close() del tmp self.env = None self.env_config = env_config
def test_traffic_respawn(vis=False): setup_logger(vis) env = PGDriveEnv( { "environment_num": 1, "manual_control": vis, "use_render": vis, "use_topdown": True, "traffic_mode": "respawn" } ) env.reset() try: for i in range(1, 3000): env.step([0, 0]) current_v = set(env.engine.traffic_manager.vehicles) for v in list(env.engine.traffic_manager.traffic_vehicles) + [env.vehicle]: if v is env.vehicle: current_v.discard(v) else: current_v.discard(v) assert len(current_v) == 0, "vehicles didn't release" assert len(env.engine.traffic_manager.vehicles) - len(env.engine.traffic_manager.traffic_vehicles) == 1, \ "vehicles didn't release" finally: env.close()
def default_config() -> PGConfig: config = PGDriveEnv.default_config() config.add("change_friction", True) config.add("friction_min", 0.8) config.add("friction_max", 1.2) config.update({"vehicle_config": {"wheel_friction": 1.0}}) return config
def default_config() -> PGConfig: config = PGDriveEnv.default_config() config.update({ "change_density": True, "density_min": 0.0, "density_max": 0.4, }) return config
def test_save_map_image(): os.makedirs("tmp_images", exist_ok=True) setup_logger(debug=True) env = PGDriveEnv(dict(environment_num=20, start_seed=0, map=10)) try: for i in range(5): env.reset() surface = env.get_map(resolution=(128, 128)) plt.imshow(surface, cmap="Greys") plt.savefig("tmp_images/map_{}.png".format(i)) env.current_map.draw_navi_line(env.vehicle, dest_resolution=(2048, 2048), save=False) env.close() finally: env.close()
def local_test_apply_action(): try: env = PGDriveEnv({"map": "SSS", "use_render": True, "fast": True}) o = env.reset() for act in [-1, 1]: for _ in range(300): assert env.observation_space.contains(o) o, r, d, i = env.step([act, 1]) if d: o = env.reset() break env.close() finally: if "env" in locals(): env = locals()["env"] env.close()
def test_config_sync(): """ The config in BaseEngine should be the same as env.config, if BaseEngine exists in process """ try: env = PGDriveEnv( {"vehicle_config": dict(show_lidar=False, show_navi_mark=False)}) env.reset() recursive_equal(env.config, env.engine.global_config) env.config.update( {"vehicle_config": dict(show_lidar=True, show_navi_mark=True)}) recursive_equal(env.config, env.engine.global_config) env.close() env.reset() recursive_equal(env.config, env.engine.global_config) env.engine.global_config.update( {"vehicle_config": dict(show_lidar=False, show_navi_mark=False)}) recursive_equal(env.config, env.engine.global_config) finally: env.close()
def default_config() -> PGConfig: config = PGDriveEnv.default_config() config.update({ "change_friction": True, "friction_min": 0.8, "friction_max": 1.2, "vehicle_config": { "wheel_friction": 1.0 } }) return config
def test_save_map_image(): os.makedirs("tmp_images", exist_ok=True) setup_logger(debug=True) env = PGDriveEnv(dict(environment_num=20, start_seed=0, map=10)) try: for i in range(5): env.reset() surface = draw_top_down_map(env.current_map, resolution=(128, 128)) plt.imshow(surface, cmap="Greys") plt.savefig("tmp_images/map_{}.png".format(i)) env.close() finally: env.close()
def vis_highway_render_with_panda_render(): setup_logger(True) env = PGDriveEnv({ "environment_num": 1, "manual_control": True, "use_render": True, "use_image": False, "use_topdown": True, }) o = env.reset() s = time.time() for i in range(1, 100000): o, r, d, info = env.step(env.action_space.sample()) env.render() if d: env.reset() if i % 1000 == 0: print("Steps: {}, Time: {}".format(i, time.time() - s)) env.close()
def test_out_of_road(): # env = PGDriveEnv(dict(vehicle_config=dict(side_detector=dict(num_lasers=8)))) for steering in [-0.01, 0.01]: for distance in [10, 50, 100]: env = PGDriveEnv( dict( map="SSSSSSSSSSS", vehicle_config=dict( side_detector=dict(num_lasers=120, distance=distance)), use_render=False, fast=True)) try: obs = env.reset() tolerance = math.sqrt(env.vehicle.WIDTH**2 + env.vehicle.LENGTH**2) / distance for _ in range(100000000): o, r, d, i = env.step([steering, 1]) if d: points = \ env.vehicle.side_detector.perceive(env.vehicle, env.vehicle.engine.physics_world.static_world).cloud_points assert min(points) < tolerance, (min(points), tolerance) print( "Side detector minimal distance: {}, Current distance: {}, steering: {}" .format( min(points) * distance, distance, steering)) break finally: env.close()
def test_get_lane_index(use_render=False): env = PGDriveEnv({ "map": "rRCXSOTCR", "environment_num": 1, "traffic_density": 0.3, "traffic_mode": "respawn", "use_render": use_render }) try: o = env.reset() for i in range(1, 1000): o, r, d, info = env.step([0, 0]) for v in env.scene_manager.traffic_manager.vehicles: old_res = env.current_map.road_network.get_closest_lane_index( v.position, True) old_lane_idx = [index[1] for index in old_res] if v.lane_index not in old_lane_idx: raise ValueError((v.lane_index), old_lane_idx) else: idx = old_lane_idx.index(v.lane_index) if old_res[idx][0] > 2. and idx > 2: raise ValueError( "L1 dist:{} of {} is too large".format( old_res[idx][0], idx)) finally: env.close()
def local_test_close_and_restart(): try: for m in ["X", "O", "C", "S", "R", "r", "T"]: env = PGDriveEnv({"map": m, "use_render": True, "fast": True}) o = env.reset() for _ in range(300): assert env.observation_space.contains(o) o, r, d, i = env.step([1, 1]) if d: break env.close() finally: if "env" in locals(): env = locals()["env"] env.close()
def test_pgdrive_env_rgb(): env = PGDriveEnv(dict(offscreen_render=True)) try: obs = env.reset() assert env.observation_space.contains(obs) _act(env, env.action_space.sample()) for x in [-1, 0, 1]: env.reset() for y in [-1, 0, 1]: _act(env, [x, y]) finally: env.close()
def default_config(cls) -> PGConfig: config = PGDriveEnv.default_config() config["vehicle_config"]["lidar"].update({"num_lasers": 0, "distance": 0}) # Remove lidar config.update( { "frame_skip": 5, "frame_stack": 3, "post_stack": 5, "rgb_clip": True, "resolution_size": 84, "distance": 30 } ) return config
def test_lidar_with_mask(render=False): setup_logger(debug=True) env = PGDriveEnv({ "use_render": render, "manual_control": render, "environment_num": 1, "traffic_density": 0.3, "vehicle_config": { "show_lidar": True, "side_detector": dict(num_lasers=2, distance=50), "lane_line_detector": dict(num_lasers=2, distance=50), }, "_disable_detector_mask": False, "map": "XXX" }) try: env.reset() v_config = env.config["vehicle_config"] v_config["spawn_longitude"] = 0 v_config["spawn_lateral"] = 7.5 another_v = DefaultVehicle(v_config, random_seed=0) another_v.reset() # for test objs = env.vehicle.side_detector.perceive( env.vehicle, env.vehicle.engine.physics_world.static_world ).detected_objects + env.vehicle.lane_line_detector.perceive( env.vehicle, env.vehicle.engine.physics_world.static_world).detected_objects yellow = 0 for obj in objs: if obj.getNode().getName() == BodyName.Yellow_continuous_line: yellow += 1 assert yellow == 2, "side detector and lane detector broken" detect_traffic_vehicle = False detect_base_vehicle = False for i in range(1, 100000): o, r, d, info = env.step([0, 1]) if len( env.vehicle.lidar.get_surrounding_vehicles( env.observations[DEFAULT_AGENT].detected_objects)) > 2: detect_traffic_vehicle = True for hit in env.observations[DEFAULT_AGENT].detected_objects: if isinstance(hit, BaseVehicle): detect_base_vehicle = True if d: break if not (detect_traffic_vehicle and detect_base_vehicle): print("Lidar detection failed") assert detect_traffic_vehicle and detect_base_vehicle, "Lidar detection failed" finally: env.close()
def test_collision_with_vehicle(): env = PGDriveEnv({"traffic_density": 1.0}) o = env.reset() pass_test = False try: for i in range(1, 100): o, r, d, info = env.step([0, 1]) if env.vehicle.crash_vehicle: pass_test = True break assert pass_test, "Collision function is broken!" finally: env.close()
def test_line_contact(): env = PGDriveEnv({"traffic_density": .0}) o = env.reset() on_broken_line = False on_continuous_line = False try: for i in range(1, 100): o, r, d, info = env.step([-0.5, 1]) on_broken_line = on_broken_line or env.vehicle.on_broken_line on_continuous_line = on_continuous_line or env.vehicle.on_white_continuous_line assert on_broken_line and on_continuous_line, "Collision function is broken!" finally: env.close()
def test_collision_with_vehicle(use_render=False): if not use_render: env = PGDriveEnv({"traffic_density": 1.0, "map": "SSS"}) else: env = PGDriveEnv({ "traffic_density": 1.0, "map": "SSS", "use_render": True, "fast": True }) o = env.reset() pass_test = False try: for i in range(1, 500): o, r, d, info = env.step([0, 1]) if env.vehicle.crash_vehicle: pass_test = True break assert pass_test, "Collision function is broken!" finally: env.close()
def vis_installation(headless=True): loadPrcFileData("", "notify-level-task fatal") try: env = PGDriveEnv({"use_render": False, "offscreen_render": False}) env.reset() for i in range(1, 100): o, r, d, info = env.step([0, 1]) env.close() del env except: print("Error happens in Bullet physics world !") sys.exit() else: print("Bullet physics world is launched successfully!") try: capture_image(headless) except: print("Error happens when drawing scene in offscreen mode!")
def default_config(cls) -> PGConfig: config = PGDriveEnv.default_config() # Set the internal environment run in 0.02s interval. config["decision_repeat"] = 1 # Speed reward is given for current state, so its magnitude need to be reduced config["speed_reward"] = config["speed_reward"] / cls.ORIGINAL_ACTION_REPEAT # Set the interval from 0.02s to 1s config.add("fixed_action_repeat", 0) # 0 stands for using varying action repeat. config.add("max_action_repeat", 50) config.add("min_action_repeat", 1) config.add("horizon", 5000) # How many primitive steps within one episode # default gamma for ORIGINAL primitive step! # Note that we will change this term since ORIGINAL primitive steps is not the internal step! # It still contains ORIGINAL_ACTION_STEP internal steps! # So we will modify this gamma to make sure it behaves like the one applied to ORIGINAL primitive steps. # config.add("gamma", 0.99) return config
def capture_image(headless): env = PGDriveEnv( dict(use_render=False, start_seed=666, traffic_density=0.1, offscreen_render=True, headless_machine_render=headless)) env.reset() for i in range(10): env.step([0, 1]) img = PNMImage() env.engine.win.getScreenshot(img) img.write("vis_installation.png") env.close() if not headless: im = Image.open("vis_installation.png") im.show() os.remove("vis_installation.png") print("Offscreen render launched successfully! \n ") else: print( "Headless mode Offscreen render launched successfully! \n " "A image named \'tset_install.png\' is saved. Open it to check if offscreen mode works well" )
def test_get_lane_index(use_render=False): env = PGDriveEnv( { "map": "rRCXSOTCR", "environment_num": 1, "traffic_density": 0.3, "traffic_mode": "reborn", "use_render": use_render } ) o = env.reset() for i in range(1, 1000): o, r, d, info = env.step([0, 0]) for v in env.scene_manager.traffic.vehicles: old = env.current_map.road_network.get_closest_lane_index(v.position) if v.lane_index != old[0]: raise ValueError env.close()
from pgdrive.envs.pgdrive_env import PGDriveEnv if __name__ == "__main__": env = PGDriveEnv({ "map": 30, "environment_num": 1, "traffic_density": 0.1, "pstats": True, "traffic_mode": "respawn" }) o = env.reset() for i in range(1, 10000): print(i) o, r, d, info = env.step([0, 0]) env.close()
from pgdrive.envs.pgdrive_env import PGDriveEnv if __name__ == "__main__": env = PGDriveEnv({ "environment_num": 1, "traffic_density": 0.3, "traffic_mode": "reborn", "start_seed": 5, # "controller": "joystick", "manual_control": True, "use_render": True, "use_saver": True, "map": 16 }) o = env.reset() env.pg_world.force_fps.toggle() for i in range(1, 100000): o, r, d, info = env.step([0, 1]) text = {"save": env.save_mode} env.render(text=text) if info["arrive_dest"]: env.reset() env.close()
from pgdrive.component.map.base_map import BaseMap, MapGenerateMethod from pgdrive.envs.pgdrive_env import PGDriveEnv from pgdrive.utils import setup_logger setup_logger(debug=True) if __name__ == "__main__": env = PGDriveEnv({ "environment_num": 4, "traffic_density": 0.1, "start_seed": 3, "image_source": "mini_map", "manual_control": True, "use_render": True, "offscreen_render": False, "decision_repeat": 5, "rgb_clip": True, "map_config": { BaseMap.GENERATE_TYPE: MapGenerateMethod.BIG_BLOCK_NUM, BaseMap.GENERATE_CONFIG: 12, BaseMap.LANE_WIDTH: 3.5, BaseMap.LANE_NUM: 3, } }) env.reset() for i in range(1, 100000): o, r, d, info = env.step([0, 1]) env.render(text={"Frame": i, "Speed": env.vehicle.speed}) env.close()
env = PGDriveEnv({ "environment_num": 1, # "traffic_density": 1.0, "traffic_mode": "hybrid", "start_seed": 82, "onscreen_message": True, # "debug_physics_world": True, # "pstats": True, # "show_fps":False, # "random_traffic":True, "vehicle_config": dict( mini_map=(168 * w_f * 6, 84 * h_f * 6, 270), # buffer length, width rgb_camera=(168 * w_f, 84 * h_f), # buffer length, width depth_camera=(168 * w_f, 84 * h_f, True), # buffer length, width, view_ground show_navi_mark=False, increment_steering=False, wheel_friction=0.6, show_lidar=True), # "camera_height":100, # "controller":"joystick", "image_source": "mini_map", "manual_control": True, "use_render": True, "use_topdown": True, "decision_repeat": 5, "rgb_clip": True, # "debug":True, "map_config": { BaseMap.GENERATE_TYPE: MapGenerateMethod.BIG_BLOCK_SEQUENCE, BaseMap.GENERATE_CONFIG: "rrXCO", BaseMap.LANE_WIDTH: 3.5, BaseMap.LANE_NUM: 3, } })
import time from pgdrive.envs.pgdrive_env import PGDriveEnv from pgdrive.scene_creator.algorithm.BIG import BigGenerateMethod from pgdrive.scene_creator.map import Map if __name__ == "__main__": env = PGDriveEnv( dict(use_render=True, map_config={ Map.GENERATE_METHOD: BigGenerateMethod.BLOCK_NUM, Map.GENERATE_PARA: 7 }, traffic_density=0.5, manual_control=True, traffic_mode=0)) start = time.time() env.reset() env.render() print("Render cost time: ", time.time() - start) while True: o, r, d, info = env.step([0, 1]) env.render() # if d: # env.reset() env.close()