Example #1
0
def _build_single_scenario(clean: bool, allow_offset_map: bool, scenario: str):
    click.echo(f"build-scenario {scenario}")
    if clean:
        _clean(scenario)

    scenario_root = Path(scenario)
    scenario_root_str = str(scenario_root)

    scenario_py = scenario_root / "scenario.py"
    if scenario_py.exists():
        _install_requirements(scenario_root)
        subprocess.check_call([sys.executable, scenario_py])

    from smarts.core.scenario import Scenario

    traffic_histories = Scenario.discover_traffic_histories(scenario_root_str)
    shift_to_origin = not allow_offset_map or bool(traffic_histories)

    map_spec = Scenario.discover_map(scenario_root_str,
                                     shift_to_origin=shift_to_origin)
    road_map, _ = map_spec.builder_fn(map_spec)
    if not road_map:
        click.echo(
            "No reference to a RoadNetwork file was found in {}, or one could not be created. "
            "Please make sure the path passed is a valid Scenario with RoadNetwork file required "
            "(or a way to create one) for scenario building.".format(
                scenario_root_str))
        return

    road_map.to_glb(os.path.join(scenario_root, "map.glb"))
Example #2
0
    def __init__(self, config):
        print(">>> ENV: ", config["eval_mode"])
        self.scenario_info = config["scenario_info"]
        self.scenarios = self.get_task(self.scenario_info[0],
                                       self.scenario_info[1])
        self._timestep_sec = config["timestep_sec"]
        self._seed = config["seed"]
        if not config["eval_mode"]:
            _scenarios = glob.glob(f"{self.scenarios['train']}")
        else:
            _scenarios = glob.glob(f"{self.scenarios['test']}")

        config["scenarios"] = _scenarios
        self.ultra_scores = BaselineAdapter.reward_adapter
        super().__init__(config=config)

        if config["ordered_scenarios"]:
            scenario_roots = []
            for root in config["scenarios"]:
                if Scenario.is_valid_scenario(root):
                    # The case that this is a scenario root
                    scenario_roots.append(root)
                else:
                    # The case that there this is a directory of scenarios: find each of the roots
                    scenario_roots.extend(Scenario.discover_scenarios(root))
            # Also see `smarts.env.HiwayEnv`
            self._scenarios_iterator = cycle(
                Scenario.variations_for_all_scenario_roots(
                    scenario_roots, list(config["agent_specs"].keys())))
Example #3
0
def spawn_sumo(worker_idx, batch_id):
    sumo_sim = SumoTrafficSimulation(headless=True)

    scenarios_iterator = Scenario.scenario_variations(
        ["scenarios/loop"],
        ["Agent007"],
    )
    sumo_sim.setup(Scenario.next(scenarios_iterator, f"{batch_id}-{worker_idx}"))
    sumo_sim.teardown()
Example #4
0
def main(scenarios, headless, seed):
    scenarios_iterator = Scenario.scenario_variations(scenarios, [])
    for _ in scenarios:
        scenario = next(scenarios_iterator)
        agent_missions = scenario.discover_missions_of_traffic_histories()

        for agent_id, mission in agent_missions.items():
            scenario.set_ego_missions({agent_id: mission})

            agent_spec = AgentSpec(
                interface=AgentInterface.from_type(AgentType.Laner,
                                                   max_episode_steps=None),
                agent_builder=KeepLaneAgent,
            )

            agent = agent_spec.build_agent()

            smarts = SMARTS(
                agent_interfaces={agent_id: agent_spec.interface},
                traffic_sim=SumoTrafficSimulation(headless=True,
                                                  auto_start=True),
                envision=Envision(),
            )
            observations = smarts.reset(scenario)

            dones = {agent_id: False}
            while not dones[agent_id]:
                agent_obs = observations[agent_id]
                agent_action = agent.act(agent_obs)

                observations, rewards, dones, infos = smarts.step(
                    {agent_id: agent_action})
