irsim.lib#

Submodules#

Attributes#

Classes#

reciprocal_vel_obs

A class to implement the Reciprocal Velocity Obstacle (RVO) algorithm for multi-robot collision avoidance.

social_force_model

Social Force Model controller for a single agent.

Behavior

Represents the behavior of an agent in the simulation.

GeometryFactory

Factory class to create geometry handlers.

KinematicsFactory

Factory class to create kinematics handlers.

KinematicsHandler

Abstract base class for handling robot kinematics.

Functions#

generate_polygon(β†’Β numpy.ndarray)

Generate a random polygon around a center point.

random_generate_polygon(...)

reference: https://stackoverflow.com/questions/8997099/algorithm-to-generate-random-2d-polygon

ackermann_kinematics(β†’Β numpy.ndarray)

Calculate the next state for an Ackermann steering vehicle.

differential_kinematics(β†’Β numpy.ndarray)

Calculate the next state for a differential wheel robot.

omni_kinematics(β†’Β numpy.ndarray)

Calculate the next position for an omnidirectional robot.

register_kinematics(name)

Decorator to register a KinematicsHandler subclass.

Package Contents#

irsim.lib.generate_polygon(center: list[float], avg_radius: float, irregularity: float, spikeyness: float, num_vertices: int) numpy.ndarray[source]#

Generate a random polygon around a center point.

Parameters:
  • center (Tuple[float, float]) – Center of the polygon.

  • avg_radius (float) – Average radius from the center to vertices.

  • irregularity (float) – Variance of angle spacing between vertices. Range [0, 1]

  • spikeyness (float) – Variance of radius from the center. Range [0, 1]

  • num_vertices (int) – Number of vertices for the polygon.

Returns:

Vertices of the polygon in CCW order.

Return type:

numpy.ndarray

irsim.lib.random_generate_polygon(number: int = 1, center_range: list[float] | None = None, avg_radius_range: list[float] | None = None, irregularity_range: list[float] | None = None, spikeyness_range: list[float] | None = None, num_vertices_range: list[int] | None = None, **kwargs: Any) numpy.ndarray | list[numpy.ndarray][source]#

reference: https://stackoverflow.com/questions/8997099/algorithm-to-generate-random-2d-polygon

Generate random polygons with specified properties.

Parameters:
  • number (int) – Number of polygons to generate (default 1).

  • center_range (List[float]) – Range for the polygon center [min_x, min_y, max_x, max_y].

  • avg_radius_range (List[float]) – Range for the average radius of the polygons.

  • irregularity_range (List[float]) – Range for the irregularity of the polygons.

  • spikeyness_range (List[float]) – Range for the spikeyness of the polygons.

  • num_vertices_range (List[int]) – Range for the number of vertices of the polygons.

Returns:

List of vertices for each polygon or a single polygon’s vertices if number=1.

irsim.lib.ackermann_kinematics(state: numpy.ndarray, velocity: numpy.ndarray, step_time: float, noise: bool = False, alpha: list[float] | None = None, mode: str = 'steer', wheelbase: float = 1) numpy.ndarray[source]#

Calculate the next state for an Ackermann steering vehicle.

Parameters:
  • state – A 4x1 vector [x, y, theta, steer_angle] representing the current state.

  • velocity – A 2x1 vector representing the current velocities, format depends on mode. For β€œsteer” mode, [linear, steer_angle] is expected. For β€œangular” mode, [linear, angular] is expected.

  • step_time – The time step for the simulation.

  • noise – Boolean indicating whether to add noise to the velocity (default False).

  • alpha – List of noise parameters for the velocity model (default [0.03, 0, 0, 0.03]). alpha[0] and alpha[1] are for linear velocity, alpha[2] and alpha[3] are for angular velocity.

  • mode – The kinematic mode, either β€œsteer” or β€œangular” (default β€œsteer”).

  • wheelbase – The distance between the front and rear axles (default 1).

Returns:

A 4x1 vector representing the next state.

Return type:

new_state

irsim.lib.differential_kinematics(state: numpy.ndarray, velocity: numpy.ndarray, step_time: float, noise: bool = False, alpha: list[float] | None = None) numpy.ndarray[source]#

