Exemple #1
0
    def _make_vehicles(self, n_vehicles: int = 10) -> None:
        """
        Populate a road with several vehicles on the highway and on the merging lane

        :return: the ego-vehicle
        """
        # Configure vehicles
        vehicle_type = utils.class_from_path(self.config["npc_vehicles_type"])
        vehicle_type.DISTANCE_WANTED = 7  # Low jam distance
        vehicle_type.COMFORT_ACC_MAX = 6
        vehicle_type.COMFORT_ACC_MIN = -3

        # Random vehicles
        simulation_steps = 3
        for t in range(n_vehicles - 1):
            self._spawn_vehicle(np.linspace(0, 80, n_vehicles)[t])
        for _ in range(simulation_steps):
            [(self.road.act(),
              self.road.step(1 / self.config["simulation_frequency"]))
             for _ in range(self.config["simulation_frequency"])]

        # Challenger vehicle
        self._spawn_vehicle(60,
                            spawn_probability=1,
                            go_straight=True,
                            position_deviation=0.1,
                            speed_deviation=0)

        # Controlled vehicles
        self.controlled_vehicles = []
        for ego_id in range(0, self.config["controlled_vehicles"]):
            ego_lane = self.road.network.get_lane(
                ("o{}".format(ego_id % 4), "ir{}".format(ego_id % 4), 0))
            destination = self.config["destination"] or "o" + str(
                self.np_random.randint(1, 4))
            ego_vehicle = self.action_type.vehicle_class(
                             self.road,
                             ego_lane.position(60 + 5*self.np_random.randn(1), 0),
                             speed=ego_lane.speed_limit,
                             heading=ego_lane.heading_at(60)) \
                .plan_route_to(destination)
            ego_vehicle.SPEED_MIN = 0
            ego_vehicle.SPEED_MAX = 9
            ego_vehicle.SPEED_COUNT = 3
            ego_vehicle.speed_index = ego_vehicle.speed_to_index(
                ego_lane.speed_limit)
            ego_vehicle.target_speed = ego_vehicle.index_to_speed(
                ego_vehicle.speed_index)

            self.road.vehicles.append(ego_vehicle)
            self.controlled_vehicles.append(ego_vehicle)
            for v in self.road.vehicles:  # Prevent early collisions
                if v is not ego_vehicle and np.linalg.norm(
                        v.position - ego_vehicle.position) < 20:
                    self.road.vehicles.remove(v)
Exemple #2
0
    def change_vehicles(self, vehicle_class_path: str) -> 'AbstractEnv':
        """
        Change the type of all vehicles on the road

        :param vehicle_class_path: The path of the class of behavior for other vehicles
                             Example: "highway_env.vehicle.behavior.IDMVehicle"
        :return: a new environment with modified behavior model for other vehicles
        """
        vehicle_class = utils.class_from_path(vehicle_class_path)

        env_copy = copy.deepcopy(self)
        vehicles = env_copy.road.vehicles
        for i, v in enumerate(vehicles):
            if v is not env_copy.vehicle:
                vehicles[i] = vehicle_class.create_from(v)
        return env_copy