Example #5
0
def scenarios():
    with temp_scenario(name="straight",
                       map="maps/straight.net.xml") as scenario_root:
        traffic = t.Traffic(flows=[
            t.Flow(
                route=t.Route(
                    begin=("west", 1, 0),
                    end=("east", 1, "max"),
                ),
                rate=50,
                actors={t.TrafficActor("car"): 1},
            )
        ])

        missions = [
            t.Mission(
                t.Route(begin=("west", 1, 10), end=("east", 1, "max")),
                entry_tactic=t.TrapEntryTactic(
                    wait_to_hijack_limit_s=3,
                    zone=t.MapZone(start=("west", 0, 1), length=100,
                                   n_lanes=3),
                ),
            )
        ]
        scenario = t.Scenario(
            traffic={"all": traffic},
            ego_missions=missions,
        )

        gen_scenario(scenario, output_dir=scenario_root)
        yield Scenario.variations_for_all_scenario_roots([str(scenario_root)],
                                                         [AGENT_ID])
Example #6
0
def two_agent_capture_offset_tenth_of_second():
    with temp_scenario(name="straight",
                       map="maps/straight.net.xml") as scenario_root:
        missions = [
            t.Mission(
                t.Route(begin=("west", 1, 20), end=("east", 1, "max")),
                entry_tactic=t.TrapEntryTactic(
                    wait_to_hijack_limit_s=0,
                    zone=t.MapZone(start=("west", 0, 1), length=100,
                                   n_lanes=3),
                ),
            ),
            t.Mission(
                t.Route(begin=("west", 2, 10), end=("east", 1, "max")),
                entry_tactic=t.TrapEntryTactic(
                    wait_to_hijack_limit_s=0.1,
                    zone=t.MapZone(start=("west", 0, 1), length=100,
                                   n_lanes=3),
                ),
            ),
        ]

        scenario = t.Scenario(
            traffic={},
            ego_missions=missions,
        )

        gen_scenario(scenario, output_dir=scenario_root)
        yield Scenario.variations_for_all_scenario_roots(
            [str(scenario_root)], [AGENT_ID, AGENT_ID_2])
Example #7
0
def test_scenario_variations_of_social_agents(scenario_root):
    iterator = Scenario.variations_for_all_scenario_roots(
        [str(scenario_root)], [AGENT_ID]
    )
    scenarios = list(iterator)

    assert len(scenarios) == 6, "3 social agents x 2 missions each "
    for s in scenarios:
        assert len(s.social_agents) == 4, "4 social agents"
        assert len(s.missions) == 5, "4 missions for social agents + 1 for ego"

    # Ensure correct social agents are being spawned
    all_social_agent_ids = set()
    for s in scenarios:
        all_social_agent_ids |= set(s.social_agents.keys())

    groups = ["group-1", "group-2", "group-3", "group-4"]
    speeds = [10, 30, 80]
    expected_social_agent_ids = {
        SocialAgentId.new(f"non-interactive-agent-{speed}-v0", group=group)
        for group, speed in itertools.product(groups, speeds)
    }

    assert (
        len(all_social_agent_ids - expected_social_agent_ids) == 0
    ), "All the correct social agent IDs were used"
