IR-SIM (Intelligent Robot Simulator)

repository·main·Indexed 22 days ago

https://github.com/hanruihua/ir-sim

An open-source, lightweight, YAML-driven Python robot simulator for navigation, control, and learning. Version 2.10.2 supports various kinematics (Differential, Omnidirectional, Ackermann), sensors (2D LiDAR, FMCW LiDAR, FOV Detector), and behaviors (RVO, ORCA, SFM). It includes a Binary Map Generator for converting 3D scene datasets (HM3D, MatterPort3D, Gibson) into 2D occupancy maps and provides examples for Control Barrier Function (CBF) controllers.

Tokens
45.7K
Snippets
123
Records
188
Agent score
77%

What's inside ir-sim

  1. Overview of IR-SIM capabilities

    main

    IR-SIM is a lightweight Python robot simulator designed for navigation, control, and learning. It provides a framework for modeling robots, sensors, and environments with built-in collision detection.

    Supported Features:

    • Kinematics: Differential drive, Omnidirectional, Omnidirectional (angular), and Ackermann steering.
    • Sensors: 2D LiDAR, 2D FMCW LiDAR, and FOV (Field-of-View) detectors.
    • Geometries: Circle, Rectangle, Polygon, LineString, and Binary grid maps.
    • Behaviors: dash, RVO (Reciprocal Velocity Obstacles), ORCA (Optimal Reciprocal Collision Avoidance), and SFM (Social Force Model).

    Key Use Cases:

    • Prototyping robotics and AI algorithms in custom scenarios.
    • Multi-agent and robot learning research.
    • Real-time visualization of simulation outcomes using matplotlib.
  2. Overview of IR-SIM YAML configuration structure

    main

    An IR-SIM scene is defined using a YAML configuration file containing up to four top-level keys: world, robot, obstacle, and gui.

    • world: Defines the simulation environment settings.
    • robot: Defines robot instances.
    • obstacle: Defines obstacle instances.
    • gui: Defines graphical user interface settings.

    Note that robot and obstacle share the same per-object key structure, though their factory defaults (such as role, color, state dimension, and image description) may vary based on their specific type and kinematics. Most keys are optional unless their default value is unset.

  3. How path planning works in IR-SIM

    main

    Path planning in IR-SIM is a programmatic workflow used to compute collision-free trajectories on an occupancy map. The process follows a consistent four-step pattern regardless of the algorithm used:

    1. Build the map: Use env.get_map(resolution=...) to generate an occupancy grid. The resolution parameter defines the planning cell size in meters.
    2. Create the planner: Instantiate a planner from irsim.lib.path_planners by passing the map (and optionally the robot for sampling-based planners).
    3. Plan: Call planner.planning(start, goal) where start and goal are typically retrieved from env.get_robot_state() and env.get_robot_info().goal respectively. This returns a list of [x, y] points (a trajectory) or None if no path is found.
    4. Draw / follow: Use env.draw_trajectory(trajectory) to visualize the path in the simulator, or pass the trajectory to a controller to move the robot.
    import irsim
    from irsim.lib.path_planners import AStarPlanner
    
    env = irsim.make("path_planning.yaml")
    
    # 1. Build map
    env_map = env.get_map(resolution=0.2)
    
    # 2. Create planner
    planner = AStarPlanner(env_map)
    
    # 3. Plan
    robot_state = env.get_robot_state()
    goal_xy = env.get_robot_info().goal[:2, 0].tolist()
    trajectory = planner.planning(robot_state, goal_xy)
    
    # 4. Draw
    if trajectory is not None:
        env.draw_trajectory(trajectory, traj_type="r-")
  4. Configure the IR-SIM environment using YAML

    main

    IR-SIM uses a YAML configuration file to initialize the simulation environment. This file allows you to define and customize parameters for:

    • The World: Simulation and visualization settings.
    • Obstacles: Properties and placement of objects in the environment.
    • The Robot: Physical characteristics and behavior.

    By modifying these parameters in the YAML file, you can customize the entire scenario and the behavior of objects within the simulation.

  5. How multiple environments work in IR-SIM

    main

    IR-SIM allows you to create and run multiple environment instances simultaneously. Each instance is completely isolated, meaning they maintain their own independent:

    • World parameters: Settings like control_mode, collision_mode, and step_time.
    • Simulation state: Current time, step count, and the list of objects.
    • Simulation time: Stepping one environment does not affect the clock of another.
    • Objects and spatial data: Each environment manages its own objects list and GeometryTree for collision detection.

    This isolation makes IR-SIM suitable for parallel simulations, comparative studies between different configurations, and reinforcement learning training loops.

    import irsim
    
    # Create two separate environments
    env1 = irsim.make("scenario_a.yaml")
    env2 = irsim.make("scenario_b.yaml")
    
    # Each environment has its own state
    print(f"Env1 robots: {env1.robot_number}")
    print(f"Env2 robots: {env2.robot_number}")
  6. How to approach the IR-SIM API

    main

    When working with IR-SIM, your choice of API depends on whether you are a user of the simulator or a developer extending it:

    • For most users (Running Simulations): Start with the high-level entry points like irsim.make and the EnvBase class to create, run, and inspect environments.
    • For developers (Extending IR-SIM): Use the lower-level modules to add new functionality, such as custom kinematics, geometry, or sensors.
  7. Configure and use FMCW LiDAR sensors

    main

    The fmcw_lidar2d sensor provides standard LiDAR geometry plus a radial_velocity measurement for each beam, useful for detecting dynamic obstacles via Doppler measurements.

    Key FMCW Parameters:

    • motion_compensate: Boolean indicating whether to remove ego-motion from the measured radial velocity.
    • velocity_noise_std: Standard deviation of Gaussian noise applied to radial_velocity.

    Data Access: When calling env.get_lidar_scan(), the returned object contains:

    • radial_velocity: Scalar radial velocity for each beam.
    • valid: Boolean array indicating if a beam has a valid return within range_max.
    • ranges: The distance measurements.

    Visualization: Use the plot: sub-dictionary to control colorization:

    • velocity_color: Boolean to enable colorizing beams by radial velocity.
    • velocity_color_max: The velocity magnitude at which the color saturates.
    import irsim
    
    env = irsim.make("fmcw_lidar_world.yaml")
    
    for step in range(120):
        env.step()
    
        scan = env.get_lidar_scan()
        valid_count = int(scan["valid"].sum())
        valid_indices = scan["valid"].nonzero()[0]
        if len(valid_indices) > 0:
            # Find the beam with the highest absolute radial velocity
            beam_idx = max(valid_indices, key=lambda idx: abs(scan["radial_velocity"][idx]))
            print(
                f"step={step:03d} valid_beams={valid_count:03d} "
                f"beam={beam_idx:03d} range={scan['ranges'][beam_idx]:.3f} "
                f"radial_velocity={scan['radial_velocity'][beam_idx]:.3f}"
            )
    
        env.render(0.05, mode="all")
    
    env.end(3)
  8. How RVO handles line obstacles

    main

    RVO behavior automatically incorporates linestring-shaped obstacles into its velocity obstacle calculations. Each line segment between consecutive vertices in a linestring object is treated as a static velocity obstacle. This allows agents to navigate around walls or complex polylines without additional configuration. This works for both omni and diff kinematics.

    robot:
      - number: 6
        kinematics: {name: 'diff'}
        behavior: {name: 'rvo'}
    
    obstacle:
      - shape: {name: 'linestring', vertices: [[2, 2], [2, 8], [8, 8]]}
  9. The IR-SIM mental model and simulation loop

    main

    IR-SIM is a declarative simulator where you describe a scene in YAML and instantiate it using irsim.make(). The simulation follows a specific lifecycle managed by the Environment (EnvBase).

    To run a simulation, you implement a step → render → done loop:

    1. step(): Advances the simulation by one time step. This resolves actions/behaviors, integrates motion, refreshes sensors, and updates collision/arrival status.
    2. render(): Draws the current state using Matplotlib.
    3. done(): Checks if a terminal condition (like a collision or all robots reaching goals) has been met.
    4. end(): Closes the window and releases resources.

    Other lifecycle methods include reset() (restore initial states) and reload() (rebuild from YAML).

    import irsim
    
    # Create the environment from a YAML file
    env = irsim.make("scene.yaml")
    
    # The core simulation loop
    while not env.done():
        env.step()
        env.render()
    
    env.end()
  10. How Behaviors and Sensors work

    main

    Behaviors

    Behaviors map an object's state (and potentially its neighbors' states) to a velocity command every step.

    • Built-in behaviors: dash (head to goal), rvo (reciprocal velocity obstacles), sfm (social force model), and orca (optimal reciprocal collision avoidance).
    • Custom control: You can bypass behaviors by passing manual commands to env.step(action) or by registering a custom behavior.

    Sensors

    Sensors are attached to objects and provide measurements (like 2D LiDAR, FMCW LiDAR, or field-of-view detection).

    • Update Timing: Sensors are refreshed after objects move during the step() call, ensuring readings reflect the most recent world state.
  11. How the Environment (EnvBase) works

    main

    The Environment (EnvBase) is the primary interface for interacting with the simulation. It acts as a container that owns the World and all Objects (robots and obstacles).

    Key responsibilities of the Environment:

    • Parsing: Using make() to build the world and objects from a YAML scenario.
    • Physics & Integration: Advancing object states based on kinematics and actions.
    • Sensor Management: Refreshing sensor readings after object movement.
    • Collision Detection: Managing global collision status using Shapely geometry.
    • Lifecycle Control: Providing step(), render(), done(), reset(), reload(), and end() methods.
  12. Configure robot and obstacle objects

    main

    In IR-SIM, both robot and obstacle entities are configured as objects using a shared set of parameters. While they share many properties, their default values (like color or role) differ. You can define the number of objects, their kinematics, shapes, initial states, goals, and behaviors using YAML configuration.

    robot:
      - name: "robot_1"
        number: 1
        kinematics: {name: 'diff'}
        state: [1.0, 1.0, 0.0]
        goal: [10.0, 10.0, 0.0]
    
    obstacle:
      - name: "wall"
        shape: {name: 'rectangle'}
        static: true