Exemple #3
0
    def _create_vehicles(self, parked_probability: float = 0.75) -> None:
        """
        Create some new random vehicles of a given type, and add them on the road.

        :param parked_probability: probability that a spot is occupied
        """

        self.vehicle = self.action_type.vehicle_class(
            self.road, self.vehicle_starting,
            2 * np.pi * self.np_random.rand(), 0)
        self.road.vehicles.append(self.vehicle)

        goal_position = [
            self.np_random.choice([-2 * self.spots - 10, 2 * self.spots + 10]),
            0
        ]
        self.goal = Landmark(self.road, goal_position, heading=0)
        self.road.objects.append(self.goal)

        vehicles_type = utils.class_from_path(self.config["npc_vehicles_type"])
        for i in range(self.config["vehicles_count"]):
            is_parked = self.np_random.rand() <= parked_probability
            if not is_parked:
                # Just an effort to spread the vehicles out
                idx = self.np_random.randint(0, self.num_middle_lanes)
                longitudinal = (i * 5) - (self.x_range /
                                          8) * self.np_random.randint(-1, 1)
                self.road.vehicles.append(
                    vehicles_type.make_on_lane(self.road, ("d", "e", idx),
                                               longitudinal,
                                               speed=2))
            else:
                lane = ("a", "b",
                        i) if self.np_random.rand() >= 0.5 else ("b", "c", i)
                self.road.vehicles.append(
                    Vehicle.make_on_lane(self.road, lane, 4, speed=0))

        for v in self.road.vehicles:  # Prevent early collisions
            if v is not self.vehicle and np.linalg.norm(
                    v.position - self.vehicle.position) < 20:
                self.road.vehicles.remove(v)
    def _reset_from_inner_backup(self) -> None:
        """Create some new random vehicles of a given type, and add them on the road."""
        
        self.controlled_vehicles = []
        train_config=self._inner_controlled_vechiles_backup_config[self._inner_backup_backtrack_step]
        npc_config=self._inner_other_vechiles_backup_config[self._inner_backup_backtrack_step]
        print(f"train_config = {train_config}")
        print(f"npc_config = {npc_config}")

        for _ in range(self.config["controlled_vehicles"]):
            vehicle = self.action_type.vehicle_class(self.road, train_config[_]["trained_vehicle_position"], train_config[_]["trained_vehicle_heading"], train_config[_]["trained_vehicle_speed"], ("0","1", train_config[_]["trained_vehicle_target_lane_index"]), train_config[_]["trained_vehicle_target_speed"])
            
            self.controlled_vehicles.append(vehicle)
            self.road.vehicles.append(vehicle)
            
        vehicles_type = utils.class_from_path(self.config["npc_vehicles_type"])
        self.other_vehicles = []
        for _ in range(self.config["vehicles_count"]):
            other_vehicle = vehicles_type(road=self.road, position=npc_config[_]["npc_vehicle_position"], heading=npc_config[_]["npc_vehicle_heading"], speed=npc_config[_]["npc_vehicle_speed"], target_lane_index=("0","1", npc_config[_]["npc_vehicle_target_lane_index"]), target_speed=npc_config[_]["npc_vehicle_target_speed"], timer= npc_config[_]["npc_vehicle_timer"])
            self.other_vehicles.append(other_vehicle)
            self.road.vehicles.append(other_vehicle)
Exemple #5
0
    def _create_vehicles(self) -> None:
        """Create some new random vehicles of a given type, and add them on the road."""
        # the number of agent with initialized postions overlapping with each other
        self.controlled_vehicles = []
        number_overlap = 0
        for i in range(self.config["controlled_vehicles"]):

            #for i in range(self.config["n_defenders"]):
            # vehicle = self.action_type.vehicle_class.create_random(self.road,
            #                                                        speed=25,
            #                                                        lane_id=self.config["initial_lane_id"],
            #                                                        spacing=self.config["ego_spacing"],
            #                                                        )
            default_spacing = 12.5  # 0.5 * speed
            longitude_position = 40 + 5 * np.random.randint(1)
            initial_lane_idx = random.choice(
                [4 * i for i in range(self.config["lanes_count"])])
            # To separate cars in different places to avoid collision
            for vehicle_ in self.controlled_vehicles:
                if abs(
                        longitude_position - vehicle_.position[0]
                ) < 5 and initial_lane_idx == 4 * vehicle_.lane_index[2]:
                    longitude_position = longitude_position - (
                        number_overlap + 1) * default_spacing
                    number_overlap = number_overlap + 1

            vehicle = self.action_type.vehicle_class(
                road=self.road,
                position=[longitude_position, initial_lane_idx],
                heading=0,
                speed=25)

            self.controlled_vehicles.append(vehicle)
            self.road.vehicles.append(vehicle)

        vehicles_type = utils.class_from_path(self.config["npc_vehicles_type"])
        for _ in range(self.config["vehicles_count"]):
            vehicle = vehicles_type.create_random(
                self.road, spacing=1 / self.config["vehicles_density"])
            self.road.vehicles.append(vehicle)
