pybotics

repository·master·Indexed 18 days ago

https://github.com/engnadeau/pybotics

A Python toolbox for robotics focusing on kinematics, dynamics, trajectory generation, and calibration using the Modified Denavit–Hartenberg convention. Version 2.0.1 provides tools for Forward and Inverse Kinematics, joint torque calculation, and robot calibration via the OptimizationHandler.

Tokens
11.8K
Snippets
55
Records
59
Agent score
55%

What's inside pybotics

  1. Overview of Pybotics

    master

    Pybotics is an open-source Python toolbox designed for robot kinematics and calibration. It provides a concise interface for simulating and evaluating robotic concepts including kinematics, dynamics, trajectory generation, and calibration.

    Key technical characteristics:

    • Kinematic Convention: Specifically designed for the Modified Denavit–Hartenberg (MDH) parameters convention, using four geometric parameters to define reference frames along robot links.
    • Computational Foundation: Leverages NumPy for computational efficiency and uses array-based notation for modeling.
    • Optimization & ML Integration: The vectorized modeling approach allows for easy integration with SciPy optimization algorithms and Scikit-learn for machine learning applications.
  2. Install Pybotics

    master

    You can install pybotics using standard Python package managers depending on your environment setup.

    # Using pip
    pip install pybotics
    
    # Using pip3
    pip3 install pybotics
    
    # Using pipenv
    pipenv install pybotics
    
    # Using poetry
    poetry add pybotics
  3. Develop in an isolated Docker environment

    master

    Docker can be used to test the package in an isolated environment, which is useful for debugging issues across different Python versions. Use the following steps to launch a container, install dependencies, and run tests.

    # launch container attached to current directory
    docker run -v $(pwd):/$(basename $(pwd)) -w /$(basename $(pwd)) -it python:3 bash
    
    # install deps
    pip install poetry
    poetry install
    
    # run tests
    make test
  4. Run tests and code formatting

    master

    The project uses a Makefile to manage common development tasks. Use these commands to maintain code quality:

    # auto-format code
    make format
    
    # perform all static tests
    make lint
    
    # run all python tests
    make test
  5. Explore Pybotics Applications and Examples

    master

    Pybotics includes several practical examples to demonstrate its capabilities. You can find these in the repository's examples/ directory:

    • Basic Usage: examples/basic_usage.py
    • Kinematics: examples/kinematics.ipynb
    • Calibration: examples/calibration.ipynb
    • Trajectory and Path Planning: examples/trajectory_generation.ipynb
    • Machine Learning: examples/machine_learning.ipynb
    • Dynamics: examples/dynamics.ipynb
  6. Use KinematicChain as a base class

    master

    KinematicChain is an abstract base class representing an assembly of rigid bodies connected by joints. It provides a mathematical model for a mechanical system's motion.

    Key properties and methods available to all kinematic chains include:

    • ndof: Returns the number of degrees of freedom (equivalent to len(chain)).
    • num_parameters: Returns the total number of parameters across all links.
    • to_json(): Encodes the model as a JSON string.
    • transforms(q=None): Generates a sequence of spatial transforms (4x4 matrices) representing the chain's position. If q is not provided, it defaults to zero positions.
    • matrix: A property to get or set the link parameters as a 2D NumPy array (Rows = links, Columns = parameters).
    • vector: A property to get or set the link parameters as a flattened 1D NumPy array.
    • links: A property to access the sequence of Link objects in the chain.
  7. Define robot links using the Link base class

    master

    The Link class is an abstract base class used to represent connected joints that allow relative motion between neighboring links. It defines the interface for kinematic modeling.

    To use Link, you must implement a subclass that provides implementations for:

    • displace(q: float): Generates a new link state vector given a displacement q.
    • transform(q: float = 0): Generates a 4x4 transformation matrix.
    • vector: A property returning the vectorized kinematic chain as a NumPy array.
    • size: A property returning the number of parameters in the link.

    Link also supports:

    • to_json(): Encodes the link model as a JSON string.
    • len(link): Returns the number of parameters via the size property.
  8. Generate a segmented linear trajectory via joint-space interpolation

    master

    Because joint-space motion is non-linear in Cartesian-space, a single joint-space segment between two points will deviate from a straight line. To approximate linear motion, you can subdivide the trajectory into smaller segments.

    One approach is to:

    1. Calculate the midpoint in Cartesian space.
    2. Create a new pose at that midpoint.
    3. Insert this pose into your sequence to create a segmented trajectory.
    # 1. Find the Cartesian midpoint
    mid_cartesian_point = np.mean([poses[1, :-1, -1], poses[0, :-1, -1]], axis=0)
    
    # 2. Create a new pose at that midpoint
    mid_pose = poses[0].copy()
    mid_pose[:-1, -1] = mid_cartesian_point
    
    # 3. Insert the midpoint into the pose sequence to create segments
    segmented_poses = np.insert(arr=poses, obj=1, values=mid_pose, axis=0)
    
    # 4. Compute joints for the new segmented trajectory
    joints = [robot.ik(p, q=start_end_joints[0]) for p in segmented_poses]
  9. Perform robot calibration using OptimizationHandler

    master

    Robot calibration involves optimizing the robot's kinematic parameters to match measured data. The workflow follows these steps:

    1. Initialize the handler: Create an OptimizationHandler with your nominal robot.
    2. Define a parameter mask: Create a boolean mask (the same shape as the kinematic chain matrix) to specify which parameters (e.g., theta, d, a, alpha) should be optimized. For example, to solve only for theta offsets, set the third column of the mask to True.
    3. Apply the mask: Flatten the mask and assign it to handler.kinematic_chain_mask.
    4. Optimize: Use a solver like scipy.optimize.least_squares with pybotics.optimization.optimize_accuracy as the objective function. Use handler.generate_optimization_vector() to provide the initial guess x0.

    Note: It is best practice to split your measured data into training and validation sets to prevent overfitting.

    from pybotics.optimization import OptimizationHandler, optimize_accuracy
    from scipy.optimize import least_squares
    import numpy as np
    
    # 1. Initialize
    handler = OptimizationHandler(nominal_robot)
    
    # 2. & 3. Set mask to solve for theta parameters (column index 2)
    kc_mask_matrix = np.zeros_like(nominal_robot.kinematic_chain.matrix, dtype=bool)
    kc_mask_matrix[:, 2] = True
    handler.kinematic_chain_mask = kc_mask_matrix.ravel()
    
    # 4. Run optimization
    result = least_squares(
        fun=optimize_accuracy,
        x0=handler.generate_optimization_vector(),
        args=(handler, train_joints, train_positions),
        verbose=2
    )
    
    # The calibrated model is accessible via:
    calibrated_robot = handler.robot
  10. Initialize a Robot Model

    master

    To work with robot kinematics, you must first initialize a Robot instance. A robot model is defined as a kinematic chain using parameters (such as Modified DH parameters). You can create a robot from a predefined model using Robot.from_parameters().

    from pybotics.robot import Robot
    from pybotics.predefined_models import ur10
    
    robot = Robot.from_parameters(ur10())