<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mohammad Shoaib on Medium]]></title>
        <description><![CDATA[Stories by Mohammad Shoaib on Medium]]></description>
        <link>https://medium.com/@shoaib6174?source=rss-9482f5c0f21a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R5aNmSkWBX05RsFHzudYXQ.png</url>
            <title>Stories by Mohammad Shoaib on Medium</title>
            <link>https://medium.com/@shoaib6174?source=rss-9482f5c0f21a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:20:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shoaib6174/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Where a Robot Lives in Space: The URDF Mental Model I Wish I Had on Day One]]></title>
            <link>https://medium.com/@shoaib6174/where-a-robot-lives-in-space-the-urdf-mental-model-i-wish-i-had-on-day-one-537aac323d1e?source=rss-9482f5c0f21a------2</link>
            <guid isPermaLink="false">https://medium.com/p/537aac323d1e</guid>
            <category><![CDATA[ros2]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Mohammad Shoaib]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 11:23:29 GMT</pubDate>
            <atom:updated>2026-06-17T11:23:29.717Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Frames, origins, and axes sound simple until you try to describe a robot with them. Here is the progressive story that finally made URDF click for me.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W092O-KA3Nq4Dek7q2rFrA.png" /></figure><p>I thought I understood coordinates.</p><p>I had used x, y, and z in math class, in comuter vision, in CAD tools. So when I opened my first URDF file and saw origin xyz=&quot;0 0.15 0.05&quot;, I assumed it meant &quot;this thing is at position (0, 0.15, 0.05).&quot;</p><p>That assumption cost me one hour of debugging a wheel that rendered inside the chassis.</p><p>The problem was not the math. The problem was that URDF uses ordinary words — <em>frame</em>, <em>origin</em>, <em>axis</em>, <em>link</em>, <em>joint</em> — with meanings that feel familiar but are narrowly technical. Until you map those words precisely, URDF feels like magic. Once you map them, it becomes mechanical.</p><p>This post is the map I wish I had on day one.</p><h3>The Real Question URDF Answers</h3><p>Forget XML for a moment. Imagine a box on a table. I ask you: <em>“Where is the box?”</em></p><p>You cannot answer without choosing a reference. “Two meters forward” only makes sense if we agree on a starting point and a direction. In robotics, that agreement is called a <strong>frame</strong>.</p><p>A frame is three things together:</p><ol><li>An <strong>origin</strong> — the zero point.</li><li>Three perpendicular axes — <strong>X</strong>, <strong>Y</strong>, <strong>Z</strong> — that define forward, left, and up.</li><li>A body those axes are attached to.</li></ol><p>The third point is the one I missed. A frame is not a coordinate system floating in space. It is a tiny ruler glued to a specific object. If the object moves, the frame moves. If the object rotates, the frame rotates.</p><p>This is why the word “frame” is so easy to misunderstand. In everyday English, a frame is a border. In robotics, a frame is a body with a ruler attached.</p><h3>A Robot Is a Family of Frames</h3><p>A mobile robot is not one solid block. It is a chassis, two drive wheels, a caster, a LiDAR, a camera, and an IMU. Each of those pieces is a rigid body, and each rigid body gets its own frame.</p><p>For the robot I built while learning this, the frames looked like this:</p><ul><li>base_link — center of the chassis, on the floor.</li><li>left_wheel_link — center of the left wheel.</li><li>right_wheel_link — center of the right wheel.</li><li>caster_wheel_link — center of the caster sphere.</li><li>laser_frame — center of the LiDAR sensor.</li><li>camera_frame — center of the camera.</li><li>imu_frame — center of the IMU.</li></ul><p>URDF’s entire job is to tell ROS where each of these frames is relative to the others. That is it. Every tag in URDF serves that one purpose.</p><h3>The Two Kinds of Origin</h3><p>Here is where I got stuck. The word <strong>origin</strong> appears in two places in URDF, and they mean different things.</p><h3>Origin in a joint</h3><p>A joint connects two links. Its origin says: <em>&quot;The child frame lives here, measured from the parent frame.&quot;</em></p><pre>&lt;joint name=&quot;left_wheel_joint&quot; type=&quot;continuous&quot;&gt;<br>  &lt;parent link=&quot;base_link&quot;/&gt;<br>  &lt;child link=&quot;left_wheel_link&quot;/&gt;<br>  &lt;origin xyz=&quot;0 0.15 0.05&quot;/&gt;<br>&lt;/joint&gt;</pre><p>This says: start at base_link, walk 0 m forward, 0.15 m left, and 0.05 m up. That is where the left wheel&#39;s frame is.</p><p>The ruler here is the <strong>parent’s frame</strong>.</p><h3>Origin in a link</h3><p>A link describes a rigid body. Inside the link, the origin says: <em>&quot;The geometry or mass lives here, measured from the link&#39;s own frame.&quot;</em></p><pre>&lt;link name=&quot;base_link&quot;&gt;<br>  &lt;visual&gt;<br>    &lt;origin xyz=&quot;0 0 0.075&quot;/&gt;<br>    &lt;geometry&gt;<br>      &lt;box size=&quot;0.30 0.20 0.15&quot;/&gt;<br>    &lt;/geometry&gt;<br>  &lt;/visual&gt;<br>&lt;/link&gt;</pre><p>Here, base_link&#39;s frame is on the floor, but the chassis box is 0.15 m tall. To center the box vertically, the visual geometry must shift up by half the height. The ruler here is the <strong>link&#39;s own frame</strong>.</p><p>Two rulers. Same word. That is the two-ruler problem.</p><p>The moment this clicked, URDF stopped being confusing. Every time I saw origin, I asked: <em>&quot;Whose ruler am I reading?&quot;</em></p><h3>Position: xyz Is a Walk, Not a Point</h3><p>When you see xyz=&quot;0 0.15 0.05&quot;, do not read it as &quot;the point (0, 0.15, 0.05).&quot; Read it as a set of instructions:</p><ul><li>Start at the reference frame’s origin.</li><li>Walk 0 m along X.</li><li>Walk 0.15 m along Y.</li><li>Walk 0.05 m along Z.</li></ul><p>In ROS, the convention is:</p><p>AxisPositive directionXforwardYleftZup</p><p>A negative Y value means right. A negative Z value means down.</p><p>This sounds trivial, but it matters because every xyz is relative. You cannot say &quot;the kitchen is at (3, 4)&quot; without saying &quot;relative to my house.&quot; Likewise, you cannot say xyz=&quot;0 0.15 0.05&quot; without knowing the parent frame.</p><h3>Rotation: Why My Wheel Was Wrong</h3><p>A cylinder in URDF is tall along the Z axis by default. If you want a wheel that rolls along the ground along X, you need the cylinder’s axle to point along Y.</p><p>To do that, you rotate the cylinder 90° around the X axis:</p><pre>&lt;origin rpy=&quot;1.5708 0 0&quot;/&gt;</pre><p>Roll-pitch-yaw means: rotate around X, then Y, then Z. For a simple wheel, only one of those three numbers is non-zero.</p><p>My first attempt used rpy=&quot;0 1.5708 0&quot; — rotation around Y. That made the cylinder&#39;s axis point along X, so the wheel would roll along Y instead of X. The robot looked like it had two tiny barrels mounted sideways.</p><p>The lesson: rotation order and axis matter. When in doubt, physically trace where the Z axis of the geometry ends up after the rotation.</p><h3>Axis: The Pin the Joint Spins Around</h3><p>For a moving joint, you must also define an <strong>axis</strong>:</p><pre>&lt;axis xyz=&quot;0 1 0&quot;/&gt;</pre><p>This is the direction of the imaginary pin that the joint spins around. A wheel rolling forward along X spins around its Y axle. If the axis were 0 0 1, the wheel would spin like a top.</p><p>The axis is defined in the joint’s own frame. Combined with the geometry rotation, this determines which way the wheel actually turns when the joint receives a velocity command.</p><h3>Why This Matters for Sensors</h3><p>Every sensor produces data in its own frame:</p><ul><li>A LiDAR returns distances in laser_frame.</li><li>A camera returns pixels that project into camera_frame.</li><li>An IMU returns accelerations in imu_frame.</li></ul><p>The navigation stack needs all of this data in a common frame, usually base_link or map. URDF is the source of truth that says:</p><blockquote><em>“laser_frame is 0.17 m above </em><em>base_link, facing forward.&quot;&quot;</em></blockquote><p>If that frame is wrong by even a few centimeters, the obstacle at (1, 0, 0) in laser coordinates will appear in the wrong place in base coordinates. The robot will think a wall is where it is not.</p><p>This is why coordinate frames are not an academic exercise. They are the foundation of sensor fusion.</p><h3>Inertial: The Physics of the Frame</h3><p>If you only care about visualization, geometry is enough. If you care about physics, you need <strong>inertial</strong> properties.</p><p>Three things matter:</p><ol><li><strong>Mass</strong> — how much matter is in the link.</li><li><strong>Center of mass</strong> — the average location of that matter.</li><li><strong>Moment of inertia</strong> — how the mass is distributed, which determines resistance to rotation.</li></ol><p>For simple shapes, you can compute inertia with standard formulas. You do not need to memorize them, but you need to know that Gazebo requires them. A link with zero or wrong inertia will behave unpredictably in simulation: it might jitter, flip, or fall through the floor.</p><h3>URDF as a Story</h3><p>Once you see URDF this way, every tag has a clear role:</p><ul><li>&lt;link&gt; — here is a rigid body.</li><li>&lt;joint&gt; — here is how two bodies connect.</li><li>&lt;origin&gt; — here is where the child frame or geometry lives.</li><li>&lt;axis&gt; — here is how the joint moves.</li><li>&lt;visual&gt; — here is what it looks like.</li><li>&lt;collision&gt; — here is the simplified shape for physics and planning.</li><li>&lt;inertial&gt; — here is how it behaves under force.</li></ul><p>Every line answers one specific question about where something is or how it moves.</p><h3>What I Got Wrong (So You Can Skip It)</h3><ol><li><strong>I treated </strong><strong>xyz as an absolute point.</strong> It is a displacement from a parent frame.</li><li><strong>I confused joint origin with link origin.</strong> Joint origin uses the parent’s ruler; link origin uses the link’s own ruler.</li><li><strong>I rotated the wheel around the wrong axis.</strong> A Z-aligned cylinder needs roll around X to become a wheel rolling along X.</li><li><strong>I forgot that continuous joints need joint states.</strong> robot_state_publisher cannot compute wheel transforms without /joint_states. Fixed joints do not have this problem.</li><li><strong>I put the caster inside the chassis.</strong> The first position I chose was entirely occluded by the chassis box. Visualizing immediately revealed the mistake.</li></ol><h3>The One-Sentence Summary</h3><p>A robot is a family of frames. URDF tells ROS where each frame lives, how it moves, and what physical properties it has.</p><p>If you are starting URDF and feeling lost, do not memorize tags. Memorize this sentence. The tags are just the syntax for expressing it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=537aac323d1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Anatomy of a ROS2 Project: How Everything Connects]]></title>
            <link>https://medium.com/@shoaib6174/the-anatomy-of-a-ros2-project-how-everything-connects-62bb07c59b72?source=rss-9482f5c0f21a------2</link>
            <guid isPermaLink="false">https://medium.com/p/62bb07c59b72</guid>
            <category><![CDATA[ros2]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Mohammad Shoaib]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 11:44:02 GMT</pubDate>
            <atom:updated>2026-06-16T11:44:02.075Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Stop copying tutorials. Understand the workspace, the packages, and the flow from build to runtime.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Ys-ReO3PCNETtgdrTFm9g.png" /></figure><p>You clone a ROS2 project from GitHub. Or you finish a tutorial and look at what you just created. The folder tree is dense. There are package.xml files, CMakeLists.txt files, launch/ folders, config/ folders, urdf/ files, and a build/ directory that appeared out of nowhere.</p><p>Your first thought: <em>I have no idea what any of this does.</em></p><p>Your second thought: <em>The tutorial told me to type these commands, and they worked, but I do not understand why.</em></p><p>That is the normal experience. ROS2 tutorials are great at getting something on your screen. They are not great at explaining the machinery underneath. This post is the explanation.</p><p>By the end, you will look at a ROS2 workspace and see a clean organization instead of chaos. You will know what each folder does, why it exists, and how the parts connect when you build and run.</p><h3>The Big Picture</h3><p>Here is the entire idea in one sentence:</p><blockquote><em>A ROS2 workspace is a folder of packages. Each package is a folder of files with a specific job. When you build, those files turn into runnable artifacts. When you run, the artifacts talk to each other.</em></blockquote><p>That is all. Everything else — colcon, CMakeLists.txt, package.xml, launch/ — exists to support this idea.</p><p>The hierarchy looks like this:</p><pre>workspace<br>  └── packages<br>        └── files<br>              └── build artifacts<br>                    └── running nodes</pre><p>If you remember nothing else, remember this hierarchy. It is the skeleton of every ROS2 project.</p><h3>Meet the Example Project</h3><p>Instead of overwhelming you with a real production project, we will use a tiny, realistic example:</p><pre>ros2_ws/<br>  src/<br>    robot_description/<br>      package.xml<br>      CMakeLists.txt<br>      urdf/<br>        robot.urdf.xacro<br>      launch/<br>        view_robot.launch.py<br>    robot_control/<br>      package.xml<br>      CMakeLists.txt<br>      src/<br>        velocity_publisher.cpp<br>    robot_bringup/<br>      package.xml<br>      CMakeLists.txt<br>      launch/<br>        robot.launch.py<br>      config/<br>        params.yaml<br>  build/<br>  install/<br>  log/</pre><p>This project has three packages:</p><ul><li><strong>robot_description</strong> — the robot&#39;s physical model and a launch file to view it.</li><li><strong>robot_control</strong> — a C++ node that publishes velocity commands.</li><li><strong>robot_bringup</strong> — the top-level launch file and parameter files that tie everything together.</li></ul><p>Keep this tree in mind. We will come back to it in every section.</p><blockquote><em>This tree is intentionally simplified. The package and file names are chosen to teach the structure, not to be a copy-paste starter project.</em></blockquote><h3>Anatomy Part 1: The Workspace Level</h3><p>A workspace has four important directories. Three of them are created automatically when you run colcon build.</p><h4>src/ — Your Code</h4><p>This is the only top-level directory you edit by hand. Every package lives here. When you write a new node, define a URDF model, or create a launch file, you do it in src/.</p><h4>build/ — The Construction Site</h4><p>When colcon build runs, CMake and setuptools do their work here. You will find object files, CMake caches, and temporary outputs. This directory is safe to delete. colcon can rebuild it from src/.</p><h4>install/ — The Finished Product</h4><p>This is what ROS2 actually runs from. After a successful build, executables, Python packages, launch files, and config files end up here. When you run ros2 run my_package my_node, ROS2 looks in install/.</p><h4>log/ — The Build Diary</h4><p>colcon writes timing data, command outputs, and error logs here. Useful for debugging, safe to delete.</p><h4>Why Separate build/ and install/?</h4><p>Because compiling is messy. build/ contains intermediate files. install/ contains only the clean, final artifacts that ROS2 needs.</p><p>This separation means you can delete build/ to force a fresh compile while keeping install/ usable. It also means you can delete install/ to clean up what ROS2 sees without touching your source.</p><h4>What Goes Into Version Control?</h4><p>Only src/ belongs in Git. The other three directories are generated. Your .gitignore should look like this:</p><pre>build/<br>install/<br>log/</pre><h3>Anatomy Part 2: The Package Level</h3><p>A package is the unit of software organization in ROS2. Think of it as a reusable, installable module.</p><p>In our example:</p><ul><li><strong>robot_description</strong> handles the robot&#39;s physical model and visualization.</li><li><strong>robot_control</strong> contains the C++ node that publishes velocity commands.</li><li><strong>robot_bringup</strong> orchestrates the top-level launch and configuration.</li></ul><p>Each package has two essential files:</p><h4>package.xml — The Manifest</h4><p>This file answers: <em>What is this package called, who wrote it, what does it need?</em></p><p>Here is the package.xml for robot_description:</p><pre>&lt;?xml version=&quot;1.0&quot;?&gt;<br>&lt;package format=&quot;3&quot;&gt;<br>  &lt;name&gt;robot_description&lt;/name&gt;<br>  &lt;version&gt;0.0.1&lt;/version&gt;<br>  &lt;description&gt;Robot model and visualization&lt;/description&gt;<br>  &lt;maintainer email=&quot;you@example.com&quot;&gt;You&lt;/maintainer&gt;<br>  &lt;license&gt;MIT&lt;/license&gt;<br>  <br>  &lt;buildtool_depend&gt;ament_cmake&lt;/buildtool_depend&gt;<br><br>  &lt;depend&gt;urdf&lt;/depend&gt;<br>  &lt;depend&gt;xacro&lt;/depend&gt;<br><br>  &lt;export&gt;<br>    &lt;build_type&gt;ament_cmake&lt;/build_type&gt;<br>  &lt;/export&gt;<br>&lt;/package&gt;</pre><p>Key parts:</p><ul><li>&lt;name&gt; — the package name.</li><li>&lt;version&gt; — semantic version.</li><li>&lt;buildtool_depend&gt; — the build tool: ament_cmake or ament_python.</li><li>&lt;depend&gt; — a dependency needed at both build and runtime.</li><li>&lt;export&gt;...&lt;build_type&gt; — tells colcon which builder to use.</li></ul><h4>CMakeLists.txt or setup.py — The Build Recipe</h4><p>This file answers: <em>How do I turn this package’s source into something runnable?</em></p><p>C++ packages use CMakeLists.txt. Python packages use setup.py.</p><p>We will look at both in the next section.</p><h3>Anatomy Part 3: Key File Types</h3><p>Now let’s look at the actual files inside the packages and what they do.</p><h4>*.launch.py — The Conductor</h4><p>A launch file starts multiple nodes together. Instead of opening five terminals, you write one launch file.</p><p>Example from robot_bringup:</p><pre>from launch import LaunchDescription<br>from launch_ros.actions import Node<br>from launch.actions import IncludeLaunchDescription<br>from launch.launch_description_sources import PythonLaunchDescriptionSource<br>from ament_index_python.packages import get_package_share_directory<br>import os<br><br>def generate_launch_description():<br>    return LaunchDescription([<br>        IncludeLaunchDescription(<br>            PythonLaunchDescriptionSource([<br>                os.path.join(<br>                    get_package_share_directory(&#39;robot_description&#39;),<br>                    &#39;launch&#39;,<br>                    &#39;view_robot.launch.py&#39;<br>                )<br>            ])<br>        ),<br>        Node(<br>            package=&#39;robot_control&#39;,<br>            executable=&#39;velocity_publisher&#39;,<br>            name=&#39;velocity_publisher&#39;<br>        ),<br>    ])</pre><p>You do not need to memorize this. The point is: launch files connect packages at runtime.</p><h3>*.urdf.xacro — The Robot Model</h3><p>URDF files describe the robot’s physical structure: links, joints, shapes. Xacro is a macro language that makes URDF reusable.</p><p>Example snippet from robot_description/urdf/robot.urdf.xacro:</p><pre>&lt;robot name=&quot;my_robot&quot; xmlns:xacro=&quot;http://www.ros.org/wiki/xacro&quot;&gt;<br>  &lt;link name=&quot;base_link&quot;&gt;<br>    &lt;visual&gt;<br>      &lt;geometry&gt;<br>        &lt;box size=&quot;0.3 0.2 0.15&quot;/&gt;<br>      &lt;/geometry&gt;<br>    &lt;/visual&gt;<br>  &lt;/link&gt;<br>&lt;/robot&gt;</pre><h3>*.cpp / *.py — The Nodes</h3><p>Nodes are the running programs. A C++ node might look like this:</p><pre>#include &lt;rclcpp/rclcpp.hpp&gt;<br><br>int main(int argc, char * argv[])<br>{<br>  rclcpp::init(argc, argv);<br>  auto node = rclcpp::Node::make_shared(&quot;velocity_publisher&quot;);<br>  RCLCPP_INFO(node-&gt;get_logger(), &quot;Velocity publisher started&quot;);<br>  rclcpp::spin(node);<br>  rclcpp::shutdown();<br>  return 0;<br>}</pre><p>Again, you do not need to memorize the code. You need to recognize that this file is a node that will become an executable.</p><h4>config/*.yaml — Parameters</h4><p>YAML files store configuration values for nodes. Example from robot_bringup/config/params.yaml:</p><pre>velocity_publisher:<br>  ros__parameters:<br>    max_velocity: 1.0<br>    publish_rate: 10.0</pre><h4>CMakeLists.txt — Build Recipe for C++</h4><p>Here is a typical CMakeLists.txt for a C++ package:</p><pre>cmake_minimum_required(VERSION 3.16)<br>project(robot_control)<br><br>find_package(ament_cmake REQUIRED)<br>find_package(rclcpp REQUIRED)<br>add_executable(velocity_publisher src/velocity_publisher.cpp)<br>ament_target_dependencies(velocity_publisher rclcpp)<br>install(TARGETS velocity_publisher DESTINATION lib/${PROJECT_NAME})<br>install(DIRECTORY launch config DESTINATION share/${PROJECT_NAME})<br>ament_package()</pre><p>What each line does:</p><ul><li>cmake_minimum_required(VERSION 3.16) — the oldest CMake version this package supports.</li><li>project(robot_control) — the project name.</li><li>find_package(ament_cmake REQUIRED) — loads ROS2 CMake helpers.</li><li>find_package(rclcpp REQUIRED) — finds the C++ client library.</li><li>add_executable(...) — declares what to compile.</li><li>ament_target_dependencies(...) — links ROS2 libraries.</li><li>install(TARGETS ...) — puts the executable where ros2 run can find it.</li><li>install(DIRECTORY ...) — copies launch/ and config/ folders into the install space so ros2 launch can find them.</li><li>ament_package() — generates ROS2 install-space metadata.</li></ul><h4>setup.py — Build Recipe for Python</h4><p>Here is a minimal setup.py for a Python package:</p><pre>from setuptools import setup, find_packages<br><br>setup(<br>    name=&#39;robot_vision&#39;,<br>    version=&#39;0.0.1&#39;,<br>    packages=find_packages(),<br>    data_files=[<br>        (&#39;share/ament_index/resource_index/packages&#39;, [&#39;resource/robot_vision&#39;]),<br>        (&#39;share/robot_vision&#39;, [&#39;package.xml&#39;]),<br>    ],<br>    install_requires=[&#39;setuptools&#39;],<br>    entry_points={<br>        &#39;console_scripts&#39;: [<br>            &#39;color_detector = robot_vision.color_detector:main&#39;,<br>        ],<br>    },<br>)</pre><p>Key parts:</p><ul><li>packages=find_packages() — finds Python packages.</li><li>data_files — registers the package with ROS2 and installs package.xml.</li><li>install_requires — Python dependencies.</li><li>entry_points[&#39;console_scripts&#39;] — makes Python scripts runnable with ros2 run robot_vision color_detector.</li></ul><p>Without entry_points, a Python module can still be imported, but it cannot be launched as a standalone executable from the command line.</p><h3>ament_cmake vs ament_python</h3><p>When I first saw find_package(ament_cmake REQUIRED) in a CMakeLists.txt, I thought ament_cmake was a completely different language from CMake. It is not.</p><h4>ament_cmake</h4><p>ament_cmake is <strong>vanilla CMake plus ROS2 helpers</strong>. The helpers do things like:</p><ul><li>Find ROS2 packages with find_package(ament_cmake REQUIRED).</li><li>Link ROS2 dependencies with ament_target_dependencies().</li><li>Install launch files and config files with install(DIRECTORY ...).</li><li>Generate install metadata with ament_package().</li></ul><p>You are still writing CMake. ROS2 just gives you extra macros.</p><h4>ament_python</h4><p>ament_python is <strong>setuptools plus ROS2 registration</strong>. You still write a normal setup.py, but you add:</p><ul><li>A resource/ marker file so ros2 pkg list can find your package.</li><li>data_files entries so package.xml ends up in the install space.</li><li>entry_points[&#39;console_scripts&#39;] so ros2 run can start your Python nodes.</li></ul><h4>Why Two Build Systems?</h4><p>Because C++ and Python are different languages.</p><ul><li>C++ must be compiled into machine code. That needs CMake.</li><li>Python is interpreted, but it still needs packaging so other code can import it. That needs setuptools.</li></ul><p>package.xml tells colcon which builder to use through the &lt;build_type&gt; tag.</p><h3>The Build Flow</h3><p>Let’s trace what happens when you run:</p><pre>cd ros2_ws<br>colcon build --symlink-install</pre><h4>Step 1: colcon Scans src/</h4><p>colcon looks inside src/ and finds three packages:</p><ul><li>robot_description</li><li>robot_control</li><li>robot_bringup</li></ul><h4>Step 2: colcon Reads package.xml</h4><p>For each package, colcon reads package.xml to learn:</p><ul><li>The package name.</li><li>The build tool (ament_cmake or ament_python).</li><li>The dependencies.</li></ul><h4>Step 3: Install Dependencies with rosdep</h4><p>Before building, rosdep reads the package.xml files and installs any missing system dependencies:</p><pre>rosdep install --from-paths src --ignore-src -y</pre><p>This step is easy to skip, but missing it is a common cause of Cannot find package errors during CMake.</p><h4>Step 4: colcon Builds in Dependency Order</h4><p>If robot_bringup depends on robot_control, colcon builds robot_control first.</p><p>For C++ packages, colcon calls <em>CMake</em>. <em>CMake</em> reads CMakeLists.txt, generates build files, and compiles the code.</p><p>For Python packages, colcon calls <em>setuptools</em>. s<em>etuptools</em> reads setup.py and installs the Python module.</p><h4>Step 5: Outputs Go to build/ and install/</h4><p>build/ holds temporary artifacts. install/ holds the final, runnable outputs.</p><p>After the build, install/ looks something like this:</p><pre>install/<br>  robot_description/<br>    share/robot_description/<br>      urdf/<br>      launch/<br>  robot_control/<br>    lib/robot_control/<br>      velocity_publisher<br>  robot_bringup/<br>    share/robot_bringup/<br>      launch/<br>      config/</pre><p>Notice that robot_control has a lib/ folder with the compiled executable, while robot_description and robot_bringup mostly have share/ folders with data files.</p><h4>Step 6: --symlink-install Links Python Files Back to src/</h4><p>Normally, colcon copies files from src/ to install/. With --symlink-install, it creates symlinks instead.</p><p>For Python development, this means you can edit a .py file in src/ and the change is active immediately. You do not need to rebuild.</p><h4>The One-Line Summary</h4><p>rosdep installs system dependencies; colcon is the coordinator; CMake builds C++; setuptools builds Python; install/ is what actually runs.</p><h3>The Runtime Flow</h3><p>Now let’s trace what happens when you run:</p><pre>ros2 launch robot_bringup robot.launch.py</pre><h4>Step 1: ROS2 Finds the Launch File</h4><p>ROS2 searches AMENT_PREFIX_PATH for the package robot_bringup. Inside that package, it looks in share/robot_bringup/launch/ for robot.launch.py.</p><p>Remember: the launch file in install/ is what runs, not the one in src/.</p><h4>Step 2: The Launch File Loads Other Files</h4><p>robot.launch.py might do three things:</p><ol><li>Include view_robot.launch.py from robot_description.</li><li>Start robot_state_publisher, which receives the URDF and broadcasts transforms.</li><li>Start velocity_publisher from robot_control.</li></ol><h4>Step 3: The Robot Model Is Loaded</h4><p>The launch file loads the URDF from install/robot_description/share/robot_description/urdf/robot.urdf.xacro and passes it to robot_state_publisher, which broadcasts the robot&#39;s frames.</p><h4>Step 4: The Control Node Starts</h4><p>velocity_publisher is the compiled executable at install/robot_control/lib/robot_control/velocity_publisher. It starts running and publishes velocity commands.</p><h4>Step 5: Parameters Are Loaded</h4><p>If the launch file loads config/params.yaml, those values are passed to the nodes.</p><h4>The Connection</h4><p>At runtime, the launch file is the glue. It connects packages by starting their nodes, loading their models, and passing their parameters. Without the launch file, each package is just a collection of files. The launch file turns them into a running robot.</p><h3>Sourcing and Environment Variables</h3><p>Here is the most common beginner trap: you build the workspace, everything works, then you open a new terminal and ros2 launch fails with package not found.</p><p>The reason is sourcing.</p><p>Every new terminal needs to run:</p><pre>source install/setup.zsh</pre><p>If you use bash, use .bash instead:</p><pre>source install/setup.bash</pre><h4>What Does Sourcing Do?</h4><p>It modifies environment variables so the shell knows about your workspace. The important ones are:</p><p>VariableWhat it doesAMENT_PREFIX_PATHThe master list of places ROS2 looks for packages at runtime.CMAKE_PREFIX_PATHWhere CMake looks when find_package() is called.PYTHONPATHWhere Python looks for importable modules.COLCON_PREFIX_PATHcolcon&#39;s record of which workspaces have been built.</p><p>After sourcing, ROS2 can find your packages. Before sourcing, it cannot.</p><h4>Why Every New Terminal Needs It</h4><p>source only affects the current shell. If you open a new terminal, you get a fresh shell with default environment variables. You must source again.</p><h4>Why .bash vs .zsh Matters</h4><p>The .bash setup scripts use a Bash-specific variable called BASH_SOURCE to figure out where they are on disk. zsh does not handle this the same way. If you use zsh and source .bash, you get confusing errors about missing local_setup.sh.</p><p>Match the setup file to your shell. Run echo $SHELL if you are not sure.</p><h3>Common Errors and What They Mean</h3><p>These are the errors I saw most often when I started. Now that you know the anatomy, they make sense.</p><p><strong>command not found for ros2</strong></p><ul><li><strong>What it means:</strong> Your shell does not know where ROS2 is installed.</li><li><strong>How to fix it:</strong> Run source /opt/ros/jazzy/setup.zsh</li></ul><p><strong>package not found</strong></p><ul><li><strong>What it means:</strong> Your workspace is not in AMENT_PREFIX_PATH.</li><li><strong>How to fix it:</strong> Run source install/setup.zsh from inside your workspace root.</li></ul><p><strong>Cannot find package during CMake</strong></p><ul><li><strong>What it means:</strong> CMAKE_PREFIX_PATH is missing a required dependency.</li><li><strong>How to fix it:</strong> Run rosdep install --from-paths src --ignore-src -y, or source the specific workspace that provides it.</li></ul><p><strong>CMake target name error</strong></p><ul><li><strong>What it means:</strong> The names used in add_executable() and ament_target_dependencies() do not match.</li><li><strong>How to fix it:</strong> Check your CMakeLists.txt and make the target names completely identical.</li></ul><p><strong>Python changes not reflected</strong></p><ul><li><strong>What it means:</strong> You built the package without the symlink flag, or you are currently scoped to the wrong Python virtual environment.</li><li><strong>How to fix it:</strong> Rebuild using colcon build --symlink-install or verify your active venv.</li></ul><p><strong>Permission denied</strong></p><ul><li><strong>What it means:</strong> The script or node file exists, but it lacks execution permissions.</li><li><strong>How to fix it:</strong> Run chmod +x filename on the target file.</li></ul><p><strong>No such file or directory (for a launch file)</strong></p><ul><li><strong>What it means:</strong> The launch file was never installed to the share/ directory during the build process.</li><li><strong>How to fix it:</strong> Add install(DIRECTORY launch ...) in your CMakeLists.txt, or include it under data_files in your setup.py.</li></ul><p>If you see one of these, you are not broken. You are just missing one of the connections this post covers.</p><h3>How to Use This When Following Tutorials</h3><p>The next time you follow a ROS2 tutorial, ask these questions before copying a command:</p><ol><li><strong>Which package does this command belong to?</strong><br>If the tutorial says to create a file, know which package it lives in.</li><li><strong>Is this a build-time command or a runtime command?</strong><br>colcon build is build-time. ros2 launch and ros2 run are runtime.</li><li><strong>Which directory will this command read from or write to?</strong><br>Source files live in src/. Executables live in install/.</li><li><strong>Will I need to source something afterward?</strong><br>If you built something, you probably need to source install/setup.zsh.</li><li><strong>If this fails, which layer is broken?</strong><br>Is it the source file, the build, the install space, or the shell environment?</li></ol><p>Asking these questions turns copying into understanding.</p><h3>What to Do Next</h3><p>Understanding anatomy is the first layer. The next layers are:</p><ol><li><strong>Build a minimal version of the example yourself.</strong><br>Create a workspace, add one C++ package and one Python package, and run colcon build --symlink-install. Watch build/, install/, and log/ appear.</li><li><strong>Add a launch file.</strong><br>Write a *.launch.py that starts a node from each package. Trace how ros2 launch finds it in install/.</li><li><strong>Break something on purpose.</strong><br>Delete install/, open a new terminal without sourcing, or rename a target in add_executable(). The errors will now make sense because you know which layer failed.</li><li><strong>Read one real package’s </strong><strong>package.xml and </strong><strong>CMakeLists.txt.</strong><br>Pick any package from nav2 or slam_toolbox. You will recognize every section.</li></ol><h3>Conclusion</h3><p>A ROS2 project is not a black box. It is a workspace of packages, each containing files with clear jobs. When you build, those files become artifacts in install/. When you run, launch files connect those artifacts into a working system.</p><p>The four ideas to remember:</p><ol><li><strong>Workspace → Package → File</strong> is the organization.</li><li><strong>src/ is for humans; </strong><strong>install/ is for ROS2.</strong></li><li><strong>colcon coordinates CMake and setuptools.</strong></li><li><strong>Sourcing connects your shell to your workspace.</strong></li></ol><p>Once you see this structure, tutorials stop feeling like magic spells. You can look at any ROS2 project, identify the packages, trace the launch files, and understand how the pieces fit together.</p><p>That is the difference between copying commands and actually knowing ROS2.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62bb07c59b72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I Wish I Knew Before Installing ROS2: A Survival Guide to Build Tools, Shells, and Executables]]></title>
            <link>https://medium.com/@shoaib6174/what-i-wish-i-knew-before-installing-ros2-a-survival-guide-to-build-tools-shells-and-executables-75e50f08ba33?source=rss-9482f5c0f21a------2</link>
            <guid isPermaLink="false">https://medium.com/p/75e50f08ba33</guid>
            <category><![CDATA[ros2]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Mohammad Shoaib]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 10:12:44 GMT</pubDate>
            <atom:updated>2026-06-16T10:12:44.642Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From Jupyter notebooks and Python scripts to compiling C++ and sourcing setup files — the prerequisites no one warned me about.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3j2dhH5_wMqrN6cTBUOolA.png" /></figure><p>Back in 2024, I decided to learn ROS2.</p><p>I knew Python. I had trained models, cleaned datasets, and written notebooks. I had even done some data structures and algorithms in C++. I thought I was ready.</p><p>I was not.</p><p>The first week was not about robots. It was about build tools, shell scripts, environment variables, and why my terminal kept telling me command not found. I copied commands from tutorials without understanding them. I installed things multiple times. I sourced setup files in the wrong shell.</p><p>The problem was not ROS2. The problem was that ROS2 assumes you already know a set of tools and ideas that nobody had explicitly taught me.</p><p>This post is the guide I wish I had read first. It covers the prerequisites you need before you install ROS2, explained from the ground up, with small copy-and-run exercises.</p><p>If you are coming from Python, AI notebooks, or beginner C++, this is for you.</p><h3>What You Need for the Exercises</h3><p>This post includes copy-and-run exercises. Before you start, make sure you have:</p><ul><li>A Linux machine or virtual machine. Ubuntu 24.04 is ideal.</li><li>A terminal open and ready.</li><li>g++, make, and cmake installed.</li><li>Python 3 and python3-venv installed.</li></ul><p>On Ubuntu, you can install the missing tools with:</p><pre>sudo apt update<br>sudo apt install build-essential cmake python3 python3-venv python3-pip</pre><p>build-essential gives you g++ and make.</p><p>You do <strong>not</strong> need ROS2 installed yet. That is the point.</p><h3>0. What Is a Terminal, Really?</h3><p>A terminal is a text-based interface for interacting with your computer. Instead of clicking buttons and menus, you communicate through text: you type commands, and the computer executes them and returns the result.</p><p>Before graphical interfaces existed, terminals were the primary way people used computers. Today, they remain one of the fastest and most powerful tools for development, automation, and modern CLI-based workflows. ROS2 is one of those environments where working comfortably in the terminal becomes essential.</p><p>Before moving forward, understand these four ideas:</p><h4>0.1. Command — What you want the computer to do</h4><p>A <strong>command</strong> is an instruction you type into the terminal.</p><p>Example:</p><pre>ls</pre><p>This tells the computer:</p><blockquote><em>“Show me what files and folders are here.”</em></blockquote><p>Commands are simply requests. The computer reads them, performs the action, and prints the result.</p><h4>0.2. Prompt — Where the terminal waits for your input</h4><p>The <strong>prompt</strong> is the text displayed before your cursor. It indicates that the terminal is ready to receive a command and often shows useful information, such as your current location.</p><p>Example:</p><pre>shoaib@ubuntu:~/ros2_ws$</pre><p>Everything before the blinking cursor is the prompt.</p><h4>0.3. Directory — A folder on your computer</h4><p>A <strong>directory</strong> is simply another word for a folder.</p><p>Examples:</p><pre>Documents/<br>Downloads/<br>ros2_ws/</pre><p>Directories organize files and other directories.</p><h4>0.4. Working Directory — The folder the terminal is currently operating inside</h4><p>The terminal always operates from one directory at a time. That current location is called the <strong>working directory</strong>.</p><p>For example, if your prompt shows:</p><pre>shoaib@ubuntu:~/ros2_ws$</pre><p>your working directory is ros2_ws.</p><p>If you run:</p><pre>ls</pre><p>the terminal lists the contents of ros2_ws.</p><p>If you change location:</p><pre>cd src</pre><p>your working directory becomes ros2_ws/src.</p><h3>Analogy: The Terminal Is Like Talking to a Reception Desk in a Building</h3><p>Imagine a huge office building with many rooms.</p><ul><li>The <strong>directories</strong> are the rooms.</li><li>Your <strong>working directory</strong> is the room you are currently standing in.</li><li>The <strong>prompt</strong> is the receptionist saying:<br><em>“You are currently in Room: </em><em>ros2_ws. What would you like to do?”</em></li><li>A <strong>command</strong> is your instruction to the receptionist.</li></ul><p>You say:</p><pre>ls</pre><p>The receptionist replies:</p><blockquote><em>“These are the things inside this room.”</em></blockquote><p>Then you say:</p><pre>cd src</pre><p>The receptionist moves you into another room.</p><p>From that moment onward, every new request happens relative to your new location.</p><p>Using the terminal is not memorizing magic words — it is learning how to navigate rooms and give clear instructions.</p><h4>Mini-exercise</h4><p>Open a terminal and try these commands one at a time:</p><pre>pwd</pre><p>pwd means &quot;print working directory.&quot; It shows the full path of the folder you are in right now.</p><pre>ls</pre><p>ls means &quot;list.&quot; It shows the files and folders in your current directory.</p><pre>cd ~<br>pwd</pre><p>cd ~ means &quot;change directory to home.&quot; The tilde ~ is shorthand for your home folder. After running pwd, the path should now end in your username.</p><pre>cd /<br>ls</pre><p>cd / takes you to the <strong>root</strong> of the file system — the top-level folder that contains everything else.</p><pre>cd ~</pre><p>Go back home.</p><p>That is it. You do not need to be a terminal wizard. You just need to know how to move around and read what the computer prints back.</p><p>If you already know pwd, ls, and cd, feel free to skim this section and move on.</p><h4>How this appears in ROS2</h4><p>Almost everything in ROS2 starts from a terminal: installing ROS2, building workspaces, launching robots, checking topics. If the terminal feels foreign, ROS2 feels impossible. Spend ten minutes getting comfortable here and everything afterwards gets easier.</p><h3>1. The Shell Is Not Just a Terminal</h3><p>The terminal window is the visual box. Inside it runs a program called the <strong>shell</strong>. The shell reads what you type, figures out which program you want to run, and starts it.</p><p>When you type a command like git, the shell asks: &quot;Where is the program named git?&quot;</p><p>It answers this by looking through a list of folders stored in an environment variable called PATH. The first match wins.</p><p>An <strong>environment variable</strong> is a named value that the shell keeps around and shares with the programs it starts. PATH is one of them. You can create your own with export MY_VAR=hello.</p><p><strong>Analogy:</strong> The shell is a librarian. You ask for a book by name (git). The librarian looks in the catalog (PATH) to find which shelf it is on, then brings it to you.</p><h4>Mini-exercise</h4><p>Open a terminal and run:</p><pre>echo $PATH</pre><p>The output is a colon-separated list of folder paths. These are the places your shell looks for commands.</p><p>Now run:</p><pre>which git</pre><p>This shows exactly which git executable the shell found. On my machine it prints /usr/bin/git.</p><p>Next, create your own command:</p><pre>mkdir -p ~/mybin</pre><p>Create a file called ~/mybin/hello.sh with this content:</p><pre>#!/bin/bash<br>echo &quot;Hello from mybin&quot;</pre><p>Make it executable:</p><pre>chmod +x ~/mybin/hello.sh</pre><p>Try running it from your home directory:</p><pre>cd ~<br>hello.sh</pre><p>It fails. The shell cannot find it because ~/mybin is not in PATH yet.</p><p>Add it:</p><pre>export PATH=&quot;$HOME/mybin:$PATH&quot;</pre><p>Now try again:</p><pre>hello.sh</pre><p>It works.</p><p>Run echo $PATH again. You should see your mybin folder at the front of the list.</p><p>Now open a <strong>new terminal</strong> and run hello.sh again. It fails. That is because export PATH=... only changed the current shell. New shells do not inherit temporary changes unless you put them in a startup file like .bashrc or .zshrc.</p><p>You can delete ~/mybin later if you do not want to keep the test command.</p><h4>How this appears in ROS2</h4><p>ROS2’s source install/setup.zsh adds your workspace&#39;s install/ folders to PATH, AMENT_PREFIX_PATH, and other environment variables. Without understanding PATH, sourcing feels like magic. Once you understand it, you realize it is just the <strong>shell being told where to look.</strong></p><h3>2. Bash, Zsh, Source, and Run</h3><p>There are different shell programs. <strong>Bash</strong> (Bourne Again Shell) has been the default on Ubuntu for a long time. <strong>Zsh</strong> (Z Shell) is now the default on macOS and is increasingly common on Ubuntu.</p><p>They understand almost all the same commands, but they read different startup files and have slightly different internal variables.</p><p>When you run a script, you can do it two ways:</p><ul><li>./set_var.sh starts a new shell, runs the script, then closes. Any changes to the environment disappear when the new shell closes.</li><li>source set_var.sh runs the script inside your current shell. Any environment changes stay with you.</li></ul><p><strong>Analogy:</strong> ./set_var.sh is like asking a friend to read a recipe and then throw it away. source set_var.sh is like reading the recipe yourself and keeping the notes.</p><h4>Mini-exercise</h4><p>Create a file called set_var.sh:</p><pre>#!/bin/bash<br>export MY_VAR=&quot;hello&quot;</pre><p>Run it the first way:</p><pre>./set_var.sh<br>echo $MY_VAR</pre><p>The output is empty. The variable was set in a child shell that already exited.</p><p>Now run it the second way:</p><pre>source set_var.sh<br>echo $MY_VAR</pre><p>This time it prints hello because the variable was set in your current shell.</p><p>Check which shell you are using:</p><pre>echo $SHELL</pre><p>If it says /bin/bash, you are using bash. If it says /usr/bin/zsh or /bin/zsh, you are using zsh.</p><p>To see why the shell flavor matters, create two tiny scripts:</p><p>setup.bash:</p><pre>export BASH_VAR=&quot;from bash&quot;</pre><p>setup.zsh:</p><pre>export ZSH_VAR=&quot;from zsh&quot;</pre><p>If you use bash:</p><pre>source setup.bash<br>echo $BASH_VAR</pre><p>This works.</p><pre>source setup.zsh<br>echo $ZSH_VAR</pre><p>This may work for a simple variable, but more complex scripts will fail because zsh syntax differs from bash syntax in subtle ways.</p><p>If you use zsh, the reverse is true. More importantly, scripts that rely on bash-only variables like BASH_SOURCE will break when sourced in zsh.</p><h4>How this appears in ROS2</h4><p>ROS2 generates both setup.bash and setup.zsh inside your workspace&#39;s install/ folder. If you use zsh but source setup.bash, the BASH_SOURCE variable behaves incorrectly and you get confusing errors about missing local_setup.sh files.</p><p>Use the file that matches your shell. If you are not sure, run echo $SHELL and pick the matching one.</p><h3>3. Compiled vs Interpreted Code</h3><p>Programs are written in text files humans understand. But computers do not understand Python or C++ directly. They understand <strong>machine code</strong>.</p><p>With <strong>Python</strong>, an interpreter reads your source code line by line and runs it. You do not need a separate build step. The source file is the thing you run.</p><p>With <strong>C++</strong>, a compiler reads the entire source file, translates it into machine code, and writes an <strong>executable</strong> file. That executable is what you run. If you change the source, you must recompile.</p><p>This difference is why C++ feels heavier: there is an extra step between writing code and running it.</p><p><strong>Analogy:</strong> Python is like having a translator follow you around and interpret everything you say in real time. C++ is like writing a letter, sending it to a translator, and receiving a finished document you can hand to anyone.</p><h4>Mini-exercise</h4><p>Create hello.py:</p><pre>print(&quot;Hello from Python&quot;)</pre><p>Run it:</p><pre>python3 hello.py</pre><p>Notice there is no separate build step. The interpreter runs the source directly.</p><p>Now create hello.cpp:</p><pre>#include &lt;iostream&gt;<br>int main() {<br>  std::cout &lt;&lt; &quot;Hello from C++&quot; &lt;&lt; std::endl;<br>  return 0;<br>}</pre><p>Compile it:</p><pre>g++ hello.cpp -o hello</pre><p>This creates a new file called hello. Run it:</p><pre>./hello</pre><p>Compare the files:</p><pre>ls -l hello.cpp hello</pre><p>The executable is much larger than the source file because it contains machine code.</p><p>Now modify hello.cpp to print a different message, but do <strong>not</strong> recompile. Run ./hello again. It still prints the old message. The executable is a snapshot from the last time you compiled.</p><p>Recompile:</p><pre>g++ hello.cpp -o hello<br>./hello</pre><p>Now it prints the new message.</p><h4>How this appears in ROS2</h4><p>ROS2 nodes can be written in Python or C++. Python nodes run directly. C++ nodes must be compiled into executables before ros2 run can execute them. That is why C++ ROS2 packages need a CMakeLists.txt: it tells the compiler how to turn source files into executables.</p><h3>4. Why Build Systems Exist</h3><p>For one file, g++ is enough. For projects with many files, dependencies, include paths, and compiler flags, manual compilation becomes error-prone.</p><p>Build systems automate this. They remember which files depend on which, which flags to use, and which order to compile things in. <strong>Make</strong> was the classic tool. <strong>CMake</strong> is the modern standard.</p><h3>Mini-exercise</h3><p>Create math.cpp:</p><pre>int add(int a, int b) {<br>  return a + b;<br>}</pre><p>Create main.cpp:</p><pre>#include &lt;iostream&gt;<br>int add(int a, int b);</pre><pre>int main() {<br>  std::cout &lt;&lt; &quot;2 + 3 = &quot; &lt;&lt; add(2, 3) &lt;&lt; std::endl;<br>  return 0;<br>}</pre><p>Compile manually:</p><pre>g++ math.cpp main.cpp -o app<br>./app</pre><p>It works. But now imagine ten files, each with its own dependencies. The command gets long fast.</p><p>Write a Makefile. Make sure the indented lines use a <strong>tab character</strong>, not spaces. Make is picky about this.</p><pre>app: math.o main.o<br>	g++ math.o main.o -o app<br>math.o: math.cpp<br> g++ -c math.cpp -o math.o<br>main.o: main.cpp<br> g++ -c main.cpp -o main.o<br>clean:<br> rm -f *.o app</pre><p>Run:</p><pre>make<br>./app</pre><p>Run it again:</p><pre>make</pre><p>This time it says nothing is to be done. Make knows the source files have not changed, so it skips recompilation.</p><p>Run make clean to delete the intermediate files, then make again to rebuild.</p><h3>How this appears in ROS2</h3><p>colcon calls CMake under the hood for C++ ROS2 packages. Understanding CMake makes CMakeLists.txt less intimidating. It is not ROS2 magic — it is just a build recipe.</p><h3>5. CMake in 10 Minutes</h3><p>CMake is a <strong>build system generator</strong>. You write a file called CMakeLists.txt, CMake reads it and generates native build files (Makefiles or Ninja files), and then the native tool compiles the code.</p><p>The advantage is portability. The same CMakeLists.txt can generate build files for Linux, macOS, and Windows.</p><h3>Mini-exercise</h3><p>Create or reuse hello.cpp from Section 3:</p><pre>#include &lt;iostream&gt;<br>int main() {<br>  std::cout &lt;&lt; &quot;Hello from CMake&quot; &lt;&lt; std::endl;<br>  return 0;<br>}</pre><p>Create CMakeLists.txt:</p><pre>cmake_minimum_required(VERSION 3.8)<br>project(hello_cmake)<br>add_executable(hello hello.cpp)<br>install(TARGETS hello DESTINATION bin)</pre><p>What each line means:</p><ul><li>cmake_minimum_required(VERSION 3.8) — the oldest CMake version this project supports.</li><li>project(hello_cmake) — the project name.</li><li>add_executable(hello hello.cpp) — build an executable called hello from hello.cpp.</li><li>install(TARGETS hello DESTINATION bin) — when installing, put the executable in a bin/ folder.</li></ul><p>Now build it:</p><pre>mkdir build<br>cd build<br>cmake ..<br>make<br>./hello</pre><p>You should see Hello from CMake.</p><p>The build/ folder now contains generated Makefiles, object files, and the executable. You can delete build/ anytime and regenerate it with cmake ...</p><p>Install the executable locally to avoid permission issues:</p><pre>cd ..<br>rm -rf build<br>mkdir build<br>cd build<br>cmake .. -DCMAKE_INSTALL_PREFIX=$HOME/hello_install<br>make<br>make install</pre><p>Now the executable is in ~/hello_install/bin/hello. You can run it with the full path:</p><pre>~/hello_install/bin/hello</pre><p>Or add ~/hello_install/bin to your PATH.</p><h4>How this appears in ROS2</h4><p>ament_cmake is vanilla CMake plus ROS2 helpers. Once you know plain CMake, lines like find_package(ament_cmake REQUIRED), ament_target_dependencies, and ament_package() become understandable. They are not new syntax — they are CMake with ROS2 conventions.</p><h3>6. Python Packaging with setuptools</h3><p>pip install works because of setuptools and setup.py. A Python <strong>package</strong> is a directory with an __init__.py file inside it. setup.py tells Python how to install the package and what metadata to record.</p><h3>Mini-exercise</h3><p>Create this directory structure:</p><pre>my_package/<br>  my_package/<br>    __init__.py<br>  setup.py</pre><p>my_package/my_package/__init__.py can be empty. Its presence is what makes the directory a package.</p><p>Create my_package/setup.py:</p><pre>from setuptools import setup, find_packages</pre><pre>setup(<br>    name=&#39;my_package&#39;,<br>    version=&#39;0.0.1&#39;,<br>    packages=find_packages(),<br>)</pre><p>Create a virtual environment so you do not pollute your system Python:</p><pre>cd my_package<br>python3 -m venv venv<br>source venv/bin/activate</pre><p>Install the package in editable mode:</p><pre>pip install -e .</pre><p>The -e flag means &quot;editable.&quot; Changes you make to the source are reflected immediately without reinstalling.</p><p>Test the installation from another directory:</p><pre>cd ~<br>python3 -c &quot;import my_package; print(my_package)&quot;</pre><p>It should print the path to your package inside the virtual environment. Notice that cd ~ did <strong>not</strong> deactivate the virtual environment. The virtual environment is active for the current shell until you run deactivate.</p><p>Deactivate the virtual environment when done:</p><pre>deactivate</pre><h4>How this appears in ROS2</h4><p>ament_python packages in ROS2 use setup.py plus an ament resource marker. The structure is the same as a normal Python package. ROS2 just adds registration so ros2 pkg list can find it.</p><h3>7. Dependency Managers</h3><p>Modern software depends on other software. Dependency managers install and track those dependencies so you do not have to download and configure everything by hand.</p><p>On Ubuntu:</p><ul><li>apt manages system packages like compilers, libraries, and tools.</li><li>pip manages Python packages.</li></ul><h4>Mini-exercise</h4><p>Run:</p><pre>which git</pre><p>This shows how the shell finds a program. On my machine it prints /usr/bin/git.</p><p>See system package metadata:</p><pre>apt list --installed | grep git</pre><p>See installed Python packages:</p><pre>pip list | head</pre><p>Optional: install a small tool with each manager to observe the process. If you use pip, do it inside a virtual environment so you do not clutter your system Python.</p><pre>sudo apt update<br>sudo apt install htop</pre><p>For the Python example, reuse the virtual environment from Section 6, or create a new one:</p><pre>python3 -m venv venv<br>source venv/bin/activate<br>pip install requests</pre><p>These commands download software from repositories, place files in standard locations, and update internal lists so the system knows what is installed.</p><h4>How this appears in ROS2</h4><p>rosdep install --from-paths src --ignore-src reads package.xml files in your workspace and installs the system dependencies needed to build everything. It is essentially apt driven by ROS2 metadata. When a ROS2 package says it depends on rclcpp, rosdep knows which Ubuntu package provides it.</p><h3>8. Common Terminal and ROS2 Errors (and What They Actually Mean)</h3><p>One of the hardest parts of learning ROS2 is realizing that terminal errors are usually not random — they are clues.</p><p>Most error messages already tell you what the computer expected and what it could not find.</p><h4>command not found</h4><p><strong>What it means</strong><br>The shell cannot locate the program you are trying to run.</p><p><strong>How to fix it</strong></p><ul><li>Verify that the program is installed.</li><li>Check whether its executable directory is included in PATH.</li></ul><h4>Permission denied</h4><p><strong>What it means</strong><br>The file exists, but you do not have permission to execute it.</p><p><strong>How to fix it</strong></p><pre>chmod +x filename</pre><h4>No such file or directory when sourcing ROS2</h4><p><strong>What it means</strong><br>You are either in the wrong directory or the workspace has not been built yet.</p><p><strong>How to fix it</strong></p><pre>cd ~/your_workspace<br>colcon build<br>source install/setup.zsh</pre><p>(Use setup.bash if you are using Bash.)</p><h4>Sourcing .bash inside zsh causes strange prefix or environment errors</h4><p><strong>What it means</strong><br>The setup script was generated for Bash and behaves differently in Zsh.</p><p><strong>How to fix it</strong></p><pre>source install/setup.zsh</pre><h4>Python changes are not reflected</h4><p><strong>What it means</strong><br>Your workspace was installed without symbolic links, or Python is being imported from another environment.</p><p><strong>How to fix it</strong></p><p>Rebuild using:</p><pre>colcon build --symlink-install</pre><p>Then verify which Python environment is active.</p><h4>make: *** No targets specified</h4><p><strong>What it means</strong><br>make cannot find a Makefile, or you are running the command from the wrong directory.</p><p><strong>How to fix it</strong></p><ul><li>Confirm that a Makefile exists.</li><li>Make sure your terminal is inside the correct folder.</li></ul><h4>CMake cannot find a package</h4><p><strong>What it means</strong><br>find_package() searched CMAKE_PREFIX_PATH but could not locate the dependency.</p><p><strong>How to fix it</strong></p><ul><li>Install the missing dependency.</li><li>Source the workspace that provides the package.</li></ul><h3>A Simple Debugging Rule</h3><p>Whenever something breaks in the terminal, ask these questions in order:</p><ol><li>Does the thing exist?<br>(command, file, package)</li><li>Am I in the correct directory?</li><li>Do I have permission?</li><li>Did I source the correct environment?</li><li>Am I using the correct shell?</li></ol><p>Most terminal and ROS2 errors reduce to one of these five questions.</p><h3>9. Quick Reference</h3><p>Keep these commands handy while learning ROS2:</p><pre># Navigation<br>pwd                 # where am I?<br>ls                  # what is here?<br>cd ~                # go home<br>cd ..               # go up one folder<br><br><br># Environment<br>echo $PATH          # see command search paths<br>export VAR=value    # set an environment variable<br>source file.sh      # run a script in the current shell<br># C++ build<br>g++ file.cpp -o out # compile one file<br>make                # build using a Makefile<br>cmake ..            # generate build files<br>make install        # install to a prefix<br># Python<br>python3 -m venv venv<br>source venv/bin/activate<br>pip install -e .<br>deactivate<br># ROS2 (preview)<br>colcon build --symlink-install<br>source install/setup.zsh<br>ros2 pkg list<br>ros2 run package_name node_name</pre><h3>10. Glossary of New Terms</h3><h4>Terminal</h4><p>A text-based interface for interacting with your computer. You type commands, and the computer executes them and returns output.</p><h4>Shell</h4><p>The program running inside the terminal that reads and interprets your commands.</p><h4>Command</h4><p>An instruction or program name you type into the terminal to perform an action.</p><h4>Directory</h4><p>Another word for a folder on your computer.</p><h4>Working Directory</h4><p>The directory your terminal is currently operating inside.</p><h4>Environment Variable</h4><p>A named value shared between the shell and programs it launches. It is commonly used to store configuration and system information.</p><h4>PATH</h4><p>An environment variable that lists the directories where the shell searches for commands.</p><h4>Source</h4><p>To execute a script inside the current shell so that any environment changes remain active after the script finishes.</p><h4>Bash</h4><p>A widely used Unix shell and command language.</p><h4>Zsh</h4><p>Another popular shell program and the default shell on modern macOS.</p><h4>Compiled Language</h4><p>A programming language whose source code is translated into machine code before execution.</p><h4>Interpreted Language</h4><p>A programming language whose code is executed directly by an interpreter at runtime.</p><h4>Executable</h4><p>A file that contains instructions the operating system can run directly.</p><h4>Build System</h4><p>A tool that automates compiling, linking, packaging, and preparing software for execution.</p><h4>CMake</h4><p>A build-system generator commonly used in C++ projects. It creates build files for tools such as Make or Ninja.</p><h4>Makefile</h4><p>A file that defines build rules and instructions for the make tool.</p><h4>setuptools</h4><p>A Python library used to package, build, and install Python projects.</p><h4>Package Manager</h4><p>A tool that installs, updates, removes, and tracks software dependencies.</p><h3>What Now?</h3><p>If you worked through the exercises in this post, you now know more about terminals, shells, build systems, and packaging than I did when I first installed ROS2.</p><p>That matters because ROS2 does not hide these tools. It uses them openly. Every workspace build runs colcon, which calls CMake or setuptools. Every new terminal needs source install/setup.zsh. Every C++ package needs a CMakeLists.txt.</p><p>When these commands show up in ROS2 tutorials, they will no longer feel like magic. You will recognize them as the same tools you just practiced.</p><p>The next step is to install ROS2 and put these tools to use. But now you are doing it with a foundation instead of copying commands blindly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75e50f08ba33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ROS2 from Zero: A No-Code Reference for Beginners]]></title>
            <link>https://medium.com/@shoaib6174/ros2-from-zero-a-no-code-reference-for-beginners-d14c0368d53c?source=rss-9482f5c0f21a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d14c0368d53c</guid>
            <category><![CDATA[ros2]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Mohammad Shoaib]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 05:51:57 GMT</pubDate>
            <atom:updated>2026-06-16T02:41:57.279Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Every core concept you need before writing your first ROS2 node — explained without code.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5QpHpWZUM3xqSnvJE8-FA.png" /></figure><p>When I started learning ROS2, I took notes. Lots of notes. They were useful, but they were messy — a collection of definitions, metaphors, and half-formed questions.</p><p>This post is the cleaned-up version. It covers all the foundational ideas I needed before I wrote my first ROS2 node, organized into one no-code reference.</p><p>If you are starting ROS2 and want the big picture before you touch a terminal, this is for you.</p><p><strong>How to use this post:</strong> Read it once for the overview, then come back to any section when you need a definition.</p><h3>What Is ROS2?</h3><p>ROS2 stands for Robot Operating System 2. The name is misleading.</p><p>ROS2 is <strong>not</strong> an operating system. It is:</p><ul><li>A <strong>communication middleware</strong> — how robot programs talk to each other.</li><li>A set of <strong>tools</strong> for building, running, and debugging robot software.</li><li>A collection of <strong>reusable libraries</strong> for navigation, perception, manipulation, and more.</li><li>A <strong>framework</strong> for organizing code into modular, reusable pieces.</li></ul><p>ROS2 is <strong>not</strong>:</p><ul><li>A programming language. You write C++ or Python.</li><li>A real-time operating system. It runs on Linux.</li><li>An AI framework. It can host AI, but it is not AI itself.</li><li>The robot’s brain. It carries signals; it does not make decisions.</li></ul><p><strong>The simplest definition:</strong> ROS2 is a framework that lets independent robot programs send typed messages to each other over named streams.</p><p><strong>The metaphor:</strong> If your robot is a body, ROS2 is the <strong>nervous system</strong>. It connects muscles, sensors, and the brain. It is not the body, not the muscles, and not the brain.</p><h3>Why Does ROS2 Exist?</h3><p>A robot is not one program. It is many.</p><p>A typical mobile robot might have:</p><ul><li>A LiDAR driver producing scans at 10 Hz.</li><li>A camera driver producing images at 30 Hz.</li><li>A localization algorithm estimating position.</li><li>A path planner deciding where to go.</li><li>A motor controller executing velocity commands.</li><li>A user interface sending goals.</li></ul><p>These programs:</p><ul><li>Run at different rates.</li><li>Are written by different people.</li><li>May fail independently.</li><li>Need to communicate without being tightly tied together.</li></ul><p>Writing all of this as one giant program is possible. It is also a maintenance nightmare. Change the planner, and you risk breaking the LiDAR driver. Add a new sensor, and you rewrite half the system.</p><p>ROS2 solves this by giving each subsystem its own program — called a <strong>node</strong> — and a clean way for nodes to communicate.</p><p><strong>The takeaway:</strong> ROS2 exists because robot software is naturally modular, and modular programs need a communication framework.</p><h3>When Should You Use ROS2?</h3><p>You do not need ROS2 for every robot.</p><p>If you are building a simple robot with one sensor and one motor, a single Python or C++ program may be enough. ROS2 adds overhead: packages, build tools, launch files, and a learning curve.</p><p>Consider ROS2 when:</p><ul><li>Your robot has multiple sensors and actuators.</li><li>Different people work on different subsystems.</li><li>You want to reuse existing libraries like Nav2 or SLAM Toolbox.</li><li>You need to run nodes on multiple machines.</li><li>You want to swap components without rewriting the whole system.</li></ul><p><strong>The takeaway:</strong> ROS2 is a scaling tool. It becomes valuable when a single program is no longer enough.</p><h3>The Compute Graph</h3><p>The central idea of ROS2 is the <strong>compute graph</strong>.</p><p>A compute graph is a live map of how your robot’s programs are connected. It has three basic building blocks.</p><h4>Node</h4><p>A <strong>node</strong> is a single program that does one job.</p><p>Examples:</p><ul><li>A LiDAR driver node reads the sensor and publishes laser scans.</li><li>A path planner node subscribes to sensor data and publishes paths.</li><li>A motor controller node subscribes to velocity commands and drives the motors.</li></ul><p>A node is the unit of computation in ROS2. It is also the unit of modularity. You can start, stop, replace, or debug one node without rewriting the whole system.</p><h4>Topic</h4><p>A <strong>topic</strong> is a named data stream.</p><p>Examples:</p><ul><li>/scan carries laser scan data.</li><li>/cmd_vel carries velocity commands.</li><li>/odom carries odometry estimates.</li></ul><p>Topics are like radio channels. A node broadcasts on a channel. Other nodes tune in. The broadcaster does not know who is listening.</p><h4>Message</h4><p>A <strong>message</strong> is the typed data structure that travels on a topic.</p><p>If a topic is a radio channel, a message is the packet of information being sent. Messages have defined fields and types.</p><p>For example, a velocity command message might have two fields:</p><ul><li>linear — how fast the robot moves forward or backward.</li><li>angular — how fast the robot turns.</li></ul><p>Both fields have a type, such as a decimal number. This agreement on structure lets different nodes understand each other.</p><h3>Publisher and Subscriber</h3><ul><li>A <strong>publisher</strong> sends messages to a topic.</li><li>A <strong>subscriber</strong> receives messages from a topic.</li></ul><p>The LiDAR node is a publisher on /scan. The planner node is a subscriber on /scan. The planner may also be a publisher on /cmd_vel, which the motor controller subscribes to.</p><h3>Decoupling</h3><p>The most important property of the compute graph is <strong>decoupling</strong>.</p><p>The LiDAR node does not know the planner exists. It just publishes /scan. The planner does not know the LiDAR&#39;s internals. It just subscribes to /scan.</p><p>This means:</p><ul><li>You can swap the planner without touching the LiDAR driver.</li><li>You can add a logger or visualizer that also subscribes to /scan.</li><li>You can run nodes on different machines without rewriting them.</li></ul><p><strong>The takeaway:</strong> The compute graph lets you build a robot as a collection of independent, replaceable parts.</p><h3>ROS1 vs ROS2</h3><p>ROS1 was released in 2007 and built for research labs. It worked well but had hard limits.</p><pre>+------------------------------+-------------------------+-------------------------------+<br>| Feature                      | ROS 1                   | ROS 2                         |<br>+------------------------------+-------------------------+-------------------------------+<br>| Communication                | Custom TCP/ROS protocol | DDS (industry-standard)       |<br>| Real-time                    | Not supported           | Supported with extensions     |<br>| Embedded / Microcontrollers  | No                      | Yes, via micro-ROS            |<br>| Security                     | None built-in           | Encryption, authentication    |<br>| Multi-robot                  | Difficult               | Native support                |<br>| Build System                 | catkin                  | colcon + ament                |<br>+------------------------------+-------------------------+-------------------------------+</pre><p>The key change was replacing ROS1’s custom networking layer with <strong>DDS</strong>, a publish-subscribe middleware standard.</p><p>This matters because:</p><ul><li>ROS2 inherits DDS’s reliability, security, and performance.</li><li>ROS2 can communicate with non-ROS systems that also use DDS.</li><li>The ROS2 team no longer maintains a custom transport protocol.</li></ul><p><strong>The takeaway:</strong> ROS2 is not an upgrade to ROS1 with new features. It is a rewrite with a different architecture, built for production robots.</p><h3>DDS: The Hidden Layer</h3><p>DDS stands for Data Distribution Service. It is the middleware underneath ROS2.</p><p>You rarely interact with DDS directly. ROS2’s C++ and Python client libraries wrap it. But understanding that DDS exists explains many ROS2 behaviors.</p><p>DDS handles:</p><ul><li><strong>Discovery:</strong> Nodes find each other automatically. There is no central nameserver like ROS1’s roscore.</li><li><strong>Transport:</strong> Messages move between nodes. This can happen over shared memory, UDP multicast, or the network.</li><li><strong>Quality of Service (QoS):</strong> Rules about reliability, durability, and message history.</li><li><strong>Serialization:</strong> Data is converted to a wire format so it can move between machines.</li></ul><h3>Why UDP Multicast for Discovery?</h3><p>DDS uses UDP multicast for discovery instead of a central nameserver for two reasons:</p><ol><li><strong>No single point of failure.</strong> A central nameserver can crash, become a bottleneck, or require manual configuration. If it goes down, nodes stop discovering each other. With multicast, every node participates in discovery directly.</li><li><strong>Plug-and-play networking.</strong> A new node can join the network, send a multicast announcement, and immediately be discovered. No central registry needs to be started first.</li></ol><h3>DDS vs ROS_DOMAIN_ID</h3><p>There is an important distinction here.</p><ul><li><strong>DDS</strong> is the middleware that makes nodes talk. It handles discovery, transport, serialization, and QoS.</li><li><strong>ROS_DOMAIN_ID</strong> is an environment variable that scopes discovery. Nodes with different domain IDs cannot see each other.</li></ul><p>Think of DDS as the phone network. Think of ROS_DOMAIN_ID as the area code. The network carries the calls; the area code decides which phones ring.</p><p><strong>The takeaway:</strong> DDS does the hard networking work. ROS2 wraps DDS so you do not have to think about it most of the time.</p><h3>Why Publish/Subscribe Fits Robotics</h3><p>ROS2 uses a <strong>publish/subscribe</strong> pattern for most communication. It is not the only option, but it is the default for a reason.</p><p>Consider the alternatives.</p><h4>Direct Function Calls</h4><p>planner.plan(scan_data)</p><p>This is simple but tightly coupled. The planner must know about the scanner. You cannot easily move the planner to another machine or replace the scanner.</p><h4>Shared Memory</h4><p>Both programs agree on a block of memory and read/write it.</p><p>This is fast but brittle. Both sides must agree on the memory layout. It does not work across a network.</p><h4>Request/Response</h4><p>One node asks a question and waits for an answer.</p><p>This is good for occasional queries. It is bad for streaming sensor data because the caller must block and wait for every response.</p><h4>Publish/Subscribe</h4><p>A node publishes data to a topic. Any number of nodes can subscribe.</p><p>Pub/sub wins in robotics because it is:</p><ul><li><strong>Many-to-many:</strong> Multiple nodes can publish or subscribe to the same topic.</li><li><strong>Asynchronous:</strong> The publisher does not wait for subscribers.</li><li><strong>Location-transparent:</strong> Subscribers can be on the same machine, another machine, or another robot.</li><li><strong>Time-decoupled:</strong> With the right QoS settings, a subscriber that starts late can still receive old messages.</li></ul><p><strong>The takeaway:</strong> Pub/sub matches how robots actually produce and consume data: continuously, from many sources, by many consumers.</p><h3>Where ROS2 Sits in the Stack</h3><p>It helps to see where ROS2 fits in a complete robot system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQYft0kZiqu2ITlRfskSkQ.png" /></figure><p>Topics are not the only way nodes communicate. ROS2 also has <strong>services</strong> and <strong>actions</strong>.</p><p>Imagine a robot that can navigate to a room and pick up an object.</p><h3>Services</h3><p>A service is a <strong>synchronous request/response</strong> pattern.</p><p>One node offers a service. Another node calls it and waits for a response.</p><p>Good for:</p><ul><li>“Compute a path from the kitchen to the living room.”</li><li>“What is the robot’s current battery level?”</li><li>“Save the current map to disk.”</li></ul><p>A service uses two message types: a request type and a response type.</p><h3>Actions</h3><p>An action is an <strong>asynchronous goal-oriented</strong> pattern.</p><p>One node asks another to perform a long-running task. The server accepts the goal, sends progress updates, and eventually returns a result. The client can also cancel the goal.</p><p>Good for:</p><ul><li>“Go to the kitchen.” — with updates like “halfway there.”</li><li>“Pick up the object on the table.” — with updates like “arm moving,” “gripping,” “done.”</li><li>“Explore this room.” — with updates on areas covered.</li></ul><p>An action is built from:</p><ul><li>A goal service</li><li>A feedback topic</li><li>A result topic</li><li>A cancel service</li></ul><h3>How They Relate to Topics and Messages</h3><p>Services and actions are not separate core building blocks. They are <strong>communication patterns built on top of nodes, topics, and messages</strong>.</p><p>PatternTimingBest ForTopic (pub/sub)AsynchronousContinuous data streamsServiceSynchronousOne-off queries and commandsActionAsynchronous with feedbackLong-running tasks</p><p><strong>The takeaway:</strong> Use topics for streaming data, services for questions, and actions for goals.</p><h3>ROS2 Communication Interfaces</h3><p>Before nodes can communicate, they must agree on what the data looks like. ROS2 uses <strong>interface files</strong> to define these agreements.</p><p>There are three types.</p><h3>.msg Files</h3><p>A .msg file defines the fields of a topic message.</p><p>For example, a velocity command message might be defined like this:</p><pre>float64 linear<br>float64 angular</pre><p>It is like defining the columns of a table or the fields of a struct.</p><h3>.srv Files</h3><p>A .srv file defines the request and response messages for a service.</p><p>It has two parts separated by three dashes:</p><pre>float64 target_x<br>float64 target_y<br>---<br>bool success<br>string message</pre><p>The top half is what the client sends. The bottom half is what the server replies with.</p><h3>.action Files</h3><p>An .action file defines the goal, result, and feedback messages for an action.</p><p>It has three parts separated by three dashes:</p><pre>string room_name<br>---<br>bool arrived<br>---<br>float64 percent_complete</pre><p>The first part is the goal. The second part is the final result. The third part is ongoing feedback.</p><h3>Interface Definition Language</h3><p>ROS2 uses an <strong>Interface Definition Language (IDL)</strong> to describe these communication contracts. IDL lets nodes written in different languages agree on the shape of the data.</p><p><strong>The takeaway:</strong> Interfaces are contracts. They ensure that a publisher and subscriber, or a client and server, agree on what data is being exchanged.</p><h3>Quality of Service (QoS)</h3><p>QoS is worth a brief mention because it shows up everywhere in ROS2.</p><p>QoS policies let you control how messages are delivered. The two most important policies for beginners are:</p><ul><li><strong>Reliability:</strong> Should the middleware guarantee delivery, or is it okay to drop messages?</li><li><em>Reliable:</em> Resend lost messages. Good for commands.</li><li><em>Best-effort:</em> Deliver if possible, but do not retry. Good for high-frequency sensor data where old messages are useless.</li><li><strong>Durability:</strong> Should new subscribers receive old messages?</li><li><em>Volatile:</em> Only deliver messages published after the subscriber starts.</li><li><em>Transient-local:</em> Keep the last message and deliver it to late subscribers. Useful for things like a map that does not change often.</li></ul><p>QoS is part of DDS, and ROS2 exposes it directly. A common beginner mistake is mismatched QoS: a reliable publisher talking to a best-effort subscriber can behave unexpectedly.</p><p><strong>The takeaway:</strong> QoS lets you tune the trade-off between reliability and performance for each topic.</p><h3>Key Vocabulary</h3><ul><li><strong>Node: </strong>A program that performs computation. The unit of modularity.</li><li><strong>Topic: </strong>A named bus over which nodes exchange messages.</li><li><strong>Message: </strong>A typed data structure sent over a topic.</li><li><strong>Publisher: </strong>A node that sends messages to a topic.</li><li><strong>Subscriber: </strong>A node that receives messages from a topic.</li><li><strong>Service </strong>A request/response mechanism for one-off queries.</li><li><strong>Action </strong>A goal-oriented mechanism with feedback and result.</li><li><strong>Parameter: </strong>A per-node configuration value.</li><li><strong>DDS: </strong>The middleware under ROS2 that handles discovery and transport.</li><li><strong>QoS: </strong>Quality of Service policies for reliability and message history.</li><li><strong>ROS_DOMAIN_ID: </strong>An environment variable that scopes which nodes can discover each other.</li></ul><h3>Common Misconceptions</h3><p>These are easy traps to fall into as a beginner.</p><h4>“ROS2 is an operating system.”</h4><p>No. It runs on top of Linux. It is middleware.</p><h4>“ROS2 is the robot’s brain.”</h4><p>No. It carries signals. Intelligence lives in the nodes you write.</p><h4>“You need ROS2 to build any robot.”</h4><p>No. You can write raw C++ or Python that talks directly to hardware. ROS2 makes organization and scaling easier, but it is optional for simple robots.</p><h4>“ROS2 handles real-time.”</h4><p>Not by default. It can be part of a real-time system, but that requires extra design.</p><h4>“Nodes must run as separate processes.”</h4><p>No. ROS2 supports multi-process nodes and single-process composition. Multi-process is safer because a crash isolates to one node. Single-process can be faster because communication may avoid copying data.</p><h3>Quick Reference: Topic vs Service vs Action</h3><h3>Topic</h3><ul><li><strong>Pattern:</strong> Publish/subscribe</li><li><strong>Timing:</strong> Asynchronous</li><li><strong>Best for:</strong> Continuous data streams</li><li><strong>Example:</strong> /scan, /cmd_vel</li><li><strong>Built from:</strong> Node + topic + message</li></ul><h3>Service</h3><ul><li><strong>Pattern:</strong> Request/response</li><li><strong>Timing:</strong> Synchronous</li><li><strong>Best for:</strong> One-off queries and commands</li><li><strong>Example:</strong> “Get current robot state”</li><li><strong>Built from:</strong> Node + service + two messages</li></ul><h3>Action</h3><ul><li><strong>Pattern:</strong> Goal + feedback + result</li><li><strong>Timing:</strong> Asynchronous</li><li><strong>Best for:</strong> Long-running tasks</li><li><strong>Example:</strong> “Go to the kitchen”</li><li><strong>Built from:</strong> Node + service + topics + three messages</li></ul><h3>The One-Page Mental Model</h3><p>If you only remember one thing, remember this:</p><blockquote><em>ROS2 lets independent robot programs talk to each other through named, typed data streams.</em></blockquote><p>A robot is many programs: sensors, planners, controllers. Each becomes a <strong>node</strong>. Nodes send <strong>messages</strong> on <strong>topics</strong>. The live wiring diagram of nodes and topics is the <strong>compute graph</strong>.</p><p>Under the hood, <strong>DDS</strong> handles discovery, transport, and serialization. ROS2 wraps DDS so you can focus on robot logic instead of networking.</p><p>For occasional queries, nodes use <strong>services</strong>. For long tasks with progress updates, they use <strong>actions</strong>. These patterns are built on top of the same nodes, topics, and messages.</p><p>That is the whole foundation. Everything else — packages, launch files, build tools, simulators — exists to support this idea.</p><h3>What to Learn Next</h3><p>This post covers the philosophy of ROS2. The next steps are practical:</p><ul><li><strong>Workspaces and packages:</strong> How ROS2 code is organized.</li><li><strong>URDF:</strong> How to describe a robot’s physical structure.</li><li><strong>Publishers and subscribers in practice:</strong> Writing nodes that talk over topics.</li><li><strong>Services and actions in practice:</strong> Implementing request/response and goal-oriented behavior.</li><li><strong>Launch files:</strong> Starting many nodes at once.</li></ul><p>Each of these builds on the mental model above. Get the model right, and the tools become much easier.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d14c0368d53c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I Got Wrong About ROS2 (And the Mental Model That Finally Clicked)]]></title>
            <link>https://medium.com/@shoaib6174/what-i-got-wrong-about-ros2-and-the-mental-model-that-finally-clicked-eea090e69d62?source=rss-9482f5c0f21a------2</link>
            <guid isPermaLink="false">https://medium.com/p/eea090e69d62</guid>
            <category><![CDATA[robot-framework]]></category>
            <category><![CDATA[ros2]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Mohammad Shoaib]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 05:18:05 GMT</pubDate>
            <atom:updated>2026-06-15T05:18:05.560Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A beginner-friendly explanation of what ROS2 actually is — no code, no jargon, just the ideas.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ml3RYJyq4sUG4wW3R0wy9A.png" /></figure><p>Back in 2024, I decided to learn ROS2.</p><p>I spent the first five days just trying to install it. I tried macOS first, then realized I needed Linux, then fought version mismatches, then finally got a simulator running — without understanding a single thing I had done.</p><p>I could launch a robot. I could make it move. But I had no idea what was actually happening under the hood.</p><p>The problem wasn’t ROS2. The problem was where I started. I started with tools, commands, and tutorials. What I needed was a mental model.</p><p>This post is the explanation I wish I had read on day one.</p><h3>Misconception 1: “ROS2 is an operating system”</h3><p>When I first heard “Robot Operating System,” I pictured something that boots up the robot and runs everything.</p><p>That is not what ROS2 is.</p><p>ROS2 is <strong>middleware</strong>. It sits on top of a real operating system — usually Linux — and helps programs talk to each other. It does not replace Linux. It does not manage memory, schedule tasks, or drive the screen.</p><p>Think of it this way: Linux is the body. Your robot programs are the muscles and senses. ROS2 is the <strong>nervous system</strong> that carries signals between them.</p><p>You still need the body. You still need the muscles. But without the nervous system, nothing coordinates.</p><p><strong>The takeaway:</strong> ROS2 does not run the robot. It organizes how the robot’s programs communicate.</p><h3>Misconception 2: “ROS2 is the robot’s brain”</h3><p>If ROS2 is not the operating system, maybe it is the intelligence — the thing that decides where to go and what to do.</p><p>Nope.</p><p>ROS2 does not decide anything. It carries decisions. If you write a program that plans a path, ROS2 helps that program send the plan to the motors. If you write a program that reads a camera, ROS2 helps that program share the image with the planner.</p><p>The brain is the code <em>you</em> write. ROS2 is the network of nerves that lets that brain reach the rest of the robot.</p><p><strong>The takeaway:</strong> ROS2 is not intelligent. It lets intelligent programs talk to the rest of the system.</p><h3>Misconception 3: “ROS2 is very hard to understand”</h3><p>This one held me back the longest.</p><p>ROS2 <em>looks</em> hard because the surface is cluttered. There are packages, workspaces, launch files, build tools, simulators, and a hundred commands. If you start there, it feels overwhelming.</p><p>But the core idea is simple.</p><p>ROS2 is a way for independent programs to send typed messages to each other over named streams. That is almost the entire story.</p><p>The rest is tooling. The tooling matters, but it only makes sense once you understand the core idea.</p><p>It is like learning to drive. If you start by memorizing every button in the cockpit, it feels impossible. If you start with the idea that turning the wheel moves the tires, the cockpit becomes manageable.</p><p><strong>The takeaway:</strong> Start with the mental model. The tools become understandable afterwards.</p><h3>Misconception 4: “ROS2 handles real-time”</h3><p>Robots need precise timing. Motors must respond quickly. Sensors must stream continuously. So I assumed ROS2 guaranteed all of that.</p><p>It does not — at least not by default.</p><p>ROS2 is fast and reliable enough for many real robots. But if you need hard real-time guarantees, you need extra pieces: a real-time kernel, the right middleware settings, and careful node design.</p><p>ROS2 gives you the <em>infrastructure</em>. Real-time is a property of the whole system, not a switch you flip.</p><p><strong>The takeaway:</strong> ROS2 is not a real-time operating system. It can be part of a real-time system, but that requires deliberate design.</p><h3>The Unifying Model: Nodes, Topics, and the Compute Graph</h3><p>Once the misconceptions fell away, the real model became clear.</p><p>A ROS2 system is a <strong>compute graph</strong>. It has three basic pieces:</p><ul><li><strong>Node:</strong> an independent program that does one job. A LiDAR driver. A path planner. A motor controller.</li><li><strong>Topic:</strong> a named data stream. /scan for laser data. /cmd_vel for movement commands.</li><li><strong>Message:</strong> the typed data structure that travels on a topic.</li></ul><p>A node publishes messages to a topic. Other nodes subscribe to that topic and receive the messages.</p><p>The powerful part is <strong>decoupling</strong>. The LiDAR node does not know who subscribes to /scan. It just publishes. The planner subscribes without knowing who publishes. You can replace either one without breaking the other.</p><p>This is why ROS2 scales. You can start with a simple robot, then add a camera, swap the planner, or move a node to another machine — all without rewriting the whole system.</p><p><strong>The takeaway:</strong> ROS2 is a communication framework for independent robot programs. The compute graph is the live map of how those programs connect.</p><h3>The Hidden Layer: DDS</h3><p>Underneath ROS2 is something called DDS, which stands for Data Distribution Service.</p><p>You do not need to understand DDS deeply to use ROS2. But knowing it exists explains a lot.</p><p>DDS handles three things for you:</p><ul><li><strong>Discovery:</strong> nodes find each other automatically, with no central server.</li><li><strong>Transport:</strong> messages move between nodes, whether they are in the same process or on different machines.</li><li><strong>Quality of service:</strong> you can set rules about reliability, history, and durability.</li></ul><p>That is why ROS2 works across a network almost for free. That is why you do not need to manually connect every node. DDS does the plumbing.</p><p><strong>The takeaway:</strong> ROS2 wraps DDS. DDS handles the hard networking so you can focus on robot logic.</p><h3>So, What Is ROS2 Really?</h3><p>ROS2 is middleware that lets independent programs talk to each other through named, typed data streams.</p><p>That is it. Everything else — packages, launch files, simulators, build tools — exists to support that idea.</p><p>If you are building a robot with one sensor and one motor, you might not need ROS2. You can write a single program. But once you have multiple sensors, multiple algorithms, and multiple actuators, you need a way to organize the chaos.</p><p>That is when ROS2 becomes valuable.</p><h3>Final Thought</h3><p>I spent my first week with ROS2 fighting installations and copy-pasting commands. I was learning the cockpit before I understood the car.</p><p>If I could go back, I would start with this question: <em>What problem does ROS2 solve?</em></p><p>The answer: robots are many independent programs that need to talk. ROS2 is the framework that lets them talk cleanly, reliably, and at scale.</p><p>Start there, and the rest becomes much easier.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eea090e69d62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Match ROS 2, Gazebo, and PyTorch CUDA Versions - For Any Ubuntu and GPU]]></title>
            <link>https://medium.com/@shoaib6174/how-to-match-ros-2-gazebo-and-pytorch-cuda-versions-for-any-ubuntu-and-gpu-fbfc7bb8ba23?source=rss-9482f5c0f21a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbfc7bb8ba23</guid>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[ros2]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[gazebo]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Mohammad Shoaib]]></dc:creator>
            <pubDate>Sat, 07 Mar 2026 11:07:39 GMT</pubDate>
            <atom:updated>2026-03-07T13:48:57.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dBep66MrsWl-ya-R71_QLw.png" /></figure><p><strong>TL;DR: ROS 2 distro, Gazebo version, CUDA toolkit, and PyTorch build must all match your Ubuntu version and GPU architecture. This guide gives you the decision process, not just commands to copy-paste, so it works regardless of when you’re reading it.</strong></p><p>The first time, I tried to install ros2 with gazebo, it took me 5 days and three OS. This time, I had an RTX 5090, a fresh Ubuntu 24.04 install, and three “definitive” ROS 2 tutorials open in browser tabs. Eight hours later, I had a broken Python environment, a Gazebo window rendering on CPU, and a PyTorch install that silently refused to touch the GPU.</p><p>The tutorials/documentations weren’t wrong, they were written for Ubuntu 22.04, Humble, and RTX 30-series cards. I was one Ubuntu version, one ROS distro, and two GPU generations ahead of every guide on the internet.</p><p>Here’s everything I figured out, structured so you can get the same stack running in 30 minutes instead of hours or even days.</p><h3>The Version Chain (This Is the Whole Post in Two Lines)</h3><pre>Ubuntu version → ROS 2 distro → Gazebo version<br>GPU model → compute capability → PyTorch CUDA build</pre><p>Every problem in this guide traces back to getting one of these arrows wrong. The rest of the post teaches you how to resolve each arrow correctly.</p><h3>Before You Start: Know Your System</h3><p>Run these commands and write down the results. You’ll need them for every decision that follows.</p><pre># Ubuntu version and codename<br>lsb_release -a<br># GPU model, driver version, CUDA version (top-right corner of output)<br>nvidia-smi<br># Python version<br>python3 --version<br># Display server (matters for Gazebo rendering)<br>echo $XDG_SESSION_TYPE</pre><p>For my machine, this gave me:</p><ul><li>Ubuntu 24.04 LTS (Noble)</li><li>RTX 5090, Driver 580.126, CUDA 13.0</li><li>Python 3.12.3</li><li>X11</li></ul><p>Your numbers will be different, but the process is the same.</p><h3>Part 1: Picking the Right ROS 2 Distro (~2 minutes)</h3><p>This is the decision everything else depends on. ROS 2 distros are locked to specific Ubuntu versions. There’s no way around this - the binary packages literally don’t exist for other Ubuntu releases.</p><h4>How to Find Your Match</h4><p>Check the <a href="https://docs.ros.org/en/rolling/Releases.html">ROS 2 Distributions page</a>:</p><p>Ubuntu VersionROS 2 DistroStatus22.04 JammyHumbleLTS, supported until 202724.04 NobleJazzyLTS, supported until 2029</p><p>The rule is simple: use the LTS distro that targets your Ubuntu version.</p><p>I made the mistake of initially planning for Humble because every tutorial uses it. On Ubuntu 24.04, apt install ros-humble-desktop returns &quot;package not found.&quot; There&#39;s no workaround that&#39;s worth the trouble - no PPA, no manual build, no Docker hack that doesn&#39;t add layers of complexity. Just use Jazzy. The API is 95% identical to Humble.</p><blockquote><em>“Should I just use Docker?” If you only need ROS 2 (no GPU, no Gazebo GUI), Docker is fine. But if you need GPU-accelerated PyTorch AND Gazebo rendering, Docker adds real complexity: NVIDIA Container Toolkit, X11 socket forwarding, GPU passthrough config. For a development machine where you’ll be iterating daily, native install is less friction. Save Docker for CI/CD and deployment.</em></blockquote><h3>Part 2: Picking the Right Gazebo Version (~1 minute)</h3><p>Gazebo versions are paired with ROS 2 distros. The integration packages (ros-&lt;distro&gt;-ros-gz) are compiled against a specific Gazebo release. Mix them and you get ABI errors.</p><h4>How to Find Your Match</h4><p>Check the <a href="https://gazebosim.org/docs/harmonic/ros_installation/">official pairing table</a>:</p><ul><li>Humble → Fortress (Gz Sim 6) → ros-humble-ros-gz</li><li>Jazzy → Harmonic (Gz Sim 8) → ros-jazzy-ros-gz</li></ul><p>ROS 2 DistroGazebo VersionIntegration PackageHumbleFortress (Gz Sim 6)ros-humble-ros-gzJazzyHarmonic (Gz Sim 8)ros-jazzy-ros-gz</p><p>If you’re on Jazzy, you use Harmonic. Period.</p><p>Naming confusion alert: “Gazebo” has been rebranded. The old simulator (Gazebo 9, 11) is now “Gazebo Classic” and is deprecated. The new one — formerly “Ignition Gazebo” — is just “Gazebo.” You’ll use the gz command, not the old gazebo command. If a tutorial tells you to run gazebo, it&#39;s outdated.</p><h3>Part 3: The Installation (~15 minutes)</h3><p>Now that we know what versions to install, let’s do it.</p><h4>Prep Work</h4><pre># Fix locale (prevents build warnings down the line)<br>sudo locale-gen en_US.UTF-8<br>sudo update-locale LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8<br># Update everything first - ROS 2 depends on system libraries like libc6.<br># Stale versions cause mysterious conflicts.<br>sudo apt update &amp;&amp; sudo apt upgrade -y<br># Prerequisites<br>sudo apt install -y software-properties-common curl mesa-utils</pre><p>Before going further, verify your GPU is actually rendering:</p><pre>glxinfo | grep &quot;OpenGL renderer&quot;</pre><p>You should see your NVIDIA GPU name here. If it says llvmpipe, your NVIDIA drivers aren&#39;t set up correctly - fix that first, or Gazebo will either crash or render on CPU.</p><blockquote><em>Wayland users: Gazebo’s rendering engine (Ogre2) works best on X11. If you’re on a Wayland session and Gazebo shows a black screen, log out and select “GNOME on Xorg” at the login screen.</em></blockquote><h4>Install ROS 2</h4><p>Replace jazzy and noble with your target distro and Ubuntu codename if different.</p><pre># Add the ROS 2 GPG key<br>sudo curl -sSL https://raw.githubusercontent.com/ros/rosdistro/master/ros.key \<br> -o /usr/share/keyrings/ros-archive-keyring.gpg<br># Add the repository<br>echo &quot;deb [arch=amd64 signed-by=/usr/share/keyrings/ros-archive-keyring.gpg] \<br>  http://packages.ros.org/ros2/ubuntu noble main&quot; | \<br>  sudo tee /etc/apt/sources.list.d/ros2.list<br>sudo apt update<br># Install ROS 2 desktop (includes RViz, rclpy, demo nodes)<br>sudo apt install -y ros-jazzy-desktop<br># Build tools<br>sudo apt install -y python3-colcon-common-extensions python3-rosdep<br># Initialize rosdep<br>sudo rosdep init 2&gt;/dev/null || true<br>rosdep update</pre><p>Verify it works:</p><pre>source /opt/ros/jazzy/setup.bash  # use setup.zsh if you&#39;re a zsh user<br>ros2 topic list</pre><p>You should see /parameter_events and /rosout. If you do, ROS 2 is alive.</p><h4>Install Gazebo + ROS Integration</h4><pre># This pulls in Gazebo Harmonic automatically<br>sudo apt install -y ros-jazzy-ros-gz<br># For robot simulation with ros2_control<br>sudo apt install -y ros-jazzy-gz-ros2-control</pre><p>Verify:</p><pre>gz sim --version<br># Expected: Gazebo Sim, version 8.x.x</pre><p>Now the real test — run this on your desktop (not over SSH):</p><pre>gz sim shapes.sdf</pre><p>A 3D window should open with colored shapes. If it renders smoothly, your GPU + Gazebo pipeline is working.</p><blockquote><em>Running on a headless server or via SSH? Gazebo needs a display for rendering. If your GPU machine is headless, use </em><a href="https://rustdesk.com/"><em>RustDesk</em></a><em> (free, open-source) or VNC for remote desktop access. RustDesk handles GPU-accelerated 3D rendering over the network with minimal setup.</em></blockquote><h4>Install Common Robotics Packages</h4><p>Most robotics projects need navigation, robot control, and description tools:</p><pre># Navigation stack<br>sudo apt install -y ros-jazzy-navigation2 ros-jazzy-nav2-bringup<br># Robot control framework<br>sudo apt install -y ros-jazzy-ros2-control ros-jazzy-ros2-controllers<br># URDF/Xacro tools<br>sudo apt install -y ros-jazzy-xacro \<br>  ros-jazzy-robot-state-publisher \<br>  ros-jazzy-joint-state-publisher-gui</pre><p>Quick sanity check:</p><pre># Should show ~34 nav2 packages<br>ros2 pkg list | grep -c nav2<br># Should show controller_manager, ros2_control, etc.<br>ros2 pkg list | grep ros2_control</pre><h3>Part 4: The Python Virtual Environment Trap (~5 minutes)</h3><p>This is the section that breaks most ML-robotics setups -and the fix is one flag.</p><p>If you’re doing any ML/AI work alongside ROS 2 - running YOLO for object detection, using LangChain for an LLM agent - you need pip packages. And pip packages should live in a virtual environment.</p><p>The trap: a standard Python venv can’t see ROS 2 packages. You’ll get ModuleNotFoundError: No module named &#39;rclpy&#39; and wonder what went wrong.</p><p>ROS 2 installs rclpy and other Python bindings under /opt/ros/jazzy/lib/python3.12/site-packages/. A normal venv isolates itself from system packages, which means import rclpy fails inside the venv.</p><h4>The Fix</h4><p>Create the venv with --system-site-packages:</p><pre>cd ~/your_project &amp;&amp; python3 -m venv --system-site-packages venv<br>source venv/bin/activate<br>pip install --upgrade pip</pre><p>This gives you the best of both worlds:</p><ul><li>ROS 2 packages (rclpy, etc.) are visible through the system site-packages</li><li>Anything you pip install goes into the venv, isolated from the system</li></ul><h4>The Source Order Gotcha</h4><p>When setting up your terminal, always source ROS first, then activate the venv:</p><pre>source /opt/ros/jazzy/setup.bash   # FIRST<br>source ~/your_project/venv/bin/activate  # SECOND</pre><p>Why? The ROS setup script adds its Python paths to PYTHONPATH. Then venv activation prepends the venv&#39;s site-packages. This layering means your pip packages take priority, with ROS packages as a fallback.</p><p>Reverse the order and PYTHONPATH gets mangled - your venv packages won&#39;t take priority, and you&#39;ll get version conflicts that are impossible to debug.</p><h4>Packages That Will Bite You</h4><p>Some Python packages exist in both the ROS 2 apt world and the pip world. Installing both leads to version conflicts:</p><ul><li>PyYAML — ROS 2 provides it (python3-yaml). Do NOT pip install. This is the #1 source of cryptic import errors.</li><li>NumPy — Usually provided by system apt. Pip installing a newer version is usually fine.</li><li>OpenCV — Not in base ROS 2. Safe to pip install.</li></ul><p>Rule of thumb: run apt list --installed | grep python3-&lt;package&gt; first. If it&#39;s there, don&#39;t pip install it.</p><h3>Part 5: PyTorch with GPU Support (~10 minutes)</h3><p>This section is where I lost the most time. Getting PyTorch to actually use your GPU requires matching three things:</p><ol><li>Your GPU’s compute capability (hardware)</li><li>Your CUDA driver version (system)</li><li>The PyTorch CUDA build (pip package)</li></ol><h4>Step 1: Find Your GPU’s Compute Capability</h4><p>Every NVIDIA GPU has a “compute capability” version that determines what CUDA features it supports. Find yours at <a href="https://developer.nvidia.com/cuda-gpus">NVIDIA’s CUDA GPUs page</a>:</p><ul><li>RTX 20xx — Turing — sm_75</li><li>RTX 30xx — Ampere — sm_86</li><li>RTX 40xx — Ada Lovelace — sm_89</li><li>RTX 50xx — Blackwell — sm_120</li></ul><h4>Step 2: Check Your CUDA Driver</h4><pre>nvidia-smi</pre><p>Look at the top-right of the output for CUDA Version: XX.X. This is the maximum CUDA toolkit version your driver supports. Your PyTorch CUDA build must be at or below this version.</p><h4>Step 3: Find a Compatible PyTorch Build</h4><p>PyTorch publishes separate builds for different CUDA versions. Here’s how to check what’s available:</p><pre>pip index versions torch --index-url https://download.pytorch.org/whl/cu124<br>pip index versions torch --index-url https://download.pytorch.org/whl/cu126<br>pip index versions torch --index-url https://download.pytorch.org/whl/cu128</pre><h4>The Compatibility Rules</h4><p>CUDA driver backward compatibility: The CUDA driver version (shown by nvidia-smi) must be &gt;= the CUDA toolkit version in the PyTorch wheel. So a cu124 build works fine on a system with CUDA driver 12.8 or 13.0 - the driver is newer than the toolkit, which is fine.</p><p>GPU architecture support: This is where it gets tricky. Each PyTorch build only includes pre-compiled kernels for certain GPU architectures. If your GPU isn’t included, PyTorch will either:</p><ul><li>Show a compatibility warning and attempt PTX fallback (may work with degraded performance)</li><li>Throw a hard runtime error (“no kernel image is available for execution on the device”)</li><li>In some cases, silently fall back to CPU</li></ul><p>Here’s a reference for which CUDA builds support which GPUs:</p><ul><li>RTX 20xx (Turing, sm_75) — cu102+ — Generally works with most builds</li><li>RTX 30xx (Ampere, sm_86) — cu113+ — “sm_86 not compatible” warning with older</li><li>RTX 40xx (Ada, sm_89) — cu118+ — “sm_89 not compatible” warning with older</li><li>RTX 50xx (Blackwell, sm_120) — cu128 — Warnings or runtime errors with older builds</li></ul><p>I learned this the hard way. My RTX 5090 (Blackwell, sm_120) showed compatibility warnings with both cu124 and cu126 builds. While basic tensor operations seemed to work via PTX fallback, this isn&#39;t reliable - some operations can fail at runtime. Only cu128 (specifically PyTorch 2.10.0+cu128, which I tested) included native sm_120 kernels and ran completely warning-free.</p><h4>The Install (Order Matters!)</h4><pre>source venv/bin/activate<br># Install PyTorch FIRST with the correct CUDA version<br># I tested with 2.10.0+cu128 on an RTX 5090 - adjust the index URL for your GPU<br>pip install torch torchvision --index-url https://download.pytorch.org/whl/cu128</pre><p>Critical: Install PyTorch before any package that depends on it — especially ultralytics (YOLO). If you pip install ultralytics first, it auto-installs CPU-only PyTorch as a dependency. Then you have to uninstall and reinstall torch with the CUDA version, which can leave broken state.</p><p>The correct order:</p><pre># 1. GPU PyTorch first<br>pip install torch torchvision --index-url https://download.pytorch.org/whl/cu128<br># 2. THEN packages that depend on it<br>pip install ultralytics  # Will use the GPU torch you just installed</pre><blockquote><em>For reference: I tested with PyTorch 2.10.0+cu128 on an RTX 5090 with CUDA 13.0 driver, and everything worked without warnings. If you’re on a different GPU, adjust the CUDA index URL accordingly.</em></blockquote><h4>Verify Everything Works</h4><pre>import torch<br>print(f&quot;PyTorch: {torch.__version__}&quot;)<br>print(f&quot;CUDA available: {torch.cuda.is_available()}&quot;)<br>print(f&quot;GPU: {torch.cuda.get_device_name(0)}&quot;)<br>print(f&quot;Compute capability: {torch.cuda.get_device_capability(0)}&quot;)<br># Actually test GPU computation<br>x = torch.randn(1000, 1000).cuda()<br>y = x @ x.T<br>print(f&quot;GPU computation: OK&quot;)</pre><p>Expected output (your specifics will differ):</p><pre>PyTorch: 2.10.0+cu128<br>CUDA available: True<br>GPU: NVIDIA GeForce RTX 5090<br>Compute capability: (12, 0)<br>GPU computation: OK</pre><p>If you see CUDA available: False, you installed CPU-only PyTorch. Go back and reinstall with --index-url. If you see a &quot;sm_XXX is not compatible&quot; warning, your CUDA build is too old for your GPU. Step up (cu124 → cu126 → cu128).</p><h3>Part 6: Make It Permanent (~1 minute)</h3><p>Add ROS 2 sourcing to your shell config so you don’t have to type it every time:</p><pre># For bash users - add to ~/.bashrc<br>echo &#39;source /opt/ros/jazzy/setup.bash&#39; &gt;&gt; ~/.bashrc<br># For zsh users - add to ~/.zshrc<br>echo &#39;source /opt/ros/jazzy/setup.zsh&#39; &gt;&gt; ~/.zshrc</pre><h3>References</h3><p>Everything below is designed to be referenced after your first read-through. Bookmark and come back when you need a quick lookup.</p><h4>Version Pairing Matrix</h4><ul><li>22.04 → Humble → Fortress (Gz 6) → Python 3.10</li><li>24.04 → Jazzy → Harmonic (Gz 8) → Python 3.12</li></ul><p>UbuntuROS 2GazeboPython22.04HumbleFortress (Gz 6)3.1024.04JazzyHarmonic (Gz 8)3.12</p><h4>GPU + PyTorch Matrix</h4><ul><li>RTX 20xx — Turing (sm_75) — cu102+</li><li>RTX 30xx — Ampere (sm_86) — cu113+</li><li>RTX 40xx — Ada (sm_89) — cu118+</li><li>RTX 50xx — Blackwell (sm_120) — cu128</li></ul><p>GPUArchitectureTested CUDA BuildRTX 20xxTuring (sm_75)cu102+RTX 30xxAmpere (sm_86)cu113+RTX 40xxAda (sm_89)cu118+RTX 50xxBlackwell (sm_120)cu128</p><h4>Common Commands</h4><pre># Source ROS 2 (do this in every terminal)<br>source /opt/ros/jazzy/setup.bash<br># Launch Gazebo with a world file<br>gz sim your_world.sdf<br># Check ROS 2 is running<br>ros2 topic list<br># Build your ROS 2 package<br>colcon build --packages-select your_package<br>source install/setup.bash<br># Check PyTorch GPU<br>python3 -c &quot;import torch; print(torch.cuda.is_available(), torch.cuda.get_device_name(0))&quot;</pre><h3>Troubleshooting Cheat Sheet</h3><p>“Package ros-humble-desktop not found” You’re on Ubuntu 24.04 trying to install Humble. Use Jazzy instead. Check your Ubuntu codename with lsb_release -cs.</p><p>Gazebo black screen or crash Check glxinfo | grep &quot;OpenGL renderer&quot;. If it doesn&#39;t show your NVIDIA GPU, fix your drivers. If you&#39;re on Wayland, switch to X11 at the login screen.</p><p>import rclpy fails in venv You created the venv without --system-site-packages. Delete it and recreate:</p><pre>rm -rf venv &amp;&amp; python3 -m venv --system-site-packages venv</pre><p>PyTorch CUDA not available Check python3 -c &quot;import torch; print(torch.__version__)&quot;. If the version doesn&#39;t end with +cuXXX, you installed CPU-only PyTorch. Reinstall with --index-url.</p><p>“sm_XXX is not compatible” warning Your CUDA build doesn’t include kernels for your GPU. Move to a newer build (cu124 → cu126 → cu128).</p><p>PyYAML import errors after pip install Uninstall the pip version: pip uninstall pyyaml. ROS 2 already provides it.</p><h3>What This Gets You</h3><p>Once everything above is working, you have a full robotics + ML development stack:</p><ul><li>ROS 2 Jazzy for robot middleware (topics, services, actions, launch files)</li><li>Gazebo Harmonic for 3D physics simulation with GPU-accelerated rendering</li><li>Nav2 for autonomous navigation (path planning, obstacle avoidance, SLAM)</li><li>ros2_control for robot joint control (arm manipulation, differential drive)</li><li>PyTorch + CUDA for GPU-accelerated deep learning (YOLO object detection, LLM inference)</li><li>A clean Python venv that sees both ROS 2 and pip packages without conflicts</li></ul><p>This is the foundation for projects like autonomous mobile manipulation, sim-to-real transfer, or LLM-powered robot task planning.</p><h3>The Bottom Line</h3><p>Version matching is the entire game. The actual install commands are trivial — it’s knowing <em>which</em> versions to install that eats your day.</p><p>One more time:</p><pre>Ubuntu version → ROS 2 distro → Gazebo version<br>GPU model → compute capability → PyTorch CUDA build</pre><p>Get those two chains right and you’re up in 30 minutes. Get them wrong and you’re in dependency hell until 2 AM.</p><p>The approach here — checking official compatibility tables, using pip index versions to discover builds, verifying with smoke tests - works regardless of when you&#39;re reading this. New Ubuntu versions, new ROS distros, new GPUs will keep coming. The version-matching process stays the same.</p><p>If this saved you time, I’m writing a follow-up series on building an LLM-powered robot task planner with this stack — natural language commands to robot actions using ROS 2, Gazebo, YOLO, and GPT-4. Follow me to catch it.</p><p>Hit a problem not covered here? Drop a comment with your Ubuntu version, GPU, and the error message. I’ll update the troubleshooting section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbfc7bb8ba23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing NMPC with CasADi: Cart-Pole System]]></title>
            <link>https://medium.com/@shoaib6174/implementing-nmpc-with-casadi-cart-pole-system-62f1d72f2efa?source=rss-9482f5c0f21a------2</link>
            <guid isPermaLink="false">https://medium.com/p/62f1d72f2efa</guid>
            <category><![CDATA[optimal-control]]></category>
            <category><![CDATA[robotics-automation]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Mohammad Shoaib]]></dc:creator>
            <pubDate>Wed, 16 Apr 2025 12:16:29 GMT</pubDate>
            <atom:updated>2025-04-16T12:23:40.684Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In today’s rapidly evolving technological landscape, achieving robust control in nonlinear and dynamically uncertain environments has become paramount. <strong>Nonlinear Model Predictive Control (NMPC)</strong> stands out as a versatile and powerful method to tackle such challenges. Unlike traditional control methods that often rely on linear assumptions, NMPC leverages a mathematical optimization framework to handle complex system dynamics and constraints in real time.</p><p>This blog post aims to guide you through the journey of formulating a basic optimal control problem using CasADi, ultimately implementing a simple NMPC controller. We will use a representative system (such as the classic cart-pole setup) as our running example. By the end of this blog, you will have a clear understanding of:</p><ul><li><strong>Theoretical Foundations: </strong>A brief recap of optimal control concepts and the motivation behind NMPC.</li><li><strong>Practical Implementation: </strong>How to build and solve an NMPC problem using direct methods (collocation or shooting techniques) with CasADi.</li><li><strong>Simulation and Analysis:</strong> How to simulate the controller’s performance on a nonlinear system, with a discussion on the results and possible improvements.</li></ul><p>This comprehensive approach is targeted toward readers with some background in control theory who are looking to deepen their understanding and practical skills in advanced control strategies.</p><h3>Fundamentals of Optimal Control</h3><p>Optimal control is a branch of control theory focused on finding a control law that will minimize (or maximize) a given cost function over a predefined time horizon, subject to system dynamics and constraints. The key elements include:</p><p><strong>Cost Function:</strong> Often expressed as an integral of a running cost (and possibly a terminal cost) that penalizes deviations from desired states and excessive use of control effort. For instance, in regulating the cart-pole system, the cost might include terms for the pole’s deviation from the vertical position and for the magnitude of the applied force.</p><p><strong>System Dynamics:</strong> Described by differential equations, which capture the evolution of the system states over time. In a nonlinear system, these dynamics can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/159/0*otMVQok1qtZc9dBI.png" /></figure><p>where x(t) represents the state vector and u(t) the control input.</p><p><strong>Constraints:</strong> These include state constraints (e.g., physical limits on the cart position) and input constraints (e.g., maximum allowable force). Handling constraints is essential for ensuring feasibility in real-world applications.</p><p><strong>Optimality Conditions:</strong> Methods like the Pontryagin’s Maximum Principle or the use of the Hamilton-Jacobi-Bellman equation provide the theoretical underpinnings for why and how an optimal control strategy can be derived.</p><h3>Introduction to Nonlinear Model Predictive Control (NMPC)</h3><p>NMPC extends the ideas of optimal control to a receding-horizon framework, where at each time step, an optimization problem is solved over a finite future horizon. The essential steps include:</p><p><strong>Prediction Horizon: </strong>The future time window over which the control action is optimized. NMPC updates this prediction at every time step, allowing it to adapt to real-time changes.</p><p><strong>Receding Horizon Strategy:</strong> At each iteration, only the first control input is applied, and the optimization problem is solved again at the next time step with new state measurements. This continuous update cycle helps in handling model mismatches and disturbances effectively.</p><p><strong>Nonlinear Dynamics:</strong> Unlike linear MPC that assumes linearity, NMPC directly handles nonlinear models. This makes it particularly powerful for systems like the cart-pole, where the dynamics are inherently nonlinear.</p><p><strong>Computational Considerations: </strong>The key challenge in NMPC is solving a nonlinear optimization problem in real time. Advances in numerical solvers and tools like CasADi — which provides efficient algorithms for automatic differentiation and numerical optimization — have greatly increased the feasibility of NMPC in embedded applications.</p><h3>Problem Statement and Mathematical Formulation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/0*zKX2SxGrxtdRjuC8" /><figcaption>Cart-Pole System</figcaption></figure><h4>Description of the Control Problem</h4><p>For our running example, we choose the <strong>cart-pole system</strong>, a classic control problem that involves balancing an inverted pendulum on a moving cart. This example illustrates a range of control and optimization issues:</p><ul><li><strong>Control Objective:</strong><br> Keep the pole upright while stabilizing the cart’s position within certain limits. This is done by applying a horizontal force u to the cart.</li><li><strong>Why the Cart-Pole?</strong><br> The cart-pole serves as an excellent testbed because its nonlinear dynamics and inherent instability capture many challenges faced in real-world control applications.</li></ul><p>Watch the following video of a cart-pole in action:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FvmS8EdxgHoE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DvmS8EdxgHoE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FvmS8EdxgHoE%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/719cecc0e3c5b05ec1c19ec304a63b52/href">https://medium.com/media/719cecc0e3c5b05ec1c19ec304a63b52/href</a></iframe><h4>System Dynamics and Constraints</h4><p>The dynamics of the cart-pole system are typically described by a set of nonlinear differential equations.</p><p>A common formulation is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*vZhHYIUH52G0jtL2.png" /></figure><p>where:</p><ul><li><em>x</em> is the cart position, <em>v</em> is its velocity,</li><li><em>θ</em> is the pendulum angle (with <em>θ</em>=0 representing the upright position), and <em>ω</em> is the angular velocity,</li><li><em>m_c</em>​ and <em>m_p</em>​ are the masses of the cart and the pole, respectively,</li><li><em>l</em> is the length of the pole,</li><li><em>g</em> is the acceleration due to gravity, and</li><li><em>F</em> is the applied force (control input).</li></ul><p>For a realistic control scenario, constraints must be incorporated:</p><ul><li><strong>State Constraints:</strong><br> Limits on the cart position, velocity, pendulum angle, and angular velocity. For example, the cart may be restricted to a predefined track, and the angle θ\thetaθ should remain in a safe range.</li><li><strong>Input Constraints:</strong><br> The applied force FFF is bounded by actuator capabilities. This constraint ensures that the computed control actions are physically realizable.</li></ul><h4>Cost Function Design</h4><p>The goal is to design a cost function <em>J</em> that balances state errors and control effort over a prediction horizon <em>T:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*F4PFuPJWDAucuStO.png" /></figure><p>This cost formulation reflects the trade-offs between achieving precise system behavior and minimizing the control energy used.</p><h3>Constructing the Optimization Problem with CasADi</h3><p>In this section, we translate our mathematical formulation into a concrete optimization problem that can be solved using CasADi. This process involves discretizing the continuous-time dynamics and encoding the objective and constraints in a form suitable for a nonlinear programming (NLP) solver.</p><h4>Step-by-Step Problem Formulation in CasADi</h4><p><strong>Defining Decision Variables</strong></p><p>Using CasADi’s symbolic framework, we define decision variables for our states and control inputs at discrete time steps:</p><pre>import casadi as ca<br>import numpy as np<br><br># State variables: x (cart position), v (cart velocity), theta (pole angle), omega (angular velocity)<br>x = ca.SX.sym(&#39;x&#39;)<br>v = ca.SX.sym(&#39;v&#39;)<br>theta = ca.SX.sym(&#39;theta&#39;)<br>omega = ca.SX.sym(&#39;omega&#39;)<br>states = ca.vertcat(x, v, theta, omega)<br>n_states = states.size1()  # should be 4<br><br># Control variable: u (force applied to cart)<br>u = ca.SX.sym(&#39;u&#39;)<br>n_controls = u.size1()     # should be 1<br><br># Decision variables for the entire horizon<br># X will be of size (n_states x (N+1)) and U of size (n_controls x N)<br>X = ca.SX.sym(&#39;X&#39;, n_states, N+1)<br>U = ca.SX.sym(&#39;U&#39;, n_controls, N)</pre><p><strong>Encoding System Dynamics</strong></p><p>Next, encode the system dynamics as a function and discritize using a simple Euler integration:</p><pre># Define parameters and constants<br>m_c = 1.0       # Mass of the cart<br>m_p = 0.1       # Mass of the pole<br>l = 0.5         # Length of the pole (center of mass distance)<br>g_val = 9.81    # Gravitational acceleration<br><br># Define the number of discretization points<br>dt = 0.1        # Time step for discretization<br>N = 20          # Prediction horizon (number of control intervals)<br><br><br># Cart-Pole Dynamics Definition<br>def cartpole_dynamics(state, u):<br>    &quot;&quot;&quot;<br>    Computes the time derivative of the state vector for the cart-pole system.<br>    &quot;&quot;&quot;<br>    x, v, theta, omega = state[0], state[1], state[2], state[3]<br>    sin_theta = ca.sin(theta)<br>    cos_theta = ca.cos(theta)<br>    <br>    total_mass = m_c + m_p<br>    temp = (u + m_p * l * omega**2 * sin_theta) / total_mass<br>    # Calculate angular acceleration (theta_acc) and cart acceleration (x_acc)<br>    theta_acc = (g_val * sin_theta - cos_theta * temp) / (l * (4/3 - m_p * cos_theta**2 / total_mass))<br>    x_acc = temp - (m_p * l * theta_acc * cos_theta) / total_mass<br>    <br>    return ca.vertcat(v, x_acc, omega, theta_acc)<br><br># Define the discrete dynamics function using simple Euler integration:<br>f = lambda state, u: state + dt * cartpole_dynamics(state, u)Setting up the Objective Function and Constraints</pre><p>Now, formulate the cost function over the prediction horizon and add the dynamic constraints:</p><pre># We choose weights for the cost function:<br>Q_x = 1.0       # Weight for cart position error<br>Q_theta = 100.0  # Weight for pole angle error<br>R = 0.1         # Weight on control effort<br><br># Desired reference values<br>x_ref = 0.0      # Desired cart position<br>theta_ref = 0.0  # Desired pole angle (vertical)<br><br># Initialize objective (cost function) and constraints<br>obj = 0         # Accumulated cost<br>g = []          # Equality constraints list<br><br># Parameter for the initial state:<br>X0 = ca.SX.sym(&#39;X0&#39;, n_states)<br><br># Enforce initial condition constraint: the first state in X equals the current state X0.<br>g.append(X[:, 0] - X0)<br><br># Loop over each control interval to build the cost and dynamics constraints<br>for k in range(N):<br>    # Cost function: Penalize errors in cart position and pole angle plus control effort.<br>    obj += Q_x * (X[0, k] - x_ref)**2 + Q_theta * (X[2, k] - theta_ref)**2 + R * U[0, k]**2<br>    <br>    # Dynamics constraint: next state equals the discrete dynamics from current state and control.<br>    x_next = f(X[:, k], U[:, k])<br>    g.append(X[:, k+1] - x_next)<br><br># Optionally, add a terminal cost on the final state<br>obj += Q_x * (X[0, N] - x_ref)**2 + Q_theta * (X[2, N] - theta_ref)**2<br><br><br><br># Define limits for the horizontal position and control input<br># Horizontal position constraint (for cart&#39;s x-position): x_min &lt;= x &lt;= x_max<br>x_min = -2.0<br>x_max = 2.0<br><br># Control constraint: u_min &lt;= u &lt;= u_max<br>u_min = -12.0<br>u_max =  12.0<br><br># The decision vector consists of:<br>#  - First: states, shaped as (n_states*(N+1),)<br>#  - Second: control inputs, shaped as (n_controls*N,)<br>n_decision = int(opt_vars.numel())<br>lbx = -np.inf * np.ones(n_decision)<br>ubx =  np.inf * np.ones(n_decision)<br><br># Set box constraints for the horizontal position (state variable x)<br># Each time step: the x-component is the first element in the state block.<br>for i in range(N+1):<br>    idx = i * n_states  # index for x at time step i<br>    lbx[idx] = x_min<br>    ubx[idx] = x_max<br><br># Set box constraints for the control variable (u)<br># Controls come after the state variables in the decision vector.<br>start_u = n_states * (N+1)<br>for i in range(N):<br>    idx = start_u + i * n_controls  # index for control at time step i<br>    lbx[idx] = u_min<br>    ubx[idx] = u_max</pre><p><strong>Solver Configuration</strong></p><p>Construct and configure the CasADi NLP solver:</p><pre># # Reshape decision variables into a single column vector.<br>opt_vars = ca.vertcat(ca.reshape(X, -1, 1), ca.reshape(U, -1, 1))<br># Concatenate all constraints into one vector.<br>g_concat = ca.vertcat(*g)<br><br># Define bounds for the constraints (all equality constraints are set to 0)<br>g_bound = np.zeros(int(g_concat.numel()))<br>lbg = g_bound<br>ubg = g_bound<br><br><br># Define the NLP problem<br>nlp_problem = {<br>    &#39;f&#39;: obj,       # Objective function<br>    &#39;x&#39;: opt_vars,  # Decision variables<br>    &#39;g&#39;: g_concat,  # Constraints<br>    &#39;p&#39;: X0         # Parameter: initial state<br>}<br><br># Create an NLP solver instance using IPOPT.<br>opts = {&#39;ipopt.print_level&#39;: 0, &#39;print_time&#39;: 0}<br>solver = ca.nlpsol(&#39;solver&#39;, &#39;ipopt&#39;, nlp_problem, opts)<br><br><br># Initial guess for the decision variables<br>init_guess = np.zeros(int(opt_vars.numel()))<br>x_current = np.array([0.0, 0.0, 3.1415, 0.0])<br><br>#solve one step<br>sol = solver(x0=init_guess, lbx=lbx, ubx=ubx, lbg=lbg, ubg=ubg, p=x_current)</pre><p>This code walkthrough provides a detailed look into the process of establishing the NMPC formulation:</p><ul><li>Defining the variables required to represent our state and control over the finite horizon.</li><li>Encoding the dynamics of the cart-pole system through a numerical integration scheme.</li><li>Formulating the cost function and dynamic constraints that capture the control objectives.</li><li>Setting up and solving the NLP using CasADi’s interface with a solver such as IPOPT.</li></ul><h3>Simulation</h3><p>After setting up the NMPC problem and configuring the solver in CasADi, it’s time to integrate the controller into a simulation environment. The goal here is to repeatedly solve the NMPC problem, update the system state with the obtained control actions, and then graphically display the evolution of the cart-pole system.</p><h3>5.1 Simulation Loop</h3><p>The simulation loop involves the following steps:</p><p><strong>Initialization:</strong></p><ul><li>Set the initial state of the cart-pole system.</li><li>Define simulation parameters such as the total simulation time and sampling time.</li></ul><p><strong>NMPC Optimization at Each Time Step:</strong></p><ul><li>At every iteration, update the current state.</li><li>Solve the NLP (using our previously defined CasADi solver) to obtain a sequence of optimal control inputs.</li><li>Apply only the first control input to the system.</li></ul><p><strong>State Update:</strong></p><ul><li>Use a numerical integrator (e.g., Euler integration) to simulate the continuous dynamics of the cart-pole given the control input.</li><li>Record state trajectories and control actions for analysis and visualization.</li></ul><p><strong>Repeat:</strong></p><ul><li>Continue until the simulation time expires.</li></ul><p>Now let’s see how we can run a simulation of the cart-pole control in code:</p><pre>sim_time = 20.0               # total simulation time (seconds)<br>n_sim_steps = int(sim_time/dt)<br>t_history = [0]<br>state_history = []  # To store state trajectories<br>control_history = []  # To store control inputs<br><br># Initialize state (for example: x=0, v=0, theta=0.1 rad, omega=0)<br>x_current = np.array([0.0, 0.0, 3.1415, 0.0])<br>state_history.append(x_current)<br><br># ------------------------------<br># Simulation Loop<br># ------------------------------<br>for i in range(n_sim_steps):<br>    # Solve the NMPC for the current state x_current<br>    sol = solver(x0=init_guess, lbx=lbx, ubx=ubx, lbg=lbg, ubg=ubg, p=x_current)<br>    sol_opt = sol[&#39;x&#39;].full().flatten()<br>    <br>    # Extract the control sequence from the solution. The state trajectory is first,<br>    # so the first control is located at index = n_states*(N+1)<br>    u_opt = sol_opt[n_states*(N+1): n_states*(N+1)+n_controls]<br>    u_current = u_opt[0]<br>    control_history.append(u_current)<br>    <br>    # Propagate the system using the discrete dynamics f (Euler integration)<br>    # Note: We use the same function f defined earlier with CasADi operators<br>    x_next = f(x_current, u_current)<br>    x_current = np.array(x_next.full()).flatten()<br>    <br>    # Store the new state and time<br>    state_history.append(x_current)<br>    t_history.append((i+1)*dt)<br>    <br>    # Optionally, update initial guess to warm-start the next iteration (shift the sequence)<br>    # For simplicity, we keep using the zero initial guess here.<br>    <br>state_history = np.array(state_history)<br>control_history = np.array(control_history)</pre><p>A animation of the simulation can be created using the following code:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from matplotlib import animation<br>from IPython.display import HTML<br><br># Assume these variables exist:<br># state_history: numpy array of shape (num_steps, 4) [columns: x, v, theta, omega]<br># control_history: numpy array of shape (num_steps-1,) containing control inputs at each simulation step<br><br># For illustration purposes, here are dummy histories (remove these lines when using your actual data)<br>num_steps = n_sim_steps  # Example: 51 simulation steps<br>dt = 0.1<br>t_history = np.arange(0, num_steps*dt, dt)<br># --------------------------------------------------<br><br># Visualization parameters<br>cart_width = 0.4<br>cart_height = 0.2<br>pole_length = 0.5  # Ensure this matches the length used in your simulation<br><br># Create the figure and axis for the animation<br>fig, ax = plt.subplots(figsize=(8, 4))<br>ax.set_xlim(-3, 3)<br>ax.set_ylim(-0.5, 2.0)<br>ax.set_xlabel(&#39;x (m)&#39;)<br>ax.set_ylabel(&#39;y (m)&#39;)<br>ax.set_title(&#39;Cart-Pole Animation from State and Control History&#39;)<br><br># Create plot elements: rectangle for the cart and a line for the pole<br>cart_patch = plt.Rectangle((0, 0), cart_width, cart_height, fc=&#39;b&#39;, ec=&#39;k&#39;)<br>ax.add_patch(cart_patch)<br>pole_line, = ax.plot([], [], lw=3, c=&#39;r&#39;)<br><br># Text annotations for time and control input<br>time_text = ax.text(0.02, 0.95, &#39;&#39;, transform=ax.transAxes, fontsize=12)<br>control_text = ax.text(0.02, 0.88, &#39;&#39;, transform=ax.transAxes, fontsize=12)<br><br># Initialization function for the animation<br>def init():<br>    cart_patch.set_xy((-cart_width/2, 0))<br>    pole_line.set_data([], [])<br>    time_text.set_text(&#39;&#39;)<br>    control_text.set_text(&#39;&#39;)<br>    return cart_patch, pole_line, time_text, control_text<br><br># Animation update function<br>def animate(i):<br>    # Extract state: [x, v, theta, omega]<br>    x_val = state_history[i, 0]<br>    theta_val = state_history[i, 2]<br>    <br>    # Update cart: center the cart at x_val, with the bottom at y = 0<br>    cart_x = x_val - cart_width/2<br>    cart_patch.set_xy((cart_x, 0))<br>    <br>    # The pivot point (where the pole is attached) is at the top-center of the cart.<br>    cart_center = np.array([x_val, cart_height])<br>    <br>    # Compute the pole tip using basic trigonometry<br>    pole_tip = cart_center + pole_length * np.array([np.sin(theta_val), np.cos(theta_val)])<br>    pole_line.set_data([cart_center[0], pole_tip[0]], [cart_center[1], pole_tip[1]])<br>    <br>    # Update annotations: simulation time and control input.<br>    time_text.set_text(f&#39;Time = {i*dt:.2f} s&#39;)<br>    # Use the last available control for the last frame.<br>    u_val = control_history[i] if i &lt; len(control_history) else control_history[-1]<br>    control_text.set_text(f&#39;Control u = {u_val:.2f}&#39;)<br>    <br>    return cart_patch, pole_line, time_text, control_text<br><br># Create the animation object. The &#39;interval&#39; parameter is set in milliseconds.<br>ani = animation.FuncAnimation(fig, animate, frames=len(state_history),<br>                              init_func=init, interval=dt*1000, blit=True)<br><br># Use HTML to display the animation inline in a Jupyter Notebook.<br>HTML(ani.to_jshtml())</pre><p>Here is how the simulation will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*BKTdbp87e6q5fMwapNkdJQ.gif" /></figure><h3>Discussion</h3><p>In the animation we observe that:</p><ul><li>The <strong>cart position</strong> remains close to the desired point, even as it moves to counteract the pole’s deviations.</li><li>The <strong>pole angle</strong> converges to the vertical (approximately 0 radians), indicating successful stabilization by the NMPC controller.</li><li>The animation visibly demonstrates how the controller applies forces to quickly counteract deviations, leading to the desired upright posture.</li></ul><h3>Conclusion</h3><p>In conclusion, the implementation of Nonlinear Model Predictive Control (NMPC) for the cart-pole system has been successfully demonstrated. By formulating the system dynamics, defining the cost function, and setting up the constraints, the NMPC controller effectively stabilizes the pole in the upright position while controlling the cart’s movement. The simulation results and the accompanying animation validate the controller’s performance, showcasing its ability to handle the nonlinearities of the system. This approach underscores the potential of NMPC in managing complex control tasks in real-time applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62f1d72f2efa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modeling Dynamics with CasADi: Simulation of a Simple Pendulum]]></title>
            <link>https://medium.com/@shoaib6174/modeling-dynamics-with-casadi-simulation-of-a-simple-pendulum-9c10f72ffae8?source=rss-9482f5c0f21a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c10f72ffae8</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[optimal-control]]></category>
            <dc:creator><![CDATA[Mohammad Shoaib]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 10:29:48 GMT</pubDate>
            <atom:updated>2025-04-15T10:29:48.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*SeNbNkGUgWadC5FL" /></figure><h3>Introduction</h3><p>In this post, we explore the exciting intersection of dynamic systems and optimization using CasADi. CasADi is a powerful tool for solving optimization problems with differential equations — commonly found in control theory and robotics. The pendulum, a classic example in dynamics, serves as a perfect case study due to its simple yet nonlinear behavior. By modeling a pendulum, we gain valuable insights into how dynamic systems can be mathematically described, simulated, and eventually controlled.</p><h3>The Mathematical Model</h3><p>For a simple pendulum, the equation of motion is derived from Newton’s second law. The classical second-order ordinary differential equation (ODE) is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/0*6IOn_29WOT6t3l4D.png" /></figure><p>Here,</p><ul><li><em>θ</em> represents the angular displacement,</li><li><em>g</em> is the acceleration due to gravity, and</li><li><em>l</em> is the length of the pendulum.</li></ul><h4>Conversion to a First-Order System</h4><p>To solve this ODE using numerical integrators and optimization frameworks like CasADi, we first rewrite it as a system of first-order ODEs. We define the state vector x such that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/179/0*3unB6hydtZpIj7sU.png" /></figure><p>Then, the dynamics are expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/134/0*YGMsAoAGAfN9m6uU.png" /></figure><p>Now that we have the equations set up, we can implement the model in CasADi. Below is a step-by-step explanation of the process along with a code snippet.</p><h3>Implementation</h3><h4>Step 1: Import Libraries and Define Constants</h4><p>We start by importing CasADi, along with NumPy for numerical operations and Matplotlib for visualization. Constants such as gravitational acceleration (g) and pendulum length (l) are defined.</p><pre>import casadi as ca<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br># Constants<br>g = 9.81  # gravitational acceleration (m/s^2)<br>l = 1.0   # length of the pendulum (m)</pre><h4>Step 2: Define State Variables and Dynamics</h4><p>Next, we define the state vector using CasADi’s symbolic variables. The dynamics of the pendulum are expressed as described previously.</p><pre># Define symbolic state variables: x[0] is theta, x[1] is theta_dot<br>x = ca.MX.sym(&#39;x&#39;, 2)<br><br>def pendulum_ode(x):<br>    theta = x[0]<br>    omega = x[1]<br>    dtheta = omega<br>    domega = - (g / l) * ca.sin(theta)<br>    return ca.vertcat(dtheta, domega)<br></pre><p>This function pendulum_ode takes a state x and returns its time derivative.</p><h4>Step 3: Simulate Using Numerical Integration</h4><p>Numerical integration methods like Euler’s and RK4 are essential in simulating physical systems where analytical solutions are impractical. They allow us to model and predict the behavior of systems over time, which is crucial in fields like physics, engineering, and computer graphics. For instance, in simulating a pendulum’s motion, these methods help approximate the pendulum’s position and velocity at discrete time intervals, enabling us to visualize and analyze its dynamics effectively</p><p><strong>Euler’s Method</strong></p><p>Euler’s method is the simplest form of numerical integration. It estimates the next value of a function by using the current value and its derivative. Given an initial value problem:​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/0*1tVKCcpkO_eIkwQ8.png" /></figure><p>Euler’s method computes the solution iteratively:​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*haf2GZzy-bwThTFR.png" /></figure><p>where <em>h</em> is the step size. While straightforward to implement, Euler’s method can be inaccurate and unstable for stiff equations or larger step sizes.</p><p><strong>Runge-Kutta 4th Order Method (RK4)</strong></p><p>The RK4 method is a more advanced and accurate numerical integration technique. It improves upon Euler’s method by taking a weighted average of slopes (derivatives) at multiple points within each step:​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/0*EVoO6ksLRGUCg711.png" /></figure><p>This method offers greater accuracy and stability, making it suitable for a wide range of problems.</p><p>We’ll implement both Euler’s method and the RK4 method using CasADi in Python to simulate the dynamics of the simple pendulum. Here’s the code:</p><pre># Create CasADi function for the ODE<br>f = ca.Function(&#39;f&#39;, [x], [pendulum_ode(x)])<br><br># Euler integration step<br>def euler_step(xk):<br>    return xk + dt * f(xk)<br><br># RK4 integration step<br>def rk4_step(xk):<br>    k1 = f(xk)<br>    k2 = f(xk + dt/2 * k1)<br>    k3 = f(xk + dt/2 * k2)<br>    k4 = f(xk + dt * k3)<br>    return xk + dt/6 * (k1 + 2*k2 + 2*k3 + k4)<br><br># Initialize arrays to store results<br>euler_results = np.zeros((N+1, 2))<br>rk4_results = np.zeros((N+1, 2))<br>time = np.linspace(0, T, N+1)<br><br># Set initial conditions<br>euler_results[0, :] = [theta0, omega0]<br>rk4_results[0, :] = [theta0, omega0]<br><br># Simulate using Euler and RK4 methods<br>x_euler = ca.DM([theta0, omega0])<br>x_rk4 = ca.DM([theta0, omega0])<br><br>for i in range(N):<br>    x_euler = euler_step(x_euler)<br>    x_rk4 = rk4_step(x_rk4)<br>    euler_results[i+1, :] = x_euler.full().flatten()<br>    rk4_results[i+1, :] = x_rk4.full().flatten()</pre><h4>Step 4: Visualize the Results</h4><p>Finally, we plot the evolution of the pendulum’s angular displacement over time. Visualization helps in understanding the system’s dynamics and validating the simulation.</p><pre># Plotting the results<br>plt.figure(figsize=(12, 6))<br>plt.plot(time, euler_results[:, 0], label=&#39;Euler Method&#39;, linestyle=&#39;--&#39;)<br>plt.plot(time, rk4_results[:, 0], label=&#39;RK4 Method&#39;, linestyle=&#39;-&#39;)<br>plt.title(&#39;Pendulum Simulation: Euler vs RK4&#39;)<br>plt.xlabel(&#39;Time (s)&#39;)<br>plt.ylabel(&#39;Angle (rad)&#39;)<br>plt.legend()<br>plt.grid(True)<br>plt.show()</pre><p>The plot generated by the above code will display the angular displacement of the pendulum over time using both Euler’s method and the RK4 method. Here’s what you should observe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*PoBaAAFcgaou_XFCKkaTzg.png" /></figure><p>Euler Method:</p><ul><li>The solution may exhibit noticeable numerical damping or energy gain, leading to inaccurate amplitude over time.</li><li>Less accurate, especially for larger time steps or longer simulation durations.</li></ul><p>RK4 Method:</p><ul><li>Provides a more accurate and stable solution.</li><li>Better preserves the energy of the system, maintaining consistent amplitude over time.</li></ul><h3>Simulating with CasADi’s Built-in Integrator</h3><p>CasADi has many built-in integrators like Runge-Kutta (RK), CVODES, IDAS, IRK (Implicit Runge-Kutta) etc. Here is a example how</p><pre># Define the ODE function<br>ode = {&#39;x&#39;: x, &#39;ode&#39;: pendulum_ode(x)}<br><br># Change &#39;cvodes&#39; to &#39;rk&#39; if you want fixed-step RK<br>integrator = ca.integrator(&#39;integrator&#39;, &#39;rk&#39;, ode, {&#39;tf&#39;: dt})<br><br># Initialize result storage for CasADi integrator<br>casadi_results = np.zeros((N+1, 2))<br>casadi_results[0, :] = [theta0, omega0]<br>x_casadi = ca.DM([theta0, omega0])<br><br># Simulate using CasADi integrator<br>for i in range(N):<br>    res = integrator(x0=x_casadi)<br>    x_casadi = res[&#39;xf&#39;]<br>    casadi_results[i+1, :] = x_casadi.full().flatten()</pre><h3>Conclusion</h3><p>The process of modeling and simulating a pendulum using CasADi provided several key takeaways:</p><ul><li><strong>Model Decomposition:</strong><br> Converting a higher-order ODE into a first-order system simplifies numerical integration and makes future optimization tasks more straightforward.</li><li><strong>Numerical Analysis Realities:</strong><br> The challenges with discretization errors underscore the importance of choosing an appropriate method based on the required precision. This experience is invaluable for more complex systems where error propagation can become critical.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c10f72ffae8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving Quadratic NLP with CasADi]]></title>
            <link>https://medium.com/@shoaib6174/solving-quadratic-nlp-with-casadi-7a49948d8c64?source=rss-9482f5c0f21a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a49948d8c64</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[optimal-control]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Mohammad Shoaib]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 19:02:40 GMT</pubDate>
            <atom:updated>2025-04-14T19:02:40.967Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this post, we tackle a quadratic minimization problem under both equality and inequality constraints using CasADi — a powerful framework for symbolic optimization — and IPOPT as the solver. The focus is on clarity, technical rigor, and practical insights that can be extended to more complex scenarios.</p><p>Optimization is indispensable across engineering, finance, and scientific research. Nonlinear programming (NLP) allows us to model real-world problems that include nonlinearity and complex constraints. CasADi offers an expressive, symbolic environment that simplifies the formulation and differentiation of these models. Here, we solve a convex quadratic optimization problem that is sufficiently representative yet accessible for beginners and experts alike.</p><h3>CasADi for Modeling NLP</h3><p>CasADi streamlines variable definition, objective and constraint formulation, and automatic differentiation. Its symbolic approach lets you express complex models in an intuitive mathematical form. Here, we use it to build our quadratic objective and linear constraints.</p><h3>Solver Selection: IPOPT</h3><p>IPOPT is tailored for large-scale, nonlinear optimization problems. Through CasADi, we can configure parameters like tolerance, iteration limits, and verbosity, allowing fine-tuning of the solver’s behavior without modifying the core model.</p><h3>Problem Formulation</h3><p>We consider the following convex quadratic minimization problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/0*5f_O2KbckFCJVGwr.png" /></figure><h3>Formulating the Optimization Problem</h3><h4>Variable Definitions</h4><p>In CasADi, decision variables are defined symbolically. For our quadratic optimization problem, we need to declare a variable xxx representing the vector of decision variables. This step is fundamental as it sets the stage for building the objective and constraint equations.</p><pre>import casadi as ca<br><br># Define the number of decision variables, for example n=3<br>n = 3<br>x = ca.MX.sym(&#39;x&#39;, n)</pre><p>Here, ca.MX.sym creates a symbolic variable x of dimension n. This object will be used to construct both the cost function and constraints.</p><h4>Defining the Cost Function</h4><p>The objective function we wish to minimize is quadratic where Q is a positive semidefinite matrix ensuring convexity, and ccc is a constant vector. In CasADi, you can construct this function by expressing it in terms of the symbolic variable x.</p><pre>import numpy as np<br><br># Define Q and c with appropriate dimensions<br>Q = np.array([[2, 0, 0],<br>              [0, 2, 0],<br>              [0, 0, 2]])<br>c = np.array([1, 1, 1])<br><br># Define the quadratic cost function using CasADi&#39;s dot product<br>cost = 0.5 * ca.dot(x, ca.mtimes(Q, x)) + ca.dot(c, x)</pre><p>In this snippet, ca.mtimes performs matrix multiplication, and ca.dot calculates the dot product, effectively building the quadratic objective.</p><h4>Setting Up Constraints</h4><p>Constraints are essential for ensuring the solution meets the required conditions. Our problem includes both equality and inequality constraints.</p><p><em>Equality constraints</em> are imposed to ensure certain relationships hold and <em>Inequality constraints</em> enforce that certain variables remain within a specified bound.</p><pre># Define A and b for the equality constraints<br>A = np.array([[1, 1, 1]])<br>b = np.array([1])<br><br># Equality constraint in CasADi: A*x == b<br>eq_constraint = ca.mtimes(A, x) - b<br><br># Inequality constraints: x &gt;= 0 (interpreted as -x &lt;= 0)<br>ineq_constraint = -x</pre><h4>Solver Settings and Execution</h4><p>For solving our NLP, we will use IPOPT. IPOPT is a widely used solver for large-scale nonlinear optimization that benefits from CasADi’s automatic differentiation. Its flexible settings allow users to fine-tune performance based on the problem’s specifics.</p><p>Configuring the solver involves setting parameters such as tolerance levels, maximum iterations, and output options.</p><pre># Create an NLP dictionary that includes the objective and constraints.<br>nlp = {&#39;x&#39;: x, &#39;f&#39;: cost, &#39;g&#39;: ca.vertcat(eq_constraint, ineq_constraint)}<br><br># Create the IPOPT solver instance.<br>opts = {&#39;ipopt.print_level&#39;: 0,  # Quiet mode<br>        &#39;print_time&#39;: 0,<br>        &#39;ipopt.max_iter&#39;: 100}<br>solver = ca.nlpsol(&#39;solver&#39;, &#39;ipopt&#39;, nlp, opts)</pre><p>In this configuration:</p><ul><li>ipopt.print_level and print_time are set to minimize console output.</li><li>ipopt.max_iter specifies the maximum number of iterations the solver will perform before stopping.</li></ul><h4>Solving the NLP</h4><p>The final step is to call the solver with an appropriate initial guess. An initial guess helps the solver start its search from a feasible region or a reasonable point:</p><pre># Provide an initial guess for the decision variables<br>x0 = np.array([0.3, 0.3, 0.4])<br>solution = solver(lbx=0, ubx=ca.inf, x0=x0, lbg=0, ubg=0)<br><br># Retrieve and print the optimal solution<br>optimal_x = solution[&#39;x&#39;]<br>print(&quot;Optimal x:&quot;, optimal_x)</pre><p>In this snippet:</p><ul><li>lbx and ubx denote lower and upper bounds on xxx respectively. We set a lower bound of zero, reflecting the inequality constraint.</li><li>lbg and ubg set the bounds on the constraints.</li><li>The solver returns an optimal solution that you can examine and later visualize.</li></ul><h3>Full Implementation</h3><p>For your ease, here is the full code with comments again:</p><pre>import casadi as ca<br>import numpy as np<br><br># ----------------------------<br># 1. Define Decision Variables<br># ----------------------------<br># For this example, we assume there are three decision variables.<br>n = 3<br>x = ca.MX.sym(&#39;x&#39;, n)  # Create a symbolic variable &#39;x&#39; of dimension n<br><br># ----------------------------<br># 2. Define the Cost Function<br># ----------------------------<br># Our quadratic cost function is:<br>#   f(x) = 0.5 * x^T Q x + c^T x<br># Here Q must be a positive semidefinite matrix to ensure convexity.<br>Q = np.array([[2, 0, 0],<br>              [0, 2, 0],<br>              [0, 0, 2]])<br>c = np.array([1, 1, 1])<br><br># Construct the cost function using CasADi operations:<br>cost = 0.5 * ca.dot(x, ca.mtimes(Q, x)) + ca.dot(c, x)<br><br># ----------------------------<br># 3. Set Up the Constraints<br># ----------------------------<br># Equality Constraint: A * x = b<br>A = np.array([[1, 1, 1]])<br>b = np.array([1])<br># Calculate A*x - b to be equal to 0.<br>eq_constraint = ca.mtimes(A, x) - b<br><br># Inequality Constraint: x &gt;= 0<br># We transform this into a constraint function of the form -x &lt;= 0.<br>ineq_constraint = -x<br><br># Combine constraints into one vector:<br># The first part corresponds to the equality constraint; the following entries are inequality.<br>g = ca.vertcat(eq_constraint, ineq_constraint)<br><br># ----------------------------<br># 4. Define the NLP Problem<br># ----------------------------<br># The NLP dictionary includes the decision variables &#39;x&#39;, the cost function &#39;f&#39;,<br># and all constraints &#39;g&#39;.<br>nlp = {&#39;x&#39;: x, &#39;f&#39;: cost, &#39;g&#39;: g}<br><br># ----------------------------<br># 5. Configure the Solver (IPOPT)<br># ----------------------------<br># Set options for IPOPT: quiet output and a max iteration count.<br>opts = {&#39;ipopt.print_level&#39;: 0,  # Minimizes console output<br>        &#39;print_time&#39;: 0,<br>        &#39;ipopt.max_iter&#39;: 100}<br>solver = ca.nlpsol(&#39;solver&#39;, &#39;ipopt&#39;, nlp, opts)<br><br># ----------------------------<br># 6. Define Constraint Bounds and Initial Guess<br># ----------------------------<br># For the equality constraint part (first element of g), set both lower and upper bounds to 0.<br># For the inequality constraints (remaining n elements), we enforce -x &lt;= 0; hence, the upper bound is 0,<br># while the lower bound can be -infinity (indicating no lower bound restriction on -x).<br>lbg = [0] + [-ca.inf]*n  # Lower bounds for constraints: eq_constraint = 0, ineq_constraint has no lower bound<br>ubg = [0] + [0]*n        # Upper bounds for constraints: eq_constraint = 0, ineq_constraint = 0<br><br># Additionally, set the lower bound for decision variables to 0 (x &gt;= 0) and leave the upper bound unbounded.<br>lbx = 0<br>ubx = ca.inf<br><br># Provide an initial guess for the solver.<br>x0 = np.array([0.3, 0.3, 0.4])<br><br># ----------------------------<br># 7. Solve the NLP<br># ----------------------------<br>solution = solver(x0=x0, lbx=lbx, ubx=ubx, lbg=lbg, ubg=ubg)<br><br># Extract the optimal solution.<br>optimal_x = solution[&#39;x&#39;]<br>print(&quot;Optimal x:&quot;, optimal_x)</pre><h3>Explanation of Key Components:</h3><ul><li><strong>Decision Variables:</strong><br> We create a symbolic variable x representing our decision variables. This variable is central to defining both the cost function and the constraints.</li><li><strong>Cost Function:</strong><br> The quadratic objective function is built using CasADi’s matrix multiplication (ca.mtimes) and dot product (ca.dot). This ensures that the expression remains symbolic and differentiable.</li><li><strong>Constraints: <br></strong>All constraints are combined into a single vector using ca.vertcat.</li><li><strong>NLP Dictionary:</strong><br> The entire problem is bundled into a dictionary containing the variable x, the cost function f, and the combined constraints g.</li><li><strong>Solver Configuration:</strong><br> We use IPOPT as our backend solver. The options provided streamline the output and set a maximum number of iterations to ensure the solver completes in a reasonable timeframe.</li><li><strong>Constraint and Variable Bounds:</strong><br> The lower and upper bounds for both the decision variables and the constraints are specified. This step guarantees that the inequality is respected.</li><li><strong>Solving and Output:</strong><br> The solver is called with an initial guess, and once the problem is solved, the optimal decision variable vector is printed.</li></ul><h3>Solver Output</h3><p>After running the solver on our formulated NLP, the solution provides values for the decision variables along with additional information such as the solver status and objective value. For our quadratic minimization problem, the printout shows the optimal vector <em>x:</em></p><pre>Optimal x: [0.333333, 0.333333, 0.333333]</pre><h3>Final Words</h3><p>This post presented a concise yet comprehensive walk-through of solving a quadratic NLP using CasADi and IPOPT. We demonstrated the formulation of a convex objective with linear constraints and provided a clear implementation in Python. CasADi’s symbolic manipulation and IPOPT’s robust solving capabilities pave the way for tackling more advanced optimization problems in various application domains.</p><p>In the next blog post we will simulate a dynamic system (ODEs) using CasADi.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a49948d8c64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to CasAdi with Python]]></title>
            <link>https://medium.com/@shoaib6174/an-introduction-to-casadi-with-python-12055f8e652f?source=rss-9482f5c0f21a------2</link>
            <guid isPermaLink="false">https://medium.com/p/12055f8e652f</guid>
            <category><![CDATA[optimal-control]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Mohammad Shoaib]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 13:51:32 GMT</pubDate>
            <atom:updated>2025-04-14T13:51:32.800Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*anl_F01lVTOn86BI.png" /></figure><p>CasADi is an open‐source framework designed for nonlinear optimization and optimal control that heavily relies on <strong>symbolic expressions</strong> and <strong>automatic differentiation</strong>.</p><h3>Symbolic Expression</h3><p>A symbolic expression is essentially an abstract representation of a mathematical formula, similar to writing equations on paper. These expressions are not evaluated immediately; instead, they form computational graphs that represent how outputs depend on inputs. This symbolic representation is crucial for enabling <em>algorithmic differentiation (AD)</em> in CasADi, as it allows the system to automatically and efficiently compute exact derivatives by traversing these graphs.</p><p>Here’s a simple example of a symbolic expression in CasADi:</p><pre>from casadi import SX<br>x = SX.sym(&#39;x&#39;)        # Define a symbolic variable x<br>y = SX.sym(&#39;y&#39;)        # Define another symbolic variable y<br>f = x**2 + 3*y         # Create a symbolic expression<br>print(f)               # Output: (x**2 + 3*y)</pre><p>In this example, f is a symbolic expression representing the function f(x) = x³ + 2x + 1. It’s not yet evaluated for any specific values of x-instead, it builds a symbolic graphnthat CasADi can later use for tasks like computing derivatives.</p><h3>Differentiation</h3><p>Let’s understand different ways of calculating derivatives:</p><p>a)<strong> Symbolic Differentiation</strong>: It differentiates functions <strong>analytically</strong> using algebraic rules (like what we’d do by hand). It calculates exact expressions which are useful for theoretical work or code generation (e.g., in SymPy, Mathematica). Complex dynamics (e.g., involving trigonometry, matrix operations, and conditional logic) lead to <strong>expression explosion</strong> — resulting in slow, hard-to-manage derivative expressions. Moreover, symbolic tools struggle with <strong>loops</strong>, <strong>conditionals</strong>, and <strong>black-box functions</strong>, which are common in robotic systems.</p><p>b)<strong> Finite Difference: </strong>It approximates derivatives using function values at nearby points. It can be done either using forward difference or center difference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/0*BGPSgnIcZLpTiKHS.png" /></figure><p>This method is slow and numerically unstable, and the result is imprecise.</p><p><strong>c) Algorithmic Differentiation (AD)</strong>: AD breaks a function into a sequence of elementary operations and applies the <strong>chain rule</strong> repeatedly to compute derivatives <strong>exactly</strong> (up to machine precision).</p><p>Watch the following video to understand these three approaches in-depth:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FwG_nF1awSSY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DwG_nF1awSSY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FwG_nF1awSSY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/63ad540834495404bcd51cd5c1f41de0/href">https://medium.com/media/63ad540834495404bcd51cd5c1f41de0/href</a></iframe><h3>Motivation Behind CasADi</h3><p>CasADi was designed to harness the power of algorithmic (or automatic) differentiation. Here’s why this approach makes a difference:</p><p><strong>Accuracy Without the Hassle:<br></strong>Algorithmic differentiation computes derivatives to machine precision — this means no guessing about how small the step should be, as in finite differences. The derivatives are calculated directly from the sequence of operations, ensuring both accuracy and reliability.</p><p><strong>Handling Complexity Gracefully:</strong><br>By avoiding full symbolic differentiation, CasADi sidesteps the “expression swell” that can cripple traditional symbolic systems. Instead, it works on a computational graph — a visual and conceptual representation of how a function is computed — allowing it to manage even very complicated functions efficiently.</p><p><strong>Optimized for Numerical Computations:<br></strong>CasADi is not just about getting derivatives; it’s about doing so in a way that integrates seamlessly with high-performance numerical solvers. This integration means that once you define your function and its derivatives using CasADi, you can easily plug it into advanced optimizers that find solutions to real-world engineering and control problems.</p><p>While many computer algebra systems (CAS) offer symbolic differentiation, CasADi’s unique blend of symbolic representation and numerical efficiency makes it stand out:</p><p><strong>Bridge Between Symbolic and Numeric Worlds:</strong><br>CasADi lets you define problems symbolically, but its backbone is geared toward numerical performance. This hybrid approach offers the best of both worlds — a clear mathematical formulation with direct applicability to numerical computations.</p><p><strong>Seamless Integration with Solvers:<br></strong>In practical applications like robotics, automotive control, and even machine learning, speed and reliability are non-negotiable. CasADi is built to work effortlessly with solvers like IPOPT, ensuring that the computed derivatives are immediately useful for optimizing performance and solving large-scale problems.</p><p><strong>User-Friendly and Flexible:<br></strong>Even if you are new to the intricacies of differentiation methods, CasADi’s design abstracts much of the complexity away. You can focus on modeling your problem clearly and intuitively, while CasADi handles the details of derivative calculation behind the scenes.</p><h3>A Practical Example of CasADi in Action</h3><p>Let’s put theory into practice with a hands-on example that clearly demonstrates why CasADi is such a valuable tool. In this section, we’ll walk through a simple problem where we define a function, calculate its derivative automatically, and compare the advantages of using CasADi over traditional methods.</p><h4><strong>Introducing the Example</strong></h4><p>Suppose we want to calculate derivative of a simple quadratic function:</p><p>f(x) = x² + 3x + 1</p><p>CasADi solves this elegantly by letting you define the function symbolically and then automatically computing the derivative with machine-level precision. Let’s see how that works in code.</p><h4><strong>Code Walkthrough</strong></h4><p>Below is an example script written in Python that demonstrates these steps. We’ll go through it line by line to explain what’s happening.</p><pre>import casadi as ca<br><br># 1. Define a symbolic variable &#39;x&#39;<br>x = ca.MX.sym(&#39;x&#39;)<br><br># 2. Create the function f(x) = x^2 + 3x + 1 using CasADi&#39;s symbolic operations<br>f = x**2 + 3*x + 1<br><br># 3. Create a CasADi function object for f. The first argument is the function&#39;s name,<br># the second is a list containing the function&#39;s inputs (symbolic variables),<br># and the third is a list containing the function&#39;s output.<br>F = ca.Function(&#39;F&#39;, [x], [f])<br><br># 4. Compute the derivative of f with respect to x using CasADi&#39;s automatic differentiation.<br># The jacobian() method computes the derivative (Jacobian) automatically.<br>F_jac = F.jacobian()<br><br># 5. Now evaluate the derivative at a specific point, for example at x = 2.<br># CasADi functions are called with a list or array of values corresponding to their inputs.<br>derivative_at_2 = F_jac([2])<br><br># 6. Print the resulting derivative value.<br>print(&quot;The derivative of f at x=2 is:&quot;, derivative_at_2)</pre><h4>Step-by-Step Explanation</h4><ol><li><strong>Symbolic Variable Definition:</strong><br> We start by creating a symbolic variable x that will serve as the input to our function. This is similar to declaring a variable in mathematics, but here it represents an expression rather than a fixed value.</li><li><strong>Function Definition:</strong><br> Using x, we define the mathematical function f(x) = x^2 + 3x + 1. CasADi lets you build this expression symbolically, so all operations on x are recorded as part of a computational graph.</li><li><strong>CasADi Function Object:</strong><br> The ca.Function object encapsulates our function. This abstraction allows CasADi to not only evaluate the function numerically but also to differentiate it and even generate low-level code for efficiency.</li><li><strong>Automatic Differentiation:</strong><br> With the .jacobian() method, CasADi automatically computes the derivative of the function with respect to x. Unlike finite difference methods, this derivative is computed exactly based on the chain rule applied to our computational graph.</li><li><strong>Evaluation at a Specific Point:</strong><br> We then evaluate the computed derivative at x=2. This step shows how easily you can obtain precise derivative values at any point of interest.</li><li><strong>Result:</strong><br> Finally, the script prints the derivative. In our case, you’d expect the derivative off(x) = x² + 3x + 1 to be f′(x)=2x+3 , which means at x=2, the derivative should be 2(2)+3=7.</li></ol><p>In this blog post, we’ve introduced CasADi as a powerful tool for automatic differentiation and numerical optimization. In the next part, we will solve a quadratic optimzation problem using CasADi.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12055f8e652f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>