Exemple #6
0
    def _make_vehicles(self) -> None:
        """
        Populate a road with several vehicles on the road

        :return: the ego-vehicle
        """
        road = self.road
        ego_vehicle = self.action_type.vehicle_class(road,
                                                     road.network.get_lane(
                                                         ("a", "b",
                                                          1)).position(30, 0),
                                                     speed=30)
        road.vehicles.append(ego_vehicle)
        self.vehicle = ego_vehicle

        vehicles_type = utils.class_from_path(self.config["npc_vehicles_type"])
        for i in range(3):
            self.road.vehicles.append(
                vehicles_type(
                    road,
                    position=road.network.get_lane(("a", "b", 1)).position(
                        70 + 40 * i + 10 * self.np_random.randn(), 0),
                    heading=road.network.get_lane(
                        ("a", "b", 1)).heading_at(70 + 40 * i),
                    speed=24 + 2 * self.np_random.randn(),
                    enable_lane_change=False))
        for i in range(2):
            v = vehicles_type(
                road,
                position=road.network.get_lane(
                    ("b", "a",
                     0)).position(200 + 100 * i + 10 * self.np_random.randn(),
                                  0),
                heading=road.network.get_lane(
                    ("b", "a", 0)).heading_at(200 + 100 * i),
                speed=20 + 5 * self.np_random.randn(),
                enable_lane_change=False)
            v.target_lane_index = ("b", "a", 0)
            self.road.vehicles.append(v)
    def _create_vehicles(self) -> None:
        """Create some new random vehicles of a given type, and add them on the road."""
        self.controlled_vehicles = []

        for i in range(self.config["controlled_vehicles"]):

            vehicle = self.action_type.vehicle_class.create_random(self.road,
                                                                   speed=25,
                                                                   lane_id=self.config["initial_lane_id"],
                                                                   spacing=self.config["ego_spacing"],
                                                                   )
            self.controlled_vehicles.append(vehicle)
            self.road.vehicles.append(vehicle)


        vehicles_type = utils.class_from_path(self.config["npc_vehicles_type"])
        self.other_vehicles = []

        for _ in range(self.config["vehicles_count"]):
            other_vehicle = vehicles_type.create_random(self.road, spacing=1 / self.config["vehicles_density"])
            self.other_vehicles.append(other_vehicle)
            self.road.vehicles.append(other_vehicle)
Exemple #8
0
    def _make_vehicles(self) -> None:
        """
        Populate a road with several vehicles on the highway and on the merging lane, as well as an ego-vehicle.

        :return: the ego-vehicle
        """
        road = self.road
        ego_vehicle = self.action_type.vehicle_class(road,
                                                     road.network.get_lane(
                                                         ("a", "b",
                                                          1)).position(30, 0),
                                                     speed=30)
        road.vehicles.append(ego_vehicle)

        npc_vehicles_type = utils.class_from_path(
            self.config["npc_vehicles_type"])
        road.vehicles.append(
            npc_vehicles_type(road,
                              road.network.get_lane(
                                  ("a", "b", 0)).position(90, 0),
                              speed=29))
        road.vehicles.append(
            npc_vehicles_type(road,
                              road.network.get_lane(
                                  ("a", "b", 1)).position(70, 0),
                              speed=31))
        road.vehicles.append(
            npc_vehicles_type(road,
                              road.network.get_lane(
                                  ("a", "b", 0)).position(5, 0),
                              speed=31.5))

        merging_v = npc_vehicles_type(road,
                                      road.network.get_lane(
                                          ("j", "k", 0)).position(110, 0),
                                      speed=20)
        merging_v.target_speed = 30
        road.vehicles.append(merging_v)
        self.vehicle = ego_vehicle