Example #8
0
    def __init__(self, config):
        seed = int(config.get("seed", 42))

        # See https://rllib.readthedocs.io/en/latest/rllib-env.html#configuring-environments
        # for context. We combine worker_index and vector_index through the Cantor pairing
        # function (https://en.wikipedia.org/wiki/Pairing_function) into a unique integer
        # and then add that to seed to both differentiate environment instances and
        # preserve determinism.
        a = config.worker_index
        b = config.vector_index
        c = (a + b) * (a + b + 1) // 2 + b
        smarts.core.seed(seed + c)

        self._agent_specs = config["agent_specs"]
        self._scenarios_iterator = Scenario.scenario_variations(
            config["scenarios"],
            list(self._agent_specs.keys()),
        )

        self._sim_name = config.get("sim_name", None)
        self._headless = config.get("headless", False)
        self._num_external_sumo_clients = config.get(
            "num_external_sumo_clients", 0)
        self._sumo_headless = config.get("sumo_headless", True)
        self._sumo_port = config.get("sumo_port")
        self._sumo_auto_start = config.get("sumo_auto_start", True)
        self._endless_traffic = config.get("endless_traffic", True)

        self._envision_endpoint = config.get("envision_endpoint", None)
        self._envision_record_data_replay_path = config.get(
            "envision_record_data_replay_path", None)
        self._timestep_sec = config.get("timestep_sec", 0.1)
        self._smarts = None  # Created on env.setup()
        self._dones_registered = 0
Example #9
0
def scenarios():
    with temp_scenario(name="straight", map="maps/straight.net.xml") as scenario_root:
        ego_missions = [
            # missions of laner and buddha
            t.Mission(
                t.Route(
                    begin=("west", 0, 30),
                    end=("east", 0, "max"),
                )
            ),
            t.Mission(
                t.Route(
                    begin=("west", 0, 40),
                    end=("east", 0, "max"),
                )
            ),
        ]
        gen_scenario(
            t.Scenario(ego_missions=ego_missions),
            output_dir=scenario_root,
        )

        yield Scenario.variations_for_all_scenario_roots(
            [str(scenario_root)], [AGENT_1, AGENT_2]
        )
def main(scenarios, headless, seed):
    agent_spec = AgentSpec(
        interface=AgentInterface.from_type(AgentType.Laner,
                                           max_episode_steps=None),
        agent_builder=None,
        observation_adapter=None,
    )

    smarts = SMARTS(
        agent_interfaces={},
        traffic_sim=SumoTrafficSimulation(headless=True, auto_start=True),
        envision=Envision(),
    )
    scenarios_iterator = Scenario.scenario_variations(
        scenarios,
        list([]),
    )

    smarts.reset(next(scenarios_iterator))

    for _ in range(5000):
        smarts.step({})
        smarts.attach_sensors_to_vehicles(
            agent_spec, smarts.vehicle_index.social_vehicle_ids())
        obs, _, _, _ = smarts.observe_from(
            smarts.vehicle_index.social_vehicle_ids())
Example #11
0
    def __init__(self, config):
        self._config = config

        # XXX: These are intentionally left public at PyMARL's request
        self.n_agents = config.get("n_agents", 1)
        self.episode_limit = config.get("episode_limit", 1000)
        self.observation_space = config.get("observation_space",
                                            DEFAULT_OBSERVATION_SPACE)
        self.action_space = config.get("action_space", DEFAULT_ACTION_SPACE)
        self.state_space = config.get("state_space", DEFAULT_STATE_SPACE)

        self._agent_ids = ["Agent %i" % i for i in range(self.n_agents)]

        self._reward_adapter = config.get("reward_adapter",
                                          default_reward_adapter)
        self._observation_adapter = config.get("observation_adapter",
                                               default_obs_adapter)
        self._action_adapter = config.get("action_adapter",
                                          default_action_adapter)
        self._done_adapter = config.get("done_adapter",
                                        lambda dones: list(dones.values()))
        self._state_adapter = config.get("state_adapter",
                                         default_state_adapter)

        self._headless = config.get("headless", False)
        self._timestep_sec = config.get("timestep_sec", 0.01)
        self._observations = None
        self._state = None
        self._steps = 0

        seed = self._config.get("seed", 42)
        smarts.core.seed(seed)

        self._scenarios_iterator = Scenario.scenario_variations(
            config["scenarios"], self._agent_ids)

        agent_interfaces = {
            agent_id: AgentInterface.from_type(
                config.get("agent_type", AgentType.Laner),
                max_episode_steps=self.episode_limit,
                debug=config.get("debug", False),
            )
            for i, agent_id, in enumerate(self._agent_ids)
        }

        envision = None
        if not self._headless:
            envision = Envision(
                endpoint=config.get("envision_endpoint", None),
                output_dir=config.get("envision_record_data_replay_path",
                                      None),
            )

        self._smarts = SMARTS(
            agent_interfaces=agent_interfaces,
            traffic_sim=SumoTrafficSimulation(
                time_resolution=self._timestep_sec),
            envision=envision,
            timestep_sec=self._timestep_sec,
        )
