irsim#
Submodules#
Classes#
Functions#
|
Create an environment by the given world file and projection. |
Package Contents#
- class irsim.EnvBase(world_name: str | None = None, display: bool = True, disable_all_plot: bool = False, save_ani: bool = False, full: bool = False, log_file: str | None = None, log_level: str = 'INFO')[source]#
The base class for simulation environments in IR-SIM.
This class serves as the foundation for creating and managing robotic simulation environments. It reads YAML configuration files to create worlds, robots, obstacles, and map objects, and provides the core simulation loop functionality.
- Parameters:
world_name (str, optional) – Path to the world YAML configuration file. If None, the environment will attempt to find a default configuration or use a minimal setup.
display (bool) – Whether to display the environment visualization. Set to False for headless operation. Default is True.
disable_all_plot (bool) – Whether to disable all plots and figures completely. When True, no visualization will be created even if display is True. Default is False.
save_ani (bool) – Whether to save the simulation as an animation file. Useful for creating videos of simulation runs. Default is False.
full (bool) – Whether to display the visualization in full screen mode. Only effective on supported platforms. Default is False.
log_file (str, optional) – Path to the log file for saving simulation logs. If None, logs will only be output to console.
log_level (str) – Logging level for the environment. Options include ‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’, ‘CRITICAL’. Default is ‘INFO’.
- display#
Display flag for the environment.
- Type:
bool
- disable_all_plot#
Plot disable flag.
- Type:
bool
- save_ani#
Animation saving flag.
- Type:
bool
- objects#
List of all objects in the environment.
- Type:
list
- robot_collection#
List of robot objects.
- Type:
list
- obstacle_collection#
List of obstacle objects.
- Type:
list
- map_collection#
List of map objects.
- Type:
list
Example
>>> # Create a basic environment >>> env = EnvBase("my_world.yaml") >>> >>> # Create headless environment for training >>> env = EnvBase("world.yaml", display=False, log_level="WARNING") >>> >>> # Create environment with animation saving >>> env = EnvBase("world.yaml", save_ani=True, full=True)
- display = True#
- disable_all_plot = False#
- save_ani = False#
- env_config#
- object_factory#
- mouse#
- pause_flag = False#
- step(action: numpy.ndarray | list[Any] | None = None, action_id: int | list[int] | None = 0) None[source]#
Perform a single simulation step in the environment.
This method advances the simulation by one time step, applying the given actions to the specified robots and updating all objects in the environment.
- Parameters:
action (Union[np.ndarray, list], optional) –
Action(s) to be performed in the environment. Can be a single action or a list of actions. Action format depends on robot type:
Differential robot: [linear_velocity, angular_velocity]
Omnidirectional robot: [velocity_x, velocity_y]
Ackermann robot: [linear_velocity, steering_angle]
If None, robots will use their default behavior or keyboard control if enabled.
action_id (Union[int, list], optional) – ID(s) of the robot(s) to apply the action(s) to. Can be a single robot ID or a list of IDs. Default is 0 (first robot). If action is a list and action_id is a single int, all actions will be applied to robots sequentially starting from action_id.
Note
If the environment is paused, this method returns without performing any updates.
The method automatically handles collision detection, status updates, and plotting.
In keyboard control mode, the action parameter is ignored and keyboard input is used.
Example
>>> # Move first robot with differential drive >>> env.step([1.0, 0.5]) # 1.0 m/s forward, 0.5 rad/s turn >>> >>> # Move specific robot by ID >>> env.step([0.8, 0.0], action_id=2) # Move robot with ID 2 >>> >>> # Move multiple robots >>> actions = [[1.0, 0.0], [0.5, 0.3]] >>> env.step(actions, action_id=[0, 1]) # Move robots 0 and 1
- render(interval: float = 0.02, figure_kwargs: dict[str, Any] | None = None, mode: str = 'dynamic', **kwargs: Any) None[source]#
Render the environment.
- Parameters:
interval (float) – Time interval between frames in seconds.
figure_kwargs (dict) – Additional keyword arguments for saving figures, see savefig for detail.
mode (str) – “dynamic”, “static”, “all” to specify which type of objects to draw and clear.
kwargs – Additional keyword arguments for drawing components. see
ObjectBase.plot()function for detail.
- draw_trajectory(traj: list[Any], traj_type: str = 'g-', **kwargs: Any) None[source]#
Draw the trajectory on the environment figure.
- Parameters:
traj (list) – List of trajectory points (2 * 1 vector).
traj_type – Type of the trajectory line, see matplotlib plot function for detail.
**kwargs – Additional keyword arguments for drawing the trajectory, see
EnvPlot.draw_trajectory()for detail.
- draw_points(points: list[Any], s: int = 30, c: str = 'b', refresh: bool = True, **kwargs: Any) None[source]#
Draw points on the environment figure.
- Parameters:
points (list) – List of points (2*1) to be drawn. or (np.array): (2, Num) to be drawn.
s (int) – Size of the points.
c (str) – Color of the points.
refresh (bool) – Flag to refresh the points in the figure.
**kwargs – Additional keyword arguments for drawing the points, see ax.scatter function for detail.
- draw_box(vertex: numpy.ndarray, refresh: bool = False, color: str = '-b') None[source]#
Draw a box by the vertices.
- Parameters:
vertex (np.ndarray) – matrix of vertices, point_dim*vertex_num
refresh (bool) – whether to refresh the plot, default True
color (str) – color of the box, default ‘-b’
- draw_quiver(point: Any, refresh: bool = False, **kwargs: Any) None[source]#
Draw a single quiver (arrow) on the environment figure.
- Parameters:
point – Point data for the quiver
refresh (bool) – Flag to refresh the quiver in the figure, default False
**kwargs – Additional keyword arguments for drawing the quiver
- draw_quivers(points: Any, refresh: bool = False, **kwargs: Any) None[source]#
Draw multiple quivers (arrows) on the environment figure.
- Parameters:
points – Points data for the quivers
refresh (bool) – Flag to refresh the quivers in the figure, default False
**kwargs – Additional keyword arguments for drawing the quivers
- end(ending_time: float = 3.0, **kwargs: Any) None[source]#
End the simulation, save the animation, and close the environment.
- Parameters:
ending_time (float) – Time in seconds to wait before closing the figure, default is 3 seconds.
**kwargs – Additional keyword arguments for saving the animation, see
EnvPlot.save_animate()for detail.
- done(mode: str = 'all') bool | None[source]#
Check if the simulation should terminate based on robot completion status.
This method evaluates whether robots in the environment have reached their goals or completed their tasks, using different criteria based on the mode.
- Parameters:
mode (str) –
Termination condition mode. Options are:
”all”: Simulation is done when ALL robots have completed their tasks
”any”: Simulation is done when ANY robot has completed its task
Default is “all”.
- Returns:
True if the termination condition is met based on the specified mode, False otherwise. Returns False if no robots are present in the environment.
- Return type:
bool
Example
>>> # Check if all robots have reached their goals >>> if env.done(mode="all"): ... print("All robots completed!") >>> >>> # Check if any robot has completed >>> if env.done(mode="any"): ... print("At least one robot completed!")
- step_status() None[source]#
Update and log the current status of all robots in the environment.
This method checks the arrival status of all robots and logs information about which robots have reached their goals. It’s automatically called during each simulation step.
Note
This is an internal method primarily used for status tracking and logging. The status information is automatically updated during simulation steps.
- pause() None[source]#
Pause the simulation execution.
When paused, calls to
step()will return immediately without performing any simulation updates. The environment status is set to “Pause”.Example
>>> env.pause() >>> env.step([1.0, 0.0]) # This will have no effect while paused
- resume() None[source]#
Resume the simulation execution after being paused.
Re-enables simulation updates and sets the environment status back to “Running”. Subsequent calls to
step()will function normally.Example
>>> env.pause() >>> # ... some time later ... >>> env.resume() >>> env.step([1.0, 0.0]) # This will now work again
- reset() None[source]#
Reset the environment to its initial state.
This method resets all objects, robots, obstacles, and the world to their initial configurations. It also resets the visualization and sets the environment status to “Reset”.
The reset process includes: - Resetting all objects to their initial positions and states - Clearing accumulated trajectories and sensor data - Resetting the world timer and status - Refreshing the visualization plot
Example
>>> # Reset environment after simulation >>> env.reset() >>> # Environment is now ready for a new simulation run
- random_obstacle_position(range_low: list[float] | None = None, range_high: list[float] | None = None, ids: list[int] | None = None, non_overlapping: bool = False) None[source]#
Random obstacle positions in the environment.
- Parameters:
range_low (list [x, y, theta]) – Lower bound of the random range for the obstacle states. Default is [0, 0, -3.14].
range_high (list [x, y, theta]) – Upper bound of the random range for the obstacle states. Default is [10, 10, 3.14].
ids (list) – A list of IDs of objects for which to set random positions. Default is None.
non_overlapping (bool) – If set, the obstacles that will be reset to random obstacles will not overlap with other obstacles. Default is False.
- random_polygon_shape(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) None[source]#
Random polygon shapes for the obstacles in the environment.
- Parameters:
center_range (list) – Range of the center of the polygon. Default is [0, 0, 10, 10].
avg_radius_range (list) – Range of the average radius of the polygon. Default is [0.1, 1].
irregularity_range (list) – Range of the irregularity of the polygon. Default is [0, 1].
spikeyness_range (list) – Range of the spikeyness of the polygon. Default is [0, 1].
num_vertices_range (list) – Range of the number of vertices of the polygon. Default is [4, 10].
center (Tuple[float, float]) – a pair representing the center of the circumference used to generate the polygon.
avg_radius (float) – the average radius (distance of each generated vertex to the center of the circumference) used to generate points with a normal distribution.
irregularity (float) – 0 - 1 variance of the spacing of the angles between consecutive vertices.
spikeyness (float) – 0 - 1 variance of the distance of each vertex to the center of the circumference.
num_vertices (int) – the number of vertices of the polygon.
- create_obstacle(**kwargs: Any)[source]#
Create an obstacle in the environment.
- Parameters:
**kwargs – Additional parameters for obstacle creation. see ObjectFactory.create_obstacle for detail
- Returns:
An instance of an obstacle.
- Return type:
Obstacle
- add_object(obj: irsim.world.ObjectBase) None[source]#
Add the object to the environment.
- Parameters:
obj (ObjectBase) – The object to be added to the environment.
- add_objects(objs: list[irsim.world.ObjectBase]) None[source]#
Add the objects to the environment.
- Parameters:
objs (list) – List of objects to be added to the environment.
- delete_object(target_id: int) None[source]#
Delete the object with the given id.
- Parameters:
target_id (int) – ID of the object to be deleted.
- delete_objects(target_ids: list[int]) None[source]#
Delete the objects with the given ids.
- Parameters:
target_ids (list) – List of IDs of objects to be deleted.
- build_tree() None[source]#
Build the geometry tree for the objects in the environment to detect the possible collision objects.
- get_robot_state() numpy.ndarray[source]#
Get the current state of the robot.
- Returns:
3*1 vector [x, y, theta]
- Return type:
state
- get_lidar_scan(id: int = 0) dict[str, Any][source]#
Get the lidar scan of the robot with the given id.
- Parameters:
id (int) – Id of the robot.
- Returns:
Dict of lidar scan points, see
world.sensors.lidar2d.Lidar2D.get_scan()for detail.- Return type:
Dict
- get_lidar_offset(id: int = 0) list[float][source]#
Get the lidar offset of the robot with the given id.
- Parameters:
id (int) – Id of the robot.
- Returns:
Lidar offset of the robot, [x, y, theta]
- Return type:
list of float
- get_obstacle_info_list() list[dict[str, Any]][source]#
Get the information of the obstacles in the environment.
- Returns:
List of obstacle information, see
ObjectBase.get_obstacle_info()for detail.- Return type:
list of dict
- get_robot_info(id: int = 0) Any[source]#
Get the information of the robot with the given id.
- Parameters:
id (int) – Id of the robot.
- Returns:
see
ObjectBase.get_info()for detail
- get_robot_info_list() list[dict[str, Any]][source]#
Get the information of the robots in the environment.
- Returns:
List of robot information, see
ObjectBase.get_info()for detail.- Return type:
list of dict
- get_map(resolution: float = 0.1) Any[source]#
Get the map of the environment with the given resolution.
- Parameters:
resolution (float) – Resolution of the map. Default is 0.1.
- Returns:
The map of the environment with the specified resolution.
- save_figure(save_name: str | None = None, include_index: bool = False, save_gif: bool = False, **kwargs: Any) None[source]#
Save the current figure.
- Parameters:
save_name (str) – Name of the file with format to save the figure. Default is None.
include_index (bool) – Flag to include index in the saved file name. Default is False.
save_gif (bool) – Flag to save as GIF format. Default is False.
**kwargs –
Additional keyword arguments for saving the figure, see savefig function for detail.
- load_behavior(behaviors: str = 'behavior_methods') None[source]#
Load behavior parameters from the script. Please refer to the behavior_methods.py file for more details. Please make sure the python file is placed in the same folder with the implemented script.
- Parameters:
behaviors (str) – name of the bevavior script.
- property robot_list: list[irsim.world.ObjectBase]#
Get the list of robots in the environment.
- Returns:
List of robot objects [].
- Return type:
list
- property obstacle_list: list[irsim.world.ObjectBase]#
Get the list of obstacles in the environment.
- Returns:
List of obstacle objects.
- Return type:
list
- property objects: list[irsim.world.ObjectBase]#
Get all objects in the environment.
- Returns:
List of all objects in the environment.
- Return type:
list
- property static_objects: list[irsim.world.ObjectBase]#
Get all static objects in the environment.
- Returns:
List of static objects in the environment.
- Return type:
list
- property dynamic_objects: list[irsim.world.ObjectBase]#
Get all dynamic objects in the environment.
- Returns:
List of dynamic objects in the environment.
- Return type:
list
- property step_time: float#
Get the step time of the simulation.
- Returns:
Step time of the simulation from the world.
- Return type:
float
- property time: float#
Get the time of the simulation.
- property status: str#
Get the status of the environment.
- property robot: irsim.world.ObjectBase#
Get the first robot in the environment.
- Returns:
The first robot object in the robot list.
- Return type:
Robot
- property obstacle_number: int#
Get the number of obstacles in the environment.
- Returns:
Number of obstacles in the environment.
- Return type:
int
- property robot_number: int#
Get the number of robots in the environment.
- Returns:
Number of robots in the environment.
- Return type:
int
- property logger: irsim.env.env_logger.EnvLogger#
Get the environment logger.
- Returns:
The logger instance for the environment.
- Return type:
- property key_vel: Any#
- property key_id: int#
- property mouse_pos: Any#
- property mouse_left_pos: Any#
- property mouse_right_pos: Any#
- class irsim.EnvBase3D(world_name: str | None, **kwargs: Any)[source]#
Bases:
irsim.env.EnvBaseThis class is the 3D version of the environment class. It inherits from the
EnvBaseclass to provide the 3D plot environment.
- irsim.make(world_name: str | None = None, projection: str | None = None, **kwargs: Any) env.EnvBase[source]#
Create an environment by the given world file and projection.
This function serves as the main entry point for creating simulation environments. It automatically selects between 2D and 3D environments based on the projection parameter.
- Parameters:
world_name (str, optional) – The name of the world YAML configuration file. If not specified, the default name of the current Python script with ‘.yaml’ extension will be used.
projection (str, optional) – The projection type of the environment. Default is None for 2D environment. If set to “3d”, creates a 3D plot environment.
**kwargs –
Additional keyword arguments passed to
EnvBaseorEnvBase3D. Common options include:display (bool): Whether to display the environment visualization
save_ani (bool): Whether to save animation
log_level (str): Logging level for the environment
- Returns:
The created environment object. Returns
EnvBase3Dif projection is “3d”, otherwise returnsEnvBase.- Return type:
Example
>>> # Create a 2D environment with default world file >>> env = make() >>> >>> # Create a 3D environment with custom world file >>> env = make("my_world.yaml", projection="3d") >>> >>> # Create environment with additional options >>> env = make("world.yaml", display=True, save_ani=False)