irsim.lib#
Submodules#
Attributes#
Classes#
A class to implement the Reciprocal Velocity Obstacle (RVO) algorithm for multi-robot collision avoidance. |
|
Vectorized Social Force Model for a crowd of agents. |
|
Social Force Model controller for a single agent. |
|
Represents the behavior of an agent in the simulation. |
|
Factory class to create geometry handlers. |
|
Factory class to create kinematics handlers. |
|
Abstract base class for handling robot kinematics. |
Functions#
|
Separate overlapping object pairs, sharing each correction by mass. |
|
Generate a random polygon around a center point. |
reference: https://stackoverflow.com/questions/8997099/algorithm-to-generate-random-2d-polygon |
|
|
Calculate the next state for an Ackermann steering vehicle. |
|
Calculate the next state for a differential wheel robot. |
|
Calculate the next position for an omnidirectional robot. |
|
Decorator to register a KinematicsHandler subclass. |
Package Contents#
- irsim.lib.contact_step(pairs: list[tuple[Any, Any]], iterations: int = CONTACT_ITERATIONS, slop: float = CONTACT_SLOP, margin: float = 0.0, step_time: float | None = None) list[Contact][源代码]#
Separate overlapping object pairs, sharing each correction by mass.
One call resolves the contacts of one simulation step, in three stages:
Order: pairs that nothing can move are dropped, and the rest are sorted by their contact-graph distance from immovable objects (
_anchored_order()), so a wall contact is handled before the robot contact behind it.Sweep: Gauss-Seidel passes over the pairs. Each overlapping pair is separated along its contact normal:
amoves bydepth * w_a / (w_a + w_b)andbby the rest, wherewis the inverse mass (zero for static or infinite-mass objects, which never move). Within a sweep, an object that was just pressed against something it cannot move only yields tangentially afterwards and its partner takes the rest, so a chain pushed into a wall settles in one sweep and a box pushed obliquely into a wall slides along it. Sweeps repeat until one moves nothing, oriterationsis reached. A pair resting withinREST_TOLERANCEof each other needs no correction but still blocks: a box resting on a wall is not pushed into it and back out again within a sweep.Apply: the sweeps work on translated copies of each object's convex pieces and accumulate one displacement per object, applied at the end through
apply_contact_displacement(), which also folds it into the object's velocity.
Both objects of every resolved pair are marked as in contact with each other.
- 参数:
pairs -- Candidate
(a, b)object pairs. They should include every pair that a correction could bring into contact, e.g. all pairs within one step's travel of each other, not only the pairs that intersect after the kinematic step; pairs that never overlap are skipped.iterations -- Maximum sweeps over the pairs.
slop -- Extra gap left between separated bodies.
margin -- How far an object may be moved by the sweeps, used to fetch enough grid-map boundary around each candidate up front.
step_time -- Simulation step, needed to report contact forces and to apply restitution; without it forces stay
0and nothing bounces.
- 返回:
One entry per pair that touched, in the order of the first sweep that found it, carrying its deepest push; a positive
depthmeans the pair was pushed apart, otherwise the two only rest against each other.- 返回类型:
list[Contact]
- irsim.lib.generate_polygon(center: list[float], avg_radius: float, irregularity: float, spikeyness: float, num_vertices: int) numpy.ndarray[源代码]#
Generate a random polygon around a center point.
- 参数:
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.
- 返回:
Vertices of the polygon in CCW order.
- 返回类型:
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][源代码]#
reference: https://stackoverflow.com/questions/8997099/algorithm-to-generate-random-2d-polygon
Generate random polygons with specified properties.
- 参数:
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.
- 返回:
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[源代码]#
Calculate the next state for an Ackermann steering vehicle.
- 参数:
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).
- 返回:
A 4x1 vector representing the next state.
- 返回类型:
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[源代码]#
Calculate the next state for a differential wheel robot.
- 参数:
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.
- 返回:
A 3x1 vector [x, y, theta] representing the next state.
- 返回类型:
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[源代码]#
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.
- 参数:
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]).
- 返回:
- A 3x1 vector [x, y, theta] representing the next state.
Theta is preserved unchanged.
- 返回类型:
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)[源代码]#
A class to implement the Reciprocal Velocity Obstacle (RVO) algorithm for multi-robot collision avoidance.
- 参数:
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)[源代码]#
Update the agent, circular-obstacle, and line-obstacle states.
- cal_vel(mode='rvo')[源代码]#
Calculate the velocity of the agent based on the Reciprocal Velocity Obstacle (RVO) algorithm.
- 参数:
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.
- 返回:
Selected velocity [vx, vy].
- 返回类型:
list[float]
- config_rvo_mode(obstacle)[源代码]#
Build one RVO cone for a circular obstacle.
- 参数:
obstacle -- Neighbour state
[x, y, vx, vy, radius], or the static form[x, y, radius](zero velocity).- 返回:
[apex, left_vector, right_vector]cone description.- 返回类型:
list
- config_hrvo_mode(obstacle)[源代码]#
Build one HRVO cone for a circular obstacle.
- 参数:
obstacle -- Neighbour state
[x, y, vx, vy, radius], or the static form[x, y, radius](zero velocity).- 返回:
[apex, left_vector, right_vector]cone description.- 返回类型:
list
- config_vo_mode(obstacle)[源代码]#
Build one VO cone for a circular obstacle.
- 参数:
obstacle -- Neighbour state
[x, y, vx, vy, radius], or the static form[x, y, radius](zero velocity).- 返回:
[apex, left_vector, right_vector]cone description.- 返回类型:
list
- config_vo_lines()[源代码]#
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)[源代码]#
Sample reachable velocities and split them by VO feasibility.
- 参数:
rvo_list -- Velocity-obstacle cone descriptions
[apex, left, right].- 返回:
Feasible velocities outside all cones and infeasible velocities inside at least one cone.
- 返回类型:
tuple[list, list]
- vel_select(vo_outside, vo_inside)[源代码]#
Select the best velocity from feasible candidates or penalized fallback.
Both arguments may be lists of
[vx, vy]or(N, 2)arrays; the first minimum is returned, asminwould.
- penalties(vels, vel_des, factor)[源代码]#
Vectorized
penalty()for an(N, 2)array of velocities.Same formulas and branches as the scalar version, evaluated for all candidates at once; the crowded-scene fallback otherwise calls
penaltyhundreds of times per robot per step.
- penalty(vel, vel_des, factor)[源代码]#
Scalar
penalties()for one velocity, kept for compatibility.
- class irsim.lib.SocialForceModelBatch(states, neighbor_states=None, line_obs_list=None, social_groups: list[list[int]] | 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, force_factor_coherence: float = 2.0, force_factor_group_repulsion: float = 1.0, group_repulsion_threshold: float | None = None, force_factor_gaze: float = 3.0, gaze_vision_angle: float = 90.0)[源代码]#
Vectorized Social Force Model for a crowd of agents.
Evaluates the same desired, social and obstacle forces as
social_force_modelforNagents at once from one state snapshot. Every agent therefore reacts to the same instant, so the result does not depend on the order in which agents are stepped, and the pairwise social term is array math over allN x (N + M)pairs instead of a Python loop.Agents can optionally be partitioned into social groups (people walking together). Members of a group receive the three extra forces of Moussaid et al. (2010), in the formulation used by pedsim_ros:
coherence -- pull toward the group's centre of mass, ramping in smoothly (
tanh) once a member is further than(size - 1) / 2metres from it;repulsion -- push apart members whose centres come closer than
group_repulsion_threshold;gaze -- brake along the velocity,
f = -alpha * v, when the other members' centre of mass lies outside agaze_vision_anglecone around the walking direction;alphais the missing head rotation in radians, so an agent slows down until it can see its group again.
引用
Moussaid, M., Perozo, N., Garnier, S., Helbing, D., Theraulaz, G. (2010), The walking behaviour of pedestrian social groups and its impact on crowd dynamics. PLoS ONE 5(4): e10047.
PySocialForce, yuxiang-gao/PySocialForce -- NumPy implementation of the extended social force model whose batched force evaluation and group forces this class follows.
- 参数:
states (array-like) --
(N, 8)agent states[x, y, vx, vy, radius, vx_des, vy_des, theta];thetais carried for the caller and not used by the forces.neighbor_states (array-like) --
(M, 5)circular neighbours that are not part of the batch,[[x, y, vx, vy, radius], ...](robots driven by other behaviors, circular obstacles). They push batch agents but are not moved.line_obs_list (array-like) --
(K, 4)line obstacles[[x1, y1, x2, y2], ...].social_groups (list[list[int]] | None) -- Index lists into
states; each agent may appear in at most one group.Noneor[]disables the group forces.vmax (float) -- Speed cap applied after the velocity update.
step_time (float) -- Integration step
dt.relaxation_time (float) --
tauin the desired-force term.force_factor_desired (float) -- Weight on the desired force.
force_factor_social (float) -- Weight on the social force.
force_factor_obstacle (float) -- Weight on the obstacle force.
sigma_obstacle (float) -- Decay length of the obstacle repulsion.
lambda_importance (float) -- Weight of relative velocity in the interaction direction.
gamma (float) -- Sets the interaction range
B = gamma * ||t||.n_angular (float) -- Angular sharpness
nfor the sideways force.n_velocity (float) -- Angular sharpness
n'for the slowdown force.neighbor_range (float) -- Agents further apart than this ignore each other in the social force.
safety_radius (float) -- Personal-space buffer subtracted from the agent-to-agent distance inside the social-force exponential.
force_factor_coherence (float) -- Weight on the group coherence force.
force_factor_group_repulsion (float) -- Weight on the intra-group repulsion force.
group_repulsion_threshold (float | None) -- Centre-to-centre distance below which two group members repel each other.
Noneuses the sum of their radii (states[:, 4]), i.e. members push apart as soon as their discs touch.force_factor_gaze (float) -- Weight on the group gaze force.
gaze_vision_angle (float) -- Half-angle, in degrees, of the cone around the walking direction inside which the group's centre of mass is considered visible.
- 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#
- force_factor_coherence = 2.0#
- force_factor_group_repulsion = 1.0#
- group_repulsion_threshold = None#
- force_factor_gaze = 3.0#
- gaze_vision_angle = 90.0#
- social_groups: list[numpy.ndarray] = []#
- update(states, neighbor_states=None, line_obs_list=None, social_groups: list[list[int]] | None = None) None[源代码]#
Refresh the per-step inputs without re-instantiating.
- 参数:
states --
(N, 8)agent states.neighbor_states --
(M, 5)external circular neighbours.line_obs_list --
(K, 4)line obstacles.social_groups -- New group partition, or
Noneto keep the current one. Pass[]to switch the group forces off.
- property n: int#
Number of agents in the batch.
- cal_vel() numpy.ndarray[源代码]#
Integrate one SFM step for every agent.
- 返回:
(N, 2)updated world-frame velocities, each clipped tovmax.- 返回类型:
np.ndarray
- social_force() numpy.ndarray[源代码]#
Anisotropic neighbour repulsion (Moussaid-Helbing 2009).
Each agent sums the contribution of every other batch agent and every external neighbour closer than
neighbor_range. Matchessocial_force_model.social_force()term by term.
- obstacle_force() numpy.ndarray[源代码]#
Exponential repulsion summed over all nearby line obstacles.
Same rule as
social_force_model.obstacle_force(): every segment within5 * sigma_obstacle + radiusof an agent's centre contributes, the decay is clamped at the body surface, and a segment passing exactly through the centre pushes along+x.
- coherence_force() numpy.ndarray[源代码]#
Pull each member toward its group's centre of mass.
The pull is
(com - p) * (tanh(d - d_max) + 1) / 2withd_max = (size - 1) / 2metres, the smooth variant of the paper's step rule used by pedsim_ros.
- group_repulsive_force() numpy.ndarray[源代码]#
Push apart group members that come too close.
Each pair closer than
group_repulsion_threshold(or the sum of the two radii when that isNone) contributes the raw offsetp_self - p_other.
- gaze_force() numpy.ndarray[源代码]#
Brake when the rest of the group falls out of view.
With
phithe angle between the walking directionvand the other members' centre of mass, the force is-(phi - phi_vis) * vwhenphiexceedsgaze_vision_angleand zero otherwise. A stationary member has no walking direction and gets no gaze force.
- 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)[源代码]#
Social Force Model controller for a single agent.
The interface mirrors
reciprocal_vel_obsso the two algorithms are interchangeable from a behavior method.- 参数:
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) --
tauin the desired-force term.force_factor_desired (float) -- Weight
alpha_Don the desired force.force_factor_social (float) -- Weight
alpha_Son the social force.force_factor_obstacle (float) -- Weight
alpha_Oon the obstacle force.sigma_obstacle (float) -- Decay length of the obstacle repulsion.
lambda_importance (float) -- Weight of relative velocity in the interaction direction (
lambdain Moussaïd 2009).gamma (float) -- Sets the interaction range
B = gamma * ||t||.n_angular (float) -- Angular sharpness
nfor 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.
0reproduces the upstream behavior (point agents).> 0shifts the decay closer-in so the repulsion saturates at2 * safety_radiusof 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[源代码]#
Refresh the per-step inputs without re-instantiating.
- cal_vel() list[源代码]#
Integrate one SFM step and return the new global velocity.
- 返回:
Updated velocity
[vx, vy], clipped tovmax.- 返回类型:
list[float]
- desired_force() list[源代码]#
Relaxation toward the desired velocity
v0 * e_goal.The desired velocity is supplied directly via
state[5:7].
- social_force() list[源代码]#
Anisotropic neighbor repulsion (Moussaid-Helbing 2009).
Iterates over all neighbors within
neighbor_rangeand sums their contribution.
- obstacle_force() list[源代码]#
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_obstaclecontributes an exponentially decayed push, so symmetric walls cancel and the agent walks the centreline. The integration is also clamped against overlap (distance < 0would otherwise makeexp(-distance/sigma)explode).
- class irsim.lib.Behavior(object_info=None, behavior_dict=None)[源代码]#
Represents the behavior of an agent in the simulation.
- 参数:
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.
- 参数:
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)[源代码]#
Generate a velocity for the agent based on configured behavior.
- 参数:
ego_object -- The agent itself (object with needed attributes).
external_objects (list | None) -- Other objects in the environment.
- 返回:
A 2x1 velocity vector appropriate for the agent kinematics.
- 返回类型:
numpy.ndarray
- load_behavior(behaviors: str = '.behavior_methods')[源代码]#
Load behavior parameters from the script.
- 参数:
behaviors (str) -- name of the behavior script.
- invoke_behavior(kinematics: str, action: str, **kwargs: Any) Any[源代码]#
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.
- 参数:
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.
- 返回:
Generated velocity vector (2x1) in the format appropriate for the specified kinematics model.
- 返回类型:
np.ndarray
- 抛出:
ValueError -- If no behavior method is found for the given kinematics and action combination.
示例
>>> # 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[源代码]#
Factory class to create geometry handlers.
- static create_geometry(name: str = 'circle', **kwargs) geometry_handler[源代码]#
Create a geometry handler from a YAML
shapename.- 参数:
name -- Shape name. Supported values are
circle,polygon,rectangle,compound,linestring, andmap.**kwargs -- Shape-specific parameters forwarded to the handler.
- 返回:
Concrete geometry handler.
- 返回类型:
- 抛出:
ValueError -- If
nameis not supported.
- class irsim.lib.KinematicsFactory[源代码]#
Factory class to create kinematics handlers.
- static create_kinematics(name: str | None = None, noise: bool = False, alpha: list | None = None, mode: str | None = None, wheelbase: float | None = None, role: str = 'robot', tau: float | None = None, *, shape_wheelbase: float | None = None, **kwargs: Any) KinematicsHandler[源代码]#
Create a kinematics handler from a YAML
kinematicsblock.- 参数:
name -- Registered kinematics name:
diff,omni,omni_angular,acker, or a custom name registered withregister_kinematics().Nonedefaults todiff;staticgives thePassiveKinematicsof an object that never drives itself.noise -- Whether to apply motion noise.
alpha -- Noise parameters passed to the handler.
mode -- Steering mode of
ackerhandlers; forwarded when given.wheelbase -- Wheelbase set under
kinematics; forwarded when given and takes precedence overshape_wheelbase.role -- Object role, retained for API compatibility.
tau -- Drive lag in seconds for
collision_mode: contact; seeKinematicsHandler.tau.Noneuses the world'sdrive_tau.shape_wheelbase -- Wheelbase taken from a car-like shape; the fallback for
ackerhandlers (default1.0) whenwheelbaseis not given.**kwargs -- Any other
kinematicskey, forwarded to the handler's__init__(a custom handler's own parameters).
- 返回:
Handler instance for
name.- 返回类型:
- 抛出:
NotImplementedError -- If
nameis not registered.TypeError -- If the handler does not accept a forwarded parameter.
- static get_handler_class(name: str) type[KinematicsHandler] | None[源代码]#
Look up a registered handler class by name without instantiation.
- 参数:
name (str) -- Kinematics name (e.g.
"diff","omni").- 返回:
The class, or
Noneif not found.- 返回类型:
type[KinematicsHandler] | None
- class irsim.lib.KinematicsHandler(name, noise: bool = False, alpha: list | None = None)[源代码]#
Bases:
abc.ABCAbstract base class for handling robot kinematics.
Subclasses should set the class-attribute metadata described below and implement
step(),velocity_to_xy(),compute_max_speed(), andcompute_heading();velocity_from_xy()may be overridden when a world-frame push maps to the command frame in another way. A subclass may add keyword parameters to__init__; any extra key underkinematics:in YAML is passed to it.Initialize the KinematicsHandler class.
- 参数:
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 | None = None#
- obstacle_color: str | None = None#
- color_key: str = 'robot'#
- description: str | None = None#
- show_arrow: bool = True#
- passive: bool = False#
- default_mass: float = 1.0#
- yaw_rate_row: int | None = None#
- translation_rows: tuple[int, ...] = (0,)#
- tau: float | None = None#
- name#
- noise = False#
- alpha = [0.03, 0, 0, 0.03]#
- classmethod default_color(role: str = 'robot', pushable: bool = False) str[源代码]#
Default color of an object with this model.
The explicit
color/obstacle_colorclass attribute wins when set; otherwise the value comes fromirsim.config.palette_param(obstaclefor obstacles, the model'scolor_keyfor robots), so a palette changed at runtime applies to objects created afterwards.- 参数:
role --
"robot"or"obstacle".pushable -- Whether contacts can move the object. A driven model keeps its role color either way; the passive model turns orange (
palette_param.pushable).
- 返回:
A Matplotlib color.
- 返回类型:
str
- abstractmethod step(state: numpy.ndarray, velocity: numpy.ndarray, step_time: float) numpy.ndarray[源代码]#
Calculate the next state using the kinematics model.
- 参数:
state (np.ndarray) -- Current state.
velocity (np.ndarray) -- Velocity vector.
step_time (float) -- Time step for simulation.
- 返回:
Next state.
- 返回类型:
np.ndarray
- velocity_to_xy(state: numpy.ndarray, velocity: numpy.ndarray) numpy.ndarray[源代码]#
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 anglestate[2], which is whatvel_diff2world()does. Subclasses with different velocity semantics (e.g. omnidirectional) should override this.- 参数:
state (np.ndarray) -- Current state vector.
velocity (np.ndarray) -- Velocity vector in kinematics frame.
- 返回:
(2, 1) array of [vx, vy].
- 返回类型:
np.ndarray
- velocity_from_xy(state: numpy.ndarray, velocity_xy: numpy.ndarray) numpy.ndarray[源代码]#
Express a world-frame
[vx, vy]motion in this model's command frame.The inverse of
velocity_to_xy()as far as the model allows; thecontactcollision mode uses it to fold a push into the velocity. The default keeps only the forward component along the headingstate[2], which is all a differential or car-like model can express: a sideways push has no command counterpart.- 参数:
state (np.ndarray) -- Current state vector.
velocity_xy (np.ndarray) -- World-frame velocity
[vx, vy](2x1).
- 返回:
(action_dim, 1)velocity in the command frame.- 返回类型:
np.ndarray
- coast(velocity: numpy.ndarray, step_time: float, friction: float, gyration: float = 0.0, gravity: float = 9.81) numpy.ndarray[源代码]#
Velocity the object keeps for one step when nothing commands it.
A driven model stops: without a command or behavior it stays put. A passive body keeps its momentum and is slowed by ground friction.
- 参数:
velocity (np.ndarray) -- Velocity at the end of the previous step.
step_time (float) -- Time step.
friction (float) -- The object's friction coefficient.
gyration (float) -- Radius of gyration, the lever at which a spinning body's rim slides;
0when it cannot spin.gravity (float) -- Gravitational acceleration, the world's.
- 返回:
Velocity to integrate this step, same shape as
velocity.- 返回类型:
np.ndarray
- compute_max_speed(vel_max: numpy.ndarray) float[源代码]#
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.- 参数:
vel_max (np.ndarray) -- Maximum velocity vector.
- 返回:
Scalar maximum speed.
- 返回类型:
float
- compute_heading(state: numpy.ndarray, velocity: numpy.ndarray) float[源代码]#
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.- 参数:
state (np.ndarray) -- Current state vector.
velocity (np.ndarray) -- Current velocity vector.
- 返回:
Heading in radians.
- 返回类型:
float
- irsim.lib.register_kinematics(name: str)[源代码]#
Decorator to register a KinematicsHandler subclass.
Any extra key under
kinematics:in YAML is passed to the subclass's__init__(aftername,noise,alpha), so a registered model can take its own parameters, e.g.kinematics: {name: lag, tau: 0.5}.- 参数:
name (str) -- Name used in YAML configs (e.g.
"diff","omni").- 返回:
Class decorator that registers and returns the class unchanged.
- 返回类型:
Callable
- irsim.lib.kinematics_factory: dict[str, collections.abc.Callable[..., Any]]#