Beispiel #1
0
    def test_find_lane(self):
        xodr_parser = XodrParser("modules/runtime/tests/data/urban_road.xodr")
        params = ParameterServer()
        world = World(params)
        map_interface = MapInterface()
        map_interface.SetOpenDriveMap(xodr_parser.map)
        world.SetMap(map_interface)

        lane_sw = map_interface.FindLane(Point2d(46, 180))
        assert lane_sw.lane_type == XodrLaneType.sidewalk

        lane_rl = map_interface.FindLane(Point2d(52, 130))
        assert lane_rl.lane_type == XodrLaneType.driving

        lane_no_lane = map_interface.FindLane(Point2d(120, 140))
        assert lane_no_lane == None

        xodr_parser = XodrParser(
            "modules/runtime/tests/data/city_highway_straight.xodr")
        np.set_printoptions(precision=8)
        params = ParameterServer()
        world = World(params)

        map_interface = MapInterface()
        map_interface.SetOpenDriveMap(xodr_parser.map)
        world.SetMap(map_interface)
        point = Point2d(5114, 5072)
        viewer = MPViewer(params=params, use_world_bounds=True)
        viewer.drawWorld(world)
        viewer.drawPoint2d(point, 'red', 1.0)
        viewer.show(block=True)
        time.sleep(0.1)
        lane_sw = map_interface.FindLane(point)
        self.assertIsNotNone(lane_sw, "This point is clearly on a lane!")
Beispiel #2
0
 def _build_world_state(self):
     param_server = ParameterServer(json=self._json_params)
     world = World(param_server)
     if self._map_interface is None:
         self.CreateMapInterface(self._map_file_name)
         world.SetMap(self._map_interface)
     else:
         world.SetMap(self._map_interface)
     for agent in self._agent_list:
         agent.GenerateRoadCorridor(self._map_interface)
         world.AddAgent(agent)
     world.UpdateAgentRTree()
     return world
    def test_dr_deu_merging(self):
        # threeway_intersection
        xodr_parser = XodrParser(
            "modules/runtime/tests/data/DR_DEU_Merging_MT_v01_shifted.xodr")

        # World Definition
        params = ParameterServer()
        world = World(params)

        map_interface = MapInterface()
        map_interface.SetOpenDriveMap(xodr_parser.map)
        world.SetMap(map_interface)

        roads = [0, 1]
        driving_direction = XodrDrivingDirection.forward
        map_interface.GenerateRoadCorridor(roads, driving_direction)
        road_corridor = map_interface.GetRoadCorridor(roads, driving_direction)

        # Draw map
        viewer = MPViewer(params=params, use_world_bounds=True)
        viewer.drawWorld(world)

        viewer.drawPolygon2d(road_corridor.lane_corridors[0].polygon,
                             color="blue",
                             alpha=0.5)
        viewer.drawPolygon2d(road_corridor.lane_corridors[1].polygon,
                             color="blue",
                             alpha=0.5)
        viewer.show(block=False)

        self.assertTrue(road_corridor.lane_corridors[0].polygon.Valid())
        self.assertTrue(road_corridor.lane_corridors[1].polygon.Valid())
        self.assertTrue(road_corridor.polygon.Valid())
