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#

bind_env(method)

Decorator making self the current environment before method runs.

normalize_actions(func)

Decorator to normalize (action, action_id) into an aligned actions list.

plot_only(method)

Decorator making an env plotting helper a no-op when the env has no figure.

time_it(→ Any)

Decorator to measure function execution time.

time_it2(→ Any)

Decorator to measure function execution time with instance attribute check.

resolve_message_targets(→ list[tuple[Any, Any]])

Pair each incoming odometry with the distinct local object it addresses.

random_uniform([low, high, size, min_distance])

Sample random points uniformly with a pairwise min-distance constraint.

set_seed(→ None)

Reseed the generator in use (see rng).

WrapToPi(→ float)

The function WrapToPi transforms an angle in radians to the range [-pi, pi].

WrapToRegion(→ float)

Transform an angle to a defined range, with length of 2*pi.

cross_product(→ float)

Compute the cross product of vectors OA and OB.

dist_hypot(→ float)

Compute Euclidean distance between two 2D points.

distance(→ float)

Compute the distance between two points.

file_check(→ str | None)

Check whether a file exists and return its absolute path.

find_duplicates(→ list[Any])

Find the values that appear more than once.

find_file(→ str | None)

Recursively search for a file under root_path.

find_object_by_identity(→ Any | None)

Find the first object matching a stable name, then an id.

gen_inequal_from_vertex(vertex)

Generate inequality constraints for a convex polygon.

geometry_transform(→ Any)

Rigidly transform a geometry by a state: rotate by theta, then translate.

is_2d_list(→ bool)

Returns True if 'data' is a non-empty list of lists (or tuples), indicating a 2D structure.

is_convex_and_ordered(→ tuple[bool, str | None])

Determine if the polygon is convex and return the order (CW or CCW).

random_point_range(→ list[float])

Generate a random point within a range.

relative_position(→ tuple[float, float])

Calculate the relative position and angle between two points.

to_numpy(→ numpy.ndarray | None)

Convert input to numpy array and optionally reshape.

transform_point_with_state(→ numpy.ndarray)

Transform a point using a state.

vel_diff2world(→ numpy.ndarray)

Convert a differential command to a world-frame velocity.

vel_omni2world(→ numpy.ndarray)

Convert an omni command to a world-frame velocity.

vel_world2diff(→ numpy.ndarray)

Convert a world-frame velocity to a differential command.

vel_world2omni(→ numpy.ndarray)

Convert a world-frame velocity to an omni command.

vertices_transform(→ numpy.ndarray | None)

Transform vertices using a state.

Package Contents#

irsim.util.bind_env(method)[源代码]#

Decorator making self the current environment before method runs.

Object ids, the random generator, and context-free logging are reached through the module-level env_param/world_param proxies, 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 objects attribute. It receives actions, a list aligned with self.objects (None where nothing was given). action is one action, a list of actions, or a dict {name: action}; action_id is an object id (obj.id) or name (None for 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.

EnvBase creates no EnvPlot in headless mode, so rendering, drawing, and saving helpers decorated with this simply return None in 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 WorldState addresses every object it contains, an ObjectState uses its embedded name and id, and a standalone odometry message goes to default_target unless a name or id selects another object.

参数:
  • objects (Iterable) -- Local objects the message can address.

  • msg -- A WorldState, an ObjectState, 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=...) or env.set_random_seed), otherwise the shared default that unseeded environments draw from.

参数:

seed -- Seed for deterministic sampling. None creates 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 name and id.

  • 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]; theta defaults 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_diff so 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. For omni this rotation is the whole conversion; a model that also steers, such as omni_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

irsim.util.vertices_transform(vertices: numpy.ndarray, state: numpy.ndarray) numpy.ndarray | None[源代码]#

Transform vertices using a state.

参数:
  • vertices (np.array) -- Vertices of the object. (2xN)

  • state (np.array) -- State [x, y, theta] (3x1).

返回:

Transformed vertices.

返回类型:

np.array