irsim.util#
Utility functions for IR-SIM simulation.
This package contains helper functions for: - Mathematical operations - Coordinate transformations - File operations - Geometry utilities
Submodules#
Attributes#
Functions#
|
Decorator making |
|
Decorator to normalize (action, action_id) into an aligned actions list. |
|
Decorator making an env plotting helper a no-op when the env has no figure. |
|
Decorator to measure function execution time. |
|
Decorator to measure function execution time with instance attribute check. |
|
Pair each incoming odometry with the distinct local object it addresses. |
|
Sample random points uniformly with a pairwise min-distance constraint. |
|
Reseed the generator in use (see |
|
The function WrapToPi transforms an angle in radians to the range [-pi, pi]. |
|
Transform an angle to a defined range, with length of 2*pi. |
|
Compute the cross product of vectors OA and OB. |
|
Compute Euclidean distance between two 2D points. |
|
Compute the distance between two points. |
|
Check whether a file exists and return its absolute path. |
|
Find the values that appear more than once. |
|
Recursively search for a file under root_path. |
|
Find the first object matching a stable name, then an id. |
|
Generate inequality constraints for a convex polygon. |
|
Rigidly transform a geometry by a state: rotate by |
|
Returns True if 'data' is a non-empty list of lists (or tuples), indicating a 2D structure. |
|
Determine if the polygon is convex and return the order (CW or CCW). |
|
Generate a random point within a range. |
|
Calculate the relative position and angle between two points. |
|
Convert input to numpy array and optionally reshape. |
|
Transform a point using a state. |
|
Convert a differential command to a world-frame velocity. |
|
Convert an omni command to a world-frame velocity. |
|
Convert a world-frame velocity to a differential command. |
|
Convert a world-frame velocity to an omni command. |
|
Transform vertices using a state. |
Package Contents#
- irsim.util.bind_env(method)[源代码]#
Decorator making
selfthe current environment beforemethodruns.Object ids, the random generator, and context-free logging are reached through the module-level
env_param/world_paramproxies, so methods that construct objects or draw random numbers bind their environment first.
- irsim.util.normalize_actions(func)[源代码]#
Decorator to normalize (action, action_id) into an aligned actions list.
The wrapped method must belong to a class that has a
objectsattribute. It receivesactions, a list aligned withself.objects(Nonewhere nothing was given).actionis one action, a list of actions, or a dict{name: action};action_idis an object id (obj.id) or name (Nonefor the first object), or a list of them. A single action is applied to every id; a list of actions is applied to the given ids, or to consecutive objects starting from the given id. Surplus actions (or ids) are dropped with a warning; an unknown id or name raises.
- irsim.util.plot_only(method)[源代码]#
Decorator making an env plotting helper a no-op when the env has no figure.
EnvBasecreates noEnvPlotin headless mode, so rendering, drawing, and saving helpers decorated with this simply returnNonein that case.
- irsim.util.time_it(name: str = 'Function') Any[源代码]#
Decorator to measure function execution time.
- 参数:
name (str) -- Function name for logging (default "Function").
- 返回:
Wrapped function with timing.
- 返回类型:
function
- irsim.util.time_it2(name: str = 'Function') Any[源代码]#
Decorator to measure function execution time with instance attribute check.
- 参数:
name (str) -- Function name for logging (default "Function").
- 返回:
Wrapped function with timing.
- 返回类型:
function
- irsim.util.resolve_message_targets(objects: collections.abc.Iterable[Any], msg: irsim.msg.WorldState | irsim.msg.ObjectState | Any, object_name: str | None = None, object_id: int | None = None, *, default_target: collections.abc.Callable[[], Any]) list[tuple[Any, Any]][源代码]#
Pair each incoming odometry with the distinct local object it addresses.
A
WorldStateaddresses every object it contains, anObjectStateuses its embedded name and id, and a standalone odometry message goes todefault_targetunless a name or id selects another object.- 参数:
objects (Iterable) -- Local objects the message can address.
msg -- A
WorldState, anObjectState, or an odometry-shaped message.object_name (str) -- Explicit target name for a standalone odometry or object message.
object_id (int) -- Explicit target id for the same messages. Names take precedence when both are given.
default_target (Callable) -- Called only when a standalone odometry selects no object; returns the object that receives it.
- 返回:
(object, odometry)pairs, one per addressed object.- 返回类型:
list
- 抛出:
ValueError -- If a target cannot be found, a name or id is combined with a
WorldState, or one object is addressed more than once.
- irsim.util.random_uniform(low=None, high=None, size=(3, 1), min_distance=1.0)[源代码]#
Sample random points uniformly with a pairwise min-distance constraint.
- 参数:
low (list | np.ndarray) -- Lower bound as a 3D vector (x, y, theta). Default is [0.5, 0.5, 0.0].
high (list | np.ndarray) -- Upper bound as a 3D vector (x, y, theta). Default is [9.5, 9.5, 6.28].
size (tuple) -- (dim, n) where dim is 2 or 3 and n is the number of points to sample. When dim == 2, only x and y are sampled and theta is set to 0. Default is (3, 1).
min_distance (float) -- Minimum pairwise distance in the xy plane. Default is 1.0.
- 返回:
Random points of shape (3, n).
- 返回类型:
np.ndarray
- irsim.util.rng#
- irsim.util.set_seed(seed: int | None = None) None[源代码]#
Reseed the generator in use (see
rng).Reseeds the current environment's own generator when it has one (
irsim.make(..., seed=...)orenv.set_random_seed), otherwise the shared default that unseeded environments draw from.- 参数:
seed -- Seed for deterministic sampling.
Nonecreates a fresh non-deterministic generator.
- irsim.util.WrapToPi(rad: float, positive: bool = False) float[源代码]#
The function WrapToPi transforms an angle in radians to the range [-pi, pi].
- 参数:
rad (float) -- Angle in radians. The rad parameter in the WrapToPi function represents an angle in radians that you want to transform to the range [-pi, pi]. The function ensures that the angle is within this range by wrapping it around if it exceeds the bounds.
positive (bool) -- Whether to return the positive value of the angle. Useful for angles difference.
- 返回:
The function WrapToPi(rad) returns the angle rad wrapped to the range [-pi, pi].
- irsim.util.WrapToRegion(rad: float, range: list[float]) float[源代码]#
Transform an angle to a defined range, with length of 2*pi.
- 参数:
rad (float) -- Angle in radians.
range (list) -- List defining the range [min, max].
- 返回:
Wrapped angle.
- 返回类型:
float
- irsim.util.cross_product(o: list[float], a: list[float], b: list[float]) float[源代码]#
Compute the cross product of vectors OA and OB.
- 参数:
o (array-like) -- Points representing vectors.
a (array-like) -- Points representing vectors.
b (array-like) -- Points representing vectors.
- 返回:
Cross product value.
- 返回类型:
float
- irsim.util.diff_to_omni#
- irsim.util.dist_hypot(x1: float, y1: float, x2: float, y2: float) float[源代码]#
Compute Euclidean distance between two 2D points.
- irsim.util.distance(point1: list[float] | numpy.ndarray, point2: list[float] | numpy.ndarray) float[源代码]#
Compute the distance between two points.
- 参数:
point1 (np.array) -- First point [x, y] (2x1).
point2 (np.array) -- Second point [x, y] (2x1).
- 返回:
Distance between points.
- 返回类型:
float
- irsim.util.file_check(file_name: str | None, root_path: str | None = None) str | None[源代码]#
Check whether a file exists and return its absolute path.
Searches in the following order: 1. The given path directly 2. Relative to sys.path[0] 3. Relative to the current working directory 4. Relative to the script directory 5. Recursively under root_path (lazy fallback)
- 参数:
file_name (str | None) -- Name or relative path of the file to check. Returns None immediately if None.
root_path (str | None) -- Root directory for recursive search fallback.
- 返回:
Absolute path of the file if found, None otherwise.
- 返回类型:
str | None
- irsim.util.find_duplicates(values: collections.abc.Iterable[Any]) list[Any][源代码]#
Find the values that appear more than once.
- 参数:
values (Iterable) -- Values to inspect, such as object names.
- 返回:
The repeated values, in first-seen order.
- 返回类型:
list
- irsim.util.find_file(root_path: str | None, target_filename: str) str | None[源代码]#
Recursively search for a file under root_path.
- 参数:
root_path (str | None) -- Directory to search under. Returns None if None.
target_filename (str) -- Name of the file to find.
- 返回:
Absolute path if found, None otherwise.
- 返回类型:
str | None
- irsim.util.find_object_by_identity(objects: collections.abc.Iterable[Any], name: str | None = None, object_id: int | None = None) Any | None[源代码]#
Find the first object matching a stable name, then an id.
Names are matched first, because they are the identity shared across simulators; ids are only used as a fallback.
- 参数:
objects (Iterable) -- Objects to search, each with
nameandid.name (str) -- Name to look for. Ignored when None or empty.
object_id (int) -- Id to look for when the name does not match.
- 返回:
The matching object, or None if neither identity matches.
- irsim.util.gen_inequal_from_vertex(vertex: numpy.ndarray)[源代码]#
Generate inequality constraints for a convex polygon.
- 参数:
vertex (np.array) -- Vertices of the polygon (2xN).
- 返回:
G matrix and h vector for the inequality Gx <= h.
- 返回类型:
tuple
- irsim.util.geometry_transform(geometry: Any, state: numpy.ndarray) Any[源代码]#
Rigidly transform a geometry by a state: rotate by
theta, then translate.- 参数:
geometry -- Shapely geometry to transform.
state (np.array or sequence) --
[x, y, theta];thetadefaults to 0.
- 返回:
Transformed geometry.
- irsim.util.is_2d_list(data: list | collections.deque) bool[源代码]#
Returns True if 'data' is a non-empty list of lists (or tuples), indicating a 2D structure. Returns False if 'data' is a single list
- irsim.util.is_convex_and_ordered(points: numpy.ndarray) tuple[bool, str | None][源代码]#
Determine if the polygon is convex and return the order (CW or CCW).
- 参数:
points (np.ndarray) -- A 2xN NumPy array representing the vertices of the polygon.
- 返回:
- A tuple where the first element is True if the polygon is convex,
and the second element is 'CW' or 'CCW' based on the order. If not convex, returns (False, None).
- 返回类型:
(bool, str)
- irsim.util.omni_to_diff#
- irsim.util.random_point_range(range_low: list[float] | None = None, range_high: list[float] | None = None) list[float][源代码]#
Generate a random point within a range.
- 参数:
range_low (list) -- Lower bound of the range.
range_high (list) -- Upper bound of the range.
- 返回:
Random point within the range.
- 返回类型:
np.array
- irsim.util.relative_position(position1: numpy.ndarray, position2: numpy.ndarray, topi: bool = True) tuple[float, float][源代码]#
Calculate the relative position and angle between two points.
- 参数:
position1 (np.array) -- First position [x, y] (2x1).
position2 (np.array) -- Second position [x, y] (2x1).
topi (bool) -- Whether to wrap angle to [-pi, pi] (default True).
- 返回:
Distance and angle (radians).
- 返回类型:
tuple
- irsim.util.to_numpy(data: Any, default: numpy.ndarray | None = None, expected_shape: tuple[int, ...] | None = None) numpy.ndarray | None[源代码]#
Convert input to numpy array and optionally reshape.
If data is None: return default (reshaped if expected_shape provided).
If data is a list: convert to ndarray. 1D lists become column vectors.
If data is a 1D ndarray: convert to column vector.
If expected_shape is provided: reshape the resulting array to it.
- irsim.util.transform_point_with_state(point: numpy.ndarray, state: numpy.ndarray) numpy.ndarray[源代码]#
Transform a point using a state.
- 参数:
point (np.array) -- Point [x, y, theta] (3x1).
state (np.array) -- State [x, y, theta] (3x1).
- 返回:
Transformed point (2x1).
- 返回类型:
np.array
- irsim.util.vel_diff2world(state_ori: float, vel_diff: numpy.ndarray) numpy.ndarray[源代码]#
Convert a differential command to a world-frame velocity.
- 参数:
state_ori (float) -- Orientation angle.
vel_diff (np.array) -- Differential velocity [linear, angular] (2x1).
- 返回:
Omnidirectional velocity [vx, vy] (2x1).
- 返回类型:
np.array
- irsim.util.vel_omni2world(state_ori: float, vel_body: numpy.ndarray) numpy.ndarray[源代码]#
Convert an omni command to a world-frame velocity.
The inverse of
vel_world2omni();vel_diff2world()does the equivalent for a differential robot.- 参数:
state_ori (float) -- Orientation angle.
vel_body (np.array) -- Body-frame velocity [forward, lateral] (2x1).
- 返回:
World-frame velocity [vx, vy] (2x1).
- 返回类型:
np.array
- irsim.util.vel_world2diff(state_ori: float, vel_omni: numpy.ndarray, w_max: float = 1.5, guarantee_time: float = 0.2, tolerance: float = 0.1, mini_speed: float = 0.02) numpy.ndarray[源代码]#
Convert a world-frame velocity to a differential command.
- 参数:
state_ori (float) -- Orientation angle.
vel_omni (np.array) -- World-frame velocity [vx, vy] (2x1). The name is kept from
omni_to_diffso existing keyword callers still work.w_max (float) -- Maximum angular velocity.
guarantee_time (float) -- Time to guarantee velocity.
tolerance (float) -- Angular tolerance.
mini_speed (float) -- Minimum speed threshold.
- 返回:
Differential velocity [linear, angular] (2x1).
- 返回类型:
np.array
- irsim.util.vel_world2omni(state_ori: float, vel_world: numpy.ndarray) numpy.ndarray[源代码]#
Convert a world-frame velocity to an omni command.
[vx, vy]describes the rigid-body motion in the world, which is what holonomic planners such as RVO, SFM and ORCA produce, while a robot is commanded in its own frame. Foromnithis rotation is the whole conversion; a model that also steers, such asomni_angular, gets only its translation from here and needs a yaw rate of its own.vel_world2diff()does the equivalent for a differential robot.- 参数:
state_ori (float) -- Orientation angle.
vel_world (np.array) -- World-frame velocity [vx, vy] (2x1).
- 返回:
Body-frame velocity [forward, lateral] (2x1).
- 返回类型:
np.array