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 is_close( a: float, b: float, rel_tolerance: float = 1e-09, abs_tolerance: float = 0.0 ) -> bool: """Determines if two values are close as defined by the inputs. Args: a: The first value. b: The other value. rel_tolerance: Difference required to be close relative to the magnitude abs_tolerance: Absolute different allowed to be close. Returns: If the two values are "close". """ return abs(a - b) <= max(rel_tolerance * max(abs(a), abs(b)), abs_tolerance)
Determines if two values are close as defined by the inputs. Args: a: The first value. b: The other value. rel_tolerance: Difference required to be close relative to the magnitude abs_tolerance: Absolute different allowed to be close. Returns: If the two values are "close".
is_close
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def rotate_cw_around_point(point, radians, origin=(0, 0)) -> np.ndarray: """Rotate a point clockwise around a given origin.""" x, y = point ox, oy = origin qx = ox + math.cos(radians) * (x - ox) + math.sin(radians) * (y - oy) qy = oy + -math.sin(radians) * (x - ox) + math.cos(radians) * (y - oy) return np.array([qx, qy])
Rotate a point clockwise around a given origin.
rotate_cw_around_point
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def line_intersect(a, b, c, d) -> Union[np.ndarray, None]: """Check if the lines ``[a, b]`` and ``[c, d]`` intersect, and return the intersection point if so. Otherwise, return None. """ r = b - a s = d - c d = r[0] * s[1] - r[1] * s[0] if d == 0: return None u = ((c[0] - a[0]) * r[1] - (c[1] - a[1]) * r[0]) / d t = ((c[0] - a[0]) * s[1] - (c[1] - a[1]) * s[0]) / d if 0 <= u <= 1 and 0 <= t <= 1: return a + t * r return None
Check if the lines ``[a, b]`` and ``[c, d]`` intersect, and return the intersection point if so. Otherwise, return None.
line_intersect
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def line_intersect_vectorized( a: np.ndarray, b: np.ndarray, C: np.ndarray, D: np.ndarray, ignore_start_pt: bool = False, ) -> bool: """Vectorized version of `line_intersect(...)`, where C and D represent the segment points for an entire line, and a and b are points of a single line segment to be tested against. If ignore_start_pt is True, then two diverging lines that *only* intersect at their starting points will cause this to return False. """ r = b - a S = D - C rs1 = np.multiply(r[0], S[:, 1]) rs2 = np.multiply(r[1], S[:, 0]) d = rs1 - rs2 if not np.any(d): return False u_numerator = np.multiply(C[:, 0] - a[0], r[1]) - np.multiply(C[:, 1] - a[1], r[0]) t_numerator = np.multiply(C[:, 0] - a[0], S[:, 1]) - np.multiply( C[:, 1] - a[1], S[:, 0] ) # Use where=d!=0 to avoid divisions by zero. The out parameter is an # array of [-1, ..., -1], to make sure we're defaulting to something # outside of our expected range for our return result. u = np.divide(u_numerator, d, out=np.zeros_like(u_numerator) - 1, where=d != 0) t = np.divide(t_numerator, d, out=np.zeros_like(t_numerator) - 1, where=d != 0) u_in_range = (0 <= u) & (u <= 1) t_in_range = (0 <= t) & (t <= 1) combined = u_in_range & t_in_range return np.any(combined) and (not ignore_start_pt or any(combined[1:]) or t[0] > 0.0)
Vectorized version of `line_intersect(...)`, where C and D represent the segment points for an entire line, and a and b are points of a single line segment to be tested against. If ignore_start_pt is True, then two diverging lines that *only* intersect at their starting points will cause this to return False.
line_intersect_vectorized
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def ray_boundary_intersect( ray_start, ray_end, boundary_pts, early_return=True ) -> Union[np.ndarray, None]: """Iterate over the boundary segments, returning the nearest intersection point if a ray intersection is found. If early_return is True, this will return the first intersection point that is found.""" vl = len(ray_start) assert vl == len(ray_end) nearest_pt = None min_dist = math.inf for j in range(len(boundary_pts) - 1): b0 = boundary_pts[j][:vl] b1 = boundary_pts[j + 1][:vl] pt = line_intersect(b0, b1, ray_start, ray_end) if pt is not None: if early_return: return pt dist = np.linalg.norm(pt - ray_start) if dist < min_dist: min_dist = dist nearest_pt = pt return nearest_pt
Iterate over the boundary segments, returning the nearest intersection point if a ray intersection is found. If early_return is True, this will return the first intersection point that is found.
ray_boundary_intersect
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def min_angles_difference_signed(first, second) -> float: """The minimum signed difference between angles(radians).""" return ((first - second) + math.pi) % (2 * math.pi) - math.pi
The minimum signed difference between angles(radians).
min_angles_difference_signed
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def wrap_value(value: Union[int, float], _min: float, _max: float) -> float: """Wraps the value around if it goes over max or under min.""" v = value assert isinstance(value, (int, float)) diff = _max - _min if value <= _min: v = _max - (_min - value) % diff if value > _max: v = _min + (value - _max) % diff return v
Wraps the value around if it goes over max or under min.
wrap_value
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def position_to_ego_frame(position, ego_position, ego_heading): """ Get the position in ego vehicle frame given the pose (of either a vehicle or some point) in global frame. Egocentric frame: The ego position becomes origin, and ego heading direction is positive x-axis. Args: position: [x,y,z] ego_position: Ego vehicle [x,y,z] ego_heading: Ego vehicle heading in radians Returns: list: The position [x,y,z] in egocentric view """ transform_matrix = _gen_ego_frame_matrix(ego_heading) ego_rel_position = np.asarray(position) - np.asarray(ego_position) new_position = np.matmul(transform_matrix, ego_rel_position.T).T return new_position.tolist()
Get the position in ego vehicle frame given the pose (of either a vehicle or some point) in global frame. Egocentric frame: The ego position becomes origin, and ego heading direction is positive x-axis. Args: position: [x,y,z] ego_position: Ego vehicle [x,y,z] ego_heading: Ego vehicle heading in radians Returns: list: The position [x,y,z] in egocentric view
position_to_ego_frame
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def world_position_from_ego_frame(position, ego_world_position, ego_world_heading): """ Restore the position from ego given the pose (of either a vehicle or some point) in world frame. world frame: The world (0, 0, 0) becomes origin. Args: position: [x,y,z] ego_world_position: Ego vehicle [x,y,z] ego_world_heading: Ego vehicle heading in radians Returns: list: The position [x,y,z] in world frame """ transform_matrix = _gen_ego_frame_matrix(ego_world_heading) transform_matrix = np.linalg.inv(transform_matrix) rot_position = np.matmul(transform_matrix, np.asarray(position).T).T new_position = np.asarray(rot_position) + np.asarray(ego_world_position) return new_position.tolist()
Restore the position from ego given the pose (of either a vehicle or some point) in world frame. world frame: The world (0, 0, 0) becomes origin. Args: position: [x,y,z] ego_world_position: Ego vehicle [x,y,z] ego_world_heading: Ego vehicle heading in radians Returns: list: The position [x,y,z] in world frame
world_position_from_ego_frame
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def comb(n, k): """Binomial coefficient""" return factorial(n) // (factorial(k) * factorial(n - k))
Binomial coefficient
comb
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def get_bezier_curve(points): """Get the curve function given a series of points. Returns: A curve function that takes a normalized offset [0:1] into the curve. """ n = len(points) - 1 return lambda t: sum( comb(n, i) * t**i * (1 - t) ** (n - i) * points[i] for i in range(n + 1) )
Get the curve function given a series of points. Returns: A curve function that takes a normalized offset [0:1] into the curve.
get_bezier_curve
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def evaluate_bezier(points, total): """Generate the approximated points of a bezier curve given a series of control points. Args: points: The bezier control points. total: The number of points generated from approximating the curve. Returns: An approximation of the bezier curve. """ bezier = get_bezier_curve(points) new_points = np.array([bezier(t) for t in np.linspace(0, 1, total)]) return new_points[:, 0], new_points[:, 1]
Generate the approximated points of a bezier curve given a series of control points. Args: points: The bezier control points. total: The number of points generated from approximating the curve. Returns: An approximation of the bezier curve.
evaluate_bezier
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def inplace_unwrap(wp_array): """Unwraps an array in place.""" ## minor optimization hack adapted from ## https://github.com/numpy/numpy/blob/v1.20.0/numpy/lib/function_base.py#L1492-L1546 ## to avoid unnecessary (slow) np array copy ## (as seen in profiling). p = np.asarray(wp_array) dd = np.subtract(p[1:], p[:-1]) ddmod = np.mod(dd + math.pi, 2 * math.pi) - math.pi np.copyto(ddmod, math.pi, where=(ddmod == -math.pi) & (dd > 0)) ph_correct = ddmod - dd np.copyto(ph_correct, 0, where=abs(dd) < math.pi) p[1:] += ph_correct.cumsum(axis=-1) return p
Unwraps an array in place.
inplace_unwrap
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def round_param_for_dt(dt: float) -> int: """For a given dt, returns what to pass as the second parameter to the `round()` function in order to not lose precision. Note that for whole numbers, like 100, the result will be negative. For example, `round_param_for_dt(100) == -2`, such that `round(190, -2) = 200`.""" strep = np.format_float_positional(dt) decimal = strep.find(".") if decimal >= len(strep) - 1: return 1 - decimal return len(strep) - decimal - 1
For a given dt, returns what to pass as the second parameter to the `round()` function in order to not lose precision. Note that for whole numbers, like 100, the result will be negative. For example, `round_param_for_dt(100) == -2`, such that `round(190, -2) = 200`.
round_param_for_dt
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def rounder_for_dt(dt: float) -> Callable[[float], float]: """Return a rounding function appropriate for time-stepping.""" rp = round_param_for_dt(dt) return lambda f: round(f, rp)
Return a rounding function appropriate for time-stepping.
rounder_for_dt
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def running_mean(prev_mean: float, prev_step: int, new_val: float) -> Tuple[float, int]: """ Returns a new running mean value, when given previous mean, previous step count, and new value, Args: prev_mean (float): Previous mean value. prev_step (int): Previous step count. new_val (float): New value to be averaged. Returns: Tuple[float, int]: Updated mean and step count. """ new_step = prev_step + 1 new_mean = prev_mean + (new_val - prev_mean) / new_step return new_mean, new_step
Returns a new running mean value, when given previous mean, previous step count, and new value, Args: prev_mean (float): Previous mean value. prev_step (int): Previous step count. new_val (float): New value to be averaged. Returns: Tuple[float, int]: Updated mean and step count.
running_mean
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def _unique_element_combination(first, second): """Generates a combination of set of values result groupings only contain values from unique indices. Only works if len(first_group) <= len(second_group). _unique_element_combination('ab', '123') -> (a1 b2) (a1 b3) (a2 b1) (a2 b3) (a3 b1) (a3 b2) _unique_element_combination('abc', '1') -> [] Args: first (Sequence): A sequence of values. second (Sequence): Another sequence of values. Yields: Tuple[Tuple[Any, Any], ...]: A set of index to index combinations. [] if len(first) > len(second) """ result = [[a] for a in first] sl = len(second) rl = len(first) perms = list(permutations(range(sl), r=rl)) for i, p in enumerate(perms): yield tuple( tuple(result[(i * rl + j) % rl] + [second[idx]]) for j, idx in enumerate(p) )
Generates a combination of set of values result groupings only contain values from unique indices. Only works if len(first_group) <= len(second_group). _unique_element_combination('ab', '123') -> (a1 b2) (a1 b3) (a2 b1) (a2 b3) (a3 b1) (a3 b2) _unique_element_combination('abc', '1') -> [] Args: first (Sequence): A sequence of values. second (Sequence): Another sequence of values. Yields: Tuple[Tuple[Any, Any], ...]: A set of index to index combinations. [] if len(first) > len(second)
_unique_element_combination
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def combination_pairs_with_unique_indices( first_group, second_group, second_group_default=None ): """Generates sets of combinations that use up all of the first group and at least as many of the second group. If `len(first_group) > len(second_group)` the second group is padded. Groups are combined using only unique indices per result. The value at an index in one group is matched to the value at an index in from the second group. Duplicate results only appear when element values repeat one of the base groups. ordered_combinations('ab', '123') -> (a1 b2) (a1 b3) (a2 b1) (a2 b3) (a3 b1) (a3 b2) ordered_combinations('ab', '1', default="k") -> (a1 bk) (ak b1) Args: first_group (Sequence): A sequence of values. second_group (Sequence): Another sequence of values which may be padded. default (Any, optional): The default used to pad the second group. Defaults to None. Returns: Generator[Tuple[Tuple[Any, Any], ...], None, None]: Unique index to index pairings using up all elements of the first group and as many of the second group. """ len_first = len(first_group) len_second = len(second_group) if len_second == 0: return product(first_group, [second_group_default]) if len_first > len_second: return _unique_element_combination( first_group, list( chain( second_group, repeat(second_group_default, len_first - len_second) ) ), ) if len_first <= len_second: return _unique_element_combination(first_group, second_group) return []
Generates sets of combinations that use up all of the first group and at least as many of the second group. If `len(first_group) > len(second_group)` the second group is padded. Groups are combined using only unique indices per result. The value at an index in one group is matched to the value at an index in from the second group. Duplicate results only appear when element values repeat one of the base groups. ordered_combinations('ab', '123') -> (a1 b2) (a1 b3) (a2 b1) (a2 b3) (a3 b1) (a3 b2) ordered_combinations('ab', '1', default="k") -> (a1 bk) (ak b1) Args: first_group (Sequence): A sequence of values. second_group (Sequence): Another sequence of values which may be padded. default (Any, optional): The default used to pad the second group. Defaults to None. Returns: Generator[Tuple[Tuple[Any, Any], ...], None, None]: Unique index to index pairings using up all elements of the first group and as many of the second group.
combination_pairs_with_unique_indices
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def slope(horizontal, vertical, default=math.inf): """Safely converts a 2 dimensional direction vector to a slope as ``y/x``. Args: horizontal (float): The x growth rate. vertical (float): The y growth rate. default (float): The default if the value approaches infinity. Defaults to ``1e10``. Returns: float: The slope of the direction vector. """ return safe_division(vertical, horizontal, default=default)
Safely converts a 2 dimensional direction vector to a slope as ``y/x``. Args: horizontal (float): The x growth rate. vertical (float): The y growth rate. default (float): The default if the value approaches infinity. Defaults to ``1e10``. Returns: float: The slope of the direction vector.
slope
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def is_power_of_2(value: int) -> bool: """Test if the given value is a power of 2 greater than 2**0. (e.g. 2**4)""" return (value & (value - 1) == 0) and value != 0
Test if the given value is a power of 2 greater than 2**0. (e.g. 2**4)
is_power_of_2
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def timeit(name: str, log): """Context manger that stopwatches the amount of time between context block start and end. .. code-block:: python import logging with timeit(n,logging.log): a = a * b """ start = time() yield elapsed_time = (time() - start) * 1000 log(f'"{name}" took: {elapsed_time:4f}ms')
Context manger that stopwatches the amount of time between context block start and end. .. code-block:: python import logging with timeit(n,logging.log): a = a * b
timeit
python
huawei-noah/SMARTS
smarts/core/utils/core_logging.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_logging.py
MIT
def isnotebook(): """Determines if executing in ipython (`Jupyter` Notebook)""" try: shell = get_ipython().__class__.__name__ # pytype: disable=name-error if shell == "ZMQInteractiveShell" or "google.colab" in sys.modules: return True # Jupyter notebook or qtconsole or Google Colab except NameError: pass return False
Determines if executing in ipython (`Jupyter` Notebook)
isnotebook
python
huawei-noah/SMARTS
smarts/core/utils/core_logging.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_logging.py
MIT
def try_fsync(fd): """Attempts to see if `fsync` will work. Workaround for error on GitHub Actions.""" try: os.fsync(fd) except OSError: # On GH actions was returning an OSError: [Errno 22] Invalid argument pass
Attempts to see if `fsync` will work. Workaround for error on GitHub Actions.
try_fsync
python
huawei-noah/SMARTS
smarts/core/utils/core_logging.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_logging.py
MIT
def suppress_output(stderr=True, stdout=True): """Attempts to suppress console print statements. .. spelling:word-list:: stderr stdout Args: stderr: Suppress `stderr`. stdout: Suppress `stdout`. """ cleanup_stderr = None cleanup_stdout = None try: if stderr: cleanup_stderr = _suppress_fileout("stderr") if stdout: cleanup_stdout = _suppress_fileout("stdout") yield finally: if stderr and cleanup_stderr: cleanup_stderr(c_stderr) if stdout and cleanup_stdout: cleanup_stdout(c_stdout)
Attempts to suppress console print statements. .. spelling:word-list:: stderr stdout Args: stderr: Suppress `stderr`. stdout: Suppress `stdout`.
suppress_output
python
huawei-noah/SMARTS
smarts/core/utils/core_logging.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_logging.py
MIT
def suppress_websocket(): """Attempts to filter out irritating `websocket` library messages.""" websocket_filter = lambda record: "goodbye" not in record.msg with warnings.catch_warnings(): # XXX: websocket-client library seems to have leaks on connection # retry that cause annoying warnings within Python 3.8+ warnings.filterwarnings("ignore", category=ResourceWarning) # Filter out the websocket "goodbye" messages. _logger = logging.getLogger("websocket") _logger.addFilter(websocket_filter) yield _logger.removeFilter(websocket_filter)
Attempts to filter out irritating `websocket` library messages.
suppress_websocket
python
huawei-noah/SMARTS
smarts/core/utils/core_logging.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_logging.py
MIT
def diff_unpackable(obj, other_obj): """Do an asserted comparison of an object that is able to be unpacked. This works with nested collections: dictionaries, named-tuples, tuples, lists, numpy arrays, and dataclasses. Raises: AssertionError: if objects do not match. """ obj_unpacked = unpack(obj) other_obj_unpacked = unpack(other_obj) def sort(orig_value): value = orig_value if isinstance(value, (dict, defaultdict)): return dict(sorted(value.items(), key=lambda item: item[0])) try: s = sorted(value, key=lambda item: item[0]) except IndexError: s = sorted(value) except (KeyError, TypeError): s = value return s def process(obj, other_obj, current_comparison): if isinstance(obj, (dict, defaultdict)): t_o = sort(obj) assert isinstance(t_o, dict) t_oo = sort(other_obj) assert isinstance(t_oo, dict) comps.append((t_o.keys(), t_oo.keys())) comps.append((t_o.values(), t_oo.values())) elif isinstance(obj, Sequence) and not isinstance(obj, (str)): comps.append((sort(obj), sort(other_obj))) elif obj != other_obj: return f"{obj}!={other_obj} in {current_comparison}" return "" comps = [] result = process(obj_unpacked, other_obj_unpacked, None) while len(comps) > 0: o_oo = comps.pop() for o, oo in zip(*o_oo): if result != "": return result result = process(o, oo, o_oo) return ""
Do an asserted comparison of an object that is able to be unpacked. This works with nested collections: dictionaries, named-tuples, tuples, lists, numpy arrays, and dataclasses. Raises: AssertionError: if objects do not match.
diff_unpackable
python
huawei-noah/SMARTS
smarts/core/utils/core_logging.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_logging.py
MIT
def buffered_shape(shape, width: float = 1.0) -> Polygon: """Generates a shape with a buffer of `width` around the original shape.""" ls = LineString(shape).buffer( width / 2, 1, cap_style=CAP_STYLE.flat, join_style=JOIN_STYLE.round, mitre_limit=5.0, ) if isinstance(ls, MultiPolygon): # Sometimes it oddly outputs a MultiPolygon and then we need to turn it into a convex hull ls = ls.convex_hull elif not isinstance(ls, Polygon): raise RuntimeError("Shapely `object.buffer` behavior may have changed.") return ls
Generates a shape with a buffer of `width` around the original shape.
buffered_shape
python
huawei-noah/SMARTS
smarts/core/utils/geometry.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/geometry.py
MIT
def triangulate_polygon(polygon: Polygon): """Attempts to convert a polygon into triangles.""" # XXX: shapely.ops.triangulate current creates a convex fill of triangles. return [ tri_face for tri_face in triangulate(polygon) if tri_face.centroid.within(polygon) ]
Attempts to convert a polygon into triangles.
triangulate_polygon
python
huawei-noah/SMARTS
smarts/core/utils/geometry.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/geometry.py
MIT
def generate( self, base_params: List[str], sumo_binary: Literal["sumo", "sumo-gui"] = "sumo" ): """Generate the process.""" raise NotImplementedError
Generate the process.
generate
python
huawei-noah/SMARTS
smarts/core/utils/sumo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/sumo_utils.py
MIT
def terminate(self, kill: bool): """Terminate this process.""" raise NotImplementedError
Terminate this process.
terminate
python
huawei-noah/SMARTS
smarts/core/utils/sumo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/sumo_utils.py
MIT
def poll(self) -> Optional[int]: """Poll the underlying process.""" raise NotImplementedError
Poll the underlying process.
poll
python
huawei-noah/SMARTS
smarts/core/utils/sumo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/sumo_utils.py
MIT
def wait(self, timeout: Optional[float] = None) -> int: """Wait on the underlying process.""" raise NotImplementedError
Wait on the underlying process.
wait
python
huawei-noah/SMARTS
smarts/core/utils/sumo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/sumo_utils.py
MIT
def port(self) -> int: """The port this process is associated with.""" raise NotImplementedError
The port this process is associated with.
port
python
huawei-noah/SMARTS
smarts/core/utils/sumo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/sumo_utils.py
MIT
def host(self) -> str: """The port this process is associated with.""" raise NotImplementedError
The port this process is associated with.
host
python
huawei-noah/SMARTS
smarts/core/utils/sumo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/sumo_utils.py
MIT
def connect( self, timeout: float, minimum_traci_version: int, minimum_sumo_version: Tuple[int, ...], debug: bool = False, ): """Attempt a connection with the SUMO process.""" traci_conn = None self._host = self._sumo_process.host self._sumo_port = self._sumo_process.port try: # See if the process is still alive before attempting a connection. with suppress_output(stderr=not debug, stdout=True): traci_conn = traci.connect( self._sumo_process.port, host=self._sumo_process.host, numRetries=max(0, int(20 * timeout)), proc=self._sumo_process, waitBetweenRetries=0.05, ) # SUMO must be ready within timeout seconds # We will retry since this is our first sumo command except traci.exceptions.FatalTraCIError as err: self._log.error( "[%s] TraCI could not connect in time to '%s:%s' [%s]", self._name, self._host, self._sumo_port, err, ) # XXX: Actually not fatal... raise except traci.exceptions.TraCIException as err: self._log.error( "[%s] SUMO process died while trying to connect to '%s:%s' [%s]", self._name, self._host, self._sumo_port, err, ) self.close_traci_and_pipes() raise except ConnectionRefusedError: self._log.error( "[%s] Intended TraCI server '%s:%s' refused connection.", self._name, self._host, self._sumo_port, ) self.close_traci_and_pipes() raise self._connected = True self._traci_conn = traci_conn try: if not self.viable: raise traci.exceptions.TraCIException("TraCI server already finished!?") vers, vers_str = traci_conn.getVersion() if vers < minimum_traci_version: raise ValueError( f"TraCI API version must be >= {minimum_traci_version}. Got version ({vers})" ) self._sumo_version = tuple( int(v) for v in vers_str.partition(" ")[2].split(".") ) # e.g. "SUMO 1.11.0" -> (1, 11, 0) if self._sumo_version < minimum_sumo_version: raise ValueError(f"SUMO version must be >= SUMO {minimum_sumo_version}") except traci.exceptions.FatalTraCIError as err: self._log.error( "[%s] TraCI disconnected for connection attempt '%s:%s': [%s]", self._name, self._host, self._sumo_port, err, ) # XXX: the error type is changed to TraCIException to make it consistent with the # process died case of `traci.connect`. Since TraCIException is fatal just in this case... self.close_traci_and_pipes() raise traci.exceptions.TraCIException(err) except OSError as err: self._log.error( "[%s] OS error occurred for TraCI connection attempt '%s:%s': [%s]", self._name, self._host, self._sumo_port, err, ) self.close_traci_and_pipes() raise traci.exceptions.TraCIException(err) except ValueError: self.close_traci_and_pipes() raise
Attempt a connection with the SUMO process.
connect
python
huawei-noah/SMARTS
smarts/core/utils/sumo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/sumo_utils.py
MIT
def connected(self) -> bool: """Check if the connection is still valid.""" return self._sumo_process is not None and self._connected
Check if the connection is still valid.
connected
python
huawei-noah/SMARTS
smarts/core/utils/sumo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/sumo_utils.py
MIT
def viable(self) -> bool: """If making a connection to the sumo process is still viable.""" return self._sumo_process is not None and self._sumo_process.poll() is None
If making a connection to the sumo process is still viable.
viable
python
huawei-noah/SMARTS
smarts/core/utils/sumo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/sumo_utils.py
MIT
def sumo_version(self) -> Tuple[int, ...]: """Get the current SUMO version as a tuple.""" return self._sumo_version
Get the current SUMO version as a tuple.
sumo_version
python
huawei-noah/SMARTS
smarts/core/utils/sumo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/sumo_utils.py
MIT
def port(self) -> Optional[int]: """Get the used TraCI port.""" return self._sumo_port
Get the used TraCI port.
port
python
huawei-noah/SMARTS
smarts/core/utils/sumo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/sumo_utils.py
MIT
def hostname(self) -> str: """Get the used TraCI port.""" return self._host
Get the used TraCI port.
hostname
python
huawei-noah/SMARTS
smarts/core/utils/sumo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/sumo_utils.py
MIT
def must_reset(self): """If the version of sumo will have errors if just reloading such that it must be reset.""" return self._sumo_version > (1, 12, 0)
If the version of sumo will have errors if just reloading such that it must be reset.
must_reset
python
huawei-noah/SMARTS
smarts/core/utils/sumo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/sumo_utils.py
MIT
def close_traci_and_pipes(self, wait: bool = True, kill: bool = True): """Safely closes all connections. We should expect this method to always work without throwing""" if self._connected: self._log.debug("Closing TraCI connection to %s", self._sumo_port) _safe_close(self._traci_conn, wait=wait) if self._sumo_process: self._sumo_process.terminate(kill=kill) self._log.info( "Killed TraCI server process '%s:%s'", self._host, self._sumo_port ) self._sumo_process = None self._connected = False
Safely closes all connections. We should expect this method to always work without throwing
close_traci_and_pipes
python
huawei-noah/SMARTS
smarts/core/utils/sumo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/sumo_utils.py
MIT
def teardown(self): """Clean up all resources.""" self.close_traci_and_pipes(True) self._traci_conn = None
Clean up all resources.
teardown
python
huawei-noah/SMARTS
smarts/core/utils/sumo_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/sumo_utils.py
MIT
def new(cls, dtype: str): """Creates a new unique id: E.g. 'boid'->'boid-93572825'""" return cls(dtype=dtype, identifier=str(uuid.uuid4())[:8])
Creates a new unique id: E.g. 'boid'->'boid-93572825
new
python
huawei-noah/SMARTS
smarts/core/utils/id.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/id.py
MIT
def parse(cls, id_: str): """Parses the id from a string.""" split = -8 - 1 # should be "-" if id_[split] != "-": raise ValueError( f"id={id_} is invalid, format should be <type>-<8_char_uuid>" ) return cls(dtype=id_[:split], identifier=id_[split + 1 :])
Parses the id from a string.
parse
python
huawei-noah/SMARTS
smarts/core/utils/id.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/id.py
MIT
def dtype(self): """The type of the id.""" return self._dtype
The type of the id.
dtype
python
huawei-noah/SMARTS
smarts/core/utils/id.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/id.py
MIT
def _make_key( args, kwds, typed=False, kwd_mark=(object(),), fasttypes={int, str}, tuple=tuple, type=type, len=len, ): """Make a cache key from optionally typed positional and keyword arguments. The key is constructed in a way that is flat as possible rather than as a nested structure that would take more memory. If there is only a single argument and its data type is known to cache its hash value, then that argument is returned without a wrapper. This saves space and improves lookup speed. """ # All of code below relies on kwds preserving the order input by the user. # Formerly, we sorted() the kwds before looping. The new way is *much* # faster; however, it means that f(x=1, y=2) will now be treated as a # distinct call from f(y=2, x=1) which will be cached separately. key = args if kwds: key += kwd_mark for item in kwds.items(): key += item if typed: key += tuple(type(v) for v in args) if kwds: key += tuple(type(v) for v in kwds.values()) elif len(key) == 1 and type(key[0]) in fasttypes: return key[0] return _HashedSeq(key)
Make a cache key from optionally typed positional and keyword arguments. The key is constructed in a way that is flat as possible rather than as a nested structure that would take more memory. If there is only a single argument and its data type is known to cache its hash value, then that argument is returned without a wrapper. This saves space and improves lookup speed.
_make_key
python
huawei-noah/SMARTS
smarts/core/utils/cache.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/cache.py
MIT
def clear_cache(self): """Clear the instance cache.""" _CacheCallable.external_clear_cache(self._instance, self._cache_key)
Clear the instance cache.
clear_cache
python
huawei-noah/SMARTS
smarts/core/utils/cache.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/cache.py
MIT
def external_clear_cache(instance, cache_key): """Clears the cache on the given instance.""" setattr(instance, cache_key, {})
Clears the cache on the given instance.
external_clear_cache
python
huawei-noah/SMARTS
smarts/core/utils/cache.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/cache.py
MIT
def clear_cache(func): """A decorator that clears `@cache` type caches.""" def _clear_caches(self): for key in self.__dict__: if key.startswith(_CACHE_KEY_PREFIX): _CacheCallable.external_clear_cache(self, key) @functools.wraps(func) def wrapper(self, *args, **kwargs): _clear_caches(self) return func(self, *args, **kwargs) return wrapper
A decorator that clears `@cache` type caches.
clear_cache
python
huawei-noah/SMARTS
smarts/core/utils/cache.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/cache.py
MIT
def import_module_from_file(module_name: str, path: Path): """Attempt to load a module dynamically from a path as `module_name`.""" path = str(path) # Get one directory up if path not in sys.path: sys.path.append(path) spec = importlib.util.spec_from_file_location(module_name, f"{path}") module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module spec.loader.exec_module(module) # pytype: disable=attribute-error
Attempt to load a module dynamically from a path as `module_name`.
import_module_from_file
python
huawei-noah/SMARTS
smarts/core/utils/import_utils.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/import_utils.py
MIT
async def start(self, timeout: Optional[float] = 60.0 * 60.0): """Start the server.""" # Create a socket object server = await asyncio.start_server(self.handle_client, self._host, self._port) address = server.sockets[0].getsockname() print(f"Server listening on `{address = }`") async with server: waitable = server.serve_forever() if timeout is not None: _timeout_watcher = asyncio.create_task(self._timeout_watcher(timeout)) waitable = asyncio.gather(waitable, _timeout_watcher) await waitable
Start the server.
start
python
huawei-noah/SMARTS
smarts/core/utils/centralized_traci_server.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/centralized_traci_server.py
MIT
async def _timeout_watcher(self, timeout: float): """Closes the server if it is not in use for `timeout` length of time.""" while True: await asyncio.sleep(60) if time.time() - self._last_client > timeout and len(self._used_ports) == 0: print(f"Closing because `{timeout=}` was reached.") loop = asyncio.get_event_loop() loop.stop()
Closes the server if it is not in use for `timeout` length of time.
_timeout_watcher
python
huawei-noah/SMARTS
smarts/core/utils/centralized_traci_server.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/centralized_traci_server.py
MIT
async def _process_manager(self, binary, args, f: asyncio.Future): """Manages the lifecycle of the TraCI server.""" _sumo_proc = None _port = None try: # Create a new Future object. while (_port := find_free_port()) in self._used_ports: pass self._used_ports.add(_port) _sumo_proc = await asyncio.create_subprocess_exec( *[ os.path.join(SUMO_PATH, "bin", binary), f"--remote-port={_port}", ], *args, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True, ) loop = asyncio.get_event_loop() future = loop.create_future() f.set_result( { "port": _port, "future": future, } ) result = await asyncio.wait_for(future, None) finally: if _port is not None: self._used_ports.discard(_port) if _sumo_proc is not None and _sumo_proc.returncode is None: _sumo_proc.kill() self._last_client = time.time()
Manages the lifecycle of the TraCI server.
_process_manager
python
huawei-noah/SMARTS
smarts/core/utils/centralized_traci_server.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/centralized_traci_server.py
MIT
async def handle_client(self, reader, writer): """Read data from the client.""" address = writer.get_extra_info("peername") print(f"Received connection from {address}") loop = asyncio.get_event_loop() try: port = None _traci_server_info = None while True: data = await reader.readline() message = data.decode("utf-8") # print(f"Received {message!r} from {addr}") if message.startswith("sumo"): kill_f = loop.create_future() sumo_binary, _, sumo_cmd = message.partition(":") response_list = json.loads(sumo_cmd) command_args = [ *response_list, ] asyncio.create_task( self._process_manager(sumo_binary, command_args, kill_f) ) if _traci_server_info is not None: print("Duplicate start request received.") continue _traci_server_info = await asyncio.wait_for(kill_f, None) port = _traci_server_info["port"] response = f"{self._host}:{port}" print(f"Send TraCI address: {response!r}") writer.write(response.encode("utf-8")) if message.startswith("e:"): if _traci_server_info is None: print("Kill received for uninitialized process.") else: _traci_server_info["future"].set_result("kill") break if len(message) == 0: break # Close the connection await writer.drain() writer.close() except asyncio.CancelledError: # Handle client disconnect pass
Read data from the client.
handle_client
python
huawei-noah/SMARTS
smarts/core/utils/centralized_traci_server.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/centralized_traci_server.py
MIT
def spawn_if_not(remote_host: str, remote_port: int): """Create a new server if it does not already exist. Args: remote_host (str): The host name. remote_port (int): The host port. """ client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: client_socket.connect((remote_host, remote_port)) except (OSError): if remote_host in ("localhost", "127.0.0.1"): command = [ "python", "-m", __name__, "--timeout", "600", "--port", remote_port, ] # Use subprocess.Popen to start the process in the background _ = subprocess.Popen( command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=False, close_fds=True, ) else: client_socket.close()
Create a new server if it does not already exist. Args: remote_host (str): The host name. remote_port (int): The host port.
spawn_if_not
python
huawei-noah/SMARTS
smarts/core/utils/centralized_traci_server.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/centralized_traci_server.py
MIT
def main(*_, _host=None, _port=None, timeout: Optional[float] = 10 * 60): """The program entrypoint.""" # Define the host and port on which the server will listen _host = _host or config()( "sumo", "central_host" ) # Use '0.0.0.0' to listen on all available interfaces _port = _port or config()("sumo", "central_port") ss = CentralizedTraCIServer(_host, _port) asyncio.run(ss.start(timeout=timeout))
The program entrypoint.
main
python
huawei-noah/SMARTS
smarts/core/utils/centralized_traci_server.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/centralized_traci_server.py
MIT
def load_vehicle_definitions_list(vehicle_list_filepath: Optional[str]): """Load a vehicle definition list file.""" if (vehicle_list_filepath is None) or not os.path.exists(vehicle_list_filepath): vehicle_list_filepath = config()("assets", "default_vehicle_definitions_list") vehicle_list_filepath = Path(vehicle_list_filepath).absolute() return VehicleDefinitions( data=load_yaml_config_with_substitution(vehicle_list_filepath), filepath=vehicle_list_filepath, )
Load a vehicle definition list file.
load_vehicle_definitions_list
python
huawei-noah/SMARTS
smarts/core/utils/resources.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/resources.py
MIT
def load_yaml_config(path: Path) -> Optional[Dict[str, Any]]: """Read in a yaml configuration to dictionary format.""" config = None if path.exists(): assert path.suffix in (".yaml", ".yml"), f"`{str(path)}` is not a YAML file." with open(path, "r", encoding="utf-8") as file: config = yaml.safe_load(file) return config
Read in a yaml configuration to dictionary format.
load_yaml_config
python
huawei-noah/SMARTS
smarts/core/utils/resources.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/resources.py
MIT
def load_yaml_config_with_substitution( path: Union[str, Path] ) -> Optional[Dict[str, Any]]: """Read in a yaml configuration to dictionary format replacing instances of ${{module}} with module's file path and ${} with the SMARTS environment variable.""" smarts_config = config() out_config = None if isinstance(path, str): path = Path(path) if path.exists(): assert path.suffix in (".yaml", ".yml"), f"`{str(path)}` is not a YAML file." with tempfile.NamedTemporaryFile("w", suffix=".py", dir=path.parent) as c: with open(str(path), "r", encoding="utf-8") as o: pattern = re.compile(r"\$\{\{(.+)\}\}") conf = o.read() match = pattern.findall(conf) if match: for val in match: conf = _replace_with_module_path(conf, val) conf = smarts_config.substitute_settings(conf, path.__str__()) c.write(conf) c.flush() with open(c.name, "r", encoding="utf-8") as file: out_config = yaml.safe_load(file) return out_config
Read in a yaml configuration to dictionary format replacing instances of ${{module}} with module's file path and ${} with the SMARTS environment variable.
load_yaml_config_with_substitution
python
huawei-noah/SMARTS
smarts/core/utils/resources.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/resources.py
MIT
def load_vehicle_definition(self, vehicle_class: str): """Loads in a particular vehicle definition.""" if vehicle_definition_filepath := self.data.get(vehicle_class): return load_yaml_config_with_substitution(Path(vehicle_definition_filepath)) raise OSError( f"Vehicle '{vehicle_class}' is not defined in {list(self.data.keys())}" )
Loads in a particular vehicle definition.
load_vehicle_definition
python
huawei-noah/SMARTS
smarts/core/utils/resources.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/resources.py
MIT
def controller_params_for_vehicle_class(self, vehicle_class: str): """Get the controller parameters for the given vehicle type""" vehicle_definition = self.load_vehicle_definition(vehicle_class) controller_params = Path(vehicle_definition["controller_params"]) return load_yaml_config_with_substitution(controller_params)
Get the controller parameters for the given vehicle type
controller_params_for_vehicle_class
python
huawei-noah/SMARTS
smarts/core/utils/resources.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/resources.py
MIT
def chassis_params_for_vehicle_class(self, vehicle_class: str): """Get the controller parameters for the given vehicle type""" vehicle_definition = self.load_vehicle_definition(vehicle_class) chassis_parms = Path(vehicle_definition["chassis_params"]) return load_yaml_config_with_substitution(chassis_parms)
Get the controller parameters for the given vehicle type
chassis_params_for_vehicle_class
python
huawei-noah/SMARTS
smarts/core/utils/resources.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/resources.py
MIT
def reset_pose(self, pose: Pose): """Resets the box to the given pose. Only call this before it needs to do anything physics-wise """ position, orientation = pose.as_bullet() self._client.resetBasePositionAndOrientation( self._bullet_id, np.sum([position, [0, 0, self._height * 0.5]], axis=0), orientation, )
Resets the box to the given pose. Only call this before it needs to do anything physics-wise
reset_pose
python
huawei-noah/SMARTS
smarts/core/utils/bullet.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/bullet.py
MIT
def teardown(self): """Cleans up bullet resource handles.""" self._client.removeBody(self._bullet_id) self._bullet_id = None
Cleans up bullet resource handles.
teardown
python
huawei-noah/SMARTS
smarts/core/utils/bullet.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/bullet.py
MIT
def move_to(self, pose: Pose): """Moves the constraint to the given pose. The attached shape will attempt to follow.""" if not self._bullet_cid: self._make_constraint(pose) position, orientation = pose.as_bullet() # TODO: Consider to remove offset when collision is improved # Move constraints slightly up to avoid ground collision ground_position = position + [0, 0, 0.2] self._client.changeConstraint(self._bullet_cid, ground_position, orientation)
Moves the constraint to the given pose. The attached shape will attempt to follow.
move_to
python
huawei-noah/SMARTS
smarts/core/utils/bullet.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/bullet.py
MIT
def teardown(self): """Clean up unmanaged resources.""" if self._bullet_cid is not None: self._client.removeConstraint(self._bullet_cid) self._bullet_cid = None
Clean up unmanaged resources.
teardown
python
huawei-noah/SMARTS
smarts/core/utils/bullet.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/bullet.py
MIT
def dummy_observation() -> Observation: """A dummy observation for tests and conversion.""" return Observation( dt=0.1, step_count=1, elapsed_sim_time=0.2, events=Events( collisions=(Collision("v", "2"),), off_road=False, off_route=False, on_shoulder=False, wrong_way=False, not_moving=False, reached_goal=False, reached_max_episode_steps=False, agents_alive_done=False, interest_done=False, ), ego_vehicle_state=EgoVehicleObservation( id="AGENT-007-07a0ca6e", position=(161.23485529, 3.2, 0.0), bounding_box=Dimensions(length=3.68, width=1.47, height=1.0), heading=Heading(-1.5707963267948966), speed=5.0, steering=-0.0, yaw_rate=4.71238898038469, road_id="east", lane_id="east_2", lane_index=2, lane_position=RefLinePoint(161.23485529, 0.0, 0.0), mission=NavigationMission( start=Start( position=np.array([163.07485529, 3.2]), heading=Heading(-1.5707963267948966), from_front_bumper=True, ), goal=EndlessGoal(), route_vias=(), start_time=0.1, entry_tactic=t.TrapEntryTactic( start_time=0, zone=None, exclusion_prefixes=(), default_entry_speed=None, ), via=(), vehicle_spec=None, ), linear_velocity=(5.000000e00, 3.061617e-16, 0.000000e00), angular_velocity=(0.0, 0.0, 0.0), linear_acceleration=(0.0, 0.0, 0.0), angular_acceleration=(0.0, 0.0, 0.0), linear_jerk=(0.0, 0.0, 0.0), angular_jerk=(0.0, 0.0, 0.0), ), under_this_agent_control=True, neighborhood_vehicle_states=( VehicleObservation( id="car-west_0_0-east_0_max-784511-726648-0-0.0", position=(-1.33354215, -3.2, 0.0), bounding_box=Dimensions(length=3.68, width=1.47, height=1.4), heading=Heading(-1.5707963267948966), speed=5.050372796758114, road_id="west", lane_id="west_0", lane_index=0, lane_position=RefLinePoint(-1.33354215, 0.0, 0.0), ), VehicleObservation( id="car-west_1_0-east_1_max--85270-726648-1-0.0", position=(-1.47159011, 0.0, 0.0), bounding_box=Dimensions(length=3.68, width=1.47, height=1.4), heading=Heading(-1.5707963267948966), speed=3.6410559446059954, road_id="west", lane_id="west_1", lane_index=1, lane_position=RefLinePoint(-1.47159011, 0.0, 0.0), ), ), waypoint_paths=[ [ Waypoint( pos=np.array([192.00733923, -3.2]), heading=Heading(-1.5707963267948966), lane_id="east_0", lane_width=3.2, speed_limit=5.0, lane_index=0, lane_offset=192.00733923, ), Waypoint( pos=np.array([193.0, -3.2]), heading=Heading(-1.5707963267948966), lane_id="east_0", lane_width=3.2, speed_limit=5.0, lane_index=0, lane_offset=193.0, ), ], [ Waypoint( pos=np.array([192.00733923, 0.0]), heading=Heading(-1.5707963267948966), lane_id="east_1", lane_width=3.2, speed_limit=5.0, lane_index=1, lane_offset=192.00733923, ), Waypoint( pos=np.array([193.0, 0.0]), heading=Heading(-1.5707963267948966), lane_id="east_1", lane_width=3.2, speed_limit=5.0, lane_index=1, lane_offset=193.0, ), ], ], distance_travelled=0.0, lidar_point_cloud=( [ np.array([1.56077973e02, 5.56008599e00, -7.24975635e-14]), np.array([math.inf, math.inf, math.inf]), np.array([math.inf, math.inf, math.inf]), np.array([1.66673185e02, 1.59127180e00, 9.07052211e-14]), ], [ True, False, False, True, ], [ ( np.array([161.23485529, 3.2, 1.0]), np.array([143.32519217, 11.39649262, -2.47296355]), ), ( np.array([161.23485529, 3.2, 1.0]), np.array([158.45533372, 22.69904572, -2.47296355]), ), ( np.array([161.23485529, 3.2, 1.0]), np.array([176.14095458, 16.07426611, -2.47296355]), ), ( np.array([161.23485529, 3.2, 1.0]), np.array([180.12197649, -2.38705439, -2.47296355]), ), ], ), drivable_area_grid_map=DrivableAreaGridMap( metadata=GridMapMetadata( resolution=0.1953125, width=256, height=256, camera_position=(161.235, 3.2, 73.6), camera_heading=-math.pi / 2, ), data=np.array( [ [[0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0]], ], dtype=np.uint8, ), ), occupancy_grid_map=OccupancyGridMap( metadata=GridMapMetadata( resolution=0.1953125, width=256, height=256, camera_position=(161.235, 3.2, 73.6), camera_heading=-math.pi / 2, ), data=np.array( [ [[0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0]], [[0], [0], [0], [0], [0], [0]], ], dtype=np.uint8, ), ), top_down_rgb=TopDownRGB( metadata=GridMapMetadata( resolution=0.1953125, width=256, height=256, camera_position=(161.235, 3.2, 73.6), camera_heading=-math.pi / 2, ), data=np.array( [ [ [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], ], [ [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], ], ], dtype=np.uint8, ), ), road_waypoints=RoadWaypoints( lanes={ "east_0": [ [ Waypoint( pos=np.array([180.00587138, -3.2]), heading=Heading(-1.5707963267948966), lane_id="east_0", lane_width=3.2, speed_limit=5.0, lane_index=0, lane_offset=180.00587138, ), Waypoint( pos=np.array([181.0, -3.2]), heading=Heading(-1.5707963267948966), lane_id="east_0", lane_width=3.2, speed_limit=5.0, lane_index=0, lane_offset=181.0, ), ] ], "east_1": [ [ Waypoint( pos=np.array([180.00587138, 0.0]), heading=Heading(-1.5707963267948966), lane_id="east_1", lane_width=3.2, speed_limit=5.0, lane_index=1, lane_offset=180.00587138, ), Waypoint( pos=np.array([181.0, 0.0]), heading=Heading(-1.5707963267948966), lane_id="east_1", lane_width=3.2, speed_limit=5.0, lane_index=1, lane_offset=181.0, ), ] ], } ), signals=( SignalObservation( SignalLightState.GO, Point(181.0, 0.0), ("east_1",), None ), ), via_data=Vias(near_via_points=(ViaPoint((181.0, 0.0), 1, "east", 5.0, False),)), steps_completed=4, )
A dummy observation for tests and conversion.
dummy_observation
python
huawei-noah/SMARTS
smarts/core/utils/dummy.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/dummy.py
MIT
def replace_rgb_image_color( rgb: np.ndarray, old_color: Sequence[np.ndarray], new_color: np.ndarray, mask: np.ndarray = np.ma.nomask, ) -> np.ndarray: """Convert pixels of value `old_color` to `new_color` within the masked region in the received RGB image. Args: rgb (np.ndarray): RGB image. Shape = (m,n,3). old_color (Sequence[np.ndarray]): List of old colors to be removed from the RGB image. Shape = (3,). new_color (np.ndarray): New color to be added to the RGB image. Shape = (3,). mask (np.ndarray, optional): Valid regions for color replacement. Shape = (m,n,3). Defaults to np.ma.nomask . Returns: np.ndarray: RGB image with `old_color` pixels changed to `new_color` within the masked region. Shape = (m,n,3). """ # fmt: off assert all(color.shape == (3,) for color in old_color), ( f"Expected old_color to be of shape (3,), but got {[color.shape for color in old_color]}.") assert new_color.shape == (3,), ( f"Expected new_color to be of shape (3,), but got {new_color.shape}.") nc = new_color.reshape((1, 1, 3)) nc_array = np.full_like(rgb, nc) rgb_masked = np.ma.MaskedArray(data=rgb, mask=mask) rgb_condition = rgb_masked result = rgb for color in old_color: result = np.ma.where((rgb_condition == color.reshape((1, 1, 3))).all(axis=-1)[..., None], nc_array, result) return result
Convert pixels of value `old_color` to `new_color` within the masked region in the received RGB image. Args: rgb (np.ndarray): RGB image. Shape = (m,n,3). old_color (Sequence[np.ndarray]): List of old colors to be removed from the RGB image. Shape = (3,). new_color (np.ndarray): New color to be added to the RGB image. Shape = (3,). mask (np.ndarray, optional): Valid regions for color replacement. Shape = (m,n,3). Defaults to np.ma.nomask . Returns: np.ndarray: RGB image with `old_color` pixels changed to `new_color` within the masked region. Shape = (m,n,3).
replace_rgb_image_color
python
huawei-noah/SMARTS
smarts/core/utils/observations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/observations.py
MIT
def points_to_pixels( points: np.ndarray, center_position: np.ndarray, heading: float, width: int, height: int, resolution: float, ) -> np.ndarray: """Converts points into pixel coordinates in order to superimpose the points onto the RGB image. Args: points (np.ndarray): Array of points. Shape (n,3). center_position (np.ndarray): Center position of image. Generally, this is equivalent to ego position. Shape = (3,). heading (float): Heading of image in radians. Generally, this is equivalent to ego heading. width (int): Width of RGB image height (int): Height of RGB image. resolution (float): Resolution of RGB image in meters/pixels. Computed as ground_size/image_size. Returns: np.ndarray: Array of point coordinates on the RGB image. Shape = (m,3). """ # fmt: off mask = np.array([not all(point == np.zeros(3,)) for point in points], dtype=bool) points_nonzero = points[mask] points_delta = points_nonzero - center_position points_rotated = rotate_axes(points_delta, theta=heading) points_pixels = points_rotated / np.array([resolution, resolution, resolution]) points_overlay = np.array([width / 2, height / 2, 0]) + points_pixels * np.array([1, -1, 1]) points_rfloat = np.rint(points_overlay) points_valid = points_rfloat[(points_rfloat[:,0] >= 0) & (points_rfloat[:,0] < width) & (points_rfloat[:,1] >= 0) & (points_rfloat[:,1] < height)] points_rint = points_valid.astype(int) return points_rint
Converts points into pixel coordinates in order to superimpose the points onto the RGB image. Args: points (np.ndarray): Array of points. Shape (n,3). center_position (np.ndarray): Center position of image. Generally, this is equivalent to ego position. Shape = (3,). heading (float): Heading of image in radians. Generally, this is equivalent to ego heading. width (int): Width of RGB image height (int): Height of RGB image. resolution (float): Resolution of RGB image in meters/pixels. Computed as ground_size/image_size. Returns: np.ndarray: Array of point coordinates on the RGB image. Shape = (m,3).
points_to_pixels
python
huawei-noah/SMARTS
smarts/core/utils/observations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/observations.py
MIT
def rotate_axes(points: np.ndarray, theta: float) -> np.ndarray: """A counterclockwise rotation of the x-y axes by an angle theta θ about the z-axis. Args: points (np.ndarray): x,y,z coordinates in original axes. Shape = (n,3). theta (np.float): Axes rotation angle in radians. Returns: np.ndarray: x,y,z coordinates in rotated axes. Shape = (n,3). """ # fmt: off theta = (theta + np.pi) % (2 * np.pi) - np.pi ct, st = np.cos(theta), np.sin(theta) R = np.array([[ ct, st, 0], [-st, ct, 0], [ 0, 0, 1]]) rotated_points = (R.dot(points.T)).T return rotated_points
A counterclockwise rotation of the x-y axes by an angle theta θ about the z-axis. Args: points (np.ndarray): x,y,z coordinates in original axes. Shape = (n,3). theta (np.float): Axes rotation angle in radians. Returns: np.ndarray: x,y,z coordinates in rotated axes. Shape = (n,3).
rotate_axes
python
huawei-noah/SMARTS
smarts/core/utils/observations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/observations.py
MIT
def find_free_port(): """Attempt to find an open networking port.""" with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: s.bind(("", 0)) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) return s.getsockname()[1]
Attempt to find an open networking port.
find_free_port
python
huawei-noah/SMARTS
smarts/core/utils/networking.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/networking.py
MIT
def insert(self, index: int, item): """Insert an item into the sequence.""" self.it.insert(index, item)
Insert an item into the sequence.
insert
python
huawei-noah/SMARTS
smarts/core/utils/key_wrapper.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/key_wrapper.py
MIT
def below_threshold(cls, desired_fps, delta): """Generate a frame-rate exception. Args: desired_fps: The intended fps. delta: The frame time taken. Returns: A new frame-rate exception. """ return cls( f"The frame rate decreased, lower than the desired threshold, \ desired: {desired_fps} fps, actual: {round(1000 / delta, 2)} fps." )
Generate a frame-rate exception. Args: desired_fps: The intended fps. delta: The frame time taken. Returns: A new frame-rate exception.
below_threshold
python
huawei-noah/SMARTS
smarts/core/utils/frame_monitor.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/frame_monitor.py
MIT
def start(self): """Starts timing the frame.""" self._start_time_ms = self._time_now()
Starts timing the frame.
start
python
huawei-noah/SMARTS
smarts/core/utils/frame_monitor.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/frame_monitor.py
MIT
def stop(self): """Ends timing the frame. Throws an exception if the frame duration is greater than desired fps. """ if self._start_time_ms is None: print("The monitor has not started yet.") return -1 now = self._time_now() delta = now - self._start_time_ms actual_fps = round(1000 / delta, 2) if actual_fps < self._desired_fps: raise FramerateException.below_threshold(self._desired_fps, delta) return actual_fps
Ends timing the frame. Throws an exception if the frame duration is greater than desired fps.
stop
python
huawei-noah/SMARTS
smarts/core/utils/frame_monitor.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/frame_monitor.py
MIT
def __init__(self, connection_mode=None): """Creates a Bullet client and connects to a simulation. Args: connection_mode: `None` connects to an existing simulation or, if fails, creates a new headless simulation, `pybullet.GUI` creates a new simulation with a GUI, `pybullet.DIRECT` creates a headless simulation, `pybullet.SHARED_MEMORY` connects to an existing simulation. """ with suppress_output(stderr=False): super().__init__(connection_mode=connection_mode)
Creates a Bullet client and connects to a simulation. Args: connection_mode: `None` connects to an existing simulation or, if fails, creates a new headless simulation, `pybullet.GUI` creates a new simulation with a GUI, `pybullet.DIRECT` creates a headless simulation, `pybullet.SHARED_MEMORY` connects to an existing simulation.
__init__
python
huawei-noah/SMARTS
smarts/core/utils/pybullet.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/pybullet.py
MIT
def __del__(self): """Clean up connection if not already done.""" try: super().__del__() except TypeError as error: # Pybullet 3.2.6 currently attempts to catch an error type that does not exist. if not error.args[0].contains("BaseException"): raise
Clean up connection if not already done.
__del__
python
huawei-noah/SMARTS
smarts/core/utils/pybullet.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/pybullet.py
MIT
def __getattr__(self, name): """Inject the client id into Bullet functions.""" if name in {"__deepcopy__", "__getstate__", "__setstate__"}: raise RuntimeError(f"{self.__class__} does not allow `{name}`") return super().__getattr__(name)
Inject the client id into Bullet functions.
__getattr__
python
huawei-noah/SMARTS
smarts/core/utils/pybullet.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/pybullet.py
MIT
def consume(bullet_connect_mode, connection: Connection): """Builds a child pybullet process. Args: bullet_connect_mode: The type of bullet process. connection: The child end of a pipe. """ # runs in sep. process client = SafeBulletClient(bullet_connect_mode) while True: method, args, kwargs = connection.recv() result = getattr(client, method)(*args, **kwargs) connection.send(result)
Builds a child pybullet process. Args: bullet_connect_mode: The type of bullet process. connection: The child end of a pipe.
consume
python
huawei-noah/SMARTS
smarts/core/utils/pybullet.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/pybullet.py
MIT
def file_in_folder(filename: str, path: str) -> bool: """Checks to see if a file exists Args: filename: The name of the file. path: The path to the directory of the file. Returns: If the file exists. """ return os.path.exists(os.path.join(path, filename))
Checks to see if a file exists Args: filename: The name of the file. path: The path to the directory of the file. Returns: If the file exists.
file_in_folder
python
huawei-noah/SMARTS
smarts/core/utils/file.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/file.py
MIT
def isnamedtupleinstance(x): """Check to see if an object is a named tuple.""" t = type(x) b = t.__bases__ if len(b) != 1 or b[0] != tuple: return False f = getattr(t, "_fields", None) if not isinstance(f, tuple): return False return all(type(n) == str for n in f)
Check to see if an object is a named tuple.
isnamedtupleinstance
python
huawei-noah/SMARTS
smarts/core/utils/file.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/file.py
MIT
def replace(obj: Any, **kwargs): """Replace dataclasses and named tuples with the same interface.""" if isnamedtupleinstance(obj): return obj._replace(**kwargs) elif dataclasses.is_dataclass(obj): return dataclasses.replace(obj, **kwargs) raise ValueError("Must be a namedtuple or dataclass.")
Replace dataclasses and named tuples with the same interface.
replace
python
huawei-noah/SMARTS
smarts/core/utils/file.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/file.py
MIT
def isdataclass(x): """Check if an object is a `dataclass`.""" return dataclasses.is_dataclass(x)
Check if an object is a `dataclass`.
isdataclass
python
huawei-noah/SMARTS
smarts/core/utils/file.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/file.py
MIT
def unpack(obj): """A helper that can be used to print nested data objects (`tuple`, `dataclass`, `namedtuple`, ...). For example, ```python pprint(unpack(obs), indent=1, width=80, compact=True) ``` """ if isinstance(obj, dict): return {key: unpack(value) for key, value in obj.items()} elif isinstance(obj, (list, np.ndarray)): return [unpack(value) for value in obj] elif isnamedtupleinstance(obj): return {key: unpack(value) for key, value in obj._asdict().items()} elif isdataclass(obj): return {key: unpack(value) for key, value in dataclasses.asdict(obj).items()} elif isinstance(obj, tuple): return tuple(unpack(value) for value in obj) else: return obj
A helper that can be used to print nested data objects (`tuple`, `dataclass`, `namedtuple`, ...). For example, ```python pprint(unpack(obs), indent=1, width=80, compact=True) ```
unpack
python
huawei-noah/SMARTS
smarts/core/utils/file.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/file.py
MIT
def copy_tree(from_path, to_path, overwrite=False): """Copy a directory tree (including files) to another location. Args: from_path: The directory to copy. to_path: The output directory. overwrite: If to overwrite the output directory. """ if os.path.exists(to_path): if overwrite: shutil.rmtree(to_path) else: raise FileExistsError( "The destination path={} already exists.".format(to_path) ) shutil.copytree(from_path, to_path)
Copy a directory tree (including files) to another location. Args: from_path: The directory to copy. to_path: The output directory. overwrite: If to overwrite the output directory.
copy_tree
python
huawei-noah/SMARTS
smarts/core/utils/file.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/file.py
MIT
def path2hash(file_path: str): """Converts a file path to a hash value.""" m = hashlib.md5() m.update(bytes(file_path, "utf-8")) return m.hexdigest()
Converts a file path to a hash value.
path2hash
python
huawei-noah/SMARTS
smarts/core/utils/file.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/file.py
MIT
def file_md5_hash(file_path: str) -> str: """Converts file contents to a hash value. Useful for doing a file diff.""" hasher = hashlib.md5() with open(file_path) as f: hasher.update(f.read().encode()) return str(hasher.hexdigest())
Converts file contents to a hash value. Useful for doing a file diff.
file_md5_hash
python
huawei-noah/SMARTS
smarts/core/utils/file.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/file.py
MIT
def pickle_hash(obj, include_version=False) -> str: """Converts a Python object to a hash value. NOTE: NOT stable across different Python versions.""" pickle_bytes = pickle.dumps(obj, protocol=4) hasher = hashlib.md5() hasher.update(pickle_bytes) if include_version: hasher.update(smarts.VERSION.encode()) return hasher.hexdigest()
Converts a Python object to a hash value. NOTE: NOT stable across different Python versions.
pickle_hash
python
huawei-noah/SMARTS
smarts/core/utils/file.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/file.py
MIT
def pickle_hash_int(obj) -> int: """Converts a Python object to a hash value. NOTE: NOT stable across different Python versions.""" hash_str = pickle_hash(obj) val = int(hash_str, 16) return c_int64(val).value
Converts a Python object to a hash value. NOTE: NOT stable across different Python versions.
pickle_hash_int
python
huawei-noah/SMARTS
smarts/core/utils/file.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/file.py
MIT
def smarts_local_user_dir() -> str: """Retrieves the smarts logging directory. Returns: str: The smarts local user directory path. """ ## Following should work for linux and macos smarts_dir = os.path.join(os.path.expanduser("~"), ".smarts") os.makedirs(smarts_dir, exist_ok=True) return smarts_dir
Retrieves the smarts logging directory. Returns: str: The smarts local user directory path.
smarts_local_user_dir
python
huawei-noah/SMARTS
smarts/core/utils/file.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/file.py
MIT
def smarts_global_user_dir() -> str: """Retrieves the smarts global user directory. Returns: str: The smarts global user directory path. """ smarts_dir = os.path.join("/etc", "smarts") return smarts_dir
Retrieves the smarts global user directory. Returns: str: The smarts global user directory path.
smarts_global_user_dir
python
huawei-noah/SMARTS
smarts/core/utils/file.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/file.py
MIT
def make_dir_in_smarts_log_dir(dir): """Return a new directory location in the smarts logging directory.""" return os.path.join(smarts_local_user_dir(), dir)
Return a new directory location in the smarts logging directory.
make_dir_in_smarts_log_dir
python
huawei-noah/SMARTS
smarts/core/utils/file.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/file.py
MIT
def suppress_pkg_resources(): """A context manager that injects an `ImportError` into the `pkg_resources` module to force package fallbacks in imports that can use alternatives to `pkg_resources`. """ import sys import pkg_resources from smarts.core.utils.invalid import raise_import_error pkg_res = sys.modules["pkg_resources"] sys.modules["pkg_resources"] = property(raise_import_error) yield sys.modules["pkg_resources"] = pkg_res
A context manager that injects an `ImportError` into the `pkg_resources` module to force package fallbacks in imports that can use alternatives to `pkg_resources`.
suppress_pkg_resources
python
huawei-noah/SMARTS
smarts/core/utils/file.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/file.py
MIT
def read_tfrecord_file(path: str) -> Generator[bytes, None, None]: """Iterate over the records in a TFRecord file and return the bytes of each record. path: The path to the TFRecord file """ with open(path, "rb") as f: while True: length_bytes = f.read(8) if len(length_bytes) != 8: return record_len = int(struct.unpack("Q", length_bytes)[0]) _ = f.read(4) # masked_crc32_of_length (ignore) record_data = f.read(record_len) _ = f.read(4) # masked_crc32_of_data (ignore) yield record_data
Iterate over the records in a TFRecord file and return the bytes of each record. path: The path to the TFRecord file
read_tfrecord_file
python
huawei-noah/SMARTS
smarts/core/utils/file.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/file.py
MIT
def get_type_chain(target_subclass: type, target_super_class: type) -> List[type]: """Finds an inheritance chain from the current sub-type to the target super-type. Args: target_subclass (type): The subclass type. target_super_class (type): The superclass type. Returns: List[type]: The inheritance chain from the current class to the target superclass. """ if not issubclass(target_subclass, target_super_class): raise TypeError(f"The first type must be a subclass of the second type.") if target_subclass is target_super_class: return [target_subclass] result = [] q = [] seen = {target_subclass} def unpack_super_types(subtype): class_tree = getclasstree([subtype]) types = [] for i in range(0, len(class_tree), 2): parent = class_tree[i] t = parent[0] types.insert(0, t) return types q.extend( ( ([target_subclass, next_super_type], next_super_type) for next_super_type in unpack_super_types(target_subclass) ) ) while len(q) > 0: subtypes, next_super_type = q.pop() if next_super_type in seen: continue seen.add(next_super_type) # found the correct inheritance chain if next_super_type == target_super_class: result = subtypes break q.extend( ( (subtypes + [next_super_type], next_super_type) for next_super_type in unpack_super_types(subtypes[-1]) ) ) return result
Finds an inheritance chain from the current sub-type to the target super-type. Args: target_subclass (type): The subclass type. target_super_class (type): The superclass type. Returns: List[type]: The inheritance chain from the current class to the target superclass.
get_type_chain
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT
def insert(self, instance: T): """Inserts the given instance into the set of managed instances. This must be a sub-class of the type that this type group manages. Args: instance (T): The instance to add. """ if instance.__class__ in self._instances_by_type: # XXX: consider allowing multiple instances of the same type. warnings.warn("Duplicate item added", category=UserWarning, stacklevel=1) return self._instances.append(instance) self._instances_by_type[instance.__class__] = instance # pytype: disable=attribute-error self._instances_by_id[instance.__class__.__name__] = instance
Inserts the given instance into the set of managed instances. This must be a sub-class of the type that this type group manages. Args: instance (T): The instance to add.
insert
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT
def remove(self, instance: T) -> Optional[T]: """Removes the given instance from this type group. Args: instance (T): The instance to remove. """ try: self._instances.remove(instance) self._instances_by_type.pop(instance.__class__) # pytype: disable=attribute-error self._instances_by_id.pop(instance.__class__.__name__) # pytype: enable=attribute-error except (KeyError, ValueError): return None return instance
Removes the given instance from this type group. Args: instance (T): The instance to remove.
remove
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT
def remove_instance_by_id(self, instance_id: str) -> Optional[T]: """Attempt to remove the instance by id. Args: instance_id (str): The name of the instance to remove. Returns: Optional[T]: The instance that was removed. """ instance = self._instances_by_id.get(instance_id) if instance is not None: self.remove(instance) return instance
Attempt to remove the instance by id. Args: instance_id (str): The name of the instance to remove. Returns: Optional[T]: The instance that was removed.
remove_instance_by_id
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT
def remove_instance_by_type(self, instance_type: Type[T]) -> Optional[T]: """Attempt to remove an instance by its type. Args: instance_type (Type[T]): The type of the instance to remove. Returns: Optional[T]: The instance that was removed. """ instance = self._instances_by_type.get(instance_type) if instance is not None: self.remove(instance) return instance
Attempt to remove an instance by its type. Args: instance_type (Type[T]): The type of the instance to remove. Returns: Optional[T]: The instance that was removed.
remove_instance_by_type
python
huawei-noah/SMARTS
smarts/core/utils/type_operations.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/type_operations.py
MIT