Example #12
0
def main(scenario):
    scenario_path = Path(scenario).absolute()
    agent_mission_count = Scenario.discover_agent_missions_count(scenario_path)

    assert agent_mission_count > 0, "agent mission count should larger than 0"

    agent_ids = [f"AGENT-{i}" for i in range(agent_mission_count)]

    agent_specs = {
        agent_id: AgentSpec(
            interface=AgentInterface.from_type(AgentType.Laner, max_episode_steps=None),
            agent_builder=RuleBasedAgent,
        )
        for agent_id in agent_ids
    }

    agents = {aid: agent_spec.build_agent() for aid, agent_spec in agent_specs.items()}

    env = HiWayEnv(scenarios=[scenario_path], agent_specs=agent_specs)

    while True:
        observations = env.reset()
        done = False
        while not done:
            agent_ids = list(observations.keys())
            actions = {aid: agents[aid].act(observations[aid]) for aid in agent_ids}
            observations, _, dones, _ = env.step(actions)
            done = dones["__all__"]
Example #13
0
    def __init__(
        self,
        scenarios: Sequence[str],
        agent_specs,
        shuffle_scenarios=True,
        headless=False,
        visdom=False,
        timestep_sec=0.1,
        seed=42,
        num_external_sumo_clients=0,
        sumo_headless=True,
        sumo_port=None,
        sumo_auto_start=True,
        endless_traffic=True,
        envision_endpoint=None,
        envision_record_data_replay_path=None,
        zoo_workers=None,
        auth_key=None,
    ):
        self._log = logging.getLogger(self.__class__.__name__)
        smarts.core.seed(seed)

        self._agent_specs = agent_specs
        self._dones_registered = 0

        self._scenarios_iterator = Scenario.scenario_variations(
            scenarios, list(agent_specs.keys()), shuffle_scenarios,
        )

        agent_interfaces = {
            agent_id: agent.interface for agent_id, agent in agent_specs.items()
        }

        envision_client = None
        if not headless:
            envision_client = Envision(
                endpoint=envision_endpoint, output_dir=envision_record_data_replay_path
            )

        visdom_client = None
        if visdom:
            visdom_client = VisdomClient()

        self._smarts = SMARTS(
            agent_interfaces=agent_interfaces,
            traffic_sim=SumoTrafficSimulation(
                headless=sumo_headless,
                time_resolution=timestep_sec,
                num_external_sumo_clients=num_external_sumo_clients,
                sumo_port=sumo_port,
                auto_start=sumo_auto_start,
                endless_traffic=endless_traffic,
            ),
            envision=envision_client,
            visdom=visdom_client,
            timestep_sec=timestep_sec,
            zoo_workers=zoo_workers,
            auth_key=auth_key,
        )
