How to add libraries to ROS2 Python Package an easy guide

Introduction

When developing a project, we often fall short on features. Sometimes there are features that we need for example, 2D mapping of the environment, to progress in our project of autonomous robots. Implementing those features from scratch takes a ton of time. In those cases, we have libraries that already have those features, and we only need to understand them. Let’s clear up our thoughts about what we understand and what our learning outcomes will be after this article on the ROS2 Python package external modules.

There are some amazing Python libraries that you can integrate into your projects. But before that, let’sclarifyr the concepts of integerating libraries, modules.

Starting Point

No understanding of

  • ROS2 Python Packages and Modules
  • ROS2 Package Structure
  • Creating Customized Modules

Learning outcomes

Easily able to

  • Creating Custom Modules into ROS2 Packages
  • Install External Libraries to your ROS2 Packages
  • Concept clearning of Python Package, Library and module

Python Libraries Concept and its Terminologies

When I started working on python packages, there were some python jargons that were disturbing me. So lets first clear our concept about these python terminologies

Python Module

It is a single file containing Python code that defines functions, classes, and variables. It allows you to organise your code into reusable units. On the right, we have an example of a simple Python module namedmy_module.py:

To use this module in another Python file, you would import it like this:


# my_module.py

def greet(name):
    return f"Hello, {name}!"

def add(a, b):
    return a + b
import my_module

print(my_module.greet("Robotisim"))
print(my_module.add(9, 6))
ros2 python nodes

Python Library

It is a collection of modules that provide specific functionality. Libraries can be built-in (provided with Python) or external (installed separately).

Here’s an example of using the built-in math library:

Externally built libraries can be used after installation through

pip install <name> # example numpy

import math
import numpy

print(math.sqrt(16))  # Output: 4.0
print(math.pi)         # Output: 3.141592653589793

Python Package

It is a directory that contains one or more modules. It also includes a special file called __init__.py to indicate that the directory should be treated as a package. Here’s an example of a simple package structure on the right.

In this example, module1.py and module2.py are Python modules, and__init__.py can be empty or contain initialization code for the package. To use this package, you would import its modules, as mentioned on the right.

my_package/
├── __init__.py
├── module1.py
└── module2.py
from my_package import module1, module2

print(module1.some_function())
print(module2.some_other_function())

Lets summarize python concepts

  • Python code is typically distributed and executed in its source form(code or script), without an explicit compilation step.
  • In Python, packages are not compiled into a binary format like libraries in some other languages, such as C++.
  • We bundle Python code into a form that is more easily distributable, using tools likedistutils.

This is where ros2 python packages comes in.

ROS2 Python Package Structure

When we create a python package using ROS2 command, we have couple of things to understand

  • ros2 pkg createThis is the command to create a new ROS2 package.
  • --build-type ament_python : Specifies that the package will be built using the Ament build system for Python packages.
  • --node-name vision_start : Specifies the name of the node that will be created in the package.
  • vision_pkg: specifies the name of the package.
ros2 pkg create --build-type ament_python --node-name vision_start vision_pkg

When we execute this command, we see a package with a node automatically created with a fixed structure. This below structure is produced mainly for keeping standards fixed for compatibility between tools and ease of maintenance.

  • For example : the convention of having the package name match the directory name inside the src directory is not a strict requirement, but it is a recommended best practice.
vision_pkg/
├── package.xml
├── CMakeLists.txt
├── setup.py
├── src/
    └── vision_pkg/
        ├── __init__.py
        └── vision_start.py

Creating and Utilising Custom Module

Lets start by understanding example directory tree for a Python package with custom modules for Object detection and Object tracking

vision_pkg/
├── package.xml
├── setup.py
└── src/
    └── vision_pkg/
        ├── __init__.py
        ├── vision_start.py
        ├── obstacle_detection/
        │   ├── __init__.py
        │   └── detector.py
        └── object_tracking/
            ├── __init__.py
            └── tracker.py
#!/usr/bin/env python3

import rclpy
from vision_pkg.obstacle_detection.detector import detect_obstacles
from vision_pkg.object_tracking.tracker import track_objects

class VisionNode(Node):
    def __init__(self):
        super().__init__('vision_node')
        self.get_logger().info('Vision node initialized')

    def modules(self, image,objects):
        obstacles = detect_obstacles(image)
        tracks = track_objects(objects)
...

That is not it; you need to mention in the the setup.py file any library you are using for the feature you have implemented,, for example:

    install_requires=[
        'setuptools',
        'opencv',        # Assuming that we using OpenCV for obstacle detection
        'kalmanfilter',  # Assuming that we using Kalman filter for object tracking
        'rclpy',
    ],

Similar questions to answer?

  1. How do I add external Python libraries to a ROS 2 Python package?
    • Answer: You can add external Python libraries to a ROS 2 Python package by including them in the install_requires list in your setup.py file. For example, if you’re using numpy for array operations, you can add 'numpy' to the install_requires list.
  2. Can I use custom Python modules in my ROS 2 Python package?
    • Answer: Yes, you can use custom Python modules in your ROS 2 Python package. Simply create your custom modules in a directory within your package, and import them in your Python nodes as needed.
  3. How do I ensure that my ROS 2 Python package includes all necessary dependencies?
    • Answer: To ensure that your ROS 2 Python package includes all necessary dependencies, list them in the install_requires list in your setup.py file. When you build and install your package, these dependencies will be installed automatically.

ROS2 Python package Libraries Quiz

Leave a Comment

Your email address will not be published. Required fields are marked *

Review Your Cart
0
Add Coupon Code
Subtotal
Total Installment Payments
Bundle Discount

 
Scroll to Top