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 agent_interfaces(self) -> Dict[str, AgentInterface]:
"""A list of all agent to agent interface mappings."""
return self._agent_interfaces | A list of all agent to agent interface mappings. | agent_interfaces | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def agent_interface_for_agent_id(self, agent_id: str) -> AgentInterface:
"""Get the agent interface of a specific agent."""
return self._agent_interfaces[agent_id] | Get the agent interface of a specific agent. | agent_interface_for_agent_id | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def pending_agent_ids(self) -> Set[str]:
"""The IDs of agents that are waiting to enter the simulation"""
return self._pending_agent_ids | The IDs of agents that are waiting to enter the simulation | pending_agent_ids | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def pending_social_agent_ids(self) -> Set[str]:
"""The IDs of social agents that are waiting to enter the simulation"""
return self._pending_social_agent_ids | The IDs of social agents that are waiting to enter the simulation | pending_social_agent_ids | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def active_agents(self) -> Set[str]:
"""A list of all active agents in the simulation (agents that have a vehicle.)"""
return self.agent_ids - self.pending_agent_ids | A list of all active agents in the simulation (agents that have a vehicle.) | active_agents | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def shadowing_agent_ids(self) -> Set[str]:
"""Get all agents that currently observe, but not control, a vehicle."""
return self._vehicle_index.shadower_ids() | Get all agents that currently observe, but not control, a vehicle. | shadowing_agent_ids | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def is_ego(self, agent_id: str) -> bool:
"""Test if the agent is an ego agent."""
return agent_id in self.ego_agent_ids | Test if the agent is an ego agent. | is_ego | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def remove_pending_agent_ids(self, agent_ids: Set[str]):
"""Remove an agent from the group of agents waiting to enter the simulation."""
assert agent_ids.issubset(self.agent_ids)
self._pending_agent_ids -= agent_ids | Remove an agent from the group of agents waiting to enter the simulation. | remove_pending_agent_ids | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def agent_for_vehicle(self, vehicle_id: str) -> str:
"""Get the controlling agent for the given vehicle."""
return self._vehicle_index.owner_id_from_vehicle_id(vehicle_id) | Get the controlling agent for the given vehicle. | agent_for_vehicle | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def agent_has_vehicle(self, agent_id: str) -> bool:
"""Test if an agent has an actor associated with it."""
return len(self.vehicles_for_agent(agent_id)) > 0 | Test if an agent has an actor associated with it. | agent_has_vehicle | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def vehicles_for_agent(self, agent_id: str) -> List[str]:
"""Get the vehicles associated with an agent."""
return self._vehicle_index.vehicle_ids_by_owner_id(
agent_id, include_shadowers=True
) | Get the vehicles associated with an agent. | vehicles_for_agent | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def fetch_agent_actions(self, ego_agent_actions: Dict[str, Any]) -> Dict[str, Any]:
"""Retrieve available social agent actions."""
try:
social_agent_actions = {
agent_id: (
self._remote_social_agents_action[agent_id].result()
if self._remote_social_agents_action.get(agent_id, None)
else None
)
for agent_id, remote_agent in self._remote_social_agents.items()
}
except Exception as e:
self._log.error(
"Resolving the remote agent's action (a Future object) generated exception."
)
raise e
agents_without_actions = [
agent_id
for (agent_id, action) in social_agent_actions.items()
if action is None
]
if len(agents_without_actions) > 0:
self._log.debug(
f"social_agents=({', '.join(agents_without_actions)}) returned no action"
)
social_agent_actions = (
self._filter_social_agent_actions_for_controlled_vehicles(
social_agent_actions
)
)
return {**ego_agent_actions, **social_agent_actions} | Retrieve available social agent actions. | fetch_agent_actions | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def _filter_social_agent_actions_for_controlled_vehicles(
self, social_agent_actions
):
"""Some agents may not be controlling a vehicle, such as when a vehicle is in
the airlock, where the agent is observing and running its policy, but the
returned action should not be executed on the vehicle until it is hijacked
by the agent.
"""
vehicle_ids_controlled_by_agents = self._vehicle_index.agent_vehicle_ids()
controlling_agent_ids = set(
[
self._vehicle_index.owner_id_from_vehicle_id(v_id)
for v_id in vehicle_ids_controlled_by_agents
]
)
social_agent_actions = {
agent_id: social_agent_actions[agent_id]
for agent_id in social_agent_actions
if agent_id in controlling_agent_ids
}
# Handle boids where some vehicles are hijacked and some have not yet been
for agent_id, actions in social_agent_actions.items():
if self.is_boid_agent(agent_id):
controlled_vehicle_ids = self._vehicle_index.vehicle_ids_by_owner_id(
agent_id, include_shadowers=False
)
social_agent_actions[agent_id] = {
vehicle_id: vehicle_action
for vehicle_id, vehicle_action in actions.items()
if vehicle_id in controlled_vehicle_ids
}
return social_agent_actions | Some agents may not be controlling a vehicle, such as when a vehicle is in
the airlock, where the agent is observing and running its policy, but the
returned action should not be executed on the vehicle until it is hijacked
by the agent. | _filter_social_agent_actions_for_controlled_vehicles | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def add_social_agent_observations_callback(
self, callback: Callable[[Any], None], callback_id: str
):
"""Subscribe a callback to observe social agents."""
self._social_agent_observation_callbacks[callback_id] = callback | Subscribe a callback to observe social agents. | add_social_agent_observations_callback | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def remove_social_agent_observations_callback(self, callback_id: str):
"""Remove a subscription to social agents."""
del self._social_agent_observation_callbacks[callback_id] | Remove a subscription to social agents. | remove_social_agent_observations_callback | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def reserve_social_agent_action(self, agent_id: str, action: Any):
"""Override a current social agent action."""
self._reserved_social_agent_actions[agent_id] = action | Override a current social agent action. | reserve_social_agent_action | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def send_observations_to_social_agents(self, observations: Dict[str, Observation]):
"""Forwards observations to managed social agents."""
# TODO: Don't send observations (or receive actions) from agents that have done
# vehicles.
self._send_observations_to_social_agents(observations) | Forwards observations to managed social agents. | send_observations_to_social_agents | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def switch_initial_agents(self, agent_interfaces: Dict[str, AgentInterface]):
"""Replaces the initial agent interfaces with a new group. This comes into effect on next reset."""
self._initial_interfaces = agent_interfaces | Replaces the initial agent interfaces with a new group. This comes into effect on next reset. | switch_initial_agents | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def setup_agents(self):
"""Initializes all agents."""
self.init_ego_agents()
self._setup_social_agents()
self._start_keep_alive_boid_agents() | Initializes all agents. | setup_agents | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def add_ego_agent(
self, agent_id: str, agent_interface: AgentInterface, for_trap: bool = True
):
"""Adds an ego agent to the manager."""
if for_trap:
self.pending_agent_ids.add(agent_id)
self._ego_agent_ids.add(agent_id)
self.agent_interfaces[agent_id] = agent_interface | Adds an ego agent to the manager. | add_ego_agent | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def init_ego_agents(self):
"""Initialize all ego agents."""
for agent_id, agent_interface in self._initial_interfaces.items():
self.add_ego_agent(agent_id, agent_interface) | Initialize all ego agents. | init_ego_agents | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def _setup_social_agents(self):
"""Initialize all social agents."""
sim = self._sim()
assert sim
social_agents = sim.scenario.social_agents
self._pending_social_agent_ids.update(social_agents.keys()) | Initialize all social agents. | _setup_social_agents | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def _start_keep_alive_boid_agents(self):
"""Configures and adds boid agents to the sim."""
sim = self._sim()
assert sim
for bubble in filter(
lambda b: b.is_boid
and b.keep_alive
and isinstance(b.actor, SocialAgentActor),
sim.scenario.bubbles,
):
actor = bubble.actor
agent_id = BubbleManager._make_boid_social_agent_id(actor)
social_agent = make_social_agent(
locator=actor.agent_locator,
**actor.policy_kwargs,
)
actor = bubble.actor
social_agent_data_model = SocialAgent(
id=SocialAgentId.new(actor.name),
actor_name=actor.name,
is_boid=True,
is_boid_keep_alive=True,
agent_locator=actor.agent_locator,
policy_kwargs=actor.policy_kwargs,
initial_speed=actor.initial_speed,
)
self.start_social_agent(agent_id, social_agent, social_agent_data_model) | Configures and adds boid agents to the sim. | _start_keep_alive_boid_agents | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def add_and_emit_social_agent(
self, agent_id: str, agent_spec, agent_model: SocialAgent
):
"""Generates an entirely new social agent and emits a vehicle for it immediately.
Args:
agent_id (str): The agent id for the new agent.
agent_spec (AgentSpec): The agent spec of the new agent
agent_model (SocialAgent): The agent configuration of the new vehicle.
Returns:
bool:
If the agent is added. False if the agent id is already reserved
by a pending ego agent or current social/ego agent.
"""
if agent_id in self.agent_ids or agent_id in self.pending_agent_ids:
return False
self._setup_agent_buffer()
remote_agent = self._agent_buffer.acquire_agent()
self._add_agent(
agent_id=agent_id,
agent_interface=agent_spec.interface,
agent_model=agent_model,
trainable=False,
boid=False,
)
if agent_id in self._pending_social_agent_ids:
self._pending_social_agent_ids.remove(agent_id)
remote_agent.start(agent_spec=agent_spec)
self._remote_social_agents[agent_id] = remote_agent
self._agent_interfaces[agent_id] = agent_spec.interface
self._social_agent_ids.add(agent_id)
self._social_agent_data_models[agent_id] = agent_model
return True | Generates an entirely new social agent and emits a vehicle for it immediately.
Args:
agent_id (str): The agent id for the new agent.
agent_spec (AgentSpec): The agent spec of the new agent
agent_model (SocialAgent): The agent configuration of the new vehicle.
Returns:
bool:
If the agent is added. False if the agent id is already reserved
by a pending ego agent or current social/ego agent. | add_and_emit_social_agent | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def start_social_agent(self, agent_id, social_agent, agent_model):
"""Starts a managed social agent."""
self._setup_agent_buffer()
remote_agent = self._agent_buffer.acquire_agent()
remote_agent.start(social_agent)
self._remote_social_agents[agent_id] = remote_agent
self._agent_interfaces[agent_id] = social_agent.interface
self._social_agent_ids.add(agent_id)
self._social_agent_data_models[agent_id] = agent_model | Starts a managed social agent. | start_social_agent | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def teardown_ego_agents(self, filter_ids: Optional[Set] = None):
"""Tears down all given ego agents passed through the filter.
Args:
filter_ids (Optional[Set[str]], optional): The whitelist of agent ids. If `None`, all ids are white-listed.
"""
ids_ = self._teardown_agents_by_ids(self._ego_agent_ids, filter_ids)
self._ego_agent_ids -= ids_
return ids_ | Tears down all given ego agents passed through the filter.
Args:
filter_ids (Optional[Set[str]], optional): The whitelist of agent ids. If `None`, all ids are white-listed. | teardown_ego_agents | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def teardown_social_agents(self, filter_ids: Optional[Set] = None):
"""Tears down all given social agents passed through the filter.
Args:
filter_ids (Optional[Set[str]], optional): The whitelist of agent ids. If `None`, all ids are white-listed.
"""
ids_ = self._teardown_agents_by_ids(self._social_agent_ids, filter_ids)
for id_ in ids_:
self._remote_social_agents[id_].terminate()
del self._remote_social_agents[id_]
del self._social_agent_data_models[id_]
self._social_agent_ids -= ids_
return ids_ | Tears down all given social agents passed through the filter.
Args:
filter_ids (Optional[Set[str]], optional): The whitelist of agent ids. If `None`, all ids are white-listed. | teardown_social_agents | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def reset_agents(
self, observations: Dict[str, Observation]
) -> Dict[str, Observation]:
"""Reset agents, feeding in an initial observation."""
self._send_observations_to_social_agents(observations)
# Observations contain those for social agents; filter them out
return self._filter_for_active_ego(observations) | Reset agents, feeding in an initial observation. | reset_agents | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def agent_name(self, agent_id: str) -> str:
"""Get the resolved agent name."""
if agent_id not in self._social_agent_data_models:
return ""
return self._social_agent_data_models[agent_id].actor_name | Get the resolved agent name. | agent_name | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def is_boid_agent(self, agent_id: str) -> bool:
"""Check if an agent is a boid agent"""
if agent_id not in self._social_agent_data_models:
return False
return self._social_agent_data_models[agent_id].is_boid | Check if an agent is a boid agent | is_boid_agent | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def is_boid_keep_alive_agent(self, agent_id: str) -> bool:
"""Check if this is a persistent boid agent"""
if agent_id not in self._social_agent_data_models:
return False
return self._social_agent_data_models[agent_id].is_boid_keep_alive | Check if this is a persistent boid agent | is_boid_keep_alive_agent | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def is_boid_done(self, agent_id: str) -> bool:
"""Check if this boid agent should not disappear yet."""
if self.is_boid_keep_alive_agent(agent_id):
return False
if self.agent_has_vehicle(agent_id):
return False
return True | Check if this boid agent should not disappear yet. | is_boid_done | python | huawei-noah/SMARTS | smarts/core/agent_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/agent_manager.py | MIT |
def _convert_truthy(t: str) -> bool:
"""Convert value to a boolean. This should only allow ([Tt]rue)|([Ff]alse)|[\\d].
This is necessary because bool("false") == True.
Args:
t (str): The value to convert.
Returns:
bool: The truth value.
"""
# ast literal_eval will parse python literals int, str, e.t.c.
out = ast.literal_eval(t.strip().title())
assert isinstance(out, (bool, int))
return bool(out) | Convert value to a boolean. This should only allow ([Tt]rue)|([Ff]alse)|[\\d].
This is necessary because bool("false") == True.
Args:
t (str): The value to convert.
Returns:
bool: The truth value. | _convert_truthy | python | huawei-noah/SMARTS | smarts/core/configuration.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/configuration.py | MIT |
def environment_prefix(self):
"""The prefix that environment variables configuration is provided with."""
return self._environment_prefix | The prefix that environment variables configuration is provided with. | environment_prefix | python | huawei-noah/SMARTS | smarts/core/configuration.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/configuration.py | MIT |
def get_setting(
self,
section: str,
option: str,
default: Any = _UNSET,
cast: Callable[[Any], Any] = _passthrough_cast,
) -> Optional[Any]:
"""Finds the given configuration checking the following in order: environment variable,
configuration file, and default.
Args:
section (str): The grouping that the configuration option is under.
option (str): The specific configuration option.
default (Any, optional): The default if the requested configuration option is not found. Defaults to _UNSET.
cast (Callable, optional): A function that takes a string and returns the desired type. Defaults to str.
Returns:
Optional[str]: The value of the configuration.
Raises:
KeyError: If the configuration option is not found in the configuration file and no default is provided.
configparser.NoSectionError: If the section in the configuration file is not found and no default is provided.
"""
env_variable = self._environment_variable_format_string.format(
section.upper(), option.upper()
)
setting = os.getenv(env_variable)
if cast is bool:
# This is necessary because bool("false") == True.
cast = _convert_truthy
if setting is not None:
return cast(setting)
try:
value = self._config[section][option]
except (configparser.NoSectionError, KeyError) as exc:
if default is _UNSET:
if (value := _config_defaults.get((section, option), _UNSET)) != _UNSET:
return value
raise EnvironmentError(
f"Setting `${env_variable}` cannot be found in environment or configuration."
) from exc
return default
return cast(value) | Finds the given configuration checking the following in order: environment variable,
configuration file, and default.
Args:
section (str): The grouping that the configuration option is under.
option (str): The specific configuration option.
default (Any, optional): The default if the requested configuration option is not found. Defaults to _UNSET.
cast (Callable, optional): A function that takes a string and returns the desired type. Defaults to str.
Returns:
Optional[str]: The value of the configuration.
Raises:
KeyError: If the configuration option is not found in the configuration file and no default is provided.
configparser.NoSectionError: If the section in the configuration file is not found and no default is provided. | get_setting | python | huawei-noah/SMARTS | smarts/core/configuration.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/configuration.py | MIT |
def substitute_settings(self, input: str, source: Optional[str] = "") -> str:
"""Given a string, substitutes in configuration settings if they exist."""
m: List[str] = self.env_variable_substitution_pattern.findall(input)
if not m:
return input
output = input
for val in set(m):
if self.environment_prefix:
environment_prefix, _, setting = val.partition("_")
if environment_prefix != self.environment_prefix:
warnings.warn(
f"Unable to substitute environment variable `{val}` from `{source}`"
)
continue
else:
setting = val
section, _, option_name = setting.lower().partition("_")
env_value = self(section, option_name)
output = output.replace(f"${{{val}}}", env_value)
return output | Given a string, substitutes in configuration settings if they exist. | substitute_settings | python | huawei-noah/SMARTS | smarts/core/configuration.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/configuration.py | MIT |
def step(self, sim_frame: SimulationFrame, renderer: RendererBase):
"""Update sensor values based on the new simulation state."""
self._sensor_resolver.step(sim_frame, self._sensor_states.values())
for sensor in self._sensors.values():
sensor.step(sim_frame=sim_frame, renderer=renderer) | Update sensor values based on the new simulation state. | step | python | huawei-noah/SMARTS | smarts/core/sensor_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor_manager.py | MIT |
def observe(
self,
sim_frame: SimulationFrame,
sim_local_constants: SimulationLocalConstants,
agent_ids: Set[str],
renderer_ref: RendererBase,
physics_ref: bc.BulletClient,
) -> Tuple[Dict[str, Observation], Dict[str, bool]]:
"""Runs observations and updates the sensor states.
Args:
sim_frame (SimulationFrame):
The current state from the simulation.
sim_local_constants (SimulationLocalConstants):
The values that should stay the same for a simulation over a reset.
agent_ids (Set[str]):
The agent ids to process.
renderer_ref (RendererBase):
The renderer (if any) that should be used.
physics_ref:
The physics client.
"""
observations, dones, updated_sensors = self._sensor_resolver.observe(
sim_frame,
sim_local_constants,
agent_ids,
renderer_ref,
physics_ref,
)
for actor_id, sensors in updated_sensors.items():
for sensor_name, sensor in sensors.items():
self._sensors[
SensorManager._actor_and_sensor_name_to_sensor_id(
sensor_name, actor_id
)
] = sensor
return observations, dones | Runs observations and updates the sensor states.
Args:
sim_frame (SimulationFrame):
The current state from the simulation.
sim_local_constants (SimulationLocalConstants):
The values that should stay the same for a simulation over a reset.
agent_ids (Set[str]):
The agent ids to process.
renderer_ref (RendererBase):
The renderer (if any) that should be used.
physics_ref:
The physics client. | observe | python | huawei-noah/SMARTS | smarts/core/sensor_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor_manager.py | MIT |
def observe_batch(
self,
sim_frame: SimulationFrame,
sim_local_constants: SimulationLocalConstants,
interface: AgentInterface,
sensor_states: Dict[str, SensorState],
vehicles: Dict[str, Vehicle],
renderer: RendererBase,
bullet_client: bc.BulletClient,
) -> Tuple[Dict[str, Observation], Dict[str, bool]]:
"""Operates all sensors on a batch of vehicles for a single agent."""
# TODO: Replace this with a more efficient implementation that _actually_
# does batching
assert sensor_states.keys() == vehicles.keys()
observations, dones = {}, {}
for vehicle_id, vehicle in vehicles.items():
sensor_state = sensor_states[vehicle_id]
(
observations[vehicle_id],
dones[vehicle_id],
updated_sensors,
) = Sensors.observe_vehicle(
sim_frame,
sim_local_constants,
interface,
sensor_state,
vehicle,
renderer,
bullet_client,
)
for sensor_name, sensor in updated_sensors.items():
self._sensors[
SensorManager._actor_and_sensor_name_to_sensor_id(
sensor_name, vehicle_id
)
] = sensor
return observations, dones | Operates all sensors on a batch of vehicles for a single agent. | observe_batch | python | huawei-noah/SMARTS | smarts/core/sensor_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor_manager.py | MIT |
def teardown(self, renderer: RendererBase):
"""Tear down the current sensors and clean up any internal resources."""
self._logger.info("++ Sensors and sensor states reset. ++")
for sensor in self._sensors.values():
sensor.teardown(renderer=renderer)
self._sensors = {}
self._sensor_states = {}
self._sensors_by_actor_id = {}
self._sensor_references.clear()
self._scheduled_sensors.clear() | Tear down the current sensors and clean up any internal resources. | teardown | python | huawei-noah/SMARTS | smarts/core/sensor_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor_manager.py | MIT |
def add_sensor_state(self, actor_id: str, sensor_state: SensorState):
"""Add a sensor state associated with a given actor."""
self._logger.debug("Sensor state added for actor '%s'.", actor_id)
self._sensor_states[actor_id] = sensor_state | Add a sensor state associated with a given actor. | add_sensor_state | python | huawei-noah/SMARTS | smarts/core/sensor_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor_manager.py | MIT |
def remove_sensor_state_by_actor_id(self, actor_id: str):
"""Add a sensor state associated with a given actor."""
self._logger.debug("Sensor state removed for actor '%s'.", actor_id)
return self._sensor_states.pop(actor_id, None) | Add a sensor state associated with a given actor. | remove_sensor_state_by_actor_id | python | huawei-noah/SMARTS | smarts/core/sensor_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor_manager.py | MIT |
def remove_actor_sensors_by_actor_id(
self, actor_id: str, schedule_teardown: bool = True
) -> Iterable[Tuple[Sensor, int]]:
"""Remove association of an actor to sensors. If the sensor is no longer associated an actor, the
sensor is scheduled to be removed."""
sensor_states = self._sensor_states.get(actor_id)
if not sensor_states:
self._logger.warning(
"Attempted to remove sensors from actor with no sensors: '%s'.",
actor_id,
)
return []
self.remove_sensor_state_by_actor_id(actor_id)
sensors_by_actor = self._sensors_by_actor_id.get(actor_id)
if not sensors_by_actor:
return []
self._logger.debug("Target sensor removal for actor '%s'.", actor_id)
discarded_sensors = []
for sensor_id in sensors_by_actor:
self._actors_by_sensor_id[sensor_id].remove(actor_id)
self._sensor_references.subtract([sensor_id])
references = self._sensor_references[sensor_id]
discarded_sensors.append((self._sensors[sensor_id], references))
if references < 1:
self._disassociate_sensor(sensor_id, schedule_teardown)
del self._sensors_by_actor_id[actor_id]
return discarded_sensors | Remove association of an actor to sensors. If the sensor is no longer associated an actor, the
sensor is scheduled to be removed. | remove_actor_sensors_by_actor_id | python | huawei-noah/SMARTS | smarts/core/sensor_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor_manager.py | MIT |
def remove_sensor(
self, sensor_id: str, schedule_teardown: bool = False
) -> Optional[Sensor]:
"""Remove a sensor by its id. Removes any associations it has with actors."""
self._logger.debug("Target removal of sensor '%s'.", sensor_id)
sensor = self._sensors.get(sensor_id)
if not sensor:
return None
self._disassociate_sensor(sensor_id, schedule_teardown)
return sensor | Remove a sensor by its id. Removes any associations it has with actors. | remove_sensor | python | huawei-noah/SMARTS | smarts/core/sensor_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor_manager.py | MIT |
def sensor_state_exists(self, actor_id: str) -> bool:
"""Determines if a actor has a sensor state associated with it."""
return actor_id in self._sensor_states | Determines if a actor has a sensor state associated with it. | sensor_state_exists | python | huawei-noah/SMARTS | smarts/core/sensor_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor_manager.py | MIT |
def sensor_states_items(self) -> Iterator[Tuple[str, SensorState]]:
"""Gets all actor to sensor state associations."""
return map(lambda x: x, self._sensor_states.items()) | Gets all actor to sensor state associations. | sensor_states_items | python | huawei-noah/SMARTS | smarts/core/sensor_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor_manager.py | MIT |
def sensors_for_actor_id(self, actor_id: str) -> List[Sensor]:
"""Gets all sensors associated with the given actor."""
return [
self._sensors[s_id]
for s_id in self._sensors_by_actor_id.get(actor_id, set())
] | Gets all sensors associated with the given actor. | sensors_for_actor_id | python | huawei-noah/SMARTS | smarts/core/sensor_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor_manager.py | MIT |
def sensors_for_actor_ids(
self, actor_ids: Set[str]
) -> Dict[str, Dict[str, Sensor]]:
"""Gets all sensors for the given actors."""
return {
actor_id: {
SensorManager._actor_sid_to_sname(s_id): self._sensors[s_id]
for s_id in self._sensors_by_actor_id.get(actor_id, set())
}
for actor_id in actor_ids
} | Gets all sensors for the given actors. | sensors_for_actor_ids | python | huawei-noah/SMARTS | smarts/core/sensor_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor_manager.py | MIT |
def sensor_state_for_actor_id(self, actor_id: str) -> Optional[SensorState]:
"""Gets the sensor state for the given actor."""
return self._sensor_states.get(actor_id) | Gets the sensor state for the given actor. | sensor_state_for_actor_id | python | huawei-noah/SMARTS | smarts/core/sensor_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor_manager.py | MIT |
def add_sensor_for_actor(self, actor_id: str, name: str, sensor: Sensor) -> str:
"""Adds a sensor association for a specific actor."""
# TAI: Allow multiple sensors of the same type on the same actor
s_id = SensorManager._actor_and_sensor_name_to_sensor_id(name, actor_id)
actor_sensors = self._sensors_by_actor_id.setdefault(actor_id, set())
if s_id in actor_sensors:
self._logger.warning(
"Duplicate sensor attempted to add to actor `%s`: `%s`", actor_id, s_id
)
return s_id
actor_sensors.add(s_id)
actors = self._actors_by_sensor_id.setdefault(s_id, set())
actors.add(actor_id)
return self.add_sensor(s_id, sensor) | Adds a sensor association for a specific actor. | add_sensor_for_actor | python | huawei-noah/SMARTS | smarts/core/sensor_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor_manager.py | MIT |
def add_sensor(self, sensor_id, sensor: Sensor) -> str:
"""Adds a sensor to the sensor manager."""
self._logger.info("Added sensor '%s' to sensor manager.", sensor_id)
assert sensor_id not in self._sensors
self._sensors[sensor_id] = sensor
self._sensor_references.update([sensor_id])
return sensor_id | Adds a sensor to the sensor manager. | add_sensor | python | huawei-noah/SMARTS | smarts/core/sensor_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor_manager.py | MIT |
def clean_up_sensors_for_actors(
self, current_actor_ids: Set[str], renderer: RendererBase
):
"""Cleans up sensors that are attached to non-existing actors."""
# This is not good enough by itself since actors can keep alive sensors that are not in use by an agent
old_actor_ids = set(self._sensor_states)
missing_actors = old_actor_ids - current_actor_ids
for aid in missing_actors:
self.remove_actor_sensors_by_actor_id(aid)
for sensor_id, sensor in self._scheduled_sensors:
self._logger.info("Sensor '%s' destroyed.", sensor_id)
sensor.teardown(renderer=renderer)
self._scheduled_sensors.clear() | Cleans up sensors that are attached to non-existing actors. | clean_up_sensors_for_actors | python | huawei-noah/SMARTS | smarts/core/sensor_manager.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensor_manager.py | MIT |
def wait_for_ram_image(self, img_format: str, retries=100):
"""Attempt to acquire a graphics buffer."""
# Rarely, we see dropped frames where an image is not available
# for our observation calculations.
#
# We've seen this happen fairly reliable when we are initializing
# a multi-agent + multi-instance simulation.
#
# To deal with this, we can try to force a render and block until
# we are fairly certain we have an image in ram to return to the user
raise NotImplementedError | Attempt to acquire a graphics buffer. | wait_for_ram_image | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def update(self, *args, **kwargs):
"""Update the location of the camera.
Args:
pose:
The pose of the camera target.
height:
The height of the camera above the camera target.
"""
raise NotImplementedError | Update the location of the camera.
Args:
pose:
The pose of the camera target.
height:
The height of the camera above the camera target. | update | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def image_dimensions(self) -> Tuple[int, int]:
"""The dimensions of the output camera image."""
raise NotImplementedError | The dimensions of the output camera image. | image_dimensions | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def position(self) -> Tuple[float, float, float]:
"""The position of the camera."""
raise NotImplementedError | The position of the camera. | position | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def heading(self) -> float:
"""The heading of this camera."""
raise NotImplementedError | The heading of this camera. | heading | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def teardown(self):
"""Clean up internal resources."""
raise NotImplementedError | Clean up internal resources. | teardown | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def id(self):
"""The id of the simulation rendered."""
raise NotImplementedError | The id of the simulation rendered. | id | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def is_setup(self) -> bool:
"""If the renderer has been fully initialized."""
raise NotImplementedError | If the renderer has been fully initialized. | is_setup | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def log(self) -> logging.Logger:
"""The rendering logger."""
raise NotImplementedError | The rendering logger. | log | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def remove_buffer(self, buffer):
"""Remove the rendering buffer."""
raise NotImplementedError | Remove the rendering buffer. | remove_buffer | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def setup(self, scenario):
"""Initialize this renderer."""
raise NotImplementedError | Initialize this renderer. | setup | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def render(self):
"""Render the scene graph of the simulation."""
raise NotImplementedError | Render the scene graph of the simulation. | render | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def reset(self):
"""Reset the render back to initialized state."""
raise NotImplementedError | Reset the render back to initialized state. | reset | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def step(self):
"""provided for non-SMARTS uses; normally not used by SMARTS."""
raise NotImplementedError | provided for non-SMARTS uses; normally not used by SMARTS. | step | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def sync(self, sim_frame):
"""Update the current state of the vehicles within the renderer."""
raise NotImplementedError | Update the current state of the vehicles within the renderer. | sync | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def teardown(self):
"""Clean up internal resources."""
raise NotImplementedError | Clean up internal resources. | teardown | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def destroy(self):
"""Destroy the renderer. Cleans up all remaining renderer resources."""
raise NotImplementedError | Destroy the renderer. Cleans up all remaining renderer resources. | destroy | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def create_vehicle_node(self, glb_model: str, vid: str, color, pose: Pose):
"""Create a vehicle node."""
raise NotImplementedError | Create a vehicle node. | create_vehicle_node | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def begin_rendering_vehicle(self, vid: str, is_agent: bool):
"""Add the vehicle node to the scene graph"""
raise NotImplementedError | Add the vehicle node to the scene graph | begin_rendering_vehicle | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def update_vehicle_node(self, vid: str, pose: Pose):
"""Move the specified vehicle node."""
raise NotImplementedError | Move the specified vehicle node. | update_vehicle_node | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def remove_vehicle_node(self, vid: str):
"""Remove a vehicle node"""
raise NotImplementedError | Remove a vehicle node | remove_vehicle_node | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def camera_for_id(self, camera_id) -> OffscreenCamera:
"""Get a camera by its id."""
raise NotImplementedError | Get a camera by its id. | camera_for_id | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def build_offscreen_camera(
self,
name: str,
mask: int,
width: int,
height: int,
resolution: float,
) -> None:
"""Generates a new off-screen camera."""
raise NotImplementedError | Generates a new off-screen camera. | build_offscreen_camera | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def build_shader_step(
self,
name: str,
fshader_path: Union[str, Path],
dependencies: Collection[
Union[ShaderStepCameraDependency, ShaderStepVariableDependency]
],
priority: int,
height: int,
width: int,
) -> None:
"""Generates a new shader camera."""
raise NotImplementedError | Generates a new shader camera. | build_shader_step | python | huawei-noah/SMARTS | smarts/core/renderer_base.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/renderer_base.py | MIT |
def signal_state_to_color(state: SignalLightState) -> SceneColors:
"""Maps a signal state to a color."""
if state == SignalLightState.STOP:
return SceneColors.SignalStop
elif state == SignalLightState.CAUTION:
return SceneColors.SignalCaution
elif state == SignalLightState.GO:
return SceneColors.SignalGo
else:
return SceneColors.SignalUnknown | Maps a signal state to a color. | signal_state_to_color | python | huawei-noah/SMARTS | smarts/core/signals.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/signals.py | MIT |
def actors_alive_done(self):
"""Deprecated. Use interest_done."""
warnings.warn("Use interest_done.", category=DeprecationWarning)
return self.interest_done | Deprecated. Use interest_done. | actors_alive_done | python | huawei-noah/SMARTS | smarts/core/events.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/events.py | MIT |
def refline_to_linear_segments(self, s_start: float, s_end: float) -> List[float]:
"""Get segment offsets between the given offsets."""
s_vals = []
geom_start = 0
for geom in self.refline._geometries:
geom_end = geom_start + geom.length
if type(geom) == LineGeometry:
s_vals.extend([geom_start, geom_end])
else:
s_vals.extend(
get_linear_segments_for_range(
geom_start, geom_end, self.segment_size
)
)
geom_start += geom.length
return [s for s in s_vals if s_start <= s <= s_end] | Get segment offsets between the given offsets. | refline_to_linear_segments | python | huawei-noah/SMARTS | smarts/core/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def get_lane_offset(self, s: float) -> float:
"""Get the lane offset for this boundary at a given s value."""
if len(self.lane_offsets) == 0:
return 0
if s < self.lane_offsets[0].start_pos:
return 0
i = bisect((KeyWrapper(self.lane_offsets, key=lambda x: x.start_pos)), s) - 1
poly = CubicPolynomial.from_list(self.lane_offsets[i].polynomial_coefficients)
ds = s - self.lane_offsets[i].start_pos
offset = poly.eval(ds)
return offset | Get the lane offset for this boundary at a given s value. | get_lane_offset | python | huawei-noah/SMARTS | smarts/core/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def lane_width_at_offset(self, offset: float) -> LaneWidthElement:
"""Get the lane width at the given offset."""
i = (
bisect((KeyWrapper(self.lane_widths, key=lambda x: x.start_offset)), offset)
- 1
)
return self.lane_widths[i] | Get the lane width at the given offset. | lane_width_at_offset | python | huawei-noah/SMARTS | smarts/core/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def calc_t(self, s: float, section_s_start: float, lane_idx: int) -> float:
"""Used to evaluate lane boundary shape."""
# Find the lateral shift of lane reference line with road reference line (known as laneOffset in OpenDRIVE)
lane_offset = self.get_lane_offset(s)
if not self.inner:
return np.sign(lane_idx) * lane_offset
width = self.lane_width_at_offset(s - section_s_start)
poly = CubicPolynomial.from_list(width.polynomial_coefficients)
return poly.eval(s - section_s_start - width.start_offset) + self.inner.calc_t(
s, section_s_start, lane_idx
) | Used to evaluate lane boundary shape. | calc_t | python | huawei-noah/SMARTS | smarts/core/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def to_linear_segments(self, s_start: float, s_end: float) -> List[float]:
"""Convert from lane boundary shape to linear segments."""
if self.inner:
inner_s_vals = self.inner.to_linear_segments(s_start, s_end)
else:
if self.lane_offsets:
return get_linear_segments_for_range(s_start, s_end, self.segment_size)
return self.refline_to_linear_segments(s_start, s_end)
outer_s_vals: List[float] = []
curr_s_start = s_start
for width in self.lane_widths:
poly = CubicPolynomial.from_list(width.polynomial_coefficients)
if poly.c == 0 and poly.d == 0:
# Special case - only 2 vertices required
outer_s_vals.extend([curr_s_start, curr_s_start + width.length])
else:
outer_s_vals.extend(
get_linear_segments_for_range(
curr_s_start, curr_s_start + width.length, self.segment_size
)
)
curr_s_start += width.length
return sorted(set(inner_s_vals + outer_s_vals)) | Convert from lane boundary shape to linear segments. | to_linear_segments | python | huawei-noah/SMARTS | smarts/core/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def from_spec(
cls,
map_spec: MapSpec,
):
"""Generate a road network from the given specification."""
if map_spec.shift_to_origin:
logger = logging.getLogger(cls.__name__)
logger.warning(
"OpenDrive road networks do not yet support the 'shift_to_origin' option."
)
xodr_file = OpenDriveRoadNetwork._map_path(map_spec)
od_map = cls(xodr_file, map_spec)
return od_map | Generate a road network from the given specification. | from_spec | python | huawei-noah/SMARTS | smarts/core/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def source(self) -> str:
"""This is the `.xodr` file of the OpenDRIVE map."""
return self._xodr_file | This is the `.xodr` file of the OpenDRIVE map. | source | python | huawei-noah/SMARTS | smarts/core/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def lane_polygon(self) -> List[Tuple[float, float]]:
"""A list of polygons that describe the shape of the lane."""
return self._lane_polygon | A list of polygons that describe the shape of the lane. | lane_polygon | python | huawei-noah/SMARTS | smarts/core/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def bounding_box(self) -> BoundingBox:
"""Get the minimal axis aligned bounding box that contains all geometry in this lane."""
# XXX: This shoudn't be public.
x_coordinates, y_coordinates = zip(*self.lane_polygon)
self._bounding_box = BoundingBox(
min_pt=Point(x=min(x_coordinates), y=min(y_coordinates)),
max_pt=Point(x=max(x_coordinates), y=max(y_coordinates)),
)
return self._bounding_box | Get the minimal axis aligned bounding box that contains all geometry in this lane. | bounding_box | python | huawei-noah/SMARTS | smarts/core/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def _edges_at_point(
self, point: Point
) -> Tuple[Optional[Point], Optional[Point]]:
"""Get the boundary points perpendicular to the center of the lane closest to the given
world coordinate.
Args:
point:
A world coordinate point.
Returns:
A pair of points indicating the left boundary and right boundary of the lane.
"""
from .shape import offset_along_shape, position_at_shape_offset
reference_line_vertices_len = int((len(self._lane_polygon) - 1) / 2)
# left_edge
left_edge_shape = [
Point(x, y) for x, y in self._lane_polygon[:reference_line_vertices_len]
]
left_offset = offset_along_shape(point, left_edge_shape)
left_edge = position_at_shape_offset(left_edge_shape, left_offset)
# right_edge
right_edge_shape = [
Point(x, y)
for x, y in self._lane_polygon[
reference_line_vertices_len : len(self._lane_polygon) - 1
]
]
right_offset = offset_along_shape(point, right_edge_shape)
right_edge = position_at_shape_offset(right_edge_shape, right_offset)
return left_edge, right_edge | Get the boundary points perpendicular to the center of the lane closest to the given
world coordinate.
Args:
point:
A world coordinate point.
Returns:
A pair of points indicating the left boundary and right boundary of the lane. | _edges_at_point | python | huawei-noah/SMARTS | smarts/core/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def bounding_box(self) -> Optional[BoundingBox]:
"""Get the minimal axis aligned bounding box that contains all road geometry."""
return self._bounding_box | Get the minimal axis aligned bounding box that contains all road geometry. | bounding_box | python | huawei-noah/SMARTS | smarts/core/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def _edges_at_point(self, point: Point) -> Tuple[Point, Point]:
"""Get the boundary points perpendicular to the center of the road closest to the given
world coordinate.
Args:
point:
A world coordinate point.
Returns:
A pair of points indicating the left boundary and right boundary of the road.
"""
# left and right edge follow the lane reference line system or direction of that road
leftmost_lane = self.lane_at_index(self._total_lanes - 1)
rightmost_lane = self.lane_at_index(0)
_, right_edge = rightmost_lane._edges_at_point(point)
left_edge, _ = leftmost_lane._edges_at_point(point)
return left_edge, right_edge | Get the boundary points perpendicular to the center of the road closest to the given
world coordinate.
Args:
point:
A world coordinate point.
Returns:
A pair of points indicating the left boundary and right boundary of the road. | _edges_at_point | python | huawei-noah/SMARTS | smarts/core/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def update(
self,
lookahead: int,
point: Point,
filter_road_ids: tuple,
llp,
paths: List[List[Waypoint]],
):
"""Update the current cache if not already cached."""
if not self._match(lookahead, point, filter_road_ids):
self.lookahead = lookahead
self.point = point
self.filter_road_ids = filter_road_ids
self._starts = {}
self._starts[llp.lp.lane.index] = paths | Update the current cache if not already cached. | update | python | huawei-noah/SMARTS | smarts/core/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def query(
self,
lookahead: int,
point: Point,
filter_road_ids: tuple,
llp,
) -> Optional[List[List[Waypoint]]]:
"""Attempt to find previously cached waypoints"""
if self._match(lookahead, point, filter_road_ids):
hit = self._starts.get(llp.lp.lane.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/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def _waypoint_paths_along_route(
self, point: Point, lookahead: int, route: Sequence[str]
) -> List[List[Waypoint]]:
"""finds the closest lane to vehicle's position that is on its route,
then gets waypoint paths from all lanes in its 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:
if closest_lane.road.road_id != route[-1] and all(
out_lane.road.road_id not in route for out_lane in lane.outgoing_lanes
):
continue
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/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def _equally_spaced_path(
self,
path: Sequence[LinkedLanePoint],
point: Point,
lp_spacing: float,
width_threshold=None,
) -> 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)
}
curr_lane_id = None
skip_lanepoints = False
index_skipped = []
for idx, lanepoint in enumerate(path):
if lanepoint.is_inferred and 0 < idx < len(path) - 1:
continue
if curr_lane_id is None:
curr_lane_id = lanepoint.lp.lane.lane_id
# Compute the lane offset for the lanepoint position
position = Point(
x=lanepoint.lp.pose.position[0], y=lanepoint.lp.pose.position[1], z=0.0
)
lane_coord = lanepoint.lp.lane.to_lane_coord(position)
# Skip one-third of lanepoints for next lanes not outgoing to previous lane
if skip_lanepoints:
if lane_coord.s > (lanepoint.lp.lane.length / 3):
skip_lanepoints = False
else:
index_skipped.append(idx)
continue
if lanepoint.lp.lane.lane_id != curr_lane_id:
previous_lane = self._lanes[curr_lane_id]
curr_lane_id = lanepoint.lp.lane.lane_id
# if the current lane is not outgoing to previous lane, start skipping one third of its lanepoints
if lanepoint.lp.lane not in previous_lane.outgoing_lanes:
skip_lanepoints = True
index_skipped.append(idx)
continue
# Compute the lane's width at lanepoint's position
width_at_offset = lanepoint.lp.lane_width
if idx != 0 and width_threshold and width_at_offset < width_threshold:
index_skipped.append(idx)
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(width_at_offset)
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
lp_position = Point(x=lp.pose.position[0], y=lp.pose.position[1], z=0.0)
lp_lane_coord = lp.lane.to_lane_coord(lp_position)
return [
Waypoint(
pos=lp.pose.as_position2d(),
heading=lp.pose.heading,
lane_width=lp.lane.width_at_offset(lp_lane_coord.s)[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)):
if idx in index_skipped:
position = Point(
x=evenly_spaced_coordinates["positions_x"][idx],
y=evenly_spaced_coordinates["positions_y"][idx],
z=0.0,
)
nearest_lane = self.nearest_lane(position)
if nearest_lane:
if variable == "lane_id":
evenly_spaced_coordinates[variable].append(
nearest_lane.lane_id
)
else:
evenly_spaced_coordinates[variable].append(
nearest_lane.index
)
else:
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/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def _waypoints_starting_at_lanepoint(
self,
lanepoint: LinkedLanePoint,
lookahead: int,
filter_road_ids: tuple,
point: Point,
) -> List[List[Waypoint]]:
"""computes equally-spaced Waypoints for all lane paths starting at lanepoint
up to lookahead waypoints ahead, constrained to filter_road_ids if specified."""
# The following acts sort of like lru_cache(1), but it allows
# for lookahead to be <= to the cached value...
cache_paths = self._waypoints_cache.query(
lookahead, point, filter_road_ids, lanepoint
)
if cache_paths:
return cache_paths
lanepoint_paths = self._lanepoints.paths_starting_at_lanepoint(
lanepoint, lookahead, filter_road_ids
)
result = [
self._equally_spaced_path(
path,
point,
self._map_spec.lanepoint_spacing,
self._default_lane_width / 2,
)
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/opendrive_road_network.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/opendrive_road_network.py | MIT |
def _step(self, agent_actions, time_delta_since_last_step: Optional[float] = None):
"""Steps through the simulation while applying the given agent actions.
Returns the observations, rewards, done, and infos signals.
"""
# Due to a limitation of our traffic simulator(SUMO) interface(TRACI), we can
# only observe traffic state of the previous simulation step.
#
# To compensate for this, we:
#
# 0. Advance the simulation clock
# 1. Fetch social agent actions
# 2. Step all providers and harmonize state
# 3. Step bubble manager
# 4. Calculate observation and reward
# 5. Send observations to social agents
# 6. Clear done agents
# 7. Perform visualization
#
# In this way, observations and reward are computed with data that is
# consistently with one step of latency and the agent will observe consistent
# data.
# 0. Advance the simulation clock.
# It's been this long since our last step.
self._last_dt = time_delta_since_last_step or self._fixed_timestep_sec or 0.1
self._elapsed_sim_time = self._rounder(self._elapsed_sim_time + self._last_dt)
# 1. Fetch agent actions
with timeit("Fetching agent actions", self._log.debug):
all_agent_actions = self._agent_manager.fetch_agent_actions(agent_actions)
# 2. Step all providers and harmonize state
with timeit("Stepping all providers and harmonizing state", self._log.debug):
provider_state = self._step_providers(all_agent_actions)
with timeit("Checking if all agents are active", self._log.debug):
self._check_if_acting_on_active_agents(agent_actions)
# 3. Step bubble manager and trap manager
with timeit("Syncing vehicle index", self._log.debug):
self._vehicle_index.sync()
with timeit("Stepping through bubble manager", self._log.debug):
self._bubble_manager.step(self)
with timeit("Stepping through actor capture managers", self._log.debug):
for actor_capture_manager in self._actor_capture_managers:
actor_capture_manager.step(self)
# 4. Calculate observation and reward
# We pre-compute vehicle_states here because we *think* the users will
# want these during their observation/reward computations.
# This is a hack to give us some short term perf wins. Longer term we
# need to expose better support for batched computations
with timeit("Syncing provider state", self._log.debug):
self._sync_smarts_and_provider_actor_states(provider_state)
self._sensor_manager.clean_up_sensors_for_actors(
set(v.actor_id for v in self._vehicle_states),
renderer=self.renderer_ref,
)
# Reset frame state
try:
del self.cached_frame
except AttributeError:
pass
self.cached_frame
# Agents
with timeit("Stepping through sensors", self._log.debug):
self._sensor_manager.step(self.cached_frame, self.renderer_ref)
if self.renderer_ref:
# runs through the render pipeline (for camera-based sensors)
# MUST perform this after _sensor_manager.step() above, and before observe() below,
# so that all updates are ready before rendering happens per
with timeit("Syncing the renderer", self._log.debug):
self.renderer_ref.sync(self.cached_frame)
# TODO OBSERVATIONS: this needs to happen between the base and rendered observations
# with timeit("Running through the render pipeline", self._log.debug):
# self.renderer_ref.render()
# TODO OBSERVATIONS: Need to split the observation generation
with timeit("Calculating observations and rewards", self._log.debug):
observations, rewards, scores, dones = self._agent_manager.observe()
with timeit("Filtering response for ego", self._log.debug):
response_for_ego = self._agent_manager.filter_response_for_ego(
(observations, rewards, scores, dones)
)
# 5. Send observations to social agents
with timeit("Sending observations to social agents", self._log.debug):
self._agent_manager.send_observations_to_social_agents(observations)
# 6. Clear done agents
with timeit("Clearing done agents", self._log.debug):
self._teardown_done_agents_and_vehicles(dones)
# 7. Perform visualization
with timeit("Trying to emit the envision state", self._log.debug):
self._try_emit_envision_state(provider_state, observations, scores)
with timeit("Trying to emit the visdom observations", self._log.debug):
self._try_emit_visdom_obs(observations)
observations, rewards, scores, dones = response_for_ego
extras = dict(scores=scores)
self._step_count += 1
return observations, rewards, dones, extras | Steps through the simulation while applying the given agent actions.
Returns the observations, rewards, done, and infos signals. | _step | python | huawei-noah/SMARTS | smarts/core/smarts.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/smarts.py | MIT |
def reset(
self, scenario: Scenario, start_time: float = 0.0
) -> Dict[str, Observation]:
"""Reset the simulation, reinitialize with the specified scenario. Then progress the
simulation up to the first time an agent returns an observation, or `start_time` if there
are no agents in the simulation.
Args:
scenario (smarts.core.scenario.Scenario): The scenario to reset the simulation with.
start_time (float):
The initial amount of simulation time to skip. This has implications on all time
dependent systems.
.. note::
SMARTS simulates a step and then updates vehicle control.
If you want a vehicle to enter at exactly ``0.3`` with a step of ``0.1`` it means the
simulation should start at ``start_time==0.2``.
Returns:
Dict[str, Observation]. This observation is as follows...
- If no agents: the initial simulation observation at `start_time`
- If agents: the first step of the simulation with an agent observation
"""
tries = config()("core", "reset_retries", cast=int) + 1
first_exception = None
for _ in range(tries):
try:
self._resetting = True
return self._reset(scenario, start_time)
except Exception as err:
if not first_exception:
first_exception = err
finally:
self._resetting = False
self._log.error("Failed to successfully reset after %i tries.", tries)
raise first_exception | Reset the simulation, reinitialize with the specified scenario. Then progress the
simulation up to the first time an agent returns an observation, or `start_time` if there
are no agents in the simulation.
Args:
scenario (smarts.core.scenario.Scenario): The scenario to reset the simulation with.
start_time (float):
The initial amount of simulation time to skip. This has implications on all time
dependent systems.
.. note::
SMARTS simulates a step and then updates vehicle control.
If you want a vehicle to enter at exactly ``0.3`` with a step of ``0.1`` it means the
simulation should start at ``start_time==0.2``.
Returns:
Dict[str, Observation]. This observation is as follows...
- If no agents: the initial simulation observation at `start_time`
- If agents: the first step of the simulation with an agent observation | reset | python | huawei-noah/SMARTS | smarts/core/smarts.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/smarts.py | MIT |
def setup(self, scenario: Scenario):
"""Setup the next scenario."""
self._check_valid()
self._scenario = scenario
self._setup_bullet_client(self._bullet_client)
provider_state = self._setup_providers(self._scenario)
self._vehicle_index.load_vehicle_definitions_list(
scenario.vehicle_definitions_filepath
)
self._agent_manager.setup_agents()
self._bubble_manager = BubbleManager(scenario.bubbles, scenario.road_map)
for actor_capture_manager in self._actor_capture_managers:
actor_capture_manager.reset(scenario, self)
if self._renderer or any(
a.requires_rendering for a in self._agent_manager.agent_interfaces.values()
):
self.renderer.setup(scenario)
self._harmonize_providers(provider_state)
self._last_provider_state = provider_state
self._is_setup = True | Setup the next scenario. | setup | python | huawei-noah/SMARTS | smarts/core/smarts.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/smarts.py | MIT |
def add_provider(
self,
provider: Provider,
recovery_flags: ProviderRecoveryFlags = ProviderRecoveryFlags.EXPERIMENT_REQUIRED,
):
"""Add a provider to the simulation. A provider is a co-simulator conformed to a common
interface.
"""
self._check_valid()
assert isinstance(provider, Provider)
provider.recovery_flags = recovery_flags
self._provider_suite.insert(provider)
if isinstance(provider, TrafficProvider):
provider.set_manager(self) | Add a provider to the simulation. A provider is a co-simulator conformed to a common
interface. | add_provider | python | huawei-noah/SMARTS | smarts/core/smarts.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/smarts.py | MIT |
def remove_provider(self, requested_type_or_provider: Union[type, Provider]):
"""Remove a provider from the simulation.
Args:
requested_type (type | Provider): The type of the provider to remove or provider to remove.
Returns:
Optional[Provider]: The provider that was removed.
"""
self._check_valid()
out_provider = None
if isinstance(requested_type_or_provider, type):
out_provider = self._provider_suite.remove_by_type(
requested_type_or_provider
)
elif isinstance(requested_type_or_provider, Provider):
out_provider = self._provider_suite.remove(requested_type_or_provider)
return out_provider | Remove a provider from the simulation.
Args:
requested_type (type | Provider): The type of the provider to remove or provider to remove.
Returns:
Optional[Provider]: The provider that was removed. | remove_provider | python | huawei-noah/SMARTS | smarts/core/smarts.py | https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/smarts.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.