Esempio n. 1
0
    def test_map_highway(self):
        xodr_parser = XodrParser(
            os.path.join(os.path.dirname(__file__),
                         "data/city_highway_straight.xodr"))

        map_interface = MapInterface()
        map_interface.SetOpenDriveMap(xodr_parser.map)
Esempio n. 2
0
    def test_number_of_agents(self):
        # World Definition
        params = ParameterServer()
        world = World(params)

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

        behavior_model2 = BehaviorConstantAcceleration(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()
        init_state = np.array([0, 13, -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, 16, -1.75, 0, 5])
        agent2 = Agent(init_state2, behavior_model2, dynamic_model2,
                       execution_model2, agent_2d_shape, agent_params,
                       GoalDefinitionPolygon(goal_polygon), map_interface)
        world.AddAgent(agent2)

        evaluator = EvaluatorNumberOfAgents(agent.id)
        world.AddEvaluator("num_agents", evaluator)

        info = world.Evaluate()
        self.assertEqual(info["num_agents"], len(world.agents))
        # do it once more
        self.assertEqual(info["num_agents"], len(world.agents))

        world.RemoveAgentById(agent2.id)
        info = world.Evaluate()
        # evaluator should still hold two
        self.assertNotEqual(info["num_agents"], len(world.agents))
        self.assertEqual(info["num_agents"], 2)

        world.Step(0.1)
        info = world.Evaluate()
        # evaluator should still hold two
        self.assertEqual(info["num_agents"], 2)
Esempio n. 3
0
    def test_map_DR_DEU_Merging_MT_v01_shifted(self):
        xodr_parser = XodrParser(
            os.path.join(os.path.dirname(__file__),
                         "data/DR_DEU_Merging_MT_v01_shifted.xodr"))

        map_interface = MapInterface()
        map_interface.SetOpenDriveMap(xodr_parser.map)
Esempio n. 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)
Esempio n. 5
0
def make_initial_world(primitives):
    # must be within examples params folder
    params = ParameterServer()
    world = World(params)

    # Define two behavior models
    behavior_model = BehaviorMPContinuousActions(params)
    primitive_mapping = {}
    for prim in primitives:
        idx = behavior_model.AddMotionPrimitive(
            np.array(prim))  # adding action
        primitive_mapping[idx] = prim

    behavior_model.ActionToBehavior(0)  # setting initial action

    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)

    return world
Esempio n. 6
0
 def setUp(self):
     params = ParameterServer()
     self.params = params
     csvfile = os.path.join(
         os.path.dirname(__file__),
         "../environments/blueprints/single_lane/base_map_lanes_guerickestr_short_assymetric_48.csv"
     )
     print(csvfile)
     self.map_interface = MapInterface()
     self.map_interface.SetCsvMap(csvfile, 692000, 5.339e+06)
