Ejemplo n.º 1
0
    def _mission2trap(self, road_network, mission, default_zone_dist=6):
        out_config = None
        if not (hasattr(mission, "start") and hasattr(mission, "goal")):
            raise ValueError(f"Value {mission} is not a mission!")

        activation_delay = mission.start_time
        patience = mission.entry_tactic.wait_to_hijack_limit_s
        zone = mission.entry_tactic.zone

        if not zone:
            n_lane = road_network.nearest_lane(mission.start.position)

            start_edge_id = n_lane.getEdge().getID()
            start_lane = n_lane.getIndex()
            lane_length = n_lane.getLength()
            lane_speed = n_lane.getSpeed()

            start_pos = mission.start.position
            vehicle_offset_into_lane = road_network.offset_into_lane(
                n_lane, (start_pos[0], start_pos[1]))
            vehicle_offset_into_lane = clip(vehicle_offset_into_lane, 1e-6,
                                            lane_length - 1e-6)

            drive_distance = lane_speed * default_zone_dist

            start_offset_in_lane = vehicle_offset_into_lane - drive_distance
            start_offset_in_lane = clip(start_offset_in_lane, 1e-6,
                                        lane_length - 1e-6)
            length = max(1e-6, vehicle_offset_into_lane - start_offset_in_lane)

            zone = MapZone(
                start=(start_edge_id, start_lane, start_offset_in_lane),
                length=length,
                n_lanes=1,
            )

        out_config = TrapConfig(
            zone=zone,
            # TODO: Make reactivation and activation delay configurable through
            #   scenario studio
            reactivation_time=-1,
            activation_delay=activation_delay,
            patience=patience,
            mission=mission,
            exclusion_prefixes=mission.entry_tactic.exclusion_prefixes,
        )

        return out_config