Calculate the next state for a differential wheel robot.

Parameters:
  • state – A 3x1 vector [x, y, theta] representing the current position and orientation.

  • velocity – A 2x1 vector [linear, angular] representing the current velocities.

  • step_time – The time step for the simulation.

  • noise – Boolean indicating whether to add noise to the velocity (default False).

  • alpha – List of noise parameters for the velocity model (default [0.03, 0, 0, 0.03]). alpha[0] and alpha[1] are for linear velocity, alpha[2] and alpha[3] are for angular velocity.

Returns:

A 3x1 vector [x, y, theta] representing the next state.

Return type:

next_state

irsim.lib.omni_kinematics(state: numpy.ndarray, velocity: numpy.ndarray, step_time: float, noise: bool = False, alpha: list[float] | None = None) numpy.ndarray[source]#

Calculate the next position for an omnidirectional robot.

Uses body-frame velocity: the two components are forward and lateral speeds relative to the robot heading (theta). Since omni robots have no yaw control, theta remains unchanged.

Parameters:
  • state – A 3x1 vector [x, y, theta] representing the current state.

  • velocity – A 2x1 vector [forward, lateral] in body frame.

  • step_time – The time step for the simulation.

  • noise – Boolean indicating whether to add noise to the velocity (default False).

  • alpha – List of noise parameters for the velocity model (default [0.03, 0.03]).

Returns:

A 3x1 vector [x, y, theta] representing the next state.

Theta is preserved unchanged.

Return type:

next_state

class irsim.lib.reciprocal_vel_obs(state: list, obs_state_list=None, vxmax=1.5, vymax=1.5, acce=0.5, factor=1.0, line_obs_list=None)[source]#

A class to implement the Reciprocal Velocity Obstacle (RVO) algorithm for multi-robot collision avoidance.

Parameters:
  • state (list) – The rvo state of the agent [x, y, vx, vy, radius, vx_des, vy_des].

  • obs_state_list (list) – List of states of static obstacles [[x, y, vx, vy, radius]].

  • vxmax (float) – Maximum velocity in the x direction.

  • vymax (float) – Maximum velocity in the y direction.

  • acce (float) – Acceleration limit.

  • factor (float) – Penalty weighting factor for velocity selection.

  • line_obs_list (list) – List of line segments [[x1, y1, x2, y2], …].

state#
obs_state_list = None#
line_obs_list = None#
vxmax = 1.5#
vymax = 1.5#
acce = 0.5#
factor = 1.0#
update(state, obs_state_list, line_obs_list=None)[source]#

Update the agent, circular-obstacle, and line-obstacle states.

cal_vel(mode='rvo')[source]#

Calculate the velocity of the agent based on the Reciprocal Velocity Obstacle (RVO) algorithm.

Parameters:

mode (str) – The vo configure to calculate the velocity. It can be β€œrvo”, β€œhrvo”, or β€œvo”. - rvo: Reciprocal Velocity Obstacle (RVO) algorithm, for multi-robot collision avoidance. - hrvo: Hybrid Reciprocal Velocity Obstacle (HRVO) algorithm, for multi-robot collision avoidance. - vo: Velocity Obstacle (VO) algorithm, for obstacle-robot collision avoidance.

Returns:

Selected velocity [vx, vy].

Return type:

list[float]

config_rvo()[source]#

Build reciprocal velocity-obstacle cones for all obstacles.

config_rvo_mode(obstacle)[source]#

Build one RVO cone for a circular obstacle.

Parameters:

obstacle – Moving obstacle state [x, y, vx, vy, radius] or static circular obstacle state [x, y, radius].

Returns:

[apex, left_vector, right_vector] cone description.

Return type:

list

config_hrvo()[source]#

Build hybrid reciprocal velocity-obstacle cones for all obstacles.

config_hrvo_mode(obstacle)[source]#

Build one HRVO cone for a circular obstacle.

Parameters:

obstacle – Moving obstacle state [x, y, vx, vy, radius] or static circular obstacle state [x, y, radius].

Returns:

[apex, left_vector, right_vector] cone description.

Return type:

list | None

config_vo()[source]#

Build standard velocity-obstacle cones for all obstacles.

config_vo_mode(obstacle)[source]#