Example #14
0
    def __init__(
        self,
        agent_specs,
        scenario_info,
        headless,
        timestep_sec,
        seed,
        eval_mode=False,
        ordered_scenarios=False,
    ):
        self.timestep_sec = timestep_sec
        self.headless = headless
        self.scenario_info = scenario_info
        self.scenarios = self.get_task(scenario_info[0], scenario_info[1])
        if not eval_mode:
            _scenarios = glob.glob(f"{self.scenarios['train']}")
        else:
            _scenarios = glob.glob(f"{self.scenarios['test']}")

        self.smarts_observations_stack = deque(maxlen=_STACK_SIZE)

        super().__init__(
            scenarios=_scenarios,
            agent_specs=agent_specs,
            headless=headless,
            timestep_sec=timestep_sec,
            seed=seed,
            visdom=False,
        )

        if ordered_scenarios:
            scenario_roots = []
            for root in _scenarios:
                if Scenario.is_valid_scenario(root):
                    # The case that this is a scenario root
                    scenario_roots.append(root)
                else:
                    # The case that there this is a directory of scenarios: find each of the roots
                    scenario_roots.extend(Scenario.discover_scenarios(root))
            # Also see `smarts.env.HiwayEnv`
            self._scenarios_iterator = cycle(
                Scenario.variations_for_all_scenario_roots(
                    scenario_roots, list(agent_specs.keys())
                )
            )
Example #15
0
def scenarios(bubble):
    with temp_scenario(name="straight",
                       map="maps/straight.net.xml") as scenario_root:
        gen_scenario(
            t.Scenario(traffic={}, bubbles=[bubble]),
            output_dir=scenario_root,
        )
        yield Scenario.variations_for_all_scenario_roots([str(scenario_root)],
                                                         [])
def scenarios():
    mission = Mission(start=Start((71.65, 63.78), Heading(math.pi * 0.91)),
                      goal=EndlessGoal())
    scenario = Scenario(
        scenario_root="scenarios/loop",
        route="basic.rou.xml",
        missions={"Agent-007": mission},
    )
    return cycle([scenario])
Example #17
0
def smarts():
    smarts_ = SMARTS(
        agent_interfaces={},
        traffic_sim=mock.Mock(),
    )
    scenario = next(
        Scenario.scenario_variations(["scenarios/intersections/4lane_t"],
                                     ["Agent-007"]))
    smarts_.reset(scenario)
    return smarts_
Example #18
0
def scenarios(request):
    with temp_scenario(name="map", map=request.param[0]) as scenario_root:
        mission = t.Mission(route=t.Route(begin=("edge-west-WE", 0, 10),
                                          end=(request.param[1], 0, 40)))
        gen_scenario(
            t.Scenario(ego_missions=[mission]),
            output_dir=scenario_root,
        )
        yield Scenario.variations_for_all_scenario_roots([str(scenario_root)],
                                                         [AGENT_ID])
Example #19
0
 def _check_reset(self) -> Optional[Dict[str, Observation]]:
     with self._reset_lock:
         if self._reset_msg:
             self._scenario_path = self._reset_msg.scenario
             rospy.loginfo(
                 f"resetting SMARTS w/ scenario={self._scenario_path}")
             self._reset_msg = None
             self._last_step_time = None
             self._recent_state = deque(maxlen=3)
             self._most_recent_state_sent = None
             self._warned_about_freq = False
             map_spec = self._get_map_spec()
             routes = Scenario.discover_routes(
                 self._scenario_path) or [None]
             return self._smarts.reset(
                 Scenario(self._scenario_path,
                          map_spec=map_spec,
                          route=routes[0]))
     return None
Example #20
0
    def __init__(
        self,
        scenarios: Sequence[str],
        agent_specs,
        visdom=False,
        headless=False,
        timestep_sec=0.1,
        seed=42,
        num_external_sumo_clients=0,
        sumo_headless=True,
        sumo_port=None,
        sumo_auto_start=True,
        endless_traffic=True,
        envision_endpoint=None,
        envision_record_data_replay_path=None,
    ):
        self._log = logging.getLogger(self.__class__.__name__)
        smarts.core.seed(seed)

        self._visdom_obs_queue = None
        if visdom:
            self._log.debug("Running with visdom")
            self._visdom_obs_queue = build_visdom_watcher_queue()

        self._agent_specs = agent_specs
        self._dones_registered = 0

        self._scenarios_iterator = Scenario.scenario_variations(
            scenarios,
            list(agent_specs.keys()),
        )

        agent_interfaces = {
            agent_id: agent.interface
            for agent_id, agent in agent_specs.items()
        }

        envision = None
        if not headless:
            envision = Envision(endpoint=envision_endpoint,
                                output_dir=envision_record_data_replay_path)

        self._smarts = SMARTS(
            agent_interfaces=agent_interfaces,
            traffic_sim=SumoTrafficSimulation(
                headless=sumo_headless,
                time_resolution=timestep_sec,
                num_external_sumo_clients=num_external_sumo_clients,
                sumo_port=sumo_port,
                auto_start=sumo_auto_start,
                endless_traffic=endless_traffic,
            ),
            envision=envision,
            timestep_sec=timestep_sec,
        )
