Convert Figma logo to code with AI

AtsushiSakai logoPythonRobotics

Python sample codes for robotics algorithms.

23,098
6,510
23,098
16

Top Related Projects

ROS Navigation stack. Code for finding where the robot is and how it can get somewhere else.

Universal grid map library for mobile robotic mapping

12,540

Bullet Physics SDK: real-time collision detection and multi-physics simulation for VR, games, visual effects, robotics, machine learning etc.

3,243

Model-based design and verification for robotics.

Quick Overview

PythonRobotics is a comprehensive collection of robotics algorithms implemented in Python. It covers various aspects of robotics, including path planning, localization, mapping, and control. The project aims to provide clear, educational implementations of common robotics algorithms for students, researchers, and hobbyists.

Pros

  • Extensive collection of robotics algorithms in one repository
  • Well-documented code with explanations and visualizations
  • Implementations are designed to be educational and easy to understand
  • Active community and regular updates

Cons

  • Not optimized for production use or real-time applications
  • Some implementations may be simplified versions of more complex algorithms
  • Requires additional libraries and dependencies for full functionality
  • May not cover the most cutting-edge or specialized algorithms in the field

Code Examples

  1. Path Planning with RRT (Rapidly-exploring Random Tree):
import numpy as np
from PythonRobotics.PathPlanning.RRT import rrt as RRT

# Define start and goal positions
start = np.array([0, 0])
goal = np.array([6, 10])

# Create obstacle list
obstacleList = [(5, 5, 1), (3, 6, 2), (3, 8, 2), (3, 10, 2), (7, 5, 2)]

# Run RRT path planning
path = RRT.rrt_planning(start, goal, obstacleList, [-2, 15], [-2, 15])
  1. Localization with Extended Kalman Filter:
import numpy as np
from PythonRobotics.Localization import extended_kalman_filter as ekf

# Initialize EKF
ekf_filter = ekf.ExtendedKalmanFilter()

# Simulate robot movement and sensor measurements
x_true = np.array([0, 0, 0]).reshape(3, 1)
u = np.array([1.0, 0.1]).reshape(2, 1)
z = np.array([1.0, 0.1]).reshape(2, 1)

# Update EKF
x_est = ekf_filter.estimate(x_true, u, z)
  1. SLAM with FastSLAM:
from PythonRobotics.SLAM import FastSLAM1 as fs

# Initialize FastSLAM
slam = fs.FastSLAM1()

# Simulate robot movement and landmark observations
u = [1.0, 0.1]
z = [[1.0, 0.1], [2.0, -0.1]]

# Update SLAM estimate
slam.update(u, z)

Getting Started

To get started with PythonRobotics:

  1. Clone the repository:

    git clone https://github.com/AtsushiSakai/PythonRobotics.git
    
  2. Install required dependencies:

    pip install -r requirements.txt
    
  3. Run a sample algorithm:

    from PythonRobotics.PathPlanning.RRT import rrt as RRT
    import matplotlib.pyplot as plt
    
    start = [0, 0]
    goal = [6, 10]
    obstacleList = [(5, 5, 1), (3, 6, 2), (3, 8, 2), (3, 10, 2), (7, 5, 2)]
    
    path = RRT.rrt_planning(start, goal, obstacleList, [-2, 15], [-2, 15])
    RRT.plot_result(path, obstacleList)
    plt.show()
    

This will run the RRT path planning algorithm and display the results.

Competitor Comparisons

ROS Navigation stack. Code for finding where the robot is and how it can get somewhere else.

Pros of navigation

  • Integrated with ROS ecosystem, allowing seamless integration with other ROS packages
  • Provides a complete navigation stack with ready-to-use components
  • Actively maintained and widely used in industry and research

Cons of navigation

  • Steeper learning curve due to ROS framework complexity
  • Less focused on educational aspects and algorithm explanations
  • Requires ROS installation and setup

Code Comparison

PythonRobotics:

def dwa_control(x, config, goal, ob):
    # Dynamic Window Approach control
    dw = calc_dynamic_window(x, config)
    u, trajectory = calc_control_and_trajectory(x, dw, config, goal, ob)
    return u, trajectory