Esempio n. 7
0
    def test_gap_distance_front(self):
        # World Definition
        params = ParameterServer()
        world = World(params)

        gap = 10

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

        behavior_model2 = BehaviorConstantAcceleration(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()
        init_state = np.array([0, 13, -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, 13 + gap, -1.75, 0, 5])
        agent2 = Agent(init_state2, behavior_model2, dynamic_model2,
                       execution_model2, agent_2d_shape, agent_params,
                       GoalDefinitionPolygon(goal_polygon), map_interface)
        world.AddAgent(agent2)

        world.Step(0.1)

        evaluator = EvaluatorGapDistanceFront(agent.id)
        world.AddEvaluator("gap", evaluator)

        info = world.Evaluate()
        self.assertAlmostEqual(info["gap"],
                               gap - agent_2d_shape.front_dist -
                               agent_2d_shape.rear_dist,
                               places=4)
Esempio n. 8
0
    def CreateMapInterface(self, map_file_name):
        map_file_load_test = Path(map_file_name)
        if map_file_load_test.is_file():
            xodr_parser = XodrParser(map_file_name)
        else:
            objects_found = sorted(Path().rglob(map_file_name))
            if len(objects_found) == 0:
                raise ValueError("No Map found")
            elif len(objects_found) > 1:
                raise ValueError("Multiple Maps found")
            else:
                xodr_parser = XodrParser(objects_found[0].as_posix())

        map_interface = MapInterface()
        map_interface.SetOpenDriveMap(xodr_parser.map)
        self._map_interface = map_interface
Esempio n. 9
0
    def test_world(self):
        # create agent
        params = ParameterServer()
        behavior = BehaviorConstantAcceleration(params)
        execution = ExecutionModelInterpolate(params)
        dynamic = SingleTrackModel(params)
        shape = Polygon2d([1.25, 1, 0], [
            Point2d(0, 0),
            Point2d(0, 2),
            Point2d(4, 2),
            Point2d(4, 0),
            Point2d(0, 0)
        ])
        init_state = np.array([0, 0, 0, 0, 5])
        agent = Agent(init_state, behavior, dynamic, execution, shape,
                      params.AddChild("agent"))
        road_map = OpenDriveMap()
        newXodrRoad = XodrRoad()
        newXodrRoad.id = 1
        newXodrRoad.name = "Autobahn A9"
        newPlanView = PlanView()
        newPlanView.AddLine(Point2d(0, 0), 1.57079632679, 10)
        newXodrRoad.plan_view = newPlanView
        line = newXodrRoad.plan_view.GetReferenceLine().ToArray()
        p = Point2d(line[-1][0], line[-1][1])
        newXodrRoad.plan_view.AddSpiral(p, 1.57079632679, 50.0, 0.0, 0.3, 0.4)
        line = newXodrRoad.plan_view.GetReferenceLine()
        lane_section = XodrLaneSection(0)
        lane = XodrLane()
        lane.line = line
        lane_section.AddLane(lane)
        newXodrRoad.AddLaneSection(lane_section)
        road_map.AddRoad(newXodrRoad)

        r = Roadgraph()
        map_interface = MapInterface()
        map_interface.SetOpenDriveMap(road_map)
        map_interface.SetRoadgraph(r)
        world = World(params)
        world.AddAgent(agent)
Esempio n. 10
0
    def test_dr_chn_merging(self):
        # threeway_intersection
        xodr_parser = XodrParser(
            os.path.join(
                os.path.dirname(__file__),
                "../../../runtime/tests/data/DR_CHN_Merging_ZS_partial_v02.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.drawPolygon2d(road_corridor.lane_corridors[2].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.lane_corridors[2].polygon.Valid())
        self.assertTrue(road_corridor.polygon.Valid())
Esempio n. 11
0
    def test_curved_road(self):
        params = ParameterServer()
        world = World(params)

        xodr_map = MakeXodrMapCurved(50, 0.1)

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

        roads = [100]
        driving_direction = XodrDrivingDirection.forward
        map_interface.GenerateRoadCorridor(roads, driving_direction)
        road_corr = map_interface.GetRoadCorridor(roads, driving_direction)

        viewer = MPViewer(params=params, use_world_bounds=True)
        viewer.drawWorld(world)
        viewer.drawRoadCorridor(road_corr)
        #viewer.show(block=True)

        # if this is not here, the second unit test is not executed (maybe parsing takes too long?)
        time.sleep(1)
Esempio n. 12
0
    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)

        # if this is not here, the second unit test is not executed (maybe parsing takes too long?)
        time.sleep(2)
Esempio n. 13
0
    def test_between_lanes(self):
        xodr_parser = XodrParser(
            os.path.join(
                os.path.dirname(__file__),
                "../../../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(2, -92.55029)
        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 = -92.55029
        i = 1.817
        lane_sw = map_interface.FindLane(Point2d(i, lng_coord))
        assert lane_sw != None
        prev = lane_sw.lane_id
        prev_i = i
        while (i < 4.817):
            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!")
Esempio n. 14
0
    def test_road_corridor_forward(self):
        xodr_parser = XodrParser(
            os.path.join(
                os.path.dirname(__file__),
                "../../../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
Esempio n. 15
0
    def test_dr_deu_merging_centered(self):
        # threeway_intersection
        xodr_parser = XodrParser(
            os.path.join(
                os.path.dirname(__file__),
                "../../../runtime/tests/data/DR_DEU_Merging_MT_v01_centered.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())

        tol = 0.2
        center_line_array = road_corridor.lane_corridors[
            0].center_line.ToArray()
        left_boundary_array = road_corridor.lane_corridors[
            0].left_boundary.ToArray()
        right_boundary_array = road_corridor.lane_corridors[
            0].right_boundary.ToArray()

        # beginning of left lane
        self.assertAlmostEquals(center_line_array[0, 0], 106.4, 1)
        self.assertAlmostEquals(center_line_array[0, 1], 103.47, 1)
        self.assertAlmostEquals(
            Distance(
                Point2d(left_boundary_array[0, 0], left_boundary_array[0, 1]),
                Point2d(right_boundary_array[0, 0],
                        right_boundary_array[0, 1])), 2.8, 1)

        # end of left lane
        self.assertAlmostEquals(center_line_array[-1, 0], -18.15, 1)
        self.assertAlmostEquals(center_line_array[-1, 1], 109.0, 1)
        self.assertAlmostEquals(
            Distance(
                Point2d(left_boundary_array[-1, 0], left_boundary_array[-1,
                                                                        1]),
                Point2d(right_boundary_array[-1, 0],
                        right_boundary_array[-1, 1])), 2.63, 1)
Esempio n. 16
0
    def test_evaluator_drivable_area(self):
        # World Definition
        params = ParameterServer()
        world = World(params)

        # Model Definitions
        behavior_model = BehaviorConstantAcceleration(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)
Esempio n. 17
0
class PyEnvironmentTests(unittest.TestCase):
    def setUp(self):
        params = ParameterServer()
        self.params = params
        csvfile = os.path.join(
            os.path.dirname(__file__),
            "../environments/blueprints/single_lane/base_map_lanes_guerickestr_short_assymetric_48.csv"
        )
        print(csvfile)
        self.map_interface = MapInterface()
        self.map_interface.SetCsvMap(csvfile, 692000, 5.339e+06)

    def test_create_environment(self):
        map_interface = self.map_interface
        observer = NearestAgentsObserver()
        env = ExternalRuntime(map_interface=map_interface,
                              observer=observer,
                              params=self.params)
        self.assertTrue(isinstance(env.observation_space, gym.spaces.box.Box))

    def create_runtime_and_setup_empty_world(self, params):
        map_interface = self.map_interface
        observer = NearestAgentsObserver()
        env = ExternalRuntime(map_interface=map_interface,
                              observer=observer,
                              params=params,
                              viewer=viewer)
        env.setupWorld()
        return env

    def test_setup_world(self):
        params = ParameterServer()
        env = self.create_runtime_and_setup_empty_world(params)
        self.assertTrue(isinstance(env._world, World))

    def test_add_ego_agent(self):
        params = ParameterServer()
        env = self.create_runtime_and_setup_empty_world(params)
        state = np.array([0, 0, 0, 0, 0, 0])
        goal_line = Line2d(np.array([[0., 0.], [1., 1.]]))
        env.addEgoAgent(state, goal_line)
        self.assertTrue(np.array_equal(env.ego_agent.state, state))

    def test_add_obstacle(self):
        params = ParameterServer()
        env = self.create_runtime_and_setup_empty_world(params)
        l = 4
        w = 2
        traj = np.array([[0, 0, 0, 0, 0]])
        obst_id = env.addObstacle(traj, l, w)
        self.assertTrue(
            np.array_equal(env._world.agents[obst_id].state, traj[0]))
        env.clearAgents()
        self.assertEqual(len(env._world.agents), 0)

    def test_create_sac_agent(self):
        params = ParameterServer()
        map_interface = self.map_interface
        observer = NearestAgentsObserver()
        env = ExternalRuntime(map_interface=map_interface,
                              observer=observer,
                              params=params)
        env.ml_behavior = BehaviorContinuousML(params)
        sac_agent = BehaviorSACAgent(environment=env, params=params)
        env.ml_behavior = sac_agent
        self.assertTrue(isinstance(env.ml_behavior, BehaviorSACAgent))

    def test_generate_ego_trajectory(self):
        params = ParameterServer()
        env = self.create_runtime_and_setup_empty_world(params)
        sac_agent = BehaviorSACAgent(environment=env, params=params)
        env.ml_behavior = sac_agent

        # add ego
        state = np.array([0, 0, 0, 0, 0, 0])
        goal_line = Line2d(np.array([[0., 0.], [1., 1.]]))
        env.addEgoAgent(state, goal_line)

        N = 10
        state_traj, action_traj = env.generateTrajectory(0.2, N)
        env._viewer.drawTrajectory(state_traj)
        env.render()
        self.assertEqual(len(state_traj), N)

    def test_generate_ego_trajectory_with_IDM(self):
        params = ParameterServer()
        env = self.create_runtime_and_setup_empty_world(params)
        env.ml_behavior = BehaviorIDMClassic(params)

        # add ego
        state = np.array([0, 0, 0, 0, 0])
        goal_line = Line2d(np.array([[0., 0.], [1., 1.]]))
        env.addEgoAgent(state, goal_line)

        N = 10
        state_traj, action_traj = env.generateTrajectory(0.2, N)
        env._viewer.drawTrajectory(state_traj)
        env.render()
        self.assertEqual(len(state_traj), N)

    def test_append_to_scenario_history(self):
        params = ParameterServer()
        env = self.create_runtime_and_setup_empty_world(params)

        # behavior_model = BehaviorSACAgent(environment=env, params=params)
        behavior_model = bark.core.models.behavior.BehaviorConstantAcceleration(
            params)

        env.ml_behavior = behavior_model
        state = np.array([0, 0, 0, 0, 0])
        goal_line = Line2d(np.array([[0., 0.], [1., 1.]]))
        env.addEgoAgent(state, goal_line)
        scenario = env.getScenarioForSerialization()
        self.assertTrue(isinstance(scenario, Scenario))
Esempio n. 18
0
 def load_map(map):
     xodr_parser = XodrParser(map)
     map_interface = MapInterface()
     map_interface.SetOpenDriveMap(xodr_parser.map)
     return map_interface
Esempio n. 19
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(
            os.path.dirname(__file__), "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 = BehaviorConstantAcceleration(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)
Esempio n. 20
0
    def test_uct_single_agent(self):
        try:
            from bark.core.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(
            os.path.dirname(__file__), "params/", scenario_param_file))

        world = World(params)

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

        behavior_model2 = BehaviorConstantAcceleration(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)
Esempio n. 21
0
# Name and Output Directory
# CHANGE THIS #
map_name = "left_turn_rural"
output_dir = "/tmp/" + map_name

# Map Definition
xodr_parser = XodrParser("bark/runtime/tests/data/" + map_name + ".xodr")

if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# 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)
viewer.drawWorld(world)
viewer.saveFig(output_dir + "/" + "world_plain.png")

color_triplet_gray = (0.7, 0.7, 0.7)

# Open Drive Elements (XodrRoads, XodrLane Sections, XodrLanes)
# for idx_r, road in open_drive_map.GetRoads().items():
#   viewer.drawWorld(world)
#   viewer.drawXodrRoad(road)
Esempio n. 22
0
    def test_three_way_intersection(self):
        # threeway_intersection
        xodr_parser = XodrParser(
            os.path.join(
                os.path.dirname(__file__),
                "../../../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)
        self.assertTrue(rc.polygon.Valid())
        rc = GenerateRoadCorridor(map_interface, comb_all[1])
        self.assertEqual(rc.road_ids, [0, 5, 2])
        self.assertEqual(len(rc.lane_corridors), 3)
        self.assertTrue(rc.polygon.Valid())
        rc = GenerateRoadCorridor(map_interface, comb_all[2])
        self.assertEqual(rc.road_ids, [1, 10, 0])
        self.assertEqual(len(rc.lane_corridors), 3)
        self.assertTrue(rc.polygon.Valid())
        rc = GenerateRoadCorridor(map_interface, comb_all[3])
        self.assertEqual(rc.road_ids, [2, 6, 1])
        self.assertEqual(len(rc.lane_corridors), 3)
        self.assertTrue(rc.polygon.Valid())
        rc = GenerateRoadCorridor(map_interface, comb_all[4])
        self.assertEqual(rc.road_ids, [2, 4, 0])
        self.assertEqual(len(rc.lane_corridors), 3)
        self.assertTrue(rc.polygon.Valid())