Example #21
0
def scenario():
    mission = Mission(
        start=Start(np.array([71.65, 63.78]), Heading(math.pi * 0.91)),
        goal=EndlessGoal(),
    )
    scenario = Scenario(
        scenario_root="scenarios/loop",
        route="basic.rou.xml",
        missions={AGENT_ID: mission},
    )
    return scenario
def scenario():
    with temp_scenario(name="map",
                       map="maps/straight.net.xml") as scenario_root:
        mission = t.Mission(route=t.Route(
            begin=("west", 1, 99.9),
            end=("east", 1, 10.0),
        ))
        gen_scenario(
            t.Scenario(ego_missions=[mission]),
            output_dir=scenario_root,
        )
        yield Scenario.variations_for_all_scenario_roots([str(scenario_root)],
                                                         [AGENT_ID])
Example #23
0
def gen_config(**kwargs):
    scenario_path = Path(kwargs["scenario"]).absolute()
    agent_missions_count = Scenario.discover_agent_missions_count(
        scenario_path)
    if agent_missions_count == 0:
        agent_ids = ["default_policy"]
    else:
        agent_ids = [f"AGENT-{i}" for i in range(agent_missions_count)]

    config = load_config(kwargs["config_file"],
                         mode=kwargs.get("mode", "training"))
    agents = {agent_id: AgentSpec(**config["agent"]) for agent_id in agent_ids}

    config["env_config"].update({
        "seed": 42,
        "scenarios": [str(scenario_path)],
        "headless": kwargs["headless"],
        "agent_specs": agents,
    })

    obs_space, act_space = config["policy"][1:3]
    tune_config = config["run"]["config"]

    if kwargs["paradigm"] == "centralized":
        config["env_config"].update({
            "obs_space":
            gym.spaces.Tuple([obs_space] * agent_missions_count),
            "act_space":
            gym.spaces.Tuple([act_space] * agent_missions_count),
            "groups": {
                "group": agent_ids
            },
        })
        tune_config.update(config["policy"][-1])
    else:
        policies = {}
        for k in agents:
            policies[k] = config["policy"][:-1] + ({
                **config["policy"][-1], "agent_id":
                k
            }, )
        tune_config.update({
            "multiagent": {
                "policies": policies,
                "policy_mapping_fn": lambda agent_id: agent_id,
            }
        })

    return config