Exemple #9
0
    def _spawn_vehicle(self,
                       longitudinal: float = 0,
                       position_deviation: float = 1.,
                       speed_deviation: float = 1.,
                       spawn_probability: float = 0.6,
                       go_straight: bool = False) -> None:
        if self.np_random.rand() > spawn_probability:
            return

        route = self.np_random.choice(range(4), size=2, replace=False)
        route[1] = (route[0] + 2) % 4 if go_straight else route[1]
        vehicle_type = utils.class_from_path(self.config["npc_vehicles_type"])
        vehicle = vehicle_type.make_on_lane(
            self.road, ("o" + str(route[0]), "ir" + str(route[0]), 0),
            longitudinal=longitudinal + 5 +
            self.np_random.randn() * position_deviation,
            speed=8 + self.np_random.randn() * speed_deviation)
        for v in self.road.vehicles:
            if np.linalg.norm(v.position - vehicle.position) < 15:
                return
        vehicle.plan_route_to("o" + str(route[1]))
        vehicle.randomize_behavior()
        self.road.vehicles.append(vehicle)
        return vehicle
Exemple #10
0
    def _make_vehicles(self) -> None:
        """
        Populate a road with several vehicles on the highway and on the merging lane, as well as an ego-vehicle.

        :return: the ego-vehicle
        """
        position_deviation = 2
        speed_deviation = 2

        # Ego-vehicle
        ego_lane = self.road.network.get_lane(("ser", "ses", 0))
        ego_vehicle = self.action_type.vehicle_class(
            self.road,
            ego_lane.position(125, 0),
            speed=8,
            heading=ego_lane.heading_at(140))
        try:
            ego_vehicle.plan_route_to("nxs")
        except AttributeError:
            pass
        MDPVehicle.SPEED_MIN = 0
        MDPVehicle.SPEED_MAX = 16
        MDPVehicle.SPEED_COUNT = 3
        self.road.vehicles.append(ego_vehicle)
        self.vehicle = ego_vehicle

        # Incoming vehicle
        destinations = ["exr", "sxr", "nxr"]
        npc_vehicles_type = utils.class_from_path(
            self.config["npc_vehicles_type"])
        vehicle = npc_vehicles_type.make_on_lane(
            self.road, ("we", "sx", 1),
            longitudinal=5 + self.np_random.randn() * position_deviation,
            speed=16 + self.np_random.randn() * speed_deviation)

        if self.config["incoming_vehicle_destination"] is not None:
            destination = destinations[
                self.config["incoming_vehicle_destination"]]
        else:
            destination = self.np_random.choice(destinations)
        vehicle.plan_route_to(destination)
        vehicle.randomize_behavior()
        self.road.vehicles.append(vehicle)

        # Other vehicles
        for i in list(range(1, 2)) + list(range(-1, 0)):
            vehicle = npc_vehicles_type.make_on_lane(
                self.road, ("we", "sx", 0),
                longitudinal=20 * i +
                self.np_random.randn() * position_deviation,
                speed=16 + self.np_random.randn() * speed_deviation)
            vehicle.plan_route_to(self.np_random.choice(destinations))
            vehicle.randomize_behavior()
            self.road.vehicles.append(vehicle)

        # Entering vehicle
        vehicle = npc_vehicles_type.make_on_lane(
            self.road, ("eer", "ees", 0),
            longitudinal=50 + self.np_random.randn() * position_deviation,
            speed=16 + self.np_random.randn() * speed_deviation)
        vehicle.plan_route_to(self.np_random.choice(destinations))
        vehicle.randomize_behavior()
        self.road.vehicles.append(vehicle)