navigation:

bool DWAPlanner::computeVelocityCommands(
    const geometry_msgs::PoseStamped& pose,
    const geometry_msgs::TwistStamped& velocity,
    geometry_msgs::TwistStamped& cmd_vel,
    std::string& message)
{
  // ... (implementation details)
}

PythonRobotics focuses on clear, educational Python implementations, while navigation provides production-ready C++ code integrated with ROS.

Universal grid map library for mobile robotic mapping

Pros of grid_map

  • Specialized for 2D grid map operations in robotics
  • Efficient C++ implementation with ROS integration
  • Comprehensive documentation and examples

Cons of grid_map

  • Limited to grid map operations, less versatile than PythonRobotics
  • Steeper learning curve due to C++ implementation
  • Requires ROS environment for full functionality

Code Comparison

grid_map example (C++):

GridMap map({"elevation"});
map.setGeometry(Length(1.0, 1.0), 0.1);
map["elevation"].setConstant(0.0);

PythonRobotics example (Python):

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1)
y = np.sin(x)
plt.plot(x, y)
plt.show()

The grid_map code demonstrates creating and initializing a grid map, while the PythonRobotics code shows a simple plotting example. PythonRobotics offers a wider range of robotics algorithms in Python, making it more accessible for beginners and rapid prototyping. grid_map, on the other hand, provides specialized tools for grid map operations with better performance but requires more setup and C++ knowledge.

12,540

Bullet Physics SDK: real-time collision detection and multi-physics simulation for VR, games, visual effects, robotics, machine learning etc.

Pros of Bullet3

  • More comprehensive physics simulation, including rigid body dynamics, soft body dynamics, and fluid simulation
  • Highly optimized C++ implementation for better performance in real-time applications
  • Widely used in game development and robotics industries, with extensive documentation and community support

Cons of Bullet3

  • Steeper learning curve due to its complexity and C++ implementation
  • Less focused on specific robotics algorithms compared to PythonRobotics
  • Requires more setup and configuration for robotics-specific applications

Code Comparison

Bullet3 (C++):

btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();
btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration);
btBroadphaseInterface* overlappingPairCache = new btDbvtBroadphase();
btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver;
btDiscreteDynamicsWorld* dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration);

PythonRobotics (Python):

import numpy as np
from scipy.spatial.transform import Rotation as Rot

def motion_model(x, u, dt):
    F = np.array([[1.0, 0, 0, 0],
                  [0, 1.0, 0, 0],
                  [0, 0, 1.0, 0],
                  [0, 0, 0, 0]])
    B = np.array([[dt * math.cos(x[2, 0]), 0],
                  [dt * math.sin(x[2, 0]), 0],
                  [0.0, dt],
                  [1.0, 0.0]])
    x = F @ x + B @ u
    return x
3,243

Model-based design and verification for robotics.

Pros of Drake

  • More comprehensive and feature-rich, offering a wide range of robotics and control system tools
  • Better performance due to C++ implementation, suitable for large-scale simulations
  • Extensive documentation and active community support

Cons of Drake

  • Steeper learning curve due to its complexity and C++ codebase
  • Requires more setup and dependencies compared to the Python-based alternative
  • May be overkill for simple robotics projects or educational purposes

Code Comparison

Drake (C++):

#include <drake/systems/framework/diagram_builder.h>
#include <drake/systems/primitives/integrator.h>

int main() {
  drake::systems::DiagramBuilder<double> builder;
  auto integrator = builder.AddSystem<drake::systems::Integrator<double>>(1);
}

PythonRobotics (Python):

import numpy as np
from scipy.integrate import odeint

def model(y, t):
    return np.array([1])

t = np.linspace(0, 10, 100)
y = odeint(model, [0], t)

Both repositories offer valuable resources for robotics enthusiasts and professionals. Drake provides a more comprehensive and performant solution, suitable for complex projects and industrial applications. PythonRobotics, on the other hand, offers a more accessible and educational approach, making it ideal for learning and prototyping robotics algorithms in Python.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

header pic

PythonRobotics

