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 setup(self, scenario) -> ProviderState: """Initialize the provider with a scenario.""" raise NotImplementedError
Initialize the provider with a scenario.
setup
python
huawei-noah/SMARTS
smarts/core/provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py
MIT
def step(self, actions, dt: float, elapsed_sim_time: float) -> ProviderState: """Progress the provider to generate new actor state. Args: actions: one or more valid actions from the supported action_spaces of this provider dt (float): time (in seconds) to simulate during this simulation step elapsed_sim_time (float): amount of time (in seconds) that's elapsed so far in the simulation Returns: ProviderState: State representation of all actors this manages. """ raise NotImplementedError
Progress the provider to generate new actor state. Args: actions: one or more valid actions from the supported action_spaces of this provider dt (float): time (in seconds) to simulate during this simulation step elapsed_sim_time (float): amount of time (in seconds) that's elapsed so far in the simulation Returns: ProviderState: State representation of all actors this manages.
step
python
huawei-noah/SMARTS
smarts/core/provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py
MIT
def sync(self, provider_state: ProviderState): """Synchronize with state managed by other Providers.""" raise NotImplementedError
Synchronize with state managed by other Providers.
sync
python
huawei-noah/SMARTS
smarts/core/provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py
MIT
def can_accept_actor(self, state: ActorState) -> bool: """Whether this Provider can take control of an existing actor with state that was previously managed by another Provider. The state.role field should indicate the desired role, not the previous role.""" return False
Whether this Provider can take control of an existing actor with state that was previously managed by another Provider. The state.role field should indicate the desired role, not the previous role.
can_accept_actor
python
huawei-noah/SMARTS
smarts/core/provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py
MIT
def add_actor( self, provider_actor: ActorState, from_provider: Optional[Provider] = None ): """Management of the actor with state is being assigned (or transferred if from_provider is not None) to this Provider. Should only be called if can_accept_actor() has returned True.""" raise NotImplementedError
Management of the actor with state is being assigned (or transferred if from_provider is not None) to this Provider. Should only be called if can_accept_actor() has returned True.
add_actor
python
huawei-noah/SMARTS
smarts/core/provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py
MIT
def reset(self): """Reset this provider to a pre-initialized state.""" raise NotImplementedError
Reset this provider to a pre-initialized state.
reset
python
huawei-noah/SMARTS
smarts/core/provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py
MIT
def teardown(self): """Clean up provider resources.""" raise NotImplementedError
Clean up provider resources.
teardown
python
huawei-noah/SMARTS
smarts/core/provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py
MIT
def recover( self, scenario: smarts.core.scenario.Scenario, elapsed_sim_time: float, error: Optional[Exception] = None, ) -> Tuple[ProviderState, bool]: """Attempt to reconnect the provider if an error or disconnection occurred. Implementations may choose to re-raise the passed in exception. Args: scenario (Scenario): The scenario of the current episode. elapsed_sim_time (float): The current elapsed simulation time. error (Optional[Exception]): An exception if an exception was thrown. Returns: ProviderState: the state of the provider upon recovery bool: The success/failure of the attempt to reconnect. """ if error: raise error return ProviderState(), False
Attempt to reconnect the provider if an error or disconnection occurred. Implementations may choose to re-raise the passed in exception. Args: scenario (Scenario): The scenario of the current episode. elapsed_sim_time (float): The current elapsed simulation time. error (Optional[Exception]): An exception if an exception was thrown. Returns: ProviderState: the state of the provider upon recovery bool: The success/failure of the attempt to reconnect.
recover
python
huawei-noah/SMARTS
smarts/core/provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py
MIT
def connected(self) -> bool: """Determine if the provider is still responsive. (e.g. the case that the provider is sending provider state over the internet and has stopped responding) Returns: bool: The connection state of the provider. """ return True
Determine if the provider is still responsive. (e.g. the case that the provider is sending provider state over the internet and has stopped responding) Returns: bool: The connection state of the provider.
connected
python
huawei-noah/SMARTS
smarts/core/provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py
MIT
def source_str(self) -> str: """This property should be used to fill in the source field of all ActorState objects created/managed by this Provider.""" return self.provider_id()
This property should be used to fill in the source field of all ActorState objects created/managed by this Provider.
source_str
python
huawei-noah/SMARTS
smarts/core/provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py
MIT
def actor_ids(self) -> Iterable[str]: """Indicate the agents that this provider currently manages. Returns: Iterable[str]: A set of agents that this provider manages. """ raise NotImplementedError
Indicate the agents that this provider currently manages. Returns: Iterable[str]: A set of agents that this provider manages.
actor_ids
python
huawei-noah/SMARTS
smarts/core/provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py
MIT
def manages_actor(self, actor_id: str) -> bool: """Returns True if the actor referenced by actor_id is managed by this Provider.""" raise NotImplementedError
Returns True if the actor referenced by actor_id is managed by this Provider.
manages_actor
python
huawei-noah/SMARTS
smarts/core/provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py
MIT
def stop_managing(self, actor_id: str): """Tells the Provider to stop managing the specified actor; it will be managed by another Provider now.""" raise NotImplementedError
Tells the Provider to stop managing the specified actor; it will be managed by another Provider now.
stop_managing
python
huawei-noah/SMARTS
smarts/core/provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py
MIT
def remove_actor(self, actor_id: str): """The actor is being removed from the simulation.""" if self.manages_actor(actor_id): self.stop_managing(actor_id)
The actor is being removed from the simulation.
remove_actor
python
huawei-noah/SMARTS
smarts/core/provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py
MIT
def provider_id(cls) -> str: """The identifying name of the provider.""" return cls.__name__
The identifying name of the provider.
provider_id
python
huawei-noah/SMARTS
smarts/core/provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py
MIT
def step(self, sim_frame: SimulationFrame, **kwargs): """Update sensor state."""
Update sensor state.
step
python
huawei-noah/SMARTS
smarts/core/sensor.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor.py
MIT
def teardown(self, **kwargs): """Clean up internal resources""" raise NotImplementedError
Clean up internal resources
teardown
python
huawei-noah/SMARTS
smarts/core/sensor.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor.py
MIT
def mutable(self) -> bool: """If this sensor mutates on call.""" return True
If this sensor mutates on call.
mutable
python
huawei-noah/SMARTS
smarts/core/sensor.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor.py
MIT
def serializable(self) -> bool: """If this sensor can be serialized.""" return True
If this sensor can be serialized.
serializable
python
huawei-noah/SMARTS
smarts/core/sensor.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor.py
MIT
def camera_name(self) -> str: """The name of the camera this sensor is using.""" return self._camera_name
The name of the camera this sensor is using.
camera_name
python
huawei-noah/SMARTS
smarts/core/sensor.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor.py
MIT
def name(self) -> str: """The name of this sensor.""" return self._name
The name of this sensor.
name
python
huawei-noah/SMARTS
smarts/core/sensor.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor.py
MIT
def follow_vehicle(self, vehicle_state: VehicleState): """Update the sensor to target the given vehicle.""" self._lidar.origin = vehicle_state.pose.position + self._lidar_offset
Update the sensor to target the given vehicle.
follow_vehicle
python
huawei-noah/SMARTS
smarts/core/sensor.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor.py
MIT
def track_latest_driven_path(self, elapsed_sim_time, vehicle_state): """Records the current location of the tracked vehicle.""" position = vehicle_state.pose.position[:2] self._driven_path.append( _DrivenPathSensorEntry(timestamp=elapsed_sim_time, position=tuple(position)) )
Records the current location of the tracked vehicle.
track_latest_driven_path
python
huawei-noah/SMARTS
smarts/core/sensor.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor.py
MIT
def distance_travelled( self, elapsed_sim_time, last_n_seconds: Optional[float] = None, last_n_steps: Optional[int] = None, ): """Find the amount of distance travelled over the last # of seconds XOR steps""" if last_n_seconds is None and last_n_steps is None: raise ValueError("Either last N seconds or last N steps must be provided") if last_n_steps is not None: n = last_n_steps + 1 # to factor in the current step we're on filtered_pos = [x.position for x in self._driven_path][-n:] else: # last_n_seconds threshold = elapsed_sim_time - last_n_seconds filtered_pos = [ x.position for x in self._driven_path if x.timestamp >= threshold ] xs = np.array([p[0] for p in filtered_pos]) ys = np.array([p[1] for p in filtered_pos]) dist_array = (xs[:-1] - xs[1:]) ** 2 + (ys[:-1] - ys[1:]) ** 2 return np.sum(np.sqrt(dist_array))
Find the amount of distance travelled over the last # of seconds XOR steps
distance_travelled
python
huawei-noah/SMARTS
smarts/core/sensor.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor.py
MIT
def update_distance_wps_record( self, waypoint_paths: List[List[Waypoint]], vehicle_state: VehicleState, plan: Plan, road_map: RoadMap, ): """Append a waypoint to the history if it is not already counted.""" # Distance calculation. Intention is the shortest trip travelled at the lane # level the agent has travelled. This is to prevent lateral movement from # increasing the total distance travelled. self._last_dist_travelled = self._dist_travelled new_wp = waypoint_paths[0][0] wp_road = road_map.lane_by_id(new_wp.lane_id).road.road_id should_count_wp = ( plan.mission == None # if we do not have a fixed route, we count all waypoints we accumulate or not plan.mission.requires_route # if we have a route to follow, only count wps on route or wp_road in [road.road_id for road in plan.route.roads] ) if not self._wps_for_distance: self._last_actor_position = vehicle_state.pose.position if should_count_wp: self._wps_for_distance.append(new_wp) return # sensor does not have enough history most_recent_wp = self._wps_for_distance[-1] # TODO: Instead of storing a waypoint every 0.5m just find the next one immediately threshold_for_counting_wp = 0.5 # meters from last tracked waypoint if ( np.linalg.norm(new_wp.pos - most_recent_wp.pos) > threshold_for_counting_wp and should_count_wp ): self._wps_for_distance.append(new_wp) additional_distance = TripMeterSensor._compute_additional_dist_travelled( most_recent_wp, new_wp, vehicle_state.pose.position, self._last_actor_position, ) self._dist_travelled += additional_distance self._last_actor_position = vehicle_state.pose.position
Append a waypoint to the history if it is not already counted.
update_distance_wps_record
python
huawei-noah/SMARTS
smarts/core/sensor.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor.py
MIT
def radius(self) -> float: """Radius to check for nearby vehicles.""" return self._radius
Radius to check for nearby vehicles.
radius
python
huawei-noah/SMARTS
smarts/core/sensor.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor.py
MIT
def _paths_for_lane( self, lane: RoadMap.Lane, vehicle_state: VehicleState, plan: Plan, overflow_offset: Optional[float] = None, ): """Gets waypoint paths along the given lane.""" # XXX: the following assumes waypoint spacing is 1m if overflow_offset is None: offset = lane.offset_along_lane(vehicle_state.pose.point) start_offset = offset - self._horizon else: start_offset = lane.length + overflow_offset incoming_lanes = lane.incoming_lanes paths = [] if start_offset < 0 and len(incoming_lanes) > 0: for lane in incoming_lanes: paths += self._paths_for_lane(lane, vehicle_state, plan, start_offset) start_offset = max(0, start_offset) wp_start = lane.from_lane_coord(RefLinePoint(start_offset)) adj_pose = Pose.from_center(wp_start, vehicle_state.pose.heading) wps_to_lookahead = self._horizon * 2 paths += lane.waypoint_paths_for_pose( pose=adj_pose, lookahead=wps_to_lookahead, route=plan.route, ) return paths
Gets waypoint paths along the given lane.
_paths_for_lane
python
huawei-noah/SMARTS
smarts/core/sensor.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor.py
MIT
def reserve_traffic_location_for_vehicle( self, vehicle_id: str, reserved_location: Polygon, ): """Reserve an area around a location where vehicles cannot spawn until a given vehicle is added. Args: vehicle_id: The vehicle to wait for. reserved_location: The space the vehicle takes up. """ raise NotImplementedError
Reserve an area around a location where vehicles cannot spawn until a given vehicle is added. Args: vehicle_id: The vehicle to wait for. reserved_location: The space the vehicle takes up.
reserve_traffic_location_for_vehicle
python
huawei-noah/SMARTS
smarts/core/traffic_provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/traffic_provider.py
MIT
def vehicle_collided(self, vehicle_id: str): """Called when a vehicle this provider manages is detected to have collided with any other vehicles in the scenario.""" raise NotImplementedError
Called when a vehicle this provider manages is detected to have collided with any other vehicles in the scenario.
vehicle_collided
python
huawei-noah/SMARTS
smarts/core/traffic_provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/traffic_provider.py
MIT
def update_route_for_vehicle(self, vehicle_id: str, new_route: RoadMap.Route): """Set a new route for the given vehicle.""" raise NotImplementedError
Set a new route for the given vehicle.
update_route_for_vehicle
python
huawei-noah/SMARTS
smarts/core/traffic_provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/traffic_provider.py
MIT
def vehicle_dest_road(self, vehicle_id: str) -> Optional[str]: """Get the final road_id in the route of the given vehicle.""" raise NotImplementedError
Get the final road_id in the route of the given vehicle.
vehicle_dest_road
python
huawei-noah/SMARTS
smarts/core/traffic_provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/traffic_provider.py
MIT
def route_for_vehicle(self, vehicle_id: str) -> Optional[RoadMap.Route]: """Gets the current Route for the specified vehicle, if known.""" return None
Gets the current Route for the specified vehicle, if known.
route_for_vehicle
python
huawei-noah/SMARTS
smarts/core/traffic_provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/traffic_provider.py
MIT
def destroy(self): """Clean up any connections/resources.""" raise NotImplementedError
Clean up any connections/resources.
destroy
python
huawei-noah/SMARTS
smarts/core/traffic_provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/traffic_provider.py
MIT
def hit_via_points(self) -> Tuple[ViaPoint]: """List of points that were hit in the previous step.""" return tuple(vp for vp in self.near_via_points if vp.hit)
List of points that were hit in the previous step.
hit_via_points
python
huawei-noah/SMARTS
smarts/core/observations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/observations.py
MIT
def from_sumo( cls, sumo_road_network, spacing, ): """Computes the lane shape (start/shape/end) lane-points for all lanes in the network, the result of this function can be used to interpolate lane-points along lanes to the desired granularity. """ from smarts.core.utils.sumo_utils import sumolib # isort:skip from sumolib.net.edge import Edge # isort:skip from sumolib.net.lane import Lane # isort:skip from .sumo_road_network import SumoRoadNetwork assert type(sumo_road_network) == SumoRoadNetwork def _shape_lanepoints_along_lane( road_map: SumoRoadNetwork, lane: RoadMap.Lane, lanepoint_by_lane_memo: dict ) -> Tuple[LinkedLanePoint, List[LinkedLanePoint]]: lane_queue = queue.Queue() lane_queue.put((lane, None)) shape_lanepoints = [] initial_lanepoint = None while not lane_queue.empty(): lane, previous_lp = lane_queue.get() first_lanepoint = lanepoint_by_lane_memo.get(lane.getID()) if first_lanepoint: if previous_lp: previous_lp.nexts.append(first_lanepoint) continue lane_shape = [np.array(p) for p in lane.getShape(False)] assert len(lane_shape) >= 2, repr(lane_shape) heading = vec_to_radians(lane_shape[1] - lane_shape[0]) heading = Heading(heading) orientation = fast_quaternion_from_angle(heading) lane_width, _ = road_map.lane_by_id(lane.getID()).width_at_offset(0) first_lanepoint = LinkedLanePoint( lp=LanePoint( lane=road_map.lane_by_id(lane.getID()), pose=Pose(position=lane_shape[0], orientation=orientation), lane_width=lane_width, ), nexts=[], is_inferred=False, ) if previous_lp is not None: previous_lp.nexts.append(first_lanepoint) if initial_lanepoint is None: initial_lanepoint = first_lanepoint lanepoint_by_lane_memo[lane.getID()] = first_lanepoint shape_lanepoints.append(first_lanepoint) curr_lanepoint = first_lanepoint for p1, p2 in zip(lane_shape[1:], lane_shape[2:]): heading_ = vec_to_radians(p2 - p1) heading_ = Heading(heading_) orientation_ = fast_quaternion_from_angle(heading_) linked_lanepoint = LinkedLanePoint( lp=LanePoint( lane=road_map.lane_by_id(lane.getID()), pose=Pose(position=p1, orientation=orientation_), lane_width=lane_width, ), nexts=[], is_inferred=False, ) shape_lanepoints.append(linked_lanepoint) curr_lanepoint.nexts.append(linked_lanepoint) curr_lanepoint = linked_lanepoint # Add a lane-point for the last point of the current lane lane_width, _ = curr_lanepoint.lp.lane.width_at_offset(0) last_linked_lanepoint = LinkedLanePoint( lp=LanePoint( lane=curr_lanepoint.lp.lane, pose=Pose( position=lane_shape[-1][:2], orientation=curr_lanepoint.lp.pose.orientation, ), lane_width=lane_width, ), nexts=[], is_inferred=False, ) shape_lanepoints.append(last_linked_lanepoint) curr_lanepoint.nexts.append(last_linked_lanepoint) curr_lanepoint = last_linked_lanepoint for out_connection in lane.getOutgoing(): out_lane = out_connection.getToLane() # Use internal lanes of junctions (if we're at a junction) via_lane_id = out_connection.getViaLaneID() if via_lane_id: out_lane = road_map._graph.getLane(via_lane_id) lane_queue.put((out_lane, curr_lanepoint)) return initial_lanepoint, shape_lanepoints # Don't request internal lanes since we get them by calling # `lane.getViaLaneID()` edges = sumo_road_network._graph.getEdges(False) lanepoint_by_lane_memo = {} shape_lps = [] for edge in edges: for lane in edge.getLanes(): _, new_lps = _shape_lanepoints_along_lane( sumo_road_network, lane, lanepoint_by_lane_memo ) shape_lps += new_lps return cls(shape_lps, spacing)
Computes the lane shape (start/shape/end) lane-points for all lanes in the network, the result of this function can be used to interpolate lane-points along lanes to the desired granularity.
from_sumo
python
huawei-noah/SMARTS
smarts/core/lanepoints.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/lanepoints.py
MIT
def from_opendrive( cls, od_road_network, spacing, ): """Computes the lane shape (start/shape/end) lane-points for all lanes in the network, the result of this function can be used to interpolate lane-points along lanes to the desired granularity. """ from .opendrive_road_network import OpenDriveRoadNetwork assert type(od_road_network) == OpenDriveRoadNetwork def _shape_lanepoints_along_lane( lane: RoadMap.Lane, lanepoint_by_lane_memo: dict, ) -> Tuple[LinkedLanePoint, List[LinkedLanePoint]]: lane_queue = queue.Queue() lane_queue.put((lane, None)) shape_lanepoints = [] initial_lanepoint = None while not lane_queue.empty(): curr_lane, previous_lp = lane_queue.get() first_lanepoint = lanepoint_by_lane_memo.get(curr_lane.lane_id) if first_lanepoint: if previous_lp: previous_lp.nexts.append(first_lanepoint) continue lane_shape = [p.as_np_array[:2] for p in curr_lane.center_polyline] assert len(lane_shape) >= 2, repr(lane_shape) heading = vec_to_radians(lane_shape[1] - lane_shape[0]) heading = Heading(heading) orientation = fast_quaternion_from_angle(heading) first_lane_coord = curr_lane.to_lane_coord( Point(x=lane_shape[0][0], y=lane_shape[0][1], z=0.0) ) lane_width, _ = curr_lane.width_at_offset(first_lane_coord.s) first_lanepoint = LinkedLanePoint( lp=LanePoint( lane=curr_lane, pose=Pose(position=lane_shape[0], orientation=orientation), lane_width=lane_width, ), nexts=[], is_inferred=False, ) if previous_lp is not None: previous_lp.nexts.append(first_lanepoint) if initial_lanepoint is None: initial_lanepoint = first_lanepoint lanepoint_by_lane_memo[curr_lane.lane_id] = first_lanepoint shape_lanepoints.append(first_lanepoint) curr_lanepoint = first_lanepoint for p1, p2 in zip(lane_shape[1:], lane_shape[2:]): heading_ = vec_to_radians(p2 - p1) heading_ = Heading(heading_) orientation_ = fast_quaternion_from_angle(heading_) lp_lane_coord = curr_lane.to_lane_coord( Point(x=p1[0], y=p1[1], z=0.0) ) lane_width, _ = curr_lane.width_at_offset(lp_lane_coord.s) linked_lanepoint = LinkedLanePoint( lp=LanePoint( lane=curr_lane, pose=Pose(position=p1, orientation=orientation_), lane_width=lane_width, ), nexts=[], is_inferred=False, ) shape_lanepoints.append(linked_lanepoint) curr_lanepoint.nexts.append(linked_lanepoint) curr_lanepoint = linked_lanepoint # Add a lane-point for the last point of the current lane last_lane_coord = curr_lanepoint.lp.lane.to_lane_coord( Point(x=lane_shape[-1][0], y=lane_shape[-1][1], z=0.0) ) lane_width, _ = curr_lanepoint.lp.lane.width_at_offset( last_lane_coord.s ) last_linked_lanepoint = LinkedLanePoint( lp=LanePoint( lane=curr_lanepoint.lp.lane, pose=Pose( position=lane_shape[-1], orientation=curr_lanepoint.lp.pose.orientation, ), lane_width=lane_width, ), nexts=[], is_inferred=False, ) shape_lanepoints.append(last_linked_lanepoint) curr_lanepoint.nexts.append(last_linked_lanepoint) curr_lanepoint = last_linked_lanepoint outgoing_roads_added = [] for out_lane in curr_lane.outgoing_lanes: if out_lane.is_drivable: lane_queue.put((out_lane, curr_lanepoint)) outgoing_road = out_lane.road if out_lane.road not in outgoing_roads_added: outgoing_roads_added.append(outgoing_road) for outgoing_road in outgoing_roads_added: for next_lane in outgoing_road.lanes: if ( next_lane.is_drivable and next_lane not in curr_lane.outgoing_lanes ): lane_queue.put((next_lane, curr_lanepoint)) return initial_lanepoint, shape_lanepoints roads = od_road_network._roads lanepoint_by_lane_memo = {} shape_lps = [] for road_id in roads: road = roads[road_id] # go ahead and add lane-points for composite lanes, # even though we don't on other map formats, # and then filter these out on lane-point queries. # (not an issue right now for OpenDrive since we don't # find composite lanes, but it may be in the future.) for lane in road.lanes: # Ignore non drivable lanes in OpenDRIVE if lane.is_drivable: _, new_lps = _shape_lanepoints_along_lane( lane, lanepoint_by_lane_memo ) shape_lps += new_lps return cls(shape_lps, spacing)
Computes the lane shape (start/shape/end) lane-points for all lanes in the network, the result of this function can be used to interpolate lane-points along lanes to the desired granularity.
from_opendrive
python
huawei-noah/SMARTS
smarts/core/lanepoints.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/lanepoints.py
MIT
def from_waymo( cls, waymo_road_network, spacing, ): """Computes the lane shape (start/shape/end) lane-points for all lanes in the network, the result of this function can be used to interpolate lane-points along lanes to the desired granularity. """ from .waymo_map import WaymoMap assert type(waymo_road_network) == WaymoMap def _shape_lanepoints_along_lane( lane: RoadMap.Lane, lanepoint_by_lane_memo: dict, ) -> Tuple[LinkedLanePoint, List[LinkedLanePoint]]: lane_queue = queue.Queue() lane_queue.put((lane, None)) shape_lanepoints = [] initial_lanepoint = None while not lane_queue.empty(): curr_lane, previous_lp = lane_queue.get() first_lanepoint = lanepoint_by_lane_memo.get(curr_lane.lane_id) if first_lanepoint: if previous_lp: previous_lp.nexts.append(first_lanepoint) continue lane_shape = curr_lane._lane_pts assert ( len(lane_shape) >= 2 ), f"{repr(lane_shape)} for lane_id={curr_lane.lane_id}" vd = lane_shape[1] - lane_shape[0] heading = Heading(vec_to_radians(vd[:2])) orientation = fast_quaternion_from_angle(heading) lane_width, _ = curr_lane.width_at_offset(0) first_lanepoint = LinkedLanePoint( lp=LanePoint( lane=curr_lane, pose=Pose(position=lane_shape[0], orientation=orientation), lane_width=lane_width, ), nexts=[], is_inferred=False, ) if previous_lp is not None: previous_lp.nexts.append(first_lanepoint) if initial_lanepoint is None: initial_lanepoint = first_lanepoint lanepoint_by_lane_memo[curr_lane.lane_id] = first_lanepoint shape_lanepoints.append(first_lanepoint) curr_lanepoint = first_lanepoint for p1, p2 in zip(lane_shape[1:], lane_shape[2:]): vd = p2 - p1 heading_ = Heading(vec_to_radians(vd[:2])) orientation_ = fast_quaternion_from_angle(heading_) lane_width, _ = curr_lane.width_at_offset(0) linked_lanepoint = LinkedLanePoint( lp=LanePoint( lane=curr_lane, pose=Pose(position=p1, orientation=orientation_), lane_width=lane_width, ), nexts=[], is_inferred=False, ) shape_lanepoints.append(linked_lanepoint) curr_lanepoint.nexts.append(linked_lanepoint) curr_lanepoint = linked_lanepoint # Add a lanepoint for the last point of the current lane curr_lanepoint_lane = curr_lanepoint.lp.lane lane_width, _ = curr_lanepoint_lane.width_at_offset(0) last_linked_lanepoint = LinkedLanePoint( lp=LanePoint( lane=curr_lanepoint.lp.lane, pose=Pose( position=lane_shape[-1], orientation=curr_lanepoint.lp.pose.orientation, ), lane_width=lane_width, ), nexts=[], is_inferred=False, ) shape_lanepoints.append(last_linked_lanepoint) curr_lanepoint.nexts.append(last_linked_lanepoint) curr_lanepoint = last_linked_lanepoint for out_lane in curr_lane.outgoing_lanes: if out_lane and out_lane.is_drivable: lane_queue.put((out_lane, curr_lanepoint)) return initial_lanepoint, shape_lanepoints roads = waymo_road_network._roads lanepoint_by_lane_memo = {} shape_lps = [] for road_id in roads: road = roads[road_id] # go ahead and add lane-points for composite lanes, # even though we don't on other map formats, # and then filter these out on lane-point queries. for lane in road.lanes: # Ignore non drivable lanes in Waymo if lane.is_drivable: _, new_lps = _shape_lanepoints_along_lane( lane, lanepoint_by_lane_memo ) shape_lps += new_lps return cls(shape_lps, spacing)
Computes the lane shape (start/shape/end) lane-points for all lanes in the network, the result of this function can be used to interpolate lane-points along lanes to the desired granularity.
from_waymo
python
huawei-noah/SMARTS
smarts/core/lanepoints.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/lanepoints.py
MIT
def from_argoverse( cls, argoverse_map, spacing, ): """Computes the lane shape (start/shape/end) lane-points for all lanes in the network, the result of this function can be used to interpolate lane-points along lanes to the desired granularity. """ from .argoverse_map import ArgoverseMap assert type(argoverse_map) == ArgoverseMap def _shape_lanepoints_along_lane( lane: RoadMap.Lane, lanepoint_by_lane_memo: dict, ) -> Tuple[LinkedLanePoint, List[LinkedLanePoint]]: lane_queue = queue.Queue() lane_queue.put((lane, None)) shape_lanepoints = [] initial_lanepoint = None while not lane_queue.empty(): curr_lane, previous_lp = lane_queue.get() first_lanepoint = lanepoint_by_lane_memo.get(curr_lane.lane_id) if first_lanepoint: if previous_lp: previous_lp.nexts.append(first_lanepoint) continue lane_shape = curr_lane._centerline assert ( len(lane_shape) >= 2 ), f"{repr(lane_shape)} for lane_id={curr_lane.lane_id}" vd = lane_shape[1] - lane_shape[0] heading = Heading(vec_to_radians(vd[:2])) orientation = fast_quaternion_from_angle(heading) lane_width, _ = curr_lane.width_at_offset(0) first_lanepoint = LinkedLanePoint( lp=LanePoint( lane=curr_lane, pose=Pose(position=lane_shape[0], orientation=orientation), lane_width=lane_width, ), nexts=[], is_inferred=False, ) if previous_lp is not None: previous_lp.nexts.append(first_lanepoint) if initial_lanepoint is None: initial_lanepoint = first_lanepoint lanepoint_by_lane_memo[curr_lane.lane_id] = first_lanepoint shape_lanepoints.append(first_lanepoint) curr_lanepoint = first_lanepoint for p1, p2 in zip(lane_shape[1:], lane_shape[2:]): vd = p2 - p1 heading_ = Heading(vec_to_radians(vd[:2])) orientation_ = fast_quaternion_from_angle(heading_) lane_width, _ = curr_lane.width_at_offset(0) linked_lanepoint = LinkedLanePoint( lp=LanePoint( lane=curr_lane, pose=Pose(position=p1, orientation=orientation_), lane_width=lane_width, ), nexts=[], is_inferred=False, ) shape_lanepoints.append(linked_lanepoint) curr_lanepoint.nexts.append(linked_lanepoint) curr_lanepoint = linked_lanepoint # Add a lanepoint for the last point of the current lane curr_lanepoint_lane = curr_lanepoint.lp.lane lane_width, _ = curr_lanepoint_lane.width_at_offset(0) last_linked_lanepoint = LinkedLanePoint( lp=LanePoint( lane=curr_lanepoint.lp.lane, pose=Pose( position=lane_shape[-1], orientation=curr_lanepoint.lp.pose.orientation, ), lane_width=lane_width, ), nexts=[], is_inferred=False, ) shape_lanepoints.append(last_linked_lanepoint) curr_lanepoint.nexts.append(last_linked_lanepoint) curr_lanepoint = last_linked_lanepoint for out_lane in curr_lane.outgoing_lanes: if out_lane and out_lane.is_drivable: lane_queue.put((out_lane, curr_lanepoint)) return initial_lanepoint, shape_lanepoints roads = argoverse_map._roads lanepoint_by_lane_memo = {} shape_lps = [] for road in roads.values(): for lane in road.lanes: if lane.is_drivable: _, new_lps = _shape_lanepoints_along_lane( lane, lanepoint_by_lane_memo ) shape_lps += new_lps return cls(shape_lps, spacing)
Computes the lane shape (start/shape/end) lane-points for all lanes in the network, the result of this function can be used to interpolate lane-points along lanes to the desired granularity.
from_argoverse
python
huawei-noah/SMARTS
smarts/core/lanepoints.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/lanepoints.py
MIT
def closest_lanepoints( self, pose: Pose, maximum_count: int = 10, ) -> List[LanePoint]: """Get the lane-points closest to the given pose. Args: pose: The pose to look around for lane-points. maximum_count: The maximum number of lane-points that should be found. """ linked_lanepoints = LanePoints._closest_linked_lp_to_point( pose.point, self._linked_lanepoints, self._lp_points, k=maximum_count, filter_composites=True, ) return [llp.lp for llp in linked_lanepoints]
Get the lane-points closest to the given pose. Args: pose: The pose to look around for lane-points. maximum_count: The maximum number of lane-points that should be found.
closest_lanepoints
python
huawei-noah/SMARTS
smarts/core/lanepoints.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/lanepoints.py
MIT
def closest_linked_lanepoint_on_lane_to_point( self, point: Point, lane_id: str ) -> LinkedLanePoint: """Returns the closest linked lane-point on the given lane.""" return LanePoints._closest_linked_lp_to_point( point, self._lanepoints_by_lane_id[lane_id], self._lp_points_by_lane_id[lane_id], k=1, )[0]
Returns the closest linked lane-point on the given lane.
closest_linked_lanepoint_on_lane_to_point
python
huawei-noah/SMARTS
smarts/core/lanepoints.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/lanepoints.py
MIT
def closest_linked_lanepoint_on_road( self, point: Point, road_id: str ) -> LinkedLanePoint: """Returns the closest linked lane-point on the given road.""" return LanePoints._closest_linked_lp_to_point( point, self._lanepoints_by_edge_id[road_id], self._lp_points_by_edge_id[road_id], )[0]
Returns the closest linked lane-point on the given road.
closest_linked_lanepoint_on_road
python
huawei-noah/SMARTS
smarts/core/lanepoints.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/lanepoints.py
MIT
def paths_starting_at_lanepoint( self, lanepoint: LinkedLanePoint, lookahead: int, route_edge_ids: tuple ) -> List[List[LinkedLanePoint]]: """Returns all full branches from the given lane-point up to the length of the look-ahead. Branches will be filtered at the lane level if they or their outgoing lanes do not belong to a road in the route edge list. Args: lanepoint (LinkedLanePoint): The starting lane-point. lookahead (int): The maximum lane-points in a branch. route_edge_ids (Tuple[str]): White-listed edge ids for a route. Returns: All branches (as lists) stemming from the input lane-point. """ # Early exit if there are no valid paths ahead in the route for this lane lp_lane = lanepoint.lp.lane if ( route_edge_ids and lp_lane.road.road_id != route_edge_ids[-1] and all( out_lane.road.road_id not in route_edge_ids for out_lane in lp_lane.outgoing_lanes ) ): return [] lanepoint_paths = [[lanepoint]] for _ in range(lookahead): next_lanepoint_paths = [] for path in lanepoint_paths: branching_paths = [] for next_lp in path[-1].nexts: # TODO: This could be a problem for SUMO. What about internal lanes? # Filter only the edges we're interested in next_lane = next_lp.lp.lane edge_id = next_lane.road.road_id if route_edge_ids and edge_id not in route_edge_ids: continue if ( route_edge_ids and edge_id != route_edge_ids[-1] and all( out_lane.road.road_id not in route_edge_ids for out_lane in next_lane.outgoing_lanes ) ): continue new_path = path + [next_lp] branching_paths.append(new_path) if not branching_paths: branching_paths = [path] next_lanepoint_paths += branching_paths lanepoint_paths = next_lanepoint_paths return lanepoint_paths
Returns all full branches from the given lane-point up to the length of the look-ahead. Branches will be filtered at the lane level if they or their outgoing lanes do not belong to a road in the route edge list. Args: lanepoint (LinkedLanePoint): The starting lane-point. lookahead (int): The maximum lane-points in a branch. route_edge_ids (Tuple[str]): White-listed edge ids for a route. Returns: All branches (as lists) stemming from the input lane-point.
paths_starting_at_lanepoint
python
huawei-noah/SMARTS
smarts/core/lanepoints.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/lanepoints.py
MIT
def name(self) -> str: """The name of this dependency.""" raise NotImplementedError()
The name of this dependency.
name
python
huawei-noah/SMARTS
smarts/core/agent_interface.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_interface.py
MIT
def is_self_targetted(self): """If the dependency is drawing from one of this agent's cameras.""" return self.target_actor == _DEFAULTS.SELF.value
If the dependency is drawing from one of this agent's cameras.
is_self_targetted
python
huawei-noah/SMARTS
smarts/core/agent_interface.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_interface.py
MIT
def actors_pattern(self) -> re.Pattern: """The expression match pattern for actors covered by this interface specifically.""" return re.compile("|".join(rf"(?:{aoi})" for aoi in self.actors_filter))
The expression match pattern for actors covered by this interface specifically.
actors_pattern
python
huawei-noah/SMARTS
smarts/core/agent_interface.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_interface.py
MIT
def actors_alive(self): """Deprecated. Use interest.""" warnings.warn("Use interest.", category=DeprecationWarning) return self.interest
Deprecated. Use interest.
actors_alive
python
huawei-noah/SMARTS
smarts/core/agent_interface.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_interface.py
MIT
def from_type(requested_type: AgentType, **kwargs) -> AgentInterface: """Instantiates from a selection of agent_interface presets Args: requested_type: Select a prefabricated AgentInterface from an AgentType max_episode_steps: The total number of steps this interface will observe before expiring """ if requested_type == AgentType.Buddha: # The enlightened one interface = AgentInterface(action=ActionSpaceType.Empty) elif requested_type == AgentType.Full: # Uses everything interface = AgentInterface( neighborhood_vehicle_states=True, waypoint_paths=True, road_waypoints=True, drivable_area_grid_map=True, occupancy_grid_map=True, top_down_rgb=True, lidar_point_cloud=True, accelerometer=True, lane_positions=True, signals=True, action=ActionSpaceType.Continuous, ) # Uses low dimensional observations elif requested_type == AgentType.StandardWithAbsoluteSteering: interface = AgentInterface( waypoint_paths=True, neighborhood_vehicle_states=True, action=ActionSpaceType.Continuous, ) elif requested_type == AgentType.Standard: interface = AgentInterface( waypoint_paths=True, neighborhood_vehicle_states=True, action=ActionSpaceType.ActuatorDynamic, ) elif requested_type == AgentType.Laner: # The lane-following agent interface = AgentInterface( waypoint_paths=True, action=ActionSpaceType.Lane, ) # The lane-following agent with speed and relative lane change direction elif requested_type == AgentType.LanerWithSpeed: interface = AgentInterface( waypoint_paths=True, action=ActionSpaceType.LaneWithContinuousSpeed, ) # The trajectory tracking agent which receives a series of reference trajectory # points and speeds to follow elif requested_type == AgentType.Tracker: interface = AgentInterface( waypoint_paths=True, action=ActionSpaceType.Trajectory, ) # The trajectory interpolation agent which receives a with-time-trajectory and move vehicle # with linear time interpolation elif requested_type == AgentType.TrajectoryInterpolator: interface = AgentInterface(action=ActionSpaceType.TrajectoryWithTime) # The MPC based trajectory tracking agent which receives a series of # reference trajectory points and speeds and computes the optimal # steering action. elif requested_type == AgentType.MPCTracker: interface = AgentInterface( waypoint_paths=True, action=ActionSpaceType.MPC, ) # For boid control (controlling multiple vehicles) elif requested_type == AgentType.Boid: interface = AgentInterface( waypoint_paths=True, neighborhood_vehicle_states=True, action=ActionSpaceType.MultiTargetPose, ) # For empty environment, good for testing control elif requested_type == AgentType.Loner: interface = AgentInterface( waypoint_paths=True, action=ActionSpaceType.Continuous, ) # Plays tag _two vehicles in the env only_ elif requested_type == AgentType.Tagger: interface = AgentInterface( waypoint_paths=True, neighborhood_vehicle_states=True, action=ActionSpaceType.Continuous, ) # Has been useful for testing imitation learners elif requested_type == AgentType.Direct: interface = AgentInterface( neighborhood_vehicle_states=True, signals=True, action=ActionSpaceType.Direct, ) else: raise Exception("Unsupported agent type %s" % requested_type) return interface.replace(**kwargs)
Instantiates from a selection of agent_interface presets Args: requested_type: Select a prefabricated AgentInterface from an AgentType max_episode_steps: The total number of steps this interface will observe before expiring
from_type
python
huawei-noah/SMARTS
smarts/core/agent_interface.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_interface.py
MIT
def replace(self, **kwargs) -> AgentInterface: """Clone this AgentInterface with the given fields updated >>> interface = AgentInterface(action=ActionSpaceType.Continuous) \ .replace(waypoint_paths=True) >>> interface.waypoint_paths Waypoints(...) """ return replace(self, **kwargs)
Clone this AgentInterface with the given fields updated >>> interface = AgentInterface(action=ActionSpaceType.Continuous) \ .replace(waypoint_paths=True) >>> interface.waypoint_paths Waypoints(...)
replace
python
huawei-noah/SMARTS
smarts/core/agent_interface.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_interface.py
MIT
def requires_rendering(self): """If this agent interface requires a renderer.""" return bool( self.top_down_rgb or self.occupancy_grid_map or self.drivable_area_grid_map or self.custom_renders )
If this agent interface requires a renderer.
requires_rendering
python
huawei-noah/SMARTS
smarts/core/agent_interface.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_interface.py
MIT
def ogm(self): """Deprecated. Use `occupancy_grid_map` instead.""" warnings.warn( "ogm property has been deprecated in favor of occupancy_grid_map. Please update your code.", category=DeprecationWarning, ) return self.occupancy_grid_map
Deprecated. Use `occupancy_grid_map` instead.
ogm
python
huawei-noah/SMARTS
smarts/core/agent_interface.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_interface.py
MIT
def rgb(self): """Deprecated. Use `top_down_rgb` instead.""" warnings.warn( "rgb property has been deprecated in favor of top_down_rgb. Please update your code.", category=DeprecationWarning, ) # for backwards compatibility return self.top_down_rgb
Deprecated. Use `top_down_rgb` instead.
rgb
python
huawei-noah/SMARTS
smarts/core/agent_interface.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_interface.py
MIT
def lidar(self): """Deprecated. Use `lidar_point_cloud` instead.""" warnings.warn( "lidar property has been deprecated in favor of lidar_point_cloud. Please update your code.", category=DeprecationWarning, ) # for backwards compatibility return self.lidar_point_cloud
Deprecated. Use `lidar_point_cloud` instead.
lidar
python
huawei-noah/SMARTS
smarts/core/agent_interface.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_interface.py
MIT
def waypoints(self): """Deprecated. Use `waypoint_paths` instead.""" warnings.warn( "waypoints property has been deprecated in favor of waypoint_paths. Please update your code.", category=DeprecationWarning, ) # for backwards compatibility return self.waypoint_paths
Deprecated. Use `waypoint_paths` instead.
waypoints
python
huawei-noah/SMARTS
smarts/core/agent_interface.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_interface.py
MIT
def neighborhood_vehicles(self): """Deprecated. Use `neighborhood_vehicle_states` instead.""" warnings.warn( "neighborhood_vehicles property has been deprecated in favor of neighborhood_vehicle_states. Please update your code.", category=DeprecationWarning, ) # for backwards compatibility return self.neighborhood_vehicle_states
Deprecated. Use `neighborhood_vehicle_states` instead.
neighborhood_vehicles
python
huawei-noah/SMARTS
smarts/core/agent_interface.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_interface.py
MIT
def agent_ids(self) -> Set[str]: """Get the ids of all agents that currently have vehicles.""" return set(self.vehicles_for_agents.keys())
Get the ids of all agents that currently have vehicles.
agent_ids
python
huawei-noah/SMARTS
smarts/core/simulation_frame.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/simulation_frame.py
MIT
def potential_agent_ids(self) -> Set[str]: """This includes current agent ids and future pending ego agent ids.""" return set(self.vehicles_for_agents.keys()) | set(self.pending_agent_ids)
This includes current agent ids and future pending ego agent ids.
potential_agent_ids
python
huawei-noah/SMARTS
smarts/core/simulation_frame.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/simulation_frame.py
MIT
def actor_states_by_id(self) -> Dict[str, ActorState]: """Get actor states paired by their ids.""" return {a_s.actor_id: a_s for a_s in self.actor_states}
Get actor states paired by their ids.
actor_states_by_id
python
huawei-noah/SMARTS
smarts/core/simulation_frame.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/simulation_frame.py
MIT
def interest_actors( self, extension: Optional[re.Pattern] = None ) -> Dict[str, ActorState]: """Get the actor states of actors that are marked as of interest. Args: extension (re.Pattern): A matching for interest actors not defined in scenario. """ _matchers: List[re.Pattern] = [] if self.interest_filter.pattern: _matchers.append(self.interest_filter) if extension is not None and extension.pattern: _matchers.append(extension) if len(_matchers) > 0: return { a_s.actor_id: a_s for a_s in self.actor_states if any(bool(m.match(a_s.actor_id)) for m in _matchers) } return {}
Get the actor states of actors that are marked as of interest. Args: extension (re.Pattern): A matching for interest actors not defined in scenario.
interest_actors
python
huawei-noah/SMARTS
smarts/core/simulation_frame.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/simulation_frame.py
MIT
def actor_is_interest( self, actor_id: str, extension: Optional[re.Pattern] = None ) -> bool: """Determine if the actor is of interest. Args: actor_id (str): The id of the actor to test. Returns: bool: If the actor is of interest. """ return actor_id in self.interest_actors(extension)
Determine if the actor is of interest. Args: actor_id (str): The id of the actor to test. Returns: bool: If the actor is of interest.
actor_is_interest
python
huawei-noah/SMARTS
smarts/core/simulation_frame.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/simulation_frame.py
MIT
def vehicle_did_collide(self, vehicle_id: str) -> bool: """Test if the given vehicle had any collisions in the last physics update.""" vehicle_collisions = self.vehicle_collisions.get(vehicle_id, []) for c in vehicle_collisions: if c.collidee_id != self._ground_bullet_id: return True return False
Test if the given vehicle had any collisions in the last physics update.
vehicle_did_collide
python
huawei-noah/SMARTS
smarts/core/simulation_frame.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/simulation_frame.py
MIT
def filtered_vehicle_collisions(self, vehicle_id: str) -> List[Collision]: """Get a list of all collisions the given vehicle was involved in during the last physics update. """ vehicle_collisions = self.vehicle_collisions.get(vehicle_id, []) return [ c for c in vehicle_collisions if c.collidee_id != self._ground_bullet_id ]
Get a list of all collisions the given vehicle was involved in during the last physics update.
filtered_vehicle_collisions
python
huawei-noah/SMARTS
smarts/core/simulation_frame.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/simulation_frame.py
MIT
def destroy(self): """Clean up TraCI related connections.""" if self._traci_conn: self._traci_conn.close_traci_and_pipes() self._is_setup = False
Clean up TraCI related connections.
destroy
python
huawei-noah/SMARTS
smarts/core/sumo_traffic_simulation.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_traffic_simulation.py
MIT
def headless(self): """Does not show TraCI visualization.""" return self._headless
Does not show TraCI visualization.
headless
python
huawei-noah/SMARTS
smarts/core/sumo_traffic_simulation.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_traffic_simulation.py
MIT
def actor_ids(self) -> Iterable[str]: """The vehicles that sumo manages. Returns: Iterable[str]: Sumo vehicle ids. """ return self._sumo_vehicle_ids
The vehicles that sumo manages. Returns: Iterable[str]: Sumo vehicle ids.
actor_ids
python
huawei-noah/SMARTS
smarts/core/sumo_traffic_simulation.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_traffic_simulation.py
MIT
def setup(self, scenario) -> ProviderState: """Initialize the simulation with a new scenario.""" self._log.debug("Setting up SumoTrafficSim %s", self) assert ( not self._is_setup ), f"Can't setup twice, {self._is_setup}, see teardown()" # restart sumo process only when map file changes restart_sumo = ( not self._scenario or not self.connected or self._scenario.road_map_hash != scenario.road_map_hash or self._current_reload_count >= self._reload_count or self._traci_conn.must_reset() # Some versions of sumo crash when reloading ) self._current_reload_count = self._current_reload_count % self._reload_count + 1 self._scenario = scenario assert isinstance( scenario.road_map, SumoRoadNetwork ), "SumoTrafficSimulation requires a SumoRoadNetwork" self._log_file = scenario.unique_sumo_log_file() try: if restart_sumo: self._restart_sumo() elif self._allow_reload: assert ( self._traci_conn is not None ), "TraCI should be connected at this point." try: self._traci_conn.load(self._base_sumo_load_params()) except traci.exceptions.FatalTraCIError: self._restart_sumo() except traci.exceptions.FatalTraCIError: return ProviderState() assert self._traci_conn is not None, "No active TraCI connection" self._traci_conn.simulation.subscribe( [tc.VAR_DEPARTED_VEHICLES_IDS, tc.VAR_ARRIVED_VEHICLES_IDS] ) self._traffic_lights = dict() for tls_id in self._traci_conn.trafficlight.getIDList(): self._traffic_lights[ tls_id ] = self._traci_conn.trafficlight.getControlledLinks(tls_id) self._traci_conn.trafficlight.subscribe( tls_id, [tc.TL_RED_YELLOW_GREEN_STATE] ) # XXX: SUMO caches the previous subscription results. Calling `simulationStep` # effectively flushes the results. We need to use epsilon instead of zero # as zero will step according to a default (non-zero) step-size. self.step({}, 1e-6, 0) if not self.connected: self._is_setup = False return ProviderState() self._is_setup = True return self._compute_provider_state()
Initialize the simulation with a new scenario.
setup
python
huawei-noah/SMARTS
smarts/core/sumo_traffic_simulation.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_traffic_simulation.py
MIT
def update_route_for_vehicle(self, vehicle_id: str, new_route: RoadMap.Route): """Sets a new route for vehicle_id, but only if it is different from the previously-set route (otherwise, avoids the TraCI call). Any sumo-special roads (e.g., junction) are removed from the new route before setting it because Sumo doesn't allow specifying these in the call to its `vehicle.setRoute()` and will raise an exception otherwise.""" if not self.connected: return old_route = self._route_for_vehicle(vehicle_id) if old_route: new_route_ids = [rr for rr in new_route.road_ids if rr[0] != ":"] if new_route_ids == list(old_route): return try: # Note: the first edge of the route must be the edge we're currently on... self._traci_conn.vehicle.setRoute(vehicle_id, new_route.road_ids) except self._traci_exceptions as err: self._handle_traci_exception(err)
Sets a new route for vehicle_id, but only if it is different from the previously-set route (otherwise, avoids the TraCI call). Any sumo-special roads (e.g., junction) are removed from the new route before setting it because Sumo doesn't allow specifying these in the call to its `vehicle.setRoute()` and will raise an exception otherwise.
update_route_for_vehicle
python
huawei-noah/SMARTS
smarts/core/sumo_traffic_simulation.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sumo_traffic_simulation.py
MIT
def road_ids(self) -> List[str]: """Get the road IDs for this route. Returns: (List[str]): A list of the road IDs for the Roads in this Route. """ return [road.road_id for road in self.roads]
Get the road IDs for this route. Returns: (List[str]): A list of the road IDs for the Roads in this Route.
road_ids
python
huawei-noah/SMARTS
smarts/core/route_cache.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/route_cache.py
MIT
def from_road_ids( road_map, road_ids: Sequence[str], resolve_intermediaries: bool = False, ) -> RoadMap.Route: """Factory to generate a new RouteWithCache from a sequence of road ids.""" if len(road_ids) > 0 and resolve_intermediaries: via_roads = [road_map.road_by_id(r) for r in road_ids[1:-1]] routes = road_map.generate_routes( start=road_map.road_by_id(road_ids[0]), end=road_map.road_by_id(road_ids[-1]), via=via_roads, max_to_gen=1, ) if len(routes) > 0: return routes[0] route_roads = [] for road_id in road_ids: road = road_map.road_by_id(road_id) assert road, f"cannot add unknown road {road_id} to route" route_roads.append(road) return road_map.Route(road_map=road_map, roads=route_roads)
Factory to generate a new RouteWithCache from a sequence of road ids.
from_road_ids
python
huawei-noah/SMARTS
smarts/core/route_cache.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/route_cache.py
MIT
def is_cached(self) -> bool: """Returns True if information about this Route has been cached.""" return self._cache_key in _route_sub_lengths
Returns True if information about this Route has been cached.
is_cached
python
huawei-noah/SMARTS
smarts/core/route_cache.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/route_cache.py
MIT
def remove_from_cache(self): """Remove information about this Route from the cache.""" if self.is_cached: del _route_sub_lengths[self._cache_key]
Remove information about this Route from the cache.
remove_from_cache
python
huawei-noah/SMARTS
smarts/core/route_cache.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/route_cache.py
MIT
def add_to_cache(self): """Add information about this Route to the cache if not already there.""" if self.is_cached: return cache_key = self._cache_key _route_sub_lengths[ cache_key ] = dict() # pytype: disable=container-type-mismatch def _backprop_length( bplane: RoadMap.Lane, length: float, rind: int, junction: bool, final_lane: RoadMap.Lane, ): assert rind >= 0 rind -= 1 for il in bplane.incoming_lanes: rl = RoadMap.Route.RouteLane(il, rind) il_cont = _route_sub_lengths[cache_key].get(rl) if il_cont is not None: if junction: if il.in_junction: junction = False else: il_cont.dist_to_junction = il_cont.dist_to_end il_cont.next_junction = final_lane il_cont.dist_to_road[final_lane.road] = il_cont.dist_to_end il_cont.dist_to_end += length _backprop_length(il, length, rind, junction, final_lane) road = None for r_ind, road in enumerate(self.roads): for lane in road.lanes: # r_ind is required to correctly handle routes with sub-cycles rl = RoadMap.Route.RouteLane(lane, r_ind) assert rl not in _route_sub_lengths[cache_key] _backprop_length(lane, lane.length, r_ind, lane.in_junction, lane) lc = _LaneContinuation(lane.length) if lane.in_junction: lc.next_junction = lane lc.dist_to_junction = 0.0 _route_sub_lengths[cache_key][rl] = lc if not road: return # give lanes that would form a loop an advantage... first_road = self.roads[0] for lane in road.lanes: rl = RoadMap.Route.RouteLane(lane, r_ind) for og in lane.outgoing_lanes: if og.road == first_road: _route_sub_lengths[cache_key][rl].dist_to_end += 1
Add information about this Route to the cache if not already there.
add_to_cache
python
huawei-noah/SMARTS
smarts/core/route_cache.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/route_cache.py
MIT
def current_seed(): """Get the last used seed.""" return _current_seed
Get the last used seed.
current_seed
python
huawei-noah/SMARTS
smarts/core/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/__init__.py
MIT
def seed(a): """Seed common pseudo-random generators.""" global _current_seed _current_seed = a random.seed(a) np.random.seed(a)
Seed common pseudo-random generators.
seed
python
huawei-noah/SMARTS
smarts/core/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/__init__.py
MIT
def gen_id(): """Generates a unique but deterministic id if `smarts.core.seed` has set the core seed.""" id_ = uuid.UUID(int=random.getrandbits(128)) return str(id_)[:8]
Generates a unique but deterministic id if `smarts.core.seed` has set the core seed.
gen_id
python
huawei-noah/SMARTS
smarts/core/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/__init__.py
MIT
def config( config_path: str = "./smarts_engine.ini", environment_prefix="SMARTS" ) -> Config: """Get the SMARTS environment configuration for the smarts engine. .. note:: This searches the following locations and loads the first one it finds: Supplied ``config_path``. Default: `./smarts_engine.ini` `~/.smarts/engine.ini` `/etc/smarts/engine.ini` `$PYTHON_PATH/smarts/engine.ini` Args: config_path (str, optional): The configurable location. Defaults to `./smarts_engine.ini`. Returns: Config: A configuration utility that allows resolving environment and `engine.ini` configuration. """ from smarts.core.utils.file import smarts_global_user_dir, smarts_local_user_dir def get_file(config_file: Path): try: if not config_file.is_file(): return "" except PermissionError: return "" return str(config_file) conf = partial(Config, environment_prefix=environment_prefix) file = get_file(Path(config_path).absolute()) if file: return conf(file) try: local_dir = smarts_local_user_dir() except PermissionError: file = "" else: file = get_file(Path(local_dir) / "engine.ini") if file: return conf(file) global_dir = smarts_global_user_dir() file = get_file(Path(global_dir) / "engine.ini") if file: return conf(file) default_path = Path(__file__).parents[1].resolve() / "engine.ini" return conf(get_file(default_path))
Get the SMARTS environment configuration for the smarts engine. .. note:: This searches the following locations and loads the first one it finds: Supplied ``config_path``. Default: `./smarts_engine.ini` `~/.smarts/engine.ini` `/etc/smarts/engine.ini` `$PYTHON_PATH/smarts/engine.ini` Args: config_path (str, optional): The configurable location. Defaults to `./smarts_engine.ini`. Returns: Config: A configuration utility that allows resolving environment and `engine.ini` configuration.
config
python
huawei-noah/SMARTS
smarts/core/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/__init__.py
MIT
def euclidean_distance(p1: Point, p2: Point) -> float: """The distance taking measuring a direct line between p1 and p2.""" dx = p1[0] - p2[0] dy = p1[1] - p2[1] return math.sqrt(dx * dx + dy * dy)
The distance taking measuring a direct line between p1 and p2.
euclidean_distance
python
huawei-noah/SMARTS
smarts/core/shape.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/shape.py
MIT
def position_at_offset(p1: Point, p2: Point, offset: float) -> Optional[Point]: """A point between p1 and p2 given an offset less than the distance between p1 and p2.""" if is_close(offset, 0.0): # for pathological cases with dist == 0 and offset == 0 return p1 dist = euclidean_distance(p1, p2) if is_close(dist, offset): return p2 if offset > dist: return None x = p1[0] + (p2[0] - p1[0]) * (offset / dist) y = p1[1] + (p2[1] - p1[1]) * (offset / dist) return Point(x, y)
A point between p1 and p2 given an offset less than the distance between p1 and p2.
position_at_offset
python
huawei-noah/SMARTS
smarts/core/shape.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/shape.py
MIT
def offset_along_shape(point: Point, shape: List[Point]) -> Union[float, int]: """An offset on a shape defined as a vector path determined by the closest location on the path to the point. """ if point not in shape: return polygon_offset_with_minimum_distance_to_point(point, shape) offset = 0 for i in range(len(shape) - 1): if shape[i] == point: break offset += euclidean_distance(shape[i], shape[i + 1]) return offset
An offset on a shape defined as a vector path determined by the closest location on the path to the point.
offset_along_shape
python
huawei-noah/SMARTS
smarts/core/shape.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/shape.py
MIT
def position_at_shape_offset(shape: List[Point], offset: float) -> Optional[Point]: """A point defined as the offset into a shape defined as vector path.""" seen_length = 0 curr = shape[0] for next_p in shape[1:]: next_length = euclidean_distance(curr, next_p) if seen_length + next_length > offset: return position_at_offset(curr, next_p, offset - seen_length) seen_length += next_length curr = next_p return shape[-1]
A point defined as the offset into a shape defined as vector path.
position_at_shape_offset
python
huawei-noah/SMARTS
smarts/core/shape.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/shape.py
MIT
def line_offset_with_minimum_distance_to_point( point: Point, line_start: Point, line_end: Point, perpendicular: bool = False, ) -> Union[float, int]: """Return the offset from line (line_start, line_end) where the distance to point is minimal""" p = point p1 = line_start p2 = line_end d = euclidean_distance(p1, p2) u = ((p[0] - p1[0]) * (p2[0] - p1[0])) + ((p[1] - p1[1]) * (p2[1] - p1[1])) if u < 0.0: return 0.0 if d == 0.0 or u > d * d: if perpendicular: return -1 return d return u / d
Return the offset from line (line_start, line_end) where the distance to point is minimal
line_offset_with_minimum_distance_to_point
python
huawei-noah/SMARTS
smarts/core/shape.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/shape.py
MIT
def polygon_offset_with_minimum_distance_to_point( point: Point, polygon: List[Point] ) -> Union[float, int]: """Return the offset and the distance from the polygon start where the distance to the point is minimal""" p = point s = polygon seen = 0 min_dist = 1e400 min_offset = -1 for i in range(len(s) - 1): p_offset = line_offset_with_minimum_distance_to_point(p, s[i], s[i + 1]) dist = ( min_dist if p_offset == -1 else euclidean_distance(p, position_at_offset(s[i], s[i + 1], p_offset)) ) if dist < min_dist: min_dist = dist min_offset = p_offset + seen seen += euclidean_distance(s[i], s[i + 1]) return min_offset
Return the offset and the distance from the polygon start where the distance to the point is minimal
polygon_offset_with_minimum_distance_to_point
python
huawei-noah/SMARTS
smarts/core/shape.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/shape.py
MIT
def distance_point_to_line( point: Point, line_start: Point, line_end: Point, perpendicular: bool = False, ) -> Union[float, int]: """Return the minimum distance between point and the line (line_start, line_end)""" p1 = line_start p2 = line_end offset = line_offset_with_minimum_distance_to_point( point, line_start, line_end, perpendicular ) if offset == -1: return -1 if offset == 0: return euclidean_distance(point, p1) u = offset / euclidean_distance(line_start, line_end) intersection = Point(p1[0] + u * (p2[0] - p1[0]), p1[1] + u * (p2[1] - p1[1])) return euclidean_distance(point, intersection)
Return the minimum distance between point and the line (line_start, line_end)
distance_point_to_line
python
huawei-noah/SMARTS
smarts/core/shape.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/shape.py
MIT
def distance_point_to_polygon( point: Point, polygon: List[Point], perpendicular: bool = False ) -> Union[float, int]: """Return the minimum distance between point and polygon""" p = point s = polygon min_dist = None for i in range(len(s) - 1): dist = distance_point_to_line(p, s[i], s[i + 1], perpendicular) if dist == -1 and perpendicular and i != 0: # distance to inner corner dist = euclidean_distance(point, s[i]) if dist != -1: if min_dist is None or dist < min_dist: min_dist = dist if min_dist is not None: return min_dist return -1
Return the minimum distance between point and polygon
distance_point_to_polygon
python
huawei-noah/SMARTS
smarts/core/shape.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/shape.py
MIT
def test_only_agents_reset_if_scenario_does_not_change(smarts, scenarios): """Upon reset, if the scenario remains the same then the agent should be reset ("teleported" somewhere else) but the social vehicles should continue as if nothing happened. """ def ego_vehicle_pose(agent_obs): state = agent_obs.ego_vehicle_state start = tuple(state.position) + (state.heading,) return np.array(start) def neighborhood_vehicle_poses(agent_obs): neighborhood_vehicle_states = agent_obs.neighborhood_vehicle_states states = sorted(neighborhood_vehicle_states, key=lambda s: s.id) starts = [tuple(s.position) + (s.heading,) for s in states] if not starts: return np.array([]) return np.stack(starts) scenario = next(scenarios) seed(42) obs = smarts.reset(scenario) agent_obs = obs["Agent-007"] ego_start_pose = ego_vehicle_pose(agent_obs) sv_start_poses = neighborhood_vehicle_poses(agent_obs) for _ in range(50): smarts.step({"Agent-007": "keep_lane"}) seed(42) obs = smarts.reset(scenario) agent_obs = obs["Agent-007"] agent_pose_reset_to_initial = np.all( np.isclose(ego_start_pose, ego_vehicle_pose(agent_obs)) ) sv_poses = neighborhood_vehicle_poses(agent_obs) sv_poses_reset_to_initial = sv_poses.shape == sv_start_poses.shape if sv_poses_reset_to_initial: sv_poses_reset_to_initial = np.all(np.isclose(sv_poses, sv_start_poses)) assert ( agent_pose_reset_to_initial ), "Upon reset the agent goes back to the starting position" assert sv_poses_reset_to_initial, "Upon reset social vehicles are unaffected"
Upon reset, if the scenario remains the same then the agent should be reset ("teleported" somewhere else) but the social vehicles should continue as if nothing happened.
test_only_agents_reset_if_scenario_does_not_change
python
huawei-noah/SMARTS
smarts/core/tests/test_smarts_reset.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/tests/test_smarts_reset.py
MIT
def test_trajectory_interpolation_provider(smarts, agent_spec, scenario): """Test trajectory interpolation provider and controller. With different planning algorithm of WithTimeTrajectoryAgent, vehicle is going to accomplish its mission or not. """ agent = agent_spec.build_agent() scenario = next(scenario) smarts.setup(scenario) observations = smarts.reset(scenario) init_ego_state = observations[AGENT_ID].ego_vehicle_state reached_goal = False for _ in range(5): agent_obs = observations[AGENT_ID] agent_action = agent.act(agent_obs) observations, _, dones, _ = smarts.step({AGENT_ID: agent_action}) if agent_obs.events.reached_goal: reached_goal = True break curr_position = agent_obs.ego_vehicle_state.position curr_heading = agent_obs.ego_vehicle_state.heading curr_speed = agent_obs.ego_vehicle_state.speed init_position = init_ego_state.position init_heading = init_ego_state.heading init_speed = init_ego_state.speed assert np.linalg.norm(np.subtract(curr_position[:2], init_position[:2])) > 1e-16 assert not np.isclose(curr_heading, init_heading) assert not np.isclose(curr_speed, init_speed)
Test trajectory interpolation provider and controller. With different planning algorithm of WithTimeTrajectoryAgent, vehicle is going to accomplish its mission or not.
test_trajectory_interpolation_provider
python
huawei-noah/SMARTS
smarts/core/tests/test_trajectory_interpolation_provider.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/tests/test_trajectory_interpolation_provider.py
MIT
def bubble( bubble_limits: t.BubbleLimits, social_actor: t.SocialAgentActor, transition_cases ): """ |(93) |(95) (100) (105)| (107)| """ _, margin, _ = transition_cases return t.Bubble( zone=t.PositionalZone(pos=(100, 0), size=(10, 10)), margin=margin, limit=bubble_limits, actor=social_actor, )
|(93) |(95) (100) (105)| (107)|
bubble
python
huawei-noah/SMARTS
smarts/core/tests/test_bubble_manager.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/tests/test_bubble_manager.py
MIT
def test_smarts_doesnt_leak_tasks_after_reset(smarts, scenarios): """We have had issues in the past where we would forget to clean up tasks between episodes resulting in a gradual decay in performance, this test gives us a bit of a smoke screen against this class of regressions. See #237 for details """ try: num_tasks_before_reset = len( smarts.renderer._showbase_instance.taskMgr.mgr.getTasks() ) except Exception as e: raise RendererException.required_to("test smarts_doesnt_leak_tasks_after_reset") scenario = next(scenarios) smarts.reset(scenario) for _ in range(10): smarts.step({}) try: num_tasks_after_reset = len( smarts.renderer._showbase_instance.taskMgr.mgr.getTasks() ) except Exception as e: raise RendererException.required_to("test smarts_doesnt_leak_tasks_after_reset") assert num_tasks_after_reset == num_tasks_before_reset
We have had issues in the past where we would forget to clean up tasks between episodes resulting in a gradual decay in performance, this test gives us a bit of a smoke screen against this class of regressions. See #237 for details
test_smarts_doesnt_leak_tasks_after_reset
python
huawei-noah/SMARTS
smarts/core/tests/test_smarts.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/tests/test_smarts.py
MIT
def test_collision(bullet_client: bc.BulletClient): """Spawn overlap to check for the most basic collision""" chassis = AckermannChassis( Pose.from_center([0, 0, 0], Heading(-math.pi * 0.5)), bullet_client ) b_chassis = BoxChassis( Pose.from_center([0, 0, 0], Heading(0)), speed=0, dimensions=VEHICLE_CONFIGS["passenger"].dimensions, bullet_client=chassis._client, ) collisions = step_with_vehicle_commands(chassis, steps=2) assert len(collisions) > 0 collided_bullet_ids = set([c.bullet_id for c in collisions]) GROUND_ID = 0 assert b_chassis.bullet_id in collided_bullet_ids assert chassis.bullet_id not in collided_bullet_ids assert GROUND_ID not in collided_bullet_ids
Spawn overlap to check for the most basic collision
test_collision
python
huawei-noah/SMARTS
smarts/core/tests/test_collision.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/tests/test_collision.py
MIT
def test_non_collision(bullet_client: bc.BulletClient): """Spawn without overlap to check for the most basic collision""" chassis = AckermannChassis( Pose.from_center([0, 0, 0], Heading(-math.pi * 0.5)), bullet_client ) b_chassis = BoxChassis( Pose.from_center([0, 10, 0], Heading(0)), speed=0, dimensions=VEHICLE_CONFIGS["passenger"].dimensions, bullet_client=chassis._client, ) collisions = step_with_vehicle_commands(chassis, steps=1) collided_bullet_ids = set([c.bullet_id for c in collisions]) assert b_chassis.bullet_id not in collided_bullet_ids assert len(collisions) == 0
Spawn without overlap to check for the most basic collision
test_non_collision
python
huawei-noah/SMARTS
smarts/core/tests/test_collision.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/tests/test_collision.py
MIT
def test_collision_collide_with_standing_vehicle(bullet_client: bc.BulletClient): """Run a vehicle at a standing vehicle as fast as possible.""" chassis = AckermannChassis( Pose.from_center([10, 0, 0], Heading(math.pi * 0.5)), bullet_client ) b_chassis = BoxChassis( Pose.from_center([0, 0, 0], Heading(0)), speed=0, dimensions=VEHICLE_CONFIGS["passenger"].dimensions, bullet_client=chassis._client, ) collisions = step_with_vehicle_commands(chassis, steps=1000, throttle=1, steering=0) collided_bullet_ids = set([c.bullet_id for c in collisions]) GROUND_ID = 0 assert len(collisions) > 0 assert b_chassis.bullet_id in collided_bullet_ids assert chassis.bullet_id not in collided_bullet_ids assert GROUND_ID not in collided_bullet_ids
Run a vehicle at a standing vehicle as fast as possible.
test_collision_collide_with_standing_vehicle
python
huawei-noah/SMARTS
smarts/core/tests/test_collision.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/tests/test_collision.py
MIT
def test_box_chassis_collision(bullet_client: bc.BulletClient): """Spawn overlap to check for the most basic BoxChassis collision""" # This is required to ensure that the bullet move_to constraint # actually moves the vehicle the correct amount bullet_client.setPhysicsEngineParameter( fixedTimeStep=0.1, numSubSteps=24, numSolverIterations=10, solverResidualThreshold=0.001, ) chassis = BoxChassis( Pose.from_center([0, 0, 0], Heading(-0.5 * math.pi)), speed=10, dimensions=VEHICLE_CONFIGS["passenger"].dimensions, bullet_client=bullet_client, ) b_chassis = BoxChassis( Pose.from_center([0, 0, 0], Heading(0.5 * math.pi)), speed=0, dimensions=VEHICLE_CONFIGS["passenger"].dimensions, bullet_client=chassis._client, ) collisions = step_with_pose_delta( chassis, steps=10, pose_delta=np.array((1.0, 0, 0)), speed=10 ) assert len(collisions) == 3 collided_bullet_ids = set([c.bullet_id for c in collisions]) GROUND_ID = 0 assert b_chassis.bullet_id in collided_bullet_ids assert chassis.bullet_id not in collided_bullet_ids assert GROUND_ID not in collided_bullet_ids
Spawn overlap to check for the most basic BoxChassis collision
test_box_chassis_collision
python
huawei-noah/SMARTS
smarts/core/tests/test_collision.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/tests/test_collision.py
MIT
def test_collision_joust(bullet_client: bc.BulletClient): """Run two agents at each other to test for clipping.""" white_knight_chassis = AckermannChassis( Pose.from_center([10, 0, 0], Heading(math.pi * 0.5)), bullet_client ) black_knight_chassis = AckermannChassis( Pose.from_center([-10, 0, 0], Heading(-math.pi * 0.5)), bullet_client ) wkc_collisions, bkc_collisions = _joust( white_knight_chassis, black_knight_chassis, steps=10000 ) assert len(wkc_collisions) > 0 assert len(bkc_collisions) > 0 assert white_knight_chassis.bullet_id in [c.bullet_id for c in bkc_collisions] assert black_knight_chassis.bullet_id in [c.bullet_id for c in wkc_collisions]
Run two agents at each other to test for clipping.
test_collision_joust
python
huawei-noah/SMARTS
smarts/core/tests/test_collision.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/tests/test_collision.py
MIT
def test_ackerman_chassis_size_unchanged(bullet_client: bc.BulletClient): """Test that the ackerman chassis size has not changed accidentally by packing it around itself with no forces and then check for collisions after a few steps.""" bullet_client.setGravity(0, 0, 0) separation_for_collision_error = 0.0501 original_vehicle_dimensions = VEHICLE_CONFIGS["passenger"].dimensions shared_heading = Heading(0) chassis = AckermannChassis( Pose.from_center([0, 0, 0], shared_heading), bullet_client ) chassis_n = BoxChassis( Pose.from_center( [ 0, (original_vehicle_dimensions.length + separation_for_collision_error), 0, ], shared_heading, ), speed=0, dimensions=VEHICLE_CONFIGS["passenger"].dimensions, bullet_client=bullet_client, ) chassis_e = BoxChassis( Pose.from_center( [ (original_vehicle_dimensions.width + separation_for_collision_error), 0, 0, ], shared_heading, ), speed=0, dimensions=VEHICLE_CONFIGS["passenger"].dimensions, bullet_client=bullet_client, ) chassis_s = BoxChassis( Pose.from_center( [ 0, -(original_vehicle_dimensions.length + separation_for_collision_error), 0, ], shared_heading, ), speed=0, dimensions=VEHICLE_CONFIGS["passenger"].dimensions, bullet_client=bullet_client, ) chassis_w = BoxChassis( Pose.from_center( [ -(original_vehicle_dimensions.width + separation_for_collision_error), 0, 0, ], shared_heading, ), speed=0, dimensions=VEHICLE_CONFIGS["passenger"].dimensions, bullet_client=bullet_client, ) collisions = step_with_vehicle_commands(chassis, steps=10) assert len(collisions) == 0
Test that the ackerman chassis size has not changed accidentally by packing it around itself with no forces and then check for collisions after a few steps.
test_ackerman_chassis_size_unchanged
python
huawei-noah/SMARTS
smarts/core/tests/test_collision.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/tests/test_collision.py
MIT
def test_bubble_hijacking(smarts, scenarios, active_bubbles, num_vehicles, traffic_sim): """Ensures bubble airlocking, hijacking, and relinquishing are functional. Additionally, we test with multiple bubbles and vehicles to ensure operation is correct in these conditions as well. """ scenario = next(scenarios) smarts.reset(scenario) index = smarts.vehicle_index geometries = [bubble_geometry(b, smarts.road_map) for b in active_bubbles] # bubble: vehicle: steps per zone steps_driven_in_zones = {b.id: defaultdict(ZoneSteps) for b in active_bubbles} vehicles_made_to_through_bubble = {b.id: [] for b in active_bubbles} for _ in range(300): smarts.step({}) for vehicle in index.vehicles: position = Point(vehicle.position) for bubble, geometry in zip(active_bubbles, geometries): in_bubble = position.within(geometry.bubble) is_shadowing = index.shadower_id_from_vehicle_id(vehicle.id) is not None is_agent_controlled = vehicle.id in index.agent_vehicle_ids() vehicle_id = ( vehicle.id if traffic_sim == "SUMO" else re.sub(r"_\d+$", "", vehicle.id) ) zone_steps = steps_driven_in_zones[bubble.id][vehicle_id] if in_bubble and not is_shadowing and is_agent_controlled: zone_steps.in_bubble += 1 elif not in_bubble and is_shadowing and not is_agent_controlled: zone_steps.airlock_entry += 1 elif not in_bubble and not is_shadowing and is_agent_controlled: zone_steps.airlock_exit += 1 if vehicle_id not in vehicles_made_to_through_bubble[bubble.id]: vehicles_made_to_through_bubble[bubble.id].append(vehicle_id) elif not any([position.within(geom.airlock) for geom in geometries]): # Not in any bubble; airlock is the encompassing region zone_steps.outside_bubble += 1 assert ( not in_bubble and not is_shadowing and not is_agent_controlled ) # Just to have some padding, we want to be in each region at least 2 steps min_steps = 2 for bubble_id, zones in steps_driven_in_zones.items(): vehicle_ids = vehicles_made_to_through_bubble[bubble_id] assert ( len(vehicle_ids) >= num_vehicles ), "Insufficient no. vehicles drove through bubble" for vehicle_id in vehicle_ids[:num_vehicles]: zone = zones[vehicle_id] assert all( [ zone.in_bubble >= min_steps, zone.outside_bubble >= min_steps, zone.airlock_entry >= min_steps, zone.airlock_exit >= min_steps, ] ), ( f"bubble={bubble_id}, vehicle_id={vehicle_id}, zone={zone} doesn't meet " f"min_steps={min_steps} requirement" )
Ensures bubble airlocking, hijacking, and relinquishing are functional. Additionally, we test with multiple bubbles and vehicles to ensure operation is correct in these conditions as well.
test_bubble_hijacking
python
huawei-noah/SMARTS
smarts/core/tests/test_bubble_hijacking.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/tests/test_bubble_hijacking.py
MIT
def connection(): """This connects to an existing SUMO server instance.""" traci_conn = traci.connect( SUMO_PORT, numRetries=100, proc=None, waitBetweenRetries=0.1 ) traci_conn.setOrder(2) return traci_conn
This connects to an existing SUMO server instance.
connection
python
huawei-noah/SMARTS
smarts/core/tests/test_traffic_simulation.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/tests/test_traffic_simulation.py
MIT
def test_collision_avoidance_in_intersection(smarts, scenarios, traffic_sim): """Ensure that traffic providers can manage basic collision avoidance around an intersection.""" scenario = next(scenarios) smarts.reset(scenario) for _ in range(1000): smarts.step({}) assert not smarts._vehicle_collisions
Ensure that traffic providers can manage basic collision avoidance around an intersection.
test_collision_avoidance_in_intersection
python
huawei-noah/SMARTS
smarts/core/tests/test_traffic_provider_collision_avoidance.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/tests/test_traffic_provider_collision_avoidance.py
MIT
def maps_dir(): """Add a maps directory.""" return Path(__file__).parent.parent / "maps"
Add a maps directory.
maps_dir
python
huawei-noah/SMARTS
smarts/core/tests/helpers/scenario.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/tests/helpers/scenario.py
MIT
def perform_lane_following( cls, sim, agent_id: str, vehicle, controller_state: LaneFollowingControllerState, sensor_state, target_speed: float = 12.5, lane_change: int = 0, ): """Control a vehicle Args: sim: The simulator instance. agent_id: The id of the agent controlling the vehicle. XXX: unsure why this is needed vehicle: The vehicle that is to be controlled. controller_state: The previous controller state from this controller. sensor_state: The current sensor state from the vehicle's sensors. target_speed: The baseline target speed (controller may give more or less regardless.) lane_change: Lane index offset from vehicle's current lane. """ assert isinstance(vehicle.chassis, AckermannChassis) state = controller_state # This lookahead value is coupled with a few calculations below, changing it # may affect stability of the controller. wp_paths = sim.road_map.waypoint_paths( vehicle.pose, lookahead=16, route=sensor_state.get_plan(sim.road_map).route ) assert wp_paths, "no waypoints found. not near lane?" current_lane = LaneFollowingController.find_current_lane( wp_paths, vehicle.position ) wp_path = wp_paths[np.clip(current_lane + lane_change, 0, len(wp_paths) - 1)] # we compute a road "curviness" to inform our throttle activation. # We should move slowly when we are on curvy roads. ewma_road_curviness = 0.0 for wp_a, wp_b in reversed(list(zip(wp_path, wp_path[1:]))): ewma_road_curviness = lerp( ewma_road_curviness, math.degrees(abs(wp_a.relative_heading(wp_b.heading))), 0.03, ) road_curviness_normalization = 2.5 road_curviness = np.clip( ewma_road_curviness / road_curviness_normalization, 0, 1 ) # Number of trajectory point used for curvature calculation. num_trajectory_points = min([10, len(wp_path)]) trajectory = [ [wp_path[i].pos[0] for i in range(num_trajectory_points)], [wp_path[i].pos[1] for i in range(num_trajectory_points)], [wp_path[i].heading for i in range(num_trajectory_points)], ] # The following calculates the radius of curvature for the 4th # waypoints in the waypoint list. Value 4 is chosen to ensure # that the heading error correction is triggered before the vehicle # reaches to a sharp turn defined be min_curvature. look_ahead_curvature = abs( TrajectoryTrackingController.curvature_calculation(trajectory, 4) ) # Minimum curvature limit for pushing forward the waypoint # which is used for heading error calculation. min_curvature = 2 # If the look_ahead_curvature is less than the min_curvature, then # update the location of the points which its curvature is less than # min_curvature. if look_ahead_curvature <= min_curvature: state.min_curvature_location = ( wp_path[4].pos[0], wp_path[4].pos[1], ) # LOOK AHEAD ERROR SETTING # look_ahead_wp_num is the ahead waypoint which is used to # calculate the lateral error TODO: use adaptive setting to # choose the ahead waypoint # if the road_curviness is high(i.e. > 0.5), we reduce the # look_ahead_wp_num to calculate a more accurate lateral error # normal look ahead distant is set to 8 meters which is reduced # to 6 meters when the curvature increases. # Note: waypoints are spaced at roughly 1 meter apart if road_curviness > 0.5: look_ahead_wp_num = 3 else: look_ahead_wp_num = 4 look_ahead_wp_num = min(look_ahead_wp_num, len(wp_path) - 1) reference_heading = wp_path[0].heading look_ahead_wp = wp_path[look_ahead_wp_num] look_ahead_dist = look_ahead_wp.dist_to(vehicle.position) vehicle_look_ahead_pt = [ vehicle.position[0] - look_ahead_dist * math.sin(vehicle.heading), vehicle.position[1] + look_ahead_dist * math.cos(vehicle.heading), ] # 5.56 m/s (20 km/h), 6.94 m/s (25 km/h) are desired speed for different thresholds # for road curviness # 0.5 , 0.8 are dimensionless thresholds for road_curviness. # 1.8 and 0.6 are the longitudinal velocity controller # proportional gains for different road curvinesss. if road_curviness < 0.3: raw_throttle = ( -METER_PER_SECOND_TO_KM_PER_HR * 1.8 * (vehicle.speed - target_speed) ) elif road_curviness > 0.3 and road_curviness < 0.8: raw_throttle = ( -0.6 * METER_PER_SECOND_TO_KM_PER_HR * (vehicle.speed - np.clip(target_speed, 0, 6.94)) ) else: raw_throttle = ( -0.6 * METER_PER_SECOND_TO_KM_PER_HR * (vehicle.speed - np.clip(target_speed, 0, 5.56)) ) speed_error = vehicle.speed - target_speed state.integral_speed_error += speed_error * sim.last_dt velocity_error_damping_term = (speed_error - state.speed_error) / sim.last_dt # 5.5 is the gain of feedforward term for throttle. This term is # directly related to the steering angle, this is added to further # enhance the speed tracking performance. TODO: currently, the bullet # does not provide the lateral acceleration which is needed for # calculating the front lateral force. we need to replace the coefficient # with better approximation of the front lateral forces using explicit # differention. lateral_force_coefficient = 1.5 if vehicle.speed < 8 or target_speed < 6: lateral_force_coefficient = 0 # 0.2 is the coefficient of d-controller for speed tracking # 0.1 is the coefficient of I-controller for speed tracking raw_throttle += ( -0.2 * velocity_error_damping_term - 0.1 * state.integral_speed_error + abs( lateral_force_coefficient * math.sin(state.steering_state * vehicle.max_steering_wheel) ) ) state.speed_error = speed_error # If the distance of the vehicle to the ahead point for which # the waypoint curvature is less than min_curvature is less than # 2 meters, then push forward the waypoint which is used to # calculate the heading error. if (state.min_curvature_location != (None, None)) and math.sqrt( (vehicle.position[0] - state.min_curvature_location[0]) ** 2 + (vehicle.position[1] - state.min_curvature_location[1]) ** 2 ) < 2: reference_heading = wp_path[look_ahead_wp_num].heading # Desired closed loop poles of the lateral dynamics # The higher the absolute value, the closed loop response will # be faster for that state, the four states of that are used for # Linearization of the lateral dynamics are: # [lateral error, heading error, yaw_rate, side_slip angle] desired_poles = np.array( [ cls.lateral_error, cls.heading_error, cls.yaw_rate, cls.side_slip_angle, ] ) LaneFollowingController.calculate_lateral_gains( sim, state, vehicle, desired_poles, target_speed ) # LOOK AHEAD CONTROLLER controller_lat_error = wp_path[look_ahead_wp_num].signed_lateral_error( vehicle_look_ahead_pt ) curvature_radius = TrajectoryTrackingController.curvature_calculation( trajectory ) brake_norm = 0 if raw_throttle < 0: brake_norm = np.clip(-raw_throttle, 0, 1) throttle_norm = 0 else: # The term involving absolute value of the lateral speed is # added as a traction control strategy, The traction controller # gain is set to 4.5, the lower the value, the vehicle becomes # more agile but may result in instability in harsh curves # with high speeds. if vehicle.speed > 70 / 3.6 and abs(curvature_radius) <= 1e3: traction_gain = 4.5 elif 40 / 3.6 <= vehicle.speed <= 70 / 3.6 and abs(curvature_radius) <= 3: traction_gain = 2.5 else: traction_gain = 0.5 throttle_norm = np.clip( raw_throttle - traction_gain * METER_PER_SECOND_TO_KM_PER_HR * abs(vehicle.chassis.longitudinal_lateral_speed[1]), 0, 1, ) # The feedback term involving yaw rate is added to reduce # the oscillation in vehicle heading, the proportional gain for # yaw rate is set to 2.75, the higher value results in less # oscillation in heading angle. 0.3 is the integral controller # gain for lateral error. The feedforward term based on the # curvature is added to enhance the transient performance when # the road curvature changes locally. state.lateral_integral_error += sim.last_dt * controller_lat_error # The feed forward term for the steering controller. This # term is proportionate to Ux^2/R. The coefficient 0.15 is # chosen to enhance the transient tracking performance. # This coefficient also depends on the inertia properties # and the cornering stiffness of the tires. See: # https://www.tandfonline.com/doi/full/10.1080/00423114.2015.1055279 steering_feed_forward_gain = 0.15 if abs(curvature_radius) < 7: steering_feed_forward_gain = 0.45 steering_controller_feed_forward = ( 1 * steering_feed_forward_gain * (1 / curvature_radius) * (vehicle.speed) ** 2 ) normalized_speed = np.clip(vehicle.speed * 3.6 / 100, 0, 1) heading_speed_gain = -lerp(0.5, 14, normalized_speed) yaw_rate_speed_gain = lerp(5.75, 11.75, normalized_speed) lateral_speed_gain = np.clip(lerp(-1, 14, normalized_speed), 1, 2) max_steering_nomralized = 1 if abs(curvature_radius) > 1e7 and lane_change != 0: heading_speed_gain = -4.95 yaw_rate_speed_gain = 1 lateral_speed_gain = 0.22 max_steering_nomralized = 0.12 z_yaw = vehicle.chassis.velocity_vectors[1][2] heading_error = min_angles_difference_signed( (vehicle.heading % (2 * math.pi)), reference_heading ) steering_norm = np.clip( -heading_speed_gain * math.degrees(state.heading_error_gain) * heading_error + lateral_speed_gain * state.lateral_error_gain * (controller_lat_error) + yaw_rate_speed_gain * z_yaw + 0.3 * state.lateral_integral_error - steering_controller_feed_forward, -max_steering_nomralized, max_steering_nomralized, ) # The steering low pass filter, 5.5 is the constant of the # first order linear low pass filter. steering_filter_constant = 5.5 state.steering_state = low_pass_filter( steering_norm, state.steering_state, steering_filter_constant, sim.last_dt, ) # The Throttle low pass filter, 2 is the constant of the # first order linear low pass filter. # TODO: Add low pass filter for brake. throttle_filter_constant = 2 state.throttle_state = low_pass_filter( throttle_norm, state.throttle_state, throttle_filter_constant, sim.last_dt, lower_bound=0, ) # Applying control actions to the vehicle vehicle.control( throttle=state.throttle_state, brake=brake_norm, steering=state.steering_state, ) LaneFollowingController._update_target_lane_if_reached_end_of_lane( agent_id, vehicle, controller_state, sensor_state.get_plan(sim.road_map), )
Control a vehicle Args: sim: The simulator instance. agent_id: The id of the agent controlling the vehicle. XXX: unsure why this is needed vehicle: The vehicle that is to be controlled. controller_state: The previous controller state from this controller. sensor_state: The current sensor state from the vehicle's sensors. target_speed: The baseline target speed (controller may give more or less regardless.) lane_change: Lane index offset from vehicle's current lane.
perform_lane_following
python
huawei-noah/SMARTS
smarts/core/controllers/lane_following_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/lane_following_controller.py
MIT
def find_current_lane(wp_paths, vehicle_position): """Find the lane of the vehicle given a set of waypoint paths.""" relative_distant_lane = [ np.linalg.norm(np.subtract(wp_paths[idx][0].pos, vehicle_position[:2])) for idx in range(len(wp_paths)) ] return np.argmin(relative_distant_lane)
Find the lane of the vehicle given a set of waypoint paths.
find_current_lane
python
huawei-noah/SMARTS
smarts/core/controllers/lane_following_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/lane_following_controller.py
MIT
def place_poles(A: np.ndarray, B: np.ndarray, poles: np.ndarray) -> np.ndarray: """Given a linear system described by ẋ = Ax + Bu, compute the gain matrix K such that the closed loop eigenvalues of A - BK are in the desired pole locations. References: - https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.place_poles.html - https://en.wikipedia.org/wiki/Ackermann%27s_formula """ # Controllability matrix C = np.hstack( [B] + [np.linalg.matrix_power(A, i) @ B for i in range(1, A.shape[0])] ) # Desired characteristic polynomial of A - BK poly = np.real(np.poly(poles)) # Solve using Ackermann's formula n = np.size(poly) p = poly[n - 1] * np.linalg.matrix_power(A, 0) for i in np.arange(1, n): p = p + poly[n - i - 1] * np.linalg.matrix_power(A, i) return np.linalg.solve(C, p)[-1][:]
Given a linear system described by ẋ = Ax + Bu, compute the gain matrix K such that the closed loop eigenvalues of A - BK are in the desired pole locations. References: - https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.place_poles.html - https://en.wikipedia.org/wiki/Ackermann%27s_formula
place_poles
python
huawei-noah/SMARTS
smarts/core/controllers/lane_following_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/lane_following_controller.py
MIT