Build one VO cone for a circular obstacle.

Parameters:

obstacle – Moving obstacle state [x, y, vx, vy, radius] or static circular obstacle state [x, y, radius].

Returns:

[apex, left_vector, right_vector] cone description.

Return type:

list

config_vo_lines()[source]#

Compute VO cones for line segment obstacles.

For each segment, compute the angular span as seen from the agent, expanded by asin(r / dist) on each side to account for the agent radius. The apex is [0, 0] since line obstacles are static.

vel_candidate(rvo_list)[source]#

Sample reachable velocities and split them by VO feasibility.

Parameters:

rvo_list – Velocity-obstacle cone descriptions.

Returns:

Feasible velocities outside all cones and infeasible velocities inside at least one cone.

Return type:

tuple[list, list]

vo_out(vx, vy, rvo_list)[source]#

Return whether a candidate velocity lies outside every VO cone.

vel_select(vo_outside, vo_inside)[source]#

Select the best velocity from feasible candidates or penalized fallback.

penalty(vel, vel_des, factor)[source]#

Compute fallback cost from desired-velocity error and collision time.

static between_vector(line_left_vector, line_right_vector, line_vector)[source]#

Return whether line_vector lies inside a cone boundary pair.

static cross_product(vector1, vector2)[source]#

Compute the 2D cross product vector1 x vector2.

class irsim.lib.social_force_model(state: list, neighbor_list: list | None = None, line_obs_list: list | None = None, vmax: float = 1.5, step_time: float = 0.1, relaxation_time: float = 0.5, force_factor_desired: float = 1.0, force_factor_social: float = 2.1, force_factor_obstacle: float = 10.0, sigma_obstacle: float = 0.8, lambda_importance: float = 2.0, gamma: float = 0.35, n_angular: float = 2.0, n_velocity: float = 3.0, neighbor_range: float = 10.0, safety_radius: float = 0.0)[source]#

Social Force Model controller for a single agent.

The interface mirrors reciprocal_vel_obs so the two algorithms are interchangeable from a behavior method.

Parameters:
  • state (list) – Agent state [x, y, vx, vy, radius, vx_des, vy_des, theta].

  • neighbor_list (list) – Other moving/static circular agents [[x, y, vx, vy, radius], ...].

  • line_obs_list (list) – Line obstacles [[x1, y1, x2, y2], ...].

  • vmax (float) – Speed cap applied after the velocity update.

  • step_time (float) – Integration step dt.

  • relaxation_time (float) – tau in the desired-force term.

  • force_factor_desired (float) – Weight alpha_D on the desired force.

  • force_factor_social (float) – Weight alpha_S on the social force.

  • force_factor_obstacle (float) – Weight alpha_O on the obstacle force.

  • sigma_obstacle (float) – Decay length of the obstacle repulsion.

  • lambda_importance (float) – Weight of relative velocity in the interaction direction (lambda in MoussaΓ―d 2009).

  • gamma (float) – Sets the interaction range B = gamma * ||t||.

  • n_angular (float) – Angular sharpness n for the sideways force.

  • n_velocity (float) – Angular sharpness n' for the slowdown force.

  • neighbor_range (float) – Max distance for an agent to count as a social-force neighbor.

  • safety_radius (float) – Personal-space buffer subtracted from the agent-to-agent distance inside the social-force exponential. 0 reproduces the upstream behavior (point agents). > 0 shifts the decay closer-in so the repulsion saturates at 2 * safety_radius of centre-to-centre clearance, effectively giving each agent a body radius for SFM.

state#
neighbor_list#
line_obs_list#
vmax = 1.5#
step_time = 0.1#
relaxation_time = 0.5#
force_factor_desired = 1.0#
force_factor_social = 2.1#
force_factor_obstacle = 10.0#
sigma_obstacle = 0.8#
lambda_importance = 2.0#
gamma = 0.35#
n_angular = 2.0#
n_velocity = 3.0#
neighbor_range = 10.0#
safety_radius = 0.0#
update(state: list, neighbor_list: list, line_obs_list: list | None = None) None[source]#

Refresh the per-step inputs without re-instantiating.

cal_vel() list[source]#

Integrate one SFM step and return the new global velocity.