GitHub_Action_Linux_CI GitHub_Action_MacOS_CI GitHub_Action_Windows_CI Build status codecov

Python codes for robotics algorithm.

Table of Contents

What is this?

This is a Python code collection of robotics algorithms.

Features:

  1. Easy to read for understanding each algorithm's basic idea.

  2. Widely used and practical algorithms are selected.

  3. Minimum dependency.

See this paper for more details:

Requirements

For running each sample code:

For development:

Documentation

This README only shows some examples of this project.

If you are interested in other examples or mathematical backgrounds of each algorithm,

You can check the full documentation online: Welcome to PythonRobotics’s documentation! — PythonRobotics documentation

All animation gifs are stored here: AtsushiSakai/PythonRoboticsGifs: Animation gifs of PythonRobotics

How to use

  1. Clone this repo.

    git clone https://github.com/AtsushiSakai/PythonRobotics.git
    
  2. Install the required libraries.

  • using conda :

    conda env create -f requirements/environment.yml
    
  • using pip :

    pip install -r requirements/requirements.txt
    
  1. Execute python script in each directory.

  2. Add star to this repo if you like it :smiley:.

Localization

Extended Kalman Filter localization

EKF pic

Ref:

Particle filter localization

2

This is a sensor fusion localization with Particle Filter(PF).

The blue line is true trajectory, the black line is dead reckoning trajectory,

and the red line is an estimated trajectory with PF.

It is assumed that the robot can measure a distance from landmarks (RFID).

These measurements are used for PF localization.

Ref:

Histogram filter localization

3

This is a 2D localization example with Histogram filter.

The red cross is true position, black points are RFID positions.

The blue grid shows a position probability of histogram filter.

In this simulation, x,y are unknown, yaw is known.

The filter integrates speed input and range observations from RFID for localization.

Initial position is not needed.

Ref:

Mapping

Gaussian grid map

This is a 2D Gaussian grid mapping example.

2

Ray casting grid map

This is a 2D ray casting grid mapping example.

2

Lidar to grid map

This example shows how to convert a 2D range measurement to a grid map.

2

k-means object clustering

This is a 2D object clustering with k-means algorithm.

2

Rectangle fitting

This is a 2D rectangle fitting for vehicle detection.

2

SLAM

Simultaneous Localization and Mapping(SLAM) examples

Iterative Closest Point (ICP) Matching

This is a 2D ICP matching example with singular value decomposition.

It can calculate a rotation matrix, and a translation vector between points and points.

3

Ref:

FastSLAM 1.0

This is a feature based SLAM example using FastSLAM 1.0.

The blue line is ground truth, the black line is dead reckoning, the red line is the estimated trajectory with FastSLAM.

The red points are particles of FastSLAM.

Black points are landmarks, blue crosses are estimated landmark positions by FastSLAM.

3

Ref:

Path Planning

Dynamic Window Approach

This is a 2D navigation sample code with Dynamic Window Approach.

2

Grid based search

Dijkstra algorithm

This is a 2D grid based the shortest path planning with Dijkstra's algorithm.

PythonRobotics/figure_1.png at master · AtsushiSakai/PythonRobotics

In the animation, cyan points are searched nodes.

A* algorithm

This is a 2D grid based the shortest path planning with A star algorithm.

PythonRobotics/figure_1.png at master · AtsushiSakai/PythonRobotics

In the animation, cyan points are searched nodes.

Its heuristic is 2D Euclid distance.

D* algorithm

This is a 2D grid based the shortest path planning with D star algorithm.

figure at master · nirnayroy/intelligentrobotics

The animation shows a robot finding its path avoiding an obstacle using the D* search algorithm.

Ref:

D* Lite algorithm

This algorithm finds the shortest path between two points while rerouting when obstacles are discovered. It has been implemented here for a 2D grid.

D* Lite

The animation shows a robot finding its path and rerouting to avoid obstacles as they are discovered using the D* Lite search algorithm.

Refs:

Potential Field algorithm

This is a 2D grid based path planning with Potential Field algorithm.

PotentialField

In the animation, the blue heat map shows potential value on each grid.

