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 get_instance_by_id(self, instance_id: str) -> Optional[T]: """Find an instance with the given id. Args: instance_id (str): The name of the instance. Returns: Optional[T]: An instance with the given name if found or else `None`. """ return self._instances_by_id.get(instance_id)
Find an instance with the given id. Args: instance_id (str): The name of the instance. Returns: Optional[T]: An instance with the given name if found or else `None`.
get_instance_by_id
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT
def get_instance_by_type(self, instance_type: Type[T]) -> Optional[T]: """Find an instance of the given type. Args: instance_type (Type[T]): The type of the instance to find. Returns: Optional[T]: An instance of that type if found or else `None`. """ return self._instances_by_type.get(instance_type)
Find an instance of the given type. Args: instance_type (Type[T]): The type of the instance to find. Returns: Optional[T]: An instance of that type if found or else `None`.
get_instance_by_type
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT
def instances(self) -> List[T]: """All instances currently managed in this type group.""" return self._instances
All instances currently managed in this type group.
instances
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT
def clear_type(self, type_to_clear: Type): """Clear all instances of the given type from this suite. This includes all sub-classes. This should be an sub-class of the type that this suite manages. Args: type_to_clear (Type[S]): The type to clear. """ self._assert_is_managed(type_to_clear) t = self._associated_groups.get(type_to_clear) if t is None: return for inst in self._type_groups[type_to_clear].instances[:]: self.remove(inst)
Clear all instances of the given type from this suite. This includes all sub-classes. This should be an sub-class of the type that this suite manages. Args: type_to_clear (Type[S]): The type to clear.
clear_type
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT
def insert(self, instance: T): """Adds the instance to the suite of managed instances. Args: instance (T): The instance to add. """ t = instance.__class__ if t not in self._associated_groups: types = get_type_chain(t, self._base_type) self._associated_groups[t] = types for group_type in self._associated_groups[t]: self._type_groups[group_type].insert(instance)
Adds the instance to the suite of managed instances. Args: instance (T): The instance to add.
insert
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT
def remove(self, instance: T) -> T: """Removes the given instance from the suite. Args: instance (T): The instance to remove. Returns: T: The removed instance. """ t = instance.__class__ for group_type in self._associated_groups[t]: self._type_groups[group_type].remove(instance) return instance
Removes the given instance from the suite. Args: instance (T): The instance to remove. Returns: T: The removed instance.
remove
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT
def remove_by_name(self, instance_id: str) -> T: """Attempts to remove an instance from the suite by its name. Args: instance_id (str): The instance to remove from the suite. Returns: T: The instance that was removed. """ assert isinstance(instance_id, str) instance = self._type_groups[self._base_type].get_instance_by_id(instance_id) return self.remove(instance=instance)
Attempts to remove an instance from the suite by its name. Args: instance_id (str): The instance to remove from the suite. Returns: T: The instance that was removed.
remove_by_name
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT
def remove_by_type(self, requested_type: Type[T]) -> T: """Attempts to remove an instance from the suite by its type. Args: requested_type (Type[T]): The type of instance to remove. Raises: TypeError: The type is not a sub-class of the type this suite manages. Returns: T: The instance that was removed. """ self._assert_is_managed(requested_type=requested_type) instance = self._type_groups[self._base_type].get_instance_by_type( requested_type ) return self.remove(instance=instance)
Attempts to remove an instance from the suite by its type. Args: requested_type (Type[T]): The type of instance to remove. Raises: TypeError: The type is not a sub-class of the type this suite manages. Returns: T: The instance that was removed.
remove_by_type
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT
def get_by_id(self, instance_id: str) -> Optional[T]: """Get an instance by its name. Args: instance_id (str): The name of the instance to retrieve. Returns: Optional[T]: The instance if it exists. """ assert isinstance(instance_id, str), "Id must be a string." return self._type_groups[self._base_type].get_instance_by_id(instance_id)
Get an instance by its name. Args: instance_id (str): The name of the instance to retrieve. Returns: Optional[T]: The instance if it exists.
get_by_id
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT
def get_by_type(self, requested_type: Type[T]) -> Optional[T]: """Get an instance of the exact given type. Args: requested_type (Type[T]): The type of instance to find. Raises: TypeError: The type is not a sub-class of the type this suite manages. Returns: Optional[T]: The instance if it exists. """ self._assert_is_managed(requested_type=requested_type) return self._type_groups[self._base_type].get_instance_by_type( instance_type=requested_type )
Get an instance of the exact given type. Args: requested_type (Type[T]): The type of instance to find. Raises: TypeError: The type is not a sub-class of the type this suite manages. Returns: Optional[T]: The instance if it exists.
get_by_type
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT
def get_all_by_type(self, requested_type: Type[S]) -> List[S]: """Gets all instances that are a sub-type of the given type. Args: requested_type (Type[T]): The type to query for. Raises: TypeError: The type is not a sub-class of the type this suite manages. Returns: Optional[T]: """ self._assert_is_managed(requested_type=requested_type) return self._type_groups[requested_type].instances
Gets all instances that are a sub-type of the given type. Args: requested_type (Type[T]): The type to query for. Raises: TypeError: The type is not a sub-class of the type this suite manages. Returns: Optional[T]:
get_all_by_type
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT
def instances(self) -> List[T]: """Gets all instances that this suite manages. This will contain all instances that that are instances of the base class T. Returns: List[T]: A list of instances this suite manages. """ if len(self._type_groups) == 0: return [] return self._type_groups[self._base_type].instances
Gets all instances that this suite manages. This will contain all instances that that are instances of the base class T. Returns: List[T]: A list of instances this suite manages.
instances
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT
def is_valid_locator(locator: str): """Validate the given locator.""" # Handle non-URL-based agents (e.g. open_agent-v0) return NAME_CONSTRAINT_REGEX.search(locator)
Validate the given locator.
is_valid_locator
python
huawei-noah/SMARTS
smarts/core/utils/class_factory.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/class_factory.py
MIT
def find_attribute_spec(name): """Finds the attribute specification from a reachable module. Args: name: The module and attribute name (i.e. smarts.core.lidar:Lidar, ...) """ module_name, attribute_name = name.split(":") module = importlib.import_module(module_name) attribute_spec = getattr(module, attribute_name) return attribute_spec
Finds the attribute specification from a reachable module. Args: name: The module and attribute name (i.e. smarts.core.lidar:Lidar, ...)
find_attribute_spec
python
huawei-noah/SMARTS
smarts/core/utils/class_factory.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/class_factory.py
MIT
def make(self, **kwargs): """Provides an object from the entrypoint. Overriding predefined keyword arguments with the given keyword arguments. """ if self.entrypoint is None: raise AttributeError(f"Entry-point does not exist for name `{self.name}`") _kwargs = self._kwargs.copy() _kwargs.update(kwargs) if callable(self.entrypoint): instance = self.entrypoint(**_kwargs) else: type_spec = find_attribute_spec(self.entrypoint) instance = type_spec(**_kwargs) return instance
Provides an object from the entrypoint. Overriding predefined keyword arguments with the given keyword arguments.
make
python
huawei-noah/SMARTS
smarts/core/utils/class_factory.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/class_factory.py
MIT
def register(self, name, entry_point=None, **kwargs): """Registers a new factory with the given locator as the key. Args: locator: The key value of the factory. entry_point: The factory method. kwargs: Predefined arguments to the factory method. """ if name in self.index: warnings.warn( f"Resident named '{name}' was already registered. Overwriting existing registration." ) self.index[name] = ClassFactory(name, entry_point, **kwargs)
Registers a new factory with the given locator as the key. Args: locator: The key value of the factory. entry_point: The factory method. kwargs: Predefined arguments to the factory method.
register
python
huawei-noah/SMARTS
smarts/core/utils/class_factory.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/class_factory.py
MIT
def find_factory(self, locator): """Locates a factory given a locator.""" self._raise_on_invalid_locator(locator) mod_name, _, name = locator.partition(":") if name != "": # There is a module component. try: # Import the module so that the agent may register itself in the index # it is assumed that a `register(name=..., entry_point=...)` exists in the target module. module = importlib.import_module(mod_name) except ImportError as exc: import sys raise ImportError( f"Ensure that `{mod_name}` module can be found from your " f"PYTHONPATH and name=`{locator}` exists (e.g. was registered " "manually or downloaded).\n" f"`PYTHONPATH`: `{sys.path}`" ) from exc else: # There is no module component. name = mod_name try: # See if `register()` has been called. # return the builder if it exists. return self.index[name] except KeyError as exc: raise NameError(f"Locator not registered in lookup: {locator}") from exc
Locates a factory given a locator.
find_factory
python
huawei-noah/SMARTS
smarts/core/utils/class_factory.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/class_factory.py
MIT
def make(self, locator, **kwargs): """Calls the factory with `locator` name key supplying the keyword arguments as argument overrides. """ factory = self.find_factory(locator) instance = factory.make(**kwargs) return instance
Calls the factory with `locator` name key supplying the keyword arguments as argument overrides.
make
python
huawei-noah/SMARTS
smarts/core/utils/class_factory.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/class_factory.py
MIT
def all(self): """Lists all available factory objects.""" return self.index.values()
Lists all available factory objects.
all
python
huawei-noah/SMARTS
smarts/core/utils/class_factory.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/class_factory.py
MIT
def raise_import_error(): """A method which when called invokes an ImportError exception.""" raise ImportError()
A method which when called invokes an ImportError exception.
raise_import_error
python
huawei-noah/SMARTS
smarts/core/utils/invalid/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/invalid/__init__.py
MIT
def ego_centric_observation_adapter(obs: Observation, *args: Any, **kwargs: Any) -> Any: """An observation adapter that converts the observation to an ego-centric perspective.""" position = obs.ego_vehicle_state.position heading = obs.ego_vehicle_state.heading def ego_frame_dynamics(v): return np.array([np.linalg.norm(v[:2]), 0, *v[2:]]) # point to X def transform(v): return position_to_ego_frame(v, position, heading) def adjust_heading(h): return wrap_value(h - heading, -math.pi, math.pi) nvs = obs.neighborhood_vehicle_states or [] wpps = obs.waypoint_paths or [] def _replace_via(via: Union[Via, ViaPoint]): return _replace(via, position=transform(via.position + (0.0,))) vd = None if obs.via_data: rpvp = lambda vps: [_replace_via(vp) for vp in vps] vd = _replace( obs.via_data, near_via_points=rpvp(obs.via_data.near_via_points), ) replace_wps = lambda lwps: [ [ _replace( wp, pos=transform(np.append(wp.pos, [0]))[:2], heading=Heading(adjust_heading(wp.heading)), ) for wp in wps ] for wps in lwps ] rwps = None if obs.road_waypoints: rwps = _replace( obs.road_waypoints, lanes={ l_id: replace_wps(wps) for l_id, wps in obs.road_waypoints.lanes.items() }, ) replace_metadata = lambda cam_obs: _replace( cam_obs, metadata=_replace( cam_obs.metadata, camera_position=(0, 0, 0), camera_heading=0 ), ) def _optional_replace_goal(goal): if isinstance(goal, PositionalGoal): return {"goal": _replace(goal, position=transform(tuple(goal.position)))} return {} def _replace_lidar(lidar): if len(lidar) == 0: return [] return [ [transform(hit_point) for hit_point in lidar[0]], lidar[1], [ [transform(ray_start), transform(ray_end)] for ray_start, ray_end in lidar[2] ], ] return _replace( obs, ego_vehicle_state=_replace( obs.ego_vehicle_state, position=np.array([0, 0, 0]), heading=Heading(0), linear_velocity=ego_frame_dynamics(obs.ego_vehicle_state.linear_velocity), linear_acceleration=ego_frame_dynamics( obs.ego_vehicle_state.linear_acceleration ), linear_jerk=ego_frame_dynamics(obs.ego_vehicle_state.linear_jerk), mission=_replace( obs.ego_vehicle_state.mission, start=_replace( obs.ego_vehicle_state.mission.start, position=transform( np.append(obs.ego_vehicle_state.mission.start.position, [0]) )[:2], heading=adjust_heading(obs.ego_vehicle_state.mission.start.heading), ), via=tuple( _replace_via(via) for via in obs.ego_vehicle_state.mission.via ), **_optional_replace_goal(obs.ego_vehicle_state.mission.goal), # TODO??: `entry_tactic.zone` zone.position? ), ), neighborhood_vehicle_states=[ _replace( nv, position=transform(nv.position), heading=Heading(adjust_heading(nv.heading)), ) for nv in nvs ], lidar_point_cloud=_replace_lidar(obs.lidar_point_cloud), waypoint_paths=replace_wps(wpps), drivable_area_grid_map=replace_metadata(obs.drivable_area_grid_map), occupancy_grid_map=replace_metadata(obs.occupancy_grid_map), top_down_rgb=replace_metadata(obs.top_down_rgb), road_waypoints=rwps, via_data=vd, )
An observation adapter that converts the observation to an ego-centric perspective.
ego_centric_observation_adapter
python
huawei-noah/SMARTS
smarts/core/utils/adapters/ego_centric_adapters.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/adapters/ego_centric_adapters.py
MIT
def _pair_adapters( ego_centric_observation_adapter: Callable[[Observation], Observation], ego_centric_action_adapter: Callable[[Any, Optional[Observation]], Any], ): """Wrapper that shares the state between both adapters.""" last_obs = None def oa_wrapper(obs: Observation): nonlocal last_obs last_obs = obs # Store the unmodified observation return ego_centric_observation_adapter(obs) def aa_wrapper(act: Any): nonlocal last_obs # Pass the last unmodified obs to the action for conversion purposes return ego_centric_action_adapter(act, last_obs) return oa_wrapper, aa_wrapper
Wrapper that shares the state between both adapters.
_pair_adapters
python
huawei-noah/SMARTS
smarts/core/utils/adapters/ego_centric_adapters.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/adapters/ego_centric_adapters.py
MIT
def get_egocentric_adapters(action_space: ActionSpaceType): """Provides a set of adapters that share state information of the unmodified observation. This will allow the action adapter to automatically convert back to world space for SMARTS. Returns: (obs_adapter, action_adapter) """ m = { ActionSpaceType.Continuous: _egocentric_continuous_action_adapter, ActionSpaceType.ActuatorDynamic: _egocentric_actuator_dynamic_adapter, ActionSpaceType.Lane: _egocentric_lane_adapter, ActionSpaceType.LaneWithContinuousSpeed: _egocentric_lane_with_continous_speed_adapter, ActionSpaceType.Trajectory: _egocentric_trajectory_adapter, ActionSpaceType.TrajectoryWithTime: _egocentric_trajectory_with_time_adapter, ActionSpaceType.MPC: _egocentric_mpc_adapter, ActionSpaceType.TargetPose: _egocentric_target_pose_adapter, ActionSpaceType.MultiTargetPose: _egocentric_multi_target_pose_adapter, ActionSpaceType.Direct: _egocentric_direct_adapter, ActionSpaceType.Empty: lambda _: None, } return _pair_adapters(ego_centric_observation_adapter, m.get(action_space))
Provides a set of adapters that share state information of the unmodified observation. This will allow the action adapter to automatically convert back to world space for SMARTS. Returns: (obs_adapter, action_adapter)
get_egocentric_adapters
python
huawei-noah/SMARTS
smarts/core/utils/adapters/ego_centric_adapters.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/adapters/ego_centric_adapters.py
MIT
def collect( self, vehicles_with_sensors: Optional[Sequence[int]], headless: bool = True ): """Records SMARTS observations for selected vehicles. Args: vehicles_with_sensors (Sequence[int], optional): A list of vehicle_ids within the scenario to which to attach sensors and record Observations. If not specified, this will default the ego vehicle of the scenario if there is one. If not, this will default to all vehicles in the scenario. headless (bool, optional): Whether to run the simulation in headless mode. Defaults to True. """ assert self._scenario and self._scenario.traffic_history is not None # In case we have any bubbles or additional non-history traffic # in the scenario, we need to add some traffic providers. traffic_sims = [] if self._scenario.supports_sumo_traffic: sumo_traffic = SumoTrafficSimulation() traffic_sims += [sumo_traffic] smarts_traffic = LocalTrafficProvider() traffic_sims += [smarts_traffic] # The actual SMARTS instance to be used for the simulation self._smarts = SMARTS( agent_interfaces=dict(), traffic_sims=traffic_sims, envision=None if headless else Envision(), ) # could also include "motorcycle" or "truck" in this set if desired vehicle_types = frozenset({"car"}) collected_data = {} off_road_vehicles = set() selected_vehicles = set() if not vehicles_with_sensors: ego_id = self._scenario.traffic_history.ego_vehicle_id if ego_id is not None: vehicles_with_sensors = [ego_id] self._logger.warning( f"No vehicle IDs specifed. Defaulting to ego vehicle ({ego_id})" ) else: vehicles_with_sensors = self._scenario.traffic_history.all_vehicle_ids() self._logger.warning( f"No vehicle IDs specifed. Defaulting to all vehicles" ) max_sim_time = 0 all_vehicles = set(self._scenario.traffic_history.all_vehicle_ids()) for v_id in vehicles_with_sensors: if v_id not in all_vehicles: self._logger.warning(f"Vehicle {v_id} not in scenario") continue config_type = self._scenario.traffic_history.vehicle_config_type(v_id) veh_type = ( VEHICLE_CONFIGS[config_type].vehicle_type if config_type in VEHICLE_CONFIGS else None ) if veh_type not in vehicle_types: self._logger.warning( f"Vehicle type for vehicle {v_id} ({veh_type}) not in selected vehicle types ({vehicle_types})" ) continue # TODO: get prefixed vehicle_id from TrafficHistoryProvider selected_vehicles.add(f"history-vehicle-{v_id}") exit_time = self._scenario.traffic_history.vehicle_final_exit_time(v_id) if exit_time > max_sim_time: max_sim_time = exit_time if not selected_vehicles: self._logger.error("No valid vehicles specified. Aborting.") return _ = self._smarts.reset(self._scenario, self._start_time) current_vehicles = self._smarts.vehicle_index.social_vehicle_ids( vehicle_types=vehicle_types ) self._record_data( collected_data, current_vehicles, off_road_vehicles, selected_vehicles, max_sim_time, ) while True: if self._smarts.elapsed_sim_time > max_sim_time: self._logger.info("All observed vehicles are finished. Exiting...") break self._smarts.step({}) current_vehicles = self._smarts.vehicle_index.social_vehicle_ids( vehicle_types=vehicle_types ) if collected_data and not current_vehicles: self._logger.info("No more vehicles. Exiting...") break self._record_data( collected_data, current_vehicles, off_road_vehicles, selected_vehicles, max_sim_time, ) if self._output_dir: # Get original missions for all vehicles missions = dict() orig_missions = self._scenario.discover_missions_of_traffic_histories() for v_id, mission in orig_missions.items(): # TODO: get prefixed vehicle_id from TrafficHistoryProvider veh_id = f"history-vehicle-{v_id}" missions[veh_id] = mission # Save recorded observations as pickle files for car, data in collected_data.items(): # Fill in mission with proper goal position for all observations last_t = max(data.keys()) last_state = data[last_t].ego_vehicle_state goal_pos = Point(last_state.position[0], last_state.position[1]) new_mission = replace( missions[last_state.id], goal=PositionalGoal(goal_pos, radius=3) ) for t in data.keys(): ego_state = data[t].ego_vehicle_state new_ego_state = ego_state._replace(mission=new_mission) data[t] = data[t]._replace(ego_vehicle_state=new_ego_state) # Create terminal state for last timestep, when the vehicle reaches the goal events = data[last_t].events new_events = events._replace(reached_goal=True) data[last_t] = data[last_t]._replace(events=new_events) outfile = os.path.join( self._output_dir, f"{car}.pkl", ) with open(outfile, "wb") as of: pickle.dump(data, of) self._smarts.destroy()
Records SMARTS observations for selected vehicles. Args: vehicles_with_sensors (Sequence[int], optional): A list of vehicle_ids within the scenario to which to attach sensors and record Observations. If not specified, this will default the ego vehicle of the scenario if there is one. If not, this will default to all vehicles in the scenario. headless (bool, optional): Whether to run the simulation in headless mode. Defaults to True.
collect
python
huawei-noah/SMARTS
smarts/dataset/traffic_histories_to_observations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/dataset/traffic_histories_to_observations.py
MIT
def init(self): """Initializer for the purposes of maintaining a singleton of this class.""" self._render_lock = Lock() try: # There can be only 1 ShowBase instance at a time. super().__init__(windowType="offscreen") gltf.patch_loader(self.loader) self.setBackgroundColor(0, 0, 0, 1) # Displayed framerate is misleading since we are not using a realtime clock self.setFrameRateMeter(False) except Exception as e: raise e
Initializer for the purposes of maintaining a singleton of this class.
init
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def set_rendering_verbosity(cls, debug_mode: DEBUG_MODE): """Set rendering debug information verbosity.""" cls._debug_mode = debug_mode loadPrcFileData("", f"notify-level {cls._debug_mode.name.lower()}") loadPrcFileData( "", f"default-directnotify-level {cls._debug_mode.name.lower()}" )
Set rendering debug information verbosity.
set_rendering_verbosity
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def set_rendering_backend( cls, rendering_backend: BACKEND_LITERALS, ): """Sets the rendering backend.""" if "__it__" not in cls.__dict__: cls._rendering_backend = rendering_backend else: if cls._rendering_backend != rendering_backend: warnings.warn("Cannot apply rendering backend after setup.")
Sets the rendering backend.
set_rendering_backend
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def destroy(self): """Destroy this renderer and clean up all remaining resources.""" super().destroy() self.__class__.__it__ = None
Destroy this renderer and clean up all remaining resources.
destroy
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def setup_sim_root(self, simid: str): """Creates the simulation root node in the scene graph.""" root_np = NodePath(simid) with self._render_lock: root_np.reparentTo(self.render) with pkg_resources.path( glsl, "unlit_shader.vert" ) as vshader_path, pkg_resources.path( glsl, "unlit_shader.frag" ) as fshader_path: unlit_shader = Shader.load( Shader.SL_GLSL, vertex=str(vshader_path.absolute()), fragment=str(fshader_path.absolute()), ) root_np.setShader(unlit_shader, priority=10) return root_np
Creates the simulation root node in the scene graph.
setup_sim_root
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def render_node(self, sim_root: NodePath): """Render a panda3D scene graph from the given node.""" # Hack to prevent other SMARTS instances from also rendering # when we call poll() here. hidden = [] with self._render_lock: for node_path in self.render.children: if node_path != sim_root and not node_path.isHidden(): node_path.hide() hidden.append(node_path) self.taskMgr.mgr.poll() for node_path in hidden: node_path.show()
Render a panda3D scene graph from the given node.
render_node
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.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 for i in range(retries): if self.tex.mightHaveRamImage(): break getattr(self, "renderer").log.debug( f"No image available (attempt {i}/{retries}), forcing a render" ) region = self.buffer.getDisplayRegion(0) region.window.engine.renderFrame() assert self.tex.mightHaveRamImage() ram_image = self.tex.getRamImageAs(img_format) assert ram_image is not None return ram_image
Attempt to acquire a graphics buffer.
wait_for_ram_image
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def image_dimensions(self): """The dimensions of the output camera image.""" return (self.tex.getXSize(), self.tex.getYSize())
The dimensions of the output camera image.
image_dimensions
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.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/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def padding(self) -> Tuple[int, int, int, int]: """The padding on the image. This follows the "css" convention: (top, left, bottom, right).""" return self.tex.getPadYSize(), self.tex.getPadXSize(), 0, 0
The padding on the image. This follows the "css" convention: (top, left, bottom, right).
padding
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def heading(self) -> float: """The heading of this camera.""" return np.radians(self.camera_np.getH())
The heading of this camera.
heading
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def teardown(self): """Clean up internal resources.""" self.camera_np.removeNode() region = self.buffer.getDisplayRegion(0) region.window.clearRenderTextures() self.buffer.removeAllDisplayRegions() getattr(self, "renderer").remove_buffer(self.buffer)
Clean up internal resources.
teardown
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def update(self, pose: Pose, height: float, *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. """ pos, heading = pose.as_panda3d() self.camera_np.setPos(pos[0], pos[1], height) self.camera_np.lookAt(*pos) self.camera_np.setH(heading)
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/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def should_get_data(self, buffer_id: BufferID, observation: Observation): """If the buffer can and should get data from the observation.""" if ( buffer_id in self._acceleration_set and observation.ego_vehicle_state.linear_acceleration is None ): return False elif ( buffer_id in self._jerk_set and observation.ego_vehicle_state.linear_jerk is None ): return False elif buffer_id in self._waypoints_set and ( observation.waypoint_paths is None or len(observation.waypoint_paths) == 0 ): return False elif buffer_id in self._road_waypoints_set and ( observation.road_waypoints is None or len(observation.road_waypoints.lanes) == 0 ): return False elif ( buffer_id in self._via_near_set and len(observation.via_data.near_via_points) == 0 ): return False elif buffer_id in self._signals_set and ( observation.signals is None or len(observation.signals) > 0 ): return False elif buffer_id in self._lidar_set and (observation.lidar_point_cloud is None): return False return True
If the buffer can and should get data from the observation.
should_get_data
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def get_data_for_buffer(self, buffer_id: BufferID, observation: Observation): """Retrieve the data buffer from the observation.""" if len(self._static_methods) == 0: self._gen_methods_for_buffer() return self._static_methods.get(buffer_id, lambda o, m: None)( observation, self._get_memo_for_buffer(buffer_id) )
Retrieve the data buffer from the observation.
get_data_for_buffer
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def update( self, pose: Optional[Pose] = None, height: Optional[float] = None, observation: Optional[Observation] = None, **kwargs, ): """Update the location of the shader directional values. Args: pose: The pose of the camera target. height: The height of the camera above the camera target. """ inputs = {} if pose is not None: self.fullscreen_quad_node.setShaderInputs( iHeading=pose.heading, iTranslation=(pose.point.x, pose.point.y), ) inputs["iHeading"] = pose.heading inputs["iTranslation"] = (pose.point.x, pose.point.y) if height is not None: inputs["iElevation"] = height if len(self.buffer_dependencies) == 0: return buffers = set(self.buffer_dependencies) if observation is not None: ba = _BufferAccessor() for b in buffers: if ba.should_get_data(b.buffer_id, observation): inputs[b.script_uniform_name] = ba.get_data_for_buffer( b.buffer_id, observation ) if inputs: self.fullscreen_quad_node.setShaderInputs(**inputs)
Update the location of the shader directional values. Args: pose: The pose of the camera target. height: The height of the camera above the camera target.
update
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def id(self): """The id of the simulation rendered.""" return self._simid
The id of the simulation rendered.
id
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def is_setup(self) -> bool: """If the renderer has been fully initialized.""" return self._is_setup
If the renderer has been fully initialized.
is_setup
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def log(self) -> logging.Logger: """The rendering logger.""" return self._log
The rendering logger.
log
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def remove_buffer(self, buffer): """Remove the rendering buffer.""" self._showbase_instance.graphicsEngine.removeWindow(buffer)
Remove the rendering buffer.
remove_buffer
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def load_road_map(self, map_path: Union[str, Path]): """Load the road map from its path.""" # Load map self._ensure_root() if self._road_map_np: self._log.debug( "road_map=%s already exists. Removing and adding a new " "one from glb_path=%s", self._road_map_np, map_path, ) with suppress_output(): map_np = self._showbase_instance.loader.loadModel(map_path, noCache=True) node_path = self._root_np.attachNewNode("road_map") map_np.reparent_to(node_path) node_path.hide(RenderMasks.OCCUPANCY_HIDE) node_path.setColor(SceneColors.Road.value) self._road_map_np = node_path self._is_setup = True return map_np.getBounds()
Load the road map from its path.
load_road_map
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def setup(self, scenario: StaticScenario): """Initialize this renderer.""" self._ensure_root() self._vehicles_np = self._root_np.attachNewNode("vehicles") self._signals_np = self._root_np.attachNewNode("signals") map_path = scenario.map_glb_filepath map_dir = Path(map_path).parent # Load map self.load_road_map(map_path) # Road lines (solid, yellow) road_lines_path = map_dir / "road_lines.glb" if road_lines_path.exists(): road_lines_np = self._load_line_data(road_lines_path, "road_lines") solid_lines_np = self._root_np.attachNewNode(road_lines_np) solid_lines_np.setColor(SceneColors.EdgeDivider.value) solid_lines_np.hide(RenderMasks.OCCUPANCY_HIDE) solid_lines_np.setRenderModeThickness(2) # Lane lines (dashed, white) lane_lines_path = map_dir / "lane_lines.glb" if lane_lines_path.exists(): lane_lines_np = self._load_line_data(lane_lines_path, "lane_lines") dashed_lines_np = self._root_np.attachNewNode(lane_lines_np) dashed_lines_np.setColor(SceneColors.LaneDivider.value) dashed_lines_np.hide(RenderMasks.OCCUPANCY_HIDE) dashed_lines_np.setRenderModeThickness(2) with pkg_resources.path( glsl, "dashed_line_shader.vert" ) as vshader_path, pkg_resources.path( glsl, "dashed_line_shader.frag" ) as fshader_path: dashed_line_shader = Shader.load( Shader.SL_GLSL, vertex=str(vshader_path.absolute()), fragment=str(fshader_path.absolute()), ) dashed_lines_np.setShader(dashed_line_shader, priority=20) dashed_lines_np.setShaderInput( "iResolution", self._showbase_instance.getSize() ) self._dashed_lines_np = dashed_lines_np if scenario_metadata := scenario.metadata: if interest_pattern := scenario_metadata.get( "actor_of_interest_re_filter", None ): self._interest_filter = re.compile(interest_pattern) self._interest_color = scenario_metadata.get( "actor_of_interest_color", SceneColors.SocialAgent ) self._is_setup = True
Initialize this renderer.
setup
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def render(self): """Render the scene graph of the simulation.""" if not self._is_setup: self._ensure_root() warnings.warn( "Renderer is not setup. Rendering before scene setup may be unintentional.", RendererNotSetUpWarning, ) self._showbase_instance.render_node(self._root_np)
Render the scene graph of the simulation.
render
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def reset(self): """Reset the render back to initialized state.""" if self._vehicles_np is not None: self._vehicles_np.removeNode() self._vehicles_np = self._root_np.attachNewNode("vehicles") if self._signals_np is not None: self._signals_np.removeNode() self._signals_np = self._root_np.attachNewNode("signals") self._vehicle_nodes = {} self._signal_nodes = {}
Reset the render back to initialized state.
reset
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def step(self): """provided for non-SMARTS uses; normally not used by SMARTS.""" self._showbase_instance.taskMgr.step()
provided for non-SMARTS uses; normally not used by SMARTS.
step
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def sync(self, sim_frame: SimulationFrame): """Update the current state of the vehicles and signals within the renderer.""" signal_ids = set() for actor_id, actor_state in sim_frame.actor_states_by_id.items(): if isinstance(actor_state, VehicleState): self.update_vehicle_node(actor_id, actor_state.pose) elif isinstance(actor_state, SignalState): signal_ids.add(actor_id) color = signal_state_to_color(actor_state.state) if actor_id not in self._signal_nodes: self.create_signal_node(actor_id, actor_state.stopping_pos, color) self.begin_rendering_signal(actor_id) else: self.update_signal_node(actor_id, actor_state.stopping_pos, color) missing_vehicle_ids = set(self._vehicle_nodes) - set(sim_frame.vehicle_ids) missing_signal_ids = set(self._signal_nodes) - signal_ids for vid in missing_vehicle_ids: self.remove_vehicle_node(vid) for sig_id in missing_signal_ids: self.remove_signal_node(sig_id)
Update the current state of the vehicles and signals within the renderer.
sync
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def teardown(self): """Clean up internal resources.""" if self._root_np is not None: self._root_np.clearLight() self._root_np.removeNode() self._root_np = None self._vehicles_np = None for sig_id in list(self._signal_nodes): self.remove_signal_node(sig_id) self._signals_np = None self._road_map_np = None self._dashed_lines_np = None self._is_setup = False
Clean up internal resources.
teardown
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def destroy(self): """Destroy the renderer. Cleans up all remaining renderer resources.""" self.teardown() self._showbase_instance = None
Destroy the renderer. Cleans up all remaining renderer resources.
destroy
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def set_interest(self, interest_filter: re.Pattern, interest_color: Colors): """Sets the color of all vehicles that have ids that match the given pattern. Args: interest_filter (re.Pattern): The regular expression pattern to match. interest_color (Colors): The color that the vehicle should show as. """ assert isinstance(interest_filter, re.Pattern) self._interest_filter = interest_filter self._interest_color = interest_color
Sets the color of all vehicles that have ids that match the given pattern. Args: interest_filter (re.Pattern): The regular expression pattern to match. interest_color (Colors): The color that the vehicle should show as.
set_interest
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def create_vehicle_node( self, glb_model: Union[str, Path], vid: str, color: Union[Colors, SceneColors], pose: Pose, ): """Create a vehicle node.""" if vid in self._vehicle_nodes: return False node_path = self._showbase_instance.loader.loadModel(glb_model) node_path.setName("vehicle-%s" % vid) if ( self._interest_filter is not None and self._interest_color is not None and self._interest_filter.match(vid) ): node_path.setColor(self._interest_color.value) else: node_path.setColor(color.value) pos, heading = pose.as_panda3d() node_path.setPosHpr(*pos, heading, 0, 0) node_path.hide(RenderMasks.DRIVABLE_AREA_HIDE) if color in (SceneColors.Agent,): node_path.hide(RenderMasks.OCCUPANCY_HIDE) self._vehicle_nodes[vid] = node_path return True
Create a vehicle node.
create_vehicle_node
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def begin_rendering_vehicle(self, vid: str, is_agent: bool): """Add the vehicle node to the scene graph""" vehicle_path = self._vehicle_nodes.get(vid, None) if not vehicle_path: self._log.warning("Renderer ignoring invalid vehicle id: %s", vid) return vehicle_path.reparentTo(self._vehicles_np)
Add the vehicle node to the scene graph
begin_rendering_vehicle
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def update_vehicle_node(self, vid: str, pose: Pose): """Move the specified vehicle node.""" vehicle_path = self._vehicle_nodes.get(vid, None) if not vehicle_path: self._log.warning("Renderer ignoring invalid vehicle id: %s", vid) return pos, heading = pose.as_panda3d() vehicle_path.setPosHpr(*pos, heading, 0, 0)
Move the specified vehicle node.
update_vehicle_node
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def remove_vehicle_node(self, vid: str): """Remove a vehicle node""" vehicle_path = self._vehicle_nodes.get(vid, None) if not vehicle_path: self._log.warning("Renderer ignoring invalid vehicle id: %s", vid) return vehicle_path.removeNode() del self._vehicle_nodes[vid]
Remove a vehicle node
remove_vehicle_node
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def create_signal_node( self, sig_id: str, position: Point, color: Union[Colors, SceneColors] ): """Create a signal node.""" if sig_id in self._signal_nodes: return False # Create geometry node name = f"signal-{sig_id}" geo_format = GeomVertexFormat.getV3() vdata = GeomVertexData(name, geo_format, Geom.UHStatic) vertex = GeomVertexWriter(vdata, "vertex") num_pts = 10 # number of points around the circumference seg_radians = 2 * math.pi / num_pts vertex.addData3(0, 0, 0) for i in range(num_pts): angle = i * seg_radians x = math.cos(angle) y = math.sin(angle) vertex.addData3(x, y, 0) prim = GeomTrifans(Geom.UHStatic) prim.addVertex(0) # add center point prim.add_next_vertices(num_pts) # add outer points prim.addVertex(1) # add first outer point again to complete the circle assert prim.closePrimitive() geom = Geom(vdata) geom.addPrimitive(prim) geom_node = GeomNode(name) geom_node.addGeom(geom) node_path = self._root_np.attachNewNode(geom_node) node_path.setName(name) node_path.setColor(color.value) node_path.setPos(position.x, position.y, 0.01) node_path.setScale(0.9, 0.9, 1) node_path.hide(RenderMasks.DRIVABLE_AREA_HIDE) self._signal_nodes[sig_id] = node_path return True
Create a signal node.
create_signal_node
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def begin_rendering_signal(self, sig_id: str): """Add the signal node to the scene graph""" signal_np = self._signal_nodes.get(sig_id, None) if not signal_np: self._log.warning("Renderer ignoring invalid signal id: %s", sig_id) return signal_np.reparentTo(self._signals_np)
Add the signal node to the scene graph
begin_rendering_signal
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def update_signal_node( self, sig_id: str, position: Point, color: Union[Colors, SceneColors] ): """Move the specified signal node.""" signal_np = self._signal_nodes.get(sig_id, None) if not signal_np: self._log.warning("Renderer ignoring invalid signal id: %s", sig_id) return signal_np.setPos(position.x, position.y, 0.01) signal_np.setColor(color.value)
Move the specified signal node.
update_signal_node
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def remove_signal_node(self, sig_id: str): """Remove a signal node""" signal_np = self._signal_nodes.get(sig_id, None) if not signal_np: self._log.warning("Renderer ignoring invalid signal id: %s", sig_id) return signal_np.removeNode() del self._signal_nodes[sig_id]
Remove a signal node
remove_signal_node
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def camera_for_id(self, camera_id: str) -> Union[P3DOffscreenCamera, P3DShaderStep]: """Get a camera by its id.""" camera = self._camera_nodes.get(camera_id) assert ( camera is not None ), f"Camera {camera_id} does not exist, have you created this camera?" return camera
Get a camera by its id.
camera_for_id
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def build_offscreen_camera( self, name: str, mask: int, width: int, height: int, resolution: float, ) -> None: """Generates a new off-screen camera.""" # setup buffer win_props = WindowProperties.size(width, height) fb_props = FrameBufferProperties() fb_props.setRgbColor(True) fb_props.setRgbaBits(8, 8, 8, 1) # XXX: Though we don't need the depth buffer returned, setting this to 0 # causes undefined behavior where the ordering of meshes is random. fb_props.setDepthBits(8) buffer = self._showbase_instance.win.engine.makeOutput( self._showbase_instance.pipe, "{}-buffer".format(name), -100, fb_props, win_props, GraphicsPipe.BFRefuseWindow, self._showbase_instance.win.getGsg(), self._showbase_instance.win, ) buffer.setClearColor((0, 0, 0, 0)) # Set background color to black # Necessary for the lane lines to be in the proper proportions if self._dashed_lines_np is not None: self._dashed_lines_np.setShaderInput( "iResolution", (buffer.size.x, buffer.size.y) ) # setup texture tex = Texture() region = buffer.getDisplayRegion(0) region.window.addRenderTexture( tex, GraphicsOutput.RTM_copy_ram, GraphicsOutput.RTP_color ) # setup camera lens = OrthographicLens() lens.setFilmSize(width * resolution, height * resolution) camera_np = self._showbase_instance.makeCamera( buffer, camName=name, scene=self._root_np, lens=lens ) camera_np.reparentTo(self._root_np) # mask is set to make undesirable objects invisible to this camera camera_np.node().setCameraMask(camera_np.node().getCameraMask() & mask) camera = P3DOffscreenCamera(self, camera_np, buffer, tex) self._camera_nodes[name] = camera
Generates a new off-screen camera.
build_offscreen_camera
python
huawei-noah/SMARTS
smarts/p3d/renderer.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/p3d/renderer.py
MIT
def log_everything_to_ROS(level=None): """ Calling this will add a LogToROSHandler handler object to the root logger. Any logger that propagates its messages to the root handler (most do by default) will also have its messages logged via the rospy logging topics. If level is passed, the the root logger level will be set to this for all non-ROS messages. NOTE: In order to avoid an infinite recursion, the `propagate` property will be set to `False` on any existing loggers whose name starts with "ros". (All of the rospy loggers start with this string.) """ root = logging.getLogger(None) for logger_name, logger in root.manager.loggerDict.items(): if logger_name.startswith("ros"): logger.propagate = False ros_handler = LogToROSHandler() if level is not None: ros_handler.setLevel(level) root.addHandler(ros_handler)
Calling this will add a LogToROSHandler handler object to the root logger. Any logger that propagates its messages to the root handler (most do by default) will also have its messages logged via the rospy logging topics. If level is passed, the the root logger level will be set to this for all non-ROS messages. NOTE: In order to avoid an infinite recursion, the `propagate` property will be set to `False` on any existing loggers whose name starts with "ros". (All of the rospy loggers start with this string.)
log_everything_to_ROS
python
huawei-noah/SMARTS
smarts/ros/logging.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/ros/logging.py
MIT
def setup_ros( self, node_name: str = "SMARTS", def_namespace: str = "SMARTS/", pub_queue_size: int = 10, ): """Set up the SMARTS ros test node.""" rospy.init_node(node_name, anonymous=True) # If the namespace is already set in the environment, we use it, # otherwise we use our default. namespace = def_namespace if not os.environ.get("ROS_NAMESPACE") else "" self._reset_publisher = rospy.Publisher( f"{namespace}reset", SmartsReset, queue_size=pub_queue_size ) self._agent_publisher = rospy.Publisher( f"{namespace}agent_spec", AgentSpec, queue_size=pub_queue_size ) self._entities_publisher = rospy.Publisher( f"{namespace}entities_in", EntitiesStamped, queue_size=pub_queue_size ) rospy.Subscriber(f"{namespace}agents_out", AgentsStamped, self._agents_callback) rospy.Subscriber( f"{namespace}entities_out", EntitiesStamped, self._entities_callback ) rospy.Subscriber(f"{namespace}reset", SmartsReset, self._reset_callback) service_name = f"{namespace}{node_name}_info" rospy.wait_for_service(service_name) self._smarts_info_srv = rospy.ServiceProxy(service_name, SmartsInfo) smarts_info = self._smarts_info_srv() rospy.loginfo(f"Tester detected SMARTS version={smarts_info.version}.")
Set up the SMARTS ros test node.
setup_ros
python
huawei-noah/SMARTS
smarts/ros/src/smarts_ros/scripts/test_smarts_ros.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/ros/src/smarts_ros/scripts/test_smarts_ros.py
MIT
def run_forever(self): """Publish the SMARTS ros test node and run indefinitely.""" if not self._smarts_info_srv: raise RuntimeError("must call setup_ros() first.") scenario = self._init_scenario() rospy.spin()
Publish the SMARTS ros test node and run indefinitely.
run_forever
python
huawei-noah/SMARTS
smarts/ros/src/smarts_ros/scripts/test_smarts_ros.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/ros/src/smarts_ros/scripts/test_smarts_ros.py
MIT
def setup_ros( self, node_name: str = "SMARTS", def_namespace: str = "SMARTS/", buffer_size: int = 3, target_freq: Optional[float] = None, time_ratio: float = 1.0, pub_queue_size: int = 10, ): """Set up the SMARTS ros node.""" assert not self._state_publisher # enforce only one SMARTS instance per ROS network... # NOTE: The node name specified here may be overridden by ROS # remapping arguments from the command line invocation. rospy.init_node(node_name, anonymous=False) # If the namespace is aready set in the environment, we use it, # otherwise we use our default. namespace = def_namespace if not os.environ.get("ROS_NAMESPACE") else "" self._service_name = f"{namespace}{node_name}_info" self._state_publisher = rospy.Publisher( f"{namespace}entities_out", EntitiesStamped, queue_size=pub_queue_size ) self._agents_publisher = rospy.Publisher( f"{namespace}agents_out", AgentsStamped, queue_size=pub_queue_size ) rospy.Subscriber(f"{namespace}reset", SmartsReset, self._smarts_reset_callback) self._state_topic = f"{namespace}entities_in" rospy.Subscriber(self._state_topic, EntitiesStamped, self._entities_callback) rospy.Subscriber(f"{namespace}agent_spec", AgentSpec, self._agent_spec_callback) buffer_size = rospy.get_param("~buffer_size", buffer_size) if buffer_size and buffer_size != self._recent_state.maxlen: assert buffer_size > 0 self._recent_state = deque(maxlen=buffer_size) # If target_freq is not specified, SMARTS is allowed to # run as quickly as it can with no delay between steps. target_freq = rospy.get_param("~target_freq", target_freq) if target_freq: assert target_freq > 0.0 self._target_freq = target_freq log_everything_to_ROS(level=logging.WARNING)
Set up the SMARTS ros node.
setup_ros
python
huawei-noah/SMARTS
smarts/ros/src/smarts_ros/scripts/ros_driver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/ros/src/smarts_ros/scripts/ros_driver.py
MIT
def setup_smarts( self, headless: bool = True, seed: int = 42, time_ratio: float = 1.0, sumo_traffic: bool = False, ): """Do the setup of the underlying SMARTS instance.""" assert not self._smarts if not self._state_publisher: raise RuntimeError("must call setup_ros() first.") self._zoo_module = rospy.get_param("~zoo_module", "zoo") headless = rospy.get_param("~headless", headless) seed = rospy.get_param("~seed", seed) time_ratio = rospy.get_param("~time_ratio", time_ratio) assert time_ratio > 0.0 self._time_ratio = time_ratio traffic_sim = None if rospy.get_param("~sumo_traffic", sumo_traffic): from smarts.core.sumo_traffic_simulation import SumoTrafficSimulation # Note that Sumo uses a fixed timestep, so if we have a highly-variable step rate, # we may want to set time_resolution to a mutiple of the target_freq? time_resolution = 1.0 / self._target_freq if self._target_freq else None traffic_sim = SumoTrafficSimulation( headless=headless, time_resolution=time_resolution, ) self._smarts = SMARTS( agent_interfaces={}, traffic_sims=[traffic_sim], fixed_timestep_sec=None, envision=None if headless else Envision(), external_provider=True, ) assert self._smarts.external_provider self._last_step_time = None
Do the setup of the underlying SMARTS instance.
setup_smarts
python
huawei-noah/SMARTS
smarts/ros/src/smarts_ros/scripts/ros_driver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/ros/src/smarts_ros/scripts/ros_driver.py
MIT
def stamp(self) -> float: """The estimated timestamp of this vehicle state.""" return self.vector[0]
The estimated timestamp of this vehicle state.
stamp
python
huawei-noah/SMARTS
smarts/ros/src/smarts_ros/scripts/ros_driver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/ros/src/smarts_ros/scripts/ros_driver.py
MIT
def average_with(self, other_vect: np.ndarray): """Update this vehicle state with the average between this state and the given new state. """ self.vector += other_vect self.vector /= 2 self.update_vehicle_state()
Update this vehicle state with the average between this state and the given new state.
average_with
python
huawei-noah/SMARTS
smarts/ros/src/smarts_ros/scripts/ros_driver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/ros/src/smarts_ros/scripts/ros_driver.py
MIT
def update_vehicle_state(self): """Update this vehicle state.""" assert len(self.vector) == 20 self.vs.pose = Pose.from_center( self.vector[1:4], Heading(self.vector[4] % (2 * math.pi)) ) self.vs.dimensions = Dimensions(*self.vector[5:8]) self.linear_velocity = self.vector[8:11] self.angular_velocity = self.vector[11:14] self.linear_acceleration = self.vector[14:17] self.angular_acceleration = self.vector[17:] self.vs.speed = np.linalg.norm(self.linear_velocity)
Update this vehicle state.
update_vehicle_state
python
huawei-noah/SMARTS
smarts/ros/src/smarts_ros/scripts/ros_driver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/ros/src/smarts_ros/scripts/ros_driver.py
MIT
def _extrapolate_to_now( vs: VehicleState, staleness: float, lin_acc_slope: float, ang_acc_slope: float ): """Here we just linearly extrapolate the acceleration to "now" from the previous state for each vehicle and then use standard kinematics to project the velocity and position from that.""" # The following ~10 lines are a hack b/c I'm too stupid to figure out # how to do calculus on quaternions... heading = vs.pose.heading heading_delta_vec = staleness * ( vs.angular_velocity + 0.5 * vs.angular_acceleration * staleness + ang_acc_slope * staleness**2 / 6.0 ) heading += vec_to_radians(heading_delta_vec[:2]) + (0.5 * math.pi) heading %= 2 * math.pi vs.pose.orientation = fast_quaternion_from_angle(heading) # XXX: also need to remove the cached heading_ since we've changed orientation vs.pose.heading_ = None # I assume the following should be updated based on changing # heading from above, but I'll leave that for now... vs.pose.position += staleness * ( vs.linear_velocity + 0.5 * vs.linear_acceleration * staleness + lin_acc_slope * staleness**2 / 6.0 ) vs.linear_velocity += staleness * ( vs.linear_acceleration + 0.5 * lin_acc_slope * staleness ) vs.speed = np.linalg.norm(vs.linear_velocity) vs.angular_velocity += staleness * ( vs.angular_acceleration + 0.5 * ang_acc_slope * staleness ) vs.linear_acceleration += staleness * lin_acc_slope vs.angular_acceleration += staleness * ang_acc_slope
Here we just linearly extrapolate the acceleration to "now" from the previous state for each vehicle and then use standard kinematics to project the velocity and position from that.
_extrapolate_to_now
python
huawei-noah/SMARTS
smarts/ros/src/smarts_ros/scripts/ros_driver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/ros/src/smarts_ros/scripts/ros_driver.py
MIT
def _get_map_spec(self) -> Optional[MapSpec]: """SMARTS ROS nodes can extend from this ROSDriver base class and implement this method to return an alternative MapSpec object designating the map builder to use in the Scenario (returning None indicates to use the default for the current Scenario). self._scenario_path can be used to construct a MapSpec object.""" return None
SMARTS ROS nodes can extend from this ROSDriver base class and implement this method to return an alternative MapSpec object designating the map builder to use in the Scenario (returning None indicates to use the default for the current Scenario). self._scenario_path can be used to construct a MapSpec object.
_get_map_spec
python
huawei-noah/SMARTS
smarts/ros/src/smarts_ros/scripts/ros_driver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/ros/src/smarts_ros/scripts/ros_driver.py
MIT
def run_forever(self): """Publish the SMARTS ros node and run indefinitely.""" if not self._state_publisher: raise RuntimeError("must call setup_ros() first.") if not self._smarts: raise RuntimeError("must call setup_smarts() first.") # pytype: disable=attribute-error rospy.Service(self._service_name, SmartsInfo, self._get_smarts_info) # pytype: enable=attribute-error warned_scenario = False observations = {} step_delta = None if self._target_freq: rate = rospy.Rate(self._target_freq) rospy.loginfo(f"starting to spin") try: while not rospy.is_shutdown(): obs = self._check_reset() if not self._scenario_path: if not warned_scenario: rospy.loginfo("waiting for scenario on reset channel...") warned_scenario = True elif self._last_step_time: rospy.loginfo("no more scenarios. exiting...") break continue if obs is not None: observations = obs try: actions = self._do_agents(observations) step_delta = self._update_smarts_state() observations, _, dones, _ = self._smarts.step(actions, step_delta) self._publish_state() self._publish_agents(observations, dones) except Exception as ex: if isinstance(ex, rospy.ROSInterruptException): raise ex batch_mode = rospy.get_param("~batch_mode", False) if not batch_mode: raise ex import traceback rospy.logerr(f"SMARTS raised exception: {ex}") rospy.logerr(traceback.format_exc()) rospy.logerr("Will wait for next reset...") self._smarts = None self._reset_smarts() self.setup_smarts() if self._target_freq: if rate.remaining().to_sec() <= 0.0: msg = f"SMARTS unable to maintain requested target_freq of {self._target_freq} Hz." if self._warned_about_freq: rospy.loginfo(msg) else: rospy.logwarn(msg) self._warned_about_freq = True rate.sleep() except rospy.ROSInterruptException: rospy.loginfo("ROS interrupted. exiting...") finally: self._reset() # cleans up the SMARTS instance...
Publish the SMARTS ros node and run indefinitely.
run_forever
python
huawei-noah/SMARTS
smarts/ros/src/smarts_ros/scripts/ros_driver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/ros/src/smarts_ros/scripts/ros_driver.py
MIT
def get_tfrecord_info(tfrecord_file: str) -> Dict[str, Dict[str, Any]]: """Extract info about each scenario in the TFRecord file.""" scenarios = dict() records = read_tfrecord_file(tfrecord_file) for record in records: scenario = scenario_pb2.Scenario() scenario.ParseFromString(bytes(record)) scenario_id = scenario.scenario_id num_vehicles = 0 num_pedestrians = 0 for track in scenario.tracks: if track.object_type == 1: num_vehicles += 1 elif track.object_type == 2: num_pedestrians += 1 scenarios[scenario_id] = { "timestamps": len(scenario.timestamps_seconds), "vehicles": num_vehicles, "pedestrians": num_pedestrians, } return scenarios
Extract info about each scenario in the TFRecord file.
get_tfrecord_info
python
huawei-noah/SMARTS
smarts/waymo/waymo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/waymo/waymo_utils.py
MIT
def plot_scenario( tfrecord_file: str, scenario_id: str, animate: bool, label_vehicles: bool, ): """Plot the map features of a Waymo scenario, and optionally plot/animate the vehicle trajectories.""" from smarts.core.waymo_map import WaymoMap source = f"{tfrecord_file}#{scenario_id}" scenario = WaymoMap.parse_source_to_scenario(source) fig = plt.figure() mng = plt.get_current_fig_manager() mng.resize(1000, 1000) map_features = _get_map_features(scenario) handles = MAP_HANDLES if label_vehicles: handles.extend(TRAJECTORY_HANDLES) trajectories = _get_trajectories(scenario) for v_id, props in trajectories.items(): valid_pts = [p for p in props["positions"] if p[0] is not None] if len(valid_pts) > 0: x = valid_pts[0][0] y = valid_pts[0][1] plt.scatter(x, y, marker="o", c="blue") bbox_props = dict(boxstyle="square,pad=0.1", fc="white", ec=None) plt.text(x + 1, y + 1, f"{v_id}", bbox=bbox_props) elif animate: trajectories = _get_trajectories(scenario) interactive_ids = [i for i in scenario.objects_of_interest] points, data, interactive_handles = _plot_trajectories( trajectories, interactive_ids ) handles.extend(TRAJECTORY_HANDLES + interactive_handles) def update(i): drawn_pts = [] for (xs, ys), point in zip(data, points): if i < len(xs) and xs[i] is not None and ys[i] is not None: point.set_data(xs[i], ys[i]) drawn_pts.append(point) return drawn_pts num_steps = len(scenario.timestamps_seconds) anim = FuncAnimation( fig, update, frames=range(1, num_steps), blit=True, interval=100 ) _plot_map_features(map_features) plt.title(f"Scenario {scenario_id}") plt.legend(handles=handles) plt.axis("equal") plt.show()
Plot the map features of a Waymo scenario, and optionally plot/animate the vehicle trajectories.
plot_scenario
python
huawei-noah/SMARTS
smarts/waymo/waymo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/waymo/waymo_utils.py
MIT
def gen_smarts_scenario_code(dataset_path: str, scenario_id: str) -> str: """Generate source code for the ``scenario.py`` of a SMARTS scenario for a Waymo scenario.""" return f"""from pathlib import Path from smarts.sstudio import gen_scenario from smarts.sstudio import types as t dataset_path = "{dataset_path}" scenario_id = "{scenario_id}" traffic_histories = [ t.TrafficHistoryDataset( name=f"waymo", source_type="Waymo", input_path=dataset_path, scenario_id=scenario_id, ) ] gen_scenario( t.Scenario( map_spec=t.MapSpec( source=f"{{dataset_path}}#{{scenario_id}}", lanepoint_spacing=1.0 ), traffic_histories=traffic_histories, ), output_dir=Path(__file__).parent, ) """
Generate source code for the ``scenario.py`` of a SMARTS scenario for a Waymo scenario.
gen_smarts_scenario_code
python
huawei-noah/SMARTS
smarts/waymo/waymo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/waymo/waymo_utils.py
MIT
def generate(self, path: str, scenario_id: str): """ Args: path (str): Absolute path to the TFRecord file. scenario_id (str): ID of the scenario to be converted. """ edge_counter = SumoMapGenerator._make_counter() node_counter = SumoMapGenerator._make_counter() self.nodes_root = ET.Element("nodes") self.edges_root = ET.Element("edges") map_features = SumoMapGenerator._read_map_data(path, scenario_id) base_dir = Path(__file__).absolute().parent nodes_path = base_dir / f"nodes-{scenario_id}.nod.xml" edges_path = base_dir / f"edges-{scenario_id}.edg.xml" net_path = base_dir / f"map-{scenario_id}.net.xml" lanes = [ SumoMapGenerator._convert_polyline(lane.polyline) for lane in map_features["lane"] ] # Build XML for xs, ys in lanes: start_id = f"node-{node_counter()}" end_id = f"node-{node_counter()}" edge_id = f"edge-{edge_counter()}" self._create_node(start_id, xs[0], ys[0]) self._create_node(end_id, xs[-1], ys[-1]) self._create_edge( edge_id, start_id, end_id, SumoMapGenerator._shape_str(xs, ys) ) # Write XML edges_xml = xml.dom.minidom.parseString( ET.tostring(self.edges_root) ).toprettyxml() nodes_xml = xml.dom.minidom.parseString( ET.tostring(self.nodes_root) ).toprettyxml() with open(edges_path, "w") as f: f.write(edges_xml) with open(nodes_path, "w") as f: f.write(nodes_xml) # Generate netfile with netconvert print(f"Generating SUMO map file: {net_path}") proc = subprocess.Popen( [ "netconvert", f"--node-files={nodes_path}", f"--edge-files={edges_path}", f"--output-file={net_path}", "--offset.disable-normalization", "--no-internal-links=false", ], stdout=subprocess.PIPE, ) for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"): print(line.rstrip()) # Clean up intermediate files os.remove(nodes_path) os.remove(edges_path)
Args: path (str): Absolute path to the TFRecord file. scenario_id (str): ID of the scenario to be converted.
generate
python
huawei-noah/SMARTS
smarts/waymo/gen_sumo_map.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/waymo/gen_sumo_map.py
MIT
def git_revision_short_hash() -> str: """ Returns Git commit short hash. Returns: str: Commit hash. """ return ( subprocess.check_output(["git", "rev-parse", "--short", "HEAD"]) .decode("ascii") .strip() )
Returns Git commit short hash. Returns: str: Commit hash.
git_revision_short_hash
python
huawei-noah/SMARTS
smarts/diagnostic/run.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/diagnostic/run.py
MIT
def git_branch() -> str: """ Returns Git branch name. Returns: str: Branch name. """ return ( subprocess.check_output(["git", "rev-parse", "--abbrev-ref", "HEAD"]) .decode("ascii") .strip() )
Returns Git branch name. Returns: str: Branch name.
git_branch
python
huawei-noah/SMARTS
smarts/diagnostic/run.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/diagnostic/run.py
MIT
def main(scenarios: Sequence[str]): """Run diagnostic. Args: scenarios (Sequence[str]): Scenarios to be timed. """ results = {} for scenario in scenarios: path = str(Path(__file__).resolve().parent / scenario) logger.info("Diagnosing: %s", path) results.update(_compute(scenario_dir=[path])) _write_report(results)
Run diagnostic. Args: scenarios (Sequence[str]): Scenarios to be timed.
main
python
huawei-noah/SMARTS
smarts/diagnostic/run.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/diagnostic/run.py
MIT
def build_scenario( scenario: str, clean: bool = False, seed: int = 42, log: Callable[[Any], None] = LOG_DEFAULT, ): """Build a scenario.""" log(f"Building: {scenario}") if clean: clean_scenario(scenario) scenario_root = Path(scenario) scenario_py = scenario_root / "scenario.py" if scenario_py.exists(): _install_requirements(scenario_root, log) try: subprocess.check_call( [ sys.executable, "scenario_builder.py", str(scenario_py.absolute()), str(seed), ], cwd=Path(__file__).parent, ) except subprocess.CalledProcessError as e: raise SystemExit(e)
Build a scenario.
build_scenario
python
huawei-noah/SMARTS
smarts/sstudio/scenario_construction.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/scenario_construction.py
MIT
def build_scenarios( scenarios: List[str], clean: bool = False, seed: int = 42, log: Callable[[Any], None] = LOG_DEFAULT, ): """Build a list of scenarios.""" if not scenarios: # nargs=-1 in combination with a default value is not supported # if scenarios is not given, set /scenarios as default scenarios = ["scenarios"] concurrency = max(1, multiprocessing.cpu_count() - 1) sema = Semaphore(concurrency) all_processes = [] for scenarios_path in scenarios: for subdir, _, _ in os.walk(scenarios_path): if _is_scenario_folder_to_build(subdir): p = Path(subdir) scenario = f"{scenarios_path}/{p.relative_to(scenarios_path)}" proc = Process( target=_build_scenario_proc, kwargs={ "scenario": scenario, "semaphore": sema, "clean": clean, "seed": seed, "log": log, }, ) all_processes.append(proc) proc.start() for proc in all_processes: proc.join()
Build a list of scenarios.
build_scenarios
python
huawei-noah/SMARTS
smarts/sstudio/scenario_construction.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/scenario_construction.py
MIT
def clean_scenario(scenario: str): """Remove all cached scenario files in the given scenario directory.""" to_be_removed = [ "map.glb", "map_spec.pkl", "bubbles.pkl", "missions.pkl", "flamegraph-perf.log", "flamegraph.svg", "flamegraph.html", "*.rou.xml", "*.rou.alt.xml", "social_agents/*", "traffic/*.rou.xml", "traffic/*.smarts.xml", "history_mission.pkl", "*.shf", "*-AUTOGEN.net.xml", "build.db", ] p = Path(scenario) shutil.rmtree(p / "build", ignore_errors=True) shutil.rmtree(p / "traffic", ignore_errors=True) shutil.rmtree(p / "social_agents", ignore_errors=True) for file_name in to_be_removed: for f in p.glob(file_name): # Remove file f.unlink()
Remove all cached scenario files in the given scenario directory.
clean_scenario
python
huawei-noah/SMARTS
smarts/sstudio/scenario_construction.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/scenario_construction.py
MIT
def generate_glb_from_sumo_file(sumo_net_file: str, out_glb_dir: str): """Creates a geometry file from a sumo map file.""" map_spec = MapSpec(sumo_net_file) road_network = SumoRoadNetwork.from_spec(map_spec) road_network.to_glb(out_glb_dir)
Creates a geometry file from a sumo map file.
generate_glb_from_sumo_file
python
huawei-noah/SMARTS
smarts/sstudio/sumo2mesh.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/sumo2mesh.py
MIT
def __next__(self): """Provides the next random route.""" def random_lane_index(road_id: str) -> int: lanes = self._road_map.road_by_id(road_id).lanes return random.randint(0, len(lanes) - 1) def random_lane_offset(road_id: str, lane_idx: int) -> float: lane = self._road_map.road_by_id(road_id).lanes[lane_idx] return random.uniform(0, lane.length) # HACK: loop + continue is a temporary solution so we more likely return a valid # route. In future we need to be able to handle random routes that are just # a single road long. for _ in range(100): route = self._road_map.random_route(max_route_len=10) if len(route.roads) < 2: continue start_road_id = route.roads[0].road_id start_lane_index = random_lane_index(start_road_id) start_lane_offset = random_lane_offset(start_road_id, start_lane_index) end_road_id = route.roads[-1].road_id end_lane_index = random_lane_index(end_road_id) end_lane_offset = random_lane_offset(end_road_id, end_lane_index) return sstypes.Route( begin=(start_road_id, start_lane_index, start_lane_offset), via=tuple(road.road_id for road in route.roads[1:-1]), end=(end_road_id, end_lane_index, end_lane_offset), ) raise InvalidRoute( "Unable to generate a valid random route that contains \ at least two roads." )
Provides the next random route.
__next__
python
huawei-noah/SMARTS
smarts/sstudio/generators.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/generators.py
MIT
def __init__( self, scenario_dir: str, scenario_map_spec: Optional[sstypes.MapSpec], log_dir: Optional[str] = None, overwrite: bool = False, ): """ Args: scenario: The path to the scenario directory. scenario_map_spec: The map spec information. log_dir: Where logging information about traffic planning should be written to. overwrite: Whether to overwrite existing traffic information. """ self._log = logging.getLogger(self.__class__.__name__) self._scenario = scenario_dir self._overwrite = overwrite self._scenario_map_spec = scenario_map_spec self._road_network_path = os.path.join(self._scenario, "map.net.xml") if scenario_map_spec and scenario_map_spec.source: if os.path.isfile(scenario_map_spec.source): self._road_network_path = scenario_map_spec.source elif os.path.exists(scenario_map_spec.source): self._road_network_path = os.path.join( scenario_map_spec.source, "map.net.xml" ) self._road_network = None self._random_route_generator = None self._log_dir = self._resolve_log_dir(log_dir)
Args: scenario: The path to the scenario directory. scenario_map_spec: The map spec information. log_dir: Where logging information about traffic planning should be written to. overwrite: Whether to overwrite existing traffic information.
__init__
python
huawei-noah/SMARTS
smarts/sstudio/generators.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/generators.py
MIT
def plan_and_save( self, traffic: sstypes.Traffic, name: str, output_dir: Optional[str] = None, seed: int = 42, ): """Writes a traffic spec to a route file in the given output_dir. traffic: The traffic to write out name: The name of the traffic resource file output_dir: The output directory of the traffic file seed: The seed used for deterministic random calls """ random.seed(seed) ext = "smarts" if traffic.engine == "SMARTS" else "rou" route_path = os.path.join(output_dir, "{}.{}.xml".format(name, ext)) if os.path.exists(route_path): if self._overwrite: self._log.info( f"Routes at routes={route_path} already exist, overwriting" ) else: self._log.info(f"Routes at routes={route_path} already exist, skipping") return None if traffic.engine == "SMARTS": self._writexml(traffic, True, route_path) return route_path assert ( traffic.engine == "SUMO" ), f"Unsupported traffic engine specified: {traffic.engine}" with tempfile.TemporaryDirectory() as temp_dir: trips_path = os.path.join(temp_dir, "trips.trips.xml") self._writexml(traffic, False, trips_path) route_alt_path = os.path.join(output_dir, "{}.rou.alt.xml".format(name)) scenario_name = os.path.basename(os.path.normpath(output_dir)) log_path = f"{self._log_dir}/{scenario_name}" os.makedirs(log_path, exist_ok=True) from smarts.core.utils.sumo_utils import sumolib int32_limits = np.iinfo(np.int32) duarouter_path = sumolib.checkBinary("duarouter") subprocess.check_call( [ duarouter_path, "--unsorted-input", "true", "--net-file", self.road_network.source, "--route-files", trips_path, "--output-file", route_path, "--seed", str(wrap_value(seed, int32_limits.min, int32_limits.max)), "--ignore-errors", "false", "--no-step-log", "true", "--repair", "true", "--error-log", f"{log_path}/{name}.log", ], stderr=subprocess.DEVNULL, # suppress warnings from duarouter stdout=subprocess.DEVNULL, # suppress success messages from duarouter ) # Remove the rou.alt.xml file if os.path.exists(route_alt_path): os.remove(route_alt_path) return route_path
Writes a traffic spec to a route file in the given output_dir. traffic: The traffic to write out name: The name of the traffic resource file output_dir: The output directory of the traffic file seed: The seed used for deterministic random calls
plan_and_save
python
huawei-noah/SMARTS
smarts/sstudio/generators.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/generators.py
MIT
def _writexml( self, traffic: sstypes.Traffic, fill_in_route_gaps: bool, route_path: str ): """Writes a traffic spec into a route file. Typically this would be the source data to Sumo's DUAROUTER. """ doc = Doc() doc.asis('<?xml version="1.0" encoding="UTF-8"?>') with doc.tag( "routes", ("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"), ("xsi:noNamespaceSchemaLocation", "http://sumo.sf.net/xsd/routes_file.xsd"), ): # Actors and routes may be declared once then reused. To prevent creating # duplicates we unique them here. actors_for_vtypes = { actor for flow in traffic.flows for actor in flow.actors.keys() } if traffic.trips: actors_for_vtypes |= {trip.actor for trip in traffic.trips} vehicle_id_set = {trip.vehicle_name for trip in traffic.trips} vehicle_ids_list = [trip.vehicle_name for trip in traffic.trips] if len(vehicle_id_set) != len(vehicle_ids_list): raise ValueError("Repeated single vehicle names is not allowed.") for actor in actors_for_vtypes: sigma = min(1, max(0, actor.imperfection.sample())) # range [0,1] min_gap = max(0, actor.min_gap.sample()) # range >= 0 doc.stag( "vType", id=actor.id, accel=actor.accel, decel=actor.decel, vClass=actor.vehicle_type, speedFactor=actor.speed.mean, speedDev=actor.speed.sigma, sigma=sigma, minGap=min_gap, maxSpeed=actor.max_speed, **actor.lane_changing_model, **actor.junction_model, ) # Make sure all routes are "resolved" (e.g. `RandomRoute` are converted to # `Route`) so that we can write them all to file. resolved_routes = {} for route in {flow.route for flow in traffic.flows}: resolved_routes[route] = self.resolve_route(route, fill_in_route_gaps) for route in set(resolved_routes.values()): doc.stag("route", id=route.id, edges=" ".join(route.roads)) # We don't de-dup flows since defining the same flow multiple times should # create multiple traffic flows. Since IDs can't be reused, we also unique # them here. for flow_idx, flow in enumerate(traffic.flows): total_weight = sum(flow.actors.values()) route = resolved_routes[flow.route] for actor_idx, (actor, weight) in enumerate(flow.actors.items()): vehs_per_hour = flow.rate * (weight / total_weight) rate_option = {} if flow.randomly_spaced: vehs_per_sec = vehs_per_hour * SECONDS_PER_HOUR_INV rate_option = dict(probability=vehs_per_sec) else: rate_option = dict(vehsPerHour=vehs_per_hour) doc.stag( "flow", # have to encode the flow.repeat_route within the vehcile id b/c # duarouter complains about any additional xml tags or attributes. id="{}-{}{}-{}-{}".format( actor.name, flow.id, "-endless" if flow.repeat_route else "", flow_idx, actor_idx, ), type=actor.id, route=route.id, departLane=route.begin[1], departPos=route.begin[2], departSpeed=actor.depart_speed, arrivalLane=route.end[1], arrivalPos=route.end[2], begin=flow.begin, end=flow.end, **rate_option, ) # write trip into xml format if traffic.trips: self.write_trip_xml(traffic, doc, fill_in_route_gaps) with open(route_path, "w") as f: f.write( indent( doc.getvalue(), indentation=" ", newline="\r\n", indent_text=True ) )
Writes a traffic spec into a route file. Typically this would be the source data to Sumo's DUAROUTER.
_writexml
python
huawei-noah/SMARTS
smarts/sstudio/generators.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/generators.py
MIT
def write_trip_xml(self, traffic, doc, fill_in_gaps): """Writes a trip spec into a route file. Typically this would be the source data to SUMO's DUAROUTER. """ # Make sure all routes are "resolved" (e.g. `RandomRoute` are converted to # `Route`) so that we can write them all to file. resolved_routes = {} for route in {trip.route for trip in traffic.trips}: resolved_routes[route] = self.resolve_route(route, fill_in_gaps) for route in set(resolved_routes.values()): doc.stag("route", id=route.id + "trip", edges=" ".join(route.roads)) # We don't de-dup flows since defining the same flow multiple times should # create multiple traffic flows. Since IDs can't be reused, we also unique # them here. for trip_idx, trip in enumerate(traffic.trips): route = resolved_routes[trip.route] actor = trip.actor doc.stag( "vehicle", id="{}".format(trip.vehicle_name), type=actor.id, route=route.id + "trip", depart=trip.depart, departLane=route.begin[1], departPos=route.begin[2], departSpeed=actor.depart_speed, arrivalLane=route.end[1], arrivalPos=route.end[2], )
Writes a trip spec into a route file. Typically this would be the source data to SUMO's DUAROUTER.
write_trip_xml
python
huawei-noah/SMARTS
smarts/sstudio/generators.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/generators.py
MIT
def resolve_edge_length(self, edge_id, lane_idx): """Determine the length of the given lane on an edge. Args: edge_id: The edge id of the road segment. lane_idx: The index of a lane. Returns: The length of the lane (same as the length of the edge.) """ self._cache_road_network() lane = self._road_network.road_by_id(edge_id).lanes[lane_idx] return lane.length
Determine the length of the given lane on an edge. Args: edge_id: The edge id of the road segment. lane_idx: The index of a lane. Returns: The length of the lane (same as the length of the edge.)
resolve_edge_length
python
huawei-noah/SMARTS
smarts/sstudio/generators.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/generators.py
MIT
def resolve_route(self, route, fill_in_gaps: bool) -> sstypes.Route: """Attempts to fill in the route between the beginning and end specified in the initial route. Args: route: An incomplete route. Returns: smarts.sstudio.sstypes.route.Route: A complete route listing all road segments it passes through. """ if not isinstance(route, sstypes.RandomRoute): return self._fill_in_gaps(route) if fill_in_gaps else route if not self._random_route_generator: road_map = self._map_for_route(route) # Lazy-load to improve performance when not using random route generation. self._random_route_generator = RandomRouteGenerator(road_map) return next(self._random_route_generator)
Attempts to fill in the route between the beginning and end specified in the initial route. Args: route: An incomplete route. Returns: smarts.sstudio.sstypes.route.Route: A complete route listing all road segments it passes through.
resolve_route
python
huawei-noah/SMARTS
smarts/sstudio/generators.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/generators.py
MIT
def road_network(self): """Retrieves the road network this generator is associated with.""" self._cache_road_network() return self._road_network
Retrieves the road network this generator is associated with.
road_network
python
huawei-noah/SMARTS
smarts/sstudio/generators.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/generators.py
MIT
def gen_scenario( scenario: sstypes.Scenario, output_dir: Union[str, Path], seed: int = 42, ): """This is now the preferred way to generate a scenario. Instead of calling the gen_* methods directly, we provide this higher-level abstraction that takes care of the sub-calls. """ # XXX: For now this simply coalesces the sub-calls but in the future this allows # us to simplify our serialization between SStudio and SMARTS. smarts.core.seed(seed) scenario_dir = os.path.abspath(str(output_dir)) build_dir = os.path.join(scenario_dir, "build") build_graph = _build_graph(scenario, build_dir) os.makedirs(build_dir, exist_ok=True) # Create DB for build caching db_path = os.path.join(build_dir, "build.db") db_conn = sqlite3.connect(db_path) cur = db_conn.cursor() cur.execute( """CREATE TABLE IF NOT EXISTS Artifacts ( artifact_path TEXT PRIMARY KEY, scenario_obj_hash TEXT ) WITHOUT ROWID""" ) db_conn.commit() cur.close() # Map spec artifact_paths = build_graph["map_spec"] obj_hash = pickle_hash(scenario.map_spec, True) if _needs_build(db_conn, scenario.map_spec, artifact_paths, obj_hash): with timeit("map_spec", logger.info): gen_map_spec_artifact(scenario_dir, scenario.map_spec) _update_artifacts(db_conn, artifact_paths, obj_hash) map_spec = scenario.map_spec else: if scenario.map_spec is not None: map_spec = scenario.map_spec else: map_spec = sstypes.MapSpec(source=scenario_dir) if map_spec.shift_to_origin and scenario.traffic_histories: logger.warning( "Attempting to shift map with traffic histories." "The data may no longer line up with the map." ) # Track changes to map file itself, if we can find it if os.path.isdir(map_spec.source): _, map_source = find_mapfile_in_dir(map_spec.source) else: map_source = map_spec.source if os.path.isfile(map_source): map_hash = file_md5_hash(map_source) else: map_hash = path2hash(map_source) # Map glb file artifact_paths = build_graph["map"] map_needs_rebuild = _needs_build(db_conn, map_spec, artifact_paths, map_hash) if map_needs_rebuild: with timeit("map_glb", logger.info): road_map, _ = map_spec.builder_fn(map_spec) if not road_map: logger.warning( "No reference to a RoadNetwork file was found in {}, or one could not be created. " "Please make sure the path passed is a valid Scenario with RoadNetwork file required " "(or a way to create one) for scenario building.".format( scenario_dir ) ) return map_dir = os.path.join(build_dir, "map") os.makedirs(map_dir, exist_ok=True) road_map.to_glb(map_dir) _update_artifacts(db_conn, artifact_paths, map_hash) # Traffic artifact_paths = build_graph["traffic"] obj_hash = pickle_hash(scenario.traffic, True) if _needs_build( db_conn, scenario.traffic, artifact_paths, obj_hash, map_needs_rebuild ): with timeit("traffic", logger.info): for iteration, (name, traffic) in enumerate(scenario.traffic.items()): derived_seed = seed + iteration gen_traffic( scenario=scenario_dir, traffic=traffic, name=name, seed=derived_seed, map_spec=map_spec, ) _update_artifacts(db_conn, artifact_paths, obj_hash) # Ego missions artifact_paths = build_graph["ego_missions"] obj_hash = pickle_hash(scenario.ego_missions, True) if _needs_build( db_conn, scenario.ego_missions, artifact_paths, obj_hash, map_needs_rebuild ): with timeit("ego_missions", logger.info): missions = [] for mission in scenario.ego_missions: if isinstance(mission, sstypes.GroupedLapMission): gen_group_laps( scenario=output_dir, begin=mission.route.begin, end=mission.route.end, grid_offset=mission.offset, used_lanes=mission.lanes, vehicle_count=mission.actor_count, entry_tactic=mission.entry_tactic, num_laps=mission.num_laps, map_spec=map_spec, ) else: missions.append(mission) if missions: gen_agent_missions( scenario=output_dir, missions=missions, map_spec=map_spec, ) _update_artifacts(db_conn, artifact_paths, obj_hash) # Social agent missions artifact_paths = build_graph["social_agent_missions"] obj_hash = pickle_hash(scenario.social_agent_missions, True) if _needs_build( db_conn, scenario.social_agent_missions, artifact_paths, obj_hash, map_needs_rebuild, ): with timeit("social_agent_missions", logger.info): for name, (actors, missions) in scenario.social_agent_missions.items(): if not ( isinstance(actors, collections.abc.Sequence) and isinstance(missions, collections.abc.Sequence) ): raise ValueError("Actors and missions must be sequences") gen_social_agent_missions( name=name, scenario=output_dir, social_agent_actor=actors, missions=missions, map_spec=map_spec, ) _update_artifacts(db_conn, artifact_paths, obj_hash) # Bubbles artifact_paths = build_graph["bubbles"] obj_hash = pickle_hash(scenario.bubbles, True) if _needs_build(db_conn, scenario.bubbles, artifact_paths, obj_hash): with timeit("bubbles", logger.info): gen_bubbles(scenario=output_dir, bubbles=scenario.bubbles) _update_artifacts(db_conn, artifact_paths, obj_hash) # Friction maps artifact_paths = build_graph["friction_maps"] obj_hash = pickle_hash(scenario.friction_maps, True) if _needs_build(db_conn, scenario.friction_maps, artifact_paths, obj_hash): with timeit("friction_maps", logger.info): gen_friction_map( scenario=output_dir, surface_patches=scenario.friction_maps ) _update_artifacts(db_conn, artifact_paths, obj_hash) # Traffic histories artifact_paths = build_graph["traffic_histories"] obj_hash = pickle_hash(scenario.traffic_histories, True) if _needs_build( db_conn, scenario.traffic_histories, artifact_paths, obj_hash, map_needs_rebuild ): with timeit("traffic_histories", logger.info): gen_traffic_histories( scenario=output_dir, histories_datasets=scenario.traffic_histories, map_spec=map_spec, ) _update_artifacts(db_conn, artifact_paths, obj_hash) # Scenario metadata artifact_paths = build_graph["scenario_metadata"] obj_hash = pickle_hash(scenario.scenario_metadata, True) if _needs_build( db_conn, scenario.scenario_metadata, artifact_paths, obj_hash, map_needs_rebuild ): with timeit("scenario_metadata", logger.info): gen_metadata( scenario=output_dir, scenario_metadata=scenario.scenario_metadata, )
This is now the preferred way to generate a scenario. Instead of calling the gen_* methods directly, we provide this higher-level abstraction that takes care of the sub-calls.
gen_scenario
python
huawei-noah/SMARTS
smarts/sstudio/genscenario.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genscenario.py
MIT
def gen_map_spec_artifact( scenario: str, map_spec: sstypes.MapSpec, output_dir: Optional[str] = None ): """Saves a map spec to file.""" _check_if_called_externally() build_dir = os.path.join(scenario, "build") output_dir = os.path.join(output_dir or build_dir, "map") os.makedirs(output_dir, exist_ok=True) output_path = os.path.join(output_dir, "map_spec.pkl") with open(output_path, "wb") as f: # we use cloudpickle here instead of pickle because the # map_spec object may contain a reference to a map_builder callable cloudpickle.dump(map_spec, f)
Saves a map spec to file.
gen_map_spec_artifact
python
huawei-noah/SMARTS
smarts/sstudio/genscenario.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genscenario.py
MIT
def gen_traffic( scenario: str, traffic: sstypes.Traffic, name: str, output_dir: Optional[str] = None, seed: int = 42, map_spec: Optional[sstypes.MapSpec] = None, ): """Generates the traffic routes for the given scenario. If the output directory is not provided, the scenario directory is used.""" _check_if_called_externally() assert name != "missions", "The name 'missions' is reserved for missions!" build_dir = os.path.join(scenario, "build") output_dir = os.path.join(output_dir or build_dir, "traffic") os.makedirs(output_dir, exist_ok=True) generator = TrafficGenerator(scenario, map_spec, overwrite=True) saved_path = generator.plan_and_save(traffic, name, output_dir, seed=seed) if saved_path: logger.debug(f"Generated traffic for scenario={scenario}")
Generates the traffic routes for the given scenario. If the output directory is not provided, the scenario directory is used.
gen_traffic
python
huawei-noah/SMARTS
smarts/sstudio/genscenario.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genscenario.py
MIT
def gen_social_agent_missions( scenario: str, missions: Sequence[sstypes.Mission], social_agent_actor: Union[ sstypes.SocialAgentActor, Sequence[sstypes.SocialAgentActor] ], name: str, map_spec: Optional[sstypes.MapSpec] = None, ): """Generates the social agent missions for the given scenario. Args: scenario: The scenario directory missions: A sequence of missions for social agents to perform social_agent_actor: The social agent actor(s) this scenario will use. name: A short name for this grouping of social agents. Is also used as the name of the social agent traffic file map_spec: An optional map specification that takes precedence over scenario directory information. """ _check_if_called_externally() # For backwards compatibility we support both a single value and a sequence actors = social_agent_actor if not isinstance(actors, collections.abc.Sequence): actors = [actors] # This doesn't support BoidAgentActor. Here we make that explicit if any(isinstance(actor, sstypes.BoidAgentActor) for actor in actors): raise ValueError( "gen_social_agent_missions(...) can't be called with BoidAgentActor, got:" f"{actors}" ) actor_names = [a.name for a in actors] if len(actor_names) != len(set(actor_names)): raise ValueError(f"Actor names={actor_names} must not contain duplicates") output_dir = os.path.join(scenario, "build", "social_agents") saved = gen_missions( scenario=scenario, missions=missions, actors=actors, name=name, output_dir=output_dir, map_spec=map_spec, ) if saved: logger.debug(f"Generated social agent missions for scenario={scenario}")
Generates the social agent missions for the given scenario. Args: scenario: The scenario directory missions: A sequence of missions for social agents to perform social_agent_actor: The social agent actor(s) this scenario will use. name: A short name for this grouping of social agents. Is also used as the name of the social agent traffic file map_spec: An optional map specification that takes precedence over scenario directory information.
gen_social_agent_missions
python
huawei-noah/SMARTS
smarts/sstudio/genscenario.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genscenario.py
MIT
def gen_agent_missions( scenario: str, missions: Sequence, map_spec: Optional[sstypes.MapSpec] = None, ): """Generates a route file to represent missions (a route per mission). Will create the output_dir if it doesn't exist already. The output file will be named `missions`. Args: scenario: The scenario directory missions: A sequence of missions for social agents to perform map_spec: An optional map specification that takes precedence over scenario directory information. """ _check_if_called_externally() output_dir = os.path.join(scenario, "build") saved = gen_missions( scenario=scenario, missions=missions, actors=[sstypes.TrafficActor(name="car")], name="missions", output_dir=output_dir, map_spec=map_spec, ) if saved: logger.debug(f"Generated missions for scenario={scenario}")
Generates a route file to represent missions (a route per mission). Will create the output_dir if it doesn't exist already. The output file will be named `missions`. Args: scenario: The scenario directory missions: A sequence of missions for social agents to perform map_spec: An optional map specification that takes precedence over scenario directory information.
gen_agent_missions
python
huawei-noah/SMARTS
smarts/sstudio/genscenario.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genscenario.py
MIT
def gen_group_laps( scenario: str, begin: Tuple[str, int, Any], end: Tuple[str, int, Any], grid_offset: int, used_lanes: int, vehicle_count: int, entry_tactic: Optional[sstypes.EntryTactic], num_laps: int = 3, map_spec: Optional[sstypes.MapSpec] = None, ): """Generates missions that start with a grid offset at the start-line and do a number of laps until finishing. Args: scenario: The scenario directory begin: The edge and offset of the first vehicle end: The edge and offset of the finish-line grid_offset: The F1 starting line staggered with offset disadvantage imposed per vehicle used_lanes: The number of lanes used for the starting-line from the innermost lane vehicle_count: The number of vehicles to use num_laps: The amount of laps before finishing """ _check_if_called_externally() start_road_id, start_lane, start_offset = begin end_road_id, end_lane, end_offset = end missions = [] for i in range(vehicle_count): s_lane = (start_lane + i) % used_lanes missions.append( sstypes.LapMission( sstypes.Route( begin=( start_road_id, s_lane, start_offset - grid_offset * i, ), end=(end_road_id, (end_lane + i) % used_lanes, end_offset), ), num_laps=num_laps, entry_tactic=entry_tactic, # route_length=route_length, ) ) saved = gen_agent_missions( scenario=scenario, missions=missions, map_spec=map_spec, ) if saved: logger.debug(f"Generated grouped lap missions for scenario={scenario}")
Generates missions that start with a grid offset at the start-line and do a number of laps until finishing. Args: scenario: The scenario directory begin: The edge and offset of the first vehicle end: The edge and offset of the finish-line grid_offset: The F1 starting line staggered with offset disadvantage imposed per vehicle used_lanes: The number of lanes used for the starting-line from the innermost lane vehicle_count: The number of vehicles to use num_laps: The amount of laps before finishing
gen_group_laps
python
huawei-noah/SMARTS
smarts/sstudio/genscenario.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genscenario.py
MIT
def gen_bubbles(scenario: str, bubbles: Sequence[sstypes.Bubble]): """Generates 'bubbles' in the scenario that capture vehicles for actors. Args: scenario: The scenario directory bubbles: The bubbles to add to the scenario. """ _check_if_called_externally() output_path = os.path.join(scenario, "build", "bubbles.pkl") with open(output_path, "wb") as f: pickle.dump(bubbles, f)
Generates 'bubbles' in the scenario that capture vehicles for actors. Args: scenario: The scenario directory bubbles: The bubbles to add to the scenario.
gen_bubbles
python
huawei-noah/SMARTS
smarts/sstudio/genscenario.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/sstudio/genscenario.py
MIT