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 __init__( self, env_constructors: Sequence[EnvConstructor], auto_reset: bool, seed: int = 42, ): """The environments can be different but must use the same action and observation spaces. Args: env_constructors (Sequence[EnvConstructor]): List of callables that create environments. auto_reset (bool): Automatically resets an environment when episode ends. seed (int, optional): Seed for the first environment. Defaults to 42. Raises: TypeError: If any environment constructor is not callable. ValueError: If the action or observation spaces do not match. """ if len(env_constructors) > mp.cpu_count(): warnings.warn( f"Simulation might slow down, as the requested number of parallel " f"environments ({len(env_constructors)}) exceed the number of available " f"CPUs ({mp.cpu_count()}).", ResourceWarning, ) if any([not callable(ctor) for ctor in env_constructors]): raise TypeError( f"Found non-callable `env_constructors`. Expected `env_constructors` of type " f"`Sequence[Callable[[int], gym.Env]]`, but got {env_constructors})." ) self._num_envs = len(env_constructors) self._polling_period = 0.1 self._closed = False # Fork is not a thread safe method. forkserver_available = "forkserver" in mp.get_all_start_methods() start_method = "forkserver" if forkserver_available else "spawn" mp_ctx = mp.get_context(start_method) self._parent_pipes = [] self._processes = [] for idx, env_constructor in enumerate(env_constructors): cur_seed = seed + idx parent_pipe, child_pipe = mp_ctx.Pipe() process = mp_ctx.Process( target=_worker, name=f"Worker-<{type(self).__name__}>-<{idx}>", args=( cloudpickle.dumps(env_constructor), cur_seed, auto_reset, child_pipe, self._polling_period, ), ) self._parent_pipes.append(parent_pipe) self._processes.append(process) # Daemonic subprocesses quit when parent process quits. However, daemonic # processes cannot spawn children. Hence, `process.daemon` is set to False. process.daemon = False process.start() child_pipe.close() self._wait_start() self._single_observation_space, self._single_action_space = self._get_spaces()
The environments can be different but must use the same action and observation spaces. Args: env_constructors (Sequence[EnvConstructor]): List of callables that create environments. auto_reset (bool): Automatically resets an environment when episode ends. seed (int, optional): Seed for the first environment. Defaults to 42. Raises: TypeError: If any environment constructor is not callable. ValueError: If the action or observation spaces do not match.
__init__
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/parallel_env.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/parallel_env.py
MIT
def batch_size(self) -> int: """The number of environments.""" return self._num_envs
The number of environments.
batch_size
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/parallel_env.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/parallel_env.py
MIT
def observation_space(self) -> gym.Space: """The environment's observation space in gym representation.""" return self._single_observation_space
The environment's observation space in gym representation.
observation_space
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/parallel_env.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/parallel_env.py
MIT
def action_space(self) -> gym.Space: """The environment's action space in gym representation.""" return self._single_action_space
The environment's action space in gym representation.
action_space
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/parallel_env.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/parallel_env.py
MIT
def seed(self) -> Sequence[int]: """Retrieves the seed used in each environment. Returns: Sequence[int]: Seed of each environment. """ seeds = self._call(_Message.SEED, [None] * self._num_envs) return seeds
Retrieves the seed used in each environment. Returns: Sequence[int]: Seed of each environment.
seed
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/parallel_env.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/parallel_env.py
MIT
def reset(self) -> Tuple[Sequence[Dict[str, Any]], Sequence[Dict[str, Any]]]: """Reset all environments. Returns: Tuple[Sequence[Dict[str, Any]], Sequence[Dict[str, Any]]]: A batch of observations and infos from the vectorized environment. """ # since the return is [(obs0, infos0), ...] they need to be zipped to form. # [(obs0, ...), (infos0, ...)] observations, infos = zip(*self._call(_Message.RESET, [None] * self._num_envs)) return observations, infos
Reset all environments. Returns: Tuple[Sequence[Dict[str, Any]], Sequence[Dict[str, Any]]]: A batch of observations and infos from the vectorized environment.
reset
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/parallel_env.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/parallel_env.py
MIT
def close(self, terminate=False): """Sends a close message to all external processes. Args: terminate (bool, optional): If `True`, then the `close` operation is forced and all processes are terminated. Defaults to False. """ if terminate: for process in self._processes: if process.is_alive(): process.terminate() else: for pipe in self._parent_pipes: try: pipe.send((_Message.CLOSE, None)) pipe.close() except IOError: # The connection was already closed. pass for process in self._processes: if process.is_alive(): process.join() self._closed = True
Sends a close message to all external processes. Args: terminate (bool, optional): If `True`, then the `close` operation is forced and all processes are terminated. Defaults to False.
close
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/parallel_env.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/parallel_env.py
MIT
def _worker( env_constructor: bytes, seed: int, auto_reset: bool, pipe: mp.connection.Connection, polling_period: float = 0.1, ): """Process to build and run an environment. Using a pipe to communicate with parent, the process receives action, steps the environment, and returns the observations. Args: env_constructor (bytes): Cloudpickled callable which constructs the environment. seed (int): Seed for the environment. auto_reset (bool): If True, auto resets environment when episode ends. pipe (mp.connection.Connection): Child's end of the pipe. polling_period (float, optional): Time to wait for keyboard interrupts. Defaults to 0.1. Raises: KeyError: If unknown message type is received. """ env = cloudpickle.loads(env_constructor)(seed=seed) pipe.send((_Message.RESULT, None)) try: while True: if not pipe.poll(polling_period): continue message, payload = pipe.recv() if message == _Message.SEED: env_seed = env.seed pipe.send((_Message.RESULT, env_seed)) elif message == _Message.ACCESS: result = getattr(env, payload, None) pipe.send((_Message.RESULT, result)) elif message == _Message.RESET: observation, info = env.reset() pipe.send((_Message.RESULT, (observation, info))) elif message == _Message.STEP: observation, reward, terminated, truncated, info = env.step(payload) if terminated["__all__"] and auto_reset: # Final observation can be obtained from `info` as follows: # `final_obs = info[agent_id]["env_obs"]` observation, _ = env.reset() pipe.send( ( _Message.RESULT, (observation, reward, terminated, truncated, info), ) ) elif message == _Message.CLOSE: break else: raise KeyError( f"Expected message from {_Message.__members__}, but got unknown message `{message}`." ) except (Exception, KeyboardInterrupt): etype, evalue, tb = sys.exc_info() if etype == KeyboardInterrupt: stacktrace = "".join(traceback.format_exception(etype, evalue, None)) else: stacktrace = "".join(traceback.format_exception(etype, evalue, tb)) payload = (mp.current_process().name, stacktrace) pipe.send((_Message.EXCEPTION, payload)) finally: env.close() pipe.close()
Process to build and run an environment. Using a pipe to communicate with parent, the process receives action, steps the environment, and returns the observations. Args: env_constructor (bytes): Cloudpickled callable which constructs the environment. seed (int): Seed for the environment. auto_reset (bool): If True, auto resets environment when episode ends. pipe (mp.connection.Connection): Child's end of the pipe. polling_period (float, optional): Time to wait for keyboard interrupts. Defaults to 0.1. Raises: KeyError: If unknown message type is received.
_worker
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/parallel_env.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/parallel_env.py
MIT
def add_dataclass(first: T, second: T) -> T: """Sums the fields of two `dataclass` objects. Args: first (T): First `dataclass` object. second (T): Second `dataclass` object. Returns: T: New summed `dataclass` object. """ assert type(first) is type(second) new = {} for field in fields(first): new[field.name] = getattr(first, field.name) + getattr(second, field.name) output = first.__class__(**new) return output
Sums the fields of two `dataclass` objects. Args: first (T): First `dataclass` object. second (T): Second `dataclass` object. Returns: T: New summed `dataclass` object.
add_dataclass
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/utils.py
MIT
def op_dataclass( first: T, second: Union[int, float], op: Callable[[Union[int, float], Union[int, float]], float], ) -> T: """Performs operation `op` on the fields of the source `dataclass` object. Args: first (T): The source `dataclass` object. second (Union[int, float]): Value input for the operator. op (Callable[[Union[int, float], Union[int, float]], float]): Operation to be performed. Returns: T: A new `dataclass` object with operation performed on all of its fields. """ new = {} for field in fields(first): new[field.name] = op(getattr(first, field.name), second) output = first.__class__(**new) return output
Performs operation `op` on the fields of the source `dataclass` object. Args: first (T): The source `dataclass` object. second (Union[int, float]): Value input for the operator. op (Callable[[Union[int, float], Union[int, float]], float]): Operation to be performed. Returns: T: A new `dataclass` object with operation performed on all of its fields.
op_dataclass
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/utils.py
MIT
def divide(value: Union[int, float], divider: Union[int, float]) -> float: """Division operation. Args: value (Union[int, float]): Numerator divider (Union[int, float]): Denominator Returns: float: Numerator / Denominator """ return float(value / divider)
Division operation. Args: value (Union[int, float]): Numerator divider (Union[int, float]): Denominator Returns: float: Numerator / Denominator
divide
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/utils.py
MIT
def multiply(value: Union[int, float], multiplier: Union[int, float]) -> float: """Multiplication operation. Args: value (Union[int, float]): Value multiplier (Union[int, float]): Multiplier Returns: float: Value x Multiplier """ return float(value * multiplier)
Multiplication operation. Args: value (Union[int, float]): Value multiplier (Union[int, float]): Multiplier Returns: float: Value x Multiplier
multiply
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/utils.py
MIT
def nearest_waypoint( matrix: np.ma.MaskedArray, points: np.ndarray, radius: float = 1 ) -> Tuple[Tuple[int, int], Optional[int]]: """ Returns (i) the `matrix` index of the nearest waypoint to the ego, which has a nearby `point`. (ii) the `points` index which is nearby the nearest waypoint to the ego. Nearby is defined as a point within `radius` of a waypoint. Args: matrix (np.ma.MaskedArray): Waypoints matrix. points (np.ndarray): Points matrix. radius (float, optional): Nearby radius. Defaults to 2. Returns: Tuple[Tuple[int, int], Optional[int]] : `matrix` index of shape (a,b) and scalar `point` index. """ cur_point_index = ((np.int32(1e10), np.int32(1e10)), None) if points.shape == (0,): return cur_point_index assert len(matrix.shape) == 3 assert matrix.shape[2] == 3 assert len(points.shape) == 2 assert points.shape[1] == 3 points_expanded = np.expand_dims(points, (1, 2)) diff = matrix - points_expanded dist = np.linalg.norm(diff, axis=-1) dist_masked = np.ma.MaskedArray(dist, diff.mask[..., 0]) for ii in range(points.shape[0]): index = np.argmin(dist_masked[ii]) index_unravel = np.unravel_index(index, dist_masked[ii].shape) min_dist = dist_masked[ii][index_unravel] if min_dist <= radius and index_unravel[1] < cur_point_index[0][1]: cur_point_index = (index_unravel, ii) return cur_point_index
Returns (i) the `matrix` index of the nearest waypoint to the ego, which has a nearby `point`. (ii) the `points` index which is nearby the nearest waypoint to the ego. Nearby is defined as a point within `radius` of a waypoint. Args: matrix (np.ma.MaskedArray): Waypoints matrix. points (np.ndarray): Points matrix. radius (float, optional): Nearby radius. Defaults to 2. Returns: Tuple[Tuple[int, int], Optional[int]] : `matrix` index of shape (a,b) and scalar `point` index.
nearest_waypoint
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/utils.py
MIT
def __init__(self, size: int): """ Args: size (int): Size of the sliding window. """ self._values = deque(maxlen=size) self._max_candidates = deque(maxlen=size) self._size = size self._time = -1
Args: size (int): Size of the sliding window.
__init__
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/utils.py
MIT
def move(self, x: Union[int, float]): """Moves the sliding window one step to the right by appending the new element x and discarding the oldest element on the left. Args: x (Union[int,float]): New element input to the sliding window. """ self._time += 1 # When values deque is full, remove head element of max_candidates deque # if it matches head element of values deque. if len(self._values) == self._size: if self._values[0][0] == self._max_candidates[0][0]: self._max_candidates.popleft() # Append x to values deque. self._values.append((self._time, x)) # Remove elements from max_candidates deque's tail which are less than x. while self._max_candidates and self._max_candidates[-1][1] < x: self._max_candidates.pop() # Append x to max_candidates deque. self._max_candidates.append((self._time, x))
Moves the sliding window one step to the right by appending the new element x and discarding the oldest element on the left. Args: x (Union[int,float]): New element input to the sliding window.
move
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/utils.py
MIT
def max(self): """Returns the maximum element within the sliding window.""" return self._max_candidates[0][1]
Returns the maximum element within the sliding window.
max
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/utils.py
MIT
def display(self): """Print the contents of the sliding window.""" print("[", end="") for i in self._values: print(i, end=" ") print("]")
Print the contents of the sliding window.
display
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/utils.py
MIT
def params(self) -> Params: """Return parameters to configure and initialize cost functions. Returns: Params: Cost function parameters. """ raise NotImplementedError
Return parameters to configure and initialize cost functions. Returns: Params: Cost function parameters.
params
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/formula.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/formula.py
MIT
def score(self, records: Dict[str, Dict[str, Record]]) -> Score: """Computes sub-component scores and one total combined score named "Overall" on the wrapped environment. Args: records (Dict[str, Dict[str, Record]]): Records. Returns: "Overall" score and other sub-component scores. """ raise NotImplementedError
Computes sub-component scores and one total combined score named "Overall" on the wrapped environment. Args: records (Dict[str, Dict[str, Record]]): Records. Returns: "Overall" score and other sub-component scores.
score
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/formula.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/formula.py
MIT
def params(self) -> Params: """Return parameters to configure and initialize cost functions. Returns: Params: Cost function parameters. """ return Params()
Return parameters to configure and initialize cost functions. Returns: Params: Cost function parameters.
params
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/formula.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/formula.py
MIT
def score(self, records: Dict[str, Dict[str, Record]]) -> Score: """Computes sub-component scores and one total combined score named "Overall" on the wrapped environment. Args: records (Dict[str, Dict[str, Record]]): Records. Returns: Score: "Overall" score and other sub-component scores. """ agent_weight = agent_weights(records=records) agent_score = agent_scores(records=records, func=costs_to_score) return weighted_score(scores=agent_score, weights=agent_weight)
Computes sub-component scores and one total combined score named "Overall" on the wrapped environment. Args: records (Dict[str, Dict[str, Record]]): Records. Returns: Score: "Overall" score and other sub-component scores.
score
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/formula.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/formula.py
MIT
def agent_weights(records: Dict[str, Dict[str, Record]]) -> Dict[str, Dict[str, float]]: """Retrieves weight for each agent in every scenario. Args: records (Dict[str, Dict[str, Record]]): Records. Returns: Dict[str,Dict[str,float]]: Weight for each agent in every scenario. """ weights = {} for scen, agents in records.items(): weights[scen] = dict( map(lambda i: (i[0], i[1].metadata.difficulty), agents.items()) ) return weights
Retrieves weight for each agent in every scenario. Args: records (Dict[str, Dict[str, Record]]): Records. Returns: Dict[str,Dict[str,float]]: Weight for each agent in every scenario.
agent_weights
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/formula.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/formula.py
MIT
def agent_scores( records: Dict[str, Dict[str, Record]], func: Callable[[Costs], Score] ) -> Dict[str, Dict[str, Score]]: """Computes score for each agent in every scenario. Args: records (Dict[str, Dict[str, Record]]): Records. func (Callable[[Costs],Score]): Function which computes Score given Costs. Returns: Dict[str,Dict[str,Score]]: Score for each agent in every scenario. """ scores = {} for scen, agents in records.items(): scores[scen] = dict(map(lambda i: (i[0], func(i[1].costs)), agents.items())) return scores
Computes score for each agent in every scenario. Args: records (Dict[str, Dict[str, Record]]): Records. func (Callable[[Costs],Score]): Function which computes Score given Costs. Returns: Dict[str,Dict[str,Score]]: Score for each agent in every scenario.
agent_scores
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/formula.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/formula.py
MIT
def weighted_score( scores: Dict[str, Dict[str, Score]], weights: Dict[str, Dict[str, float]] ) -> Score: """Computes single overall weighted score using `weights`. Args: scores (Dict[str,Dict[str,Score]]): Score for each agent in every scenario. weights (Dict[str,Dict[str,float]]): Weight for each agent in every scenario. Returns: Score: Weighted score. """ cumulative_score = {} total_weight = 0 for scen, agent in scores.items(): for agent_name, agent_score in agent.items(): current_score = dict( map( lambda i: (i[0], i[1] * weights[scen][agent_name]), agent_score.items(), ) ) cumulative_score = { score_name: score_val + cumulative_score.get(score_name, 0) for score_name, score_val in current_score.items() } total_weight += weights[scen][agent_name] return Score({key: val / total_weight for key, val in cumulative_score.items()})
Computes single overall weighted score using `weights`. Args: scores (Dict[str,Dict[str,Score]]): Score for each agent in every scenario. weights (Dict[str,Dict[str,float]]): Weight for each agent in every scenario. Returns: Score: Weighted score.
weighted_score
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/formula.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/formula.py
MIT
def costs_to_score(costs: Costs) -> Score: """Compute score from costs. +-------------------+--------+-----------------------------------------------------------+ | | Range | Remarks | +===================+========+===========================================================+ | Overall | [0, 1] | Total score. The higher, the better. | +-------------------+--------+-----------------------------------------------------------+ | DistToDestination | [0, 1] | Remaining distance to destination. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | Time | [0, 1] | Time taken to complete scenario. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | HumannessError | [0, 1] | Humanness indicator. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | RuleViolation | [0, 1] | Traffic rules compliance. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ Args: costs (Costs): Costs. Returns: Score: Score. """ dist_to_destination = costs.dist_to_destination humanness_error = _score_humanness_error(costs=costs) rule_violation = score_rule_violation(costs=costs) time = costs.steps overall = ( 0.25 * (1 - dist_to_destination) + 0.25 * (1 - time) + 0.25 * (1 - humanness_error) + 0.25 * (1 - rule_violation) ) return Score( { "overall": overall, "dist_to_destination": dist_to_destination, "time": time, "humanness_error": humanness_error, "rule_violation": rule_violation, } )
Compute score from costs. +-------------------+--------+-----------------------------------------------------------+ | | Range | Remarks | +===================+========+===========================================================+ | Overall | [0, 1] | Total score. The higher, the better. | +-------------------+--------+-----------------------------------------------------------+ | DistToDestination | [0, 1] | Remaining distance to destination. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | Time | [0, 1] | Time taken to complete scenario. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | HumannessError | [0, 1] | Humanness indicator. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | RuleViolation | [0, 1] | Traffic rules compliance. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ Args: costs (Costs): Costs. Returns: Score: Score.
costs_to_score
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/formula.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/formula.py
MIT
def score_rule_violation(costs: Costs) -> float: """Default rule violation scoring formula. Args: costs (Costs): Costs. Returns: float: Rule violation score. """ rule_violation = np.array([costs.speed_limit, costs.wrong_way]) rule_violation = np.mean(rule_violation, dtype=float) return rule_violation
Default rule violation scoring formula. Args: costs (Costs): Costs. Returns: float: Rule violation score.
score_rule_violation
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/formula.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/formula.py
MIT
def _jerk_linear() -> Callable[[RoadMap, VehicleIndex, Done, Observation], Costs]: mean = 0 step = 0 jerk_linear_max = np.linalg.norm(np.array([0.9, 0.9, 0])) # Units: m/s^3 """ Maximum comfortable linear jerk as presented in: Bae, Il and et. al., "Self-Driving like a Human driver instead of a Robocar: Personalized comfortable driving experience for autonomous vehicles", Machine Learning for Autonomous Driving Workshop at the 33rd Conference on Neural Information Processing Systems, NeurIPS 2019, Vancouver, Canada. """ def func( road_map: RoadMap, vehicle_index: VehicleIndex, done: Done, obs: Observation ) -> Costs: nonlocal mean, step, jerk_linear_max jerk_linear = np.linalg.norm(obs.ego_vehicle_state.linear_jerk) j_l = min(jerk_linear / jerk_linear_max, 1) mean, step = running_mean(prev_mean=mean, prev_step=step, new_val=j_l) return Costs(jerk_linear=mean) return func
Maximum comfortable linear jerk as presented in: Bae, Il and et. al., "Self-Driving like a Human driver instead of a Robocar: Personalized comfortable driving experience for autonomous vehicles", Machine Learning for Autonomous Driving Workshop at the 33rd Conference on Neural Information Processing Systems, NeurIPS 2019, Vancouver, Canada.
_jerk_linear
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/costs.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/costs.py
MIT
def make_cost_funcs(params: Params, **kwargs) -> CostFuncs: """ Returns a dictionary of active cost functions to be computed as specified by the corresponding `active` field in `params`. Cost functions are initialized using `kwargs`, if any are provided. Args: params (Params): Parameters to configure individual cost functions. kwargs (Dict[str, Dict[str,Any]]): If any, used to initialize the appropriate cost functions. Returns: CostFuncs: Dictionary of active cost functions to be computed. """ cost_funcs = CostFuncs({}) for field in CostFuncsBase.__dataclass_fields__: if getattr(params, field).active: func = getattr(CostFuncsBase, field) args = kwargs.get(field, {}) cost_funcs[field] = func(**args) return cost_funcs
Returns a dictionary of active cost functions to be computed as specified by the corresponding `active` field in `params`. Cost functions are initialized using `kwargs`, if any are provided. Args: params (Params): Parameters to configure individual cost functions. kwargs (Dict[str, Dict[str,Any]]): If any, used to initialize the appropriate cost functions. Returns: CostFuncs: Dictionary of active cost functions to be computed.
make_cost_funcs
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/costs.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/costs.py
MIT
def get_dist( road_map: RoadMap, point_a: Point, point_b: Point, tolerate: bool = False ) -> Tuple[float, RoadMap.Route]: """ Computes the shortest route distance from point_a to point_b in the road map. Both points should lie on a road in the road map. Key assumption about the road map: Any two given points on the road map have valid routes in both directions. Args: road_map: Scenario road map. point_a: A point, in world-map coordinates, which lies on a road. point_b: A point, in world-map coordinates, which lies on a road. tolerate: If False, raises an error when distance is negative due to route being computed in reverse direction from point_b to point_a. Defaults to False. Returns: float: Shortest road distance between two points in the road map. RoadMap.Route: Planned route between point_a and point_b. """ mission = NavigationMission( start=Start( position=point_a.as_np_array, heading=Heading(0), from_front_bumper=False, ), goal=PositionalGoal( position=point_b, radius=2, ), ) plan = Plan(road_map=road_map, mission=mission, find_route=False) plan.create_route(mission=mission, start_lane_radius=3, end_lane_radius=0.5) assert isinstance(plan.route, RoadMap.Route) from_route_point = RoadMap.Route.RoutePoint(pt=point_a) to_route_point = RoadMap.Route.RoutePoint(pt=point_b) dist_tot = plan.route.distance_between(start=from_route_point, end=to_route_point) if dist_tot == None: raise CostError("Unable to find road on route near given points.") elif dist_tot < 0 and not tolerate: raise CostError( "Route computed in reverse direction from point_b to " f"point_a resulting in negative distance: {dist_tot}." ) return dist_tot, plan.route
Computes the shortest route distance from point_a to point_b in the road map. Both points should lie on a road in the road map. Key assumption about the road map: Any two given points on the road map have valid routes in both directions. Args: road_map: Scenario road map. point_a: A point, in world-map coordinates, which lies on a road. point_b: A point, in world-map coordinates, which lies on a road. tolerate: If False, raises an error when distance is negative due to route being computed in reverse direction from point_b to point_a. Defaults to False. Returns: float: Shortest road distance between two points in the road map. RoadMap.Route: Planned route between point_a and point_b.
get_dist
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/costs.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/costs.py
MIT
def on_route( road_map: RoadMap, route: RoadMap.Route, point: Point, radius: float = 7 ) -> Tuple[bool, Optional[RoadMap.Lane], Optional[Point], Optional[float]]: """ Computes whether `point` is within the search `radius` distance from any lane in the `route`. Args: road_map (RoadMap): Road map. route (RoadMap.Route): Route consisting of a set of roads. point (smarts.core.coordinates.Point): A world-coordinate point. radius (float): Search radius. Returns: Tuple[bool, Optional[RoadMap.Lane], Optional[smarts.core.coordinates.Point], Optional[float]]: True if `point` is nearby any road in `route`, else False. If true, additionally returns the (i) nearest lane in route, (ii) its nearest lane center point, and (iii) displacement between `point` and lane center point. """ lanes = road_map.nearest_lanes( point=point, radius=radius, include_junctions=True, ) route_roads = route.roads for lane, _ in lanes: if lane.road in route_roads: offset = lane.offset_along_lane(world_point=point) lane_point = lane.from_lane_coord(RefLinePoint(s=offset)) displacement = np.linalg.norm(lane_point.as_np_array - point.as_np_array) return True, lane, lane_point, displacement return False, None, None, None
Computes whether `point` is within the search `radius` distance from any lane in the `route`. Args: road_map (RoadMap): Road map. route (RoadMap.Route): Route consisting of a set of roads. point (smarts.core.coordinates.Point): A world-coordinate point. radius (float): Search radius. Returns: Tuple[bool, Optional[RoadMap.Lane], Optional[smarts.core.coordinates.Point], Optional[float]]: True if `point` is nearby any road in `route`, else False. If true, additionally returns the (i) nearest lane in route, (ii) its nearest lane center point, and (iii) displacement between `point` and lane center point.
on_route
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/costs.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/costs.py
MIT
def step(self, action: Dict[str, Any]): """Steps the environment by one step.""" result = super().step(action) obs, _, terminated, truncated, info = result # Only count steps in which an ego agent is present. if len(obs) == 0: return result dones = {} if isinstance(terminated, dict): # Caters to environments which use (i) ObservationOptions.multi_agent, # (ii) ObservationOptions.unformatted, and (iii) ObservationOptions.default . dones = {k: v or truncated[k] for k, v in terminated.items()} elif isinstance(terminated, bool): # Caters to environments which use (i) ObservationOptions.full . if terminated or truncated: dones["__all__"] = True else: dones["__all__"] = False dones.update({a: d["done"] for a, d in info.items()}) if isinstance(next(iter(obs.values())), dict): # Caters to environments which use (i) ObservationOptions.multi_agent, # (ii) ObservationOptions.full, and (iii) ObservationOptions.default . active_agents = [ agent_id for agent_id, agent_obs in obs.items() if agent_obs["active"] ] else: # Caters to environments which uses (i) ObservationOptions.unformatted . active_agents = list(obs.keys()) for agent_name in active_agents: base_obs: Observation = info[agent_name]["env_obs"] self._steps[agent_name] += 1 # Compute all cost functions. costs = Costs() for _, cost_func in self._cost_funcs[agent_name].items(): new_costs = cost_func( self._road_map, self._vehicle_index, Done(dones[agent_name]), base_obs, ) if dones[agent_name]: costs = add_dataclass(new_costs, costs) if dones[agent_name] == False: # Skip the rest, if agent is not done yet. continue self._done_agents.add(agent_name) # Only these termination reasons are considered by the current metrics. if not ( base_obs.events.reached_goal or len(base_obs.events.collisions) or base_obs.events.off_road or base_obs.events.reached_max_episode_steps or base_obs.events.interest_done ): raise MetricsError( "Expected reached_goal, collisions, off_road, " "max_episode_steps, or interest_done, to be true " f"on agent done, but got events: {base_obs.events}." ) # Update stored counts and costs. counts = Counts( episodes=1, steps=self._steps[agent_name], goals=base_obs.events.reached_goal, ) self._records_sum[self._scen_name][agent_name].counts = add_dataclass( counts, self._records_sum[self._scen_name][agent_name].counts ) self._records_sum[self._scen_name][agent_name].costs = add_dataclass( costs, self._records_sum[self._scen_name][agent_name].costs ) if dones["__all__"] is True: assert ( self._done_agents == self._cur_agents ), f'done["__all__"]==True but not all agents are done. Current agents = {self._cur_agents}. Agents done = {self._done_agents}.' return result
Steps the environment by one step.
step
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/metrics.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/metrics.py
MIT
def reset(self, **kwargs): """Resets the environment.""" result = super().reset(**kwargs) self._cur_agents = set(self.env.agent_interfaces.keys()) self._steps = dict.fromkeys(self._cur_agents, 0) self._done_agents = set() self._scen = self.env.smarts.scenario self._scen_name = self.env.smarts.scenario.name self._road_map = self.env.smarts.scenario.road_map self._vehicle_index = self.env.smarts.vehicle_index self._cost_funcs = {} _check_scen(scenario=self._scen, agent_interfaces=self.env.agent_interfaces) # Get the actor of interest, if any is present in the current scenario. interest_actors = self.env.smarts.cached_frame.interest_actors().keys() if len(interest_actors) == 0: interest_actor = None elif len(interest_actors) == 1: interest_actor = next(iter(interest_actors)) else: raise MetricsError( f"Expected <=1 actor of interest, but got {len(interest_actors)} " "actors of interest." ) # fmt: off # Refresh the cost functions for every episode. for agent_name in self._cur_agents: cost_funcs_kwargs = {} if self._params.dist_to_destination.active: interest_criteria = self.env.agent_interfaces[agent_name].done_criteria.interest if interest_criteria == None: end_pos = self._scen.missions[agent_name].goal.position dist_tot, route = get_dist( road_map=self._road_map, point_a=self._scen.missions[agent_name].start.point, point_b=end_pos, ) elif isinstance(interest_criteria, InterestDoneCriteria) and (interest_actor is not None): end_pos, dist_tot, route = _get_end_and_dist( interest_actor=interest_actor, vehicle_index=self._vehicle_index, traffic_sims=self.env.smarts.traffic_sims, scenario=self._scen, road_map=self._road_map, ) cost_funcs_kwargs.update( { "vehicle_gap": { "num_agents": len(self._cur_agents), "actor": interest_actor, } } ) else: raise MetricsError( "Unsupported configuration for distance-to-destination cost function." ) cur_on_route, cur_route_lane, cur_route_lane_point, cur_route_displacement = on_route( road_map=self._road_map, route=route, point=self._scen.missions[agent_name].start.point ) assert cur_on_route, f"{agent_name} does not start nearby the desired route." cost_funcs_kwargs.update({ "dist_to_destination": { "end_pos": end_pos, "dist_tot": dist_tot, "route": route, "prev_route_lane": cur_route_lane, "prev_route_lane_point": cur_route_lane_point, "prev_route_displacement": cur_route_displacement, } }) max_episode_steps = self._scen.metadata.get("scenario_duration",0) / self.env.smarts.fixed_timestep_sec max_episode_steps = max_episode_steps or self.env.agent_interfaces[agent_name].max_episode_steps cost_funcs_kwargs.update({ "dist_to_obstacles": { "ignore": self._params.dist_to_obstacles.ignore }, "steps": { "max_episode_steps": max_episode_steps }, }) self._cost_funcs[agent_name] = make_cost_funcs( params=self._params, **cost_funcs_kwargs ) # Create new entry in records_sum for new scenarios. if self._scen_name not in self._records_sum.keys(): self._records_sum[self._scen_name] = { agent_name: Record( costs=Costs(), counts=Counts(), metadata=Metadata(difficulty=self._scen.metadata.get("scenario_difficulty",1)), ) for agent_name in self._cur_agents } return result
Resets the environment.
reset
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/metrics.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/metrics.py
MIT
def records(self) -> Dict[str, Dict[str, Record]]: """ Fine grained performance metric for each agent in each scenario. .. code-block:: bash $ env.records() $ { scen1: { agent1: Record(costs, counts, metadata), agent2: Record(costs, counts, metadata), }, scen2: { agent1: Record(costs, counts, metadata), }, } Returns: Dict[str, Dict[str, Record]]: Performance record in a nested dictionary for each agent in each scenario. """ records = {} for scen, agents in self._records_sum.items(): records[scen] = {} for agent, data in agents.items(): data_copy = copy.deepcopy(data) records[scen][agent] = Record( costs=op_dataclass( data_copy.costs, data_copy.counts.episodes, divide ), counts=data_copy.counts, metadata=data_copy.metadata, ) return records
Fine grained performance metric for each agent in each scenario. .. code-block:: bash $ env.records() $ { scen1: { agent1: Record(costs, counts, metadata), agent2: Record(costs, counts, metadata), }, scen2: { agent1: Record(costs, counts, metadata), }, } Returns: Dict[str, Dict[str, Record]]: Performance record in a nested dictionary for each agent in each scenario.
records
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/metrics.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/metrics.py
MIT
def score(self) -> Score: """ Computes score according to environment specific formula from the Formula class. Returns: Dict[str, float]: Contains key-value pairs denoting score components. """ return self._formula.score(records=self.records())
Computes score according to environment specific formula from the Formula class. Returns: Dict[str, float]: Contains key-value pairs denoting score components.
score
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/metrics.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/metrics.py
MIT
def _get_end_and_dist( interest_actor: str, vehicle_index: VehicleIndex, traffic_sims: List[TrafficProvider], scenario: Scenario, road_map: RoadMap, ) -> Tuple[Point, float, RoadMap.Route]: """Computes the end point and route distance for a given vehicle of interest. Args: interest_actor (str): Name of vehicle of interest. vehicle_index (VehicleIndex): Index of all vehicles currently present. traffic_sims (List[TrafficProvider]): List of traffic providers. scenario (Scenario): Current scenario. road_map (RoadMap): Underlying road map. Returns: Tuple[Point, float, RoadMap.Route]: End point, route distance, and planned route. """ # Check if the interest vehicle is a social agent. interest_social_missions = [ mission for name, mission in scenario.missions.items() if interest_actor in name ] # Check if the actor of interest is a traffic vehicle. interest_traffic_sims = [ traffic_sim for traffic_sim in traffic_sims if traffic_sim.manages_actor(interest_actor) ] if len(interest_social_missions) + len(interest_traffic_sims) != 1: raise MetricsError( "Social agents and traffic providers contain zero or " "more than one actor of interest." ) if len(interest_social_missions) == 1: interest_social_mission = interest_social_missions[0] goal = interest_social_mission.goal assert isinstance(goal, PositionalGoal) end_pos = goal.position dist_tot, route = get_dist( road_map=road_map, point_a=interest_social_mission.start.point, point_b=end_pos, ) else: interest_traffic_sim = interest_traffic_sims[0] end_pos, dist_tot, route = _get_traffic_end_and_dist( vehicle_name=interest_actor, vehicle_index=vehicle_index, traffic_sim=interest_traffic_sim, road_map=road_map, ) return end_pos, dist_tot, route
Computes the end point and route distance for a given vehicle of interest. Args: interest_actor (str): Name of vehicle of interest. vehicle_index (VehicleIndex): Index of all vehicles currently present. traffic_sims (List[TrafficProvider]): List of traffic providers. scenario (Scenario): Current scenario. road_map (RoadMap): Underlying road map. Returns: Tuple[Point, float, RoadMap.Route]: End point, route distance, and planned route.
_get_end_and_dist
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/metrics.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/metrics.py
MIT
def _get_traffic_end_and_dist( vehicle_name: str, vehicle_index: VehicleIndex, traffic_sim: TrafficProvider, road_map: RoadMap, ) -> Tuple[Point, float, RoadMap.Route]: """Computes the end point and route distance of a (i) SUMO traffic, (ii) SMARTS traffic, or (iii) history traffic vehicle specified by `vehicle_name`. Args: vehicle_name (str): Name of vehicle. vehicle_index (VehicleIndex): Index of all vehicles currently present. traffic_sim (TrafficProvider): Traffic provider. road_map (RoadMap): Underlying road map. Returns: Tuple[Point, float, RoadMap.Route]: End point, route distance, and planned route. """ if isinstance(traffic_sim, (SumoTrafficSimulation, LocalTrafficProvider)): start_pos = Point(*vehicle_index.vehicle_position(vehicle_name)) dest_road = traffic_sim.vehicle_dest_road(vehicle_name) end_pos = ( road_map.road_by_id(dest_road) .lane_at_index(0) .from_lane_coord(RefLinePoint(s=np.inf)) ) dist_tot, route = get_dist( road_map=road_map, point_a=start_pos, point_b=end_pos ) return end_pos, dist_tot, route elif isinstance(traffic_sim, TrafficHistoryProvider): history = traffic_sim.vehicle_history_window(vehicle_id=vehicle_name) start_pos = Point(x=history.start_position_x, y=history.start_position_y) end_pos = Point(x=history.end_position_x, y=history.end_position_y) # TODO : Plan.create_route() creates the shortest route which is # sufficient in simple maps, but it may or may not match the actual # roads traversed by the history vehicle in complex maps. Ideally we # should use the actual road ids traversed by the history vehicle to # compute the distance. dist_tot, route = get_dist( road_map=road_map, point_a=start_pos, point_b=end_pos ) return end_pos, dist_tot, route else: raise MetricsError(f"Unsupported traffic provider {traffic_sim.source_str}.")
Computes the end point and route distance of a (i) SUMO traffic, (ii) SMARTS traffic, or (iii) history traffic vehicle specified by `vehicle_name`. Args: vehicle_name (str): Name of vehicle. vehicle_index (VehicleIndex): Index of all vehicles currently present. traffic_sim (TrafficProvider): Traffic provider. road_map (RoadMap): Underlying road map. Returns: Tuple[Point, float, RoadMap.Route]: End point, route distance, and planned route.
_get_traffic_end_and_dist
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/metrics.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/metrics.py
MIT
def __getattr__(self, name: str): """Returns an attribute with ``name``, unless ``name`` is a restricted attribute or starts with an underscore.""" if name == "_np_random": raise AttributeError( "Can't access `_np_random` of a wrapper, use `self.unwrapped._np_random` or `self.np_random`." ) elif name.startswith("_") or name in [ "smarts", ]: raise AttributeError(f"accessing private attribute '{name}' is prohibited") return getattr(self.env, name)
Returns an attribute with ``name``, unless ``name`` is a restricted attribute or starts with an underscore.
__getattr__
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/metrics.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/metrics.py
MIT
def _check_env(agent_interfaces: Dict[str, AgentInterface], params: Params): """Checks environment suitability to compute performance metrics. Args: agent_interfaces (Dict[str,AgentInterface]): Agent interfaces. params (Params): Metric parameters. Raises: AttributeError: If any required agent interface is disabled or is ill defined. """ def check_intrfc(agent_intrfc: AgentInterface): intrfc = { "accelerometer": bool(agent_intrfc.accelerometer), "max_episode_steps": bool(agent_intrfc.max_episode_steps), "neighborhood_vehicle_states": bool(agent_intrfc.neighborhood_vehicles), "waypoint_paths": bool(agent_intrfc.waypoints), "done_criteria.collision": agent_intrfc.done_criteria.collision, "done_criteria.off_road": agent_intrfc.done_criteria.off_road, } return intrfc for agent_name, agent_interface in agent_interfaces.items(): intrfc = check_intrfc(agent_interface) if not all(intrfc.values()): raise AttributeError( ( "Enable {0}'s disabled interface to " "compute its metrics. Current interface is " "{1}." ).format(agent_name, intrfc) ) interest_criteria = agent_interface.done_criteria.interest if ( params.dist_to_destination.active and isinstance(interest_criteria, InterestDoneCriteria) ) and not ( len(interest_criteria.actors_filter) == 0 and interest_criteria.include_scenario_marked == True ): raise AttributeError( ( "InterestDoneCriteria with none or multiple actors of " "interest is currently not supported when " "dist_to_destination cost function is enabled. Current " "interface is {0}:{1}." ).format(agent_name, interest_criteria) )
Checks environment suitability to compute performance metrics. Args: agent_interfaces (Dict[str,AgentInterface]): Agent interfaces. params (Params): Metric parameters. Raises: AttributeError: If any required agent interface is disabled or is ill defined.
_check_env
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/metrics.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/metrics.py
MIT
def _check_scen(scenario: Scenario, agent_interfaces: Dict[str, AgentInterface]): """Checks scenario suitability to compute performance metrics. Args: scen (Scenario): A ``smarts.core.scenario.Scenario`` class. agent_interfaces (Dict[str,AgentInterface]): Agent interfaces. Raises: MetricsError: If (i) scenario difficulty is not properly normalized, or (ii) any agent's goal is improperly configured. """ difficulty = scenario.metadata.get("scenario_difficulty", None) if not ((difficulty is None) or (0 < difficulty <= 1)): raise MetricsError( "Expected scenario difficulty to be normalized within (0,1], but " f"got difficulty={difficulty}." ) goal_types = { agent_name: type(agent_mission.goal) for agent_name, agent_mission in scenario.missions.items() } aoi = scenario.metadata.get("actor_of_interest_re_filter", None) for agent_name, agent_interface in agent_interfaces.items(): interest_criteria = agent_interface.done_criteria.interest if not ( (goal_types[agent_name] == PositionalGoal and interest_criteria is None) or ( goal_types[agent_name] == EndlessGoal and isinstance(interest_criteria, InterestDoneCriteria) and aoi != None ) ): raise MetricsError( "{0} has an unsupported goal type {1} and interest done criteria {2} " "combination.".format( agent_name, goal_types[agent_name], interest_criteria ) )
Checks scenario suitability to compute performance metrics. Args: scen (Scenario): A ``smarts.core.scenario.Scenario`` class. agent_interfaces (Dict[str,AgentInterface]): Agent interfaces. Raises: MetricsError: If (i) scenario difficulty is not properly normalized, or (ii) any agent's goal is improperly configured.
_check_scen
python
huawei-noah/SMARTS
smarts/env/gymnasium/wrappers/metric/metrics.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/gymnasium/wrappers/metric/metrics.py
MIT
def reset(self, **kwargs): """ Reset the gym environment and restart recording. """ observations = super().reset(**kwargs) if self.recording == False: self.start_recording() return observations
Reset the gym environment and restart recording.
reset
python
huawei-noah/SMARTS
smarts/env/wrappers/recorder_wrapper.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/wrappers/recorder_wrapper.py
MIT
def start_recording(self): """ Start the gif recorder and capture the first frame. """ if self.gif_recorder is None: self.gif_recorder = GifRecorder(self.video_name_folder, self.env) image = super().render(mode="rgb_array") self.gif_recorder.capture_frame(self.next_frame_id(), image) self.recording = True
Start the gif recorder and capture the first frame.
start_recording
python
huawei-noah/SMARTS
smarts/env/wrappers/recorder_wrapper.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/wrappers/recorder_wrapper.py
MIT
def stop_recording(self): """ Stop recording. """ self.recording = False
Stop recording.
stop_recording
python
huawei-noah/SMARTS
smarts/env/wrappers/recorder_wrapper.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/wrappers/recorder_wrapper.py
MIT
def step(self, action): """ Step the environment using the action and record the next frame. """ observations, rewards, dones, infos = super().step(action) if self.recording == True: image = super().render(mode="rgb_array") self.gif_recorder.capture_frame(self.next_frame_id(), image) return observations, rewards, dones, infos
Step the environment using the action and record the next frame.
step
python
huawei-noah/SMARTS
smarts/env/wrappers/recorder_wrapper.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/wrappers/recorder_wrapper.py
MIT
def next_frame_id(self): """ Get the id for next frame. """ self.current_frame += 1 return self.current_frame
Get the id for next frame.
next_frame_id
python
huawei-noah/SMARTS
smarts/env/wrappers/recorder_wrapper.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/wrappers/recorder_wrapper.py
MIT
def close(self): """ Close the recorder by deleting the image folder and generate the gif file. """ if self.gif_recorder is not None: self.gif_recorder.generate_gif() self.gif_recorder.close_recorder() self.gif_recorder = None self.recording = False
Close the recorder by deleting the image folder and generate the gif file.
close
python
huawei-noah/SMARTS
smarts/env/wrappers/recorder_wrapper.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/wrappers/recorder_wrapper.py
MIT
def capture_frame(self, step_num: int, image: np.ndarray): """ Create image according to the ``"rgb_array"`` and store it with step number in the destination folder """ with ImageClip(image) as image_clip: image_clip.save_frame( f"{self.frame_folder}/{self._video_name}_{step_num}.jpeg" )
Create image according to the ``"rgb_array"`` and store it with step number in the destination folder
capture_frame
python
huawei-noah/SMARTS
smarts/env/wrappers/gif_recorder.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/wrappers/gif_recorder.py
MIT
def generate_gif(self): """ Use the images in the same folder to create a gif file. """ with ImageSequenceClip(self.frame_folder, fps=10) as clip: clip.write_gif(f"{self._video_root_path}/{self._video_name}.gif") clip.close()
Use the images in the same folder to create a gif file.
generate_gif
python
huawei-noah/SMARTS
smarts/env/wrappers/gif_recorder.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/wrappers/gif_recorder.py
MIT
def close_recorder(self): """ close the recorder by deleting the image folder. """ shutil.rmtree(self.frame_folder, ignore_errors=True)
close the recorder by deleting the image folder.
close_recorder
python
huawei-noah/SMARTS
smarts/env/wrappers/gif_recorder.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/wrappers/gif_recorder.py
MIT
def flatten_obs(sim_obs): """Convert the observation into tuples of observations (for purposes of flattening boids).""" obs = [] for agent_id, agent_obs in sim_obs.items(): if agent_obs is None: continue elif isinstance(agent_obs, dict): # is_boid_agent for vehicle_id, vehicle_obs in agent_obs.items(): obs.append((vehicle_id, vehicle_obs)) else: obs.append((agent_id, agent_obs)) return obs
Convert the observation into tuples of observations (for purposes of flattening boids).
flatten_obs
python
huawei-noah/SMARTS
smarts/env/wrappers/utils/rendering.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/wrappers/utils/rendering.py
MIT
def vis_sim_obs(sim_obs) -> Dict[str, np.ndarray]: """Convert the observations into format for mp4 video output.""" vis_images = defaultdict(list) for agent_id, agent_obs in flatten_obs(sim_obs): drivable_area = getattr(agent_obs, "drivable_area_grid_map", None) if drivable_area is not None: image = drivable_area.data image = image[:, :, [0, 0, 0]] image = image.astype(np.uint8) vis_images[f"{agent_id}-DrivableAreaGridMap"].append(image) ogm = getattr(agent_obs, "occupancy_grid_map", None) if ogm is not None: image: np.ndarray = ogm.data image = image[:, :, [0, 0, 0]] image = image.astype(np.uint8) vis_images[f"{agent_id}-OGM"].append(image) rgb = getattr(agent_obs, "top_down_rgb", None) if rgb is not None: image = rgb.data image = image.astype(np.uint8) vis_images[f"{agent_id}-Top-Down-RGB"].append(image) return {key: np.array(images) for key, images in vis_images.items()}
Convert the observations into format for mp4 video output.
vis_sim_obs
python
huawei-noah/SMARTS
smarts/env/wrappers/utils/rendering.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/wrappers/utils/rendering.py
MIT
def show_notebook_videos(path="videos", height="400px", split_html=""): """Render a video in a python display. Usually for jupyter notebooks.""" if not isnotebook(): return from IPython import display as ipythondisplay html = [] for mp4 in Path(path).glob("*.mp4"): video_b64 = base64.b64encode(mp4.read_bytes()) html.append( """<video alt="{}" autoplay loop controls style="height: {};"> <source src="data:video/mp4;base64,{}" type="video/mp4" /> </video>""".format( mp4, height, video_b64.decode("ascii") ) ) ipythondisplay.display(ipythondisplay.HTML(data=split_html.join(html)))
Render a video in a python display. Usually for jupyter notebooks.
show_notebook_videos
python
huawei-noah/SMARTS
smarts/env/wrappers/utils/rendering.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/wrappers/utils/rendering.py
MIT
def step(self, obs, rewards, dones, infos): """Record a step.""" single_env_obs = obs if self.is_vector_env: # For now only render one environment single_env_obs = obs[0] self._record_for_render(single_env_obs)
Record a step.
step
python
huawei-noah/SMARTS
smarts/env/utils/record.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/record.py
MIT
def render(self, mode="rgb_array", **kwargs): """Render the given camera image in this environment.""" if len(self._image_frame) > 0: return self._image_frame
Render the given camera image in this environment.
render
python
huawei-noah/SMARTS
smarts/env/utils/record.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/record.py
MIT
def reset(self, obs) -> Any: """Record the reset of the environment.""" self._record_for_render(obs) return obs
Record the reset of the environment.
reset
python
huawei-noah/SMARTS
smarts/env/utils/record.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/record.py
MIT
def format(self, obs: Observation): """Selects and formats the given observation to get a value that matches the space attribute.""" raise NotImplementedError()
Selects and formats the given observation to get a value that matches the space attribute.
format
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def active(self, agent_interface: AgentInterface) -> bool: """If this formatting is active and should be included in the output.""" raise NotImplementedError()
If this formatting is active and should be included in the output.
active
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def name(self): """The name that should represent this observation space in hierarchy.""" raise NotImplementedError()
The name that should represent this observation space in hierarchy.
name
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def space(self): """The observation space this should format the smarts observation to match.""" raise NotImplementedError()
The observation space this should format the smarts observation to match.
space
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def __call__(self, agent_interface: AgentInterface) -> "BaseSpaceFormat": """The observation space this should format the smarts observation to match.""" raise NotImplementedError()
The observation space this should format the smarts observation to match.
__call__
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def format(self, obs: Observation): """Selects and formats the given observation to get a value that matches the :attr:`space`.""" return self._formatting_func(obs)
Selects and formats the given observation to get a value that matches the :attr:`space`.
format
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def active(self, agent_interface: AgentInterface) -> bool: """If this formatting is active and should be included in the output.""" return self._active_func(agent_interface)
If this formatting is active and should be included in the output.
active
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def name(self): """The name that should represent this observation space in hierarchy.""" return self._name
The name that should represent this observation space in hierarchy.
name
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def space(self): """The observation space this should format the smarts observation to match.""" return self._space
The observation space this should format the smarts observation to match.
space
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def format(self, obs: Observation): """Selects and formats the given observation to get a value that matches the :attr:`space`.""" return self._formatting_func(obs, self._agent_interface)
Selects and formats the given observation to get a value that matches the :attr:`space`.
format
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def active(self, agent_interface: AgentInterface) -> bool: """If this formatting is active and should be included in the output.""" return self._active_func(agent_interface)
If this formatting is active and should be included in the output.
active
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def name(self): """The name that should represent this observation space in hierarchy.""" return self._name
The name that should represent this observation space in hierarchy.
name
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def space(self): """The observation space this should format the smarts observation to match.""" assert ( self._agent_interface is not None ), "Agent interface must be applied to call this method." return self._space_func(self._agent_interface)
The observation space this should format the smarts observation to match.
space
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def active(self, agent_interface: AgentInterface) -> bool: """If this formatting is active and should be included in the output.""" return self._active_func(agent_interface)
If this formatting is active and should be included in the output.
active
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def name(self): """The name that should represent this observation space in hierarchy.""" return self._name
The name that should represent this observation space in hierarchy.
name
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def format(self, observations: Dict[str, Observation]): """Formats smarts observations fixed sized containers.""" if self.observation_options == ObservationOptions.unformatted: return observations # TODO MTA: Parallelize the conversion if possible active_obs = { agent_id: self._space_formats[agent_id].format(obs) for agent_id, obs in observations.items() } out_obs = active_obs if self.observation_options == ObservationOptions.full: missing_ids = set(self._space_formats.keys()) - set(active_obs.keys()) padded_obs = { agent_id: space_format.space.sample() for agent_id, space_format in self._space_formats.items() if agent_id in missing_ids } for obs in padded_obs.values(): obs["active"] = np.int64(False) out_obs.update(padded_obs) return out_obs
Formats smarts observations fixed sized containers.
format
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def space(self): """The observation space this should format the smarts observations to match.""" if self.observation_options is ObservationOptions.unformatted: return None return gym.spaces.Dict( { agent_id: space_format.space for agent_id, space_format in self._space_formats.items() } )
The observation space this should format the smarts observations to match.
space
python
huawei-noah/SMARTS
smarts/env/utils/observation_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/observation_conversion.py
MIT
def get_scenario_specs(scenario: str): """Returns the appropriate scenario specification. Args: scenario (str): Scenario Returns: Dict[str, Any]: A parameter dictionary. """ if os.path.isdir(scenario): import re regexp_agent = re.compile(r"agents_\d+") regexp_num = re.compile(r"\d+") matches_agent = regexp_agent.search(scenario) if not matches_agent: raise Exception( f"Scenario path should match regexp of 'agents_\\d+', but got {scenario}" ) num_agent = regexp_num.search(matches_agent.group(0)) return { "scenario": str(scenario), "num_agent": int(num_agent.group(0)), } else: raise Exception(f"Unknown scenario {scenario}.")
Returns the appropriate scenario specification. Args: scenario (str): Scenario Returns: Dict[str, Any]: A parameter dictionary.
get_scenario_specs
python
huawei-noah/SMARTS
smarts/env/utils/scenario.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/scenario.py
MIT
def get_formatters() -> Dict[ActionSpaceType, FormattingGroup]: """Get the currently available formatting groups for converting actions from `gym` space standard to SMARTS accepted observations. Returns: Dict[ActionSpaceType, Any]: The currently available formatting groups. """ return { ActionSpaceType.ActuatorDynamic: FormattingGroup( space=_actuator_dynamic_space, ), ActionSpaceType.Continuous: FormattingGroup( space=_continuous_space, ), ActionSpaceType.Direct: FormattingGroup( space=_direct_space, ), ActionSpaceType.Empty: FormattingGroup( space=gym.spaces.Tuple(spaces=()), formatting_func=lambda a: None, ), ActionSpaceType.Lane: FormattingGroup( space=_lane_space, formatting_func=_format_lane_space, ), ActionSpaceType.LaneWithContinuousSpeed: FormattingGroup( space=_lane_with_continuous_speed_space, ), ActionSpaceType.MPC: FormattingGroup( space=_mpc_space, ), ActionSpaceType.MultiTargetPose: FormattingGroup( space=_multi_target_pose_space, ), ActionSpaceType.RelativeTargetPose: FormattingGroup( space=_relative_target_pose_space, ), ActionSpaceType.TargetPose: FormattingGroup( space=_target_pose_space, ), ActionSpaceType.Trajectory: FormattingGroup( space=_trajectory_space, ), ActionSpaceType.TrajectoryWithTime: FormattingGroup( space=_trajectory_with_time_space, ), }
Get the currently available formatting groups for converting actions from `gym` space standard to SMARTS accepted observations. Returns: Dict[ActionSpaceType, Any]: The currently available formatting groups.
get_formatters
python
huawei-noah/SMARTS
smarts/env/utils/action_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/action_conversion.py
MIT
def format(self, actions: Dict[str, Any]): """Format the action to a form that SMARTS can use. Args: actions (Dict[str, Any]): The actions to format. Returns: (Observation, Dict[str, Any]): The formatted actions. """ if self.action_options == ActionOptions.unformatted: return actions out_actions = {} formatting_groups = get_formatters() for agent_id, action in actions.items(): agent_interface = self._agent_interfaces[agent_id] format_ = formatting_groups[agent_interface.action] space: gym.Space = self.space[agent_id] assert space is format_.space dtype = action.dtype if isinstance(action, np.ndarray) else None assert space.contains( action ), f"Action {action} of type `{type(action)}` & {dtype} does not match space {space}!" formatted_action = format_.formatting_func(action) out_actions[agent_id] = formatted_action if self.action_options == ActionOptions.full: assert actions.keys() == self.space.spaces.keys() return out_actions
Format the action to a form that SMARTS can use. Args: actions (Dict[str, Any]): The actions to format. Returns: (Observation, Dict[str, Any]): The formatted actions.
format
python
huawei-noah/SMARTS
smarts/env/utils/action_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/action_conversion.py
MIT
def supported(action_type: ActionSpaceType): """Test if the action is in the supported int Args: action_type (ActionSpaceType): The action type to check. Returns: bool: If the action type is supported by the formatter. """ return action_type in get_formatters()
Test if the action is in the supported int Args: action_type (ActionSpaceType): The action type to check. Returns: bool: If the action type is supported by the formatter.
supported
python
huawei-noah/SMARTS
smarts/env/utils/action_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/action_conversion.py
MIT
def space(self) -> gym.spaces.Dict: """The action space given the current configuration. Returns: gym.spaces.Dict: A description of the action space that this formatter requires. """ if self.action_options is ActionOptions.unformatted: return None return gym.spaces.Dict( { agent_id: get_formatters()[agent_interface.action].space for agent_id, agent_interface in self._agent_interfaces.items() } )
The action space given the current configuration. Returns: gym.spaces.Dict: A description of the action space that this formatter requires.
space
python
huawei-noah/SMARTS
smarts/env/utils/action_conversion.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/env/utils/action_conversion.py
MIT
def auto_install_requirements(benchmark_spec: Dict[str, Any]): """Install dependencies as specified by the configuration given.""" # TODO MTA: add configuration to configuration file requirements: List[str] = benchmark_spec.get("requirements", []) if len(requirements) > 0: subprocess.check_call( [ sys.executable, "-m", "pip", "install", *requirements, ] )
Install dependencies as specified by the configuration given.
auto_install_requirements
python
huawei-noah/SMARTS
smarts/benchmark/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/benchmark/__init__.py
MIT
def run_benchmark( benchmark_name: str, benchmark_version: Optional[float], agent_locator: str, benchmark_listing: pathlib.Path, debug_log: bool = False, auto_install: bool = False, ): """Runs a benchmark with the given configuration. Use `scl benchmark list` to see the available benchmarks. Args: benchmark_name(str): The name of the benchmark to run. benchmark_version(float|None): The version of the benchmark. agent_locator(str): Locator string for the registered agent. benchmark_listing(pathlib.Path): A configuration file that lists benchmark metadata and must list the target benchmark. debug_log: Debug to `stdout`. """ from smarts.core.utils.resources import load_yaml_config_with_substitution listing_dict = load_yaml_config_with_substitution(benchmark_listing) benchmarks = listing_dict["benchmarks"] try: benchmark_group = benchmarks[benchmark_name] except KeyError as err: raise RuntimeError( f"`{benchmark_name}` not found in config `{BENCHMARK_LISTING_FILE}`." ) from err benchmark_spec = _benchmark_at_version(benchmark_group, benchmark_version) if auto_install: auto_install_requirements(benchmark_spec) module, _, name = benchmark_spec["entrypoint"].rpartition(".") entrypoint = _get_entrypoint(module, name) entrypoint( **benchmark_spec.get("params", {}), agent_locator=agent_locator, debug_log=debug_log, )
Runs a benchmark with the given configuration. Use `scl benchmark list` to see the available benchmarks. Args: benchmark_name(str): The name of the benchmark to run. benchmark_version(float|None): The version of the benchmark. agent_locator(str): Locator string for the registered agent. benchmark_listing(pathlib.Path): A configuration file that lists benchmark metadata and must list the target benchmark. debug_log: Debug to `stdout`.
run_benchmark
python
huawei-noah/SMARTS
smarts/benchmark/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/benchmark/__init__.py
MIT
def list_benchmarks(benchmark_listing): """Lists details of the currently available benchmarks.""" from smarts.core.utils.resources import load_yaml_config_with_substitution return load_yaml_config_with_substitution(pathlib.Path(benchmark_listing))
Lists details of the currently available benchmarks.
list_benchmarks
python
huawei-noah/SMARTS
smarts/benchmark/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/benchmark/__init__.py
MIT
def test_e10_drive(get_benchmark_args): """Tests Driving SMARTS 2023.1 and 2023.2 benchmarks using `examples/e10_drive` model.""" from contrib_policy.policy import Policy agent_locator = "examples.e10_drive.inference:contrib-agent-v0" action = 1 with mock.patch.object(Policy, "_get_model", _get_model(action)): benchmark(benchmark_args=get_benchmark_args, agent_locator=agent_locator)
Tests Driving SMARTS 2023.1 and 2023.2 benchmarks using `examples/e10_drive` model.
test_e10_drive
python
huawei-noah/SMARTS
smarts/benchmark/tests/test_benchmark_runner.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/benchmark/tests/test_benchmark_runner.py
MIT
def test_e11_platoon(get_benchmark_args): """Tests Driving SMARTS 2023.3 benchmark using `examples/e11_platoon` model.""" from contrib_policy.policy import Policy agent_locator = "examples.e11_platoon.inference:contrib-agent-v0" action = 2 with mock.patch.object(Policy, "_get_model", _get_model(action)): benchmark(benchmark_args=get_benchmark_args, agent_locator=agent_locator)
Tests Driving SMARTS 2023.3 benchmark using `examples/e11_platoon` model.
test_e11_platoon
python
huawei-noah/SMARTS
smarts/benchmark/tests/test_benchmark_runner.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/benchmark/tests/test_benchmark_runner.py
MIT
def benchmark(benchmark_args, agent_locator) -> Tuple[Dict, Dict]: """Runs the benchmark using the following: Args: benchmark_args(dict): Arguments configuring the benchmark. agent_locator(str): Locator string for the registered agent. debug_log(bool): Whether the benchmark should log to `stdout`. """ print(f"\n\n<-- Starting `{benchmark_args['name']}` benchmark -->\n") message = benchmark_args.get("message") if message is not None: print(message) debug = benchmark_args.get("debug", {}) iterator = _serial_task_iterator if debug.get("serial") else _parallel_task_iterator root_dir = Path(__file__).resolve().parents[3] metric_formula_default = ( root_dir / "smarts" / "env" / "gymnasium" / "wrappers" / "metric" / "formula.py" ) weighted_scores, agent_scores = {}, {} for env_name, env_config in benchmark_args["envs"].items(): metric_formula = ( root_dir / x if (x := env_config.get("metric_formula", None)) != None else metric_formula_default ) env_args = {} for scenario in env_config["scenarios"]: kwargs = dict(benchmark_args.get("shared_env_kwargs", {})) kwargs.update(env_config.get("kwargs", {})) env_args[f"{env_name}-{scenario}"] = dict( env=env_config.get("loc") or env_config["locator"], scenario=str(root_dir / scenario), kwargs=kwargs, metric_formula=metric_formula, ) records_cumulative: Dict[str, Dict[str, Record]] = {} for _, records in iterator( env_args=env_args, benchmark_args=benchmark_args, agent_locator=agent_locator, ): records_cumulative.update(records) weighted_score = _get_weighted_score( records=records_cumulative, metric_formula=metric_formula ) weighted_scores[env_name] = weighted_score print("\n\nOverall Weighted Score:\n") print(json.dumps(weighted_score, indent=2)) agent_score = _get_agent_score( records=records_cumulative, metric_formula=metric_formula ) agent_scores[env_name] = agent_score print("\n\nIndividual Agent Score:\n") print(json.dumps(agent_score, indent=2)) print("\n<-- Evaluation complete -->\n") return weighted_scores, agent_scores
Runs the benchmark using the following: Args: benchmark_args(dict): Arguments configuring the benchmark. agent_locator(str): Locator string for the registered agent. debug_log(bool): Whether the benchmark should log to `stdout`.
benchmark
python
huawei-noah/SMARTS
smarts/benchmark/entrypoints/benchmark_runner_v0.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/benchmark/entrypoints/benchmark_runner_v0.py
MIT
def benchmark_from_configs(benchmark_config, agent_locator, debug_log=False): """Runs a benchmark given the following. Args: benchmark_config (str): The file path to the benchmark configuration. agent_locator (str): Locator string for the registered agent. debug_log (bool): Deprecated. Whether the benchmark should log to `stdout`. """ benchmark_args = load_config(benchmark_config) benchmark( benchmark_args=benchmark_args["benchmark"], agent_locator=agent_locator, )
Runs a benchmark given the following. Args: benchmark_config (str): The file path to the benchmark configuration. agent_locator (str): Locator string for the registered agent. debug_log (bool): Deprecated. Whether the benchmark should log to `stdout`.
benchmark_from_configs
python
huawei-noah/SMARTS
smarts/benchmark/entrypoints/benchmark_runner_v0.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/benchmark/entrypoints/benchmark_runner_v0.py
MIT
def load_config(path: Path) -> Optional[Dict[str, Any]]: """Load in a benchmark configuration.""" if isinstance(path, (str,)): path = Path(path) return _load_config(path)
Load in a benchmark configuration.
load_config
python
huawei-noah/SMARTS
smarts/benchmark/driving_smarts/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/benchmark/driving_smarts/__init__.py
MIT
def params(self) -> Params: """Return parameters to configure and initialize cost functions. Returns: Params: Cost function parameters. """ params = Params( collisions=Collisions(active=False), comfort=Comfort(active=True), dist_to_destination=DistToDestination(active=True), dist_to_obstacles=DistToObstacles(active=False), jerk_linear=JerkLinear(active=False), lane_center_offset=LaneCenterOffset(active=True), off_road=OffRoad(active=False), speed_limit=SpeedLimit(active=True), steps=Steps(active=False), vehicle_gap=VehicleGap(active=True), wrong_way=WrongWay(active=True), ) return params
Return parameters to configure and initialize cost functions. Returns: Params: Cost function parameters.
params
python
huawei-noah/SMARTS
smarts/benchmark/driving_smarts/v2023/metric_formula_platoon.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/benchmark/driving_smarts/v2023/metric_formula_platoon.py
MIT
def score(self, records: Dict[str, Dict[str, Record]]) -> Score: """ Computes several sub-component scores and one total combined score named "Overall" on the wrapped environment. Args: records (Dict[str, Dict[str, Record]]): Records. Returns: Score: "Overall" score and other sub-component scores. """ agent_weight = agent_weights(records=records) agent_score = agent_scores(records=records, func=costs_to_score) return weighted_score(scores=agent_score, weights=agent_weight)
Computes several sub-component scores and one total combined score named "Overall" on the wrapped environment. Args: records (Dict[str, Dict[str, Record]]): Records. Returns: Score: "Overall" score and other sub-component scores.
score
python
huawei-noah/SMARTS
smarts/benchmark/driving_smarts/v2023/metric_formula_platoon.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/benchmark/driving_smarts/v2023/metric_formula_platoon.py
MIT
def costs_to_score(costs: Costs) -> Score: """Compute score from costs. +-------------------+--------+-----------------------------------------------------------+ | | Range | Remarks | +===================+========+===========================================================+ | Overall | [0, 1] | Total score. The higher, the better. | +-------------------+--------+-----------------------------------------------------------+ | DistToDestination | [0, 1] | Remaining distance to destination. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | VehicleGap | [0, 1] | Gap between vehicles in a convoy. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | HumannessError | [0, 1] | Humanness indicator. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | RuleViolation | [0, 1] | Traffic rules compliance. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ Args: costs (Costs): Costs. Returns: Score: Score. """ dist_to_destination = costs.dist_to_destination humanness_error = _score_humanness_error(costs=costs) rule_violation = score_rule_violation(costs=costs) vehicle_gap = costs.vehicle_gap overall = ( 0.25 * (1 - dist_to_destination) + 0.25 * (1 - vehicle_gap) + 0.25 * (1 - humanness_error) + 0.25 * (1 - rule_violation) ) return Score( { "overall": overall, "dist_to_destination": dist_to_destination, "vehicle_gap": vehicle_gap, "humanness_error": humanness_error, "rule_violation": rule_violation, } )
Compute score from costs. +-------------------+--------+-----------------------------------------------------------+ | | Range | Remarks | +===================+========+===========================================================+ | Overall | [0, 1] | Total score. The higher, the better. | +-------------------+--------+-----------------------------------------------------------+ | DistToDestination | [0, 1] | Remaining distance to destination. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | VehicleGap | [0, 1] | Gap between vehicles in a convoy. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | HumannessError | [0, 1] | Humanness indicator. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | RuleViolation | [0, 1] | Traffic rules compliance. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ Args: costs (Costs): Costs. Returns: Score: Score.
costs_to_score
python
huawei-noah/SMARTS
smarts/benchmark/driving_smarts/v2023/metric_formula_platoon.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/benchmark/driving_smarts/v2023/metric_formula_platoon.py
MIT
def params(self) -> Params: """Return parameters to configure and initialize cost functions. Returns: Params: Cost function parameters. """ params = Params( collisions=Collisions(active=False), comfort=Comfort(active=True), dist_to_destination=DistToDestination(active=True), dist_to_obstacles=DistToObstacles(active=False), jerk_linear=JerkLinear(active=False), lane_center_offset=LaneCenterOffset(active=True), off_road=OffRoad(active=False), speed_limit=SpeedLimit(active=True), steps=Steps(active=True), vehicle_gap=VehicleGap(active=False), wrong_way=WrongWay(active=True), ) return params
Return parameters to configure and initialize cost functions. Returns: Params: Cost function parameters.
params
python
huawei-noah/SMARTS
smarts/benchmark/driving_smarts/v2023/metric_formula_drive.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/benchmark/driving_smarts/v2023/metric_formula_drive.py
MIT
def score(self, records: Dict[str, Dict[str, Record]]) -> Score: """ Computes several sub-component scores and one total combined score named "Overall" on the wrapped environment. Args: records (Dict[str, Dict[str, Record]]): Records. Returns: Score: "Overall" score and other sub-component scores. """ agent_weight = agent_weights(records=records) agent_score = agent_scores(records=records, func=costs_to_score) return weighted_score(scores=agent_score, weights=agent_weight)
Computes several sub-component scores and one total combined score named "Overall" on the wrapped environment. Args: records (Dict[str, Dict[str, Record]]): Records. Returns: Score: "Overall" score and other sub-component scores.
score
python
huawei-noah/SMARTS
smarts/benchmark/driving_smarts/v2023/metric_formula_drive.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/benchmark/driving_smarts/v2023/metric_formula_drive.py
MIT
def costs_to_score(costs: Costs) -> Score: """Compute score from costs. +-------------------+--------+-----------------------------------------------------------+ | | Range | Remarks | +===================+========+===========================================================+ | Overall | [0, 1] | Total score. The higher, the better. | +-------------------+--------+-----------------------------------------------------------+ | DistToDestination | [0, 1] | Remaining distance to destination. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | Time | [0, 1] | Time taken to complete scenario. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | HumannessError | [0, 1] | Humanness indicator. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | RuleViolation | [0, 1] | Traffic rules compliance. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ Args: costs (Costs): Costs. Returns: Score: Score. """ dist_to_destination = costs.dist_to_destination humanness_error = _score_humanness_error(costs=costs) rule_violation = score_rule_violation(costs=costs) time = costs.steps overall = ( 0.25 * (1 - dist_to_destination) + 0.25 * (1 - time) + 0.25 * (1 - humanness_error) + 0.25 * (1 - rule_violation) ) return Score( { "overall": overall, "dist_to_destination": dist_to_destination, "time": time, "humanness_error": humanness_error, "rule_violation": rule_violation, } )
Compute score from costs. +-------------------+--------+-----------------------------------------------------------+ | | Range | Remarks | +===================+========+===========================================================+ | Overall | [0, 1] | Total score. The higher, the better. | +-------------------+--------+-----------------------------------------------------------+ | DistToDestination | [0, 1] | Remaining distance to destination. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | Time | [0, 1] | Time taken to complete scenario. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | HumannessError | [0, 1] | Humanness indicator. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ | RuleViolation | [0, 1] | Traffic rules compliance. The lower, the better. | +-------------------+--------+-----------------------------------------------------------+ Args: costs (Costs): Costs. Returns: Score: Score.
costs_to_score
python
huawei-noah/SMARTS
smarts/benchmark/driving_smarts/v2023/metric_formula_drive.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/benchmark/driving_smarts/v2023/metric_formula_drive.py
MIT
def build_agent(self) -> Agent: """Construct an Agent from the AgentSpec configuration.""" if self.agent_builder is None: raise ValueError("Can't build agent, no agent builder was supplied") if not callable(self.agent_builder): raise ValueError( f"""agent_builder: {self.agent_builder} is not callable Use a combination of agent_params and agent_builder to define how to build your agent, ie. AgentSpec( agent_params={{"input_dimensions": 12}}, agent_builder=MyAgent # we are not instantiating the agent, just passing the class reference ) """ ) if self.agent_params is None: # no args to agent builder return self.agent_builder() elif isinstance(self.agent_params, (list, tuple)): # a list or tuple is treated as positional arguments return self.agent_builder(*self.agent_params) elif isinstance(self.agent_params, dict): # dictionaries, as keyword arguments fas = inspect.getfullargspec(self.agent_builder) if fas[2] is not None: return self.agent_builder(**self.agent_params) else: return self.agent_builder( **{ k: self.agent_params[k] for k in self.agent_params.keys() & set(fas[0]) } ) else: # otherwise, the agent params are sent as is to the builder return self.agent_builder(self.agent_params)
Construct an Agent from the AgentSpec configuration.
build_agent
python
huawei-noah/SMARTS
smarts/zoo/agent_spec.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/zoo/agent_spec.py
MIT
def entry_point(speed=10, **kwargs): """An example entrypoint for a simple agent. This can have any number of arguments similar to the gym environment standard. """ return AgentSpec( AgentInterface( action=ActionSpaceType.RelativeTargetPose, ), agent_builder=RandomRelativeTargetPoseAgent, agent_params=dict(speed=speed), )
An example entrypoint for a simple agent. This can have any number of arguments similar to the gym environment standard.
entry_point
python
huawei-noah/SMARTS
smarts/zoo/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/zoo/__init__.py
MIT
def register(locator: str, entry_point, **kwargs): """Register an AgentSpec with the zoo. In order to load a registered AgentSpec it needs to be reachable from a directory contained in the PYTHONPATH. Args: locator: A string in the format of 'locator-name' entry_point: A callable that returns an AgentSpec or an AgentSpec object For example: .. code-block:: python register( locator="motion-planner-agent-v0", entry_point=lambda **kwargs: AgentSpec( interface=AgentInterface(waypoint_paths=True, action=ActionSpaceType.TargetPose), agent_builder=MotionPlannerAgent, ), ) """ agent_registry.register(name=locator, entry_point=entry_point, **kwargs)
Register an AgentSpec with the zoo. In order to load a registered AgentSpec it needs to be reachable from a directory contained in the PYTHONPATH. Args: locator: A string in the format of 'locator-name' entry_point: A callable that returns an AgentSpec or an AgentSpec object For example: .. code-block:: python register( locator="motion-planner-agent-v0", entry_point=lambda **kwargs: AgentSpec( interface=AgentInterface(waypoint_paths=True, action=ActionSpaceType.TargetPose), agent_builder=MotionPlannerAgent, ), )
register
python
huawei-noah/SMARTS
smarts/zoo/registry.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/zoo/registry.py
MIT
def make(locator: str, **kwargs): """Create an AgentSpec from the given locator. In order to load a registered AgentSpec it needs to be reachable from a directory contained in the PYTHONPATH. Args: locator: A string in the format of 'path.to.file:locator-name' where the path is in the form `{PYTHONPATH}[n]/path/to/file.py` kwargs: Additional arguments to be passed to the constructed class. Returns: AgentSpec: The agent specifications needed to instantiate and configure an agent. """ from smarts.zoo.agent_spec import AgentSpec agent_spec = agent_registry.make(locator, **kwargs) assert isinstance( agent_spec, AgentSpec ), f"Expected make to produce an instance of AgentSpec, got: {agent_spec}" return agent_spec
Create an AgentSpec from the given locator. In order to load a registered AgentSpec it needs to be reachable from a directory contained in the PYTHONPATH. Args: locator: A string in the format of 'path.to.file:locator-name' where the path is in the form `{PYTHONPATH}[n]/path/to/file.py` kwargs: Additional arguments to be passed to the constructed class. Returns: AgentSpec: The agent specifications needed to instantiate and configure an agent.
make
python
huawei-noah/SMARTS
smarts/zoo/registry.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/zoo/registry.py
MIT
def make_agent(locator: str, **kwargs): """Create an Agent from the given agent spec locator. In order to load a registered AgentSpec it needs to be reachable from a directory contained in the PYTHONPATH. Args: locator: A string in the format of 'path.to.file:locator-name' where the path is in the form `{PYTHONPATH}[n]/path/to/file.py` kwargs: Additional arguments to be passed to the constructed class. Returns: Tuple[Agent, AgentInterface]: The agent and its interface. """ agent_spec = make(locator, **kwargs) return agent_spec.build_agent(), agent_spec.interface
Create an Agent from the given agent spec locator. In order to load a registered AgentSpec it needs to be reachable from a directory contained in the PYTHONPATH. Args: locator: A string in the format of 'path.to.file:locator-name' where the path is in the form `{PYTHONPATH}[n]/path/to/file.py` kwargs: Additional arguments to be passed to the constructed class. Returns: Tuple[Agent, AgentInterface]: The agent and its interface.
make_agent
python
huawei-noah/SMARTS
smarts/zoo/registry.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/zoo/registry.py
MIT
def send(self, obs): """Send an observation to the Visdom server.""" try: self._visdom_obs_queue.put(obs, block=False) except Exception: self._log.debug("Dropped Visdom frame instead of blocking")
Send an observation to the Visdom server.
send
python
huawei-noah/SMARTS
smarts/visdom/visdom_client.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/visdom/visdom_client.py
MIT
def teardown(self): """Clean up unmanaged resources.""" if not self._visdom_obs_queue: return self._visdom_obs_queue.put(QueueDone())
Clean up unmanaged resources.
teardown
python
huawei-noah/SMARTS
smarts/visdom/visdom_client.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/visdom/visdom_client.py
MIT
def default(cls): """Give a new default filter.""" return cls(defaultdict(_default_override), defaultdict(_default_override))
Give a new default filter.
default
python
huawei-noah/SMARTS
envision/client_config.py
https://github.com/huawei-noah/SMARTS/blob/master/envision/client_config.py
MIT
def format_actor_id(actor_id: str, vehicle_id: str, is_multi: bool): """A conversion utility to ensure that an actor id conforms to envision's actor id standard. Args: actor_id: The base id of the actor. vehicle_id: The vehicle id of the vehicle the actor associates with. is_multi: If an actor associates with multiple vehicles. Returns: An envision compliant actor id. """ if is_multi: return f"{actor_id}-{{{vehicle_id[:4]}}}" return actor_id
A conversion utility to ensure that an actor id conforms to envision's actor id standard. Args: actor_id: The base id of the actor. vehicle_id: The vehicle id of the vehicle the actor associates with. is_multi: If an actor associates with multiple vehicles. Returns: An envision compliant actor id.
format_actor_id
python
huawei-noah/SMARTS
envision/etypes.py
https://github.com/huawei-noah/SMARTS/blob/master/envision/etypes.py
MIT
def reset(self): """Returns this context back to blank.""" self._current_id = 0 self._mapping = {} self.removed = []
Returns this context back to blank.
reset
python
huawei-noah/SMARTS
envision/data_formatter.py
https://github.com/huawei-noah/SMARTS/blob/master/envision/data_formatter.py
MIT