Ref:

Grid based coverage path planning

This is a 2D grid based coverage path planning simulation.

PotentialField

State Lattice Planning

This script is a path planning code with state lattice planning.

This code uses the model predictive trajectory generator to solve boundary problem.

Ref:

Biased polar sampling

PythonRobotics/figure_1.png at master · AtsushiSakai/PythonRobotics

Lane sampling

PythonRobotics/figure_1.png at master · AtsushiSakai/PythonRobotics

Probabilistic Road-Map (PRM) planning

PRM

This PRM planner uses Dijkstra method for graph search.

In the animation, blue points are sampled points,

Cyan crosses means searched points with Dijkstra method,

The red line is the final path of PRM.

Ref:

  

Rapidly-Exploring Random Trees (RRT)

RRT*

PythonRobotics/figure_1.png at master · AtsushiSakai/PythonRobotics

This is a path planning code with RRT*

Black circles are obstacles, green line is a searched tree, red crosses are start and goal positions.

Ref:

RRT* with reeds-shepp path

Robotics/animation.gif at master · AtsushiSakai/PythonRobotics

Path planning for a car robot with RRT* and reeds shepp path planner.

LQR-RRT*

This is a path planning simulation with LQR-RRT*.

A double integrator motion model is used for LQR local planner.

LQR_RRT

Ref:

Quintic polynomials planning

Motion planning with quintic polynomials.

2

It can calculate a 2D path, velocity, and acceleration profile based on quintic polynomials.

Ref:

Reeds Shepp planning

A sample code with Reeds Shepp path planning.

RSPlanning

Ref:

LQR based path planning

A sample code using LQR based path planning for double integrator model.

RSPlanning

Optimal Trajectory in a Frenet Frame

3

This is optimal trajectory generation in a Frenet Frame.

The cyan line is the target course and black crosses are obstacles.

The red line is the predicted path.

Ref:

Path Tracking

move to a pose control

This is a simulation of moving to a pose control

2

Ref:

Stanley control

Path tracking simulation with Stanley steering control and PID speed control.

2

Ref:

Rear wheel feedback control

Path tracking simulation with rear wheel feedback steering control and PID speed control.

PythonRobotics/figure_1.png at master · AtsushiSakai/PythonRobotics

Ref:

Linear–quadratic regulator (LQR) speed and steering control

Path tracking simulation with LQR speed and steering control.

3

Ref:

Model predictive speed and steering control

Path tracking simulation with iterative linear model predictive speed and steering control.

MPC pic

Ref:

Nonlinear Model predictive control with C-GMRES

A motion planning and path tracking simulation with NMPC of C-GMRES

3

Ref:

Arm Navigation

N joint arm to point control

N joint arm to a point control simulation.

This is an interactive simulation.

You can set the goal position of the end effector with left-click on the plotting area.

3

In this simulation N = 10, however, you can change it.

Arm navigation with obstacle avoidance

Arm navigation with obstacle avoidance simulation.

3

Aerial Navigation

drone 3d trajectory following

This is a 3d trajectory following simulation for a quadrotor.

3

rocket powered landing

This is a 3d trajectory generation simulation for a rocket powered landing.

3

Ref:

Bipedal

bipedal planner with inverted pendulum

This is a bipedal planner for modifying footsteps for an inverted pendulum.

You can set the footsteps, and the planner will modify those automatically.

3

License

MIT

Use-case

If this project helps your robotics project, please let me know with creating an issue.

Your robot's video, which is using PythonRobotics, is very welcome!!

This is a list of user's comment and references:users_comments

Contribution

Any contribution is welcome!!

Please check this document:How To Contribute — PythonRobotics documentation

Citing

If you use this project's code for your academic work, we encourage you to cite our papers

If you use this project's code in industry, we'd love to hear from you as well; feel free to reach out to the developers directly.

Supporting this project

If you or your company would like to support this project, please consider:

If you would like to support us in some other way, please contact with creating an issue.

Sponsors

JetBrains

They are providing a free license of their IDEs for this OSS development.

1Password

They are providing a free license of their 1Password team license for this OSS project.

Authors