def main(scenarios: Sequence[str], headless: bool, seed: int):
    agent_spec = AgentSpec(
        interface=AgentInterface.from_type(AgentType.Laner,
                                           max_episode_steps=None),
        agent_builder=None,
        observation_adapter=None,
    )

    smarts = SMARTS(
        agent_interfaces={},
        traffic_sim=SumoTrafficSimulation(headless=headless, auto_start=True),
        envision=None if headless else Envision(),
    )
    scenarios_iterator = Scenario.scenario_variations(
        scenarios,
        list([]),
    )

    scenario = next(scenarios_iterator)
    obs = smarts.reset(scenario)

    collected_data = {}
    _record_data(smarts.elapsed_sim_time, obs, collected_data)

    # could also include "motorcycle" or "truck" in this set if desired
    vehicle_types = frozenset({"car"})

    while True:
        smarts.step({})
        current_vehicles = smarts.vehicle_index.social_vehicle_ids(
            vehicle_types=vehicle_types)

        if collected_data and not current_vehicles:
            print("no more vehicles.  exiting...")
            break

        smarts.attach_sensors_to_vehicles(agent_spec, current_vehicles)
        obs, _, _, dones = smarts.observe_from(current_vehicles)

        _record_data(smarts.elapsed_sim_time, obs, collected_data)

    # an example of how we might save the data per car
    for car, data in collected_data.items():
        outfile = f"data_{scenario.name}_{scenario.traffic_history.name}_{car}.pkl"
        with open(outfile, "wb") as of:
            pickle.dump(data, of)

    smarts.destroy()
Example #25
0
def uturn_scenarios():
    with temp_scenario(name="straight",
                       map="maps/6lane.net.xml") as scenario_root:
        ego_missions = [
            t.Mission(
                route=t.Route(begin=("edge-west-WE", 0, 30),
                              end=("edge-west-EW", 0, "max")),
                task=t.UTurn(),
            ),
        ]
        gen_scenario(
            t.Scenario(ego_missions=ego_missions),
            output_dir=scenario_root,
        )

        yield Scenario.variations_for_all_scenario_roots([str(scenario_root)],
                                                         [AGENT_ID])
Example #26
0
def main(scenarios, headless, seed):
    scenarios_iterator = Scenario.scenario_variations(scenarios, [])
    smarts = SMARTS(
        agent_interfaces={},
        traffic_sim=None,
        envision=None if headless else Envision(),
    )
    for _ in scenarios:
        scenario = next(scenarios_iterator)
        agent_missions = scenario.discover_missions_of_traffic_histories()

        for agent_id, mission in agent_missions.items():
            agent_spec = AgentSpec(
                interface=AgentInterface.from_type(AgentType.LanerWithSpeed,
                                                   max_episode_steps=None),
                agent_builder=KeepLaneAgent,
                agent_params=scenario.traffic_history_target_speed,
            )
            agent = agent_spec.build_agent()

            # Take control of vehicle with corresponding agent_id
            smarts.switch_ego_agent({agent_id: agent_spec.interface})

            # tell the traffic history provider to start traffic
            # at the point when this agent enters...
            traffic_history_provider = smarts.get_provider_by_type(
                TrafficHistoryProvider)
            assert traffic_history_provider
            traffic_history_provider.start_time = mission.start_time

            # agent vehicle will enter right away...
            modified_mission = replace(mission, start_time=0.0)
            scenario.set_ego_missions({agent_id: modified_mission})

            observations = smarts.reset(scenario)

            dones = {agent_id: False}
            while not dones.get(agent_id, True):
                agent_obs = observations[agent_id]
                agent_action = agent.act(agent_obs)

                observations, rewards, dones, infos = smarts.step(
                    {agent_id: agent_action})

    smarts.destroy()
def main(scenarios, headless, seed):
    agent_spec = AgentSpec(
        interface=AgentInterface.from_type(AgentType.Laner,
                                           max_episode_steps=None),
        agent_builder=None,
        observation_adapter=None,
    )

    smarts = SMARTS(
        agent_interfaces={},
        traffic_sim=SumoTrafficSimulation(headless=headless, auto_start=True),
        envision=None if headless else Envision(),
    )
    scenarios_iterator = Scenario.scenario_variations(
        scenarios,
        list([]),
    )

    smarts.reset(next(scenarios_iterator))

    prev_vehicles = set()
    done_vehicles = set()
    for _ in range(5000):
        smarts.step({})

        current_vehicles = smarts.vehicle_index.social_vehicle_ids()
        # We explicitly watch for which agent/vehicles left the simulation here
        # since we don't have a "done criteria" that detects when a vehicle's
        # traffic history has played itself out.
        done_vehicles = prev_vehicles - current_vehicles
        prev_vehicles = current_vehicles

        smarts.attach_sensors_to_vehicles(agent_spec, current_vehicles)
        obs, _, _, dones = smarts.observe_from(current_vehicles)
        # The `dones` returned above should be empty for traffic histories
        # where all vehicles are assumed to stay on the road and not collide.
        # TODO:  add the following assert once the maps are accurate enough that
        # we don't have any agents accidentally go off-road.
        # assert not done
        for v in done_vehicles:
            dones[f"Agent-{v}"] = True
        # TODO: save observations for imitation learning

    smarts.destroy()