Beispiel #4
0
    def test_lane_change(self):
        # World Definition
        params = ParameterServer()
        world = World(params)

        # Model Definitions
        behavior_model = BehaviorMobil(params)
        execution_model = ExecutionModelInterpolate(params)
        dynamic_model = SingleTrackModel(params)

        behavior_model2 = BehaviorIDMLaneTracking(params)
        execution_model2 = ExecutionModelInterpolate(params)
        dynamic_model2 = SingleTrackModel(params)

        # Map Definition
        map_interface = MapInterface()
        xodr_map = MakeXodrMapOneRoadTwoLanes()
        map_interface.SetOpenDriveMap(xodr_map)
        world.SetMap(map_interface)

        #agent_2d_shape = CarLimousine()
        agent_2d_shape = CarRectangle()
        init_state = np.array([0, 3, -1.75, 0, 5])
        agent_params = params.AddChild("agent1")
        goal_polygon = Polygon2d(
            [1, 1, 0],
            [Point2d(0, 0),
             Point2d(0, 2),
             Point2d(2, 2),
             Point2d(2, 0)])
        goal_polygon = goal_polygon.Translate(Point2d(50, -2))

        agent = Agent(init_state, behavior_model, dynamic_model,
                      execution_model, agent_2d_shape, agent_params,
                      GoalDefinitionPolygon(goal_polygon), map_interface)
        world.AddAgent(agent)

        init_state2 = np.array([0, 15, -1.75, 0, 2])
        agent2 = Agent(init_state2, behavior_model2, dynamic_model2,
                       execution_model2, agent_2d_shape, agent_params,
                       GoalDefinitionPolygon(goal_polygon), map_interface)
        world.AddAgent(agent2)

        # viewer
        viewer = MPViewer(params=params, use_world_bounds=True)

        # World Simulation
        sim_step_time = params["simulation"]["step_time",
                                             "Step-time in simulation", 0.05]
        sim_real_time_factor = params["simulation"][
            "real_time_factor", "execution in real-time or faster", 100]

        # Draw map
        for _ in range(0, 10):
            viewer.clear()
            world.Step(sim_step_time)
            viewer.drawWorld(world)
            viewer.show(block=False)
            time.sleep(sim_step_time / sim_real_time_factor)
    def test_road_corridor_forward(self):
        xodr_parser = XodrParser(
            "modules/runtime/tests/data/road_corridor_test.xodr")

        # World Definition
        params = ParameterServer()
        world = World(params)

        map_interface = MapInterface()
        map_interface.SetOpenDriveMap(xodr_parser.map)
        world.SetMap(map_interface)
        open_drive_map = world.map.GetOpenDriveMap()
        viewer = MPViewer(params=params, use_world_bounds=True)

        # Draw map
        viewer.drawWorld(world)
        viewer.show(block=False)

        # Generate RoadCorridor
        roads = [0, 1, 2]
        driving_direction = XodrDrivingDirection.forward
        map_interface.GenerateRoadCorridor(roads, driving_direction)
        road_corridor = map_interface.GetRoadCorridor(roads, driving_direction)

        # Assert road corridor

        # Assert: 3 roads
        self.assertEqual(len(road_corridor.roads), 3)

        # Assert: road1: 2 lanes, road2: 1 lane, road3: 1 lane
        self.assertEqual(len(road_corridor.GetRoad(0).lanes), 3)
        self.assertEqual(len(road_corridor.GetRoad(1).lanes), 2)
        self.assertEqual(len(road_corridor.GetRoad(2).lanes), 3)

        # Assert: next road
        self.assertEqual(road_corridor.GetRoad(0).next_road.road_id, 1)
        self.assertEqual(road_corridor.GetRoad(1).next_road.road_id, 2)

        # Assert: lane links
        self.assertEqual(
            road_corridor.GetRoad(0).GetLane(3).next_lane.lane_id, 5)
        self.assertEqual(
            road_corridor.GetRoad(1).GetLane(5).next_lane.lane_id, 8)

        # Assert: LaneCorridor
        self.assertEqual(len(road_corridor.lane_corridors), 3)

        colors = ["blue", "red", "green"]
        count = 0
        for lane_corridor in road_corridor.lane_corridors:
            viewer.drawPolygon2d(lane_corridor.polygon,
                                 color=colors[count],
                                 alpha=0.5)
            viewer.drawLine2d(lane_corridor.left_boundary, color="red")
            viewer.drawLine2d(lane_corridor.right_boundary, color="blue")
            viewer.drawLine2d(lane_corridor.center_line, color="black")
            viewer.show(block=False)
            plt.pause(2.)
            count += 1
    def test_between_lanes(self):
        xodr_parser = XodrParser(
            "modules/runtime/tests/data/city_highway_straight.xodr")
        np.set_printoptions(precision=8)
        params = ParameterServer()

        world = World(params)
        map_interface = MapInterface()
        map_interface.SetOpenDriveMap(xodr_parser.map)
        world.SetMap(map_interface)

        # Simple test
        point_close = Point2d(5114.68262, 5086.44971)
        lane_sw = map_interface.FindLane(point_close)
        self.assertIsNotNone(
            lane_sw,
            "This point is still in the left lane! XodrLane boundary is 5114.683"
        )

        switched_lane = False
        lng_coord = 5086.44971
        i = 5114.5
        lane_sw = map_interface.FindLane(Point2d(i, lng_coord))
        assert lane_sw != None
        prev = lane_sw.lane_id
        prev_i = i
        while (i < 5117.5):
            lane_sw = map_interface.FindLane(Point2d(i, lng_coord))
            self.assertIsNotNone(
                lane_sw,
                "Should always be on at least one lane! Currently at ({}, {})".
                format(i, lng_coord))
            if prev != lane_sw.lane_id:
                # print(prev)
                # print(prev_i)
                # print(lane_sw.lane_id)
                # print(i)
                self.assertFalse(switched_lane,
                                 "XodrLane switch should only happens once!")
                switched_lane = True
            prev_i = i
            prev = lane_sw.lane_id
            i = i + 0.01
        self.assertTrue(switched_lane,
                        "Eventually should have switched lanes!")