Ejemplo n.º 2
0
def generate_left_turn_missions(
    mission,
    route_distributions,
    route_lanes,
    speed,
    map_dir,
    level_name,
    save_dir,
    stopwatcher_behavior,
    stopwatcher_route,
    seed,
    intersection_name,
    traffic_density,
):
    # dont worry about these seeds, theyre used by sumo
    sumo_seed = random.choice([0, 1, 2, 3, 4])
    stopwatcher_info = None
    stopwatcher_added = False
    if stopwatcher_behavior:
        stopwatcher_info = {
            "behavior": stopwatcher_behavior,
            "direction": get_direction(stopwatcher_route),
        }

    random.seed(seed)
    np.random.seed(seed)
    all_flows = []
    metadata = {"routes": {}, "total_vehicles": 0, "stopwatcher": None}

    scenario = save_dir + f"-flow-{seed}"

    # Remove old traffic route if it exists(otherwise, won't update to new flows)
    if os.path.exists(f"{scenario}/traffic/all.rou.xml"):
        shutil.rmtree(scenario)

    for route_key, route_info in route_distributions["routes"].items():
        # to skip None
        if route_info:
            if stopwatcher_behavior:  # put the ego on the side road
                ego_start_lane, ego_end_lane = 0, 0
                mission_start, mission_end = "south-side", "dead-end"
                ego_start_pos, ego_end_pos = 100, 5
                ego_num_lanes = 1
            else:
                mission_start, mission_end = mission["start"], mission["end"]
                ego_start_lane, ego_end_lane = (
                    route_lanes[mission_start] - 1,
                    route_lanes[mission_end] - 1,
                )
                ego_start_pos, ego_end_pos = (
                    random.randint(50, 120),
                    random.randint(50, 150),
                )
                ego_num_lanes = route_lanes[mission_start]

            ego_route = Route(
                begin=(f"edge-{mission_start}", ego_start_lane, ego_start_pos),
                end=(f"edge-{mission_end}", ego_end_lane, ego_end_pos),
            )
            flows, vehicles_log_info = generate_social_vehicles(
                ego_start_lane=ego_start_lane,
                route_distribution=route_info["distribution"],
                begin_time_init=route_info["begin_time_init"],
                num_vehicles=route_info["vehicles"],
                route_direction=get_direction(route_key),
                route_lanes=route_lanes,
                route_has_turn=route_info["has_turn"],
                start_end_on_different_lanes_probability=route_info[
                    "start_end_on_different_lanes_probability"],
                deadlock_optimization=route_info["deadlock_optimization"],
                stopwatcher_info=stopwatcher_info,
            )
            if (stopwatcher_behavior and len(flows) > 0 and
                    get_direction(route_key) == stopwatcher_info["direction"]):
                stopwatcher_added = True
                print(
                    f'stop watcher added to {get_direction(route_key)} flows among {route_info["vehicles"]} vehicles!'
                )
            all_flows.extend(flows)
            metadata["routes"][route_key] = vehicles_log_info
    scenario = save_dir + f"-flow-{seed}"
    if stopwatcher_behavior:
        if not stopwatcher_added and level_name != "no-traffic":
            print(
                f'There was no matching flows for stopwatcher, adding it to {stopwatcher_info["direction"]}.'
            )
            # vehicles_log_info[f'stopwatcher_{stopwatcher_info["behavior"]}']["count"] += 1
            all_flows.append(
                generate_stopwatcher(
                    stopwatcher_behavior=stopwatcher_info["behavior"],
                    stopwatcher_route=stopwatcher_info["direction"],
                    start_lane_id=0,
                    end_lane_id=0,
                ))
        scenario += f"-stopwatcher-{stopwatcher_info['behavior']}"

    copy_map_files(scenario, map_dir, speed)
    if stopwatcher_behavior or "ego_hijacking_params" not in route_distributions:
        gen_missions(scenario, [Mission(ego_route)])
    else:
        speed_m_per_s = float("".join(filter(str.isdigit, speed))) * 5.0 / 18.0
        hijacking_params = route_distributions["ego_hijacking_params"]
        zone_range = hijacking_params["zone_range"]
        waiting_time = hijacking_params["wait_to_hijack_limit_s"]
        start_time = hijacking_params["start_time"]

        if start_time == "default":
            start_time = random.randint((LANE_LENGTH // speed_m_per_s), 60)
        gen_missions(
            scenario,
            [
                Mission(
                    ego_route,
                    # optional: control hijacking time, place, and emission.
                    start_time=
                    start_time,  # when to start hijacking (might start later)
                    entry_tactic=TrapEntryTactic(
                        wait_to_hijack_limit_s=
                        waiting_time,  # when to give up on hijacking and start emitting a social vehicle instead
                        zone=MapZone(
                            start=(
                                f'edge-{mission["start"]}',
                                0,
                                ego_start_pos + zone_range[0],
                            ),
                            length=zone_range[1],
                            n_lanes=route_lanes[mission["start"]],
                        ),  # area to hijack
                        exclusion_prefixes=tuple(
                        ),  # vehicles to be excluded (check vehicle ids)
                    ),
                ),
            ],
        )

    traffic = Traffic(flows=all_flows)
    gen_traffic(scenario, traffic, name=f"all", seed=sumo_seed)
    # patch: remove route files from traffic folder to make intersection empty
    if traffic_density == "no-traffic":

        os.remove(f"{scenario}/traffic/all.rou.xml")
    if stopwatcher_behavior:
        metadata["stopwatcher"] = {
            "direction": stopwatcher_info["direction"],
            "behavior": stopwatcher_info["behavior"],
        }
    metadata["intersection"] = {
        "type": intersection_name[-1],
        "name": intersection_name,
    }
    metadata["total_vehicles"] = len(all_flows)
    metadata["seed"] = seed
    metadata["flow_id"] = f"flow_{seed}"
    with open(f"{scenario}/metadata.json", "w") as log:
        json.dump(metadata, log)
Ejemplo n.º 3
0
    TrapEntryTactic,
    MapZone,
)

scenario = os.path.dirname(os.path.realpath(__file__))

gen_missions(
    scenario,
    [
        Mission(
            Route(begin=("edge-west-WE", 0, 10), end=("edge-south-NS", 0, 40)),
            entry_tactic=TrapEntryTactic(
                wait_to_hijack_limit_s=3,
                zone=MapZone(
                    start=("edge-west-WE", 0, 5),
                    length=30,
                    n_lanes=1,
                ),
            ),
        ),
        Mission(
            Route(begin=("edge-west-WE", 0, 10), end=("edge-west-WE", 0, 25)),
            entry_tactic=TrapEntryTactic(
                wait_to_hijack_limit_s=3,
                zone=MapZone(
                    start=("edge-west-WE", 0, 5),
                    length=30,
                    n_lanes=1,
                ),
            ),
        ),
Ejemplo n.º 4
0
def generate_left_turn_missions(
    missions,
    shuffle_missions,
    route_distributions,
    route_lanes,
    speed,
    map_dir,
    level_name,
    save_dir,
    stopwatcher_behavior,
    stopwatcher_route,
    seed,
    stops,
    bubbles,
    intersection_name,
    traffic_density,
):
    # dont worry about these seeds, theyre used by sumo
    sumo_seed = random.choice([0, 1, 2, 3, 4])
    stopwatcher_info = None
    stopwatcher_added = False
    if stopwatcher_behavior:
        stopwatcher_info = {
            "behavior": stopwatcher_behavior,
            "direction": get_direction(stopwatcher_route),
        }

    random.seed(seed)
    np.random.seed(seed)
    all_flows = []
    metadata = {"routes": {}, "total_vehicles": 0, "stopwatcher": None}

    scenario = save_dir + f"-flow-{seed}"

    # Remove old traffic route if it exists(otherwise, won't update to new flows)
    if os.path.exists(f"{scenario}/traffic/all.rou.xml"):
        shutil.rmtree(scenario)

    for route_key, route_info in route_distributions["routes"].items():
        # to skip None
        if route_info:
            ego_routes = [
                ego_mission_config_to_route(
                    ego_mission_config=ego_mission_config,
                    route_lanes=route_lanes,
                    stopwatcher_behavior=stopwatcher_behavior,
                )
                for ego_mission_config in missions
            ]
            # Not all routes need to have a custom start/end offset
            if "pos_offsets" in route_info:
                pos_offsets = route_info["pos_offsets"]
            else:
                pos_offsets = None
            flows, vehicles_log_info = generate_social_vehicles(
                route_distribution=route_info["distribution"],
                begin_time_init=route_info["begin_time_init"],
                num_vehicles=route_info["vehicles"],
                route_direction=get_direction(route_key),
                route_lanes=route_lanes,
                route_has_turn=route_info["has_turn"],
                start_end_on_different_lanes_probability=route_info[
                    "start_end_on_different_lanes_probability"
                ],
                stops=stops,
                deadlock_optimization=route_info["deadlock_optimization"],
                pos_offsets=pos_offsets,
                stopwatcher_info=stopwatcher_info,
                traffic_params={"speed": speed, "traffic_density": traffic_density},
            )
            if (
                stopwatcher_behavior
                and len(flows) > 0
                and get_direction(route_key) == stopwatcher_info["direction"]
            ):
                stopwatcher_added = True
                print(
                    f'stop watcher added to {get_direction(route_key)} flows among {route_info["vehicles"]} vehicles!'
                )
            all_flows.extend(flows)
            metadata["routes"][route_key] = vehicles_log_info
    scenario = save_dir + f"-flow-{seed}"
    if stopwatcher_behavior:
        if not stopwatcher_added and level_name != "no-traffic":
            print(
                f'There was no matching flows for stopwatcher, adding it to {stopwatcher_info["direction"]}.'
            )
            # vehicles_log_info[f'stopwatcher_{stopwatcher_info["behavior"]}']["count"] += 1
            all_flows.append(
                generate_stopwatcher(
                    stopwatcher_behavior=stopwatcher_info["behavior"],
                    stopwatcher_route=stopwatcher_info["direction"],
                    start_lane_id=0,
                    end_lane_id=0,
                )
            )
        scenario += f"-stopwatcher-{stopwatcher_info['behavior']}"

    copy_map_files(scenario, map_dir, speed)

    vehicles_to_not_hijack = []
    traffic = Traffic(flows=all_flows)
    try:
        gen_traffic(scenario, traffic, name=f"all", seed=sumo_seed)
        if stops:
            add_stops_to_traffic(scenario, stops, vehicles_to_not_hijack)
    except Exception as exception:
        print(exception)

    # Patch: Remove route files from traffic folder to make intersection empty.
    if traffic_density == "no-traffic":
        os.remove(f"{scenario}/traffic/all.rou.xml")

    if stopwatcher_behavior or "ego_hijacking_params" not in route_distributions:
        mission_objects = [Mission(ego_route) for ego_route in ego_routes]
    else:
        speed_m_per_s = float("".join(filter(str.isdigit, speed))) * 5.0 / 18.0
        hijacking_params = route_distributions["ego_hijacking_params"]
        zone_range = hijacking_params["zone_range"]
        waiting_time = hijacking_params["wait_to_hijack_limit_s"]
        start_time = (
            hijacking_params["start_time"]
            if hijacking_params["start_time"] != "default"
            else random.randint((LANE_LENGTH // speed_m_per_s), 60)
        )
        mission_objects = [
            Mission(
                ego_route,
                # Optional: control hijacking time, place, and emission.
                start_time=start_time,  # When to start hijacking (might start later).
                entry_tactic=TrapEntryTactic(
                    wait_to_hijack_limit_s=waiting_time,  # When to give up hijacking.
                    zone=MapZone(
                        start=(
                            ego_route.begin[0],
                            0,
                            ego_route.begin[2] + zone_range[0],
                        ),
                        length=zone_range[1],
                        n_lanes=(ego_route.begin[1] + 1),
                    ),  # Area to hijack.
                    exclusion_prefixes=vehicles_to_not_hijack,  # Don't hijack these.
                ),
            )
            for ego_route in ego_routes
        ]
    # Shuffle the missions so agents don't do the same route all the time.
    if shuffle_missions:
        random.shuffle(mission_objects)
    gen_missions(scenario, mission_objects)

    if bubbles:
        bubble_objects = [
            bubble_config_to_bubble_object(
                scenario, bubble_config, vehicles_to_not_hijack
            )
            for bubble_config in bubbles
        ]
        gen_bubbles(scenario, bubble_objects)

    if stopwatcher_behavior:
        metadata["stopwatcher"] = {
            "direction": stopwatcher_info["direction"],
            "behavior": stopwatcher_info["behavior"],
        }
    metadata["intersection"] = {
        "type": intersection_name[-1],
        "name": intersection_name,
    }
    metadata["total_vehicles"] = len(all_flows)
    metadata["seed"] = seed
    metadata["flow_id"] = f"flow_{seed}"
    with open(f"{scenario}/metadata.json", "w") as log:
        json.dump(metadata, log)
Ejemplo n.º 5
0
def bubble_config_to_bubble_object(
    scenario: str, bubble_config: Dict[str, Any], vehicles_to_not_hijack: Sequence[str]
) -> Bubble:
    """Converts a bubble config to a bubble object.

    Args:
        scenario:
            A string representing the path to this scenario.
        bubble_config:
            A dictionary with 'location', 'actor_name', 'agent_locator', and
            'agent_params' keys that is used to initialize the bubble.
        vehicles_to_not_hijack:
            A tuple of vehicle IDs that are passed to the bubble. The bubble will not
            capture those vehicles that have an ID in this tuple.

    Returns:
        Bubble: The bubble object created from the bubble config.
    """
    BUBBLE_MARGIN = 2
    map_file = sumolib.net.readNet(f"{scenario}/map.net.xml")

    location_name = bubble_config["location"][0]
    location_data = bubble_config["location"][1:]
    actor_name = bubble_config["actor_name"]
    agent_locator = bubble_config["agent_locator"]
    agent_params = bubble_config["agent_params"]

    if location_name == "intersection":
        # Create a bubble centered at the intersection.
        assert len(location_data) == 2
        bubble_length, bubble_width = location_data
        bubble_coordinates = map_file.getNode("junction-intersection").getCoord()
        zone = PositionalZone(
            pos=bubble_coordinates, size=(bubble_length, bubble_width)
        )
    else:
        # Create a bubble on one of the lanes.
        assert len(location_data) == 4
        lane_index, lane_offset, bubble_length, num_lanes_spanned = location_data
        zone = MapZone(
            start=("edge-" + location_name, lane_index, lane_offset),
            length=bubble_length,
            n_lanes=num_lanes_spanned,
        )

    bubble = Bubble(
        zone=zone,
        actor=SocialAgentActor(
            name=actor_name,
            agent_locator=agent_locator,
            policy_kwargs=agent_params,
            initial_speed=None,
        ),
        margin=BUBBLE_MARGIN,
        limit=None,
        exclusion_prefixes=vehicles_to_not_hijack,
        follow_actor_id=None,
        follow_offset=None,
        keep_alive=False,
    )
    return bubble