irsim.env.env_base#
Class EnvBase is the base class of the environment.
It loads YAML configuration via EnvConfig to construct the world,
robots, obstacles, and maps, and provides the core simulation loop.
The environment can be reconfigured in-place (same figure) by reloading
the YAML at runtime.
Author: Ruihua Han
Attributes#
Classes#
The base class for simulation environments in IR-SIM. |
Module Contents#
- irsim.env.env_base.keyboard_module = True#
- irsim.env.env_base.BACKEND_PREFERENCES#
- irsim.env.env_base.backends#
- irsim.env.env_base.backend_set = True#
- class irsim.env.env_base.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)[源代码]#
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.- 参数:
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
示例
>>> # 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.
- 参数:
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.
备注
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.
示例
>>> # 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[源代码]#
Render the environment.
- 参数:
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[源代码]#
Draw the trajectory on the environment figure.
- 参数:
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[源代码]#
Draw points on the environment figure.
- 参数:
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[源代码]#
Draw a box by the vertices.
- 参数:
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[源代码]#
Draw a single quiver (arrow) on the environment figure.
- 参数:
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[源代码]#
Draw multiple quivers (arrows) on the environment figure.
- 参数:
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[源代码]#
End the simulation, save the animation, and close the environment.
- 参数:
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[源代码]#
Alias for
end()for Gym-style API compatibility.
- done(mode: str = 'all') bool | None[源代码]#
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.
- 参数:
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".
- 返回:
True if the termination condition is met based on the specified mode, False otherwise. Returns False if no robots are present in the environment.
- 返回类型:
bool
示例
>>> # 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[源代码]#
Pause the simulation execution.
When paused, calls to
step()will return immediately without performing any simulation updates. The environment status is set to "Pause".示例
>>> env.pause() >>> env.step([1.0, 0.0]) # This will have no effect while paused
- resume() None[源代码]#
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.示例
>>> env.pause() >>> # ... some time later ... >>> env.resume() >>> env.step([1.0, 0.0]) # This will now work again
- reset(random: bool = False) None[源代码]#
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
- 参数:
random (bool) -- If True, rebuild the world from the cached YAML parse (the config loaded at env creation, not the file on disk) so any randomized elements (e.g.
distribution: random, random shape generators) are re-sampled from the current RNG state. Callirsim.util.random.set_seed()beforereset(random=True)to get a reproducible fresh scene. Default is False — only restores original initial states.
示例
>>> # Reset environment after simulation >>> env.reset() >>> # Reset and re-sample random distributions / shapes >>> env.reset(random=True)
- refresh() None[源代码]#
Refresh state-derived attributes across the environment without advancing the simulation.
Calls
ObjectBase.refreshon every object (geometry, geometry validity, sensor readings), rebuilds the collision STRtree, and re-evaluates collision/arrival status. Used afterresetand whenever callers mutate object states directly and need derived views (geometry, sensors, collisions) brought up to date.
- reset_plot() None[源代码]#
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[源代码]#
Random obstacle positions in the environment.
- 参数:
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[源代码]#
Random polygon shapes for the obstacles in the environment.
- 参数:
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[源代码]#
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).
- 参数:
world_name (str) -- Optional name/path of the world YAML to reload. If
None, the previous YAML file is used.
- create_obstacle(**kwargs: Any)[源代码]#
Create an obstacle in the environment.
- 参数:
**kwargs -- Additional parameters for obstacle creation. see ObjectFactory.create_obstacle for detail
- 返回:
An instance of an obstacle.
- 返回类型:
Obstacle
- create_robot(**kwargs: Any)[源代码]#
Create a robot in the environment.
- 参数:
**kwargs -- Additional parameters for robot creation. see ObjectFactory.create_robot for detail
- 返回:
An instance of a robot.
- 返回类型:
Robot
- add_object(obj: irsim.world.ObjectBase) None[源代码]#
Add the object to the environment, enforcing unique names.
- 参数:
obj (ObjectBase) -- The object to be added to the environment.
- add_objects(objs: list[irsim.world.ObjectBase]) None[源代码]#
Add the objects to the environment, enforcing unique names (both within the new list and against existing objects).
- 参数:
objs (list) -- List of objects to be added to the environment.
- delete_object(target_id: int) None[源代码]#
Delete the object with the given id.
- 参数:
target_id (int) -- ID of the object to be deleted.
- delete_objects(target_ids: list[int]) None[源代码]#
Delete the objects with the given ids.
- 参数:
target_ids (list) -- List of IDs of objects to be deleted.
- build_tree() None[源代码]#
Build the geometry tree for the objects in the environment to detect the possible collision objects.
- validate_unique_names() None[源代码]#
Validate that all object names are unique.
- 抛出:
ValueError -- If duplicates exist.
- get_robot_state() numpy.ndarray[源代码]#
Get the current state of the robot.
- 返回:
3*1 vector [x, y, theta]
- 返回类型:
- get_lidar_scan(id: int = 0) dict[str, Any][源代码]#
Get the LiDAR scan of the robot with the given id.
- 参数:
id (int) -- Id of the robot.
- 返回:
Dict of lidar scan points, see
world.sensors.lidar2d.Lidar2D.get_scan()for detail.- 返回类型:
Dict
- get_lidar_offset(id: int = 0) list[float][源代码]#
Get the LiDAR offset of the robot with the given id.
- 参数:
id (int) -- Id of the robot.
- 返回:
Lidar offset of the robot, [x, y, theta]
- 返回类型:
list of float
- get_obstacle_info_list() list[Any][源代码]#
Get the information of the obstacles in the environment.
- 返回:
List of obstacle information, see
ObjectBase.get_obstacle_info()for detail.- 返回类型:
list of ObstacleInfo
- get_robot_info(id: int = 0) Any[源代码]#
Get the information of the robot with the given id.
- 参数:
id (int) -- Id of the robot.
- 返回:
see
ObjectBase.get_info()for detail
- get_robot_info_list() list[Any][源代码]#
Get the information of the robots in the environment.
- 返回:
List of robot information, see
ObjectBase.get_info()for detail.- 返回类型:
list of ObjectInfo
- get_map(resolution: float = 0.1) Any[源代码]#
Get the map of the environment with the given resolution.
- 参数:
resolution (float) -- Resolution of the map. Default is 0.1.
- 返回:
The map of the environment with the specified resolution.
- get_group_by_name(group_name: str) list[irsim.world.ObjectBase][源代码]#
Get the objects with the given group name.
- 参数:
group_name (str) -- Group name of the robot.
- 返回:
The object list with the given group name.
- 返回类型:
list[ObjectBase]
- get_object_by_name(name: str) irsim.world.ObjectBase | None[源代码]#
Get the object with the given name.
- get_object_by_id(target_id: int) irsim.world.ObjectBase | None[源代码]#
Get the object with the given id.
- set_random_seed(seed: int | None = None, reload: bool = False) None[源代码]#
Set IR-SIM's random seed for reproducibility.
- 参数:
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).
示例
>>> 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[源代码]#
Save the current figure.
- 参数:
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[源代码]#
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.
- 参数:
behaviors (str) -- name of the behavior script.
- property robot_list: list[irsim.world.ObjectBase]#
Get the list of robots in the environment.
- 返回:
List of robot objects [].
- 返回类型:
list
- property obstacle_list: list[irsim.world.ObjectBase]#
Get the list of obstacles in the environment.
- 返回:
List of obstacle objects.
- 返回类型:
list
- property objects: list[irsim.world.ObjectBase]#
Get all objects in the environment.
- 返回:
List of all objects in the environment.
- 返回类型:
list
- property static_objects: list[irsim.world.ObjectBase]#
Get all static objects in the environment.
- 返回:
List of static objects in the environment.
- 返回类型:
list
- property dynamic_objects: list[irsim.world.ObjectBase]#
Get all dynamic objects in the environment.
- 返回:
List of dynamic objects in the environment.
- 返回类型:
list
- property step_time: float#
Get the step time of the simulation.
- 返回:
Step time of the simulation from the world.
- 返回类型:
float
- property world_param#
Get the world parameters of the simulation.
- 返回:
- World parameters including time, control_mode,
collision_mode, step_time, and count.
- 返回类型:
- property env_param#
Get the environment parameters.
- 返回:
Environment parameters including logger and objects.
- 返回类型:
- property path_param#
Get the path manager for the simulation.
- 返回:
- Path manager including root_path, ani_buffer_path,
ani_path, and fig_path.
- 返回类型:
- 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.
- 返回:
The first robot object in the robot list.
- 返回类型:
Robot
- 抛出:
IndexError -- If no robots exist in the environment.
- property obstacle_number: int#
Get the number of obstacles in the environment.
- 返回:
Number of obstacles in the environment.
- 返回类型:
int
- property robot_number: int#
Get the number of robots in the environment.
- 返回:
Number of robots in the environment.
- 返回类型:
int
- property logger: irsim.env.env_logger.EnvLogger#
Get the environment logger.
- 返回:
The logger instance for the environment.
- 返回类型:
- property key_vel: Any#
Get current keyboard velocity command.
- 返回:
A 3x1 vector
[[linear], [lateral], [angular]]from keyboard input.- 返回类型:
Any
- property key_id: int#
Get current keyboard-controlled robot id.
- 返回:
The robot id currently controlled by keyboard.
- 返回类型:
int
- property mouse_pos: Any#
Get current mouse position on the canvas.
- 返回:
Mouse coordinates
(x, y)orNoneif outside axes.- 返回类型:
Any
- property mouse_left_pos: Any#
Get last left-click position.
- 返回:
Position array or
Noneif not set.- 返回类型:
Any
- property mouse_right_pos: Any#
Get last right-click position.
- 返回:
Position array or
Noneif not set.- 返回类型:
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.