Beispiel #7
0
    def test_two_roads_one_lane(self):
        xodr_map = MakeXodrMapOneRoadTwoLanes()

        # World Definition
        params = ParameterServer()
        world = World(params)

        map_interface = MapInterface()
        map_interface.SetOpenDriveMap(xodr_map)
        world.SetMap(map_interface)
        open_drive_map = world.map.GetOpenDriveMap()
        viewer = MPViewer(params=params, use_world_bounds=True)

        # Draw map
        viewer.drawWorld(world)
        viewer.show(block=False)

        # Generate RoadCorridor
        roads = [100]
        driving_direction = XodrDrivingDirection.forward
        map_interface.GenerateRoadCorridor(roads, driving_direction)
        road_corridor = map_interface.GetRoadCorridor(roads, driving_direction)

        # Assert road corridor

        # Assert: 1 road
        self.assertEqual(len(road_corridor.roads), 1)

        # Assert: road1: 2 lanes
        self.assertEqual(len(road_corridor.GetRoad(roads[0]).lanes), 3)

        colors = ["blue", "red", "green"]
        count = 0
        for lane_corridor in road_corridor.lane_corridors:
            viewer.drawPolygon2d(lane_corridor.polygon,
                                 color=colors[count],
                                 alpha=0.5)
            viewer.drawLine2d(lane_corridor.left_boundary, color="red")
            viewer.drawLine2d(lane_corridor.right_boundary, color="blue")
            viewer.drawLine2d(lane_corridor.center_line, color="black")
            viewer.show(block=False)
            plt.pause(2.)
            count += 1
        viewer.show(block=True)
Beispiel #8
0
    def test_road_corridor_intersection(self):
        xodr_parser = XodrParser(
            "modules/runtime/tests/data/road_corridor_test.xodr")

        # World Definition
        params = ParameterServer()
        world = World(params)

        map_interface = MapInterface()
        map_interface.SetOpenDriveMap(xodr_parser.map)
        world.SetMap(map_interface)
        open_drive_map = world.map.GetOpenDriveMap()
        viewer = MPViewer(params=params, use_world_bounds=True)

        # Draw map
        viewer.drawWorld(world)
        viewer.show(block=False)

        # Generate RoadCorridor
        roads = [0, 1, 2]
        driving_direction = XodrDrivingDirection.forward
        map_interface.GenerateRoadCorridor(roads, driving_direction)

        road_corridor = map_interface.GetRoadCorridor(roads, driving_direction)

        colors = ["blue", "red", "green", "yellow"]
        count = 0

        for road_id, road in road_corridor.roads.items():
            for lane_id, lane in road.lanes.items():
                print(road_id, lane_id, lane.driving_direction)
        for lane_corridor in road_corridor.lane_corridors:
            viewer.drawPolygon2d(lane_corridor.polygon,
                                 color=colors[count],
                                 alpha=0.5)
            viewer.drawLine2d(lane_corridor.left_boundary, color="red")
            viewer.drawLine2d(lane_corridor.right_boundary, color="blue")
            viewer.drawLine2d(lane_corridor.center_line, color="black")
            viewer.show(block=False)
            plt.pause(0.5)
            count += 1
        viewer.show(block=True)