Returns:

Updated velocity [vx, vy], clipped to vmax.

Return type:

list[float]

desired_force() list[source]#

Relaxation toward the desired velocity v0 * e_goal.

The desired velocity is supplied directly via state[5:7].

social_force() list[source]#

Anisotropic neighbor repulsion (Moussaid-Helbing 2009).

Iterates over all neighbors within neighbor_range and sums their contribution.

obstacle_force() list[source]#

Exponential repulsion summed over all nearby line obstacles.

The upstream reference uses only the single nearest obstacle, which oscillates in symmetric environments (two parallel walls flip which one is β€œnearest” each step). We use the Helbing-Molnar (1995) summation form instead: every segment within 5 * sigma_obstacle contributes an exponentially decayed push, so symmetric walls cancel and the agent walks the centreline. The integration is also clamped against overlap (distance < 0 would otherwise make exp(-distance/sigma) explode).

class irsim.lib.Behavior(object_info=None, behavior_dict=None)[source]#

Represents the behavior of an agent in the simulation.

Parameters:
  • object_info (object) – Object information from the object_base class ObjectInfo.

  • behavior_dict (dict) –

    Dictionary containing behavior parameters for different behaviors. Name Options include: β€˜dash’, β€˜rvo’. target_roles:

    • ’all’: all objects in the environment will be considered within this behavior.

    • ’obstacle’: only obstacles will be considered within this behavior.

    • ’robot’: only robots will be considered within this behavior.

Initialize the behavior with object info and parameters.

Parameters:
  • object_info – Information about the agent (from ObjectBase.ObjectInfo).

  • behavior_dict (dict | None) – Behavior parameters; if None, defaults to an empty dict.

object_info = None#
behavior_dict#
gen_vel(ego_object, external_objects=None)[source]#

Generate a velocity for the agent based on configured behavior.

Parameters:
  • ego_object – The agent itself (object with needed attributes).

  • external_objects (list | None) – Other objects in the environment.

Returns:

A 2x1 velocity vector appropriate for the agent kinematics.

Return type:

numpy.ndarray

load_behavior(behaviors: str = '.behavior_methods')[source]#

Load behavior parameters from the script.

Parameters:

behaviors (str) – name of the behavior script.

invoke_behavior(kinematics: str, action: str, **kwargs: Any) Any[source]#

Invoke a specific behavior method based on kinematics model and action type.

This method looks up and executes the appropriate behavior function from the behavior registry based on the combination of kinematics model and action name.

Parameters:
  • kinematics (str) –

    Kinematics model identifier. Supported values:

    • ’diff’: Differential drive kinematics

    • ’omni’: Omnidirectional kinematics

    • ’acker’: Ackermann steering kinematics

  • action (str) –

    Behavior action name. Examples:

    • ’dash’: Direct movement toward goal

    • ’rvo’: Reciprocal Velocity Obstacles for collision avoidance

  • **kwargs – Additional keyword arguments passed to the behavior function. Common parameters include ego_object, external_objects, goal, etc.

Returns:

Generated velocity vector (2x1) in the format appropriate for the specified kinematics model.

Return type:

np.ndarray

Raises:

ValueError – If no behavior method is found for the given kinematics and action combination.

Example

>>> # Invoke differential drive dash behavior
>>> vel = behavior.invoke_behavior('diff', 'dash',
...                               ego_object=robot,
...                               external_objects=obstacles)
irsim.lib.register_behavior#
irsim.lib.register_behavior_class#
irsim.lib.register_group_behavior#
irsim.lib.register_group_behavior_class#
class irsim.lib.GeometryFactory[source]#

Factory class to create geometry handlers.

static create_geometry(name: str = 'circle', **kwargs) geometry_handler[source]#

Create a geometry handler from a YAML shape name.

Parameters:
  • name – Shape name. Supported values are circle, polygon, rectangle, linestring, and map.

  • **kwargs – Shape-specific parameters forwarded to the handler.

Returns:

Concrete geometry handler.

Return type:

geometry_handler

Raises:

ValueError – If name is not supported.

class irsim.lib.KinematicsFactory[source]#

Factory class to create kinematics handlers.

