irsim.env#
Submodules#
Classes#
Package Contents#
- class irsim.env.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', seed: int | None = None)[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 (through
EnvConfig) to create worlds, robots, obstacles, and map objects, and provides the core simulation loop functionality. The environment supports in-place reload of YAML configuration to update the scene in the existing figure without opening a new window.- 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’.
seed (int, optional) – Seed for the random number generator. Default is None. If None, the seed will be set to a random value, which will make the simulation non-reproducible. If a fixed seed is provided, the random simulation scenario will be reproducible.
- display#
Whether to display the environment visualization.
- Type:
bool
- disable_all_plot#
Whether all plotting is disabled.
- Type:
bool
- save_ani#
Whether to save animation during simulation.
- Type:
bool
- keyboard#
Keyboard input handler for manual control.
- Type:
- mouse#
Mouse input handler for zoom and pan.
- Type:
- pause_flag#
Internal flag indicating if simulation is paused.
- Type:
bool
- quit_flag#
Internal flag indicating if simulation should quit.
- Type:
bool
- debug_flag#
Internal flag for debug mode (frame-by-frame stepping).
- Type:
bool
- debug_count#
Counter for debug mode frames.
- Type:
int
- reset_flag#
Internal flag for environment reset.
- Type:
bool
- reload_flag#
Internal flag for YAML reload.
- Type:
bool
- save_figure_flag#
Internal flag to save current figure.
- Type:
bool
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) >>> >>> # Create environment with a fixed seed for reproducibility >>> env = EnvBase("world.yaml", seed=42)
- display = True#
- disable_all_plot = False#
- save_ani = False#
- mouse#
- pause_flag = False#
- quit_flag = False#
- debug_flag = False#
- debug_count = 0#
- reset_flag = False#
- reload_flag = False#
- save_figure_flag = False#
- step(action: numpy.ndarray | list[Any] | None = None, action_id: int | list[int] | None = 0) None#
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.
- Note - Priority Order:
Apply keyboard control for the specified
action_idif enabled.Apply the provided
action(list of numpy arrays) to robots byaction_id(int or list of int).For remaining robots, fall back to their configured behaviors when
actionisNone.
- 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.01, 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 details.
mode (str) – One of {“dynamic”, “static”, “all”} specifying which types of objects to draw and clear each frame.
kwargs – Additional keyword arguments for drawing components. See
ObjectBase.plot()for details.
- 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. Each point is a 2x1 vector or an array of shape (2, N).
traj_type (str) – Matplotlib line style (e.g., “g-”, “r–“).
**kwargs – Additional keyword arguments; forwarded to
EnvPlot.draw_trajectory().
- 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 | np.ndarray) – Either a list of 2x1 points or a numpy array with shape (2, N).
s (int) – Marker size.
c (str) – Marker color.
refresh (bool) – Whether to clear previous points before drawing.
**kwargs – Additional keyword arguments, forwarded to Axes.scatter.
- draw_box(vertex: numpy.ndarray, refresh: bool = False, color: str = '-b') None[source]#
Draw a box by the vertices.
- Parameters:
vertex (np.ndarray) – Vertices matrix with shape (point_dim, num_vertices).
refresh (bool) – Whether to clear previous boxes before drawing. Default is False.
color (str) – Line style/color for the box (e.g., “-b”).
- draw_quiver(point: Any, refresh: bool = False, **kwargs: Any) None[source]#
Draw a single quiver (arrow) on the environment figure.
- Parameters:
point – A tuple
(x, y, u, v)or compatible structure defining the arrow’s origin and vector.refresh (bool) – Whether to clear previous quiver before drawing. 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 – Iterable of tuples/lists/arrays compatible with
(x, y, u, v)per arrow.refresh (bool) – Whether to clear previous quivers before drawing. 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.
- close(ending_time: float = 3.0, **kwargs: Any) None[source]#
Alias for
end()for Gym-style API compatibility.
- 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!")
- 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
- reset_plot() None[source]#
Reset the environment figure in-place.
Re-initializes drawing on the current figure/axes using the existing
EnvPlotinstance; does not create a new figure window.
- random_obstacle_position(range_low: list[float] | numpy.ndarray | None = None, range_high: list[float] | numpy.ndarray | 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.
- reload(world_name: str | None = None) None[source]#
Reload the environment from YAML and update the current figure.
This re-parses the YAML and re-creates world/objects, then refreshes drawing on the existing figure/axes (no new window is created).
- Parameters:
world_name (str) – Optional name/path of the world YAML to reload. If
None, the previous YAML file is used.
- 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
- create_robot(**kwargs: Any)[source]#
Create a robot in the environment.
- Parameters:
**kwargs – Additional parameters for robot creation. see ObjectFactory.create_robot for detail
- Returns:
An instance of a robot.
- Return type:
Robot
- add_object(obj: irsim.world.ObjectBase) None[source]#
Add the object to the environment, enforcing unique names.
- 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, enforcing unique names (both within the new list and against existing objects).
- 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.
- validate_unique_names() None[source]#
Validate that all object names are unique.
- Raises:
ValueError – If duplicates exist.
- get_robot_state() numpy.ndarray[source]#
Get the current state of the robot.
- Returns:
3*1 vector [x, y, theta]
- Return type:
- 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[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 ObstacleInfo
- 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[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 ObjectInfo
- 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.
- get_group_by_name(group_name: str) list[irsim.world.ObjectBase][source]#
Get the objects with the given group name.
- Parameters:
group_name (str) – Group name of the robot.
- Returns:
The object list with the given group name.
- Return type:
list[ObjectBase]
- get_object_by_name(name: str) irsim.world.ObjectBase | None[source]#
Get the object with the given name.
- get_object_by_id(target_id: int) irsim.world.ObjectBase | None[source]#
Get the object with the given id.
- set_random_seed(seed: int | None = None, reload: bool = False) None[source]#
Set IR-SIM’s random seed for reproducibility.
- Parameters:
seed (int, optional) – Seed for IR-SIM’s project RNG. If
None, a new unseeded generator is created (non-reproducible). This controls randomness that goes through IR-SIM’s RNG. Custom code usingnp.random.*or Pythonrandommust be seeded separately or migrated to use IR-SIM’s RNG.reload (bool) – If True, reload the environment to regenerate random obstacles with the new seed. Default is False (only sets seed).
Example
>>> env.set_random_seed(100) # Only set seed, no regeneration >>> env.set_random_seed(100, reload=True) # Set seed and regenerate env by yaml file
- 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.
This method imports the specified module and reinitializes all behaviors (both individual and group) so that newly registered behaviors are available.
- Parameters:
behaviors (str) – name of the behavior 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 world_param#
Get the world parameters of the simulation.
- Returns:
- World parameters including time, control_mode,
collision_mode, step_time, and count.
- Return type:
- property env_param#
Get the environment parameters.
- Returns:
Environment parameters including logger and objects.
- Return type:
- property path_param#
Get the path manager for the simulation.
- Returns:
- Path manager including root_path, ani_buffer_path,
ani_path, and fig_path.
- Return type:
- 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
- Raises:
IndexError – If no robots exist in the environment.
- 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#
Get current keyboard velocity command.
- Returns:
A 2x1 vector
[[linear], [angular]]from keyboard input.- Return type:
Any
- property key_id: int#
Get current keyboard-controlled robot id.
- Returns:
The robot id currently controlled by keyboard.
- Return type:
int
- property mouse_pos: Any#
Get current mouse position on the canvas.
- Returns:
Mouse coordinates
(x, y)orNoneif outside axes.- Return type:
Any
- property mouse_left_pos: Any#
Get last left-click position.
- Returns:
Position array or
Noneif not set.- Return type:
Any
- property mouse_right_pos: Any#
Get last right-click position.
- Returns:
Position array or
Noneif not set.- Return type:
Any
- property names: list[str]#
Get the names of all objects in the environment.
- property object_factory: irsim.world.ObjectFactory#
Get the object factory of the environment.
- class irsim.env.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.Initialize a 3D environment with world and objects parsed from YAML.
- Parameters:
world_name (str | None) – Path to the world configuration YAML.
**kwargs – Additional environment options forwarded to
EnvBase.