Beispiel #9
0
    def test_Crossing8Course(self):
        xodr_parser = XodrParser(
            "modules/runtime/tests/data/Crossing8Course.xodr")

        params = ParameterServer()
        world = World(params)

        map_interface = MapInterface()
        map_interface.SetOpenDriveMap(xodr_parser.map)
        world.SetMap(map_interface)

        start_point = Point2d(0, -11)
        lanes_near_start = map_interface.find_nearest_lanes(start_point, 1)
        assert (len(lanes_near_start) == 1)

        goal_point = Point2d(-191.789, -50.1725)
        lanes_near_goal = map_interface.find_nearest_lanes(goal_point, 1)
        assert (len(lanes_near_goal) == 1)
        time.sleep(
            2
        )  # if this is not here, the second unit test is not executed (maybe parsing takes too long?)
  def test_two_roads_one_lane(self):
    params = ParameterServer()
    world = World(params)

    xodr_map = MakeXodrMapOneRoadTwoLanes()

    map_interface = MapInterface()
    map_interface.SetOpenDriveMap(xodr_map)
    world.SetMap(map_interface)

    start_point = Point2d(0, -11)
    lanes_near_start = map_interface.find_nearest_lanes(start_point, 1)
    assert(len(lanes_near_start) == 1)

    goal_point = Point2d(-191.789, -50.1725)
    lanes_near_goal = map_interface.find_nearest_lanes(goal_point, 1)
    assert(len(lanes_near_goal) == 1)

    viewer = MPViewer(params=params, use_world_bounds=True)
    viewer.drawWorld(world)

    time.sleep(2)  # if this is not here, the second unit test is not executed (maybe parsing takes too long?)