static create_kinematics(name: str | None = None, noise: bool = False, alpha: list | None = None, mode: str = 'steer', wheelbase: float | None = None, role: str = 'robot') KinematicsHandler[source]#

Create a kinematics handler from a YAML kinematics.name value.

Parameters:
  • name – Registered kinematics name, such as diff, omni, omni_angular, or acker. None uses the fallback.

  • noise – Whether to apply motion noise.

  • alpha – Noise parameters passed to the handler.

  • mode – Ackermann mode, used only by acker.

  • wheelbase – Ackermann wheelbase; defaults to 1.0 for acker.

  • role – Object role used for warnings.

Returns:

Registered handler instance, or a differential handler fallback when the name is missing or unknown.

Return type:

KinematicsHandler

static get_handler_class(name: str) type[KinematicsHandler] | None[source]#

Look up a registered handler class by name without instantiation.

Parameters:

name (str) – Kinematics name (e.g. "diff", "omni").

Returns:

The class, or None if not found.

Return type:

type[KinematicsHandler] | None

class irsim.lib.KinematicsHandler(name, noise: bool = False, alpha: list | None = None)[source]#

Bases: abc.ABC

Abstract base class for handling robot kinematics.

Subclasses should set the class-attribute metadata described below and implement step(), velocity_to_xy(), compute_max_speed(), and compute_heading().

Initialize the KinematicsHandler class.

Parameters:
  • name (str) – Kinematics model name.

  • noise (bool) – Boolean indicating whether to add noise to the velocity (default False).

  • alpha (list) – List of noise parameters for the velocity model (default [0.03, 0, 0, 0.03]).

action_dim: int = 2#
min_state_dim: int = 3#
state_dim: int = 3#
vel_max: ClassVar[list[float]] = [1, 1]#
vel_min: ClassVar[list[float]]#
acce: ClassVar[list[float]]#
color: str = 'g'#
obstacle_color: str = 'k'#
description: str | None = None#
show_arrow: bool = True#
name#
noise = False#
alpha = [0.03, 0, 0, 0.03]#
abstractmethod step(state: numpy.ndarray, velocity: numpy.ndarray, step_time: float) numpy.ndarray[source]#

Calculate the next state using the kinematics model.

Parameters:
  • state (np.ndarray) – Current state.

  • velocity (np.ndarray) – Velocity vector.

  • step_time (float) – Time step for simulation.

Returns:

Next state.

Return type:

np.ndarray

velocity_to_xy(state: numpy.ndarray, velocity: numpy.ndarray) numpy.ndarray[source]#

Convert velocity to [vx, vy] in world frame.

The default implementation follows differential-drive conventions: velocity[0] is the linear speed projected through the heading angle state[2]. Subclasses with different velocity semantics (e.g. omnidirectional) should override this.

Parameters:
  • state (np.ndarray) – Current state vector.

  • velocity (np.ndarray) – Velocity vector in kinematics frame.

Returns:

(2, 1) array of [vx, vy].

Return type:

np.ndarray

compute_max_speed(vel_max: numpy.ndarray) float[source]#

Compute the scalar maximum speed from the vel_max vector.

The default implementation follows differential-drive conventions: the first component vel_max[0, 0] is the translational speed limit. Subclasses where max speed is derived differently (e.g. omnidirectional using the L2 norm) should override this.

Parameters:

vel_max (np.ndarray) – Maximum velocity vector.

Returns:

Scalar maximum speed.

Return type:

float

compute_heading(state: numpy.ndarray, velocity: numpy.ndarray) float[source]#

Compute the heading angle.

The default implementation follows differential-drive conventions: heading is state[2] (the orientation component). Returns 0.0 if the state has fewer than 3 rows.

Parameters:
  • state (np.ndarray) – Current state vector.

  • velocity (np.ndarray) – Current velocity vector.

Returns:

Heading in radians.

Return type:

float

irsim.lib.register_kinematics(name: str)[source]#

Decorator to register a KinematicsHandler subclass.

Parameters:

name (str) – Name used in YAML configs (e.g. "diff", "omni").

Returns:

Class decorator that registers and returns the class unchanged.

Return type:

Callable

irsim.lib.kinematics_factory: dict[str, collections.abc.Callable[Ellipsis, Any]]#