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 sync(self):
"""Update the state of the index."""
for vehicle_id, vehicle in self._vehicles.items():
v_index = self._controlled_by["vehicle_id"] == vehicle_id
entity = _ControlEntity(*self._controlled_by[v_index][0])
self._controlled_by[v_index] = tuple(
entity._replace(position=vehicle.position)
) | Update the state of the index. | sync | python | huawei-noah/SMARTS | smarts/core/vehicle_index.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle_index.py | MIT |
def teardown(self, renderer: RendererBase):
"""Clean up resources, resetting the index."""
self._controlled_by = VehicleIndex._build_empty_controlled_by()
for vehicle in self._vehicles.values():
vehicle.teardown(renderer=renderer, exclude_chassis=True)
self._vehicles = {}
self._controller_states = {}
self._2id_to_id = {} | Clean up resources, resetting the index. | teardown | python | huawei-noah/SMARTS | smarts/core/vehicle_index.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle_index.py | MIT |
def start_agent_observation(
self,
sim: SMARTS,
vehicle_id: str,
agent_id: str,
agent_interface: AgentInterface,
plan: "plan.Plan",
boid: bool = False,
initialize_sensors: bool = True,
):
"""Associate an agent to a vehicle. Set up any needed sensor requirements."""
b_vehicle_id, b_agent_id = _2id(vehicle_id), _2id(agent_id)
self._2id_to_id[b_agent_id] = agent_id
vehicle = self._vehicles[b_vehicle_id]
sim.sensor_manager.add_sensor_state(
vehicle.id,
SensorState(
agent_interface.max_episode_steps,
plan_frame=plan.frame(),
),
)
if initialize_sensors:
Vehicle.attach_sensors_to_vehicle(
sim.sensor_manager, sim, vehicle, agent_interface
)
self._controller_states[b_vehicle_id] = ControllerState.from_action_space(
agent_interface.action, vehicle.pose, sim
)
v_index = self._controlled_by["vehicle_id"] == b_vehicle_id
entity = _ControlEntity(*self._controlled_by[v_index][0])
self._controlled_by[v_index] = tuple(
entity._replace(shadower_id=b_agent_id, is_boid=boid)
)
# XXX: We are not giving the vehicle a chassis here but rather later
# when we switch_to_agent_control. This means when control that requires
# a chassis comes online, it needs to appropriately initialize
# chassis-specific states, such as tire rotation.
return vehicle | Associate an agent to a vehicle. Set up any needed sensor requirements. | start_agent_observation | python | huawei-noah/SMARTS | smarts/core/vehicle_index.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle_index.py | MIT |
def switch_control_to_agent(
self,
sim: SMARTS,
vehicle_id: str,
agent_id: str,
boid: bool = False,
hijacking: bool = False,
recreate: bool = False,
agent_interface: Optional[AgentInterface] = None,
):
"""Give control of the specified vehicle to the specified agent.
Args:
sim:
An instance of a SMARTS simulation.
vehicle_id:
The id of the vehicle to associate.
agent_id:
The id of the agent to associate.
boid:
If the agent is acting as a boid agent controlling multiple vehicles.
hijacking:
If the vehicle has been taken over from another controlling owner.
recreate:
If the vehicle should be destroyed and regenerated.
agent_interface:
The agent interface for sensor requirements.
"""
self._log.debug("Switching control of '%s' to '%s'", vehicle_id, agent_id)
b_vehicle_id, b_agent_id = _2id(vehicle_id), _2id(agent_id)
if recreate:
# XXX: Recreate is presently broken for bubbles because it impacts the
# sumo traffic sim sync(...) logic in how it detects a vehicle as
# being hijacked vs joining. Presently it's still used for trapping.
return self._switch_control_to_agent_recreate(
sim, b_vehicle_id, b_agent_id, boid, hijacking
)
vehicle = self._vehicles[b_vehicle_id]
chassis = None
if agent_interface and agent_interface.action in sim.dynamic_action_spaces:
vehicle_definition = self._vehicle_definitions.load_vehicle_definition(
agent_interface.vehicle_class
)
chassis = AckermannChassis(
pose=vehicle.pose,
bullet_client=sim.bc,
vehicle_dynamics_filepath=vehicle_definition.get("dynamics_model"),
tire_parameters_filepath=vehicle_definition.get("tire_params"),
friction_map=sim.scenario.surface_patches,
controller_parameters=self._vehicle_definitions.controller_params_for_vehicle_class(
agent_interface.vehicle_class
),
chassis_parameters=self._vehicle_definitions.chassis_params_for_vehicle_class(
agent_interface.vehicle_class
),
initial_speed=vehicle.speed,
)
else:
chassis = BoxChassis(
pose=vehicle.pose,
speed=vehicle.speed,
dimensions=vehicle.state.dimensions,
bullet_client=sim.bc,
)
vehicle.swap_chassis(chassis)
v_index = self._controlled_by["vehicle_id"] == b_vehicle_id
entity = _ControlEntity(*self._controlled_by[v_index][0])
role = ActorRole.SocialAgent if hijacking else ActorRole.EgoAgent
self._controlled_by[v_index] = tuple(
entity._replace(
role=role,
owner_id=b_agent_id,
shadower_id=b"",
is_boid=boid,
is_hijacked=hijacking,
)
)
return vehicle | Give control of the specified vehicle to the specified agent.
Args:
sim:
An instance of a SMARTS simulation.
vehicle_id:
The id of the vehicle to associate.
agent_id:
The id of the agent to associate.
boid:
If the agent is acting as a boid agent controlling multiple vehicles.
hijacking:
If the vehicle has been taken over from another controlling owner.
recreate:
If the vehicle should be destroyed and regenerated.
agent_interface:
The agent interface for sensor requirements. | switch_control_to_agent | python | huawei-noah/SMARTS | smarts/core/vehicle_index.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle_index.py | MIT |
def stop_shadowing(self, shadower_id: str, vehicle_id: Optional[str] = None):
"""Ends the shadowing by an a shadowing observer.
Args:
shadower_id (str): Removes this shadowing observer from all vehicles.
vehicle_id (str, optional):
If given this method removes shadowing from a specific vehicle. Defaults to None.
"""
shadower_id = _2id(shadower_id)
v_index = self._controlled_by["shadower_id"] == shadower_id
if vehicle_id:
b_vehicle_id = _2id(vehicle_id)
# This multiplication finds overlap of "shadower_id" and "vehicle_id"
v_index = (self._controlled_by["vehicle_id"] == b_vehicle_id) * v_index
for entity in self._controlled_by[v_index]:
entity = _ControlEntity(*entity)
self._controlled_by[v_index] = tuple(entity._replace(shadower_id=b"")) | Ends the shadowing by an a shadowing observer.
Args:
shadower_id (str): Removes this shadowing observer from all vehicles.
vehicle_id (str, optional):
If given this method removes shadowing from a specific vehicle. Defaults to None. | stop_shadowing | python | huawei-noah/SMARTS | smarts/core/vehicle_index.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle_index.py | MIT |
def stop_agent_observation(self, vehicle_id: str) -> Vehicle:
"""Strip all sensors from a vehicle and stop all owners from watching the vehicle."""
b_vehicle_id = _2id(vehicle_id)
vehicle = self._vehicles[b_vehicle_id]
v_index = self._controlled_by["vehicle_id"] == b_vehicle_id
entity = self._controlled_by[v_index][0]
entity = _ControlEntity(*entity)
self._controlled_by[v_index] = tuple(entity._replace(shadower_id=b""))
return vehicle | Strip all sensors from a vehicle and stop all owners from watching the vehicle. | stop_agent_observation | python | huawei-noah/SMARTS | smarts/core/vehicle_index.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle_index.py | MIT |
def relinquish_agent_control(
self, sim: SMARTS, vehicle_id: str, road_map: RoadMap
) -> Tuple[VehicleState, Optional[RoadMap.Route]]:
"""Give control of the vehicle back to its original controller."""
self._log.debug(f"Relinquishing agent control v_id={vehicle_id}")
v_id = _2id(vehicle_id)
ss = sim.sensor_manager.sensor_state_for_actor_id(vehicle_id)
route = ss.get_plan(road_map).route if ss else None
vehicle = self.stop_agent_observation(vehicle_id)
# pytype: disable=attribute-error
Vehicle.detach_all_sensors_from_vehicle(vehicle)
# pytype: enable=attribute-error
sim.sensor_manager.remove_actor_sensors_by_actor_id(vehicle_id)
sim.sensor_manager.remove_sensor_state_by_actor_id(vehicle_id)
vehicle = self._vehicles[v_id]
box_chassis = BoxChassis(
pose=vehicle.chassis.pose,
speed=vehicle.chassis.speed,
dimensions=vehicle.chassis.dimensions,
bullet_client=sim.bc,
)
vehicle.swap_chassis(box_chassis)
v_index = self._controlled_by["vehicle_id"] == v_id
entity = self._controlled_by[v_index][0]
entity = _ControlEntity(*entity)
self._controlled_by[v_index] = tuple(
entity._replace(
role=ActorRole.Social,
owner_id=b"",
shadower_id=b"",
is_boid=False,
is_hijacked=False,
)
)
return vehicle.state, route | Give control of the vehicle back to its original controller. | relinquish_agent_control | python | huawei-noah/SMARTS | smarts/core/vehicle_index.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle_index.py | MIT |
def attach_sensors_to_vehicle(
self,
sim: SMARTS,
vehicle_id: str,
agent_interface: AgentInterface,
plan: "plan.Plan",
):
"""Attach sensors as per the agent interface requirements to the specified vehicle."""
b_vehicle_id = _2id(vehicle_id)
vehicle = self._vehicles[b_vehicle_id]
Vehicle.attach_sensors_to_vehicle(
sim.sensor_manager,
sim,
vehicle,
agent_interface,
)
sim.sensor_manager.add_sensor_state(
vehicle.id,
SensorState(
agent_interface.max_episode_steps,
plan_frame=plan.frame(),
),
)
self._controller_states[b_vehicle_id] = ControllerState.from_action_space(
agent_interface.action, vehicle.pose, sim
) | Attach sensors as per the agent interface requirements to the specified vehicle. | attach_sensors_to_vehicle | python | huawei-noah/SMARTS | smarts/core/vehicle_index.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle_index.py | MIT |
def _build_agent_vehicle(
cls,
sim: SMARTS,
vehicle_id: str,
action: Optional[ActionSpaceType],
vehicle_type: str,
vehicle_class: str,
mission: plan.NavigationMission,
vehicle_dynamics_filepath: Optional[str],
tire_filepath: str,
visual_model_filepath: str,
trainable: bool,
surface_patches: Sequence[Dict[str, Any]],
initial_speed: Optional[float] = None,
) -> Vehicle:
"""Create a new vehicle and set up sensors and planning information as required by the
ego agent.
"""
chassis_dims = Vehicle.agent_vehicle_dims(mission, default=vehicle_type)
start = mission.start
if start.from_front_bumper:
start_pose = Pose.from_front_bumper(
front_bumper_position=np.array(start.position[:2]),
heading=start.heading,
length=chassis_dims.length,
)
else:
start_pose = Pose.from_center(start.position, start.heading)
vehicle_color = SceneColors.Agent if trainable else SceneColors.SocialAgent
controller_parameters = (
sim.vehicle_index._vehicle_definitions.controller_params_for_vehicle_class(
vehicle_class
)
)
chassis_parameters = (
sim.vehicle_index._vehicle_definitions.chassis_params_for_vehicle_class(
vehicle_class
)
)
chassis = None
if action in sim.dynamic_action_spaces:
if mission.vehicle_spec:
logger = logging.getLogger(cls.__name__)
logger.warning(
"setting vehicle dimensions on a AckermannChassis not yet supported"
)
chassis = AckermannChassis(
pose=start_pose,
bullet_client=sim.bc,
vehicle_dynamics_filepath=vehicle_dynamics_filepath,
tire_parameters_filepath=tire_filepath,
friction_map=surface_patches,
controller_parameters=controller_parameters,
chassis_parameters=chassis_parameters,
initial_speed=initial_speed,
)
else:
chassis = BoxChassis(
pose=start_pose,
speed=initial_speed,
dimensions=chassis_dims,
bullet_client=sim.bc,
)
vehicle = Vehicle(
id=vehicle_id,
chassis=chassis,
color=vehicle_color,
vehicle_config_type=vehicle_type,
vehicle_class=vehicle_class,
visual_model_filepath=visual_model_filepath,
)
return vehicle | Create a new vehicle and set up sensors and planning information as required by the
ego agent. | _build_agent_vehicle | python | huawei-noah/SMARTS | smarts/core/vehicle_index.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle_index.py | MIT |
def build_agent_vehicle(
self,
sim: SMARTS,
agent_id: str,
agent_interface: AgentInterface,
plan: "plan.Plan",
trainable: bool,
initial_speed: Optional[float] = None,
boid: bool = False,
*,
vehicle_id: Optional[str] = None,
) -> Vehicle:
"""Build an entirely new vehicle for an agent."""
vehicle_definition = self._vehicle_definitions.load_vehicle_definition(
agent_interface.vehicle_class
)
vehicle = VehicleIndex._build_agent_vehicle(
sim=sim,
vehicle_id=vehicle_id or agent_id,
action=agent_interface.action,
vehicle_type=vehicle_definition.get("type"),
vehicle_class=agent_interface.vehicle_class,
mission=plan.mission,
vehicle_dynamics_filepath=vehicle_definition.get("dynamics_model"),
tire_filepath=vehicle_definition.get("tire_params"),
visual_model_filepath=vehicle_definition.get("visual_model"),
trainable=trainable,
surface_patches=sim.scenario.surface_patches,
initial_speed=initial_speed,
)
sensor_state = SensorState(agent_interface.max_episode_steps, plan.frame())
controller_state = ControllerState.from_action_space(
agent_interface.action, vehicle.pose, sim
)
self._enfranchise_agent(
sim,
agent_id,
agent_interface,
vehicle,
controller_state,
sensor_state,
boid,
hijacking=False,
)
return vehicle | Build an entirely new vehicle for an agent. | build_agent_vehicle | python | huawei-noah/SMARTS | smarts/core/vehicle_index.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle_index.py | MIT |
def _build_social_vehicle(
sim: SMARTS, vehicle_id: str, vehicle_state: VehicleState
) -> Vehicle:
"""Create a new unassociated vehicle."""
dims = Dimensions.copy_with_defaults(
vehicle_state.dimensions,
VEHICLE_CONFIGS[vehicle_state.vehicle_config_type].dimensions,
)
chassis = BoxChassis(
pose=vehicle_state.pose,
speed=vehicle_state.speed,
dimensions=dims,
bullet_client=sim.bc,
)
return Vehicle(
id=vehicle_id,
chassis=chassis,
vehicle_config_type=vehicle_state.vehicle_config_type,
visual_model_filepath=None,
) | Create a new unassociated vehicle. | _build_social_vehicle | python | huawei-noah/SMARTS | smarts/core/vehicle_index.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle_index.py | MIT |
def build_social_vehicle(
self,
sim: SMARTS,
vehicle_state: VehicleState,
owner_id: str,
vehicle_id: Optional[str] = None,
) -> Vehicle:
"""Build an entirely new vehicle for a social agent."""
if vehicle_id is None:
vehicle_id = gen_id()
vehicle = VehicleIndex._build_social_vehicle(
sim,
vehicle_id,
vehicle_state,
)
b_vehicle_id, b_owner_id = _2id(vehicle_id), _2id(owner_id) if owner_id else b""
if sim.is_rendering:
vehicle.create_renderer_node(sim.renderer_ref)
sim.renderer.begin_rendering_vehicle(vehicle.id, is_agent=False)
self._vehicles[b_vehicle_id] = vehicle
self._2id_to_id[b_vehicle_id] = vehicle.id
role = vehicle_state.role
assert role not in (
ActorRole.EgoAgent,
ActorRole.SocialAgent,
), f"role={role} from {vehicle_state.source}"
entity = _ControlEntity(
vehicle_id=b_vehicle_id,
owner_id=b_owner_id,
role=role,
shadower_id=b"",
is_boid=False,
is_hijacked=False,
position=np.asarray(vehicle.position),
)
self._controlled_by = np.insert(self._controlled_by, 0, tuple(entity))
return vehicle | Build an entirely new vehicle for a social agent. | build_social_vehicle | python | huawei-noah/SMARTS | smarts/core/vehicle_index.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle_index.py | MIT |
def begin_rendering_vehicles(self, renderer: RendererBase):
"""Render vehicles using the specified renderer."""
agent_vehicle_ids = self.agent_vehicle_ids()
for vehicle in self._vehicles.values():
if vehicle.create_renderer_node(renderer):
is_agent = vehicle.id in agent_vehicle_ids
renderer.begin_rendering_vehicle(vehicle.id, is_agent) | Render vehicles using the specified renderer. | begin_rendering_vehicles | python | huawei-noah/SMARTS | smarts/core/vehicle_index.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle_index.py | MIT |
def controller_state_for_vehicle_id(self, vehicle_id: str) -> ControllerState:
"""Retrieve the controller state of the given vehicle."""
return self._controller_states[_2id(vehicle_id)] | Retrieve the controller state of the given vehicle. | controller_state_for_vehicle_id | python | huawei-noah/SMARTS | smarts/core/vehicle_index.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle_index.py | MIT |
def load_vehicle_definitions_list(self, vehicle_definitions_filepath: str):
"""Loads in a list of vehicle definitions."""
self._vehicle_definitions = resources.load_vehicle_definitions_list(
vehicle_definitions_filepath
) | Loads in a list of vehicle definitions. | load_vehicle_definitions_list | python | huawei-noah/SMARTS | smarts/core/vehicle_index.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/vehicle_index.py | MIT |
def origin(self):
"""The center of the emission point of the lidar lasers."""
return self._origin | The center of the emission point of the lidar lasers. | origin | python | huawei-noah/SMARTS | smarts/core/lidar.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/lidar.py | MIT |
def compute_point_cloud(
self, bullet_client
) -> Tuple[List[np.ndarray], List[int], List[Tuple[np.ndarray, np.ndarray]]]:
"""Generate a point cloud.
Returns:
Point cloud of 3D points, a list of hit objects, a list of rays fired.
"""
rays = self._compute_rays()
point_cloud, hits = self._trace_rays(rays, bullet_client)
# point_cloud = self._apply_noise(point_cloud)
assert (
len(point_cloud) == len(hits) == len(rays) == len(self._static_lidar_noise)
)
return point_cloud, hits, rays | Generate a point cloud.
Returns:
Point cloud of 3D points, a list of hit objects, a list of rays fired. | compute_point_cloud | python | huawei-noah/SMARTS | smarts/core/lidar.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/lidar.py | MIT |
def from_flow(cls, flow: Dict[str, Any], owner: LocalTrafficProvider):
"""Factory to construct a _TrafficActor object from a flow dictionary."""
vclass = flow["vtype"]["vClass"]
dimensions = VEHICLE_CONFIGS[vclass].dimensions
vehicle_type = vclass if vclass != "passenger" else "car"
new_actor = cls(flow, owner)
new_actor._lane, new_actor._offset = new_actor._resolve_flow_pos(
flow, "depart", dimensions
)
position = new_actor._lane.from_lane_coord(RefLinePoint(s=new_actor._offset))
heading = vec_to_radians(
new_actor._lane.vector_at_offset(new_actor._offset)[:2]
)
init_speed = new_actor._resolve_flow_speed(flow)
endless = "-endless" if flow.get("endless", False) else ""
vehicle_id = f"{new_actor._vtype['id']}{endless}-{owner._actors_created}"
new_actor._state = VehicleState(
actor_id=vehicle_id,
actor_type=vehicle_type,
source=owner.source_str,
role=ActorRole.Social,
pose=Pose.from_center(position, Heading(heading)),
dimensions=dimensions,
vehicle_config_type=vclass,
speed=init_speed,
linear_acceleration=np.array((0.0, 0.0, 0.0)),
)
new_actor._dest_lane, new_actor._dest_offset = new_actor._resolve_flow_pos(
flow, "arrival", dimensions
)
return new_actor | Factory to construct a _TrafficActor object from a flow dictionary. | from_flow | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def from_state(
cls,
state: VehicleState,
owner: LocalTrafficProvider,
route: Optional[RouteWithCache],
):
"""Factory to construct a _TrafficActor object from an existing VehiclState object."""
cur_lane = owner.road_map.nearest_lane(state.pose.point)
assert (
cur_lane
), f"LocalTrafficProvider accepted a vehicle that's off road? pos={state.pose.point}"
if not route or not route.roads:
# initialize with a random route, which will probably be replaced
route = owner.road_map.random_route(starting_road=cur_lane.road)
route.add_to_cache()
flow = dict()
flow["vtype"] = dict()
flow["route"] = route
flow["arrivalLane"] = f"{cur_lane.index}" # XXX: assumption!
flow["arrivalPos"] = "max"
flow["departLane"] = f"{cur_lane.index}" # XXX: assumption!
flow["departPos"] = "0"
flow["endless"] = "endless" in state.actor_id
# use default values for everything else in flow dict(s)...
new_actor = _TrafficActor(flow, owner)
new_actor.state = state
new_actor._lane = cur_lane
new_actor._offset = cur_lane.offset_along_lane(state.pose.point)
new_actor._dest_lane, new_actor._dest_offset = new_actor._resolve_flow_pos(
flow, "arrival", state.dimensions
)
return new_actor | Factory to construct a _TrafficActor object from an existing VehiclState object. | from_state | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def state(self) -> VehicleState:
"""Returns the current VehicleState for this actor."""
return self._state | Returns the current VehicleState for this actor. | state | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def state(self, state: VehicleState):
"""Sets the current VehicleState for this actor."""
self._state = state
self.bbox.cache_clear() | Sets the current VehicleState for this actor. | state | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def actor_id(self) -> str:
"""A unique id identifying this actor."""
return self._state.actor_id | A unique id identifying this actor. | actor_id | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def bump_id(self):
"""Changes the id of a teleporting vehicle."""
mm = re.match(r"([^_]+)(_(\d+))?$", self._state.actor_id)
if mm:
ver = int(mm.group(3)) if mm.group(3) else 0
self._state.actor_id = f"{mm.group(1)}_{ver + 1}" | Changes the id of a teleporting vehicle. | bump_id | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def route(self) -> RoadMap.Route:
"""The route this actor will attempt to take."""
return self._route | The route this actor will attempt to take. | route | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def update_route(self, route: RoadMap.Route):
"""Update the route (sequence of road_ids) this actor will attempt to take.
A unique route_key is provided for referencing the route cache in the owner provider.
"""
self._route = route
if isinstance(self._route, RouteWithCache):
self._route.add_to_cache()
self._dest_lane, self._dest_offset = self._resolve_flow_pos(
self._flow, "arrival", self._state.dimensions
)
self._route_ind = 0 | Update the route (sequence of road_ids) this actor will attempt to take.
A unique route_key is provided for referencing the route cache in the owner provider. | update_route | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def stay_put(self):
"""Tells this actor to stop acting and remain where it is indefinitely."""
if not self._stranded:
self._logger.info(f"{self.actor_id} stranded")
self._stranded = True
self._state.speed = 0
self._state.linear_acceleration = None | Tells this actor to stop acting and remain where it is indefinitely. | stay_put | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def finished_route(self) -> bool:
"""Returns True if this vehicle has reached the end of its route."""
return self._done_with_route | Returns True if this vehicle has reached the end of its route. | finished_route | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def off_route(self) -> bool:
"""Returns True if this vehicle has left its route before it got to the end."""
return self._off_route | Returns True if this vehicle has left its route before it got to the end. | off_route | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def wrong_way(self) -> bool:
"""Returns True if this vehicle is currently going the wrong way in its lane."""
return self._wrong_way | Returns True if this vehicle is currently going the wrong way in its lane. | wrong_way | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def teleporting(self) -> bool:
"""Returns True if this vehicle is teleporting back to the beginning of its route on this step."""
return self._teleporting | Returns True if this vehicle is teleporting back to the beginning of its route on this step. | teleporting | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def lane(self) -> RoadMap.Lane:
"""Returns the current Lane object."""
return self._lane | Returns the current Lane object. | lane | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def road(self) -> RoadMap.Road:
"""Returns the current Road object."""
return self._lane.road | Returns the current Road object. | road | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def offset_along_lane(self) -> float:
"""Returns the current offset along the current Lane object."""
return self._offset | Returns the current offset along the current Lane object. | offset_along_lane | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def speed(self) -> float:
"""Returns the current speed."""
return self._state.speed | Returns the current speed. | speed | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def acceleration(self) -> float:
"""Returns the current (linear) acceleration."""
if self._state.linear_acceleration is None:
return 0.0
return np.linalg.norm(self._state.linear_acceleration) | Returns the current (linear) acceleration. | acceleration | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def bbox(self, cushion_length: bool = False) -> Polygon:
"""Returns a bounding box around the vehicle."""
# note: lru_cache must be cleared whenever pose changes
pos = self._state.pose.point
dims = self._state.dimensions
length_buffer = self._min_space_cush if cushion_length else 0
half_len = 0.5 * dims.length + length_buffer
poly = shapely_box(
pos.x - 0.5 * dims.width,
pos.y - half_len,
pos.x + 0.5 * dims.width,
pos.y + half_len,
)
return shapely_rotate(poly, self._state.pose.heading, use_radians=True) | Returns a bounding box around the vehicle. | bbox | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def stopped_at_features(self) -> List[str]:
"""If this vehicle is currently stopped at any features,
returns their feature_ids, otherwise an empty list."""
return list(self._stopped_at_feat.keys()) | If this vehicle is currently stopped at any features,
returns their feature_ids, otherwise an empty list. | stopped_at_features | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def drive_time(self) -> float:
"""The amount of time this vehicle might drive in the
target lane under present conditions."""
return min(self.ttc, self.adj_time_left) | The amount of time this vehicle might drive in the
target lane under present conditions. | drive_time | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def width(self) -> float:
"""The width of this lane at its lane_coord."""
return self.lane.width_at_offset(self.lane_coord.s)[0] | The width of this lane at its lane_coord. | width | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def radius(self) -> float:
"""The radius of curvature of this lane at its lane_coord."""
# we round the offset in an attempt to reduce the unique hits on the LRU caches...
rounded_offset = round(self.lane_coord.s)
return self.lane.curvature_radius_at_offset(
rounded_offset, lookahead=max(math.ceil(2 * self.width), 2)
) | The radius of curvature of this lane at its lane_coord. | radius | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def crossing_time_at_speed(
self, to_index: int, speed: float, acc: float = 0.0
) -> float:
"""Returns how long it would take to cross from this lane to
the lane indexed by to_index given our current speed and acceleration."""
angle_scale = self._angle_scale(to_index)
return time_to_cover(angle_scale * self.width, speed, acc) | Returns how long it would take to cross from this lane to
the lane indexed by to_index given our current speed and acceleration. | crossing_time_at_speed | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def exit_time(self, speed: float, to_index: int, acc: float = 0.0) -> float:
"""Returns how long it would take to drive into the to_index lane
from this lane given our current speed and acceleration."""
ct = self.crossing_time_at_speed(to_index, speed, acc)
t = self.lane_coord.t
pm = (-1 if to_index >= self.lane.index else 1) * np.sign(t)
angle_scale = self._angle_scale(to_index)
return 0.5 * ct + pm * time_to_cover(angle_scale * abs(t), speed, acc) | Returns how long it would take to drive into the to_index lane
from this lane given our current speed and acceleration. | exit_time | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def add_to_win(
self,
veh_id: str,
bumper: int,
fv_pos: np.ndarray,
my_pos: np.ndarray,
my_heading: float,
dt: float,
) -> Tuple[float, float]:
"""Add a relative observation of veh_id over the last dt secs."""
bvec = fv_pos - my_pos
fv_range = np.linalg.norm(bvec)
rel_bearing = min_angles_difference_signed(vec_to_radians(bvec), my_heading)
fv_win = self._junction_foes.setdefault(
(veh_id, bumper), deque(maxlen=self._width)
)
fv_win.append(self._RelativeVehInfo(fv_range, rel_bearing, my_heading, dt))
return rel_bearing, fv_range | Add a relative observation of veh_id over the last dt secs. | add_to_win | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def predict_crash_in(self, veh_id: str, bumper: int) -> float:
"""Estimate if and when I might collide with veh_id using
the constant bearing, decreasing range (CBDR) techique, but
attempting to correct for non-linearities."""
# CBDR is a good approximation at distance over time with
# both vehicles behaving "steadily" (ideally, driving
# straight at a constant speed). It breaks down, thankfully
# in preictable ways, if these assumptions are violated.
#
# Range Dependency:
# As range gets small, bearing can fluctuate more, but will also
# tend to start to change steadily when on a collision course.
# To overcome this here, we just make our "CB" computation
# depend on range.
#
# When range is on the order of car length(s), the following might eventually
# help with evasive maneuvers:
# - for side impacts to me, the absolute value of the rel_bearing from my front bumper
# will increase monotonically (and rapidly) just before impact, meanwhile the value
# from my back bumper will decrease analogously.
# - for side impacts to them, the rel_bearing to their front bumper from mine will change
# signs just before impact, while abs(rel_bearing) to their back bumper will dramatically
# reduce.
#
# Heading Changes:
# - If we turn, we need to consider how this will change rel_bearing from our perspective.
# Adding to the heading will increase apparent rel_bearing, but this instaneous change
# should not count against CBDR, so we correct for it here.
# - If they turn, we don't need to do anything (CBDR as implemented here still works
# to predict collisions).
#
# (Relative) Acceleration:
# - if there is a difference in our accelerations, rel_bearing for a collision course
# will change quadratically in a complicated way. We don't try to mitigate this.
window = self._junction_foes[(veh_id, bumper)]
if len(window) <= 1:
return math.inf
prev_range, prev_bearing, prev_heading = None, None, None
range_del = 0.0
bearing_del = 0.0
for rvi in window:
if prev_range is not None:
range_del += (rvi.dist - prev_range) / rvi.dt
if prev_bearing is not None:
bearing_del += (
min_angles_difference_signed(rvi.bearing, prev_bearing)
+ min_angles_difference_signed(rvi.heading, prev_heading)
) / rvi.dt
prev_range = rvi.dist
prev_bearing = rvi.bearing
prev_heading = rvi.heading
range_del /= len(window) - 1
bearing_del /= len(window) - 1
final_range = window[-1].dist
# the exponent here was determined by trial and error
if range_del < 0 and abs(bearing_del) < safe_division(
math.pi, final_range**1.4
):
return safe_division(-final_range, range_del)
return math.inf | Estimate if and when I might collide with veh_id using
the constant bearing, decreasing range (CBDR) techique, but
attempting to correct for non-linearities. | predict_crash_in | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def purge_unseen(self, seen: Set[str]):
"""Remove unseen vehicle IDs from this cache."""
self._junction_foes = {
(sv, bumper): self._junction_foes[(sv, bumper)]
for sv in seen
for bumper in (False, True)
if (sv, bumper) in self._junction_foes
} | Remove unseen vehicle IDs from this cache. | purge_unseen | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def compute_next_state(self, dt: float):
"""Pre-computes the next state for this traffic actor."""
self._compute_lane_speeds()
if math.isclose(self.speed, 0, abs_tol=1.5):
self._current_impatience = min(
MAX_IMPATIENCE, self._current_impatience + dt / self._time_to_impatience
)
else:
self._current_impatience = max(
0, self._current_impatience - dt / self._time_to_impatience
)
self._pick_lane(dt)
self._check_speed(dt)
angular_velocity = self._angle_to_lane(dt)
acceleration = self._compute_acceleration(dt)
target_heading = self._state.pose.heading + angular_velocity * dt
target_heading %= 2 * math.pi
heading_vec = radians_to_vec(target_heading)
self._next_linear_acceleration = dt * acceleration * heading_vec
self._next_speed = self._state.speed + acceleration * dt
if self._next_speed < 0:
# don't go backwards
self._next_speed = 0
dpos = heading_vec * self.speed * dt
target_pos = self._state.pose.position + np.append(dpos, 0.0)
self._next_pose = Pose.from_center(target_pos, Heading(target_heading)) | Pre-computes the next state for this traffic actor. | compute_next_state | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def step(self, dt: float):
"""Updates to the pre-computed next state for this traffic actor."""
if self._stranded:
return
self._teleporting = False
self._state.pose = self._next_pose
self._state.speed = self._next_speed
self._state.linear_acceleration = self._next_linear_acceleration
self._state.updated = False
prev_road_id = self._lane.road.road_id
self.bbox.cache_clear()
# if there's more than one lane near us (like in a junction) pick closest one that's in our route
owner = self._owner()
assert owner
nls = owner.road_map.nearest_lanes(
self._next_pose.point,
radius=self._state.dimensions.length,
include_junctions=True,
)
if not nls:
self._logger.warning(
f"actor {self.actor_id} out-of-lane: {self._next_pose}"
)
self._off_route = True
if self._flow["endless"]:
self._reroute()
return
self._lane = None
best_ri_delta = None
next_route_ind = None
for nl, d in nls:
try:
next_route_ind = self._route.road_ids.index(
nl.road.road_id, self._route_ind
)
self._off_route = False
ri_delta = next_route_ind - self._route_ind
if ri_delta <= 1:
self._lane = nl
best_ri_delta = ri_delta
break
if best_ri_delta is None or ri_delta < best_ri_delta:
self._lane = nl
best_ri_delta = ri_delta
except ValueError:
pass
if not self._lane:
self._off_route = True
self._lane = nls[0][0]
self._logger.info(
f"actor {self.actor_id} is off of its route. now in lane {self._lane.lane_id}."
)
road_id = self._lane.road.road_id
if road_id != prev_road_id:
self._route_ind += 1 if best_ri_delta is None else best_ri_delta
self._offset = self._lane.offset_along_lane(self._next_pose.point)
if self._near_dest():
if self._lane == self._dest_lane:
if self._flow["endless"]:
self._reroute()
else:
self._done_with_route = True
else:
self._off_route = True
self._logger.info(
f"actor {self.actor_id} is beyond end of route in wrong lane ({self._lane.lane_id} instead of {self._dest_lane.lane_id})."
) | Updates to the pre-computed next state for this traffic actor. | step | python | huawei-noah/SMARTS | smarts/core/local_traffic_provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/local_traffic_provider.py | MIT |
def find_mapfile_in_dir(map_dir: str) -> Tuple[MapType, str]:
"""Looks in a given directory for a supported map file."""
map_filename_type = {
"map.net.xml": MapType.Sumo,
"shifted_map-AUTOGEN.net.xml": MapType.Sumo,
"map.xodr": MapType.Opendrive,
}
map_type = MapType.Unknown
map_path = map_dir
for f in os.listdir(map_dir):
cand_map_type = map_filename_type.get(f)
if cand_map_type is not None:
return cand_map_type, os.path.join(map_dir, f)
if f.endswith(".net.xml"):
map_type = MapType.Sumo
map_path = os.path.join(map_dir, f)
elif f.endswith(".xodr"):
map_type = MapType.Opendrive
elif ".tfrecord" in f:
map_type = MapType.Waymo
map_path = os.path.join(map_dir, f)
elif "log_map_archive" in f:
map_type = MapType.Argoverse
map_path = os.path.join(map_dir, f)
return map_type, map_path | Looks in a given directory for a supported map file. | find_mapfile_in_dir | python | huawei-noah/SMARTS | smarts/core/default_map_builder.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/default_map_builder.py | MIT |
def get_road_map(map_spec) -> Tuple[Optional[RoadMap], Optional[str]]:
"""@return a RoadMap object and a hash
that uniquely identifies it. Changes to the hash
should signify that the map is different enough
that map-related caches should be reloaded.
If possible, the RoadMap object may be cached here
and re-used.
"""
assert map_spec, "A road map spec must be specified"
assert map_spec.source, "A road map source must be specified"
if os.path.isdir(map_spec.source):
map_type, map_source = find_mapfile_in_dir(map_spec.source)
else:
map_type = MapType.Unknown
map_source = map_spec.source
if map_source.endswith(".net.xml"):
map_type = MapType.Sumo
elif map_source.endswith(".xodr"):
map_type = MapType.Opendrive
elif ".tfrecord" in map_source:
map_type = MapType.Waymo
if map_type == MapType.Sumo:
from smarts.core.sumo_road_network import SumoRoadNetwork
map_class = SumoRoadNetwork
elif map_type == MapType.Opendrive:
from smarts.core.utils.custom_exceptions import OpenDriveException
try:
from smarts.core.opendrive_road_network import OpenDriveRoadNetwork
except ImportError:
raise OpenDriveException.required_to("use OpenDRIVE maps")
map_class = OpenDriveRoadNetwork
elif map_type == MapType.Waymo:
from smarts.core.waymo_map import WaymoMap
map_class = WaymoMap
elif map_type == MapType.Argoverse:
try:
from smarts.core.argoverse_map import (
ArgoverseMap, # pytype: disable=import-error
)
except (ImportError, ModuleNotFoundError):
print(sys.exc_info())
print(
"Missing dependencies for Argoverse. Install them using the command `pip install -e .[argoverse]` at the source directory."
)
return None, None
map_class = ArgoverseMap
else:
warnings.warn(
f"A map source for road surface generation can not be resolved from the given reference: `{map_spec.source}`.",
category=UserWarning,
)
return None, None
if _existing_map:
if isinstance(_existing_map.obj, map_class) and _existing_map.obj.is_same_map(
map_spec
):
return _existing_map.obj, _existing_map.map_hash
_clear_cache()
road_map = map_class.from_spec(map_spec)
if road_map is None:
return None, None
if os.path.isfile(road_map.source):
road_map_hash = file_md5_hash(road_map.source)
else:
road_map_hash = path2hash(road_map.source)
_cache_result(map_spec, road_map, road_map_hash)
return road_map, road_map_hash | @return a RoadMap object and a hash
that uniquely identifies it. Changes to the hash
should signify that the map is different enough
that map-related caches should be reloaded.
If possible, the RoadMap object may be cached here
and re-used. | get_road_map | python | huawei-noah/SMARTS | smarts/core/default_map_builder.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/default_map_builder.py | MIT |
def exclusion_prefixes(self):
"""The blacklist of actor prefixes, used to ignore specific actors."""
return self._exclusion_prefixes | The blacklist of actor prefixes, used to ignore specific actors. | exclusion_prefixes | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def id(self):
"""The id of the underlying bubble."""
return self._bubble.id | The id of the underlying bubble. | id | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def actor(self) -> Union[SocialAgentActor, TrafficEngineActor]:
"""The actor that should replace the captured actor."""
return self._bubble.actor | The actor that should replace the captured actor. | actor | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def follow_actor_id(self) -> str:
"""A target actor that the bubble should remain at a fixed offset from."""
return self._bubble.follow_actor_id | A target actor that the bubble should remain at a fixed offset from. | follow_actor_id | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def follow_vehicle_id(self) -> str:
"""A target vehicle that the bubble should remain at a fixed offset from."""
return self._bubble.follow_vehicle_id | A target vehicle that the bubble should remain at a fixed offset from. | follow_vehicle_id | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def limit(self):
"""The maximum number of actors that the bubble can have captured at the same time."""
return self._limit | The maximum number of actors that the bubble can have captured at the same time. | limit | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def is_boid(self):
"""If the actors captured by the bubble should be controlled by a boid agent."""
return self._bubble.is_boid | If the actors captured by the bubble should be controlled by a boid agent. | is_boid | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def keep_alive(self):
"""If enabled, the social agent actor will be spawned upon first vehicle airlock
and be reused for every subsequent vehicle entering the bubble until the episode
is over.
"""
return self._bubble.keep_alive | If enabled, the social agent actor will be spawned upon first vehicle airlock
and be reused for every subsequent vehicle entering the bubble until the episode
is over. | keep_alive | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def airlock_condition(self) -> Condition:
"""Conditions under which this bubble will accept an agent."""
return self._airlock_condition | Conditions under which this bubble will accept an agent. | airlock_condition | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def active_condition(self) -> Condition:
"""Fast inclusions for the bubble."""
return self._active_condition | Fast inclusions for the bubble. | active_condition | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def geometry(self) -> Polygon:
"""The geometry of the managed bubble."""
return self._cached_inner_geometry | The geometry of the managed bubble. | geometry | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def airlock_geometry(self) -> Polygon:
"""The airlock geometry of the managed bubble."""
return self._cached_airlock_geometry | The airlock geometry of the managed bubble. | airlock_geometry | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def condition_passes(
self,
active_condition_requirements,
):
"""If the broadphase condition allows for this"""
return ConditionState.TRUE in self.active_condition.evaluate(
**active_condition_requirements
) | If the broadphase condition allows for this | condition_passes | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def admissibility(
self,
vehicle_id: str,
index: VehicleIndex,
vehicle_ids_in_bubbles: Dict["Bubble", Set[str]],
running_cursors: Set["Cursor"],
):
"""The vehicle_id we are querying for and the `other_vehicle_ids` _presently in
this :class:`~smarts.sstudio.sstypes.bubble.Bubble`.
"""
for prefix in self.exclusion_prefixes:
if vehicle_id.startswith(prefix):
return False, False
hijackable, shadowable = True, True
if self._limit is not None:
# Already hijacked (according to VehicleIndex) + to be hijacked (running cursors)
current_hijacked_vehicle_ids = {
v_id
for v_id in vehicle_ids_in_bubbles[self]
if index.vehicle_is_hijacked(v_id)
}
current_shadowed_vehicle_ids = {
v_id
for v_id in vehicle_ids_in_bubbles[self]
if index.vehicle_is_shadowed(v_id)
}
vehicle_ids_by_bubble_state = (
BubbleManager._vehicle_ids_divided_by_bubble_state(
frozenset(running_cursors)
)
)
all_hijacked_vehicle_ids = (
current_hijacked_vehicle_ids
| vehicle_ids_by_bubble_state[BubbleRelationState.InAirlock][self]
) - {vehicle_id}
all_shadowed_vehicle_ids = (
current_shadowed_vehicle_ids
| vehicle_ids_by_bubble_state[BubbleRelationState.InBubble][self]
) - {vehicle_id}
hijackable = len(all_hijacked_vehicle_ids) < (
self._limit.hijack_limit or maxsize
)
shadowable = len(all_shadowed_vehicle_ids) + len(
all_hijacked_vehicle_ids
) < (self._limit.shadow_limit or maxsize)
return hijackable, shadowable | The vehicle_id we are querying for and the `other_vehicle_ids` _presently in
this :class:`~smarts.sstudio.sstypes.bubble.Bubble`. | admissibility | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def in_bubble_or_airlock_zone(self, position: Point):
"""Test if the position is within the bubble or airlock around the bubble."""
if not isinstance(position, Point):
position = Point(position)
in_airlock = position.within(self._cached_airlock_geometry)
if not in_airlock:
return False, False
in_bubble = position.within(self._cached_inner_geometry)
return in_bubble, in_airlock and not in_bubble | Test if the position is within the bubble or airlock around the bubble. | in_bubble_or_airlock_zone | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def is_traveling(self):
"""If the bubble is following an actor."""
return (
self._bubble.follow_actor_id is not None
or self._bubble.follow_vehicle_id is not None
) | If the bubble is following an actor. | is_traveling | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def move_to_follow_vehicle(self, vehicle: Vehicle):
"""Move the bubble to a pose relative to the given vehicle."""
if not vehicle.valid:
return
x, y, _ = vehicle.position
def _transform(geom):
centroid = geom.centroid
# Bring back to origin
geom = translate(geom, xoff=-centroid.x, yoff=-centroid.y)
geom = rotate(geom, -self._bubble_heading, "centroid", use_radians=True)
# Now apply new transformation in "vehicle coordinate space"
geom = translate(
geom,
xoff=self._bubble.follow_offset[0],
yoff=self._bubble.follow_offset[1],
)
geom = rotate(geom, vehicle.heading, (0, 0), use_radians=True)
geom = translate(geom, xoff=x, yoff=y)
return geom
self._cached_inner_geometry = _transform(self._cached_inner_geometry)
self._cached_airlock_geometry = _transform(self._cached_airlock_geometry)
self.centroid = [
self._cached_inner_geometry.centroid.x,
self._cached_inner_geometry.centroid.y,
]
self._bubble_heading = vehicle.heading | Move the bubble to a pose relative to the given vehicle. | move_to_follow_vehicle | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def for_removed(
vehicle_id: str,
bubble: Bubble,
index: VehicleIndex,
vehicle_ids_per_bubble: Dict[Bubble, Set[str]],
) -> "Cursor":
"""Generate a cursor for an inactive bubble.
Args:
vehicle (Vehicle):
The vehicle that is to be tracked.
bubble (Bubble):
The bubble that the vehicle is interacting with.
index (VehicleIndex):
The vehicle index the vehicle is in.
vehicle_ids_per_bubble (Dict[Bubble, Set[str]]):
Bubbles associated with vehicle ids.
running_cursors (Set["Cursor"]):
A set of existing cursors.
"""
was_in_this_bubble = vehicle_id in vehicle_ids_per_bubble[bubble]
is_hijacked, is_shadowed = index.vehicle_is_hijacked_or_shadowed(vehicle_id)
transition = None
if was_in_this_bubble and (is_shadowed or is_hijacked):
transition = BubbleTransition.AirlockExited
return Cursor(
vehicle_id=vehicle_id,
transition=transition,
state=BubbleRelationState.WasInBubble,
capture=BubbleCaptureState.Uncaptured,
bubble=bubble,
) | Generate a cursor for an inactive bubble.
Args:
vehicle (Vehicle):
The vehicle that is to be tracked.
bubble (Bubble):
The bubble that the vehicle is interacting with.
index (VehicleIndex):
The vehicle index the vehicle is in.
vehicle_ids_per_bubble (Dict[Bubble, Set[str]]):
Bubbles associated with vehicle ids.
running_cursors (Set["Cursor"]):
A set of existing cursors. | for_removed | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def from_pos(
position: Point,
vehicle_id: str,
bubble: Bubble,
index: VehicleIndex,
vehicle_ids_per_bubble: Dict[Bubble, Set[str]],
running_cursors: Set["Cursor"],
previous_cursor: Optional["Cursor"],
is_hijack_admissible,
is_airlock_admissible,
) -> "Cursor":
"""Generate a cursor.
Args:
position (Point):
The shapely position of the vehicle.
vehicle (Vehicle):
The vehicle that is to be tracked.
bubble (Bubble):
The bubble that the vehicle is interacting with.
index (VehicleIndex):
The vehicle index the vehicle is in.
vehicle_ids_per_bubble (Dict[Bubble, Set[str]]):
Bubbles associated with vehicle ids.
running_cursors (Set["Cursor"]):
A set of existing cursors.
"""
in_bubble_zone, in_airlock_zone = bubble.in_bubble_or_airlock_zone(position)
is_social = vehicle_id in index.social_vehicle_ids()
was_in_this_bubble = vehicle_id in vehicle_ids_per_bubble[bubble]
previous_capture = (
previous_cursor.capture
if previous_cursor is not None
else BubbleCaptureState.Uncaptured
)
# XXX: When a traveling bubble disappears and an agent is airlocked or
# hijacked. It remains in that state.
# TODO: Depending on step size, we could potentially skip transitions (e.g.
# go straight to relinquish w/o hijacking first). This may be solved by
# time-based airlocking. For robust code we'll want to handle these
# scenarios (e.g. hijacking if didn't airlock first)
transition = None
capture = previous_capture
if (
is_social
and previous_capture is BubbleCaptureState.Uncaptured
and is_airlock_admissible
and (in_airlock_zone or in_bubble_zone)
):
# In this case a vehicle has just entered the airlock
transition = BubbleTransition.AirlockEntered
capture = BubbleCaptureState.Captured
elif (
previous_capture is BubbleCaptureState.Captured
and is_hijack_admissible
and in_bubble_zone
):
# In this case a vehicle has just entered the bubble
transition = BubbleTransition.Entered
capture = BubbleCaptureState.Controlled
elif (
was_in_this_bubble
and previous_capture is BubbleCaptureState.Controlled
and in_airlock_zone
):
# XXX: This may get called repeatedly because we don't actually change
# any state when this happens.
# In this case a vehicle has just exited the bubble
transition = BubbleTransition.Exited
elif (
was_in_this_bubble
and previous_capture
in {BubbleCaptureState.Controlled, BubbleCaptureState.Captured}
and not (in_airlock_zone or in_bubble_zone)
):
# In this case a vehicle has just exited the airlock around the bubble
transition = BubbleTransition.AirlockExited
capture = BubbleCaptureState.Uncaptured
state = None
if in_bubble_zone:
state = BubbleRelationState.InBubble
elif in_airlock_zone:
state = BubbleRelationState.InAirlock
return Cursor(
vehicle_id=vehicle_id,
transition=transition,
capture=capture,
state=state,
bubble=bubble,
) | Generate a cursor.
Args:
position (Point):
The shapely position of the vehicle.
vehicle (Vehicle):
The vehicle that is to be tracked.
bubble (Bubble):
The bubble that the vehicle is interacting with.
index (VehicleIndex):
The vehicle index the vehicle is in.
vehicle_ids_per_bubble (Dict[Bubble, Set[str]]):
Bubbles associated with vehicle ids.
running_cursors (Set["Cursor"]):
A set of existing cursors. | from_pos | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def active_bubbles(self) -> Sequence[Bubble]:
"""A sequence of currently active bubbles."""
return self._active_bubbles | A sequence of currently active bubbles. | active_bubbles | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def vehicle_ids_per_bubble(
self,
) -> Dict[Bubble, Set[str]]:
"""Bubbles associated with the vehicles they contain."""
vid = self._vehicle_ids_divided_by_bubble_state(frozenset(self._cursors))
return defaultdict(
set,
{**vid[BubbleRelationState.InBubble], **vid[BubbleRelationState.InAirlock]},
) | Bubbles associated with the vehicles they contain. | vehicle_ids_per_bubble | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def agent_ids_for_bubble(self, bubble: Bubble, sim) -> Set[str]:
"""Agents generated by this bubble."""
bubble_cursors = set(filter(lambda c: c.bubble == bubble, self._cursors))
agent_ids = set()
for bc in bubble_cursors:
if bc.state != BubbleRelationState.InBubble:
continue
agent_id = sim.vehicle_index.owner_id_from_vehicle_id(bc.vehicle_id)
if agent_id is not None:
agent_ids.add(agent_id)
return agent_ids | Agents generated by this bubble. | agent_ids_for_bubble | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def step(self, sim):
"""Update the associations between bubbles, actors, and agents"""
self._active_bubbles, _ = self._bubble_groups(sim)
self._move_traveling_bubbles(sim)
self._cursors = self._sync_cursors(
self._last_vehicle_index, sim.vehicle_index, sim
)
self._handle_transitions(sim, self._cursors)
self._last_vehicle_index = deepcopy(sim.vehicle_index) | Update the associations between bubbles, actors, and agents | step | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def _airlock_social_vehicle_with_social_agent(
self,
sim,
vehicle_id: str,
social_agent_actor: SocialAgentActor,
is_boid: bool,
keep_alive: bool,
):
"""When airlocked. The social agent will receive observations and execute
its policy, however it won't actually operate the vehicle's controller.
"""
assert isinstance(
social_agent_actor, SocialAgentActor
), "This must be a social agent actor type."
self._log.debug(
f"Airlocked vehicle={vehicle_id} with actor={social_agent_actor}"
)
if is_boid:
agent_id = BubbleManager._make_boid_social_agent_id(social_agent_actor)
else:
agent_id = BubbleManager._make_social_agent_id(vehicle_id)
social_agent = None
if is_boid and keep_alive or agent_id in sim.agent_manager.social_agent_ids:
# E.g. if agent is a boid and was being re-used
interface = sim.agent_manager.agent_interface_for_agent_id(agent_id)
else:
social_agent = make_social_agent(
locator=social_agent_actor.agent_locator,
**social_agent_actor.policy_kwargs,
)
interface = social_agent.interface
self._prepare_sensors_for_agent_control(
sim, vehicle_id, agent_id, interface, is_boid=is_boid
)
if social_agent is None:
return
self._start_social_agent(
sim,
agent_id,
social_agent,
social_agent_actor,
is_boid=is_boid,
keep_alive=keep_alive,
) | When airlocked. The social agent will receive observations and execute
its policy, however it won't actually operate the vehicle's controller. | _airlock_social_vehicle_with_social_agent | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def _hijack_social_vehicle_with_social_agent(
self, sim, vehicle_id: str, social_agent_actor: SocialAgentActor, is_boid: bool
):
"""Upon hijacking the social agent is now in control of the vehicle. It will
initialize the vehicle chassis (and by extension the controller) with a
"greatest common denominator" state; that is: what's available via the vehicle
front-end common to both source and destination policies during airlock.
"""
assert isinstance(
social_agent_actor, SocialAgentActor
), "This must be a social agent actor type."
self._log.debug(f"Hijack vehicle={vehicle_id} with actor={social_agent_actor}")
if is_boid:
agent_id = BubbleManager._make_boid_social_agent_id(social_agent_actor)
else:
agent_id = BubbleManager._make_social_agent_id(vehicle_id)
agent_interface = sim.agent_manager.agent_interface_for_agent_id(agent_id)
vehicle = sim.vehicle_index.switch_control_to_agent(
sim,
vehicle_id,
agent_id,
boid=is_boid,
hijacking=True,
recreate=False,
agent_interface=agent_interface,
)
if vehicle:
sim.create_vehicle_in_providers(vehicle, agent_id) | Upon hijacking the social agent is now in control of the vehicle. It will
initialize the vehicle chassis (and by extension the controller) with a
"greatest common denominator" state; that is: what's available via the vehicle
front-end common to both source and destination policies during airlock. | _hijack_social_vehicle_with_social_agent | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def teardown(self):
"""Clean up internal state."""
self._cursors = set()
self._bubbles = [] | Clean up internal state. | teardown | python | huawei-noah/SMARTS | smarts/core/bubble_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/bubble_manager.py | MIT |
def sorted_keys(self) -> List[int]:
"""@return the keys in ascending order; only to be used after dict contents are final"""
# if we want to add another dependency, it would probably be better to use SortedDict...
return sorted(self.keys()) | @return the keys in ascending order; only to be used after dict contents are final | sorted_keys | python | huawei-noah/SMARTS | smarts/core/waymo_map.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/waymo_map.py | MIT |
def accum(self, pt: np.ndarray) -> float:
"""@return accumulated distance so far"""
if self._last_pt is not None:
self._d += np.linalg.norm(pt - self._last_pt)
self._last_pt = pt
return self._d | @return accumulated distance so far | _polyline_dists.accum | python | huawei-noah/SMARTS | smarts/core/waymo_map.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/waymo_map.py | MIT |
def _polyline_dists(polyline) -> Tuple[np.ndarray, np.ndarray]:
lane_pts = np.array([WaymoMap._map_pt_to_point(p) for p in polyline])
class _Accum:
def __init__(self):
self._d = 0.0
self._last_pt = None
def accum(self, pt: np.ndarray) -> float:
"""@return accumulated distance so far"""
if self._last_pt is not None:
self._d += np.linalg.norm(pt - self._last_pt)
self._last_pt = pt
return self._d
q = _Accum()
dists = np.array([q.accum(pt) for pt in lane_pts])
return lane_pts, dists | @return accumulated distance so far | _polyline_dists | python | huawei-noah/SMARTS | smarts/core/waymo_map.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/waymo_map.py | MIT |
def parse_source_to_scenario(source: str):
"""Read the dataset file and get the specified scenario"""
dataset_path = source.split("#")[0]
scenario_id = source.split("#")[1]
# Reset cache if this is a new TFRecord file
if not WaymoMap._tfrecord_path or WaymoMap._tfrecord_path != dataset_path:
WaymoMap._tfrecord_path = dataset_path
WaymoMap._tfrecord_generator = read_tfrecord_file(dataset_path)
WaymoMap._scenario_cache = dict()
parsed_scenario = WaymoMap._scenario_cache.get(scenario_id)
if parsed_scenario:
return parsed_scenario
while True:
record = next(WaymoMap._tfrecord_generator, None)
if not record:
raise ValueError(
f"Dataset file does not contain scenario with id: {scenario_id}"
)
parsed_scenario = scenario_pb2.Scenario()
parsed_scenario.ParseFromString(bytes(record))
WaymoMap._scenario_cache[parsed_scenario.scenario_id] = parsed_scenario
if parsed_scenario.scenario_id == scenario_id:
return parsed_scenario | Read the dataset file and get the specified scenario | parse_source_to_scenario | python | huawei-noah/SMARTS | smarts/core/waymo_map.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/waymo_map.py | MIT |
def from_spec(cls, map_spec: MapSpec):
"""Generate a road network from the given specification."""
if len(map_spec.source.split("#")) != 2:
return None
waymo_scenario = cls.parse_source_to_scenario(map_spec.source)
assert waymo_scenario
return cls(map_spec, waymo_scenario) | Generate a road network from the given specification. | from_spec | python | huawei-noah/SMARTS | smarts/core/waymo_map.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/waymo_map.py | MIT |
def to_glb(self, glb_dir):
"""Build a `.glb` file for camera rendering and envision."""
polygons = []
for lane_id, lane in self._lanes.items():
metadata = {
"road_id": lane.road.road_id,
"lane_id": lane_id,
"lane_index": lane.index,
}
polygons.append((lane.shape(), metadata))
lane_dividers = self._compute_traffic_dividers()
map_glb = make_map_glb(polygons, self.bounding_box, lane_dividers, [])
map_glb.write_glb(Path(glb_dir) / "map.glb")
lane_lines_glb = make_road_line_glb(lane_dividers)
lane_lines_glb.write_glb(Path(glb_dir) / "lane_lines.glb") | Build a `.glb` file for camera rendering and envision. | to_glb | python | huawei-noah/SMARTS | smarts/core/waymo_map.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/waymo_map.py | MIT |
def update(
self,
lookahead: int,
point: Point,
filter_road_ids: tuple,
llp,
paths: List[List[Waypoint]],
):
"""Update the current cache if not already cached."""
if not self._match(lookahead, point, filter_road_ids):
self.lookahead = lookahead
self.point = point
self.filter_road_ids = filter_road_ids
self._starts = {}
self._starts[llp.lp.lane.index] = paths | Update the current cache if not already cached. | update | python | huawei-noah/SMARTS | smarts/core/waymo_map.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/waymo_map.py | MIT |
def query(
self,
lookahead: int,
point: Point,
filter_road_ids: tuple,
llp,
) -> Optional[List[List[Waypoint]]]:
"""Attempt to find previously cached waypoints"""
if self._match(lookahead, point, filter_road_ids):
hit = self._starts.get(llp.lp.lane.index, None)
if hit:
# consider just returning all of them (not slicing)?
return [path[: (lookahead + 1)] for path in hit]
return None | Attempt to find previously cached waypoints | query | python | huawei-noah/SMARTS | smarts/core/waymo_map.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/waymo_map.py | MIT |
def _waypoint_paths_along_route(
self, point: Point, lookahead: int, route: Sequence[str]
) -> List[List[Waypoint]]:
"""finds the closest lane to vehicle's position that is on its route,
then gets waypoint paths from all lanes in its road there."""
assert len(route) > 0, f"Expected at least 1 road in the route, got: {route}"
closest_llp_on_each_route_road = [
self._lanepoints.closest_linked_lanepoint_on_road(point, road)
for road in route
]
closest_linked_lp = min(
closest_llp_on_each_route_road,
key=lambda l_lp: np.linalg.norm(
vec_2d(l_lp.lp.pose.position) - vec_2d(point)
),
)
closest_lane = closest_linked_lp.lp.lane
waypoint_paths = []
for lane in closest_lane.road.lanes:
waypoint_paths += lane._waypoint_paths_at(point, lookahead, route)
return sorted(waypoint_paths, key=len, reverse=True) | finds the closest lane to vehicle's position that is on its route,
then gets waypoint paths from all lanes in its road there. | _waypoint_paths_along_route | python | huawei-noah/SMARTS | smarts/core/waymo_map.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/waymo_map.py | MIT |
def _equally_spaced_path(
path: Sequence[LinkedLanePoint],
point: Point,
lp_spacing: float,
) -> List[Waypoint]:
"""given a list of LanePoints starting near point, return corresponding
Waypoints that may not be evenly spaced (due to lane change) but start at point.
"""
continuous_variables = [
"positions_x",
"positions_y",
"headings",
"lane_width",
"speed_limit",
"lane_offset",
]
discrete_variables = ["lane_id", "lane_index"]
ref_lanepoints_coordinates = {
parameter: [] for parameter in (continuous_variables + discrete_variables)
}
for idx, lanepoint in enumerate(path):
if lanepoint.is_inferred and 0 < idx < len(path) - 1:
continue
ref_lanepoints_coordinates["positions_x"].append(
lanepoint.lp.pose.position[0]
)
ref_lanepoints_coordinates["positions_y"].append(
lanepoint.lp.pose.position[1]
)
ref_lanepoints_coordinates["headings"].append(
lanepoint.lp.pose.heading.as_bullet
)
ref_lanepoints_coordinates["lane_id"].append(lanepoint.lp.lane.lane_id)
ref_lanepoints_coordinates["lane_index"].append(lanepoint.lp.lane.index)
ref_lanepoints_coordinates["lane_width"].append(lanepoint.lp.lane_width)
ref_lanepoints_coordinates["lane_offset"].append(
lanepoint.lp.lane.offset_along_lane(lanepoint.lp.pose.point)
)
ref_lanepoints_coordinates["speed_limit"].append(
lanepoint.lp.lane.speed_limit
)
ref_lanepoints_coordinates["headings"] = inplace_unwrap(
ref_lanepoints_coordinates["headings"]
)
first_lp_heading = ref_lanepoints_coordinates["headings"][0]
lp_position = path[0].lp.pose.point.as_np_array[:2]
vehicle_pos = point.as_np_array[:2]
heading_vec = radians_to_vec(first_lp_heading)
projected_distant_lp_vehicle = np.inner(
(vehicle_pos - lp_position), heading_vec
)
ref_lanepoints_coordinates["positions_x"][0] = (
lp_position[0] + projected_distant_lp_vehicle * heading_vec[0]
)
ref_lanepoints_coordinates["positions_y"][0] = (
lp_position[1] + projected_distant_lp_vehicle * heading_vec[1]
)
cumulative_path_dist = np.cumsum(
np.sqrt(
np.ediff1d(ref_lanepoints_coordinates["positions_x"], to_begin=0) ** 2
+ np.ediff1d(ref_lanepoints_coordinates["positions_y"], to_begin=0) ** 2
)
)
if len(cumulative_path_dist) <= lp_spacing:
lp = path[0].lp
return [
Waypoint(
pos=lp.pose.position[:2],
heading=lp.pose.heading,
lane_width=lp.lane.width_at_offset(0)[0],
speed_limit=lp.lane.speed_limit,
lane_id=lp.lane.lane_id,
lane_index=lp.lane.index,
lane_offset=lp.lane.offset_along_lane(lp.pose.point),
)
]
evenly_spaced_cumulative_path_dist = np.linspace(
0, cumulative_path_dist[-1], len(path)
)
evenly_spaced_coordinates = {}
for variable in continuous_variables:
evenly_spaced_coordinates[variable] = np.interp(
evenly_spaced_cumulative_path_dist,
cumulative_path_dist,
ref_lanepoints_coordinates[variable],
)
for variable in discrete_variables:
ref_coordinates = ref_lanepoints_coordinates[variable]
evenly_spaced_coordinates[variable] = []
jdx = 0
for idx in range(len(path)):
while (
jdx + 1 < len(cumulative_path_dist)
and evenly_spaced_cumulative_path_dist[idx]
> cumulative_path_dist[jdx + 1]
):
jdx += 1
evenly_spaced_coordinates[variable].append(ref_coordinates[jdx])
evenly_spaced_coordinates[variable].append(ref_coordinates[-1])
waypoint_path = []
for idx in range(len(path)):
waypoint_path.append(
Waypoint(
pos=np.array(
[
evenly_spaced_coordinates["positions_x"][idx],
evenly_spaced_coordinates["positions_y"][idx],
]
),
heading=Heading(evenly_spaced_coordinates["headings"][idx]),
lane_width=evenly_spaced_coordinates["lane_width"][idx],
speed_limit=evenly_spaced_coordinates["speed_limit"][idx],
lane_id=evenly_spaced_coordinates["lane_id"][idx],
lane_index=evenly_spaced_coordinates["lane_index"][idx],
lane_offset=evenly_spaced_coordinates["lane_offset"][idx],
)
)
return waypoint_path | given a list of LanePoints starting near point, return corresponding
Waypoints that may not be evenly spaced (due to lane change) but start at point. | _equally_spaced_path | python | huawei-noah/SMARTS | smarts/core/waymo_map.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/waymo_map.py | MIT |
def _waypoints_starting_at_lanepoint(
self,
lanepoint: LinkedLanePoint,
lookahead: int,
filter_road_ids: tuple,
point: Point,
) -> List[List[Waypoint]]:
"""computes equally-spaced Waypoints for all lane paths starting at lanepoint
up to lookahead waypoints ahead, constrained to filter_road_ids if specified."""
# The following acts sort of like lru_cache(1), but it allows
# for lookahead to be <= to the cached value...
cache_paths = self._waypoints_cache.query(
lookahead, point, filter_road_ids, lanepoint
)
if cache_paths:
return cache_paths
lanepoint_paths = self._lanepoints.paths_starting_at_lanepoint(
lanepoint, lookahead, filter_road_ids
)
result = [
WaymoMap._equally_spaced_path(
path,
point,
self._map_spec.lanepoint_spacing,
)
for path in lanepoint_paths
]
self._waypoints_cache.update(
lookahead, point, filter_road_ids, lanepoint, result
)
return result | computes equally-spaced Waypoints for all lane paths starting at lanepoint
up to lookahead waypoints ahead, constrained to filter_road_ids if specified. | _waypoints_starting_at_lanepoint | python | huawei-noah/SMARTS | smarts/core/waymo_map.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/waymo_map.py | MIT |
def merge(self, other: ProviderState):
"""Merge state with another provider's state."""
our_actors = {a.actor_id for a in self.actors}
other_actors = {a.actor_id for a in other.actors}
if not our_actors.isdisjoint(other_actors):
overlap = our_actors & other_actors
logging.warning(
"multiple providers control the same actors: %s. "
"Later added providers will take priority. ",
overlap,
)
logging.info(
"Conflicting actor states: \n" "Previous: %s\n" "Later: %s\n",
[(a.actor_id, a.source) for a in self.actors if a.actor_id in overlap],
[(a.actor_id, a.source) for a in other.actors if a.actor_id in overlap],
)
## TODO: Properly harmonize these actor ids so that there is a priority and per actor source
self.actors += filter(lambda a: a.actor_id not in our_actors, other.actors)
self.dt = max(self.dt, other.dt, key=lambda x: x if x else 0) | Merge state with another provider's state. | merge | python | huawei-noah/SMARTS | smarts/core/provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py | MIT |
def filter(self, actor_ids: Set[str]):
"""Filter actor states down to the given actors."""
provider_actor_ids = [a.actor_id for a in self.actors]
for a_id in actor_ids:
try:
index = provider_actor_ids.index(a_id)
del provider_actor_ids[index]
del self.actors[index]
except ValueError:
continue | Filter actor states down to the given actors. | filter | python | huawei-noah/SMARTS | smarts/core/provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py | MIT |
def intersects(self, actor_ids: Set[str]) -> bool:
"""Returns True if any of the actor_ids are contained in this ProviderState .
Returns False for empty-set containment."""
provider_actor_ids = {a.actor_id for a in self.actors}
intersection = actor_ids & provider_actor_ids
return bool(intersection) | Returns True if any of the actor_ids are contained in this ProviderState .
Returns False for empty-set containment. | intersects | python | huawei-noah/SMARTS | smarts/core/provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py | MIT |
def replace_actor_type(
self, updated_actors: List[ActorState], actor_state_type: type
):
"""Replaces all actors of the given type.
Args:
updated_actors (List[ActorState]): The actors to use as replacement.
actor_type (str): The actor type to replace.
"""
self.actors = [
actor_state
for actor_state in self.actors
if not issubclass(actor_state.__class__, actor_state_type)
] + updated_actors | Replaces all actors of the given type.
Args:
updated_actors (List[ActorState]): The actors to use as replacement.
actor_type (str): The actor type to replace. | replace_actor_type | python | huawei-noah/SMARTS | smarts/core/provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py | MIT |
def provider_releases_actor(
self, current_provider: Optional[Provider], state: ActorState
) -> Optional[Provider]:
"""The current provider gives up control over the specified actor. The manager
finds a new Provider for the actor from among the Providers managed by this
ProviderManager. If no provider accepts the actor the actor is removed from all providers.
Returns:
(Provider|None): A suitable new provider or `None` if a suitable one could not be found.
"""
new_provider, actor_provider_transition = self.provider_relinquishing_actor(
current_provider=current_provider, state=state
)
if new_provider is None or not self.transition_to_provider(
new_provider=new_provider,
actor_provider_transition=actor_provider_transition,
):
logging.warning(
"could not find a provider to assume control of vehicle %s with role=%s after being relinquished. removing it.",
state.actor_id,
state.role.name,
)
self._stop_managing_with_providers(state.actor_id, None)
self.provider_removing_actor(current_provider, state.actor_id)
return new_provider | The current provider gives up control over the specified actor. The manager
finds a new Provider for the actor from among the Providers managed by this
ProviderManager. If no provider accepts the actor the actor is removed from all providers.
Returns:
(Provider|None): A suitable new provider or `None` if a suitable one could not be found. | provider_releases_actor | python | huawei-noah/SMARTS | smarts/core/provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py | MIT |
def provider_relinquishing_actor(
self, current_provider: Optional[Provider], state: ActorState
) -> Tuple[Optional[Provider], ActorProviderTransition]:
"""Find a new Provider for an actor from among the Providers managed
by this ProviderManager.
Returns:
(Provider|None): A suitable new provider or `None` if a suitable one could not be found.
"""
raise NotImplementedError | Find a new Provider for an actor from among the Providers managed
by this ProviderManager.
Returns:
(Provider|None): A suitable new provider or `None` if a suitable one could not be found. | provider_relinquishing_actor | python | huawei-noah/SMARTS | smarts/core/provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py | MIT |
def provider_removing_actor(self, provider: Optional[Provider], actor_id: str):
"""Called by a Provider when it is removing an actor from the simulation. It
means that the Provider is indicating that the actor no longer exists.
This was added for convenience, but it isn't always necessary to be called."""
raise NotImplementedError | Called by a Provider when it is removing an actor from the simulation. It
means that the Provider is indicating that the actor no longer exists.
This was added for convenience, but it isn't always necessary to be called. | provider_removing_actor | python | huawei-noah/SMARTS | smarts/core/provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py | MIT |
def provider_for_actor(self, actor_id: str) -> Optional[Provider]:
"""Find the provider that currently manages the given actor.
Args:
actor_id (str): The actor id to query.
Returns:
(Provider|None): The provider that manages this actor.
"""
raise NotImplementedError | Find the provider that currently manages the given actor.
Args:
actor_id (str): The actor id to query.
Returns:
(Provider|None): The provider that manages this actor. | provider_for_actor | python | huawei-noah/SMARTS | smarts/core/provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py | MIT |
def transition_to_provider(
self,
new_provider: Provider,
actor_provider_transition: ActorProviderTransition,
) -> Optional[Provider]:
"""Passes a released actor to a new provider. This depends on `provider_relinquishing_actor`.
Args:
new_provider (Provider):
The provider to transition to.
actor_provider_transition (ActorProviderTransition):
The released actor information.
Returns:
(Provider|None): Returns the provider if successful else will return `None` on failure.
"""
if actor_provider_transition.current_provider is new_provider:
return new_provider
if new_provider.can_accept_actor(actor_provider_transition.actor_state):
new_provider.add_actor(
actor_provider_transition.actor_state,
actor_provider_transition.current_provider,
)
self._stop_managing_with_providers(
actor_provider_transition.actor_state.actor_id, new_provider
)
return new_provider
return None | Passes a released actor to a new provider. This depends on `provider_relinquishing_actor`.
Args:
new_provider (Provider):
The provider to transition to.
actor_provider_transition (ActorProviderTransition):
The released actor information.
Returns:
(Provider|None): Returns the provider if successful else will return `None` on failure. | transition_to_provider | python | huawei-noah/SMARTS | smarts/core/provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py | MIT |
def providers(self) -> List["Provider"]:
"""The providers that are current managed by this provider manager."""
raise NotImplementedError | The providers that are current managed by this provider manager. | providers | python | huawei-noah/SMARTS | smarts/core/provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py | MIT |
def recovery_flags(self) -> ProviderRecoveryFlags:
"""Flags specifying what this provider should do if it fails.
(May be overridden by child classes.)"""
return (
ProviderRecoveryFlags.EXPERIMENT_REQUIRED
| ProviderRecoveryFlags.RELINQUISH_ACTORS
) | Flags specifying what this provider should do if it fails.
(May be overridden by child classes.) | recovery_flags | python | huawei-noah/SMARTS | smarts/core/provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py | MIT |
def recovery_flags(self, flags: ProviderRecoveryFlags):
"""Setter to allow recovery flags to be changed."""
raise NotImplementedError | Setter to allow recovery flags to be changed. | recovery_flags | python | huawei-noah/SMARTS | smarts/core/provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py | MIT |
def set_manager(self, manager: ProviderManager):
"""Indicate the manager that this provider should inform of all actor hand-offs."""
raise NotImplementedError | Indicate the manager that this provider should inform of all actor hand-offs. | set_manager | python | huawei-noah/SMARTS | smarts/core/provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py | MIT |
def actions(self) -> Set[ActionSpaceType]:
"""The action spaces of the provider."""
raise NotImplementedError | The action spaces of the provider. | actions | python | huawei-noah/SMARTS | smarts/core/provider.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/provider.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.