Beispiel #11
0
    def test_evaluator_drivable_area(self):
        # World Definition
        params = ParameterServer()
        world = World(params)

        # Model Definitions
        behavior_model = BehaviorConstantVelocity(params)
        execution_model = ExecutionModelInterpolate(params)
        dynamic_model = SingleTrackModel(params)

        # Map Definition
        map_interface = MapInterface()
        xodr_map = MakeXodrMapOneRoadTwoLanes()
        map_interface.SetOpenDriveMap(xodr_map)
        world.SetMap(map_interface)
        #open_drive_map = world.map.GetOpenDriveMap()

        #agent_2d_shape = CarLimousine()
        agent_2d_shape = Polygon2d(
            [1.25, 1, 0],
            [Point2d(-1, -1),
             Point2d(-1, 1),
             Point2d(3, 1),
             Point2d(3, -1)])
        init_state = np.array([0, 3, -1.75, 0, 5])
        agent_params = params.AddChild("agent1")
        goal_polygon = Polygon2d(
            [1, 1, 0],
            [Point2d(0, 0),
             Point2d(0, 2),
             Point2d(2, 2),
             Point2d(2, 0)])
        goal_polygon = goal_polygon.Translate(Point2d(50, -2))

        agent = Agent(
            init_state,
            behavior_model,
            dynamic_model,
            execution_model,
            agent_2d_shape,
            agent_params,
            GoalDefinitionPolygon(goal_polygon),  # goal_lane_id
            map_interface)
        world.AddAgent(agent)

        evaluator = EvaluatorDrivableArea()
        world.AddEvaluator("drivable_area", evaluator)

        info = world.Evaluate()
        self.assertFalse(info["drivable_area"])

        viewer = MPViewer(params=params, use_world_bounds=True)

        # Draw map
        viewer.drawGoalDefinition(goal_polygon,
                                  color=(1, 0, 0),
                                  alpha=0.5,
                                  facecolor=(1, 0, 0))
        viewer.drawWorld(world)
        viewer.drawRoadCorridor(agent.road_corridor)
        viewer.show(block=False)
    def test_three_way_intersection(self):
        # threeway_intersection
        xodr_parser = XodrParser(
            "modules/runtime/tests/data/threeway_intersection.xodr")

        # World Definition
        params = ParameterServer()
        world = World(params)

        map_interface = MapInterface()
        map_interface.SetOpenDriveMap(xodr_parser.map)
        world.SetMap(map_interface)
        open_drive_map = world.map.GetOpenDriveMap()
        viewer = MPViewer(params=params, use_world_bounds=True)
        comb_all = []
        start_point = [Point2d(-30, -2)]
        end_point_list = [Point2d(30, -2), Point2d(-2, -30)]
        comb = list(itertools.product(start_point, end_point_list))
        comb_all = comb_all + comb

        # starting on the right
        start_point = [Point2d(30, 2)]
        end_point_list = [Point2d(-30, 2)]
        comb = list(itertools.product(start_point, end_point_list))
        comb_all = comb_all + comb

        # starting on the bottom
        start_point = [Point2d(2, -30)]
        end_point_list = [Point2d(30, -2), Point2d(-30, 2)]
        comb = list(itertools.product(start_point, end_point_list))
        comb_all = comb_all + comb

        # check few corridors
        def GenerateRoadCorridor(map_interface, comb):
            (start_p, end_p) = comb
            polygon = Polygon2d([0, 0, 0], [
                Point2d(-1, -1),
                Point2d(-1, 1),
                Point2d(1, 1),
                Point2d(1, -1)
            ])
            start_polygon = polygon.Translate(start_p)
            goal_polygon = polygon.Translate(end_p)
            rc = map_interface.GenerateRoadCorridor(start_p, goal_polygon)
            return rc

        # assert road ids
        rc = GenerateRoadCorridor(map_interface, comb_all[0])
        self.assertEqual(rc.road_ids, [0, 11, 1])
        self.assertEqual(len(rc.lane_corridors), 3)
        rc = GenerateRoadCorridor(map_interface, comb_all[1])
        self.assertEqual(rc.road_ids, [0, 5, 2])
        self.assertEqual(len(rc.lane_corridors), 3)
        rc = GenerateRoadCorridor(map_interface, comb_all[2])
        self.assertEqual(rc.road_ids, [1, 10, 0])
        self.assertEqual(len(rc.lane_corridors), 3)
        rc = GenerateRoadCorridor(map_interface, comb_all[3])
        self.assertEqual(rc.road_ids, [2, 6, 1])
        self.assertEqual(len(rc.lane_corridors), 3)
        rc = GenerateRoadCorridor(map_interface, comb_all[4])
        self.assertEqual(rc.road_ids, [2, 4, 0])
        self.assertEqual(len(rc.lane_corridors), 3)
Beispiel #13
0
# set parameter that is accessible in Python as well as cpp
# param_server.setReal("wheel_base", 0.8)

# World Definition
world = World(param_server)

# Model Definitions
behavior_model = BehaviorConstantVelocity(param_server)
execution_model = ExecutionModelInterpolate(param_server)
dynamic_model = SingleTrackModel(param_server)

# Map Definition
xodr_parser = XodrParser("modules/runtime/tests/data/Crossing8Course.xodr")
map_interface = MapInterface()
map_interface.SetOpenDriveMap(xodr_parser.map)
world.SetMap(map_interface)

# Agent Definition
agent_2d_shape = CarLimousine()
init_state = np.array([0, -15, -13, 3.14 * 5.0 / 4.0, 10 / 3.6])
agent_params = param_server.addChild("agent1")
goal_polygon = Polygon2d(
    [0, 0, 0],
    [Point2d(-1, -1),
     Point2d(-1, 1),
     Point2d(1, 1),
     Point2d(1, -1)])
