code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def _equally_spaced_path(
path: Sequence[LinkedLanePoint],
point: Point,
lp_spacing: float,
) -> List[Waypoint]:
"""given a list of LanePoints starting near point, return corresponding
Waypoints that may not be evenly spaced (due to lane change) but start at point.
"""
continuous_variables = [
"positions_x",
"positions_y",
"headings",
"lane_width",
"speed_limit",
"lane_offset",
]
discrete_variables = ["lane_id", "lane_index"]
ref_lanepoints_coordinates = {
parameter: [] for parameter in (continuous_variables + discrete_variables)
}
for idx, lanepoint in enumerate(path):
if lanepoint.is_inferred and 0 < idx < len(path) - 1:
continue
ref_lanepoints_coordinates["positions_x"].append(
lanepoint.lp.pose.position[0]
)
ref_lanepoints_coordinates["positions_y"].append(
lanepoint.lp.pose.position[1]
)
ref_lanepoints_coordinates["headings"].append(
lanepoint.lp.pose.heading.as_bullet
)
ref_lanepoints_coordinates["lane_id"].append(lanepoint.lp.lane.lane_id)
ref_lanepoints_coordinates["lane_index"].append(lanepoint.lp.lane.index)
ref_lanepoints_coordinates["lane_width"].append(lanepoint.lp.lane_width)
ref_lanepoints_coordinates["lane_offset"].append(
lanepoint.lp.lane.offset_along_lane(lanepoint.lp.pose.point)
)
ref_lanepoints_coordinates["speed_limit"].append(
lanepoint.lp.lane.speed_limit
)
ref_lanepoints_coordinates["headings"] = inplace_unwrap(
ref_lanepoints_coordinates["headings"]
)
first_lp_heading = ref_lanepoints_coordinates["headings"][0]
lp_position = path[0].lp.pose.point.as_np_array[:2]
vehicle_pos = point.as_np_array[:2]
heading_vec = radians_to_vec(first_lp_heading)
projected_distant_lp_vehicle = np.inner(
(vehicle_pos - lp_position), heading_vec
)
ref_lanepoints_coordinates["positions_x"][0] = (
lp_position[0] + projected_distant_lp_vehicle * heading_vec[0]
)
ref_lanepoints_coordinates["positions_y"][0] = (
lp_position[1] + projected_distant_lp_vehicle * heading_vec[1]
)
cumulative_path_dist = np.cumsum(
np.sqrt(
np.ediff1d(ref_lanepoints_coordinates["positions_x"], to_begin=0) ** 2
+ np.ediff1d(ref_lanepoints_coordinates["positions_y"], to_begin=0) ** 2
)
)
if len(cumulative_path_dist) <= lp_spacing:
lp = path[0].lp
return [
Waypoint(
pos=lp.pose.position[:2],
heading=lp.pose.heading,
lane_width=lp.lane.width_at_offset(0)[0],
speed_limit=lp.lane.speed_limit,
lane_id=lp.lane.lane_id,
lane_index=lp.lane.index,
lane_offset=lp.lane.offset_along_lane(lp.pose.point),
)
]
evenly_spaced_cumulative_path_dist = np.linspace(
0, cumulative_path_dist[-1], len(path)
)
evenly_spaced_coordinates = {}
for variable in continuous_variables:
evenly_spaced_coordinates[variable] = np.interp(
evenly_spaced_cumulative_path_dist,
cumulative_path_dist,
ref_lanepoints_coordinates[variable],
)
for variable in discrete_variables:
ref_coordinates = ref_lanepoints_coordinates[variable]
evenly_spaced_coordinates[variable] = []
jdx = 0
for idx in range(len(path)):
while (
jdx + 1 < len(cumulative_path_dist)
and evenly_spaced_cumulative_path_dist[idx]
> cumulative_path_dist[jdx + 1]
):
jdx += 1
evenly_spaced_coordinates[variable].append(ref_coordinates[jdx])
evenly_spaced_coordinates[variable].append(ref_coordinates[-1])
waypoint_path = []
for idx in range(len(path)):
waypoint_path.append(
Waypoint(
pos=np.array(
[
evenly_spaced_coordinates["positions_x"][idx],
evenly_spaced_coordinates["positions_y"][idx],
]
),
heading=Heading(evenly_spaced_coordinates["headings"][idx]),
lane_width=evenly_spaced_coordinates["lane_width"][idx],
speed_limit=evenly_spaced_coordinates["speed_limit"][idx],
lane_id=evenly_spaced_coordinates["lane_id"][idx],
lane_index=evenly_spaced_coordinates["lane_index"][idx],
lane_offset=evenly_spaced_coordinates["lane_offset"][idx],
)
)
return waypoint_path | given a list of LanePoints starting near point, return corresponding
Waypoints that may not be evenly spaced (due to lane change) but start at point. | _equally_spaced_path | python | huawei-noah/SMARTS | smarts/core/argoverse_map.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/argoverse_map.py | MIT |
def _waypoints_starting_at_lanepoint(
self,
lanepoint: LinkedLanePoint,
lookahead: int,
filter_road_ids: tuple,
point: Point,
) -> List[List[Waypoint]]:
"""computes equally-spaced Waypoints for all lane paths starting at lanepoint
up to lookahead waypoints ahead, constrained to filter_road_ids if specified."""
# The following acts sort of like lru_cache(1), but it allows
# for lookahead to be <= to the cached value...
cache_paths = self._waypoints_cache.query(
lookahead, point, filter_road_ids, lanepoint
)
if cache_paths:
return cache_paths
lanepoint_paths = self._lanepoints.paths_starting_at_lanepoint(
lanepoint, lookahead, filter_road_ids
)
result = [
ArgoverseMap._equally_spaced_path(
path,
point,
self._map_spec.lanepoint_spacing,
)
for path in lanepoint_paths
]
self._waypoints_cache.update(
lookahead, point, filter_road_ids, lanepoint, result
)
return result | computes equally-spaced Waypoints for all lane paths starting at lanepoint
up to lookahead waypoints ahead, constrained to filter_road_ids if specified. | _waypoints_starting_at_lanepoint | python | huawei-noah/SMARTS | smarts/core/argoverse_map.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/argoverse_map.py | MIT |
def ready(self, sim_time: float):
"""If the trap is ready to capture a vehicle."""
return self.activation_time < sim_time or math.isclose(
self.activation_time, sim_time
) | If the trap is ready to capture a vehicle. | ready | python | huawei-noah/SMARTS | smarts/core/trap_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/trap_manager.py | MIT |
def patience_expired(self, sim_time: float):
"""If the trap has expired and should no longer capture a vehicle."""
expiry_time = self.activation_time + self.patience
return expiry_time < sim_time and not math.isclose(expiry_time, sim_time) | If the trap has expired and should no longer capture a vehicle. | patience_expired | python | huawei-noah/SMARTS | smarts/core/trap_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/trap_manager.py | MIT |
def includes(self, vehicle_id: str):
"""Returns if the given actor should be considered for capture."""
for prefix in self.entry_tactic.exclusion_prefixes:
if vehicle_id.startswith(prefix):
return False
return True | Returns if the given actor should be considered for capture. | includes | python | huawei-noah/SMARTS | smarts/core/trap_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/trap_manager.py | MIT |
def init_traps(self, road_map, missions, sim: SMARTS):
"""Set up the traps used to capture actors."""
self._traps.clear()
cancelled_agents: Set[str] = set()
for agent_id, mission in missions.items():
added, expired = self.add_trap_for_agent(
agent_id, mission, road_map, sim.elapsed_sim_time, reject_expired=True
)
if expired and not added:
cancelled_agents.add(agent_id)
if len(cancelled_agents) > 0:
sim.agent_manager.teardown_ego_agents(cancelled_agents) | Set up the traps used to capture actors. | init_traps | python | huawei-noah/SMARTS | smarts/core/trap_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/trap_manager.py | MIT |
def add_trap_for_agent(
self,
agent_id: str,
mission: NavigationMission,
road_map: RoadMap,
sim_time: float,
reject_expired: bool = False,
) -> Tuple[bool, bool]:
"""Add a new trap to capture an actor for the given agent.
:param agent_id: The agent to associate to this trap.
:type agent_id: str
:param mission: The mission to assign to the agent and vehicle.
:type mission: smarts.core.plan.NavigationMission
:param road_map: The road map to provide information to about the map.
:type road_map: RoadMap
:param sim_time: The current simulator time.
:type sim_time: float
:param reject_expired: If traps should be ignored if their patience would already be
expired on creation
:type reject_expired: bool
:return: If the trap was added and if the trap is already expired.
:rtype: Tuple[bool, bool]
"""
if mission is None:
mission = NavigationMission.random_endless_mission(road_map)
if not mission.entry_tactic:
mission = replace(mission, entry_tactic=default_entry_tactic())
if not isinstance(mission.entry_tactic, TrapEntryTactic):
return False, False
entry_tactic: TrapEntryTactic = (
mission.entry_tactic
) # pytype: disable=annotation-type-mismatch
# Do not add trap if simulation time is specified and patience already expired
patience_expired = mission.start_time + entry_tactic.wait_to_hijack_limit_s
if reject_expired and patience_expired < sim_time:
self._log.warning(
f"Trap skipped for `{agent_id}` scheduled to start between "
+ f"`{mission.start_time}` and `{patience_expired}` because simulation skipped to "
f"simulation time `{sim_time}`"
)
return False, True
plan = Plan(road_map, mission)
trap = self._mission2trap(road_map, plan.mission)
self._traps[agent_id] = trap
return True, False | Add a new trap to capture an actor for the given agent.
:param agent_id: The agent to associate to this trap.
:type agent_id: str
:param mission: The mission to assign to the agent and vehicle.
:type mission: smarts.core.plan.NavigationMission
:param road_map: The road map to provide information to about the map.
:type road_map: RoadMap
:param sim_time: The current simulator time.
:type sim_time: float
:param reject_expired: If traps should be ignored if their patience would already be
expired on creation
:type reject_expired: bool
:return: If the trap was added and if the trap is already expired.
:rtype: Tuple[bool, bool] | add_trap_for_agent | python | huawei-noah/SMARTS | smarts/core/trap_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/trap_manager.py | MIT |
def remove_traps(self, used_traps):
"""Remove the given used traps."""
for agent_id, _ in used_traps:
del self._traps[agent_id] | Remove the given used traps. | remove_traps | python | huawei-noah/SMARTS | smarts/core/trap_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/trap_manager.py | MIT |
def reset_traps(self, used_traps):
"""Reset all used traps."""
self._log.warning(
"Please update usage: ",
exc_info=DeprecationWarning(
"`TrapManager.reset_traps(..)` method has been deprecated in favor of `remove_traps(..)`."
),
)
self.remove_traps(used_traps) | Reset all used traps. | reset_traps | python | huawei-noah/SMARTS | smarts/core/trap_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/trap_manager.py | MIT |
def step(self, sim: SMARTS):
"""Run vehicle hijacking and update agent and actor states."""
capture_by_agent_id: Dict[str, _CaptureState] = defaultdict(
lambda: _CaptureState(
ready_state=ConditionState.FALSE,
trap=None,
default=True,
)
)
# An optimization to short circuit if there are no pending agents.
if not (
sim.agent_manager.pending_agent_ids
| sim.agent_manager.pending_social_agent_ids
):
return
social_vehicle_ids: List[str] = [
v_id
for v_id in sim.vehicle_index.social_vehicle_ids()
if not sim.vehicle_index.vehicle_is_shadowed(v_id)
]
vehicles: Dict[str, Vehicle] = {
v_id: sim.vehicle_index.vehicle_by_id(v_id) for v_id in social_vehicle_ids
}
vehicle_comp = [
(v.position[:2], max(v.chassis.dimensions.as_lwh[:2]), v)
for v in vehicles.values()
]
pending_agent_ids = (
sim.agent_manager.pending_agent_ids
| sim.agent_manager.pending_social_agent_ids
)
# Pending agents is currently used to avoid
for agent_id in pending_agent_ids:
trap = self._traps.get(agent_id)
if trap is None:
continue
# Skip the capturing process if history traffic is used
if trap.mission.vehicle_spec is not None:
continue
if not trap.ready(sim.elapsed_sim_time):
capture_by_agent_id[agent_id] = _CaptureState(
ConditionState.BEFORE, trap
)
continue
if (
trap.patience_expired(sim.elapsed_sim_time)
and sim.elapsed_sim_time > sim.fixed_timestep_sec
):
capture_by_agent_id[agent_id] = _CaptureState(
ConditionState.EXPIRED, trap, updated_mission=trap.mission
)
continue
sim_eval_kwargs = ActorCaptureManager._gen_simulation_condition_kwargs(
sim, trap.entry_tactic.condition.requires
)
mission_eval_kwargs = ActorCaptureManager._gen_mission_condition_kwargs(
agent_id, trap.mission, trap.entry_tactic.condition.requires
)
trap_condition = trap.entry_tactic.condition.evaluate(
**sim_eval_kwargs, **mission_eval_kwargs
)
if not trap_condition:
capture_by_agent_id[agent_id] = _CaptureState(trap_condition, trap)
continue
# Order vehicle ids by distance.
sorted_vehicle_ids = sorted(
list(social_vehicle_ids),
key=lambda v: squared_dist(
vehicles[v].position[:2], trap.mission.start.position[:2]
),
)
for vehicle_id in sorted_vehicle_ids:
if not trap.includes(vehicle_id):
continue
vehicle: Vehicle = vehicles[vehicle_id]
point = vehicle.pose.point.as_shapely
if not point.within(trap.geometry):
continue
capture_by_agent_id[agent_id] = _CaptureState(
ready_state=trap_condition,
trap=trap,
updated_mission=replace(
trap.mission,
start=Start(vehicle.position[:2], vehicle.pose.heading),
),
vehicle_id=vehicle_id,
)
social_vehicle_ids.remove(vehicle_id)
break
else:
capture_by_agent_id[agent_id] = _CaptureState(
ready_state=trap_condition,
trap=trap,
)
used_traps = []
for agent_id in pending_agent_ids:
capture = capture_by_agent_id[agent_id]
if capture.default:
continue
if capture.trap is None:
continue
if not capture.trap.ready(sim.elapsed_sim_time):
continue
vehicle: Optional[Vehicle] = None
if capture.ready_state and capture.vehicle_id is not None:
vehicle = self._take_existing_vehicle(
sim,
capture.vehicle_id,
agent_id,
capture.updated_mission,
social=agent_id in sim.agent_manager.pending_social_agent_ids,
)
elif ConditionState.EXPIRED in capture.ready_state:
# Make sure there is not a vehicle in the same location
mission = capture.updated_mission or capture.trap.mission
if mission.vehicle_spec is None:
nv_dims = Vehicle.agent_vehicle_dims(mission)
new_veh_maxd = max(nv_dims.as_lwh[:2])
overlapping = False
for pos, largest_dimension, _ in vehicle_comp:
if (
squared_dist(pos, mission.start.position[:2])
<= (0.5 * (largest_dimension + new_veh_maxd)) ** 2
):
overlapping = True
break
if overlapping:
continue
vehicle = TrapManager._make_new_vehicle(
sim,
agent_id,
mission,
capture.trap.default_entry_speed,
social=agent_id in sim.agent_manager.pending_social_agent_ids,
)
else:
continue
if vehicle is None:
continue
used_traps.append((agent_id, capture.trap))
self.remove_traps(used_traps) | Run vehicle hijacking and update agent and actor states. | step | python | huawei-noah/SMARTS | smarts/core/trap_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/trap_manager.py | MIT |
def traps(self) -> Dict[str, Trap]:
"""The traps in this manager."""
return self._traps | The traps in this manager. | traps | python | huawei-noah/SMARTS | smarts/core/trap_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/trap_manager.py | MIT |
def reset(self, scenario: smarts.core.scenario.Scenario, sim: SMARTS):
"""
:param scenario: The scenario to initialize from.
:type scenario: smarts.core.scenario.Scenario
:param sim: The simulation this is associated to.
:type scenario: smarts.core.smarts.SMARTS
"""
self.init_traps(scenario.road_map, scenario.missions, sim) | :param scenario: The scenario to initialize from.
:type scenario: smarts.core.scenario.Scenario
:param sim: The simulation this is associated to.
:type scenario: smarts.core.smarts.SMARTS | reset | python | huawei-noah/SMARTS | smarts/core/trap_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/trap_manager.py | MIT |
def from_function(cls, agent_function: Callable[[Any], Any]) -> "Agent":
"""A utility function to create an agent from a lambda or other callable object.
.. code-block:: python
keep_lane_agent = Agent.from_function(lambda obs: "keep_lane")
"""
return FunctionAgent(agent_function) | A utility function to create an agent from a lambda or other callable object.
.. code-block:: python
keep_lane_agent = Agent.from_function(lambda obs: "keep_lane") | from_function | python | huawei-noah/SMARTS | smarts/core/agent.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent.py | MIT |
def act(self, obs, **configs):
"""The agent action. See documentation on observations, `AgentSpec`, and `AgentInterface`.
Expects an adapted observation and returns a raw action.
"""
raise NotImplementedError | The agent action. See documentation on observations, `AgentSpec`, and `AgentInterface`.
Expects an adapted observation and returns a raw action. | act | python | huawei-noah/SMARTS | smarts/core/agent.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent.py | MIT |
def deprecated_agent_spec(*args, **kwargs):
"""Deprecated version of AgentSpec, see smarts.zoo.agent_spec"""
from smarts.zoo.agent_spec import AgentSpec as AgentSpecAlias
warnings.warn(
"The AgentSpec class has moved to the following module: smarts.zoo.agent_spec. Calling it from this module will be deprecated.",
DeprecationWarning,
)
return AgentSpecAlias(*args, **kwargs) | Deprecated version of AgentSpec, see smarts.zoo.agent_spec | deprecated_agent_spec | python | huawei-noah/SMARTS | smarts/core/agent.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent.py | MIT |
def pairwise(iterable):
"""Generates pairs of neighboring elements.
>>> list(pairwise('ABCDEFG'))
[('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G')]
"""
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b) | Generates pairs of neighboring elements.
>>> list(pairwise('ABCDEFG'))
[('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G')] | pairwise | python | huawei-noah/SMARTS | smarts/core/sumo_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_road_network.py | MIT |
def nearest_roads(self, point: Point, radius: float):
"""Finds the nearest roads to the given point within the given radius."""
x = point[0]
y = point[1]
r = radius
edges: List[sumolib.net.edge.Edge] = sorted(
self._graph.getEdges(), key=lambda e: e.getID()
)
if self._rtree_roads is None:
self._rtree_roads = self._init_rtree(edges)
near_roads: List[RoadMap.Road] = []
for i in self._rtree_roads.intersection((x - r, y - r, x + r, y + r)):
near_roads.append(self.road_by_id(edges[i].getID()))
return near_roads | Finds the nearest roads to the given point within the given radius. | nearest_roads | python | huawei-noah/SMARTS | smarts/core/sumo_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_road_network.py | MIT |
def shifted_net_file_path(cls, net_file_path):
"""The path of the modified map file after coordinate normalization."""
net_file_folder = os.path.dirname(net_file_path)
return os.path.join(net_file_folder, cls.shifted_net_file_name) | The path of the modified map file after coordinate normalization. | shifted_net_file_path | python | huawei-noah/SMARTS | smarts/core/sumo_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_road_network.py | MIT |
def from_spec(cls, map_spec: MapSpec):
"""Generate a road network from the given map specification."""
net_file = SumoRoadNetwork._map_path(map_spec)
import multiprocessing
junction_check_proc = multiprocessing.Process(
target=cls._check_junctions, args=(net_file,), daemon=True
)
try:
junction_check_proc.start()
except AssertionError:
cls._check_junctions(net_file)
# Connections to internal lanes are implicit. If `withInternal=True` is
# set internal junctions and the connections from internal lanes are
# loaded into the network graph.
# pytype: disable=module-attr
G = sumolib.net.readNet(net_file, withInternal=True)
# pytype: enable=module-attr
if not cls._check_net_origin(G.getBoundary()):
shifted_net_file = cls.shifted_net_file_path(net_file)
if os.path.isfile(shifted_net_file) or (
map_spec.shift_to_origin
and cls._shift_coordinates(net_file, shifted_net_file)
):
# pytype: disable=module-attr
G = sumolib.net.readNet(shifted_net_file, withInternal=True)
# pytype: enable=module-attr
assert cls._check_net_origin(G.getBoundary())
net_file = shifted_net_file
# keep track of having shifted the graph by
# injecting state into the network graph.
# this is needed because some maps have been pre-shifted,
# and will already have a locationOffset, but for those
# the offset should not be used (because all their other
# coordinates are relative to the origin).
G._shifted_by_smarts = True
if junction_check_proc.is_alive():
junction_check_proc.join(5)
return cls(G, net_file, map_spec) | Generate a road network from the given map specification. | from_spec | python | huawei-noah/SMARTS | smarts/core/sumo_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_road_network.py | MIT |
def source(self) -> str:
"""This is the `.net.xml` file that corresponds with our possibly-offset coordinates."""
return self._net_file | This is the `.net.xml` file that corresponds with our possibly-offset coordinates. | source | python | huawei-noah/SMARTS | smarts/core/sumo_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_road_network.py | MIT |
def get_distance(
self,
point: Point,
radius: float,
get_offset=...,
perpendicular: bool = False,
) -> Union[float, Tuple[float, Optional[float]]]:
"""Get the distance on the lane from the given point within the given radius.
Specifying to get the offset returns the offset value.
"""
x = point[0]
y = point[1]
r = radius
self._ensure_rtree()
dist = math.inf
INVALID_DISTANCE = -1
INVALID_INDEX = -1
found_index = INVALID_INDEX
for i in self._rtree_lane_fragments.intersection(
(x - r, y - r, x + r, y + r)
):
d = sumolib.geomhelper.distancePointToLine(
point,
self._lane_shape_for_rtree[i],
self._lane_shape_for_rtree[i + 1],
perpendicular=perpendicular,
)
if d == INVALID_DISTANCE and i != 0 and dist == math.inf:
# distance to inner corner
dist = min(
sumolib.geomhelper.distance(
point, self._lane_shape_for_rtree[i]
),
sumolib.geomhelper.distance(
point, self._lane_shape_for_rtree[i + 1]
),
)
found_index = i
elif d != INVALID_DISTANCE and (dist is None or d < dist):
dist = d
found_index = i
if get_offset is not ...:
if get_offset is False:
return dist, None
offset = 0.0
if found_index != INVALID_INDEX:
offset = self._segment_offset(found_index)
offset += sumolib.geomhelper.lineOffsetWithMinimumDistanceToPoint(
point,
self._lane_shape_for_rtree[found_index],
self._lane_shape_for_rtree[found_index + 1],
False,
)
assert isinstance(offset, float)
return dist, offset
return dist | Get the distance on the lane from the given point within the given radius.
Specifying to get the offset returns the offset value. | get_distance | python | huawei-noah/SMARTS | smarts/core/sumo_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_road_network.py | MIT |
def _waypoint_paths_at(
self,
point: Point,
lookahead: int,
filter_road_ids: Optional[Sequence[str]] = None,
) -> List[List[Waypoint]]:
"""Waypoints on this lane leading on from the given point."""
closest_linked_lp = (
self._map._lanepoints.closest_linked_lanepoint_on_lane_to_point(
point, self._lane_id
)
)
return self._map._waypoints_starting_at_lanepoint(
closest_linked_lp,
lookahead,
tuple(filter_road_ids) if filter_road_ids else (),
point,
) | Waypoints on this lane leading on from the given point. | _waypoint_paths_at | python | huawei-noah/SMARTS | smarts/core/sumo_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_road_network.py | MIT |
def _edges_at_point(self, point: Point) -> Tuple[Point, Point]:
"""Get the boundary points perpendicular to the center of the lane closest to the given
world coordinate.
Args:
point:
A world coordinate point.
Returns:
A pair of points indicating the left boundary and right boundary of the lane.
"""
offset = self.offset_along_lane(point)
width, _ = self.width_at_offset(offset)
left_edge = RefLinePoint(s=offset, t=width / 2)
right_edge = RefLinePoint(s=offset, t=-width / 2)
return self.from_lane_coord(left_edge), self.from_lane_coord(right_edge) | Get the boundary points perpendicular to the center of the lane closest to the given
world coordinate.
Args:
point:
A world coordinate point.
Returns:
A pair of points indicating the left boundary and right boundary of the lane. | _edges_at_point | python | huawei-noah/SMARTS | smarts/core/sumo_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_road_network.py | MIT |
def _edges_at_point(self, point: Point) -> Tuple[Point, Point]:
"""Get the boundary points perpendicular to the center of the road closest to the given
world coordinate.
Args:
point:
A world coordinate point.
Returns:
A pair of points indicating the left boundary and right boundary of the road.
"""
lanes = self.lanes
_, right_edge = lanes[0]._edges_at_point(point)
left_edge, _ = lanes[-1]._edges_at_point(point)
return left_edge, right_edge | Get the boundary points perpendicular to the center of the road closest to the given
world coordinate.
Args:
point:
A world coordinate point.
Returns:
A pair of points indicating the left boundary and right boundary of the road. | _edges_at_point | python | huawei-noah/SMARTS | smarts/core/sumo_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_road_network.py | MIT |
def random_route(
self,
max_route_len: int = 10,
starting_road: Optional["SumoRoadNetwork.Road"] = None,
only_drivable: bool = True,
) -> RoadMap.Route:
"""Generate a random route."""
assert not starting_road or not only_drivable or starting_road.is_drivable
next_edges = (
[starting_road._sumo_edge] if starting_road else self._graph.getEdges(False)
)
route_roads = []
cur_edge = None
while next_edges and len(route_roads) < max_route_len:
choice = random.choice(next_edges)
if cur_edge:
# include internal connection edges as well (TAI: don't count these towards max_route_len?)
connection_roads = set()
for cnxn in cur_edge.getConnections(choice):
via_lane_id = cnxn.getViaLaneID()
if via_lane_id:
via_road = self.lane_by_id(via_lane_id).road
if via_road not in connection_roads:
route_roads.append(via_road)
connection_roads.add(via_road)
cur_edge = choice
rroad = self.road_by_id(cur_edge.getID())
assert rroad.is_drivable
route_roads.append(rroad)
next_edges = list(cur_edge.getOutgoing().keys())
return SumoRoadNetwork.Route(road_map=self, roads=route_roads) | Generate a random route. | random_route | python | huawei-noah/SMARTS | smarts/core/sumo_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_road_network.py | MIT |
def _waypoint_paths_along_route(
self, point: Point, lookahead: int, route: Sequence[str]
) -> List[List[Waypoint]]:
"""finds the closest lane to vehicle's position that is on its route,
then gets waypoint paths from all lanes in its edge there."""
assert len(route) > 0, f"Expected at least 1 road in the route, got: {route}"
closest_llp_on_each_route_road = [
self._lanepoints.closest_linked_lanepoint_on_road(point, road)
for road in route
]
closest_linked_lp = min(
closest_llp_on_each_route_road,
key=lambda l_lp: np.linalg.norm(
vec_2d(l_lp.lp.pose.position) - vec_2d(point)
),
)
closest_lane = closest_linked_lp.lp.lane
waypoint_paths = []
for lane in closest_lane.road.lanes:
waypoint_paths += lane._waypoint_paths_at(point, lookahead, route)
return sorted(waypoint_paths, key=lambda p: p[0].lane_index) | finds the closest lane to vehicle's position that is on its route,
then gets waypoint paths from all lanes in its edge there. | _waypoint_paths_along_route | python | huawei-noah/SMARTS | smarts/core/sumo_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_road_network.py | MIT |
def get_edge_in_junction(
self, start_edge_id, start_lane_index, end_edge_id, end_lane_index
) -> str:
"""Returns the id of the edge between the start and end edge. Can be used for any edge but
is mainly useful for junctions.
"""
start_edge = self._graph.getEdge(start_edge_id)
start_lane = start_edge.getLane(start_lane_index)
end_edge = self._graph.getEdge(end_edge_id)
end_lane = end_edge.getLane(end_lane_index)
connection = start_lane.getConnection(end_lane)
# If there is no connection between, try and do the best
if connection is None:
# The first id is good enough since we just need to determine the junction edge id
connection = start_edge.getConnections(end_edge)[0]
connection_lane_id = connection.getViaLaneID()
connection_lane = self._graph.getLane(connection_lane_id)
return connection_lane.getEdge().getID() | Returns the id of the edge between the start and end edge. Can be used for any edge but
is mainly useful for junctions. | get_edge_in_junction | python | huawei-noah/SMARTS | smarts/core/sumo_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_road_network.py | MIT |
def update(
self,
lookahead: int,
point: Point,
filter_road_ids: tuple,
llp,
paths: List[List[Waypoint]],
):
"""Update the current cache if not already cached."""
if not self._match(lookahead, point, filter_road_ids):
self.lookahead = lookahead
self.point = point
self.filter_road_ids = filter_road_ids
self._starts = {}
self._starts[llp.lp.lane.lane_id] = paths | Update the current cache if not already cached. | update | python | huawei-noah/SMARTS | smarts/core/sumo_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_road_network.py | MIT |
def query(
self,
lookahead: int,
point: Point,
filter_road_ids: tuple,
llp,
) -> Optional[List[List[Waypoint]]]:
"""Attempt to find previously cached waypoints"""
if self._match(lookahead, point, filter_road_ids):
hit = self._starts.get(llp.lp.lane.lane_id, None)
if hit:
# consider just returning all of them (not slicing)?
return [path[: (lookahead + 1)] for path in hit]
return None | Attempt to find previously cached waypoints | query | python | huawei-noah/SMARTS | smarts/core/sumo_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_road_network.py | MIT |
def _waypoints_starting_at_lanepoint(
self,
lanepoint: LinkedLanePoint,
lookahead: int,
filter_road_ids: tuple,
point: Point,
) -> List[List[Waypoint]]:
"""computes equally-spaced Waypoints for all lane paths starting at lanepoint
up to lookahead waypoints ahead, constrained to filter_road_ids if specified."""
# The following acts sort of like lru_cache(1), but it allows
# for lookahead to be <= to the cached value...
cache_paths = self._waypoints_cache.query(
lookahead, point, filter_road_ids, lanepoint
)
if cache_paths:
return cache_paths
lanepoint_paths = self._lanepoints.paths_starting_at_lanepoint(
lanepoint, lookahead, filter_road_ids
)
result = [
SumoRoadNetwork._equally_spaced_path(
path, point, self._map_spec.lanepoint_spacing
)
for path in lanepoint_paths
]
self._waypoints_cache.update(
lookahead, point, filter_road_ids, lanepoint, result
)
return result | computes equally-spaced Waypoints for all lane paths starting at lanepoint
up to lookahead waypoints ahead, constrained to filter_road_ids if specified. | _waypoints_starting_at_lanepoint | python | huawei-noah/SMARTS | smarts/core/sumo_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_road_network.py | MIT |
def _equally_spaced_path(
path: Sequence[LinkedLanePoint],
point: Point,
lp_spacing: float,
) -> List[Waypoint]:
"""given a list of LanePoints starting near point, that may not be evenly spaced,
returns the same number of Waypoints that are evenly spaced and start at point.
"""
continuous_variables = [
"positions_x",
"positions_y",
"headings",
"lane_width",
"speed_limit",
"lane_offset",
]
discrete_variables = ["lane_id", "lane_index"]
ref_lanepoints_coordinates = {
parameter: [] for parameter in (continuous_variables + discrete_variables)
}
for idx, lanepoint in enumerate(path):
if lanepoint.is_inferred and 0 < idx < len(path) - 1:
continue
ref_lanepoints_coordinates["positions_x"].append(
lanepoint.lp.pose.position[0]
)
ref_lanepoints_coordinates["positions_y"].append(
lanepoint.lp.pose.position[1]
)
ref_lanepoints_coordinates["headings"].append(
lanepoint.lp.pose.heading.as_bullet
)
ref_lanepoints_coordinates["lane_id"].append(lanepoint.lp.lane.lane_id)
ref_lanepoints_coordinates["lane_index"].append(lanepoint.lp.lane.index)
lane_offset = lanepoint.lp.lane.offset_along_lane(lanepoint.lp.pose.point)
ref_lanepoints_coordinates["lane_width"].append(
lanepoint.lp.lane.width_at_offset(lane_offset)[0]
)
ref_lanepoints_coordinates["lane_offset"].append(lane_offset)
ref_lanepoints_coordinates["speed_limit"].append(
lanepoint.lp.lane.speed_limit
)
ref_lanepoints_coordinates["headings"] = inplace_unwrap(
ref_lanepoints_coordinates["headings"]
)
first_lp_heading = ref_lanepoints_coordinates["headings"][0]
lp_position = path[0].lp.pose.point.as_np_array[:2]
vehicle_pos = point.as_np_array[:2]
heading_vec = np.array(radians_to_vec(first_lp_heading))
projected_distant_lp_vehicle = np.inner(
(vehicle_pos - lp_position), heading_vec
)
ref_lanepoints_coordinates["positions_x"][0] = (
lp_position[0] + projected_distant_lp_vehicle * heading_vec[0]
)
ref_lanepoints_coordinates["positions_y"][0] = (
lp_position[1] + projected_distant_lp_vehicle * heading_vec[1]
)
# To ensure that the distance between waypoints are equal, we used
# interpolation approach inspired by:
# https://stackoverflow.com/a/51515357
cumulative_path_dist = np.cumsum(
np.sqrt(
np.ediff1d(ref_lanepoints_coordinates["positions_x"], to_begin=0) ** 2
+ np.ediff1d(ref_lanepoints_coordinates["positions_y"], to_begin=0) ** 2
)
)
if len(cumulative_path_dist) <= lp_spacing:
lp = path[0].lp
lane_offset = lp.lane.offset_along_lane(lp.pose.point)
return [
Waypoint(
pos=lp.pose.as_position2d(),
heading=lp.pose.heading,
lane_width=lp.lane.width_at_offset(lane_offset)[0],
speed_limit=lp.lane.speed_limit,
lane_id=lp.lane.lane_id,
lane_index=lp.lane.index,
lane_offset=lane_offset,
)
]
evenly_spaced_cumulative_path_dist = np.linspace(
0, cumulative_path_dist[-1], len(path)
)
evenly_spaced_coordinates = {}
for variable in continuous_variables:
evenly_spaced_coordinates[variable] = np.interp(
evenly_spaced_cumulative_path_dist,
cumulative_path_dist,
ref_lanepoints_coordinates[variable],
)
for variable in discrete_variables:
ref_coordinates = ref_lanepoints_coordinates[variable]
evenly_spaced_coordinates[variable] = []
jdx = 0
for idx in range(len(path)):
while (
jdx + 1 < len(cumulative_path_dist)
and evenly_spaced_cumulative_path_dist[idx]
> cumulative_path_dist[jdx + 1]
):
jdx += 1
evenly_spaced_coordinates[variable].append(ref_coordinates[jdx])
evenly_spaced_coordinates[variable].append(ref_coordinates[-1])
equally_spaced_path = []
for idx in range(len(path)):
equally_spaced_path.append(
Waypoint(
pos=np.array(
[
evenly_spaced_coordinates["positions_x"][idx],
evenly_spaced_coordinates["positions_y"][idx],
]
),
heading=Heading(evenly_spaced_coordinates["headings"][idx]),
lane_width=evenly_spaced_coordinates["lane_width"][idx],
speed_limit=evenly_spaced_coordinates["speed_limit"][idx],
lane_id=evenly_spaced_coordinates["lane_id"][idx],
lane_index=evenly_spaced_coordinates["lane_index"][idx],
lane_offset=evenly_spaced_coordinates["lane_offset"][idx],
)
)
return equally_spaced_path | given a list of LanePoints starting near point, that may not be evenly spaced,
returns the same number of Waypoints that are evenly spaced and start at point. | _equally_spaced_path | python | huawei-noah/SMARTS | smarts/core/sumo_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_road_network.py | MIT |
def act(self, obs):
"""Call the agent's act function asynchronously and return a Future."""
act_future = futures.Future()
act_future.set_result(self._agent.act(obs))
return act_future | Call the agent's act function asynchronously and return a Future. | act | python | huawei-noah/SMARTS | smarts/core/local_agent.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_agent.py | MIT |
def start(self, agent_spec: AgentSpec):
"""Send the AgentSpec to the agent runner."""
self._agent_spec = agent_spec
self._agent = self._agent_spec.build_agent() | Send the AgentSpec to the agent runner. | start | python | huawei-noah/SMARTS | smarts/core/local_agent.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_agent.py | MIT |
def get_scenario_list(scenarios_or_scenarios_dirs: Sequence[str]) -> Sequence[str]:
"""Find all specific scenario directories in the directory trees of the initial scenario
directory.
"""
scenario_roots = []
for root in scenarios_or_scenarios_dirs:
if Scenario.is_valid_scenario(root):
# This is the single scenario mode, only training against a single scenario
scenario_roots.append(root)
else:
scenario_roots.extend(Scenario.discover_scenarios(root))
return scenario_roots | Find all specific scenario directories in the directory trees of the initial scenario
directory. | get_scenario_list | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def scenario_variations(
scenarios_or_scenarios_dirs: Sequence[str],
agents_to_be_briefed: Sequence[str],
shuffle_scenarios: bool = True,
circular: bool = True,
) -> Generator["Scenario", None, None]:
"""Generate a cycle of scenario configurations.
Args:
scenarios_or_scenarios_dirs (Sequence[str]):
A sequence of either the scenario to run (see scenarios/ for some samples you
can use) OR a directory of scenarios to sample from.
agents_to_be_briefed:
Agent IDs that will be assigned a mission ("briefed" on a mission).
Returns:
A generator that serves up Scenarios.
"""
scenario_roots = Scenario.get_scenario_list(scenarios_or_scenarios_dirs)
if shuffle_scenarios:
np.random.shuffle(scenario_roots)
if circular:
scenario_roots = cycle(scenario_roots)
return Scenario.variations_for_all_scenario_roots(
scenario_roots, agents_to_be_briefed, shuffle_scenarios
) | Generate a cycle of scenario configurations.
Args:
scenarios_or_scenarios_dirs (Sequence[str]):
A sequence of either the scenario to run (see scenarios/ for some samples you
can use) OR a directory of scenarios to sample from.
agents_to_be_briefed:
Agent IDs that will be assigned a mission ("briefed" on a mission).
Returns:
A generator that serves up Scenarios. | scenario_variations | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def variations_for_all_scenario_roots(
scenario_roots, agents_to_be_briefed, shuffle_scenarios=True
) -> Generator["Scenario", None, None]:
"""Convert scenario roots to concrete scenarios.
Args:
scenario_roots:
Scenario directories containing scenario resource files.
agents_to_be_briefed:
Agent IDs that will be assigned a mission ("briefed" on a mission).
shuffle_scenarios:
Return scenarios in a pseudo-random order.
Returns:
A generator that serves up Scenarios.
"""
for scenario_root in scenario_roots:
surface_patches = Scenario.discover_friction_map(scenario_root)
agent_missions = Scenario.discover_agent_missions(
scenario_root, agents_to_be_briefed
)
social_agent_infos = Scenario._discover_social_agents_info(scenario_root)
social_agents = [
{
agent_id: (agent.to_agent_spec(), (agent, mission))
for agent_id, (
agent,
mission,
) in per_episode_social_agent_infos.items()
}
for per_episode_social_agent_infos in social_agent_infos
]
# `or [None]` so that product(...) will not return an empty result
# but insted a [(..., `None`), ...].
agent_missions = agent_missions or [None]
if len(agents_to_be_briefed) > len(agent_missions):
warnings.warn(
f"Scenario `{scenario_root}` has {len(agent_missions)} missions and"
f" but there are {len(agents_to_be_briefed)} agents to assign"
" missions to. The missions will be padded with random missions."
)
mission_agent_groups = combination_pairs_with_unique_indices(
agents_to_be_briefed, agent_missions
)
social_agents = social_agents or [None]
traffic_histories = Scenario.discover_traffic_histories(scenario_root) or [
None
]
traffic = Scenario.discover_traffic(scenario_root) or [[]]
roll_traffic = 0
roll_social_agents = 0
roll_traffic_histories = 0
if shuffle_scenarios:
roll_traffic = random.randint(0, len(traffic))
roll_social_agents = random.randint(0, len(social_agents))
roll_traffic_histories = 0 # random.randint(0, len(traffic_histories))
for (
concrete_traffic,
concrete_agent_missions,
concrete_social_agents,
concrete_traffic_history,
) in product(
np.roll(traffic, roll_traffic, 0),
mission_agent_groups,
np.roll(social_agents, roll_social_agents, 0),
np.roll(traffic_histories, roll_traffic_histories, 0),
):
concrete_social_agent_missions = {
agent_id: mission
for agent_id, (_, (_, mission)) in (
concrete_social_agents or {}
).items()
}
# Filter out mission
concrete_social_agents = {
agent_id: (_agent_spec, social_agent)
for agent_id, (_agent_spec, (social_agent, _)) in (
concrete_social_agents or {}
).items()
}
yield Scenario(
scenario_root,
traffic_specs=concrete_traffic,
missions={
**{a_id: mission for a_id, mission in concrete_agent_missions},
**concrete_social_agent_missions,
},
social_agents=concrete_social_agents,
surface_patches=surface_patches,
traffic_history=concrete_traffic_history,
) | Convert scenario roots to concrete scenarios.
Args:
scenario_roots:
Scenario directories containing scenario resource files.
agents_to_be_briefed:
Agent IDs that will be assigned a mission ("briefed" on a mission).
shuffle_scenarios:
Return scenarios in a pseudo-random order.
Returns:
A generator that serves up Scenarios. | variations_for_all_scenario_roots | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def discover_agent_missions_count(scenario_root):
"""Retrieve the agent missions from the given scenario directory."""
missions_file = os.path.join(scenario_root, "build", "missions.pkl")
if os.path.exists(missions_file):
with open(missions_file, "rb") as f:
return len(pickle.load(f))
return 0 | Retrieve the agent missions from the given scenario directory. | discover_agent_missions_count | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def discover_agent_missions(scenario_root, agents_to_be_briefed):
"""Returns a sequence of {agent_id: mission} mappings.
If no missions are discovered we generate random ones. If there is only one
agent to be briefed we return a list of `{agent_id: mission}` cycling through
each mission. If there are multiple agents to be briefed we assume that each
one is intended to get its own mission and that `len(agents_to_be_briefed) ==
len(missions)`. In this case a list of one dictionary is returned.
"""
road_map, _ = Scenario.build_map(scenario_root)
missions = []
missions_file = os.path.join(scenario_root, "build", "missions.pkl")
if os.path.exists(missions_file):
with open(missions_file, "rb") as f:
missions = pickle.load(f)
missions = [
Scenario._extract_mission(actor_and_mission.mission, road_map)
for actor_and_mission in missions
]
if not missions:
missions = [None for _ in range(len(agents_to_be_briefed))]
return missions | Returns a sequence of {agent_id: mission} mappings.
If no missions are discovered we generate random ones. If there is only one
agent to be briefed we return a list of `{agent_id: mission}` cycling through
each mission. If there are multiple agents to be briefed we assume that each
one is intended to get its own mission and that `len(agents_to_be_briefed) ==
len(missions)`. In this case a list of one dictionary is returned. | discover_agent_missions | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def discover_friction_map(scenario_root) -> List[Dict[str, Any]]:
"""Returns the list of surface patches parameters defined in
scenario file. Each element of the list contains the
parameters of the specified surface patch.
"""
surface_patches = []
friction_map_file = os.path.join(scenario_root, "build", "friction_map.pkl")
if os.path.exists(friction_map_file):
with open(friction_map_file, "rb") as f:
map_surface_patches = pickle.load(f)
for surface_patch in map_surface_patches:
surface_patches.append(
{
"zone": surface_patch.zone,
"begin_time": surface_patch.begin_time,
"end_time": surface_patch.end_time,
"friction coefficient": surface_patch.friction_coefficient,
}
)
return surface_patches | Returns the list of surface patches parameters defined in
scenario file. Each element of the list contains the
parameters of the specified surface patch. | discover_friction_map | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def _discover_social_agents_info(
scenario: Union[str, Scenario],
) -> Sequence[Dict[str, Tuple[SocialAgent, NavigationMission]]]:
"""Loops through the social agent mission pickles, instantiating corresponding
implementations for the given types. The output is a list of
{agent_id: (mission, locator)}, where each dictionary corresponds to the
social agents to run for a given concrete Scenario (which translates to
"per episode" when swapping).
"""
scenario_root = (
scenario.root_filepath if isinstance(scenario, Scenario) else scenario
)
road_map, _ = Scenario.build_map(scenario_root)
social_agents_path = os.path.join(scenario_root, "build", "social_agents")
if not os.path.exists(social_agents_path):
return []
# [ ( missions_file, agent_actor, Mission ) ]
agent_bucketer = []
# like dict.setdefault
def setdefault(l: list, index: int, default):
while len(l) < index + 1:
l.append([])
return l[index]
file_match = os.path.join(social_agents_path, "*.pkl")
for missions_file_path in glob.glob(file_match):
with open(missions_file_path, "rb") as missions_file:
count = 0
missions = pickle.load(missions_file)
for mission_and_actor in missions:
# Each pickle file will contain a list of actor/mission pairs. The pairs
# will most likely be generated in an M:N fashion
# (i.e. A1: M1, A1: M2, A2: M1, A2: M2). The desired behavior is to have
# a single pair per concrete Scenario (which would translate to
# "per episode" when swapping)
assert isinstance(
mission_and_actor.actor, sstudio_types.SocialAgentActor
)
actor = mission_and_actor.actor
extracted_mission = Scenario._extract_mission(
mission_and_actor.mission, road_map
)
namespace = os.path.basename(missions_file_path)
namespace = os.path.splitext(namespace)[0]
setdefault(agent_bucketer, count, []).append(
(
SocialAgent(
id=SocialAgentId.new(actor.name, group=namespace),
actor_name=actor.name,
is_boid=False,
is_boid_keep_alive=False,
agent_locator=actor.agent_locator,
policy_kwargs=actor.policy_kwargs,
initial_speed=actor.initial_speed,
),
extracted_mission,
)
)
count += 1
social_agents_info = []
for l in agent_bucketer:
social_agents_info.append(
{agent.id: (agent, mission) for agent, mission in l}
)
return social_agents_info | Loops through the social agent mission pickles, instantiating corresponding
implementations for the given types. The output is a list of
{agent_id: (mission, locator)}, where each dictionary corresponds to the
social agents to run for a given concrete Scenario (which translates to
"per episode" when swapping). | _discover_social_agents_info | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def discover_scenarios(scenario_or_scenarios_dir):
"""Retrieve all specific scenarios in the directory tree of the given scenario directory.
Args:
scenario_or_scenario_dir:
A directory that either immediately contains a scenario or the root of a directory tree that contains multiple scenarios.
Returns:
All specific scenarios.
"""
if Scenario.is_valid_scenario(scenario_or_scenarios_dir):
# This is the single scenario mode, only training against a single scenario
scenario = scenario_or_scenarios_dir
discovered_scenarios = [scenario]
else:
# Find all valid scenarios in the given scenarios directory
discovered_scenarios = []
for scenario_file in os.listdir(scenario_or_scenarios_dir):
scenario_root = os.path.join(scenario_or_scenarios_dir, scenario_file)
if Scenario.is_valid_scenario(scenario_root):
discovered_scenarios.append(scenario_root)
assert (
len(discovered_scenarios) > 0
), f"No valid scenarios found in {scenario_or_scenarios_dir}"
return discovered_scenarios | Retrieve all specific scenarios in the directory tree of the given scenario directory.
Args:
scenario_or_scenario_dir:
A directory that either immediately contains a scenario or the root of a directory tree that contains multiple scenarios.
Returns:
All specific scenarios. | discover_scenarios | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def build_map(scenario_root: str) -> Tuple[Optional[RoadMap], Optional[str]]:
"""Builds a road map from the given scenario's resources."""
# XXX: using a map builder_fn supplied by users is a security risk
# as SMARTS will be executing the code "as is". We are currently
# trusting our users to not try to sabotage their own simulations.
# In the future, this may need to be revisited if SMARTS is ever
# shared in a multi-user mode.
map_spec = Scenario.discover_map(scenario_root)
return map_spec.builder_fn(map_spec) | Builds a road map from the given scenario's resources. | build_map | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def discover_map(
scenario_root: str,
lanepoint_spacing: Optional[float] = None,
default_lane_width: Optional[float] = None,
shift_to_origin: bool = False,
) -> MapSpec:
"""Generates the map specification from the given scenario's file resources.
Args:
scenarios_root:
A specific scenario to run (e.g. scenarios/sumo/loop)
lanepoint_spacing:
The distance between lane-points that represent a lane's geometry.
default_lane_width:
The default width of a lane from its center if it does not have a specific width.
shift_to_origin:
Shifts the map location to near the simulation origin so that the map contains (0, 0).
Returns:
A new map spec.
"""
path = os.path.join(scenario_root, "build", "map", "map_spec.pkl")
if not os.path.exists(path):
# Use our default map builder if none specified by scenario...
return MapSpec(
scenario_root,
lanepoint_spacing,
default_lane_width,
shift_to_origin,
)
with open(path, "rb") as f:
road_map = cloudpickle.load(f)
return road_map | Generates the map specification from the given scenario's file resources.
Args:
scenarios_root:
A specific scenario to run (e.g. scenarios/sumo/loop)
lanepoint_spacing:
The distance between lane-points that represent a lane's geometry.
default_lane_width:
The default width of a lane from its center if it does not have a specific width.
shift_to_origin:
Shifts the map location to near the simulation origin so that the map contains (0, 0).
Returns:
A new map spec. | discover_map | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def discover_routes(scenario_root):
"""Discover the route files in the given scenario.
>>> Scenario.discover_routes("scenarios/sumo/intersections/2lane")
['all.rou.xml', 'horizontal.rou.xml', 'turns.rou.xml', 'unprotected_left.rou.xml', 'vertical.rou.xml']
>>> Scenario.discover_routes("scenarios/sumo/loop") # loop does not have any routes
['basic.rou.xml']
"""
warnings.warn(
"Scenario.discover_routes() has been deprecated in favor of Scenario.discover_traffic(). Please update your code.",
category=DeprecationWarning,
)
return sorted(
[
os.path.basename(r)
for r in glob.glob(
os.path.join(scenario_root, "build", "traffic", "*.rou.xml")
)
]
) | Discover the route files in the given scenario.
>>> Scenario.discover_routes("scenarios/sumo/intersections/2lane")
['all.rou.xml', 'horizontal.rou.xml', 'turns.rou.xml', 'unprotected_left.rou.xml', 'vertical.rou.xml']
>>> Scenario.discover_routes("scenarios/sumo/loop") # loop does not have any routes
['basic.rou.xml'] | discover_routes | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def discover_traffic(scenario_root: str) -> List[Optional[List[str]]]:
"""Discover the traffic spec files in the given scenario."""
traffic_path = os.path.join(scenario_root, "build", "traffic")
# combine any SMARTS and SUMO traffic together...
sumo_traffic = glob.glob(os.path.join(traffic_path, "*.rou.xml"))
smarts_traffic = glob.glob(os.path.join(traffic_path, "*.smarts.xml"))
if sumo_traffic and not smarts_traffic:
return [[ts] for ts in sumo_traffic]
elif not sumo_traffic and smarts_traffic:
return [[ts] for ts in smarts_traffic]
return [list(ts) for ts in product(sumo_traffic, smarts_traffic)] | Discover the traffic spec files in the given scenario. | discover_traffic | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def set_ego_missions(self, ego_missions: Dict[str, NavigationMission]):
"""Replaces the ego missions within the scenario.
Args:
ego_missions: Ego agent ids mapped to missions.
"""
self._missions = ego_missions | Replaces the ego missions within the scenario.
Args:
ego_missions: Ego agent ids mapped to missions. | set_ego_missions | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def get_vehicle_start_at_time(
self, vehicle_id: str, start_time: float
) -> Tuple[Start, float]:
"""Returns a Start object that can be used to create a Mission for
a vehicle from a traffic history dataset starting at its location
at start_time. Also returns its speed at that time."""
pphs = self._traffic_history.vehicle_pose_at_time(vehicle_id, start_time)
assert pphs
pos_x, pos_y, heading, speed = pphs
# missions start from front bumper, but pos is center of vehicle
veh_dims = self._traffic_history.vehicle_dims(vehicle_id)
hhx, hhy = radians_to_vec(heading) * (0.5 * veh_dims.length)
return (
Start(
np.array([pos_x + hhx, pos_y + hhy]),
Heading(heading),
from_front_bumper=True,
),
speed,
) | Returns a Start object that can be used to create a Mission for
a vehicle from a traffic history dataset starting at its location
at start_time. Also returns its speed at that time. | get_vehicle_start_at_time | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def get_vehicle_goal(self, vehicle_id: str) -> Point:
"""Get the final position for a history vehicle."""
final_exit_time = self._traffic_history.vehicle_final_exit_time(vehicle_id)
final_pose = self._traffic_history.vehicle_pose_at_time(
vehicle_id, final_exit_time
)
assert final_pose
final_pos_x, final_pos_y, _, _ = final_pose
return Point(final_pos_x, final_pos_y) | Get the final position for a history vehicle. | get_vehicle_goal | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def discover_missions_of_traffic_histories(self) -> Dict[str, NavigationMission]:
"""Retrieves the missions of traffic history vehicles."""
vehicle_missions = {}
for row in self._traffic_history.first_seen_times():
v_id = str(row[0])
start_time = float(row[1])
start, speed = self.get_vehicle_start_at_time(v_id, start_time)
entry_tactic = default_entry_tactic(speed)
veh_config_type = self._traffic_history.vehicle_config_type(v_id)
veh_dims = self._traffic_history.vehicle_dims(v_id)
vehicle_missions[v_id] = NavigationMission(
start=start,
entry_tactic=entry_tactic,
goal=TraverseGoal(self.road_map),
start_time=start_time,
vehicle_spec=VehicleSpec(
veh_id=v_id,
veh_config_type=veh_config_type,
dimensions=veh_dims,
),
)
return vehicle_missions | Retrieves the missions of traffic history vehicles. | discover_missions_of_traffic_histories | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def create_dynamic_traffic_history_mission(
self, vehicle_id: str, trigger_time: float, positional_radius: int
) -> Tuple[NavigationMission, NavigationMission]:
"""Builds missions out of the given vehicle information.
Args:
vehicle_id:
The id of a vehicle in the traffic history dataset.
trigger_time:
The time that this mission should become active.
positional_radius:
The goal radius for the positional goal.
Returns:
(smarts.core.plan.NavigationMission, smarts.core.plan.NavigationMission): A positional mission that follows the initial
original vehicle's travel as well as a traverse style mission which is done when the
vehicle leaves the map.
"""
start, speed = self.get_vehicle_start_at_time(vehicle_id, trigger_time)
veh_goal = self.get_vehicle_goal(vehicle_id)
entry_tactic = default_entry_tactic(speed)
# create a positional mission and a traverse mission
positional_mission = NavigationMission(
start=start,
entry_tactic=entry_tactic,
goal=PositionalGoal(veh_goal, radius=positional_radius),
)
traverse_mission = NavigationMission(
start=start,
entry_tactic=entry_tactic,
goal=TraverseGoal(self._road_map),
)
return positional_mission, traverse_mission | Builds missions out of the given vehicle information.
Args:
vehicle_id:
The id of a vehicle in the traffic history dataset.
trigger_time:
The time that this mission should become active.
positional_radius:
The goal radius for the positional goal.
Returns:
(smarts.core.plan.NavigationMission, smarts.core.plan.NavigationMission): A positional mission that follows the initial
original vehicle's travel as well as a traverse style mission which is done when the
vehicle leaves the map. | create_dynamic_traffic_history_mission | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def history_missions_for_window(
self,
exists_at_or_after: float,
ends_before: float,
minimum_vehicle_window: float,
filter: Optional[
Callable[
[Iterable[VehicleWindow]],
Iterable[VehicleWindow],
]
] = None,
) -> Sequence[NavigationMission]:
"""Discovers vehicle missions for the given window of time.
:param exists_at_or_after: The starting time of any vehicles to query for.
:type exists_at_or_after: float
:param ends_before: The last point in time a vehicle should be in the simulation.
Vehicles ending after that time are not considered.
:type ends_before: float
:param minimum_vehicle_window: The minimum time that a vehicle must be in the simulation
to be considered for a mission.
:type minimum_vehicle_window: float
:param filter: A filter in the form of ``(func(Sequence[TrafficHistoryVehicleWindow]) -> Sequence[TrafficHistoryVehicleWindow])``,
which passes in traffic vehicle information and then should be used purely to filter the sequence down.
:return: A set of missions derived from the traffic history.
:rtype: List[smarts.core.plan.NavigationMission]
"""
vehicle_windows = self._traffic_history.vehicle_windows_in_range(
exists_at_or_after, ends_before, minimum_vehicle_window
)
def _gen_mission(vw: TrafficHistory.TrafficHistoryVehicleWindow):
assert isinstance(
vw, TrafficHistory.TrafficHistoryVehicleWindow
), "`filter(..)` likely returns malformed data."
v_id = str(vw.vehicle_id)
start_time = float(vw.start_time)
start = Start(
np.array(vw.axle_start_position),
Heading(vw.start_heading),
)
entry_tactic = default_entry_tactic(vw.start_speed)
veh_config_type = vw.vehicle_type
veh_dims = vw.dimensions
vehicle_mission = NavigationMission(
start=start,
entry_tactic=entry_tactic,
goal=TraverseGoal(self.road_map),
start_time=start_time,
vehicle_spec=VehicleSpec(
veh_id=v_id,
veh_config_type=veh_config_type,
dimensions=veh_dims,
),
)
return vehicle_mission
if filter is not None:
vehicle_windows = filter(vehicle_windows)
return [_gen_mission(vw) for vw in vehicle_windows] | Discovers vehicle missions for the given window of time.
:param exists_at_or_after: The starting time of any vehicles to query for.
:type exists_at_or_after: float
:param ends_before: The last point in time a vehicle should be in the simulation.
Vehicles ending after that time are not considered.
:type ends_before: float
:param minimum_vehicle_window: The minimum time that a vehicle must be in the simulation
to be considered for a mission.
:type minimum_vehicle_window: float
:param filter: A filter in the form of ``(func(Sequence[TrafficHistoryVehicleWindow]) -> Sequence[TrafficHistoryVehicleWindow])``,
which passes in traffic vehicle information and then should be used purely to filter the sequence down.
:return: A set of missions derived from the traffic history.
:rtype: List[smarts.core.plan.NavigationMission] | history_missions_for_window | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def discover_traffic_histories(scenario_root: str):
"""Finds all existing traffic history files in the specific scenario."""
build_dir = Path(scenario_root) / "build"
return [
entry
for entry in os.scandir(str(build_dir))
if entry.is_file() and entry.path.endswith(".shf")
] | Finds all existing traffic history files in the specific scenario. | discover_traffic_histories | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def _extract_mission(mission, road_map):
"""Takes a sstudio.sstypes.(Mission, EndlessMission, etc.) and converts it to
the corresponding SMARTS mission types.
"""
def resolve_offset(offset: Union[str, float], lane_length: float):
# epsilon to ensure we are within this edge and not the subsequent one
epsilon = 1e-6
lane_length -= epsilon
if offset == "base":
return epsilon
elif offset == "max":
return lane_length
elif offset == "random":
return random.uniform(epsilon, lane_length)
else:
return float(offset)
def to_position_and_heading(
road_id: str, lane_index: int, offset: Union[str, float], road_map: RoadMap
):
road = road_map.road_by_id(road_id)
lane = road.lane_at_index(lane_index)
offset = resolve_offset(offset, lane.length)
position = lane.from_lane_coord(RefLinePoint(s=offset))
lane_vector = lane.vector_at_offset(offset)
heading = vec_to_radians(lane_vector[:2])
return position, Heading(heading)
def to_scenario_via(
vias: Tuple[SSVia, ...], road_map: RoadMap
) -> Tuple[Via, ...]:
s_vias = []
for via in vias:
road = road_map.road_by_id(via.road_id)
lane = road.lane_at_index(via.lane_index)
lane_width, _ = lane.width_at_offset(via.lane_offset)
hit_distance = (
via.hit_distance if via.hit_distance > 0 else lane_width / 2
)
via_position = lane.from_lane_coord(RefLinePoint(via.lane_offset))
s_vias.append(
Via(
lane_id=lane.lane_id,
lane_index=via.lane_index,
road_id=via.road_id,
position=tuple(via_position[:2]),
hit_distance=hit_distance,
required_speed=via.required_speed,
)
)
return tuple(s_vias)
# XXX: For now we discard the route and just take the start and end to form our missions.
# In the future, we could create a Plan object here too when there's a route specified.
if isinstance(mission, sstudio_types.Mission):
position, heading = to_position_and_heading(
*mission.route.begin,
road_map,
)
start = Start(position, heading)
position, _ = to_position_and_heading(
*mission.route.end,
road_map,
)
goal = PositionalGoal(position, radius=2)
entry_tactic = mission.entry_tactic
start_time = Scenario._extract_mission_start_time(mission, entry_tactic)
return NavigationMission(
start=start,
route_vias=mission.route.via,
goal=goal,
start_time=start_time,
entry_tactic=entry_tactic,
via=to_scenario_via(mission.via, road_map),
)
elif isinstance(mission, sstudio_types.EndlessMission):
position, heading = to_position_and_heading(
*mission.begin,
road_map,
)
start = Start(position, heading)
entry_tactic = mission.entry_tactic
start_time = Scenario._extract_mission_start_time(mission, entry_tactic)
return NavigationMission(
start=start,
goal=EndlessGoal(),
start_time=start_time,
entry_tactic=entry_tactic,
via=to_scenario_via(mission.via, road_map),
)
elif isinstance(mission, sstudio_types.LapMission):
start_road_id, start_lane, start_road_offset = mission.route.begin
end_road_id, end_lane, end_road_offset = mission.route.end
travel_road = road_map.road_by_id(start_road_id)
if start_road_id == end_road_id:
travel_road = travel_road.outgoing_roads[0]
end_road = road_map.road_by_id(end_road_id)
via_roads = [road_map.road_by_id(r) for r in mission.route.via]
route = road_map.generate_routes(travel_road, end_road, via_roads, 1)[0]
start_position, start_heading = to_position_and_heading(
*mission.route.begin,
road_map,
)
end_position, _ = to_position_and_heading(
*mission.route.end,
road_map,
)
entry_tactic = mission.entry_tactic
start_time = Scenario._extract_mission_start_time(mission, entry_tactic)
return LapMission(
start=Start(start_position, start_heading),
goal=PositionalGoal(end_position, radius=2),
route_vias=mission.route.via,
start_time=start_time,
entry_tactic=entry_tactic,
via=to_scenario_via(mission.via, road_map),
num_laps=mission.num_laps,
route_length=route.road_length,
)
raise RuntimeError(
f"sstudio mission={mission} is an invalid type={type(mission)}"
) | Takes a sstudio.sstypes.(Mission, EndlessMission, etc.) and converts it to
the corresponding SMARTS mission types. | _extract_mission | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def is_valid_scenario(scenario_root) -> bool:
"""Checks if the scenario_root directory matches our expected scenario structure
>>> Scenario.is_valid_scenario("scenarios/sumo/loop")
True
>>> Scenario.is_valid_scenario("scenarios/non_existant")
False
"""
# just make sure we can load the map
try:
road_map, _ = Scenario.build_map(scenario_root)
except FileNotFoundError:
return False
return road_map is not None | Checks if the scenario_root directory matches our expected scenario structure
>>> Scenario.is_valid_scenario("scenarios/sumo/loop")
True
>>> Scenario.is_valid_scenario("scenarios/non_existant")
False | is_valid_scenario | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def next(scenario_iterator, log_id="") -> "Scenario":
"""Utility to override specific attributes from a scenario iterator"""
scenario = next(scenario_iterator)
scenario._log_id = log_id
return scenario | Utility to override specific attributes from a scenario iterator | next | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def name(self) -> str:
"""The name of the scenario."""
return os.path.normpath(self._root) | The name of the scenario. | name | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def root_filepath(self) -> str:
"""The root directory of the scenario."""
return self._root | The root directory of the scenario. | root_filepath | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def surface_patches(self):
"""A list of surface areas with dynamics implications (e.g. icy road.)"""
return self._surface_patches | A list of surface areas with dynamics implications (e.g. icy road.) | surface_patches | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def road_map_hash(self):
"""A hash value of this road map."""
return self._road_map_hash | A hash value of this road map. | road_map_hash | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def plane_filepath(self) -> str:
"""The ground plane."""
return os.path.join(self._root, "plane.urdf") | The ground plane. | plane_filepath | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def vehicle_filepath(self) -> Optional[str]:
"""The file-path of the vehicle's physics model."""
warnings.warn(
"tire_parameters_filepath is no longer in use. Please update your code.",
category=DeprecationWarning,
)
if not os.path.isdir(self._root):
return None
for fname in os.listdir(self._root):
if fname.endswith("vehicle.urdf"):
return os.path.join(self._root, fname)
return None | The file-path of the vehicle's physics model. | vehicle_filepath | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def tire_parameters_filepath(self) -> str:
"""The path of the tire model's parameters."""
warnings.warn(
"tire_parameters_filepath is no longer in use. Please update your code.",
category=DeprecationWarning,
)
return os.path.join(self._root, "tire_parameters.yaml") | The path of the tire model's parameters. | tire_parameters_filepath | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def controller_parameters_filepath(self) -> str:
"""The path of the vehicle controller parameters."""
warnings.warn(
"controller_parameters_filepath is no longer in use. Please update your code.",
category=DeprecationWarning,
)
return os.path.join(self._root, "controller_parameters.yaml") | The path of the vehicle controller parameters. | controller_parameters_filepath | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def vehicle_definitions_filepath(self) -> str:
"""The path to the default list of vehicle definitions."""
return os.path.join(self._root, "vehicle_definitions_list.yaml") | The path to the default list of vehicle definitions. | vehicle_definitions_filepath | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def traffic_specs(self) -> Sequence[str]:
"""The traffic spec file names to use for this scenario."""
return self._traffic_specs | The traffic spec file names to use for this scenario. | traffic_specs | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def route(self) -> Optional[str]:
"""The traffic route file name."""
warnings.warn(
"Scenario route property has been deprecated in favor of traffic_specs. Please update your code.",
category=DeprecationWarning,
)
assert len(self._traffic_specs) <= 1
return (
os.path.basename(self._traffic_specs[0])
if len(self._traffic_specs) == 1
else None
) | The traffic route file name. | route | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def route_files_enabled(self):
"""If there is a traffic route file."""
warnings.warn(
"Scenario route_file_enabled property has been deprecated in favor of traffic_specs. Please update your code.",
category=DeprecationWarning,
)
return bool(self._traffic_specs) | If there is a traffic route file. | route_files_enabled | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def route_filepath(self):
"""The file-path to the traffic route file."""
warnings.warn(
"Scenario route_filepath property has been deprecated in favor of traffic_specs. Please update your code.",
category=DeprecationWarning,
)
assert len(self._traffic_specs) == 1
return self._traffic_specs[0] | The file-path to the traffic route file. | route_filepath | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def map_glb_filepath(self):
"""The map geometry file-path."""
return os.path.join(self._root, "build", "map", "map.glb") | The map geometry file-path. | map_glb_filepath | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def map_glb_metadata(self):
"""The metadata for the current map `.glb` file."""
metadata = self.map_glb_meta_for_file(self.map_glb_filepath)
return metadata | The metadata for the current map `.glb` file. | map_glb_metadata | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def map_glb_meta_for_file(filepath):
"""The map metadata given a file."""
scene = trimesh.load(filepath)
return scene.metadata | The map metadata given a file. | map_glb_meta_for_file | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def unique_sumo_log_file(self):
"""A unique logging file for SUMO logging."""
return os.path.join(self._log_dir, f"sumo-{str(uuid.uuid4())[:8]}") | A unique logging file for SUMO logging. | unique_sumo_log_file | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def road_map(self) -> RoadMap:
"""The road map of the scenario."""
return self._road_map | The road map of the scenario. | road_map | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def map_spec(self) -> Optional[MapSpec]:
"""The map spec for the road map used in this scenario."""
return self.road_map.map_spec | The map spec for the road map used in this scenario. | map_spec | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def supports_sumo_traffic(self) -> bool:
"""Returns True if this scenario uses a Sumo road network."""
from smarts.core.sumo_road_network import SumoRoadNetwork
return isinstance(self._road_map, SumoRoadNetwork) | Returns True if this scenario uses a Sumo road network. | supports_sumo_traffic | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def any_support_sumo_traffic(scenarios: Sequence[str]) -> bool:
"""Determines if any of the given scenarios support Sumo traffic simulation."""
from smarts.core.default_map_builder import MapType, find_mapfile_in_dir
for scenario_root in Scenario.get_scenario_list(scenarios):
map_type, _ = find_mapfile_in_dir(scenario_root)
if map_type == MapType.Sumo:
return True
return False | Determines if any of the given scenarios support Sumo traffic simulation. | any_support_sumo_traffic | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def all_support_sumo_traffic(scenarios: Sequence[str]) -> bool:
"""Determines if all given scenarios support Sumo traffic simulation."""
from smarts.core.sumo_road_network import SumoRoadNetwork
for scenario_root in Scenario.get_scenario_list(scenarios):
try:
road_map, _ = Scenario.build_map(scenario_root)
except FileNotFoundError:
raise FileNotFoundError(
f"Unable to find network file in map_source={scenario_root}."
)
if not isinstance(road_map, SumoRoadNetwork):
return False
return True | Determines if all given scenarios support Sumo traffic simulation. | all_support_sumo_traffic | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def missions(self) -> Dict[str, NavigationMission]:
"""Agent missions contained within this scenario."""
return self._missions | Agent missions contained within this scenario. | missions | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def social_agents(self) -> Dict[str, Tuple[Any, SocialAgent]]:
"""Managed social agents within this scenario."""
return self._social_agents | Managed social agents within this scenario. | social_agents | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def bubbles(self):
"""Bubbles within this scenario."""
return self._bubbles | Bubbles within this scenario. | bubbles | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def mission(self, agent_id) -> Optional[NavigationMission]:
"""Get the mission assigned to the given agent."""
return self._missions.get(agent_id, None) | Get the mission assigned to the given agent. | mission | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def traffic_history(self) -> Optional[TrafficHistory]:
"""Traffic history contained within this scenario."""
return self._traffic_history | Traffic history contained within this scenario. | traffic_history | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def scenario_hash(self) -> str:
"""A hash of the scenario."""
return self._scenario_hash | A hash of the scenario. | scenario_hash | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def metadata(self) -> Dict:
"""Scenario metadata values.
Returns:
Dict: The values.
"""
return self._metadata or {} | Scenario metadata values.
Returns:
Dict: The values. | metadata | python | huawei-noah/SMARTS | smarts/core/scenario.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/scenario.py | MIT |
def perform_agent_actions(self, agent_actions: Dict[str, Any]):
"""Applies any actions specified by agents controlling the actors managed by
this provider via appropriate controllers (to their chassis if vehicles).
Args:
agent_actions: a dictionary from each agent_id to its actions for this step.
"""
self._remove_actors_without_actions(agent_actions)
agents_without_actors = agent_actions.keys() - self._my_agent_actors.keys()
if agents_without_actors:
warnings.warn(
"actions specified for an agent without an actor: %s."
% agents_without_actors,
)
agent_manager = self._agent_manager
sensor_manager = self._sensor_manager
vehicle_index = self._vehicle_index
sim = self._sim()
assert sim
for agent_id, vehicle_states in self._my_agent_actors.items():
action = agent_actions.get(agent_id)
if action is None or len(action) == 0:
self._log.info("no actions for agent_id=%s", agent_id)
continue
if agent_id in agents_without_actors:
continue
agent_interface = agent_manager.agent_interface_for_agent_id(agent_id)
is_boid_agent = agent_manager.is_boid_agent(agent_id)
for vs in vehicle_states:
vehicle = vehicle_index.vehicle_by_id(vs.actor_id)
vehicle_action = action[vehicle.id] if is_boid_agent else action
controller_state = vehicle_index.controller_state_for_vehicle_id(
vehicle.id
)
sensor_state = sensor_manager.sensor_state_for_actor_id(vehicle.id)
Controllers.perform_action(
sim,
agent_id,
vehicle,
vehicle_action,
controller_state,
sensor_state,
agent_interface.action,
) | Applies any actions specified by agents controlling the actors managed by
this provider via appropriate controllers (to their chassis if vehicles).
Args:
agent_actions: a dictionary from each agent_id to its actions for this step. | perform_agent_actions | python | huawei-noah/SMARTS | smarts/core/agents_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agents_provider.py | MIT |
def actor_ids(self) -> Iterable[str]:
"""The set of actors that this provider manages.
Returns:
Iterable[str]: The actors this provider manages.
"""
return set(vs.actor_id for vss in self._my_agent_actors.values() for vs in vss) | The set of actors that this provider manages.
Returns:
Iterable[str]: The actors this provider manages. | actor_ids | python | huawei-noah/SMARTS | smarts/core/agents_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agents_provider.py | MIT |
def start_time(self):
"""The start time of the traffic playback"""
return self._start_time_offset | The start time of the traffic playback | start_time | python | huawei-noah/SMARTS | smarts/core/traffic_history_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/traffic_history_provider.py | MIT |
def done_this_step(self):
"""The vehicles that are to be removed this step."""
return self._this_step_dones | The vehicles that are to be removed this step. | done_this_step | python | huawei-noah/SMARTS | smarts/core/traffic_history_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/traffic_history_provider.py | MIT |
def setup(self, scenario) -> ProviderState:
"""Initialize this provider with the given scenario."""
if "history_vehicle_ids" in self.__dict__:
# clear the cached_property
del self.__dict__["history_vehicle_ids"]
self._scenario = scenario
self._histories = scenario.traffic_history
if self._histories:
self._histories.connect_for_multiple_queries()
self._reset_scenario_state()
self._is_setup = True
return ProviderState() | Initialize this provider with the given scenario. | setup | python | huawei-noah/SMARTS | smarts/core/traffic_history_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/traffic_history_provider.py | MIT |
def set_replaced_ids(self, actor_ids: Iterable[str]):
"""Replace the given vehicles, excluding them from control by this provider."""
self._replaced_actor_ids.update(self._get_base_id(a_id) for a_id in actor_ids) | Replace the given vehicles, excluding them from control by this provider. | set_replaced_ids | python | huawei-noah/SMARTS | smarts/core/traffic_history_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/traffic_history_provider.py | MIT |
def history_vehicle_ids(self) -> Set[str]:
"""Actor IDs for all history vehicles."""
if not self._histories:
return set()
return {
self._dbid_to_actor_id(hvid) for hvid in self._histories.all_vehicle_ids()
} | Actor IDs for all history vehicles. | history_vehicle_ids | python | huawei-noah/SMARTS | smarts/core/traffic_history_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/traffic_history_provider.py | MIT |
def vehicle_history_window(
self, vehicle_id: str
) -> TrafficHistory.TrafficHistoryVehicleWindow:
"""Retrieves vehicle history in the specified time window.
Args:
vehicle_id (str): Id of vehicle of interest.
Raises:
ValueError: If `vehicle_id` is not present in traffic history.
Returns:
TrafficHistory.TrafficHistoryVehicleWindow: Vehicle history in the
specified time window.
"""
if vehicle_id in self.history_vehicle_ids:
vehicle_id = vehicle_id[len(self._vehicle_id_prefix) :]
else:
raise ValueError(
f"Vehicle id {vehicle_id} is not present in traffic history."
)
return self._histories.vehicle_window_by_id(vehicle_id=vehicle_id) | Retrieves vehicle history in the specified time window.
Args:
vehicle_id (str): Id of vehicle of interest.
Raises:
ValueError: If `vehicle_id` is not present in traffic history.
Returns:
TrafficHistory.TrafficHistoryVehicleWindow: Vehicle history in the
specified time window. | vehicle_history_window | python | huawei-noah/SMARTS | smarts/core/traffic_history_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/traffic_history_provider.py | MIT |
def point(self) -> Point:
"""The coordinate of this starting location."""
return Point.from_np_array(self.position) | The coordinate of this starting location. | point | python | huawei-noah/SMARTS | smarts/core/plan.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/plan.py | MIT |
def from_pose(cls, pose: Pose):
"""Convert to a starting location from a pose."""
return cls(
position=pose.as_position2d(),
heading=pose.heading,
from_front_bumper=False,
) | Convert to a starting location from a pose. | from_pose | python | huawei-noah/SMARTS | smarts/core/plan.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/plan.py | MIT |
def is_specific(self) -> bool:
"""If the goal is reachable at a specific position."""
return False | If the goal is reachable at a specific position. | is_specific | python | huawei-noah/SMARTS | smarts/core/plan.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/plan.py | MIT |
def is_reached(self, vehicle_state) -> bool:
"""If the goal has been completed."""
return False | If the goal has been completed. | is_reached | python | huawei-noah/SMARTS | smarts/core/plan.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/plan.py | MIT |
def from_road(
cls,
road_id: str,
road_map: RoadMap,
lane_index: int = 0,
lane_offset: Optional[float] = None,
radius: float = 1,
):
"""Generate the goal ending at the specified road lane."""
road = road_map.road_by_id(road_id)
lane = road.lane_at_index(lane_index)
if lane_offset is None:
# Default to the midpoint safely ensuring we are on the lane and not
# bordering another
lane_offset = lane.length * 0.5
position = lane.from_lane_coord(RefLinePoint(lane_offset))
return cls(position=position, radius=radius) | Generate the goal ending at the specified road lane. | from_road | python | huawei-noah/SMARTS | smarts/core/plan.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/plan.py | MIT |
def default_entry_tactic(default_entry_speed: Optional[float] = None) -> EntryTactic:
"""The default tactic the simulation will use to acquire an actor for an agent."""
return TrapEntryTactic(
start_time=MISSING,
wait_to_hijack_limit_s=0,
exclusion_prefixes=tuple(),
zone=None,
default_entry_speed=default_entry_speed,
) | The default tactic the simulation will use to acquire an actor for an agent. | default_entry_tactic | python | huawei-noah/SMARTS | smarts/core/plan.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/plan.py | MIT |
def requires_route(self) -> bool:
"""If the mission requires a route to be generated."""
return self.goal.is_specific() | If the mission requires a route to be generated. | requires_route | python | huawei-noah/SMARTS | smarts/core/plan.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/plan.py | MIT |
def is_complete(self, vehicle_state, distance_travelled: float) -> bool:
"""If the mission has been completed successfully."""
return self.goal.is_reached(vehicle_state) | If the mission has been completed successfully. | is_complete | python | huawei-noah/SMARTS | smarts/core/plan.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/plan.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.