def scenarios():
    with temp_scenario(name="6lane", map="maps/6lane.net.xml") as scenario_root:
        actors = [
            t.SocialAgentActor(
                name=f"non-interactive-agent-{speed}-v0",
                agent_locator="zoo.policies:non-interactive-agent-v0",
                policy_kwargs={"speed": speed},
            )
            for speed in [10, 30, 80]
        ]

        def to_mission(start_edge, end_edge):
            route = t.Route(begin=(start_edge, 1, 0), end=(end_edge, 1, "max"))
            return t.Mission(route=route)

        def fifth_mission(start_edge, end_edge):
            route = t.Route(begin=(start_edge, 0, 0), end=(end_edge, 0, "max"))
            return t.Mission(route=route)

        gen_scenario(
            t.Scenario(
                social_agent_missions={
                    "group-1": (actors, [to_mission("edge-north-NS", "edge-south-NS")]),
                    "group-2": (actors, [to_mission("edge-west-WE", "edge-east-WE")]),
                    "group-3": (actors, [to_mission("edge-east-EW", "edge-west-EW")]),
                    "group-4": (actors, [to_mission("edge-south-SN", "edge-north-SN")]),
                    "group-5": (
                        actors,
                        [fifth_mission("edge-south-SN", "edge-east-WE")],
                    ),
                },
                ego_missions=[
                    t.Mission(
                        t.Route(
                            begin=("edge-west-WE", 0, 0), end=("edge-east-WE", 0, "max")
                        )
                    )
                ],
            ),
            output_dir=scenario_root,
        )
        yield Scenario.variations_for_all_scenario_roots(
            [str(scenario_root)], [AGENT_1]
        )
def test_mutiple_traffic_data(create_scenario, create_history_files):
    Scenario.discover_traffic_histories = MagicMock(
        return_value=create_history_files)
    iterator = Scenario.variations_for_all_scenario_roots(
        [str(create_scenario)], [AGENT_ID], shuffle_scenarios=False)
    scenarios = list(iterator)

    assert len(scenarios) == 8  # 2 social agents x 2 missions x 2 histories

    traffic_history_provider = TrafficHistoryProvider()

    for scenario, traffic_history in zip(
            scenarios, [traffic_history_1, traffic_history_2]):
        for key in scenario.traffic_history_service.traffic_history:
            assert (scenario.traffic_history_service.traffic_history[key] ==
                    traffic_history[key])

        traffic_history_provider.setup(scenario)
        assert (traffic_history_provider._traffic_history_service ==
                scenario.traffic_history_service)
Example #30
0
def scenarios(bubble):
    with temp_scenario(name="straight", map="maps/straight.net.xml") as scenario_root:
        traffic = t.Traffic(
            flows=[
                t.Flow(
                    route=t.Route(
                        begin=("west", lane_idx, 0), end=("east", lane_idx, "max"),
                    ),
                    rate=50,
                    actors={t.TrafficActor("car"): 1,},
                )
                for lane_idx in range(3)
            ]
        )

        gen_scenario(
            t.Scenario(traffic={"all": traffic}, bubbles=[bubble]),
            output_dir=scenario_root,
        )

        yield Scenario.variations_for_all_scenario_roots([str(scenario_root)], [])