goal_polygon = goal_polygon.Translate(Point2d(-191.789, -50.1725))

agent = Agent(
    init_state,
Beispiel #14
0
    def test_python_behavior_model(self):
        # World Definition
        scenario_param_file = "macro_actions_test.json"  # must be within examples params folder
        params = ParameterServer(filename=os.path.join(
            "modules/world/tests/params/", scenario_param_file))

        world = World(params)

        # Define two behavior models one python one standard c++ model
        behavior_model = PythonDistanceBehavior(params)
        execution_model = ExecutionModelInterpolate(params)
        dynamic_model = SingleTrackModel(params)

        behavior_model2 = BehaviorConstantVelocity(params)
        execution_model2 = ExecutionModelInterpolate(params)
        dynamic_model2 = SingleTrackModel(params)

        # Define the map interface and load a testing map
        map_interface = MapInterface()
        xodr_map = MakeXodrMapOneRoadTwoLanes()
        map_interface.SetOpenDriveMap(xodr_map)
        world.SetMap(map_interface)

        # Define the agent shapes
        agent_2d_shape = CarRectangle()
        init_state = np.array([0, 3, -5.25, 0, 20])

        # Define the goal definition for agents
        center_line = Line2d()
        center_line.AddPoint(Point2d(0.0, -1.75))
        center_line.AddPoint(Point2d(100.0, -1.75))

        max_lateral_dist = (0.4, 0.5)
        max_orientation_diff = (0.08, 0.1)
        velocity_range = (5.0, 20.0)
        goal_definition = GoalDefinitionStateLimitsFrenet(
            center_line, max_lateral_dist, max_orientation_diff,
            velocity_range)

        # define two agents with the different behavior models
        agent_params = params.AddChild("agent1")
        agent = Agent(init_state, behavior_model, dynamic_model,
                      execution_model, agent_2d_shape, agent_params,
                      goal_definition, map_interface)
        world.AddAgent(agent)

        init_state2 = np.array([0, 25, -5.25, 0, 15])
        agent2 = Agent(init_state2, behavior_model2, dynamic_model2,
                       execution_model2, agent_2d_shape, agent_params,
                       goal_definition, map_interface)
        world.AddAgent(agent2)

        # viewer
        viewer = MPViewer(params=params, use_world_bounds=True)

        # World Simulation
        sim_step_time = params["simulation"]["step_time",
                                             "Step-time in simulation", 0.2]
        sim_real_time_factor = params["simulation"][
            "real_time_factor", "execution in real-time or faster", 1]

        # Draw map
        video_renderer = VideoRenderer(renderer=viewer,
                                       world_step_time=sim_step_time)

        for _ in range(0, 20):
            world.Step(sim_step_time)
            viewer.clear()
            video_renderer.drawWorld(world)
            video_renderer.drawGoalDefinition(goal_definition, "red", 0.5,
                                              "red")
            time.sleep(sim_step_time / sim_real_time_factor)

        video_renderer.export_video(filename="./test_video_intermediate",
                                    remove_image_dir=True)
Beispiel #15
0
    def test_uct_single_agent(self):
        try:
            from bark.models.behavior import BehaviorUCTSingleAgentMacroActions
        except:
            print("Rerun with --define planner_uct=true")
            return
        # World Definition
        scenario_param_file = "macro_actions_test.json"  # must be within examples params folder
        params = ParameterServer(filename=os.path.join(
            "modules/world/tests/params/", scenario_param_file))

        world = World(params)

        # Model Definitions
        behavior_model = BehaviorUCTSingleAgentMacroActions(params)
        execution_model = ExecutionModelInterpolate(params)
        dynamic_model = SingleTrackModel(params)

        behavior_model2 = BehaviorConstantVelocity(params)
        execution_model2 = ExecutionModelInterpolate(params)
        dynamic_model2 = SingleTrackModel(params)

        # Map Definition
        map_interface = MapInterface()
        xodr_map = MakeXodrMapOneRoadTwoLanes()
        map_interface.SetOpenDriveMap(xodr_map)
        world.SetMap(map_interface)

        # agent_2d_shape = CarLimousine()
        agent_2d_shape = CarRectangle()
        init_state = np.array([0, 3, -5.25, 0, 20])
        agent_params = params.AddChild("agent1")

        # goal_polygon = Polygon2d(
        #     [1, 1, 0], [Point2d(0, 0), Point2d(0, 2), Point2d(2, 2), Point2d(2, 0)])
        # goal_definition = GoalDefinitionPolygon(goal_polygon)
        # goal_polygon = goal_polygon.Translate(Point2d(90, -2))

        center_line = Line2d()
        center_line.AddPoint(Point2d(0.0, -1.75))
        center_line.AddPoint(Point2d(100.0, -1.75))

        max_lateral_dist = (0.4, 0.5)
        max_orientation_diff = (0.08, 0.1)
        velocity_range = (5.0, 20.0)
        goal_definition = GoalDefinitionStateLimitsFrenet(
            center_line, max_lateral_dist, max_orientation_diff,
            velocity_range)

        agent = Agent(init_state, behavior_model, dynamic_model,
                      execution_model, agent_2d_shape, agent_params,
                      goal_definition, map_interface)
        world.AddAgent(agent)

        init_state2 = np.array([0, 25, -5.25, 0, 0])
        agent2 = Agent(init_state2, behavior_model2, dynamic_model2,
                       execution_model2, agent_2d_shape, agent_params,
                       goal_definition, map_interface)
        world.AddAgent(agent2)

        # viewer
        viewer = MPViewer(params=params, use_world_bounds=True)

        # World Simulation
        sim_step_time = params["simulation"]["step_time",
                                             "Step-time in simulation", 0.2]
        sim_real_time_factor = params["simulation"][
            "real_time_factor", "execution in real-time or faster", 1]

        # Draw map
        video_renderer = VideoRenderer(renderer=viewer,
                                       world_step_time=sim_step_time)

        for _ in range(0, 5):
            world.Step(sim_step_time)
            viewer.clear()
            video_renderer.drawWorld(world)
            video_renderer.drawGoalDefinition(goal_definition)
            time.sleep(sim_step_time / sim_real_time_factor)

        video_renderer.export_video(filename="./test_video_intermediate",
                                    remove_image_dir=True)
class Cosimulation:
    def __init__(self):
        self.carla_server = None
        self.carla_client = None
        self.carla_controller = None
        self.bark_viewer = None
        self.cosimulation_viewer = None
        self.launch_args = ["external/carla/CarlaUE4.sh", "-quality-level=Low"]

        # Bark parameter server
        self.param_server = ParameterServer(
            filename=BARK_PATH +
            "examples/params/od8_const_vel_one_agent.json")

        # World Definition
        self.bark_world = World(self.param_server)

        # Model Definitions
        self.behavior_model = BehaviorIDMClassic(self.param_server)
        self.execution_model = ExecutionModelInterpolate(self.param_server)
        self.dynamic_model = SingleTrackModel(self.param_server)

        # Map Definition
        xodr_parser = XodrParser(BARK_PATH + "modules/runtime/tests/data/" +
                                 BARK_MAP + ".xodr")
        self.map_interface = MapInterface()
        self.map_interface.SetOpenDriveMap(xodr_parser.map)
        self.bark_world.SetMap(self.map_interface)

        # Bark agent definition
        self.agent_2d_shape = CarLimousine()

        # use for converting carla actor id to bark agent id
        self.carla_2_bark_id = dict()
        # store the camera id attached to an agent
        self.carla_agents_cam = dict()

    def initialize_viewer(self):
        # Viewer of Bark simulation, the pygame surface will be extracted
        self.bark_viewer = PygameViewer(params=self.param_server,
                                        use_world_bounds=True,
                                        screen_dims=BARK_SCREEN_DIMS)

        # Viewer of cosimulation
        # Set the number of cameras to show both simulation side by side
        # windows from Bark simulation & camera image from Carla simulation
        self.cosimulation_viewer = CosimulationViewer(BARK_SCREEN_DIMS,
                                                      num_cameras=NUM_CAMERAS)

    def close(self):
        pg.display.quit()
        pg.quit()

        # kill the child of the subprocess
        # sometimes the socket is not killed, blocking the launch of carla
        # server
        os.system("fuser {}/tcp -k".format(CARLA_PORT))
        exit()

    def launch_carla_server(self):
        self.carla_server = subprocess.Popen(
            self.launch_args[0] if not CARLA_LOW_QUALITY else self.launch_args)
        # Wait for launching carla
        time.sleep(8)

    def connect_carla_server(self):
        """
        create a carla client and try connect to carla server
        """
        self.carla_client = CarlaClient()
        self.carla_client.connect(carla_map=CARLA_MAP,
                                  port=CARLA_PORT,
                                  timeout=10)
        self.carla_client.set_synchronous_mode(SYNCHRONOUS_MODE, DELTA_SECOND)
        self.carla_controller = Controller(self.carla_client)

    def spawn_npc_agents(self, num_agents):
        """spawn npc agents in both Carla and Bark

        Arguments:
            num_agents {int} -- number of agents to be spawned
        """

        for i in range(num_agents):
            carla_agent_id = self.carla_client.spawn_random_vehicle(
                num_retries=5)
            if carla_agent_id is not None:
                self.carla_client.set_autopilot(carla_agent_id, True)

                # spawn agent object in BARK
                agent_params = self.param_server.addChild("agent{}".format(i))
                bark_agent = Agent(
                    np.empty(5),
                    self.behavior_model,
                    self.dynamic_model,
                    self.execution_model,
                    self.agent_2d_shape,
                    agent_params,
                    None,  # goal_lane_id
                    self.map_interface)
                self.bark_world.AddAgent(bark_agent)
                self.carla_2_bark_id[carla_agent_id] = bark_agent.id

        if len(self.carla_2_bark_id) != num_agents:
            logging.warning(
                "Some agents cannot be spawned due to collision in the spawning location, {} agents are spawned"
                .format(len(self.carla_2_bark_id)))
        else:
            logging.info("{} agents spawned sucessfully.".format(num_agents))

    def initialize_camera_manager(self, surfaces):
        """create object for fetching image from carla

        Arguments:
            surfaces {list} -- list of pygame surfaces
        """
        self.cam_manager = CameraManager(surfaces,
                                         synchronous_mode=SYNCHRONOUS_MODE)

    def simulation_loop(self, carla_ego_id):
        bark_ego_id = self.carla_2_bark_id[carla_ego_id]

        self.bark_viewer.clear()
        self.cosimulation_viewer.tick()

        agent_state_map = self.carla_client.get_vehicles_state(
            self.carla_2_bark_id)
        self.bark_world.fillWorldFromCarla(0, agent_state_map)

        plan = self.bark_world.plan_agents(DELTA_SECOND,
                                           [bark_ego_id])[bark_ego_id]

        self.carla_controller.control(
            self.carla_client.get_actor(carla_ego_id), plan[-2][1:3],
            plan[-1][1:3], plan[-1][4], plan[-1][3])

        if SYNCHRONOUS_MODE:
            frame_id = self.carla_client.tick()
            self.cam_manager.fetch_image(frame_id)

        self.cosimulation_viewer.update_cameras(self.cam_manager.surfaces)

        # get agents' state in carla, and fill the state into bark
        carla_agent_states = self.carla_client.get_vehicles_state(
            self.carla_2_bark_id)
        self.bark_world.fillWorldFromCarla(DELTA_SECOND, carla_agent_states)

        self.bark_viewer.drawWorld(self.bark_world,
                                   show=False,
                                   eval_agent_ids=[bark_ego_id])
        self.cosimulation_viewer.update_bark(self.bark_viewer.screen_surface)

        self.cosimulation_viewer.show()