<?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 Mohit Jain on Medium]]></title>
        <description><![CDATA[Stories by Mohit Jain on Medium]]></description>
        <link>https://medium.com/@mohitjain72?source=rss-52b350dff91d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GQYLO-XnWg-TU26paXbvlg.jpeg</url>
            <title>Stories by Mohit Jain on Medium</title>
            <link>https://medium.com/@mohitjain72?source=rss-52b350dff91d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 04:12:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohitjain72/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[Building An AI Enabled Robot — Part 5]]></title>
            <link>https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-5-831e4979cb5b?source=rss-52b350dff91d------2</link>
            <guid isPermaLink="false">https://medium.com/p/831e4979cb5b</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Mohit Jain]]></dc:creator>
            <pubDate>Sun, 13 Jul 2025 14:20:39 GMT</pubDate>
            <atom:updated>2025-07-13T18:38:55.790Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building An AI Enabled Robot — Part 5</h3><p>In case you don’t have membership, you can read it <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-5-831e4979cb5b?source=friends_link&amp;sk=49fbfd05fdf52c2fc1bd4bd31e1ea8d1">here</a>.</p><p>Special thanks to Hoa Mattaliano for her kind support.</p><p>Building upon the work, we discussed in <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-1-fecc688e5798">Part 1</a>, <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-2-3e6a86747c66">Part 2</a>, <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-3-68a71e44c140">Part3</a>, and <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-4-0418afedeb1a">Part 4</a>, to assemble an AI enabled robot, which can now detect and identify objects using AI, can measure objects’ distance from robot using stereo cameras , has GPS, LIDAR, and servos with controller to control camera angle, can measure environmental conditions (temperature, pressure and humidity), provides robot’s orientation using digital compass, can send information about robot’s position (roll, pitch and yaw), and uses Raspberry Pi 5 with Ubuntu 24.04 installed, in this part we will be installing more AI based capabilities, specifically <a href="https://en.wikipedia.org/wiki/Agentic_AI">Agentic AI</a>. This will comprise of utilizing <a href="https://www.crewai.com/open-source">CrewAI </a>platform for multi-agent systems, and controlling robot from a chat interface. This will allow, in future, to control robot by just talking to it.</p><p>Figure 1 shows the schematic of how we are going to deploy this system, but the basic idea is to send commands from a chat interface to the robot to either perform certain action, or fetch certain information from the robot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dl-ezJl5QpsKRqxohkY1Fg.png" /></figure><p><strong>Figure 1:</strong> Schematic of workflow on sending/receiving and orchestrating commands to/from the robot</p><p>As illustrated in Figure 1, the user types the command in the chatbot, for example to know the condition the robot is in — environment, diagnostic, objects around it, or asking it to move in certain direction. The command is passed through an API to multi-agents crew, via a router, and those agents based on the intent, call an appropriate tool, which in return call an API to create a ROS topic to subscribe or publish message, which are intercepted by the robot to do required action. I am using Crew AI Flows for multi-agent system, as I found it to be easy to use, and you can learn more about it <a href="https://docs.crewai.com/en/concepts/flows">here</a> and <a href="https://medium.com/@diwakarkumar_18755/a-comprehensive-guide-to-crewai-flows-building-a-smart-greeting-system-9d80f906847d">here</a>, or take a course <a href="https://www.udemy.com/course/the-complete-agentic-ai-engineering-course/">here</a>.</p><p>So now let’s breakdown the whole workflow into different sections, starting from the chatbot itself.</p><p><strong>A. Building the Chat Interface</strong></p><p>The chatbot from the UI side is build using JavaScript. Since, I only have minimal understanding of JavaScript, I utilized a coding assistant, i.e. vibe coding for that. Figure 2 shows the code for that and Figure 3 shows the corresponding interface. The message from the Chatbot is passed to the backend API, that uses FastAPI shown in Figure 4. The API calls multi-agent system, which utilizes CrewAI, as discussed in next section.</p><pre> &lt;!-- Chatbot CSS --&gt;<br>   &lt;style&gt;<br>        body { font-family: Arial, sans-serif; background: #f5f5f5; }<br>        #chatContainer { max-width: 500px; margin: 40px auto; background: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); padding: 20px; }<br>        #chatMessages { height: 300px; overflow-y: auto; border: 1px solid #ddd; border-radius: 4px; padding: 10px; margin-bottom: 15px; background: #fafafa; }<br>        .chat-message { margin-bottom: 10px; }<br>        .chat-message.user .message { background: #d1e7dd; align-self: flex-end; }<br>        .chat-message.bot .message { background: #74d471; align-self: flex-start; }<br>        .message { display: inline-block; padding: 8px 14px; border-radius: 16px; max-width: 80%; }<br>        form { display: flex; gap: 8px; }<br>        #chatInput { flex: 1; padding: 8px; border-radius: 4px; border: 1px solid #ccc; }<br>        button { padding: 8px 16px; border: none; border-radius: 4px; background: #42f760; color: #fff; cursor: pointer; }<br>        button:hover { background: #0056b3; }<br>    &lt;/style&gt;<br><br>&lt;!-- Chat container --&gt;<br>    &lt;div class=&quot;col-sm-12&quot;&gt;<br>      &lt;h2 style=&quot;text-align: center;&quot;&gt;Chat with the Robot&lt;/h2&gt;<br>      &lt;p style=&quot;text-align: center;&quot;&gt;Ask the robot questions or give it commands.&lt;/p&gt;<br>      <br>        &lt;div id=&quot;chatContainer&quot;&gt;<br>        &lt;div id=&quot;chatMessages&quot;&gt;&lt;/div&gt;<br>          &lt;form id=&quot;chatForm&quot; autocomplete=&quot;off&quot;&gt;<br>              &lt;input type=&quot;text&quot; id=&quot;chatInput&quot; placeholder=&quot;Type your message...&quot; required /&gt;<br>              &lt;button type=&quot;submit&quot;&gt;Send&lt;/button&gt;<br>          &lt;/form&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br><br>    &lt;!-- script to handle chat messages --&gt;<br>    &lt;script&gt;<br>        const chatForm = document.getElementById(&#39;chatForm&#39;);<br>        const chatInput = document.getElementById(&#39;chatInput&#39;);<br>        const chatMessages = document.getElementById(&#39;chatMessages&#39;);<br><br>        function appendMessage(text, sender) {<br>            const msgDiv = document.createElement(&#39;div&#39;);<br>            msgDiv.className = `chat-message ${sender} d-flex`;<br>            const msgContent = document.createElement(&#39;div&#39;);<br>            msgContent.className = &#39;message&#39;;<br>            msgContent.textContent = text;<br>            msgDiv.appendChild(msgContent);<br>            chatMessages.appendChild(msgDiv);<br>            chatMessages.scrollTop = chatMessages.scrollHeight;<br>        }<br><br>        chatForm.addEventListener(&#39;submit&#39;, async function(e) {<br>            e.preventDefault();<br>            const message = chatInput.value.trim();<br>            if (message) {<br>                appendMessage(message, &#39;user&#39;);<br>                chatInput.value = &#39;&#39;;<br>                // Send message to FastAPI backend<br>                try {<br>                    const response = await fetch(&#39;http://localhost:8000/robot&#39;, {<br>                        method: &#39;POST&#39;,<br>                        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>                        body: JSON.stringify({ message })<br>                    });<br>                    if (response.ok) {<br>                        console.log(&#39;Response received from server&#39;);<br>                        console.log(&#39;Response status:&#39;, response.status);<br>                        console.log(&#39;Response headers:&#39;, response.headers);<br>                        //console.log(&#39;Response body:&#39;, await response.text());<br><br>                        const data = await response.json();<br>                        console.log(&#39;Response body:&#39;, data.response);<br>                        appendMessage(data.response, &#39;bot&#39;);<br>                    } else {<br>                        appendMessage(&#39;Bot: Error communicating with server.&#39;, &#39;bot&#39;);<br>                    }<br>                } catch (err) {<br>                    appendMessage(&#39;Bot: Server not reachable.&#39;, &#39;bot&#39;);<br>                }<br>            }<br>        });<br>    &lt;/script&gt;</pre><p><strong>Figure 2:</strong> Code used for creating chat interface</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*3rEm9749-tqp5ahMxd1h3g.png" /></figure><p><strong>Figure 3:</strong> The chat interface to control the robot</p><pre>from fastapi import FastAPI, APIRouter, HTTPException<br>from pydantic import BaseModel<br>from main import kickoff  # Import the kickoff_async method from main.py<br>import asyncio<br>from fastapi.middleware.cors import CORSMiddleware<br>app = FastAPI()<br><br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;*&quot;], <br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)<br><br>@app.post(&quot;/robot&quot;)<br>async def create_bot_inputs(inputs: dict):<br>    &quot;&quot;&quot;<br>    Create a greeting based on the provided inputs.<br>    &quot;&quot;&quot;<br>    try:<br>        # Call the kickoff method of the RobotFlow with inputs<br>        result = await kickoff(inputs=inputs)<br>        return {&quot;response&quot;: result}<br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=str(e))</pre><p><strong>Figure 4: </strong>API to receive user query and kicking off the multi-agent system</p><p><strong>B.</strong> <strong>Building the Multi-Agent CrewAI Flows</strong></p><p>Once the message is passed through the user, via API, it kickoffs the crew, by using the Flows, shown in Figure 5, and corresponding code in Figure 6. Figure 7 shows the directory structure for the Flows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zb_JIXMkuPD92Fx6nnnKFQ.png" /></figure><p><strong>Figure 5:</strong> CrewAI Flows to kickoff the crew</p><pre>#!/usr/bin/env python<br>from random import randint<br><br>from pydantic import BaseModel<br><br>from crewai.flow import Flow, listen, start, router, or_, and_<br>from crewai import LLM<br>import json<br><br><br>from rosrobot_flow.crews.propulsion_crew.propulsion_crew import PropulsionCrew<br>from rosrobot_flow.crews.environment_crew.environment_crew import EnvironmentCrew<br>from rosrobot_flow.crews.scan_crew.scan_crew import ScanCrew<br>from rosrobot_flow.crews.diagnostic_crew.diagnostic_crew import DiagnosticCrew<br><br>from rosrobot_flow.base_models import PanTilt, IntentFormation<br>from dotenv import load_dotenv<br>load_dotenv()<br><br><br>class RobotConversationState(BaseModel):<br>    message: str = &quot;&quot;<br>    intent: str = &quot;&quot;<br>    confidence: float = 0.0<br>    response: str = &quot;&quot;<br><br><br>class RobotFlow(Flow[RobotConversationState]):<br><br>    def __init__(self, **kwargs):<br>        super().__init__(**kwargs)<br><br>    @start()<br>    def kickoff_async(self, inputs=None):<br>        # Assign inputs directly to state in kickoff and pass to route_based_on_relationship<br>        print(inputs)<br>        if inputs:<br>            # Initialize state with inputs<br>            for key, value in inputs.items():<br>                setattr(self.state, key, value)<br><br>        return super().kickoff_async(inputs=inputs)<br>    <br>    @listen(kickoff_async)<br>    def identify_intent(self):<br>        &quot;&quot;&quot;Identify the intent of the user query.&quot;&quot;&quot;<br>        print(&quot;Identifying intent from user query:&quot;, self.state.message)<br><br>        #initialize lll<br>        llm = LLM(model=&quot;openai/gpt-4.1-mini&quot;, response_format=IntentFormation)<br><br>        #create a prompt for intent identification<br>        prompt = f&quot;&quot;&quot;<br>        Identify the intent of the following user query and provide a confidence score:<br>        If the query is about scanning, propulsion, or environment, return the corresponding intent.<br>        If the query does not match any of these categories, return &quot;Not Intent Found&quot; with a confidence score of 0.0.<br>        Example intents:<br>        - Scan: &quot;Can you scan the area for obstacles?&quot;<br>        - Propulsion: &quot;How do we adjust the propulsion system?&quot;<br>        - Environment: &quot;What is the current environmental status?&quot;<br>        - Scan: &quot;Please adjust the pan and tilt angles to scan the area.&quot;<br>        - Propulsion: &quot;Can you move the robot forward?&quot;<br>        - Environment: &quot;What is the temperature in the environment?&quot;<br>        - Environment: &quot;What is your current location?&quot;<br>        - Environment: &quot;What is the current GPS location?&quot;<br>        - Environment: &quot;Which direction is the robot facing?&quot;<br>        - Environment: &quot;what is your roll, pitch and yaw?&quot;<br>        - Diagnostic: &quot;What is battery voltage?&quot;<br>        - Diagnostic: &quot;What is the current battery level?&quot;<br>        - Diagnostic: &quot;What is the currnet wattage consumed by the robot?&quot;<br>        - Diagnostic: &quot;What is the current power consumption?&quot;<br>        - Scan: &quot;can you move the camera up to 30 degrees?&quot;<br>        - Scan: &quot;can you move the camera down to 30 degrees?&quot;<br>        - Scan: &quot;can you move the camera left to 30 degrees?&quot;<br>        - Scan: &quot;can you move the camera right to 30 degrees?&quot;<br>        - Scan: &quot;can you move the camera to the left to 30 degrees and down to 40 degree?&quot;<br><br><br>        User Query: &quot;{self.state.message}&quot;<br>        Provide the intent and confidence in the format:<br>        intent: &lt;intent&gt;<br>        confidence: &lt;confidence_score&gt;<br>        &quot;&quot;&quot;<br>        # Call the LLM to identify intent<br>        result = llm.call(prompt)<br>        #Parse the result and update the state<br>        intent_dict = json.loads(result)<br>        self.state.intent = intent_dict.get(&quot;intent&quot;, &quot;&quot;)<br>        self.state.confidence = intent_dict.get(&quot;confidence&quot;, 0.0)<br>        print(f&quot;Identified intent: {self.state.intent} with confidence: {self.state.confidence}&quot;)<br><br>    <br>    @router(identify_intent)<br>    def route_based_on_query(self):<br>        &quot;&quot;&quot;Route based on intent to route the query.&quot;&quot;&quot;<br>        if self.state.intent == &quot;Scan&quot;:<br>            return &quot;scan_crew&quot;<br>        elif self.state.intent == &quot;Propulsion&quot;:<br>            return &quot;propulsion_crew&quot;<br>        elif self.state.intent == &quot;Environment&quot;:<br>            return &quot;environment_crew&quot;<br>        elif self.state.intent == &quot;Diagnostic&quot;:<br>            return &quot;diagnostic_crew&quot;<br>        else:<br>            self.state.intent = &quot;No intent found&quot;<br>            self.state.confidence = 0.0<br>            print(&quot;No intent found, returning default response.&quot;)       <br>            return &quot;NoIntent&quot;  # Return the intent if no crew matches<br>        <br>    @listen(&quot;scan_crew&quot;)<br>    def handle_scan_crew(self):<br>        &quot;&quot;&quot;Handle the ScanCrew.&quot;&quot;&quot;<br>        if self.state.intent == &quot;Scan&quot;:<br>            print(&quot;Handling ScanCrew&quot;)<br>            result = (<br>                ScanCrew()<br>                .crew()<br>                .kickoff(inputs={&quot;message&quot;: self.state.message})<br>            )<br>            print(&quot;Scan Crew Result:&quot;, result.raw)<br>            self.state.response = result.raw<br>            return self.state.response<br>        <br>    @listen(&quot;propulsion_crew&quot;)<br>    def handle_propulsion_crew(self):<br>        &quot;&quot;&quot;Handle the PropulsionCrew.&quot;&quot;&quot;<br>        if self.state.intent == &quot;Propulsion&quot;:<br>            print(&quot;Handling PropulsionCrew&quot;)<br>            result = (<br>                PropulsionCrew()<br>                .crew()<br>                .kickoff(inputs={&quot;message&quot;: self.state.message})<br>            )<br>            print(&quot;Propulsion Crew Result:&quot;, result.raw)<br>            self.state.response = result.raw<br>            return self.state.response<br>    <br>    @listen(&quot;environment_crew&quot;)<br>    def handle_environment_crew(self):<br>        &quot;&quot;&quot;Handle the EnvironmentCrew.&quot;&quot;&quot;<br>        if self.state.intent == &quot;Environment&quot;:<br>            print(&quot;Handling EnvironmentCrew&quot;)<br>            result = (<br>                EnvironmentCrew()<br>                .crew()<br>                .kickoff(inputs={&quot;message&quot;: self.state.message})<br>            )<br>            print(&quot;Environment Crew Result:&quot;, result.raw)<br>            self.state.response = result.raw<br>            return self.state.response<br>        <br>    @listen(&quot;diagnostic_crew&quot;)<br>    def handle_diagnostic_crew(self):<br>        &quot;&quot;&quot;Handle the DiagnosticCrew.&quot;&quot;&quot;<br>        if self.state.intent == &quot;Diagnostic&quot;:<br>            print(&quot;Handling DiagnosticCrew&quot;)<br>            result = (<br>                DiagnosticCrew()<br>                .crew()<br>                .kickoff(inputs={&quot;message&quot;: self.state.message})<br>            )<br>            print(&quot;Diagnostic Crew Result:&quot;, result.raw)<br>            self.state.response = result.raw<br>            return self.state.response<br>    <br>    @listen(&quot;NoIntent&quot;)<br>    def handle_no_intent(self):<br>        &quot;&quot;&quot;Handle the case where no intent is found.&quot;&quot;&quot;<br>        print(&quot;No intent found, returning default response.&quot;)<br>        self.state.response = &quot;No intent found. Please try again with a different query.&quot;<br>        return self.state.response<br><br><br>async def kickoff(inputs):<br>    print(&quot;Starting Robot Flow with inputs:&quot;, inputs)<br>    robot_flow = RobotFlow()<br>    return await robot_flow.kickoff_async(inputs=inputs)<br><br><br>def plot():<br>    robot_flow = RobotFlow()<br>    robot_flow.plot()<br><br></pre><p><strong>Figure 6:</strong> Code for Flows (main.py)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*OdshNGG6y1PN9CnhX3wfnQ.png" /></figure><p><strong>Figure 7:</strong> Directory Structure for the Flows</p><p>Initially, <strong>kickoff_async</strong> method, in main.py, takes the chat inputs and updates the crew state. Subsequently, identity_intent picks up, as it is using @listen decorator and calls LLM, in this case OpenAI GPT-4.1-mini, and classifies the intent, so appropriate crew can be called by the router. It also gets the confidence to identify the intent. The state is updated accordingly. Now, the intent is passed to the <strong>route_based_on_query</strong> method, and since it has @router decorator, it routes the information to the appropriate crew. The subsequent, @listen decorator is called, based on the crew identified.</p><p>Now, for example, I want to know the location where the robot is, and want to know the humidity at that location. This intent is associated with calling Environment Crew. So, <strong>handle_environment_crew</strong> method is called, and the message is passed to Environment Crew, shown in Figure 8. Here the agent <strong>env_crew_task_manager </strong>(Figure 9) selects the appropriate tasks. Since, we have asked robot for location and humidity, it is passed to two tasks, — <strong>local_env_task</strong> for humidity and l<strong>ocal_location__task</strong> for location. Figure 10 shows these two tasks information. Now local_env_task calls <strong>LocalEnvTool</strong>, shown in Figure 11. This tool in essence calls <strong>get_env_data</strong> API end point (Figure 12), which basically has a ROS2 subscriber (subscription_env) that receives the data from ROS2 publisher from the robot(<strong>/sensors/env</strong>), that in turn gets the data from BMP280 chip. We discussed about this robot ROS2 topic in previous <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-2-3e6a86747c66">blog</a>. Similar thing happens for local_location_task, where it calls <strong>GPSLocationTool</strong>. Figure 13 shows the whole chain of execution, starting from this query. Figure 14, shows the actual execution, printed on terminal, as AI goes through various steps.</p><pre>from crewai import Agent, Crew, Process, Task<br>from crewai.project import CrewBase, agent, crew, task<br>from crewai.agents.agent_builder.base_agent import BaseAgent<br>from typing import List<br>from rosrobot_flow.tools.local_env_tool import LocalEnvTool<br>from rosrobot_flow.tools.gps_location import GPSLocationTool<br># If you want to run a snippet of code before or after the crew starts,<br># you can use the @before_kickoff and @after_kickoff decorators<br># https://docs.crewai.com/concepts/crews#example-crew-class-with-decorators<br><br>@CrewBase<br>class EnvironmentCrew():<br>    &quot;&quot;&quot;EnvironmentCrew crew&quot;&quot;&quot;<br><br>    agents: List[BaseAgent]<br>    tasks: List[Task]<br><br>    # Learn more about YAML configuration files here:<br>    # Agents: https://docs.crewai.com/concepts/agents#yaml-configuration-recommended<br>    # Tasks: https://docs.crewai.com/concepts/tasks#yaml-configuration-recommended<br>    <br>    # If you would like to add tools to your agents, you can learn more about it here:<br>    # https://docs.crewai.com/concepts/agents#agent-tools<br>    @agent<br>    def env_crew_task_manager(self) -&gt; Agent:<br>        return Agent(<br>            config=self.agents_config[&#39;env_crew_task_manager&#39;], # type: ignore[index]<br>            verbose=True<br>        )<br><br>    # To learn more about structured task outputs,<br>    # task dependencies, and task callbacks, check out the documentation:<br>    # https://docs.crewai.com/concepts/tasks#overview-of-a-task<br>    @task<br>    def get_local_task(self) -&gt; Task:<br>        return Task(<br>            config=self.tasks_config[&#39;local_env_task&#39;], # type: ignore[index]<br>            tools=[LocalEnvTool()]# Register the LocalEnvTool<br>        )<br>    @task<br>    def get_gps_task(self) -&gt; Task:<br>        return Task(<br>            config=self.tasks_config[&#39;local_location_task&#39;], # type: ignore[index]<br>            tools=[GPSLocationTool()]# Register the GPSLocationTool<br>        )<br><br><br>    @crew<br>    def crew(self) -&gt; Crew:<br>        &quot;&quot;&quot;Creates the ScanCrew crew&quot;&quot;&quot;<br>        # To learn how to add knowledge sources to your crew, check out the documentation:<br>        # https://docs.crewai.com/concepts/knowledge#what-is-knowledge<br><br>        return Crew(<br>            agents=self.agents, # Automatically created by the @agent decorator<br>            tasks=self.tasks, # Automatically created by the @task decorator<br>            process=Process.sequential,<br>            verbose=True,<br>            # process=Process.hierarchical, # In case you wanna use that instead https://docs.crewai.com/how-to/Hierarchical/<br>        )</pre><p><strong>Figure 8: </strong>Environment Crew Code</p><pre>env_crew_task_manager:<br>  role: &gt;<br>    {message} Environment Task Manager<br>  goal: &gt;<br>    Find the most relevant task based on the user query {message}<br>  backstory: &gt;<br>    You are a task manager specializing in finding the appropriate tasks<br>    based on user queries. You excel at understanding the context and<br>    requirements of the tasks, ensuring that the right task is assigneg.<br><br>  instructions: &gt;<br>    1. Analyze the user&#39;s query {message} to identify the key requirements and context.<br>    2. Search through the available tasks to find the most relevant one.<br>    3. Provide a clear and concise response with the selected task details.<br>    4. If no relevant task is found, suggest alternative actions or tasks.<br>  examples:<br>    - user_query: &quot;I need to find the temperature around the area.&quot;<br>      response: &quot;The most relevant task is local_env_task.&quot;<br>    - user_query: &quot;I need to find the humidity around the area.&quot;<br>      response: &quot;The most relevant task is local_env_task.&quot;<br>    - user_query: &quot;I need to find the pressure around the area.&quot;<br>      response: &quot;The most relevant task is local_env_task.&quot;<br>    - user_query: &quot;I need to find the local environmental conditions.&quot;<br>      response: &quot;The most relevant task is local_env_task.&quot;<br>    - user_query: &quot;I need to find your location&quot;<br>      response: &quot;The most relevant task is local_location_task.&quot;<br>    - user_query: &quot;where are you located?&quot;<br>      response: &quot;The most relevant task is local_location_task.&quot;<br>    - user_query: &quot;Tell me your gps coordinates.&quot;<br>      response: &quot;The most relevant task is local_location_task.&quot;<br>    - user_query: &quot;what longitude and latitude are you at?&quot;<br>      response: &quot;The most relevant task is local_location_task.&quot;</pre><p><strong>Figure 9:</strong> Env_Crew_Task_Manager Agent Code</p><pre>local_env_task:<br>  description: &gt;<br>    Analyze the {message} and look for the information user is asking for. You can only provide information about temperature, pressure and humidity. Only provide <br>    the information that the user is asking for. For exampke if the user is asking for temperature, only provide the temperature information. If the user is asking for pressure, only provide the pressure information. If the user is asking for humidity, only provide the humidity information. If the user is asking for all three, provide all three information.<br>    The information should be provided in a clear and concise manner. The user is asking for the local envirnment conditons than provide all three information.<br>    The information should be provided in a format that is easy to understand.<br>    For example, if the user is asking for temperature, provide the temperature in degrees Celsius, pressure in atm, and humidity in percentage.<br>    If the user is asking for all three, provide all three information in a single sentence.<br>    Example: &quot;Temperature is 25 degrees Celsius, pressure is 1.017 atm, and humidity is 60% at my current location.&quot;<br>    The information is given in degrees Celsius for temperature, atm for pressure, and percentage for humidity. Pass the message to LocalEnvTool in json format. You need to use the LocalEnvTool to get the local environmental conditions.<br>    Use the output from LocalEnvTool to provide the information to the user, using the format specified in expected_output. Pass the output to the user in a clear and concise manner.<br>  parameters:<br>    - name: message<br>      type: str<br>      description: &gt;<br>        The message containing the query for local environmental conditions.<br>        Example: &quot;What is the current temperature, pressure, and humidity in the area?&quot;<br>  expected_output: &gt;<br>    The expected output is a description of the local environmental conditions based on the provided message.<br>    The output should clearly state the temperature in degrees Celsius, pressure in atm, and humidity in percentage. Howvere if the user is asking for only one of the three, then only provide that information. For example,<br>    if the user is asking for temperature, provide the temperature in degrees Celsius, if the user is asking for pressure, provide the pressure in atm, and if the user is asking for humidity, provide the humidity in percentage.<br>    If the user is asking for all three, provide all three information in a single sentence.<br>    Make sure to provide the information in a clear and concise manner.<br>  examples:<br>    - user_query: &quot;What is the current temperature in the area?&quot;<br>      response: &quot;The current temperature is 25 degrees Celsius.&quot;<br>    - user_query: &quot;What is the current pressure in the area?&quot;<br>      response: &quot;The current pressure is 1.017 atm.&quot;<br>    - user_query: &quot;What is the current humidity in the area?&quot;<br>      response: &quot;The current humidity is 60%.&quot;<br>    - user_query: &quot;What are the local environmental conditions?&quot;<br>      response: &quot;The current temperature is 25 degrees Celsius, pressure is 1.017 atm, and humidity is 60% at my current location.&quot;<br><br>  agent: env_crew_task_manager<br><br>local_location_task:<br>  description: &gt;<br>    Analyze the {message} and look for the information user is asking for. You can only provide information about the current location of the robot.<br>    The information should be provided in a clear and concise manner.<br>    The information should be provided in a format that is easy to understand.<br>    You neeed to use GPSLocationTool to get the current location of the robot.<br>    For example, if the user is asking for the current location, provide the current location in latitude and longitude format.<br>  parameters:<br>    - name: message<br>      type: str<br>      description: &gt;<br>        The message containing the query for the current location of the robot.<br>        Example: &quot;What is your current location?&quot;<br>  expected_output: &gt;<br>    The expected output is a description of the current location of the robot based on the provided message.<br>    The output should clearly state the current location in latitude and longitude format.<br>  examples:<br>    - user_query: &quot;What is your current location?&quot;<br>      response: &quot;My current location is at latitude 37.7749° N, longitude 122.4194° W.&quot;<br>    - user_query: &quot;Where are you located?&quot;<br>      response: &quot;I am located at latitude 37.7749° N, longitude 122.4194° W.&quot;<br><br>  agent: env_crew_task_manager</pre><p><strong>Figure 10:</strong> Environment Crew Tasks Code</p><pre>from typing import Type<br><br>from crewai.tools import BaseTool<br>from pydantic import BaseModel, Field<br>import requests<br>import json<br><br><br>class LocalEnvToolInput(BaseModel):<br>    &quot;&quot;&quot;Input schema for MyCustomTool.&quot;&quot;&quot;<br><br>    argument: str = Field(..., description=&quot;Get the local conditions for the robot.&quot;)<br><br><br>class LocalEnvTool(BaseTool):<br>    name: str = &quot;Local Env Tool&quot;<br>    description: str = (<br>        &quot;This tool will accept the data from get_env_data endpoint and return temeperature, humidity and pressure.&quot;<br>        &quot; It is used to get the local environment data of the robot.&quot;<br>        &quot;it will send temperature, humidity and pressure values as requested by local_env_task&quot;<br>    )<br>    args_schema: Type[BaseModel] = LocalEnvToolInput<br><br>    def _run(self, argument: str) -&gt; str:<br>        # Implementation goes here<br>        print(f&quot;Running LocalEnvTool with argument: {argument}&quot;)<br>        # Here we will call the FastAPI endpoint to get the environment data<br>        # and return the data as a string.<br><br>        try:<br>            response = requests.get(<br>                &quot;http://localhost:9000/get_env_data/&quot;,<br>                timeout=5<br>            )<br>            response.raise_for_status()<br>            data = response.json()<br>            <br>        except requests.RequestException as e:<br>            return f&quot;Failed to get env values: {e}&quot;<br>    <br>        output = str(data)<br>        return output</pre><p><strong>Figure 11:</strong> LocalEnvTool Code</p><pre>from fastapi import FastAPI, HTTPException<br>from pydantic import BaseModel<br>import rclpy<br>from rclpy.node import Node<br>from std_msgs.msg import String, Int32, Float32<br>import threading<br>import json<br>import atexit<br>from fastapi.middleware.cors import CORSMiddleware<br># Enable CORS for FastAPI<br><br># ROS2 Node in a thread<br>class RosPublisherNode(Node):<br>    def __init__(self):<br>        super().__init__(&#39;fastapi_ros_publisher&#39;)<br><br>        self.publisher_servo = self.create_publisher(String, &#39;camera_angle&#39;, 10)<br>        self.latest_param_servo = None<br>        self.publisher_timer_servo = self.create_timer(0.25, self._timer_callback_servo)<br>        <br>        # Subscriber: Environment data<br>        self.subscription_env = self.create_subscription(<br>                String,<br>                &#39;/sensors/env&#39;,<br>                self.env_callback,<br>                10<br>            )<br>        self.subscription_env  # prevent unused variable warning<br>        self.latest_env_msg = None<br><br>        # Subscriber: GPA data<br>        self.subscription_gps = self.create_subscription(<br>                String,<br>                &#39;/sensors/gps&#39;,<br>                self.gps_callback,<br>                10<br>            )<br>        self.subscription_gps  # prevent unused variable warning<br>        self.latest_gps_msg = None<br>    <br>    def env_callback(self, msg):<br>        self.latest_env_msg = msg.data<br>        self.get_logger().info(f&#39;Received message on /sensors/env: {msg.data}&#39;)<br><br>    def gps_callback(self, msg):<br>        self.latest_gps_msg = msg.data<br>        self.get_logger().info(f&#39;Received message on /sensors/gps: {msg.data}&#39;)<br><br><br>    def update_param_servo(self, pan: float, tilt: float):<br>        if not isinstance(pan, float) or not isinstance(tilt, float):<br>            raise ValueError(&quot;Pan and tilt must be float values.&quot;)<br>        self.latest_param_servo = json.dumps({&quot;pan&quot;: pan, &quot;tilt&quot;: tilt})<br><br><br>    def _timer_callback_servo(self):<br>        if self.latest_param_servo is not None:<br>            msg = String()<br>            msg.data = self.latest_param_servo<br>            self.publisher_servo.publish(msg)<br>            self.get_logger().info(f&#39;Published Servo: {msg.data}&#39;)<br><br>def ros_spin(node):<br>    rclpy.spin(node)<br><br># FastAPI app<br>app = FastAPI()<br># CORS configuration<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;*&quot;],  <br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)<br><br># Pydantic models for request bodies<br><br>class ServoParam(BaseModel):<br>    pan: float<br>    tilt: float<br><br># Initialize ROS2 node and start spinning in a separate thread<br>rclpy.init()<br>ros_node = RosPublisherNode()<br>ros_thread = threading.Thread(target=ros_spin, args=(ros_node,), daemon=True)<br>ros_thread.start()<br><br><br>@app.post(&quot;/send_servo_param/&quot;)<br>def send_param_servo(param: ServoParam):<br>    try:<br>        ros_node.update_param_servo(param.pan, param.tilt)<br>        return {&quot;status&quot;: &quot;Servo parameter sent to ROS2 topic&quot;}<br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=str(e))<br>    <br>@app.get(&quot;/get_env_data/&quot;)<br>def get_env_data():<br>    if ros_node.latest_env_msg is not None:<br>        return {ros_node.latest_env_msg}<br>    else:<br>        raise HTTPException(status_code=404, detail=&quot;No environment data received yet&quot;)<br><br>@app.get(&quot;/get_gps_data/&quot;)<br>def get_gps_data():<br>    if ros_node.latest_gps_msg is not None:<br>        return {ros_node.latest_gps_msg}<br>    else:<br>        raise HTTPException(status_code=404, detail=&quot;No GPS data received yet&quot;)<br><br># Graceful shutdown<br>@atexit.register<br>def shutdown():<br>    ros_node.destroy_node()<br>    rclpy.shutdown()</pre><p><strong>Figure 12:</strong> FastAPI get_env_data endpoint code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sNCJpR-lAwdtRc1OG9y8TQ.png" /></figure><p><strong>Figure 13:</strong> Chain of execution, after user query — “Can you give me environmental conditions at your current location”. Location information is partially masked for privacy reasons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tn1WV3txjBVn1liNY-K6ZQ.png" /></figure><p><strong>Figure 14:</strong> Output in CrewAI Flows for the query — “Can you give me environmental conditions at your current location”. Numbers indicate sequence of execution. Location information is partially masked for privacy reasons.</p><p>When we need to control any components of robot, for example movement or camera angle we can apply similar strategy. For example, if I want to control stereo camera angle, I can type “can you move the camera left to 30 degree and up to 45 degree”. This will call Scan Crew and will follow the similar flow (<strong>Scan Crew → scan_crew_task_manager → pan_tilt_camera_task → PanTiltTool → FastAPI → ROS2 Publisher → Robot ROS2 Subscriber → Servo Driver Module → Servo Motors</strong>). Figure 15 shows robot response and also Figure 16 shows steps printed by CrewAI Flows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*zcAyzPRIt_X3sy0lnmmizw.png" /></figure><p><strong>Figure 15:</strong> Robot response for the command to change the camera angle</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7OTmbtM3hjXSYNG7FP3Ndg.png" /></figure><p><strong>Figure 16:</strong> Output in CrewAI Flows, when execution request to change camera angle. Numbers indicates sequence of execution.</p><p>This work shows that now the robot can be controlled, relatively easily, just by chatting with it, and in future just by talking to it, by leveraging multi-agent frameworks like CrewAI and LangGraph.</p><p>This is the end of Part 5 of the series. Some tips, which I learned:</p><p>1. Always make sure that while designing the multi-agent system for the robot, you have specified all the details — like how to aggregates tasks in appropriate crews, and which tools to call, based on the functionalities.</p><p>2. Since all the communications with the robot is happening through ROS2 topics, the messages passed to the robots should be properly validated, to prevent failures. Try to use BaseModel class from Pydantic library to minimize this.</p><p>3. Keep track of these fast evolving multi-agent frameworks to integrate the latest capabilities.</p><p>In the next blog we will further enhance the robot capabilities using multi-agent framework, and finally giving robot freedom to move around.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=831e4979cb5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building An AI Enabled Robot — Part 4]]></title>
            <link>https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-4-0418afedeb1a?source=rss-52b350dff91d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0418afedeb1a</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Mohit Jain]]></dc:creator>
            <pubDate>Mon, 26 May 2025 16:42:21 GMT</pubDate>
            <atom:updated>2025-05-26T23:41:20.482Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building An AI Enabled Robot — Part 4</strong></h3><p>In case you don’t have membership, you can read it <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-4-0418afedeb1a?source=friends_link&amp;sk=546c29f15a72f947cc95abaa74dbbeec">here</a>.</p><p>Special thanks to Hoa Mattaliano for her kind support.</p><p>Building upon the work, we discussed in <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-1-fecc688e5798">Part 1</a>, <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-2-3e6a86747c66">Part 2</a> and <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-3-68a71e44c140">Part 3</a>, to assemble an AI enabled robot, which now has GPS, LIDAR, and servos with controller to control camera angle, in this part we will discuss about installing stereo camera and using it with Raspberry Pi 5. Further we will be doing object detection and using stereo images taken by this module to estimate distance of the nearby detected objects.</p><p>Figure 1 shows the picture of the camera installed on a pan/tilt servo mount and the angle is controlled by PCA9685 board, which was discussed in <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-3-68a71e44c140">Part 3</a>. The camera module is <a href="https://www.amazon.com/dp/B086JTDG25?ref=ppx_yo2ov_dt_b_fed_asin_title">Waveshare Binocular Camera module </a>with Dual IMX219 8 Megapixels cameras. The camera is connected to Raspberry Pi 5, using two FCC cables. The module also comes with 9DOF IMU, which we will use in future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTtVaKEQ6wVEtxLhCC60TQ.jpeg" /></figure><p>Figure 1: Stereo camera module installed on the robot and connected to Raspberry Pi 5</p><p>Now let’s discuss different libraries we will need to take images from these cameras. The complications comes as we are using Ubuntu 24.04 OS for Raspberry Pi, which comes with additional work to be performed, compared to the standard Raspberry PI OS. This answer in <a href="https://askubuntu.com/questions/1542652/getting-rpicam-tools-rpicam-apps-working-on-ubuntu-22-04-lts-for-the-raspber">askubuntu.com</a> provides a good description to achieve this. Essentially it will require you to build the libcamera and rpicam-apps from source, before your camera is detected and used by Ubuntu OS 24.04 installed on Raspberry Pi 5. Once installed, you need to make changes in your config.txt file in /boot/firmware directory, for cameras to be registered. Figure 2 shows the desired configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*MWIzIc-m2IleIiad3iVZZw.png" /></figure><p>Figure 2: Camera setup in config.txt file, for cameras to be detected by OS</p><p>Once rpicam app is installed, we can use various commands that can be utilized to take image and video at various setting. This <a href="https://www.waveshare.com/wiki/RPi_Camera_(G)">link</a> and <a href="https://www.raspberrypi.com/documentation/computers/camera_software.html">this</a> link provides a good description of using rpicam app. In our case, we need to solve not only the issue of taking images of our desired setting but also take those pictures as in-sync as possible. Since, the module does not come with any hardware control to take pictures in-sync, I decided to use python <a href="https://www.geeksforgeeks.org/processpoolexecutor-class-in-python/">ProcessPoolExecutor</a> class to activate both cameras in parallel. The average time difference observed between the two images taken was around 15 ms, which is reasonable, compared to taking in sequence, which was over 1 second. Figure 3 shows the code utilized for that.</p><pre>import subprocess<br>from concurrent.futures import ProcessPoolExecutor<br>import time<br><br>def my_parallel_command(command):<br>    subprocess.run(command, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)<br><br>ratio = 4<br>height = int(2464/ratio)<br>width = int(3280/ratio)<br>cameraL = f&quot;rpicam-still --camera 0 --width {width} --height {height} -n --immediate -o Documents/camera_data/cameraL/stereoL_ros.png --vflip --hflip&quot;<br>cameraR = f&quot;rpicam-still --camera 1 --width {width} --height {height} -n --immediate -o Documents/camera_data/cameraR/stereoR_ros.png --vflip --hflip&quot;<br>sleep_capture = time.sleep(0.1)<br>commands = [cameraL, cameraR]<br>    <br>cpus = 2<br>with ProcessPoolExecutor(max_workers = cpus) as executor:<br>    futures = executor.map(my_parallel_command, commands)</pre><p>Figure 3: Code to take pictures from both cameras in parallel from stereo camera module</p><p>Once, I figure out how to take the images from both the cameras in close to in-sync, the next step was to create a ROS node to transmit these images over the Wi-Fi so they can be consumed by the code running on the desktop for object detection and depth estimation. Figure 4 shows the code to use that. One thing I did was combining the images from both left and right cameras, before transmitting, to make sure they are taken within a small time interval (~ 15 ms). For this, I used OpenCV hconcat function.</p><pre>import rclpy<br>from rclpy.node import Node<br>from std_msgs.msg import String<br>from sensor_msgs.msg import Image, CompressedImage <br>import serial<br>import time<br>import math<br>import numpy as np<br>import subprocess<br>import time<br>import cv2<br>from cv_bridge import CvBridge<br><br>class RosRobotImageNode(Node):<br><br>    def __init__(self):<br>        super().__init__(&quot;rosrobot_camera_image&quot;)<br><br>        <br>        timer_period = 0.5 #seconds<br>        self.publisher_image = self.create_publisher(CompressedImage, &quot;image/compressed&quot;, 10)<br>        self.timer_image = self.create_timer(timer_period, self.publish_camera_image)<br><br>        self.publisher_stereo = self.create_publisher(CompressedImage, &quot;stereo/compressed&quot;, 10)<br>        self.timer_stereo = self.create_timer(timer_period, self.publish_camera_stereo)<br>        <br>        self.image_path_r = f&quot;Documents/camera_data/cameraR/stereoR_ros.png&quot;<br>        self.image_path_l = f&quot;Documents/camera_data/cameraL/stereoL_ros.png&quot;<br>        self.image_l = cv2.imread(self.image_path_l, cv2.IMREAD_COLOR)<br>        self.image_r = cv2.imread(self.image_path_l, cv2.IMREAD_COLOR)<br>        self.stack_image = cv2.hconcat([self.image_l, self.image_r])<br><br>        # convert between ROS and OpenCV images<br>        self.br = CvBridge()<br>        <br>        self.get_logger().info(&quot;Camera Image Broadcast Started...&quot;)<br><br>    def camera_parallel_command(self, command):<br>        subprocess.run(command, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)<br>    <br>    def publish_camera_image(self):<br><br>        command = f&quot;python Documents/ros2_ws/src/camera_pkg/camera_pkg/camera_multiprocess.py&quot;<br>        kill_command = f&quot;pkill -9 -f Documents/ros2_ws/src/camera_pkg/camera_pkg/camera_multiprocess.py&quot;<br>        subprocess.run(command, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)<br>        time.sleep(0.25)<br>        subprocess.run(kill_command, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)<br><br>        self.image_l = cv2.imread(self.image_path_l, cv2.IMREAD_COLOR)<br>        self.image_r = cv2.imread(self.image_path_r, cv2.IMREAD_COLOR)<br>        image_l_gray = cv2.imread(self.image_path_l, cv2.IMREAD_GRAYSCALE)<br>        image_r_gray = cv2.imread(self.image_path_r, cv2.IMREAD_GRAYSCALE)<br>        self.stack_image = cv2.hconcat([self.image_l, self.image_r])<br><br>        self.publisher_image.publish(self.br.cv2_to_compressed_imgmsg(self.image_l, &#39;jpeg&#39;))<br><br>    def publish_camera_stereo(self):<br>        self.publisher_stereo.publish(self.br.cv2_to_compressed_imgmsg(self.stack_image, &#39;png&#39;))<br><br><br>def main(args=None):<br>    rclpy.init(args=args)<br>    node = RosRobotImageNode()<br>    rclpy.spin(node=node)<br>    rclpy.shutdown()<br><br>if __name__==&quot;__main__&quot;:<br>    main()</pre><p>Figure 4: ROS node for transmitting stereo images</p><p>Controlling the camera angle using servos was relatively easy, and I used <a href="https://docs.circuitpython.org/projects/servokit/en/stable/">Adafruit ServoKit</a> library. Figure 5 shows the ROS node used for that.</p><pre>import rclpy<br>from rclpy.node import Node<br>from std_msgs.msg import String<br>import json<br>import time<br>from adafruit_servokit import ServoKit<br>import busio<br><br>class RosRobotCameraAngleNode(Node):<br><br>    def __init__(self):<br>        super().__init__(&quot;rosrobot_camera_angle_get&quot;)<br>        self.subscriber_env = self.create_subscription(<br>             String, &quot;camera_angle&quot;, self.callback_rosrobot_angle, 10)<br>        <br>        self.i2c_bus = busio.I2C(3, 2)<br>        self.kit = ServoKit(i2c = self.i2c_bus, channels=16)<br><br>        self.center_angle = 65<br>        self.horizontal_angle = 7 <br>        <br>        self.get_logger().info(&quot;Camera Angle Control Started...&quot;)<br><br>    def callback_rosrobot_angle(self, msg:String):<br>        data_camera_angle = msg.data<br>        data_list = data_camera_angle.split(&#39;,&#39;)<br>        tilt_angle = float(data_list[0])<br>        pan_angle = float(data_list[1])<br>        self.kit.servo[14].angle = self.center_angle + pan_angle #65 is center<br>        self.kit.servo[15].angle = self.horizontal_angle + tilt_angle #7 is horizontal<br>        <br>        self.get_logger().info(f&quot;Tilt: {tilt_angle}, Pan: {pan_angle}&quot;)<br><br><br>def main(args=None):<br>    rclpy.init(args=args)<br>    node = RosRobotCameraAngleNode()<br>    rclpy.spin(node=node)<br>    rclpy.shutdown()<br><br>if __name__==&quot;__main__&quot;:<br>    main()</pre><p>Figure 5: ROS node for controlling camera angle</p><p>This is all we need to do from Raspberry Pi side to transmit the stereo images, over the Wi-Fi and controlling the camera angle. Next step is utilizing these images for object detection and depth/distance estimations.</p><p>Let’s start with object detection using AI and rendering those images on UI. First thing we need to do is to consume the stereo image transmitted by Raspberry Pi and split them into left and right camera image. This is achieved by subscribing /stereo/compress ROS topic broadcast by the robot, and OpenCV to extract image by providing it the indices of starting pixels and ending pixels for each image. Subsequently, we save them as left and right images, for further processing. Figure 6 shows the code for this node.</p><pre>import rclpy<br>from rclpy.node import Node<br>from std_msgs.msg import String<br>from sensor_msgs.msg import Image, CompressedImage <br>import json<br>import time<br><br>import cv2<br>from cv_bridge import CvBridge, CvBridgeError<br><br>class RosRobotStereoNode(Node):<br><br>    def __init__(self):<br>        super().__init__(&quot;rosrobot_stereo_get&quot;)<br>        self.subscriber_stereo = self.create_subscription(<br>             CompressedImage, &quot;/stereo/compressed&quot;, self.callback_rosrobot_stereo, 10)<br>        <br>        self.subscriber_image = self.create_subscription(<br>             CompressedImage, &quot;/image/compressed&quot;, self.callback_rosrobot_image, 10)<br><br>        self.publisher_depthmap = self.create_publisher(CompressedImage, &#39;/image/object&#39;, 10)<br>        self.publisher_depth_timer = self.create_timer(1.0, self.callback_depthmap_image)<br><br>        # convert between ROS and OpenCV images<br>        self.br = CvBridge()<br>        self.image_path = f&quot;Documents/AI/RosRobot/RosRobotUI/images/stereo.png&quot;<br>        self.image_path_l = f&quot;Documents/AI/RosRobot/RosRobotUI/images/stereoL.png&quot;<br>        self.image_path_r = f&quot;Documents/AI/RosRobot/RosRobotUI/images/stereoR.png&quot;<br>        self.image_path_color = f&quot;Documents/AI/RosRobot/RosRobotUI/images/color_image.png&quot;<br>        self.image_path_object = f&quot;Documents/AI/RosRobot/RosRobotUI/images/image_object_L_matched.png&quot;<br>        #self.cv_image = cv2.imread(self.image_path, cv2.IMREAD_GRAYSCALE)<br><br>        self.get_logger().info(&quot;Stereo Image Processing Started...&quot;)<br><br>    def callback_rosrobot_stereo(self, data):<br>        try:<br>            self.cv_image = self.br.compressed_imgmsg_to_cv2(data)<br>            ratio = 4<br>            width = int(3280/ratio)<br>            height = int(2664/ratio)<br><br>            cv2.imwrite(self.image_path, self.cv_image)<br>            #self.get_logger().info(cv_image.shape)<br>            # Make sure to check size of stereo image sent by RPi<br>            x_l, y_l, w, h = 0, 0, width, height<br>            stereoL = self.cv_image[y_l:y_l+h, x_l:x_l+w]<br>            cv2.imwrite(self.image_path_l, stereoL)<br><br>            x_r, y_r, w, h = 820, 0, width, height<br>            stereoR = self.cv_image[y_r:y_r+h, x_r:x_r+w]<br>            cv2.imwrite(self.image_path_r, stereoR)<br>            time.sleep(0.1)<br>            # use object detection to identify <br><br>        except CvBridgeError as e:<br>            print(e)<br><br>    def callback_rosrobot_image(self, data):<br>        try:<br>            self.cv_image = self.br.compressed_imgmsg_to_cv2(data)<br>            cv2.imwrite(self.image_path_color, self.cv_image)<br><br>        except CvBridgeError as e:<br>            print(e)<br><br>    def callback_depthmap_image(self):<br>        depthmap_image = cv2.imread(self.image_path_object, cv2.IMREAD_COLOR)<br>        self.publisher_depthmap.publish(self.br.cv2_to_compressed_imgmsg(depthmap_image, &#39;jpeg&#39;))<br>  <br>def main(args=None):<br>    rclpy.init(args=args)<br>    node = RosRobotStereoNode()<br>    rclpy.spin(node=node)<br>    rclpy.shutdown()<br><br>if __name__==&quot;__main__&quot;:<br>    main()</pre><p>Figure 6: ROS node for subscribing stereo images transmitted by Raspberry Pi and splitting stereo image to left and right camera images</p><p>Once, we have the separate stereo images, we can detect the objects in each of them, and extract the bounding box for those objects. I used Facebook’s <a href="https://huggingface.co/facebook/detr-resnet-101">ResNet-101</a> model. It is a DEtection TRansformer (DETR) model trained end-to-end on COCO 2017 object detection (118k annotated images) with object queries set of 100. Determining accurate position of the same object in both stereo images allows us to calculated how far the object is from the camera.</p><p>Before we feed these images to the Object Detection model, we need to remove distortion caused by camera lens in the images. It is not as such required for object detection but highly recommended if we are using the images for depth estimation, subsequently. This is where camera calibration comes in play for removing distortion. We utilized OpenCV module for that, and details on how to use this can be found <a href="https://docs.opencv.org/4.x/dc/dbb/tutorial_py_calibration.html">here</a>. This <a href="https://medium.com/into-the-ai-frontier-navigating-genai-computer/pythonic-eyes-unveiling-the-art-of-stereo-vision-calibration-with-opencv-537628cd5a25">blog</a> post also provides a good explanation. Typically, we calibrate the camera using a chessboard pattern, and take several images of that pattern at different angles and positions. Since, the flatness of this pattern is very critical, it is better to use a tablet such as iPad to display the pattern. Once you have at least 15–20 images “in-sync” from both the cameras, we can calibrate both the cameras. A typical chessboard image will look like what is shown in Figure 7. To be noted the I cropped the full image, due to privacy concern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*YVGjh_fOw2xKXI74RAGmLw.png" /></figure><p>Figure 7: Typical image used during camera calibration</p><p>The code to calibrate the camera, is shown in Figure 8.</p><pre>import cv2<br>import numpy as np<br>import glob<br><br># Settings<br>chessboard_size = (9, 6)<br>square_size = 0.025  # meters<br>left_images_path = &#39;camera_data/cameraL/*.png&#39;<br>right_images_path = &#39;camera_data/cameraR/*.png&#39;<br><br># Prepare object points<br>objp = np.zeros((chessboard_size[0]*chessboard_size[1], 3), np.float32)<br>objp[:, :2] = np.mgrid[0:chessboard_size[0], 0:chessboard_size[1]].T.reshape(-1, 2)<br>objp *= square_size<br><br>objpoints = []<br>imgpoints_left = []<br>imgpoints_right = []<br><br>left_images = sorted(glob.glob(left_images_path))<br>right_images = sorted(glob.glob(right_images_path))<br><br>for left_img_path, right_img_path in zip(left_images, right_images):<br>    img_left = cv2.imread(left_img_path)<br>    img_right = cv2.imread(right_img_path)<br>    gray_left = cv2.cvtColor(img_left, cv2.COLOR_BGR2GRAY)<br>    gray_right = cv2.cvtColor(img_right, cv2.COLOR_BGR2GRAY)<br><br>    ret_left, corners_left = cv2.findChessboardCorners(gray_left, chessboard_size, None)<br>    ret_right, corners_right = cv2.findChessboardCorners(gray_right, chessboard_size, None)<br><br>    if ret_left and ret_right:<br>        objpoints.append(objp)<br>        corners2_left = cv2.cornerSubPix(gray_left, corners_left, (11, 11), (-1, -1),<br>                                         criteria=(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001))<br>        corners2_right = cv2.cornerSubPix(gray_right, corners_right, (11, 11), (-1, -1),<br>                                          criteria=(cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001))<br>        imgpoints_left.append(corners2_left)<br>        imgpoints_right.append(corners2_right)<br><br># Calibrate individual cameras<br>ret_left, mtx_left, dist_left, rvecs_left, tvecs_left = cv2.calibrateCamera(<br>    objpoints, imgpoints_left, gray_left.shape[::-1], None, None)<br>ret_right, mtx_right, dist_right, rvecs_right, tvecs_right = cv2.calibrateCamera(<br>    objpoints, imgpoints_right, gray_right.shape[::-1], None, None)<br><br># Stereo calibration<br>flags = cv2.CALIB_FIX_INTRINSIC<br>criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-6)<br>ret, mtx_left, dist_left, mtx_right, dist_right, R, T, E, F = cv2.stereoCalibrate(<br>    objpoints, imgpoints_left, imgpoints_right,<br>    mtx_left, dist_left, mtx_right, dist_right,<br>    gray_left.shape[::-1], criteria=criteria, flags=flags)<br><br>image_size = gray_left.shape[::-1]<br><br>def compute_rectification(left_mtx, left_dist, right_mtx, right_dist, image_size, R, T, rect_scale=0.0):<br>    &quot;&quot;&quot;<br>    Compute stereo rectification transforms<br>    &quot;&quot;&quot;<br>    R1, R2, P1, P2, Q, roi1, roi2 = cv2.stereoRectify(<br>        left_mtx, left_dist, right_mtx, right_dist, image_size, R, T,<br>        flags=cv2.CALIB_ZERO_DISPARITY, alpha=rect_scale)<br>    <br>    # Compute mapping for rectification<br>    left_map_x, left_map_y = cv2.initUndistortRectifyMap(<br>        left_mtx, left_dist, R1, P1, image_size, 5)<br>    right_map_x, right_map_y = cv2.initUndistortRectifyMap(<br>        right_mtx, right_dist, R2, P2, image_size, 5)<br>    <br>    left_rect_map = (left_map_x, left_map_y)<br>    right_rect_map = (right_map_x, right_map_y)<br>    <br>    return left_rect_map, right_rect_map, Q<br><br># Compute rectification transforms<br>rect_scale = 0.5  # Set to 0 for full resolution or adjust as needed<br>left_rect_map, right_rect_map, Q = compute_rectification(mtx_left, dist_left, <br>                                                           mtx_right, dist_right, <br>                                                           image_size, R, T, rect_scale)<br><br><br><br>print(&quot;Stereo Calibration RMS error:&quot;, ret)<br>print(&quot;Left Camera Matrix:\n&quot;, mtx_left)<br>print(&quot;Right Camera Matrix:\n&quot;, mtx_right)<br>print(&quot;Rotation Matrix:\n&quot;, R)<br>print(&quot;Translation Vector:\n&quot;, T)<br><br># Return calibration results<br>calibration_data = {<br>        &#39;left_camera_matrix&#39;: mtx_left,<br>        &#39;left_dist_coeffs&#39;: dist_left,<br>        &#39;right_camera_matrix&#39;: mtx_right,<br>        &#39;right_dist_coeffs&#39;: dist_right,<br>        &#39;rotation_matrix&#39;: R,<br>        &#39;translation_vector&#39;: T,<br>        &#39;essential_matrix&#39;: E,<br>        &#39;fundamental_matrix&#39;: F,<br>        &#39;left_rect_map&#39;: left_rect_map,<br>        &#39;right_rect_map&#39;: right_rect_map,<br>        &#39;disparity_to_depth_map&#39;: Q,<br>        &#39;image_size&#39;: image_size<br>    }<br><br># Save calibration results<br>np.savez(&#39;stereo_calibration_copilot.npz&#39;,**calibration_data)</pre><p>Figure 8: Code to calibrate the stereo camera module</p><p>Figure 9 shows a image on how the code can detect inner corners of the chessboard in the image. The code saves all the relevant calibrated parameters as .npz file, which is utilized during the removal of distortion in the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*CiWxHeriM6Uqvc1sn1oiSw.png" /></figure><p>Figure 9: Detection of corners in chessboard pattern, during camera calibration</p><p>Once, we remove distortion from the images, the images are fed to object detection model, discussed before, and bounding boxe for each detected object is obtained. The coordinates of each bounding box are used to find the position of the center of the object in the image. These center positions are used to determine the distance of the object from camera.</p><p>Now, let’s discuss how can we determine distance from stereo camera images. This <a href="https://medium.com/analytics-vidhya/distance-estimation-cf2f2fd709d8">blog</a> discuss good details on that. The first step is to find the disparity between the same object between the two images. To understand, disparity, we need to understand that images taken from these two cameras have a slightly different view of world, hence different location of the same object in left and right camera image. This difference, also called <a href="https://en.wikipedia.org/wiki/Binocular_disparity#:~:text=The%20disparity%20of%20features%20between,comparing%20their%20corresponding%20image%20patches.">binocular disparity</a>, is what gives sense of depth to our brain, as view from each eye is slightly different. Figure 10, shows how correspondence between a certain point in left image (x_left) is matched in right image (x_right) along a epipolar line, and finding the difference between the those two positions, a.k.a disparity. A detailed discussion on epipolar line can be found <a href="https://en.wikipedia.org/wiki/Epipolar_geometry#:~:text=The%20epipolar%20geometry%20is%20simplified,having%20a%20common%20image%20plane.">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*LxpxOSP6FbGKxKgcoyfkUQ.png" /></figure><p>Figure 10: Schematic showing how to calculate depth from stereo images</p><p>Typically, it is not easy to match a single point present on left side image to right side image, hence we use surrounding area of the point/pixel in consideration. In our case, we detect same object in both images, using ResNet-101 model, and corresponding bounding box, and subsequently central position of that bounding box. Let’s say central coordinate of an object on left image is (center_x_l, center_y_l) and for right side image is (center_x_r, center_y_r). The disparity will be the following:</p><p>disparity_object (d) = |center_x_l — center_y_r|</p><p>Baseline — distance between the two cameras — is given by the manufacturer, and in our case in 60 mm. The horizontal angle of view is 73 degree in our case. Now we have to convert focal length of the camera from mm to pixel. For this we need, width of the image in pixel, and then we use the following formula to get focal length in pixel. The need for focal length in pixel is that the disparity is calculated in pixel, from the two images.</p><p>focal_length_pixel = (image_width x 0.5)/tan(horizontal_angle_of_view x 0.5 x pi/180)</p><p>There is another way to calculate focal_length_pixel, using the following formula</p><p>focal_length_pixel = (focal_length_mm/sensor_width) x image_width</p><p>Once we have all three required values, we can calculate depth/distance using the following equation</p><p>distance = (baseline x focal_length_pixel)/disparity_object</p><p>Figure 11 shows the code used to detect the objects, in undistorted images, followed by calculating disparity and corresponding distance. The object name and distance is written on the image itself and modified image is saved, so it can be displayed in UI. It is highly likely that two different objects, with same description, can be detected in the same image, for example, books or persons. In this case, we need to make sure we are matching correct object in both images. This was taken care by first matching the object name followed by closest matching “x” coordinate of the center of the bounding box.</p><pre>from transformers import DetrImageProcessor, DetrForObjectDetection<br>import torch<br>from PIL import Image<br>import requests<br>import pathlib <br>import time<br>import cv2<br>import json<br>from concurrent.futures import ProcessPoolExecutor<br>import torch.multiprocessing as mp<br>import pandas as pd<br>import numpy as np<br><br><br>image_path = f&quot;Documents/AI/RosRobot/RosRobotUI/images/color_image.png&quot;<br>image_path_object_L = f&quot;Documents/AI/RosRobot/RosRobotUI/images/image_object_L.png&quot;<br>image_path_object_R = f&quot;Documents/AI/RosRobot/RosRobotUI/images/image_object_R.png&quot;<br>image_path_json = f&quot;Documents/AI/RosRobot/RosRobotUI/images/object_data.json&quot;<br>image_path_left = f&quot;Documents/AI/RosRobot/RosRobotUI/images/stereoL.png&quot;<br>image_path_right = f&quot;Documents/AI/RosRobot/RosRobotUI/images/stereoR.png&quot;<br>image_path_left_u = f&quot;Documents/AI/RosRobot/RosRobotUI/images/stereoL_u.png&quot;<br>image_path_right_u = f&quot;Documents/AI/RosRobot/RosRobotUI/images/stereoR_u.png&quot;<br>calib_file = f&quot;stereo_calibration_copilot.npz&quot;<br><br>#camera parameters<br>baseline = 6.0  # Baseline in cm<br>focal_length = 0.26  # Focal length in cm<br>angle_of_view_horizontal = 73  # Angle of view in degrees<br>sensor_width = 0.276  # Sensor width not available, using 1 cm as a placeholder<br><br>device = &quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br><br># Load object detection model<br>processor = DetrImageProcessor.from_pretrained(&quot;facebook/detr-resnet-101&quot;, revision=&quot;no_timm&quot;)<br>model = DetrForObjectDetection.from_pretrained(&quot;facebook/detr-resnet-101&quot;, revision=&quot;no_timm&quot;).to(device)<br><br># Read calibration file to undistort stereo images<br><br>def read_calibration_file(calib_file):<br>    data = np.load(calib_file)<br> <br>    left_camera_matrix = data[&quot;left_camera_matrix&quot;]<br>    print(left_camera_matrix)<br>    left_dist_coeffs = data[&quot;left_dist_coeffs&quot;]<br>    print(left_dist_coeffs)<br><br>    right_camera_matrix = data[&quot;right_camera_matrix&quot;]<br>    print(right_camera_matrix)<br>    right_dist_coeffs = data[&quot;right_dist_coeffs&quot;]<br>    print(right_dist_coeffs)<br>    left_map_x = np.array(data[&#39;left_rect_map&#39;][0])<br>    left_map_y = np.array(data[&#39;left_rect_map&#39;][1])<br>    print(left_map_x)<br>    right_map_x, right_map_y = data[&#39;right_rect_map&#39;]<br><br>    return left_camera_matrix, left_dist_coeffs, right_camera_matrix, right_dist_coeffs, left_map_x, left_map_y, right_map_x, right_map_y<br><br>#Undistorst stereo images for depth estimation<br><br>def undistort_stereo_images(left_img_path, right_img_path, <br>                            left_camera_matrix, left_dist_coeffs, <br>                            right_camera_matrix, right_dist_coeffs):<br>    left_img = cv2.imread(left_img_path)<br>    right_img = cv2.imread(right_img_path)<br>    left_undistorted = cv2.undistort(left_img, left_camera_matrix, left_dist_coeffs)<br>    right_undistorted = cv2.undistort(right_img, right_camera_matrix, right_dist_coeffs)<br>    return left_undistorted, right_undistorted<br><br><br>def detect_objects_frame(image_path):<br>    img_frame = Image.open(pathlib.Path(image_path))<br>    inputs = processor(images=img_frame, return_tensors=&quot;pt&quot;).to(device)<br>    outputs = model(**inputs)<br>    target_sizes = torch.tensor([img_frame.size[::-1]])<br>    results = processor.post_process_object_detection(outputs, target_sizes=target_sizes, threshold=0.95)[0]<br>    return results<br><br>def object_coordinates(results, frame):<br>    min_score = 0.90<br>    object_index = 0<br>    object_info = []<br>    <br>    for score, label, box in zip(results[&quot;scores&quot;], results[&quot;labels&quot;], results[&quot;boxes&quot;]):<br>        box = [round(i, 2) for i in box.tolist()]<br>        if score &gt; min_score:<br>            object_index += 1<br><br>            object_info.append({<br>                &quot;object&quot;: model.config.id2label[label.item()],<br>                &quot;score&quot;: round(score.item(), 3),<br>                &quot;x1&quot;: int(box[0]),<br>                &quot;y1&quot;: int(box[1]),<br>                &quot;x2&quot;: int(box[2]),<br>                &quot;y2&quot;: int(box[3]),<br>                &quot;cntr_x&quot;: int((box[0] + box[2]) / 2),<br>                &quot;cntr_y&quot;: int((box[1] + box[3]) / 2),<br>                &quot;object_index&quot;: object_index,<br>                &quot;frame&quot;: frame<br>            })<br><br>    return object_info<br><br>def find_depth(right_x_point, left_x_point, img_left, baseline,f, sensor_width, alpha_horizontal):<br><br>    # Convert focal length from mm to pixels using sensor width and image width<br>    # f: focal length in mm<br>    # alpha: sensor width in mm<br>    # img_left: image (to get width in pixels)<br>    height, width, depth = img_left.shape<br>    <br>    f_pixel_1 = (f / sensor_width) * width # if sensor width available<br><br>    f_pixel_2 = (width * 0.5) / np.tan(alpha_horizontal * 0.5 * np.pi/180) # if camera alpha available<br><br>    # CALCULATE THE DISPARITY:<br>    disparity = abs(left_x_point - right_x_point)      #Displacement between left and right frames [pixels]<br><br>    # CALCULATE DEPTH z:<br>    if disparity &gt; 0:<br>        zDepth = (baseline*f_pixel_2)/disparity             #Depth in [cm]<br>    else:<br>        zDepth = None<br>        print(&quot;Disparity is zero or negative, cannot calculate depth.&quot;)<br><br>    return zDepth<br><br><br><br>if __name__ == &quot;__main__&quot;:<br>   <br>    left_camera_matrix, left_dist_coeffs, right_camera_matrix, right_dist_coeffs, left_map_x, left_map_y, right_map_x, right_map_y  = read_calibration_file(calib_file)<br><br>    while True:<br>        left_img_path = cv2.imread(image_path_left)<br>        right_img_path = cv2.imread(image_path_right)<br>        left_undistorted, right_undistorted = undistort_stereo_images(image_path_left, image_path_right,<br>                                left_camera_matrix, left_dist_coeffs, <br>                                right_camera_matrix, right_dist_coeffs)<br>        cv2.imwrite(image_path_left_u, left_undistorted)<br>        cv2.imwrite(image_path_right_u, right_undistorted)<br> <br>        img_L_u = cv2.imread(image_path_left_u)<br>        img_R_u = cv2.imread(image_path_right_u)<br><br>        results_L = detect_objects_frame(image_path_left_u)<br>        results_R = detect_objects_frame(image_path_right_u)<br>        object_coordinates_L = object_coordinates(results_L, &quot;left&quot;)<br>        object_coordinates_R = object_coordinates(results_R, &quot;right&quot;)<br>        all_object_coordinates = object_coordinates_L + object_coordinates_R<br><br>        json_object = json.dumps(all_object_coordinates, indent=4)<br><br>        # Find the matched objects in two images for depth calculation<br>        object_df = pd.DataFrame(all_object_coordinates)<br>        object_df.to_csv(&quot;Documents/AI/RosRobot/RosRobotUI/images/object_data.csv&quot;, index=False)<br>        print(&quot;Object Data:&quot;)<br>        print(object_df)<br>        # Group by &#39;frame&#39; and match objects first by &#39;object&#39; label, then by closest &#39;cntr_x&#39;<br>        left_objects = object_df[object_df[&#39;frame&#39;] == &#39;left&#39;]<br>        right_objects = object_df[object_df[&#39;frame&#39;] == &#39;right&#39;]<br><br>        matches = []<br>        for _, left_row in left_objects.iterrows():<br>            # Filter right objects with the same label<br>            right_candidates = right_objects[right_objects[&#39;object&#39;] == left_row[&#39;object&#39;]]<br>            if not right_candidates.empty:<br>                # Find the right object with closest cntr_x<br>                right_row = right_candidates.iloc[(right_candidates[&#39;cntr_x&#39;] - left_row[&#39;cntr_x&#39;]).abs().argsort()[:1]]<br>                if not right_row.empty:<br>                    match = {<br>                        &#39;left_object_index&#39;: left_row[&#39;object_index&#39;],<br>                        &#39;right_object_index&#39;: right_row.iloc[0][&#39;object_index&#39;],<br>                        &#39;left_cntr_x&#39;: left_row[&#39;cntr_x&#39;],<br>                        &#39;right_cntr_x&#39;: right_row.iloc[0][&#39;cntr_x&#39;],<br>                        &#39;object&#39;: left_row[&#39;object&#39;],<br>                        &#39;x1_left&#39;: left_row[&#39;x1&#39;],<br>                        &#39;y1_left&#39;: left_row[&#39;y1&#39;],<br>                        &#39;x2_left&#39;: left_row[&#39;x2&#39;],<br>                        &#39;y2_left&#39;: left_row[&#39;y2&#39;],<br>                        &#39;x1_right&#39;: right_row.iloc[0][&#39;x1&#39;],<br>                        &#39;y1_right&#39;: right_row.iloc[0][&#39;y1&#39;],<br>                        &#39;x2_right&#39;: right_row.iloc[0][&#39;x2&#39;],<br>                        &#39;y2_right&#39;: right_row.iloc[0][&#39;y2&#39;],<br>                        &#39;score_left&#39;: left_row[&#39;score&#39;],<br>                        &#39;score_right&#39;: right_row.iloc[0][&#39;score&#39;]<br>                    }<br>                    matches.append(match)<br><br>        matches_df = pd.DataFrame(matches)<br>        print(&quot;Matched objects based on cntr_x:&quot;)<br>        print(matches_df)<br>        matches_df.to_csv(&quot;Documents/AI/RosRobot/RosRobotUI/images/matched_objects.csv&quot;, index=False)<br><br>        # Draw matched objects on the left image<br>        img_matched = img_L_u.copy()<br>        for match in matches:<br>            x1, y1, x2, y2 = int(match[&#39;x1_left&#39;]), int(match[&#39;y1_left&#39;]), int(match[&#39;x2_left&#39;]), int(match[&#39;y2_left&#39;])<br>            label = match[&#39;object&#39;] + f&quot; {match[&#39;score_left&#39;]:.2f}&quot;<br>            cv2.rectangle(img_matched, (x1, y1), (x2, y2), (0, 0, 255), 2)<br>            cv2.putText(img_matched, label, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)<br>            distance = find_depth(match[&#39;right_cntr_x&#39;], match[&#39;left_cntr_x&#39;], img_matched, baseline, focal_length, sensor_width, angle_of_view_horizontal)<br>            if distance is not None and not np.isnan(distance) and not np.isinf(distance) and distance &gt; 0 and distance &lt; 50:<br>            # Draw the distance on the image<br>                cv2.putText(img_matched, f&quot;Distance: {distance:.1f} cm&quot;, (x1, y1 + 15), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)<br>            <br>        cv2.imwrite(&quot;Documents/AI/RosRobot/RosRobotUI/images/image_object_L_matched.png&quot;, img_matched)<br><br>        with open(image_path_json, &quot;w&quot;) as outfile:<br>            outfile.write(json_object)<br><br>        time.sleep(1.0)</pre><p>Figure 11: Code for object detection and depth/distance measurement</p><p>Figure 12, shows how distances of multiple objects are detected in the same frame, by the robot, using the above code. In this case apple and orange, with image on left one is in front of other and in image of right one is on the side of other. This gives the robot capability of understanding its surrounding and putting the objects around it in spatial perspective. This will be helpful when AI agents with reasoning capability will be deployed to this robot. I have not shown how it is integrated with UI, as it is not the focus of the blog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mAhBqssZWQN_TEWUxLUy0w.png" /></figure><p>Figure 12: Robot identifying objects as well as their respective spatial position</p><p>Figure 13, shows images taken of an object (apple or orange) at various distances and corresponding actual and measured values. Since disparity is inversely proportional to distance, the accuracy to measure distance decreases as distance increases. This makes it difficult to accurately measure disparity for far away objects, with limited hardware. In the code, we don’t measure distance for objects, which are more than 50 cm away, as error might make information impractical.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*IKSdC7-HLAwCx2U13iZsfQ.png" /></figure><p>Figure 13: Distance measurement at different settings. The actual distance is measured between the center point of the object and the camera, as bounding box is close to the center point of the object since it is the maximum width of the object. The number next to the object name is probability of identifying the object.</p><p>Finally, Figure 14 shows modified ROS topic/node graphs after adding camera module. Compared to Part 3 of the blog, this one also has nodes for image transmission and processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hc00w4ZkzDXq3gRgrIXkLQ.png" /></figure><p>Figure 14: ROS Topic/Node graph showing the flow of information</p><p>This is the end of Part 4 of the series. Some tips, which I learned:</p><p>1. Always make sure to register your camera in config.txt file, in case of Ubuntu OS, otherwise camera will not be detected</p><p>2. It will need some effort to install rpicam app in Ubuntu OS for Raspberry Pi, and link shared above is a good resource.</p><p>3. You need to take several good quality images, for camera calibration. Also use flat surface to display chessboard pattern. Typically tablets such as iPad.</p><p>4. Distance measurement accuracy from the robot decreases with distance, and it is better to have a distance threshold for measurement</p><p>In the next blog we will discuss how to utilize deep learning architecture for disparity estimation, as well as give robot a voice, i.e. installing speaker and mic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0418afedeb1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building An AI Enabled Robot — Part 3]]></title>
            <link>https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-3-68a71e44c140?source=rss-52b350dff91d------2</link>
            <guid isPermaLink="false">https://medium.com/p/68a71e44c140</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[robot-operating-system]]></category>
            <dc:creator><![CDATA[Mohit Jain]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 00:18:20 GMT</pubDate>
            <atom:updated>2025-04-07T00:18:20.045Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building An AI Enabled Robot — Part 3</strong></h3><p>Special thanks to Hoa Mattaliano for her kind support.</p><p>Building upon the work, we discussed in <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-1-fecc688e5798">Part 1</a> and <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-2-3e6a86747c66">Part 2</a> to assemble an AI enabled Robot, in this blog we will discuss the following tasks:</p><p>1. Assembling and connecting various components on top of the robot chassis</p><p>2. Adding GPS module</p><p>3. Adding LIDAR module</p><p>4. Installing and controlling servos to control stereo camera angle</p><p>5. Building a simple user interface (UI) to access all the information supplied by the sensors and control the servos to set camera angle</p><p>Figure 1 shows the picture of the assembled robot, with components in various layers. Layer 0 is the robot chassis (discussed on <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-2-3e6a86747c66">Part 2</a>), while Layer 1 contains the power supply for Raspberry Pi 5. It contains three 3.7 V Li-ion batteries, and the output is 5 V, which is compatible with Raspberry Pi. Layer 2 is the main layer and has Raspberry Pi, PCA9685 — a 16 channel 12 bit PWM/Servo driver — I2C interface, which will be used to control the angle of stereo camera mounted on a Pan/Tilt mount. Other components in the layer are — GT-U7 GPS module for location tracking, BME280 for measuring atmospheric temperature, pressure and relative humidity, a I2C multiplexer (TCA9548A), for future proofing in case two I2C modules have same address, which can create conflict and I2C based IO Expansion Board (PCF8574) to increase the number of GPIO pins, in case all GPIO pins on Raspberry PI gets occupied. It also contains two home assembled hubs to distribute power (5 V) and to connect various I2C devices to Raspberry Pi. Layer 3 has a a Light Detection and Ranging (LIDAR) — WayPonDEV LD14P 2D 360 Degree LIDAR — mounted on it, for obstacle detection and mapping the surrounding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*spPQx9qnDJ6zLi3j7vIKzg.png" /><figcaption><strong>Figure 1:</strong> Picture of the assembled robot, as of now</figcaption></figure><p>Figure 2 is the top view of Layer 2, showing how all the main components are assembled on it. The components are assembled in away to make sure we will have easy access to them, once assembled, as this whole process of building the robot is iterative and it will be assembled and reassembled several times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DLJTiJ_YReIm1-zPDqQpNQ.png" /><figcaption><strong>Figure 2:</strong> Components on Layer 2</figcaption></figure><p>Now let’s discuss various functionality added to the robot in detail, starting with GPS module, followed by LIDAR and the servos for pan/tilt of camera and utilizing ROS2 to bring them all together. Addition of BME280 chip, and communicating with sensors on robot chassis was already discussed in <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-2-3e6a86747c66">Part 2</a>.</p><p><strong>Using GPS module in the robot</strong></p><p>I am using MakerFocus <a href="https://www.amazon.com/dp/B07P8YMVNT">GT-U7 GPS </a>module with NEO-6M. The module comes with 5 pins connector, which needs to soldered, and an antenna. The module provide information using <a href="https://en.wikipedia.org/wiki/NMEA_0183">NMEA 1083</a> specifications, and these specification are controlled by National Marine Electronics Association. The module was connected to Raspberry Pi using one of the UART port, discussed in <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-1-fecc688e5798">Part 1</a> of the blog. There is a lot of data that is sent by the GPS module in NMEA format, and can be parsed by python pynmea2 library, namely — longitude, latitude, altitude (not very reliable), number of satellites it is getting information from, timestamp in UTC (very accurate) , and speed (might not be useful in this case, as robot will move very slow). Figure 3 shows the sample raw data output from GPS module, and Figure 4 shows it after parsing using pynmea2 library. Please note currently actual ground speed of the robot is zero and speed data is just noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*goEh5oHpVdLjKN_s8Ffchg.png" /><figcaption><strong>Figure 3:</strong> Raw data from the GPS module</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rn37qizWJRaQebB2-yPlbQ.png" /><figcaption><strong>Figure 4:</strong> Output from GPS module, after parsing data with pynmea2 library</figcaption></figure><p>Since, I will use the information from this module, using <a href="https://docs.ros.org/en/jazzy/index.html">ROS2</a>, Figure 5 shows ROS2 publisher code from robot side, and Figure 6 shows ROS2 subscriber code from Linux Desktop side. Figure 6 also shows code for GPS data publisher, which will be consumed by UI — discussed later.</p><pre>import rclpy<br>from rclpy.node import Node<br>from std_msgs.msg import String <br><br># serial connection<br>import serial<br>import time<br>import math<br>import numpy as np<br><br>class RosRobotGPSNode(Node):<br><br>    def __init__(self):<br>        super().__init__(&quot;rosrobot_gps_info&quot;)<br>       <br>        self.ser = serial.Serial(port=&#39;/dev/ttyAMA3&#39;, baudrate=9600) #UART Connection<br><br>        self.publisher_ = self.create_publisher(String, &quot;rosrobot_gps_sensor&quot;, 10)<br>        timer_period = 0.01 #every 10 miliiseconds<br>        <br>        self.timer_ = self.create_timer(timer_period, self.publish_gps_info)<br><br>        self.get_logger().info(&quot;GPS Broadcast Started...&quot;)<br><br>    <br>    def publish_gps_info(self):<br>       <br>        data = self.ser.readline().decode(&#39;utf-8&#39;).rstrip()<br>      <br>        msg = String()<br>        msg.data = data<br>        self.publisher_.publish(msg)<br><br><br>def main(args=None):<br>    rclpy.init(args=args)<br>    node = RosRobotGPSNode()<br>    rclpy.spin(node=node)<br>    rclpy.shutdown()<br><br>if __name__==&quot;__main__&quot;:<br>    main()</pre><p><strong>Figure 5:</strong> ROS2 publisher, on Raspberry Pi, to transmit data from the GPS module</p><pre>import rclpy<br>from rclpy.node import Node<br>from std_msgs.msg import String<br>import json<br>import pynmea2<br>import pytz<br>import datetime<br><br>class RosRobotGPSNode(Node):<br><br>    def __init__(self):<br>        super().__init__(&quot;rosrobot_gps_get&quot;)<br>        self.subscriber_env = self.create_subscription(<br>             String, &quot;rosrobot_gps_sensor&quot;, self.callback_rosrobot_gps, 10<br>        )<br><br>        self.publish_gps_status = self.create_publisher(String, &#39;sensors/gps&#39;, 10)<br>        self.publish_gps_timer = self.create_timer(0.5, self.callback_gps_pub)<br><br>        self.gps_data = &quot;&quot;<br><br>        self.timezone = pytz.timezone(&#39;America/New_York&#39;)<br>        self.dummy_date = datetime.datetime(2024, 1, 1)<br><br><br>        self.get_logger().info(&quot;GPS Sensor Broadcast Started...&quot;)<br><br>    <br>    <br>    def decimal_to_dms(self, decimal_degrees, is_longitude=False):<br>        &quot;&quot;&quot;<br>        Converts decimal degrees to degrees, minutes, and seconds (DMS).<br><br>        Args:<br>            decimal_degrees: The decimal degree value to convert.<br>            is_longitude: Boolean indicating if the value is longitude.<br><br>        Returns:<br>            A string representing the DMS value.<br>        &quot;&quot;&quot;<br>        degrees = int(decimal_degrees)<br>        minutes = int((decimal_degrees - degrees) * 60)<br>        seconds = (decimal_degrees - degrees - minutes/60) * 3600<br>        <br>        direction = &#39;&#39;<br>        if is_longitude:<br>            direction = &#39;E&#39; if degrees &gt;= 0 else &#39;W&#39;<br>        else:<br>            direction = &#39;N&#39; if degrees &gt;= 0 else &#39;S&#39;<br><br>        if degrees &lt; 0:<br>            degrees = (-1)*degrees<br>            minutes = (-1)*minutes<br>            seconds = (-1)*seconds<br><br>        return f&quot;{degrees}° {minutes}&#39; {seconds:.2f}\&quot; {direction}&quot;<br>    <br>    def callback_rosrobot_gps(self, msg:String):<br>        data = msg.data<br>        if data.startswith(&quot;$GPGGA&quot;):<br>            msg = pynmea2.parse(data)<br>            num_sats = msg.num_sats<br>            altitude = round((msg.altitude)*3.28084, 0) #convert to feet<br>            gps_quality = msg.gps_qual<br>            time_stamp = msg.timestamp<br><br>            # localized_time = self.timezone.localize(datetime.datetime.combine(self.dummy_date, time_stamp))<br>            # localized_time = localized_time.strftime(&#39;%H:%M:%S %Z%z&#39;)<br>            latitude = msg.latitude<br>            latitude_dms = self.decimal_to_dms(latitude)<br>            longitude = msg.longitude<br>            longitude_dms = self.decimal_to_dms(longitude, is_longitude=True)<br>            self.gps_data = json.dumps({&#39;time_stamp&#39;: str(time_stamp), &#39;num_sats&#39;: num_sats, &#39;longitude&#39;: longitude_dms, &#39;latitude&#39;: latitude_dms, &#39;altitude&#39;: altitude, &#39;gps_quality&#39;: gps_quality})<br>            self.get_logger().info(self.gps_data)<br>        elif data.startswith(&quot;$GPRMC&quot;):<br>            msg = pynmea2.parse(data)<br>            time_stamp = msg.timestamp<br>            latitude = msg.latitude<br>            longitude = msg.longitude<br>            speed = msg.spd_over_grnd<br>            data_json = json.dumps({&#39;time_stamp&#39;: str(time_stamp), &#39;longitude&#39;: longitude, &#39;latitude&#39;: latitude, &#39;speed&#39;: speed})<br><br>    def callback_gps_pub(self):<br>        data = self.gps_data<br>        self.get_logger().info(&quot;Publishing GPS Info&quot;)<br>        self.get_logger().info(data)<br>        msg = String()<br>        msg.data = data<br>        self.publish_gps_status.publish(msg)<br><br><br>def main(args=None):<br>    rclpy.init(args=args)<br>    node = RosRobotGPSNode()<br>    rclpy.spin(node=node)<br>    rclpy.shutdown()<br><br>if __name__==&quot;__main__&quot;:<br>    main()</pre><p><strong>Figure 6:</strong> ROS2 subscriber and publisher, on Linux Desktop, to receive data from robot and to transmit in a format suitable for UI to consume</p><p><strong>Using LIDAR for Obstacle Detection</strong></p><p>Since, obstacle detection is must for any mobile robot, I decided to use LIDAR for obstacle detection. Also I will use it for the mapping of surroundings. The LIDAR I am using is relatively inexpensive — <a href="https://www.amazon.com/dp/B0C1C4VW47?ref">WayPonDEV LD14P 2D 360 Degree LIDAR</a>. Figure 7 shows the picture of the LIDAR mounted on the robot. It is connected to the Raspberry Pi, using one of the UART port.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*reaaEQVCV2XDAbizJSa_Cw.jpeg" /><figcaption><strong>Figure 7:</strong> LIDAR mounted on top layer of the robot</figcaption></figure><p>Interestingly, the LIDAR manufacturer or one of its affiliates provided ROS2 driver for this model, that can be downloaded <a href="https://github.com/AlgoPathfinder/sdk_ldrobotsensorteam_stl/tree/main/ros2_app">here</a>. Hence, once we build the ROS2 package, the ROS2 publisher can easily be launched using the following command:</p><pre>ros2 launch ldlidar ld19.launch.py </pre><p>And information can be retrieved using <strong>/scan </strong>topic. However, now the question comes, how can the information provided in /scan topic can be used and shown in UI. There might be several ways to do that, but being a data scientist, I decided to just use Matplotlib library to create a polar plot, showing radial distance and angle, from robot, where the obstacle is located. This plot is then transmitted by ROS2 topic as compressed image to be consumed by UI or any other subscriber. Figure 8 shows the ROS2 publisher code and Figure 9 shows the polar plot. One important package I needed to use is <a href="https://wiki.ros.org/cv_bridge">CVBridge</a> that allows you to convert between ROS images and OpenCV images.</p><pre>import rclpy<br>from rclpy.node import Node<br>from sensor_msgs.msg import Image, CompressedImage<br>from sensor_msgs.msg import LaserScan<br>import cv2<br>from cv_bridge import CvBridge, CvBridgeError<br>import numpy as np<br>import json<br>from example_interfaces.msg import String<br>import numpy as np<br>import matplotlib.pyplot as plt<br><br>class LidarScanSubscriber(Node):<br>    def __init__(self):<br>        super().__init__(&#39;lidar_scan&#39;)<br><br>        self.br = CvBridge()<br><br>        self.lidar_image_url = &quot;~/RosRobot/RosRobotUI/images/lidar.jpeg&quot;<br><br>       <br>        self.subscriber_ = self.create_subscription(LaserScan, &quot;/scan&quot;, self.callback_scan_subscribe, 10)<br>        self.range_array = []<br>        self.intensity_array = []<br>        self.range_array_len = 0<br>        self.intensity_arry_len = 0<br>        self.min_angle = 0.0<br>        self.max_angle = 0.0<br>        self.angle_increment = 0.0<br>        <br>        self.publisher_lidar = self.create_publisher(CompressedImage, &#39;lidar/compressed&#39;, 10)<br>        self.publisher_lidar_timer = self.create_timer(1.0, self.callback_lidar)<br><br>        self.get_logger().info(&quot;LIDAR Scan Node Started&quot;)<br><br>    def callback_scan_subscribe(self, msg):<br><br>        self.range_array = msg.ranges<br>        self.intensity_array = msg.intensities<br>        self.range_array_len = len(msg.ranges)<br>        self.intensity_arry_len = len(msg.intensities)<br>        self.min_angle = msg.angle_min<br>        self.max_angle = msg.angle_max<br>        self.angle_increment = msg.angle_increment<br>        angle_array = np.arange(self.min_angle, self.max_angle, self.angle_increment)<br>        range_array_clean = (np.nan_to_num(self.range_array, copy=True, nan=0.0, posinf=8.0, neginf=8.0))*3.28<br>        intensity_array_clean = np.nan_to_num(self.intensity_array, copy=True, nan=0, posinf=0, neginf=0)<br><br>        min_length = np.min([len(range_array_clean), len(intensity_array_clean), len(angle_array)])<br><br>        fig = plt.figure(num=1,clear=True) #import to use num=1 and clear=True othewise memory keeps incleasing<br>        ax = fig.add_subplot(projection=&#39;polar&#39;)<br>        ax.set_theta_zero_location(&quot;S&quot;)<br>        c = ax.scatter(angle_array[0:min_length], range_array_clean[0:min_length], c=intensity_array_clean[0:min_length], s=0.1, cmap=&#39;hsv&#39;, )<br>        self.get_logger().info(&quot;Starting to save&quot;)<br>        plt.savefig(self.lidar_image_url)<br>        self.get_logger().info(&quot;Saved image&quot;)<br>        #fig.clear()<br>        #plt.close(fig=fig)<br>        <br>        <br>    def callback_lidar(self):<br>        compressed_image = cv2.imread(self.lidar_image_url, cv2.IMREAD_COLOR)<br>        self.publisher_lidar.publish(self.br.cv2_to_compressed_imgmsg(compressed_image, &#39;jpeg&#39;))<br>        self.get_logger().info(&#39;Publishing lidar image&#39;)<br><br>def main(args=None):<br>    rclpy.init(args=args)<br>    lidar_subscriber = LidarScanSubscriber()<br>    rclpy.spin(lidar_subscriber)<br>    lidar_subscriber.destroy_node()<br>    rclpy.shutdown()<br><br>if __name__==&#39;__main__&#39;:<br>    main()</pre><p><strong>Figure 8:</strong> ROS2 publisher code to transmit create and transmit LIDAR output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*4uCoppjsWQKl0GtVCObxpQ.jpeg" /><figcaption><strong>Figure 9: </strong>Polar plot to show distance and angle of obstacles from robot</figcaption></figure><p><strong>Installing Servos and Pan/Tilt Mount to Control Camera Angle</strong></p><p>The next enhancement is to add a stereo camera to create depth maps, which will be discussed in next part of the blog series. To achieve this, we need to mount the camera and its angle needs to be controlled. To accomplish that, I am using two MG996R <a href="https://www.amazon.com/dp/B07MFK266B">servos</a> and corresponding <a href="https://www.amazon.com/dp/B07PQ12TXS">mount</a>. Figure 10, shows the mounted servos and the stereo camera.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Wx0XYMQnpHboH8wFJYP-A.png" /><figcaption><strong>Figure 10:</strong> Stereo camera with servos and mount</figcaption></figure><p>Figure 11 shows the PCA9685 board used to control the servos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bl4JIq-JeCVHuB_dFSy9Qw.png" /><figcaption><strong>Figure 11: </strong>PCA9685 board to control the servos, which are used to set camera angle</figcaption></figure><p>The angles of the servos will be controlled from UI, using ROS2 publisher coded using javascript/roslibjs, which will be discussed later. On the other hand, the ROS2 subscriber, to control servos on Raspberry PI follows similar pattern as other ROS2 subscribers, and shown in Figure 12. One thing to pay attention here is use of <a href="https://docs.circuitpython.org/projects/servokit/en/latest/">Adafruit Servokit</a> library, which makes it easier to control servos.</p><pre>import rclpy<br>from rclpy.node import Node<br>from std_msgs.msg import String<br>import json<br>import time<br>from adafruit_servokit import ServoKit<br>import busio<br><br>class RosRobotCameraAngleNode(Node):<br><br>    def __init__(self):<br>        super().__init__(&quot;rosrobot_camera_angle_get&quot;)<br>        self.subscriber_env = self.create_subscription(<br>             String, &quot;camera_angle&quot;, self.callback_rosrobot_angle, 10)<br>        <br>        self.i2c_bus = busio.I2C(3, 2)<br>        self.kit = ServoKit(i2c = self.i2c_bus, channels=16)<br><br>        self.center_angle = 65<br>        self.horizontal_angle = 7 <br>        <br>        self.get_logger().info(&quot;Camera Angle Control Started...&quot;)<br><br>    def callback_rosrobot_angle(self, msg:String):<br>        data_camera_angle = msg.data<br>        data_list = data_camera_angle.split(&#39;,&#39;)<br>        tilt_angle = float(data_list[0])<br>        pan_angle = float(data_list[1])<br>        self.kit.servo[14].angle = self.center_angle + pan_angle #65 is center<br>        self.kit.servo[15].angle = self.horizontal_angle + tilt_angle #7 is horizontal<br>        <br>        self.get_logger().info(f&quot;Tilt: {tilt_angle}, Pan: {pan_angle}&quot;)<br><br><br>def main(args=None):<br>    rclpy.init(args=args)<br>    node = RosRobotCameraAngleNode()<br>    rclpy.spin(node=node)<br>    rclpy.shutdown()<br><br>if __name__==&quot;__main__&quot;:<br>    main()</pre><p><strong>Figure 12:</strong> ROS2 subscriber to control servos</p><p><strong>Need to use Roslibjs and ROSBridge</strong></p><p>When we use ROS, it preliminary uses TCP/UDP sockets for communications between its nodes, which are not directly accessible from web browsers. In order to circumvent this issue, I used <a href="https://wiki.ros.org/roslibjs#:~:text=roslibjs%20is%20the%20core%20JavaScript,the%20Robot%20Web%20Tools%20effort.">roslibjs</a>, which is a javascript library that facilitate communication with <a href="https://github.com/RobotWebTools/rosbridge_suite">ROSBridge,</a> allowing web applications to publish and subscribe ROS topics and services. ROSBridge itself acts as a bridge and translates ROS message into JSON format that can be sent over Websockets. More information can be found <a href="https://foxglove.dev/blog/using-rosbridge-with-ros1">here</a>.</p><p>Since, I will be building a web interface to control the robot, I decided to use these libraries. It is relatively easy to write javascript code to create topics, using roslibjs. Figure 13 shows the code snippet of various publisher and subscriber topics I created for this robot.</p><pre>//Script to subscribe and publish ROS2 topics<br><br>var url = &quot;ws://192.168.1.17:9090&quot;;<br>var ros = new ROSLIB.Ros({<br>  url: url,<br>});<br><br>function getRosServerConnectionStatus() {<br>  ros.on(&quot;connection&quot;, function () {<br>    document.getElementById(&quot;status&quot;).innerHTML = &quot;Connected to Server&quot;;<br>  });<br><br>  ros.on(&quot;error&quot;, function (error) {<br>    document.getElementById(&quot;status&quot;).innerHTML = &quot;Error&quot;;<br>  });<br><br>  ros.on(&quot;close&quot;, function () {<br>    document.getElementById(&quot;status&quot;).innerHTML = &quot;Closed&quot;;<br>  });<br>}<br><br>function getRobotOrientation() {<br>  var orientation_listener = new ROSLIB.Topic({<br>    ros: ros,<br>    name: &quot;/sensors/orientation&quot;,<br>    messageType: &quot;std_msgs/String&quot;,<br>  });<br>  orientation_listener.subscribe(function (m) {<br>    str_to_json = JSON.parse(m.data);<br>    document.getElementById(&quot;orientation_roll_msg&quot;).innerHTML =<br>      str_to_json.roll;<br>    document.getElementById(&quot;orientation_pitch_msg&quot;).innerHTML =<br>      str_to_json.pitch;<br>    document.getElementById(&quot;orientation_yaw_msg&quot;).innerHTML = str_to_json.yaw;<br>    console.log(str_to_json);<br>  });<br>}<br><br>function getChassisBatteryStatus() {<br>  var battery_listener = new ROSLIB.Topic({<br>    ros: ros,<br>    name: &quot;/sensors/battery&quot;,<br>    messageType: &quot;std_msgs/String&quot;,<br>  });<br><br>  battery_listener.subscribe(function (m) {<br>    str_to_json = JSON.parse(m.data);<br><br>    document.getElementById(&quot;battery_voltage_msg&quot;).innerHTML =<br>      str_to_json.batt_voltage;<br>    document.getElementById(&quot;battery_current_msg&quot;).innerHTML =<br>      str_to_json.load_curr;<br>    document.getElementById(&quot;battery_power_msg&quot;).innerHTML =<br>      str_to_json.load_power;<br><br>    //console.log(str_to_json);<br>  });<br>}<br><br>function getRobotCompassStatus() {<br>  var compass_listener = new ROSLIB.Topic({<br>    ros: ros,<br>    name: &quot;/sensors/compass&quot;,<br>    messageType: &quot;std_msgs/String&quot;,<br>  });<br><br>  compass_listener.subscribe(function (m) {<br>    str_to_json = JSON.parse(m.data);<br>    console.log(str_to_json.angle);<br>    document.getElementById(&quot;compass_msg&quot;).innerHTML = str_to_json.angle;<br><br>    //console.log(str_to_json);<br>  });<br>}<br><br>function getEnvironmentStatus() {<br>  var env_listener = new ROSLIB.Topic({<br>    ros: ros,<br>    name: &quot;/sensors/env&quot;,<br>    messageType: &quot;std_msgs/String&quot;,<br>  });<br><br>  env_listener.subscribe(function (m) {<br>    str_to_json = JSON.parse(m.data);<br>    document.getElementById(&quot;env_temp_msg&quot;).innerHTML =<br>      str_to_json.temperature_c;<br>    document.getElementById(&quot;env_pressure_msg&quot;).innerHTML =<br>      str_to_json.pressure_hpa;<br>    document.getElementById(&quot;env_humidity_msg&quot;).innerHTML =<br>      str_to_json.humidity_percent;<br><br>    console.log(str_to_json);<br>  });<br>}<br><br>function getLocationStatus() {<br>  var gps_listener = new ROSLIB.Topic({<br>    ros: ros,<br>    name: &quot;/sensors/gps&quot;,<br>    messageType: &quot;std_msgs/String&quot;,<br>  });<br><br>  gps_listener.subscribe(function (m) {<br>    str_to_json = JSON.parse(m.data);<br>    document.getElementById(&quot;gps_time_msg&quot;).innerHTML = str_to_json.time_stamp;<br>    document.getElementById(&quot;gps_longitude_msg&quot;).innerHTML =<br>      str_to_json.longitude;<br>    document.getElementById(&quot;gps_latitude_msg&quot;).innerHTML =<br>      str_to_json.latitude;<br>    document.getElementById(&quot;gps_altitude_msg&quot;).innerHTML =<br>      str_to_json.altitude;<br>    document.getElementById(&quot;gps_num_sat_msg&quot;).innerHTML = str_to_json.num_sats;<br>    document.getElementById(&quot;gps_quality_msg&quot;).innerHTML =<br>      str_to_json.gps_quality;<br><br>    console.log(str_to_json);<br>  });<br>}<br><br>function getLIDARData() {<br>  var image_listener = new ROSLIB.Topic({<br>    ros: ros,<br>    name: &quot;/lidar/compressed&quot;,<br>    messageType: &quot;sensor_msgs/CompressedImage&quot;,<br>  });<br><br>  image_listener.subscribe(function (message) {<br>    console.log(&quot;Got Lidar&quot;);<br>    document.getElementById(&quot;lidar_data&quot;).src =<br>      &quot;data:image/jpeg;base64,&quot; + message.data;<br><br>  });<br>}<br><br>function setCameraAngleCommand() {<br>  var camera_tilt_angle = Number(<br>    document.getElementById(&quot;cameraTiltAngle&quot;).value<br>  );<br>  var camera_pan_angle = Number(<br>    document.getElementById(&quot;cameraPanAngle&quot;).value<br>  );<br>  document.getElementById(&quot;display_tilt_angle&quot;).innerHTML = camera_tilt_angle;<br>  document.getElementById(&quot;display_pan_angle&quot;).innerHTML = camera_pan_angle;<br><br>  var camera_angle_message = `${camera_tilt_angle},${camera_pan_angle}`;<br>  console.log(&quot;Send Camera angle: &quot; + camera_angle_message);<br><br>  var camera_angle = new ROSLIB.Topic({<br>    ros: ros,<br>    name: &quot;/camera_angle&quot;,<br>    messageType: &quot;std_msgs/String&quot;,<br>  });<br><br>  var camera_angle_message_pub = new ROSLIB.Message({<br>    data: camera_angle_message,<br>  });<br>  // console.log(&#39;Servo Top Angle &#39; + top_servo_angle)<br>  // console.log(&#39;Servo Bottom Angle &#39; + bottom_servo_angle)<br>  camera_angle.publish(camera_angle_message_pub);<br>}</pre><p><strong>Figure 13:</strong> Javascript code to create ROS2 publisher and subscriber topics</p><p>To make the UI to communicate with ROS topics, we need to build <a href="https://github.com/RobotWebTools/rosbridge_suite">ROSBridge server package</a>, and start the server using the following command.</p><pre>ros2 launch rosbridge_server rosbridge_websocket_launch.xml</pre><p>One thing I observed that the server fails to starts if you are in Conda environment, and the environment needs to be deactivated.</p><p><strong>Building a simple UI to interact with the robot</strong></p><p>I build a simple UI, using <a href="https://getbootstrap.com/docs/5.0/getting-started/download/">Bootstrap</a> to interact with the robot. Figure 14 shows the screenshot of the UI, Figure 15, 16, and 17 shows information in different rows of the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*MewgtX_HOH2fdrC4IX-DOw.png" /><figcaption><strong>Figure 14:</strong> Screenshot of the full UI</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8bg42hqT7yh3BPoDGYIuLg.png" /><figcaption><strong>Figure 15:</strong> First row of UI showing power status (INA219 chip), robot overall orientation (accelerometer, gyroscope and digital compass) and direction (digital compass)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdUVNmI-HUc58oHP-O91fg.png" /><figcaption><strong>Figure 16:</strong> Second row of UI showing environment information (BME280 chip) , geographical location (GPS module) and controls to set camera angle (servos)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*26q5xpO1-L7aFvEPAqXq-Q.png" /><figcaption><strong>Figure 17: </strong>Third row showing LIDAR data for obstacle detection</figcaption></figure><p>I will not discuss how the UI was build as it can easily be created using several methods.</p><p>Finally 18 brings all things together showing the information flow using ROS2 topics. Basically the topics — /scan (LIDAR), /rosrobot_chassis_sensors (power, orientation and direction), /rosrobot_env_sensors (environment information), and /rosrobot_gps_sensor (for location) originates from the robot, and subscribed by the Linux Desktop and published, after data transformation, as /lidar/compressed, /sensors/orientation, /sensors/battery, /sensors/compass, /sensors/env, and /sensors/gps. Finally, the topics from Linux Desktop are subscribed by UI, using ROSBridge. The topic /camera_angle is published by UI, using roslibjs and ROSBridge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bniHtfPr_l0c_X8yGYnZ4g.png" /><figcaption><strong>Figure 18:</strong> ROS Topic/Node graph showing the flow of information</figcaption></figure><p>This is the end to Part 3 of the series. Some tips, which I learned along the way:</p><p>1. Make sure you have proper grounding and all components are connected to a common ground, otherwise you might run into issues when trying to acquires data form UART and I2C.</p><p>2. Sometime some unrecognized characters shows up in the serial port data stream, not sure why but maybe due to some signal noise. So to prevent your code from crashing due to this issue, maybe use “ignore” option if you are using pyserial to read data.</p><p>3. As the project grows it is difficult to run various ROS packages in different terminals. To circumvent this issues, use “launch” files. More information can be found <a href="https://docs.ros.org/en/jazzy/Tutorials/Intermediate/Launch/Creating-Launch-Files.html">here</a>.</p><p>4. As there will many commands to write, to get the whole system working, better to use a shell script.</p><p>As most of the robot assembly is done for now, the next step is to use AI to extract and utilize the information provided by the sensors. In the upcoming blog I will discuss how to generate depth maps using stereo cameras as well as depth maps created using monocular camera and Deep Learning vision models, such as open-source/weight Vision Transformer (ViT)-based depth-estimation models, which can be downloaded from <a href="https://huggingface.co/models?pipeline_tag=depth-estimation&amp;sort=trending">Hugging Face</a>.</p><p>Stay tuned for the next part of the series…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68a71e44c140" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building An AI Enabled Robot — Part 2]]></title>
            <link>https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-2-3e6a86747c66?source=rss-52b350dff91d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e6a86747c66</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[esp32-programming]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[arduino-projects]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Mohit Jain]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 16:30:47 GMT</pubDate>
            <atom:updated>2025-03-09T16:48:54.509Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building An AI Enabled Robot — Part 2</strong></h3><p>Special thanks to Hoa Mattaliano for her kind support.</p><p>In case you don’t have Medium membership, you can read it <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-2-3e6a86747c66?source=friends_link&amp;sk=f874966d3f2ce1121dd69f48e9a007f7">here</a>.</p><p>Building upon the work, we discussed in <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-1-fecc688e5798?source=friends_link&amp;sk=ead96491cddf506e1daa7e2dbb0e14c1">Part 1</a>, in this part, we will work on getting the information from 4 sensors in the robot chassis, I will be using, as well environment information from BME280 chip, discussed in <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-1-fecc688e5798?source=friends_link&amp;sk=ead96491cddf506e1daa7e2dbb0e14c1">Part 1</a>. To enable communication between the robot and the base computer, we will be creating Robotic Operating System (ROS) topics — publishers and subscribers, which will allow us to transmit and receive sensors information, remotely. Figure 1, is the schematic, describing the idea:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y4lhIpM_FCTuuFC9-Tfsrw.png" /><figcaption><strong>Figure 1:</strong> Schematic of various communications between the devices that will be discussed in this blog</figcaption></figure><p>The chassis I am using is <a href="https://www.amazon.com/dp/B0CF55LM6Q?ref=ppx_yo2ov_dt_b_fed_asin_title">Waveshare Wave Rover 4WD Mobile Robot Chassis</a>. A word of advice if you are planning to use this chassis — just be aware that, as of now, amount of documentation is minimal<strong>,</strong> so you need to figure out how to make it work for your needs. This is specifically true if you want to control it using a host computer, such as Raspberry Pi, instead of just using the software that comes with it. Having said that, the chassis is well built, and comes with lots of functionality, if configured correctly, and that is the reason I decided to use it.</p><p>Figure 2 shows the robot chassis as received, except I have removed the top cover to show the underlying circuit board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8RWk7CTqiScQEVA-Rolbg.png" /><figcaption><strong>Figure 2: </strong>Picture of the robot chassis, which will be used during this project</figcaption></figure><p>Figure 3 shows the dismantled chassis, showing 4 DC motors for wheels, power supply circuit board and batteries (you need to buy batteries separately, if you go with this chassis). Figure 4 shows another circuit board in the chassis, that has ESP32 micro-controller, and various sensor chips, as identified in the figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6lpV2iAsmVCfzKESkK8JA.png" /><figcaption>Figure 3: Dismantlement robot chassis, showing motors for the wheels and battery supply</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ogu2Xi2aTcy2OVePVBtMRQ.png" /><figcaption><strong>Figure 4:</strong> Circuit board showing position of various sensors chips, which will be discussed in this blog.</figcaption></figure><p>Now, let’s start with programming the ESP32 board in the chassis so we can get information from most of the sensors embedded on the board, namely — accelerometer, gyroscope, magnetometer, power supply information — battery voltage, load current, load voltage, load power and overflow voltages. The chips that are providing this information are the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nfH1dUwY02a_FJ-QnAFu3Q.png" /></figure><p>We can get the relevant libraries and some example codes to retrieve information from the sensors <a href="https://www.waveshare.com/wiki/WAVE_ROVER">here</a>.</p><p>To program the ESP32 board, I decided to use PlatformIO instead of Arduino IDE, as PlatformIO provides far greater flexibility and is more feature rich compared to Aruduino IDE, in case you are planning to write a fairly complex code in future. Some of the benefits can be seen <a href="https://docs.platformio.org/en/latest/faq/arduino-vs-platformio.html">here</a>. I am using Visual Studio Code, so I used PlatformIO extension, as it allows me to do all the development work using the same IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVGJsqsfVdN0OoyrlQ6kMA.png" /><figcaption><strong>Figure 5:</strong> Screenshot of PlatformIO extension in VS Code.</figcaption></figure><p>The code I uploaded to ESP32 board, is mostly inspired from the code provided in Waveshare <a href="https://www.waveshare.com/wiki/WAVE_ROVER">wiki</a> or generated using Gen-AI tools. Figure 6 shows the directory structure I used and Figure 7 shows the code that was uploaded. In the code, you might also notice reference to OLED Display. This is for small display that is on the chassis, that can be programmed using Adafruit SSD1306 library. I used it to provide information of the battery state (voltage, current, load).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*8nPIUF1_rUUysjpgf0rpsQ.png" /><figcaption><strong>Figure 6:</strong> Directory structure</figcaption></figure><pre><br>#include &lt;INA219_WE.h&gt;<br>#include &lt;Wire.h&gt;<br>#include&quot;IMU.h&quot;<br>#include &lt;Adafruit_SSD1306.h&gt;<br><br>#define S_SDA 32<br>#define S_SCL 33<br><br><br>#define INA219_ADDRESS 0x42<br>INA219_WE ina219 = INA219_WE(INA219_ADDRESS);<br><br>float shuntVoltage_mV = 0.0;<br>float loadVoltage_V = 0.0;<br>float busVoltage_V = 0.0;<br>float current_mA = 0.0;<br>float power_mW = 0.0; <br>bool ina219_overflow = false;<br><br>// SENSORS DATA RETRIVAL SETTING<br>EulerAngles stAngles;<br>IMU_ST_SENSOR_DATA_FLOAT stGyroRawData;<br>IMU_ST_SENSOR_DATA_FLOAT stAccelRawData;<br>IMU_ST_SENSOR_DATA stMagnRawData;<br>float temp;<br>float angle;<br>float angleDegree;<br>float correctedAngleDegree;<br><br>int com_x;<br>int com_y;<br>int com_z;<br>int acc_x;<br>int acc_y;<br>int acc_z;<br>int gyr_x;<br>int gyr_y;<br>int gyr_z;<br><br>float declination_location = -12; //For Central, NJ USA<br><br>unsigned long previousMillis = 0;<br>const long interval = 10; //in milliseconds<br><br>// default OLED Display<br>String screenLine_0;<br>String screenLine_1;<br>String screenLine_2;<br>String screenLine_3;<br><br>void InitINA219(){<br>  if(!ina219.init()){<br>    Serial.println(&quot;INA219 not connected!&quot;);<br>  }<br>  ina219.setADCMode(BIT_MODE_9);<br>  ina219.setPGain(PG_320);<br>  ina219.setBusRange(BRNG_16);<br>  ina219.setShuntSizeInOhms(0.01); // used in INA219.<br>}<br><br>void SensorDataUpdate(){<br><br>  // INA219<br>  shuntVoltage_mV = ina219.getShuntVoltage_mV();<br>  busVoltage_V = ina219.getBusVoltage_V();<br>  current_mA = ina219.getCurrent_mA();<br>  power_mW = ina219.getBusPower();<br>  loadVoltage_V  = busVoltage_V + (shuntVoltage_mV/1000);<br>  ina219_overflow = ina219.getOverflow();<br><br>  //IMU (AK09918 -&gt; Compass, QMI8658 -&gt; Accelometer and Gyroscope)<br>  imuDataGet( &amp;stAngles, &amp;stGyroRawData, &amp;stAccelRawData, &amp;stMagnRawData);<br>}<br><br>// OLED Display<br><br>#define SCREEN_WIDTH 128 // OLED display width, in pixels<br>#define SCREEN_HEIGHT 32 // OLED display height, in pixels<br>#define OLED_RESET     -1 // Reset pin # (or -1 if sharing Arduino reset pin)<br>#define SCREEN_ADDRESS 0x3C ///&lt; See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32<br><br>Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &amp;Wire, OLED_RESET);<br><br>void InitScreen(){<br>  if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {<br>    Serial.println(F(&quot;SSD1306 allocation failed&quot;));<br>  }<br>  display.clearDisplay();<br>  display.display();<br>}<br><br>void Screenupdate(){<br>  display.clearDisplay();<br>  display.setTextSize(1);<br>  display.setTextColor(SSD1306_WHITE);<br>  display.setCursor(0,0);<br>  screenLine_0 = &quot;B V: &quot;+String(busVoltage_V);<br>  display.println(screenLine_0);<br>  screenLine_1 = &quot;mA: &quot;+String(current_mA);<br>  display.println(screenLine_1);<br>  screenLine_2 = &quot;mW: &quot;+String(power_mW);<br>  display.println(screenLine_2);<br>  screenLine_3 = &quot;L V: &quot;+String(loadVoltage_V);<br>  display.println(screenLine_3);<br>  display.display();<br>}<br><br>void SerialSensorData(){<br><br>  //Power Bus Data (INA219)<br><br>  Serial.print(busVoltage_V);<br>  Serial.print(&quot;,&quot;);<br>  Serial.print(current_mA);<br>  Serial.print(&quot;,&quot;);<br>  Serial.print(power_mW);<br>  Serial.print(&quot;,&quot;);<br>  Serial.print(loadVoltage_V);<br>  Serial.print(&quot;,&quot;);<br>  Serial.print(ina219_overflow);<br>  Serial.print(&quot;,&quot;);<br>  <br>  //IMU Data<br>  <br>  com_x = stMagnRawData.s16X;<br>  Serial.print(com_x);<br>  Serial.print(&quot;,&quot;);<br>  com_y = stMagnRawData.s16Y;<br>  Serial.print(com_y);<br>  Serial.print(&quot;,&quot;);<br>  com_z = stMagnRawData.s16Z;<br>  Serial.print(com_z);<br>  Serial.print(&quot;,&quot;);<br><br>  acc_x = stAccelRawData.X;<br>  Serial.print(acc_x);<br>  Serial.print(&quot;,&quot;);<br>  acc_y = stAccelRawData.Y;<br>  Serial.print(acc_y);<br>  Serial.print(&quot;,&quot;);<br>  acc_z = stAccelRawData.Z;<br>  Serial.print(acc_z);<br>  Serial.print(&quot;,&quot;);<br><br>  gyr_x = stGyroRawData.X;<br>  Serial.print(gyr_x);<br>  Serial.print(&quot;,&quot;);<br>  gyr_y = stGyroRawData.Y;<br>  Serial.print(gyr_y);<br>  Serial.print(&quot;,&quot;);<br>  gyr_z = stGyroRawData.Z;<br>  Serial.print(gyr_z);<br>  Serial.println();<br><br>}<br><br>void setup() {<br>  // put your setup code here, to run once:<br>  Wire.begin(S_SDA,S_SCL);<br>  Serial.begin(115200);<br>  while(!Serial){}<br><br>  InitINA219();<br>   //Sensor initialization<br>  imuInit();<br>  //OLED Initialization<br>  InitScreen();<br>}<br><br>void loop() {<br><br>  unsigned long currentMillis = millis();<br><br>  if (currentMillis - previousMillis &gt;= interval){<br><br>    previousMillis = currentMillis;<br>    SensorDataUpdate();<br>    SerialSensorData();<br>    Screenupdate();<br><br>  }<br>}</pre><p><strong>Figure 7: </strong>Code in the main.cpp file, that can give you idea of the main functionality</p><p>Figure 8 shows the PlatformIO configuration file, for various settings and libraries that were imported.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*yuyvjyXoCBmPYPKLMP6r-A.png" /><figcaption><strong>Figure 8: </strong>PlatformIO configuration file</figcaption></figure><p>Discussed below are various sensors, and how we get live updates from these sensors.</p><p><strong>Sensor Information From ESP32 in Robot Chassis</strong></p><p><strong>Using Power Monitor Chip INA219 for Battery Status — </strong>The information about embedded chip — INA219 — can be found <a href="https://www.ti.com/product/INA219">here</a>. The chip communicates using I2C with ESP32, using wollewald/INA219_WE library. We are extracting the following information from the chip — Battery Bus Voltage (in V), Load Current (in mA), Power (in mW), and Load Voltage (in V). Figure 9 is the code snippet (taken from example code provided <a href="https://www.waveshare.com/wiki/Tutorial_VII:_INA219_Voltage_And_Current_Monitoring_Demo">here</a>), used to get this information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*c0c0CtkpAlx5svmNM71YUg.png" /><figcaption><strong>Figure 9: </strong>Code snippet to get information from INA219 — power monitor chip</figcaption></figure><p><strong>Using QMI8658 for Accelerometer and Gyroscope — </strong>Another embedded chip — QMI8658 is a 6-axis Inertial Measurement Unit (IMU) with a 3-axis gyroscope and a 3-axis accelerometer. Additional information about the chip can be found <a href="https://www.qstcorp.com/en_imu_prod/">here</a>. I used the example code provided <a href="https://www.waveshare.com/wiki/Tutorial_V:_IMU_Data_Reading_Demo">here</a>, for inspiration, to extract information from this sensor (Figure 10).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*fKTR6rziYO1ZKXHQKY3XGQ.png" /><figcaption><strong>Figure 10: </strong>Code snippet to get accelerometer and gyroscope data from QMI8658 chip</figcaption></figure><p><strong>Using AK09918 for Magnetic Field — </strong>AK009918 is a 3-axis electronic compass, and more information can be found <a href="https://www.akm.com/us/en/products/electronic-compass/lineup-electronic-compass/ak09918c/">here</a>. The chip uses I2C communication protocol. I used some of the example code information provided <a href="https://files.waveshare.com/upload/3/39/9DOF_Demo_v2.zip">here</a> — which will ask you to download zip file (so observe precaution) — to extract the information from the compass. The code snippet uploaded to the ESP32 is shown in Figure 11.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*1ZEK4BCiPgEUmf2bWVSzhA.png" /><figcaption><strong>Figure 11: </strong>Code snippet to get magnetic field data from AK09918 — magnetic compass</figcaption></figure><p><strong>Updating Small OLED Display Module for Battery Information — </strong>The robot chassis comes with a 0.91 inch OLED screen. I am using that screen for battery status information. The example code can be found <a href="https://www.waveshare.com/wiki/Tutorial_VIII:_OLED_Screen_Control_Demo">here</a> and shown in Figure 12. The code uses Adafruit’s SSD1306 library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*nE1eeRFwsvTNFIRbb648kA.png" /><figcaption><strong>Figure 12: </strong>Code snippet to display information on OLED on the robot chassis</figcaption></figure><p>Figure 13 shows the display in robot chassis, showing battery information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tIx1YdnEIerQS8aRn48wkA.png" /><figcaption>Figure 13: OLED display on robot chassis, showing power information</figcaption></figure><p>Figure 14 shows the output coming from ESP32 board, after the code was uploaded, through the serial bus, connected to the Raspberry Pi 5 using UART (see blog <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-1-fecc688e5798?source=friends_link&amp;sk=ead96491cddf506e1daa7e2dbb0e14c1">Part 1</a> for that discussion). As can be seen the output is a string, with various readings, which we will transmit, over the WiFi, using ROS topics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*jC7OhWF4VQ_bRs2vsx6rkw.png" /><figcaption>Figure 14: Raw data from ESP32 board, using UART connection</figcaption></figure><p><strong>Transmission of Sensor Data from Raspberry Pi to Base Computer</strong></p><p>I am planning to do majority of the data analysis on my desktop (Linux Ubuntu), which is significantly more capable in terms of compute, compared to Raspberry Pi. In order to transmit information from Raspberry Pi to the base computer, over WiFi, I decided to use ROS2 (<a href="https://docs.ros.org/en/jazzy/Releases/Release-Jazzy-Jalisco.html">Jazzy Jalisco</a>). Using ROS2 is slightly complicated, if you don’t have the basics clear about it. There is good course I came across on <a href="https://www.udemy.com/course/ros2-for-beginners/">Udemy</a> that can be used to learn the basics.</p><p>In Raspberry Pi, we created two publishers topics, which are used to broadcast information from the sensors on robot chassis connected using UART, and from the environment chip, BME280 connected using I2C, to Raspberry Pi.</p><p>Figure 15, shows the code snippet of publisher for broadcasting chassis sensors info. Figure 16, shows the data transmitted by this topic, and contains information from power monitor (INA219), IMU (QMI8658), and Compass (AK09918).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*3mt6gW6eLxKdJtvOTvT9jA.png" /><figcaption><strong>Figure 15: </strong>ROS publisher topic to broadcast robot chassis information</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qV0OPOR2Xd21Grmk6aoO0A.png" /><figcaption><strong>Figure 16:</strong> Data stream broadcast by the topic</figcaption></figure><p>Since, BME280 chip is connected using I2C interface, the topic for it uses SMBUS2 python library. Figure 17 shows the code snippet for the topic and Figure 18 shows transmitted data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*kRqAnySimgoGrwtEgVdjsg.png" /><figcaption><strong>Figure 17: </strong>Code snippet to publish environment information, using BME280 sensor</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nS95XT-Y0ZNPeVFyYyXRvw.png" /><figcaption><strong>Figure 18: </strong>Data stream showing environment information published by the topic</figcaption></figure><p><strong>Data Analysis of Sensor Data on Linux Desktop</strong></p><p>Now the sensor data is broadcast by the host computer (Raspberry Pi), we can retrieve this data by creating ROS subscriber topics on the base computer (Linux Desktop). Figure 19 shows the code snippet for subscriber topic for robot chassis sensors information published by Raspberry Pi. Figure 20 shows the output from the subscriber, where the raw Power Monitor, IMU and Compass data is transformed into useful information — roll, pitch, yaw and battery information (more discussion on this later in the blog).</p><pre><br>import rclpy<br>from rclpy.node import Node<br>from std_msgs.msg import String<br>import json<br>import math<br>import numpy as np<br>import sys<br>import imufusion<br>from datetime import datetime, timedelta<br><br>#sys.path.append(&#39;/home/mohit/anaconda3/envs/ros2_jazzy/lib/python3.12/site-packages&#39;)<br><br><br>dt = 0.01<br>sample_rate = 100<br><br>class RosRobotSensorsNode(Node):<br><br>    def __init__(self):<br>        super().__init__(&quot;rosrobot_sensors_get&quot;)<br>        self.subscriber_chassis = self.create_subscription(<br>            String, &quot;rosrobot_chassis_sensors&quot;, self.callback_rosrobot_sensors, 10<br>        )<br>        self.get_logger().info(&quot;Sensors Broadcast Started...&quot;)<br>        self.previousTime = datetime.now()<br>        self.currentTime = datetime.now()<br>        self.prev_yaw = 0<br><br><br>    def compass_calibration(self):<br>        y_cord = [22, 33, 36, 27, 13, 3, -5, 4]<br>        x_cord = [-11, -3, 15, 26, 30, 24, 6, -8]<br><br>        offset_x = (max(x_cord) + min(x_cord))/2<br>        offset_y = (max(y_cord) + min(y_cord))/2<br><br>        avg_delta_x = (max(x_cord) - min(x_cord))/2<br>        avg_delta_y = (max(y_cord) - min(y_cord))/2<br>        avg_delta = (avg_delta_x + avg_delta_y)/2<br><br>        scale_x = avg_delta/avg_delta_x<br>        scale_y = avg_delta/avg_delta_y<br><br>        location_declination = 0 # location specific<br><br>        return offset_x, offset_y, scale_x, scale_y, location_declination<br>    <br>    def calculate_pitch_roll_yaw_imufusion(self, acc_x, acc_y, acc_z, gyr_x, gyr_y, gyr_z, mag_x, mag_y, mag_z, delta_time):<br>        offset = imufusion.Offset(sample_rate)<br>        ahrs = imufusion.Ahrs()<br><br>        ahrs.settings = imufusion.Settings(<br>            imufusion.CONVENTION_NWU,  # convention<br>            0.5,  # gain<br>            2000,  # gyroscope range<br>            10,  # acceleration rejection<br>            10,  # magnetic rejection<br>            5 * sample_rate,  # recovery trigger period = 5 seconds<br>        )<br><br>        #Process sensor data<br><br>        # Calculate gravity vector from accelerometer data<br>        norm_accel = np.sqrt(acc_x**2 + acc_y**2 + acc_z**2)<br>        x_gravity = acc_x/norm_accel<br>        y_gravity = acc_y/norm_accel<br>        z_gravity = acc_z/norm_accel <br><br><br><br>        gyro_array = np.array([gyr_x, gyr_y, gyr_z])<br>        acc_array = np.array([x_gravity, y_gravity, z_gravity])<br>        mag_array = np.array([mag_x, mag_y, mag_z])<br><br>        gyro_array = offset.update(gyro_array)<br>        ahrs.update(gyro_array, acc_array, mag_array, delta_time)<br>        euler = np.array(ahrs.quaternion.to_euler())<br><br>    <br>    def calaculate_pitch_roll_yaw(self, acc_x, acc_y, acc_z, gyr_x, gyr_y, gyr_z, mag_x, mag_y, mag_z, prev_yaw, dt):<br>         <br>         # Calculate gravity vector from accelerometer data<br>         norm_accel = np.sqrt(acc_x**2 + acc_y**2 + acc_z**2)<br>         x_gravity = acc_x/norm_accel<br>         y_gravity = acc_y/norm_accel<br>         z_gravity = acc_z/norm_accel<br><br>         #Calculate roll and pitch using arctangent and convert to degrees<br>         roll = np.arctan2(y_gravity,  z_gravity)<br>         pitch = np.arctan2(-x_gravity, np.sqrt(y_gravity**2 + z_gravity**2))<br><br>         # Correct magnetometer readings from rool and pitch<br>         mag_x_corr = mag_x*math.cos(pitch) + mag_z*math.sin(pitch)<br>         mag_y_corr = mag_x*math.sin(roll)*math.sin(pitch) + mag_y*math.cos(roll) - mag_z*math.sin(roll)*math.cos(pitch)<br><br>         # Calculate yaw from magnetometer data<br>         mag_yaw = math.atan2(-mag_y_corr, mag_x_corr)<br><br>         # Calculate yaw from gyroscope data<br><br>         gyro_yaw  = prev_yaw + gyr_z*dt<br><br>         # Use complementry filter to fuse the data<br><br>         alpha = 0.98 # Adjust for amount of filtering<br>         roll = alpha*(roll + gyr_x*dt) + (1-alpha)*roll<br>         pitch = alpha*(pitch + gyr_y*dt) + (1-alpha)*pitch<br>         yaw = alpha*gyro_yaw + (1-alpha)*mag_yaw<br><br>         # Convert radians to degrees<br>         roll = round(np.rad2deg(roll), 2)<br>         pitch = round(np.rad2deg(pitch), 2)<br>         yaw = round(np.rad2deg(yaw), 2)<br><br>         return roll, pitch, yaw<br><br><br>    def callback_rosrobot_sensors(self, msg:String):<br>        offset_x, offset_y, scale_x, scale_y, location_declination = self.compass_calibration()<br>        data = msg.data<br>        data_list = data.split(&#39;,&#39;)<br>        curr_time = datetime.now()<br>        delta_time = curr_time - self.previousTime<br>        self.previousTime = curr_time<br><br>        delta_time_float = (delta_time/timedelta(milliseconds=1))/1000<br>        #print(delta_time_float)<br><br>        batt_voltage = float(data_list[0])<br>        load_current = float(data_list[1])<br>        load_power = float(data_list[2])<br>        load_voltage = float(data_list[3])<br>        overflow_voltage = float(data_list[4])<br><br><br>        mag_X = (float(data_list[5]) - offset_x)*scale_x<br>        mag_Y = (float(data_list[6]) - offset_y)*scale_y<br>        mag_Z = float(data_list[7])<br><br>        acc_X = float(data_list[8])<br>        acc_Y = float(data_list[9])<br>        acc_Z = float(data_list[10])<br><br>        gyr_X = float(data_list[11])<br>        gyr_Y = float(data_list[12])<br>        gyr_Z = float(data_list[13])<br><br>        angle = round((math.atan2(mag_Y, mag_X)*180/math.pi + location_declination), 0)<br>        if angle &lt;= 0:<br>                angle = 360 + angle<br><br>        <br>        #self.calculate_pitch_roll_yaw_imufusion(acc_X, acc_Y, acc_Z, gyr_X, gyr_Y, gyr_Z, mag_X, mag_Y, mag_Z, delta_time_float)<br>        roll, pitch, yaw = self.calaculate_pitch_roll_yaw(acc_x=acc_X, acc_y=acc_Y, acc_z=acc_Z, gyr_x=gyr_X, gyr_y=gyr_Y, gyr_z=gyr_Z, mag_x=mag_X, mag_y=mag_Y, mag_z=mag_Z, prev_yaw=self.prev_yaw, dt=delta_time_float)<br><br>        self.prev_yaw = np.deg2rad(yaw)<br><br>        data_json = json.dumps({&#39;batt_voltage&#39;: batt_voltage, &#39;load_curr&#39;: load_current, &#39;load_power&#39;: load_power, &#39;load_voltage&#39;: load_voltage, &#39;overflow_voltage&#39;: overflow_voltage,<br>                                 &#39;angle&#39;: angle,&#39;roll&#39;: roll, &#39;pitch&#39;: pitch, &#39;yaw&#39;: yaw})<br><br><br><br>        self.get_logger().info(data_json)<br><br><br>def main(args=None):<br>    rclpy.init(args=args)<br>    node = RosRobotSensorsNode()<br>    rclpy.spin(node=node)<br>    rclpy.shutdown()<br><br>if __name__==&quot;__main__&quot;:<br>    main()</pre><p><strong>Figure 19: </strong>Code to receive and transform information from the sensors on robot chassis</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpAuu8gQW3QJMLwbe8dBAQ.png" /><figcaption><strong>Figure 20: </strong>Output from the subscriber, using robot chassis sensors information</figcaption></figure><p>Figure 21 shows the code snippet for subscriber topic to receive information from publisher topic for BME280 chip, broadcast by Raspberry Pi. Figure 22 shows the output from this subscriber.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0iev3TJzYgsP_NK0PkotaQ.png" /><figcaption><strong>Figure 21:</strong> Code snippet showing subscriber topic for environment information</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXVZZi6bK-XVtntw56W3eg.png" /><figcaption><strong>Figure 22: </strong>Output from the subscriber, using environment sensors information</figcaption></figure><p>Figure 23 shows both publisher topics (from Raspberry Pi) and subscriber topics (from Desktop), in action, in a single screenshot. Figure 24, show them using <a href="https://docs.ros.org/en/foxy/Concepts/About-RQt.html">RQT Graph</a>, a very useful utility provided in ROS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFXP1RqrcFemV7K4Yz1Zhw.png" /><figcaption><strong>Figure 23: </strong>The subscriber and publisher topics, in action</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Q4ehQAGdIrXkrxb5y82fQ.png" /><figcaption><strong>Figure 24:</strong> RQT Graph showing publishers, subscribers and topics</figcaption></figure><p>So far we discussed gathering the data and publishing and subscribing it, so we can control the robot. Now, let’s discuss what are we going to do with some of the data we are receiving so far.</p><p><strong>Calculate Pitch, Roll and Yaw of the Robot — </strong>Since, we are getting accelerometer, gyroscope and compass data, we can utilize it to calculate roll, pitch and yaw of the robot. You can read this <a href="https://wiki.dfrobot.com/How_to_Use_a_Three-Axis_Accelerometer_for_Tilt_Sensing">blog</a> to have better understanding of what roll, pitch and yaw means. In terms of our robot, Figure 25 shows the coordinate system we are using.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7jYhb8U_T60qgSvDjhlKw.png" /><figcaption><strong>Figure 25:</strong> Coordinate system defined for the robot chassis, to determine roll, pitch and yaw</figcaption></figure><p>Figure 26, shows the code snippet for calculating roll, pitch and yaw from the data for all three sensors. The code is generated using Gen-AI. Additionally, I am using complementary filter, to get more accurate reading, as we can fuse information from all three sensors (accelerometer, gyroscope, and compass). The benefits of using complementary filter can be found <a href="https://ahrs.readthedocs.io/en/latest/filters/complementary.html">here</a>. Other, algorithms I might use in future are <a href="https://ahrs.readthedocs.io/en/latest/filters/ekf.html">Kalman filter</a> or <a href="https://github.com/xioTechnologies/Fusion">IMUFusion</a> library. I found roll and pitch data to be relatively accurate, however yaw calculation needs modification to get accurate reading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M3Rvd1KH3-FEHsLMDgS2MA.png" /><figcaption><strong>Figure 26:</strong> Code snippet to determine roll, pitch, and yaw using accelerometer, gyroscope and compass</figcaption></figure><p><strong>Calibration of Compass — </strong>If we try to use the direction from digital compass, using the raw magnetic fields readings, it might be off from the actual direction. In this case it is beneficial to calibrate the digital compass. A good description on how to do soft and hard calibration of digital compass can be found <a href="https://ozzmaker.com/compass3/">here</a>. Figure 27 shows the difference in digital compass reading and iPhone compass reading (with true north setting off), without calibration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bgxdF7itI3wKDS4Tsyq3vQ.png" /><figcaption><strong>Figure 27: </strong>Data showing significant difference in reading from iPhone compass app and reading from uncalibrated robot chassis compass</figcaption></figure><p>During the calibration process, we obtained various readings (magnetic field in x and y directions) in different orientations, by following the method described <a href="https://ozzmaker.com/compass3/">here</a>, for hard and soft calibration. As shown in Figure 28, the approximate circle center was significantly off from (0,0) coordinate, before calibration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*BEf5YLnoed3xEQuv1Qfd9g.png" /><figcaption><strong>Figure 28:</strong> Circle (approximate) drawn using raw magnetic X and Y direction reading from the digital compass after turning the robot in different directions.</figcaption></figure><p>Figure 29, shows the comparison between reading from iPhone compass (true north setting off) and the robot, after calibration. While, it is still not as accurate as iPhone compass, assuming iPhone compass is accurate, however it is a significant improvement from before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPy-o4MpwYuqxuEKijJMpw.png" /><figcaption><strong>Figure 29:</strong> Comparison between compass reading from iPhone compass app and calibrated digital compass on the robot chassis.</figcaption></figure><p>So, in summary, we have completed the following tasks, described in this blog:</p><p>1. Getting sensors information from robot chassis and BME280 chip</p><p>2. Created ROS topics — publishers on Raspberry Pi and subscribes on desktop</p><p>3. Performed data analysis and transformation to determine the orientation — roll, pitch and yaw — of the robot</p><p>4. Calibrated the digital compass on the robot</p><p>5. Receiving environment information — temperature, atmospheric pressure and relative humidity</p><p>Additionally, have some interesting tips, which I learned during these tasks:</p><p>1. Make sure you create an virtual environment, preferably conda, and the PYTHONPATH of the environment is defined in your .bashrc file (if using Ubuntu). Otherwise, you might run into issues of No Module found error when you run ROS, even though the package might get build without any error.</p><p>2. I am using Remote Explorer extension in VS Code, to remote login to Raspberry Pi and write code in VS Code IDE. With default options, you might see performance degradation in Raspberry PI, including it is crashing, when you try to connect with it using the extension. I found a cleaver workaround for that <a href="https://medium.com/good-robot/use-visual-studio-code-remote-ssh-sftp-without-crashing-your-server-a1dc2ef0936d">here</a>.</p><p>3. Install ROS2 base version in Raspberry Pi, instead of full desktop version as you won’t be using ROS2 packages — ROS, RViz, demos, tutorials — on Raspberry Pi, and base package is around 200 MB compared to around 2 GB for the desktop version.</p><p>4. Most of code I shown here can easily be generated using Gen AI, and I did that, wherever possible.</p><p>In the next part of the blog series, which will be published in few weeks, we will install a LIDAR and a GPS module to the robot for obstacle detection and to determine geographic location, respectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e6a86747c66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building An AI enabled Robot — Part 1]]></title>
            <link>https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-1-fecc688e5798?source=rss-52b350dff91d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fecc688e5798</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[uart]]></category>
            <category><![CDATA[i2c]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Mohit Jain]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 23:48:04 GMT</pubDate>
            <atom:updated>2025-03-10T22:43:15.662Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building An AI enabled Robot — Part 1</strong></h3><p>Special thanks to Hoa Mattaliano for her kind support.</p><p>The combination of robotics and AI is gaining significant traction now, after the advancement in AI and as well as relatively easy access to hardware needed to build AI enhanced robots. I am writing this blog, to document while building a basic AI robot, which can be customized and improved based on need. This is going to be a multi-part series, where we are going to build this robot in steps. Part 1 to 6 of the series will be more concentrated on setting up hardware and associated software, so the robot can interact with the world, followed by part 7 to 12, where we will bring in various components of AI.</p><p>Figure below, shows various components of the robot, I am planning to build. The list might change, in case I face issues during the build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69C8mJungD3VC09zuLXYCw.png" /><figcaption>Various components of the robot, that will be integrated.</figcaption></figure><h3><strong>Operating System and Base Computer</strong></h3><p>We are going to use Raspberry Pi 5 with Ubuntu 24.04 installed. The reason, I am using Ubuntu, instead of typical Raspberry PI OS, as I will be utilizing Robotic Operating System (ROS) 2. <a href="https://www.ros.org/blog/why-ros/">ROS</a> is an open source robotic software development kit, and provides a lots of functionality for robotics, and it is well supported for Ubuntu. The instructions on how to install Ubuntu for Raspberry Pi can be found <a href="https://www.raspberrypi.com/documentation/computers/getting-started.html">here</a>, and it uses Raspberry Pi Imager. Select Ubuntu 24.04 LTS (64 bit) from Other general-purpose OS, in Raspberry Pi Imager. I am using 128 GB SD card. Once OS is installed and updated, we need to make few configuration changes, specifically to enable two communications interfaces to the peripherals — I2C and UART. This will allow us to control the robot, using Raspberry PI and/or from a remote computer. Below are short instructions to accomplish that.</p><h4><strong>Enabling I2C and UART</strong></h4><p>While what I2C and UART are, will be described later part of the blog, we need to enable them using Raspberry Pi utility, called raspi-config. Unfortunately, this utility does not come by default in Ubuntu OS, that was installed for Raspberry Pi. However, it can easily be installed, by using the following commands:</p><p><strong>$ sudo apt-get update</strong></p><p><strong>$ sudo apt-get install raspi-config</strong></p><p>Once the utility is installed, we can start using it by using the following command:</p><p><strong>$ sudo raspi-config</strong></p><p>Below screenshots show you how to enable I2C communication:</p><p><strong>Step 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YdtGhH4e4iRzZu9-ltppFQ.png" /></figure><p><strong>Step 2:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rO0Va_tf1yCWsnOhdL9AnA.png" /></figure><p><strong>Step 3:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*gTZ-DJuStUgkwSu-Ja8dkQ.png" /></figure><p>Similarly Serial port for UART can be accessed using the following steps:</p><p><strong>Step 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4ZTWcaLP5UG1tM6sGeH_Q.png" /></figure><p><strong>Step 2:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*GOSwMiEFXyIDg1dHi5qg7Q.png" /></figure><p><strong>Step 3:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*ZE54TZ8e8N3Q_hHfZnKhAA.png" /></figure><p><strong>Step 4:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*_yITE0zO9xIwii8DZEXwoQ.png" /></figure><p>You will need to reboot Raspberry Pi to enable them.</p><p>There are few more things that are useful to have, such as having python environment and enabling SSH to remotely access the robot. We will be using python for majority of our coding needs. I am using Miniconda, which is a miniature installation of Anaconda Distribution, and quick instructions to installing it can be found <a href="https://docs.anaconda.com/miniconda/install/#quick-command-line-install">here.</a> The SSH utility can be installed by following the following instructions <a href="https://www.cyberciti.biz/faq/how-to-install-ssh-on-ubuntu-linux-using-apt-get/">here</a>. But in summary you need to use the following command to install SSH server on your Raspberry Pi robot, that uses Ubuntu:</p><h4>$ sudo apt install openssh-server</h4><h3><strong>Communication interface using I2C protocol</strong></h3><p>So now the basic setup is there, let’s talk about our first hardware communication interface — <strong>I2C or Two Wire Protocol</strong>. Why I2C? Because it only needs 2 wires + ground to communicate and you can add up to 128 devices!!! As of the current plan, I will be using I2C for getting environmental condition data — temperature, humidity, and pressure, as well as to communicate with servo motor controller — which allows us to control up to 16 servos from a single interface. You can learn more about I2C <a href="https://learn.sparkfun.com/tutorials/i2c/all">here</a>. Now, you need to get a device, that supports I2C, and you connect it to Raspberry Pi using appropriate pins (details later). How do you know, it is correctly connected? By scanning for that. For that you need to install i2c-tools utility, using the following command.</p><p><strong>$ sudo apt-get install i2c-tools</strong></p><p>and once install you can scan using the following command:</p><p><strong>$ i2cdetect -y 1</strong></p><p>When you scan, without any I2C device connected, you should get something as following, with all blanks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*MtglstBG-0jdGMZp49RepQ.png" /></figure><p>Once, the device is connected, you should be able to see the address of the device, when you run the same command again. In my case I connected a temperature/humidity/pressure sensor (<a href="https://randomnerdtutorials.com/raspberry-pi-bme280-python/">BME 280</a>), and it is detected at address 76.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*hhFAveCvkrxOLqejDZVl-g.png" /></figure><p>This sensor comes with four pins, as shown in picture below. VIN → connected to Raspberry Pi pin 1 (3.3 V power) on GPIO board, SDA → connected to Pin 3, SCL → connected to Pin 5, and ground → connected to Pin 9 or any other ground pin available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XR9gRbf6Kh4aE35H5d5vyw.jpeg" /></figure><p>Usually you can find libraries that support a particular I2C device. Since, I am going to use this chip for the robot, I installed RPI.BME280 library, using the following command:</p><p><strong>$ sudo pip install RPI.BME280</strong></p><p>And using and running the code provided <a href="https://randomnerdtutorials.com/raspberry-pi-bme280-python/">here</a>, you can easily get data from the chip, as shown below. We will use this data in our robot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*kqICjreoXkzmEANfQXCxhg.png" /></figure><p>So we have our setup completed for I2C, now let’s move on to UART setup, which can be slightly more complicated.</p><h3><strong>Communication Interface using UART protocol</strong></h3><p>UART stands for Universal Asynchronous Receive and Transmit. It is a serial communication protocol, and details can be found <a href="https://www.rohde-schwarz.com/us/products/test-and-measurement/essentials-test-equipment/digital-oscilloscopes/understanding-uart_254524.html#:~:text=What%20is%20UART%3F,and%20receive%20in%20both%20directions.">here</a>. It usage is very simple and required only two wires + ground. We will be using UART to get accelerometer, gyroscope and magnetic field data from the robot, as well as to move the robot, using four DC motors. There are total 5 UART communication possible in Raspberry Pi 5, that we will enable after few configuration changes. We have to check cmdline.txt file in /boot/firmware directory to make sure “<strong>console=serial0 ttyAMA0</strong>” is not present. Next we need to update config.txt file in /boot/firmware directory. We can use the following command:</p><p><strong>$ sudo nano /boot/firmware/config.txt</strong></p><p>and add the following lines in the end of config.txt file, as shown in the picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*uLR3rXeigha71MHkWanpUA.png" /></figure><p>Reboot the computer, and once you run the following command, you should be able to see the following UART ports enabled:</p><p><strong>$ ls -la /dev/ttyAMA*</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*Mx1FHLAB7_TJHUKtRQbJ0g.png" /></figure><p>We can use ttyAMA0 to ttyAMA4 ports for our robot to communicate with the peripherals. However the question is, which UART corresponds to which pair of pins. You can use the following diagram as a guide. The diagram is inspired from <a href="https://www.youtube.com/watch?v=LsNIRMNAAZ8&amp;t=634s">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ODR3SpAN9LJjCTtoAcJTfg.png" /></figure><p>We can test that if the ports are working, by looping TX and RX of the ports. Make sure you have python Serial library installed, in your python environment, using following command:</p><p><strong>$ pip install pyserial</strong></p><p>A simple script, shown below, that can be found on internet or generated by AI can be used to test the UART. In this example, we are using ttyAMA1 (UART1), by connecting pin 27 to pin 28.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*0jEhegM43AuSSVRuctUhfA.png" /></figure><p>You might get a permission denied error, when you run the script, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFpc1Fhl-tevgSydQDhGXg.png" /></figure><p>In that case, use the following command:</p><p><strong>$ sudo chmod 766 /dev/ttyAMA1</strong></p><p>Change ttyAMA1 to whichever port you are connected to. If everything working fine, you should get the following, when running the above script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*GpKltyqjFA7z7S7DYeXHWQ.png" /></figure><p>Since we are going to be using GPIO very often in our project, it is a good idea to install <strong>pinctrl</strong> library. While it comes in Raspberry PI OS, it does not comes as default for Ubuntu. However, you can easily build it from <a href="https://github.com/raspberrypi/utils/tree/master/pinctrl">here</a>. For example we can see which function is assigned to pins GPIO0 (Pin 27) and GPIO1 (Pin 28), by using the following command:</p><p><strong>$ sudo pinctrl get 0,1</strong></p><p>and we should see the following, if we have setup the UART1 properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sl2SSpzr8JWgNoIv_dyUcg.png" /></figure><p>So, in Part I of this series we have setup Raspberry Pi for our next step — connecting Raspberry Pi to robot chassis. We will do that <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-2-3e6a86747c66?source=friends_link&amp;sk=f874966d3f2ce1121dd69f48e9a007f7">Part 2</a>. We will also see how to receive data from various sensors — accelerometer, gyroscope, and digital compass — over UART. This will involve using Arduino IDE, with ESP32 board and python script. Additionally, we will do soft calibration of the digital compass to get accurate direction reading.</p><p>Stay tuned for <a href="https://medium.com/@mohitjain72/building-an-ai-enabled-robot-part-2-3e6a86747c66?source=friends_link&amp;sk=f874966d3f2ce1121dd69f48e9a007f7">Part 2</a>, which will be released in couple of weeks…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fecc688e5798" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detection and visualization of brainwaves using Python, D3 and Bootstrap]]></title>
            <link>https://medium.com/@mohitjain72/detection-and-visualization-of-brainwaves-using-python-d3-and-bootstrap-742129f9ed97?source=rss-52b350dff91d------2</link>
            <guid isPermaLink="false">https://medium.com/p/742129f9ed97</guid>
            <category><![CDATA[eeg]]></category>
            <category><![CDATA[brainwaves]]></category>
            <category><![CDATA[d3js]]></category>
            <category><![CDATA[bootstrap]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Mohit Jain]]></dc:creator>
            <pubDate>Sat, 26 Sep 2020 17:22:01 GMT</pubDate>
            <atom:updated>2021-08-12T10:17:03.303Z</atom:updated>
            <content:encoded><![CDATA[<p>Brainwaves are electrical signals produced when neurons within the brain communicate with each other, which leads to emotions, consciousness, and behavior. These brainwaves can be detected using a technique called Electroencephalography (<a href="https://en.wikipedia.org/wiki/Electroencephalography">EEG</a>). During EEG, electrodes are placed on certain locations of scalp to detect these electrical impulses. Just from a magnitude perspective the electrical potential (voltage) generated by these electrical impulses have amplitude of only around 100 <a href="http://www.bem.fi/book/13/13.htm#:~:text=The%20amplitude%20of%20the%20EEG,as%20demonstrated%20in%20Figure%2013.1.">microvolts</a>, which leads to very weak signals.</p><p>The brainwaves are typically divided into certain bands, based on the frequency range, to determine various states of the brain. Below is the brief description of the various <a href="https://nhahealth.com/brainwaves-the-language/">bands</a>:</p><p><strong>Delta Waves (0.5–3 Hz):</strong> These waves have the lowest frequency and typically associated with dreamless sleep or a deep state of meditation.</p><p><strong>Theta Waves (3–8 Hz): </strong>These waves are typically present during light sleep, which also includes rapid eye movement (REM) state. They are also present during deep meditation or spiritual awareness and can reflect subconscious state of mind.</p><p><strong>Alpha Waves (8–12 Hz):</strong> Alpha waves are associated with the resting state of mind and typically observed during when thinking quietly or in some stages of meditation.</p><p><strong>Beta Waves</strong> <strong>(12–38 Hz):</strong> These waves are related to ‘fast’ activity of brain and associate with an alert brain or when we have our eyes open. Since these waves have a large range, they are further divided into three categories: Low-Beta (12- 15 Hz) — musing, Mid-Beta (15 -1 8Hz) — high engagement, and High-Beta (18 -30 Hz) — high anxiety or excitement.</p><p><strong>Gamma (38–42 Hz): </strong>These are the highest frequency waves and associated with burst of insight and high -level information processing.</p><p>While a professional EEG detector can cost hundreds to thousands of dollars, I decided to use a relatively cheap (&lt; $50) TGAM brainwave sensor manufactured by NeuroSky. While the expensive sensors have multiple electrodes, TGAM has only one electrode, which is placed on the forehead. Hence the sensitivity of this sensor is not that great, but it is good enough to get some experience in EEG analysis. Another advantage is that it works with dry electrode, so no gel is needed.</p><p>Figure 1 shows the picture of the sensor I used. It has four major components: (1) TGAM module; (2) Bluetooth module; (3) Stainless steel electrode; and (4) Battery pack (2 AAA batteries). You can buy the modules separately and solder the connections and electrode. However, soldering stainless steel is not an easy task, hence I opted for a pre-assembled unit. This unit can easily be purchased from eBay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*McWr9IZpYMs4OgMfeQNBTw.png" /><figcaption><strong>Figure 1:</strong> Photograph of the brainwave sensor, based on TGAM module. (Image by author)</figcaption></figure><p>The operating system I used to write the python code and connecting to the sensor was Ubuntu 18.04. While there are various python libraries that can be used to automatically search for Bluetooth device and connect to it, I found that it is much more reliable and easier to just manually connect the Bluetooth of the brainwave sensor to the serial port of the computer using serial python library. Instead of using default Bluetooth utility provided by Ubuntu, I opted to use<strong> blue man</strong> package. Instructions on how to install this package can be found <a href="https://www.maketecheasier.com/setup-bluetooth-in-linux/">here</a> . I used ZEXMTE Bluetooth USB <a href="https://www.amazon.com/gp/product/B0775YF36R/ref=ppx_yo_dt_b_asin_title_o05_s00?ie=UTF8&amp;psc=1">adapter</a>.</p><p>The data was visualized on web browser using D3, which is a data visualization library written in JavaScript. You can learn more about D3 <a href="https://d3js.org/">here</a>. A good link to learn D3 quickly can be found <a href="https://leanpub.com/D3-Tips-and-Tricks">here</a> . To create the web page, I used <a href="https://getbootstrap.com/">Bootstrap </a>, which is a front-end open source toolkit.</p><p><strong>Connecting TGAM module to the computer</strong></p><p>Figure 2 shows the screenshots to connect TGAM, using Bluetooth, to the serial port of the computer. Once connected we get the port information, in this case ‘/dev/rfcomm7’. We will use this port information to receive data for further processing using the python code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*55bqgdt3qXkx3MEw4PN5Rw.png" /><figcaption><strong>Figure 2:</strong> Screenshots of connecting TGAM module using Bluetooth (Image by author)</figcaption></figure><p><strong>TGAM Module Communication Information</strong></p><p>A detailed description of the data communication protocol used for TGAM module can be found <a href="http://wearcam.org/ece516/mindset_communications_protocol.pdf">here</a> and TGAM data sheet can be found <a href="http://www.seeedstudio.com/document/pdf/TGAM%20Datasheet.pdf">here</a> .</p><p>Figure 3 shows codes for the data transmitted by TGAM module. Two of the most important codes, which we will utilize are 0x02 and 0x80. The code 0x02 will let us know the signal quality. It is a single-byte code and has value between 0 -255, and updated every second. Any value above 5 will be treated as noisy signals coming from the sensor. The value 200 for this code also tells us if the electrode is touching the skin. The multi-byte code 0x80 gives us the raw value of the signals. It is 16-bit code and has value between -32768 and 32767 and updated every 2 ms(512 samples/second). We will also record code 0x04 (Attention), 0x05 (Meditation), and 0x83 (Brainwave Bands) but will not use them for visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*we1QqNCO2K60_4mT4PQiTA.png" /><figcaption><strong>Figure 3:</strong> Code definitions for TGAM module (reproduced from TGAM datasheet)</figcaption></figure><p>Figure 4 shows the sample data, reproduced from TGAM module datasheet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*o7DX67EMKLtWOPccn6LKBg.png" /><figcaption><strong>Figure 4:</strong> Example sample data (reproduced from TGAM datasheet)</figcaption></figure><p>Figure 5 shows a snippet of raw data received from the sensor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*bxsss8OKC0GuicOItVvM5g.png" /><figcaption><strong>Figure 5:</strong> Snippet of data from TGAM</figcaption></figure><p><strong>Processing and Visualizing Data from TGAM Module</strong></p><p>Figure 6 shows the simple function to read the data, using serial port. One thing to keep in mind is to make sure that the baud rate is 57600, as we get raw value data only at these high baud rates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*fy54r_BFeMPWESU3uVo61A.png" /><figcaption><strong>Figure 6:</strong> Function to read data from the sensor</figcaption></figure><p>Once the data is read, we take advantage of python’s generator function to read each byte at a time and perform processing based on the type of data received. For example, if the data is for raw values (code: 0x80) we read two bytes, and when the data is for poor signals (code: 0x02) we read single byte. Figure 7 shows a code snippet where we read raw values data. We need to perform bit shifting to read both bytes to get the whole value. Once we have read 512 values (~1 second worth of data), we save them in a temporary JSON file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*sEPedS2It-BxvNnE38N4zA.png" /><figcaption><strong>Figure 7:</strong> Code snippet to read raw wave values.</figcaption></figure><p>The first thing we do after saving the data is to normalize the data so that all the values are between -1 and 1, using the equation below:</p><p>Normalized_Value = 2*(Absolute_Value — Minimum_Value)/ (Maximum_Value — Minimum_Value) -1</p><p>Figure 8 shows the normalized brainwave data chart generated using D3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOx6Fx2-dp_UcFeXZVecuQ.gif" /><figcaption><strong>Figure 8:</strong> Normalized brainwave data (Image by author)</figcaption></figure><p><strong>Determining Brainwave Bands</strong></p><p>Subsequently, I used normalized brainwave data, collected for 1 second, and applied <a href="https://en.wikipedia.org/wiki/Welch%27s_method">Welch’s</a> method to determine spectral density of the wave. This allowed us to calculate power of a signal at different frequencies. It was further used to determine the signal strength for each brain wave type. We used S<strong><em>ignal</em></strong> library of the SciPy library. Figure 9 shows the code snippet to perform this analysis. We get frequencies and associated power density signals using the code shown in Figure 9. Figure 10 show shows the visual created using this data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*1esCJpGAxyllZzIeO52AOA.png" /><figcaption><strong>Figure 9:</strong> Code snippet to perform to use Welch’s method for power density estimation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*fWGw9yFfFanObx_T8dAD6g.png" /><figcaption><strong>Figure 10:</strong> Welch’s Periodogram of the brainwaves (Image by author)</figcaption></figure><p>The data derived from Welch’s periodogram was further analyzed to determine the specific brainwave bands. This was achieved by determining the area-under-the-curve within the frequency range allocated to the band. Subsequently the total area-under-the-curve was also calculated and the area for the bands was normalized. We applied Simpson’s rule using scipy.integrate.sims library to calculate the area-under-the-curve. Details about Simpson’s rule to calculate area can be found <a href="https://www.dummies.com/education/math/calculus/how-to-approximate-area-with-simpsons-rule/">here</a>. Figure 12 shows the strength of each type of brainwave.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*pzb4kXoLlkMpBtYS-Y1W0Q.png" /><figcaption><strong>Figure 11:</strong> Code snippet showing range of various bands used for calculation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*EELDu6apqe8leTwfee1D8Q.png" /><figcaption><strong>Figure 12:</strong> Various brainwave bands calculated from the raw brainwave data (Image by author)</figcaption></figure><p>If you are interested in additional details on determining bands, you can read <a href="https://raphaelvallat.com/bandpower.html">here</a>.</p><p>We can also drive a spectrogram from the raw wave data. This allows us to visualize the strength of brainwave signals at various frequencies over a period of time. You can learn more about spectrogram <a href="https://www.pnsn.org/spectrograms/what-is-a-spectrogram">here</a> . Figure 13 shows the spectrogram, which demonstrate a heat map of frequency vs. time. We used build-in function of matplotlib python library for this. You can also use python Librosa library to generate the spectrogram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*pfdzpkXj4FVmjTP9sW5ROQ.png" /><figcaption><strong>Figure 13:</strong> Brainwave spectrogram (Image by author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*N3cyEWTS75cjWu4f1GVqEw.png" /><figcaption><strong>Figure 14:</strong> Code snippet to generate spectrogram</figcaption></figure><p>The final part is to generate an imaginary scenario, where we can hear the brainwaves. This entails transforming the brainwave into acoustic waves. This was achieved using amplitude modulation (AM). Details on how to perform amplitude modulation can be found <a href="https://en.wikipedia.org/wiki/Amplitude_modulation#:~:text=Amplitude%20modulation%20(AM)%20is%20a,such%20as%20an%20audio%20signal">here</a> . In essence we need to select a carrier wave and information signal. In our case the information signal is the normalized brainwave data. We selected a carrier frequency of 500 Hz, but you can select based on your preference. Higher the frequency you select, higher the pitch in the sound you will hear. We selected the sample rate of 22,050. This should not be confused with the sample rate used in the TGMA chip, which is only 512 Hz. Below is the code snippet. The carrier signal modulation and amplitude can be adjusted, as desired. Basically, we generate extra data points from the raw brainwave signal using NumPy interpolation library, and use that to create the sound wave. Finally, the data was saved as a MP3 file using scipy.io.wavfile write module. Figure 15 shows the visualization of the sound wave, generated using the raw brainwave and the carrier wave.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*_sIEF-lN6mI0gIbrBxjY_w.png" /><figcaption><strong>Figure 15:</strong> Brainwave visualized as sound wave (Image by author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*FSq5YwrVNEVlZT_2FjrSLw.png" /><figcaption><strong>Figure 16:</strong> Code to transform brainwave to sound wave</figcaption></figure><p>Figure 17 shows the widget to play the corresponding MP3 file on the webpage, created using HTML5 audio element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*DODK1XJpl5HxbaKv9UoMpA.png" /><figcaption><strong>Figure 17:</strong> Widget to hear simulated sound of the brainwave (Image by author)</figcaption></figure><p>The code for both data processing in python and data visualization using D3 and Bootstrap can be found <a href="https://github.com/mjain72/brainwave">here</a> .</p><p><strong>Disclaimer:</strong> Do not use the work described in this article and the associated code for medical research. This is just to get some familiarity with brainwaves.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=742129f9ed97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A New Hyperbolic Tangent Based Activation Function for Neural Networks]]></title>
            <link>https://medium.com/data-science/a-new-hyperbolic-tangent-based-activation-function-for-neural-networks-2aaa20087d7c?source=rss-52b350dff91d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2aaa20087d7c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[activation-functions]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[relu]]></category>
            <dc:creator><![CDATA[Mohit Jain]]></dc:creator>
            <pubDate>Sat, 10 Nov 2018 16:07:07 GMT</pubDate>
            <atom:updated>2021-08-12T10:13:45.818Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A New Hyperbolic Tangent Based Activation Function for Neural Networks</strong></p><p><strong>Abstract:</strong></p><p>In this article, I introduce a new hyperbolic tangent based activation function, <em>tangent linear unit (TaLU),</em> for neural networks. The function was evaluated for performance using CIFAR-10 and CIFAR-100 database. The performance of the proposed activation function was in par or better than other activation functions such as: <em>standard rectified linear unit (ReLU)</em>, <em>leaky rectified linear unit (Leaky ReLU),</em> and exponential linear unit (ELU).</p><p><strong>Introduction:</strong></p><p>The rectified linear unit (ReLU)(Nair V. and Hinton, G. E., “Rectified linear units improve restricted Boltzmann machines”, <em>ICML</em>, 2010, pp. 807–810) is one of the most popular non-saturated activation functions, used in neural networks. However, ReLU suffers from the problem of <em>dying ReLU</em>, where some of the neurons starts to output 0. Sometimes, half the neurons die, in particular if they are used with large learning rate (Géron, A., “Hands-On Machine Learning with Scikit-Learn &amp; TensorFlow”, 1st ed., <em>O’Reilly Media, Inc.</em>, 2017, p. 281). To circumvent these problems, Xu et al. ( Xu, B., Wang, N., Chen, T., Li, M., “Emperical Evaluation of Rectified Activations in Convolution Network”, <em>aerXiv preprint arXiv:1505.00853v2</em>, 2015)evaluated variants of ReLU, such as <em>leaky rectified linear unit</em> (leaky ReLU), <em>parametric rectified linear unit</em> (PReLU) and <em>randomized rectified linear unit</em> (RReLU). It was observed that leaky ReLU mostly outperformed the standard ReLU. Clevert et al. (Clevert, D., Unterthiner, T., Hochreiter, S., “Fast and Accurate Deep Network Learning by Exponential Linear Units”, <em>aerXiv preprint arXiv:1511.07289</em>, 2015) proposed exponential linear unit (ELU) that was observed to outperform all the variants of ReLU (Géron, A., “Hands-On Machine Learning with Scikit-Learn &amp; TensorFlow”, 1st ed., <em>O’Reilly Media, Inc.</em>, 2017, p. 282).</p><p>I propose a new activation function based on hyperbolic tangent function, <em>tangent linear unit (TaLU)</em>. Discussed below are the definition of TaLU, followed by determination of its optimized parameters and its comparison with other activation functions such as ReLU, leaky ReLU and ELU.</p><p><strong>Tangent Linear Unit (TaLU):</strong></p><p>The tangent linear unit (TaLu) can be illustrated in <strong>Figure 1</strong>, and can be described by <strong>equation below</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YmmSd40fgluD3dkppmQAew.png" /><figcaption>(Image by author)</figcaption></figure><p><strong>Figure 1:</strong> Tangent Linear Unit (TaLU)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*190fkpW3fiwy2vgWB7_szA.png" /></figure><p>where α is a fixed parameter with values &lt; 0. α was tested from -0.50 to -0.01 in this article.</p><p><strong>Experimental Setup:</strong></p><p>The proposed activation function was tested on CIFAR-10 and CIFAR-100 datasets, and the performance was compared with ReLU, leaky ReLu (α = 0.01) and ELU (α = 1). The python-based libraries: Tensorflow, Numpy, Pandas and Keras library were used during this study. The neural network architecture is described in <strong>Figure 2</strong>. The data was divided into train and validation in the ratio of 9:1 from the train datasets provided for CIFAR-10 and CIFAR-100, and the model was tested on test datasets provided for CIFAR-10 and CIFAR-100.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJQhR-vQvcnpuYvtwEep2g.png" /></figure><p><strong>Figure 2: </strong>The architecture of the neural network used during this study (Note: the activation function (af) in Layers 1, 2, 5, 7, 11 was Talu, ReLU, ELU, and leaky ReLU, based on the experiment).</p><p>The code can be found at <a href="https://github.com/mjain72/TaLuActivationFunction">https://github.com/mjain72/TaLuActivationFunction</a></p><p><strong>Parametric Study for TaLU:</strong></p><p>Initially, a parametric study was performed to determine the optimum value of α. <strong>Table 1</strong> shows the loss and accuracy values for train, validation and test for CIFAR-10 dataset. The number of epochs were 25, during training. The optimum value of α was found to be -0.05. Similar optimal value for α was observed for CIFAR-100 dataset (<strong>Table 2</strong>).</p><p><strong>Table 1:</strong> Parametric Study for TaLU using CIFAR-10 dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*8DfE4U6ZEvR5aOzWQP1R8Q.png" /></figure><p><strong>Table 2:</strong> Parametric Study for TaLU using CIFAR-100 dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*JH8QA4F8P1Pm6Gnd44RN4A.png" /></figure><p>Based on these studies, it was decided to use α = -0.05 for TaLU, during the comparison study with ReLU, leaky ReLU and ELU activation functions.</p><p><strong>Comparative study of TaLU with various activation functions:</strong></p><p>Once it was determined that the optimum value of α is -0.05, in case of TaLU, we used this value to perform a comparative study, with other activation functions. <strong>Table 3</strong> shows the performance of various functions, in the case of CIFAR-100 dataset. The performance of TaLU was observed to be superior, in terms of accuracy, compared to other activation functions.</p><p><strong>Table 3:</strong> Performance of various activation functions for CIFAR-100 dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*e9PxHHwLVghUlveQXor5Uw.png" /></figure><p><strong>Table 4</strong>, shows the performance of various activation functions, in the case of CIFAR-10 dataset. In this case also, the performance of TaLU was in par or superior to other activation functions.</p><p><strong>Table 4:</strong> Performance of various activation functions for CIFAR-10 dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*Cq8pYJC_KPr0LrOSnSXOTw.png" /></figure><p><strong>Conclusions:</strong></p><p>Based on the above study, it can be concluded that the proposed activation function, TaLU, provides a better or similar performance as currently used activation functions, such as ReLU, leaky ReLU and ELU, and should be evaluated for future studies.</p><p><strong>Convergence Curves:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*6nU56t5bdIzjD8bSQRZ1Ow.png" /><figcaption>(Image by author)</figcaption></figure><p><strong>Figure 3:</strong> Convergence curves for TaLU at different α values, shown in parenthesis, using CIFAR-10 dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*HBcGj8CBGhXB1YvtB-Ajzw.png" /><figcaption>(Image by author)</figcaption></figure><p><strong>Figure 4:</strong> Convergence curves for TaLU at different α values, shown in parenthesis, using CIFAR-100 dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*vBJPd5t5C8uwOmlzt8inRQ.png" /><figcaption>(Image by author)</figcaption></figure><p><strong>Figure 5:</strong> Convergence curves for different activation functions, using CIFAR-10 dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*8-G8xDQ_a4NyK3gU3zYTFg.png" /><figcaption>(Image by author)</figcaption></figure><p><strong>Figure 6:</strong> Convergence curves, for different activation functions, for CIFAR-100 dataset.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2aaa20087d7c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-new-hyperbolic-tangent-based-activation-function-for-neural-networks-2aaa20087d7c">A New Hyperbolic Tangent Based Activation Function for Neural Networks</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hyperparameter tuning in XGBoost using genetic algorithm]]></title>
            <link>https://medium.com/data-science/hyperparameter-tuning-in-xgboost-using-genetic-algorithm-17bd2e581b17?source=rss-52b350dff91d------2</link>
            <guid isPermaLink="false">https://medium.com/p/17bd2e581b17</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[genetic-algorithm]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Mohit Jain]]></dc:creator>
            <pubDate>Mon, 17 Sep 2018 02:00:46 GMT</pubDate>
            <atom:updated>2021-08-12T10:11:54.988Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>Genetic algorithm, as defined in <a href="https://en.wikipedia.org/wiki/Genetic_algorithm">wikipedia</a>, takes its inspiration from the process of natural selection, proposed by <a href="https://en.wikipedia.org/wiki/Natural_selection">Charles Darwin</a>. In a more general term, we can understand the natural process and how it is related it to the genetic algorithm, using the following description:</p><p>We start with initial population, which will have certain traits, as shown in Figure 1. This initial population will be tested in a certain environment to observe how well the individuals (parents) in this population perform, based on a predefined fitness criteria. The fitness in case of machine learning can be any performance metric- accuracy, precision, recall, F1-score, auc among others. Based on the fitness value we select top performing parents (“survival of the fittest”), as the survived population (Figure 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uqQLuhCeqbfyOyHtPt3Ixg.png" /><figcaption>(Image by author)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9mrDW_6WWBuggN6pGLinwg.png" /><figcaption>(Image by author)</figcaption></figure><p>Now the parents in the survived population will mate to produce offspring, using a combination of two steps: crossover/recombination and mutation. In the case of crossover, the genes (parameters) from the mating parents will be recombined, to produce offspring, with each children inheriting some genes (parameters) from each parent (Figure 3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-rR-u4oyCZy39m4v-Pvhg.png" /><figcaption>(Image by author)</figcaption></figure><p>Finally, in the case of mutation, some of the values of the genes (parameters) will be altered to maintain a genetic diversity (Figure 4). This allows the nature/genetic algorithm to typically arrive at a better solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zlcm1KQCD3Enzx5F1WhufQ.png" /><figcaption>(Image by author)</figcaption></figure><p>Figure 5 shows the second generation of population, which will contain both survived parents as well as children. We keep the survived parents so as to retain best fitness parameters in case the offspring’s fitness value turns out to be worse than the parents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pn-Ab86YbsqVH_C5t_OAmA.png" /><figcaption>(Image by author)</figcaption></figure><h3><strong>Genetic Algorithm Module for </strong><a href="https://xgboost.readthedocs.io/en/latest/index.html"><strong>XGBoost</strong></a><strong>:</strong></h3><p>We will create a genetic algorithm module customized for XGBoost. Below is the description of XGboost:</p><blockquote><strong>XGBoost</strong> is an optimized distributed gradient boosting library designed to be highly <strong>efficient</strong>, <strong>flexible</strong> and <strong>portable</strong>. It implements machine learning algorithms under the <a href="https://en.wikipedia.org/wiki/Gradient_boosting">Gradient Boosting</a> framework.</blockquote><p>The module will have functions to follow the four steps: (i) initialization, (ii) selection, (iii) crossover, and (iv) mutation, similar to the what is discussed above (A small section of this code is inspired from the post <a href="https://towardsdatascience.com/genetic-algorithm-implementation-in-python-5ab67bb124a6">here</a>).</p><p><strong>Initialization:</strong></p><p>The first step is initialization, where the parameters are randomly initialized to create the population. It is similar to the first generation of the population shown in Figure 1. The code below shows the initialization process, where we generate a vector containing the parameters. In the case of XGBoost we have selected 7 parameters to optimize: learning_rate, n_estimators, max_depth, min_child_weight, subsample, colsample_bytree, and gamma. A detailed description of these parameters can be found <a href="https://xgboost.readthedocs.io/en/latest/parameter.html">here</a>.</p><pre>def initilialize_poplulation(numberOfParents):<br>    learningRate = np.empty([numberOfParents, 1])<br>    nEstimators = np.empty([numberOfParents, 1], dtype = np.uint8)<br>    maxDepth = np.empty([numberOfParents, 1], dtype = np.uint8)<br>    minChildWeight = np.empty([numberOfParents, 1])<br>    gammaValue = np.empty([numberOfParents, 1])<br>    subSample = np.empty([numberOfParents, 1])<br>    colSampleByTree =  np.empty([numberOfParents, 1])</pre><pre>for i in range(numberOfParents):<br>        print(i)<br>        learningRate[i] = round(random.uniform(0.01, 1), 2)<br>        nEstimators[i] = random.randrange(10, 1500, step = 25)<br>        maxDepth[i] = int(random.randrange(1, 10, step= 1))<br>        minChildWeight[i] = round(random.uniform(0.01, 10.0), 2)<br>        gammaValue[i] = round(random.uniform(0.01, 10.0), 2)<br>        subSample[i] = round(random.uniform(0.01, 1.0), 2)<br>        colSampleByTree[i] = round(random.uniform(0.01, 1.0), 2)<br>    <br>    population = np.concatenate((learningRate, nEstimators, maxDepth, minChildWeight, gammaValue, subSample, colSampleByTree), axis= 1)<br>    return population</pre><p>The limits on the parameters are either based on the limits described in the XGBoost documentation or based on an reasonable guess, if the upper limit is set to infinity. We start with creating an empty array for each parameter, followed by populating it with random values.</p><p><strong>Parent selection (survival of the fittest)</strong></p><p>In the second step we train our model using the initial population and calculate the fitness value. In this case we will calculate the F1-score.</p><pre>def fitness_f1score(y_true, y_pred):<br>    fitness = round((f1_score(y_true, y_pred, average=&#39;weighted&#39;)), 4)<br>    return fitness</pre><pre>#train the data annd find fitness score<br>def train_population(population, dMatrixTrain, dMatrixtest, y_test):<br>    fScore = []<br>    for i in range(population.shape[0]):<br>        param = { &#39;objective&#39;:&#39;binary:logistic&#39;,<br>              &#39;learning_rate&#39;: population[i][0],<br>              &#39;n_estimators&#39;: population[i][1], <br>              &#39;max_depth&#39;: int(population[i][2]), <br>              &#39;min_child_weight&#39;: population[i][3],<br>              &#39;gamma&#39;: population[i][4], <br>              &#39;subsample&#39;: population[i][5],<br>              &#39;colsample_bytree&#39;: population[i][6],<br>              &#39;seed&#39;: 24}<br>        num_round = 100<br>        xgbT = xgb.train(param, dMatrixTrain, num_round)<br>        preds = xgbT.predict(dMatrixtest)<br>        preds = preds&gt;0.5<br>        fScore.append(fitness_f1score(y_test, preds))<br>    return fScore</pre><p>We will define how many parents we would like to select and create an array with the selected parents, based on their fitness value.</p><pre>#select parents for mating<br>def new_parents_selection(population, fitness, numParents):<br>    selectedParents = np.empty((numParents, population.shape[1])) #create an array to store fittest parents<br>    <br>    #find the top best performing parents<br>    for parentId in range(numParents):<br>        bestFitnessId = np.where(fitness == np.max(fitness))<br>        bestFitnessId  = bestFitnessId[0][0]<br>        selectedParents[parentId, :] = population[bestFitnessId, :]<br>        fitness[bestFitnessId] = -1 #set this value to negative, in case of F1-score, so this parent is not selected again<br>    return selectedParents</pre><p><strong>Crossover</strong></p><p>There are various methods to define crossover in the case of <a href="https://en.wikipedia.org/wiki/Crossover_(genetic_algorithm)">genetic algorithms</a><a href="https://en.wikipedia.org/wiki/Crossover_(genetic_algorithm)),">,</a> such as single-point, two-point and k-point crossover, uniform crossover and crossover for ordered lists. We are going to use uniform crossover, where each parameter for the child will be independently selected from the parents, based on a certain distribution. In our case we will use “discrete uniform” distribution from <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html#numpy.random.randint">numpy random function </a>.</p><pre>&#39;&#39;&#39;<br>Mate these parents to create children having parameters from these parents (we are using uniform crossover method)<br>&#39;&#39;&#39;<br>def crossover_uniform(parents, childrenSize):<br>    <br>    crossoverPointIndex = np.arange(0, np.uint8(childrenSize[1]), 1, dtype= np.uint8) #get all the index<br>    crossoverPointIndex1 = np.random.randint(0, np.uint8(childrenSize[1]), np.uint8(childrenSize[1]/2)) # select half  of the indexes randomly<br>    crossoverPointIndex2 = np.array(list(set(crossoverPointIndex) - set(crossoverPointIndex1))) #select leftover indexes<br>    <br>    children = np.empty(childrenSize)<br>    <br>    &#39;&#39;&#39;<br>    Create child by choosing parameters from two parents selected using new_parent_selection function. The parameter values<br>    will be picked from the indexes, which were randomly selected above. <br>    &#39;&#39;&#39;<br>    for i in range(childrenSize[0]):<br>        <br>        #find parent 1 index <br>        parent1_index = i%parents.shape[0]<br>        #find parent 2 index<br>        parent2_index = (i+1)%parents.shape[0]<br>        #insert parameters based on random selected indexes in parent 1<br>        children[i, crossoverPointIndex1] = parents[parent1_index, crossoverPointIndex1]<br>        #insert parameters based on random selected indexes in parent 1<br>        children[i, crossoverPointIndex2] = parents[parent2_index, crossoverPointIndex2]<br>    return children</pre><p><strong>Mutation</strong></p><p>The final step will be to introduce diversity in the children by randomly selecting one of the parameter and altering it’s value by a <a href="https://en.wikipedia.org/wiki/Mutation_(genetic_algorithm)">random amount</a>. We will introduce some limits also, in order to constrain the altered values within a certain range. Skipping these constrains might lead to error.</p><pre>def mutation(crossover, numberOfParameters):<br>    #Define minimum and maximum values allowed for each parameter</pre><pre>minMaxValue = np.zeros((numberOfParameters, 2))<br>    <br>    minMaxValue[0:] = [0.01, 1.0] #min/max learning rate<br>    minMaxValue[1, :] = [10, 2000] #min/max n_estimator<br>    minMaxValue[2, :] = [1, 15] #min/max depth<br>    minMaxValue[3, :] = [0, 10.0] #min/max child_weight<br>    minMaxValue[4, :] = [0.01, 10.0] #min/max gamma<br>    minMaxValue[5, :] = [0.01, 1.0] #min/maxsubsample<br>    minMaxValue[6, :] = [0.01, 1.0] #min/maxcolsample_bytree<br> <br>    # Mutation changes a single gene in each offspring randomly.<br>    mutationValue = 0<br>    parameterSelect = np.random.randint(0, 7, 1)<br>    print(parameterSelect)<br>    if parameterSelect == 0: #learning_rate<br>        mutationValue = round(np.random.uniform(-0.5, 0.5), 2)<br>    if parameterSelect == 1: #n_estimators<br>        mutationValue = np.random.randint(-200, 200, 1)<br>    if parameterSelect == 2: #max_depth<br>        mutationValue = np.random.randint(-5, 5, 1)<br>    if parameterSelect == 3: #min_child_weight<br>        mutationValue = round(np.random.uniform(5, 5), 2)<br>    if parameterSelect == 4: #gamma<br>        mutationValue = round(np.random.uniform(-2, 2), 2)<br>    if parameterSelect == 5: #subsample<br>        mutationValue = round(np.random.uniform(-0.5, 0.5), 2)<br>    if parameterSelect == 6: #colsample<br>        mutationValue = round(np.random.uniform(-0.5, 0.5), 2)<br>  <br>    #indtroduce mutation by changing one parameter, and set to max or min if it goes out of range<br>    for idx in range(crossover.shape[0]):<br>        crossover[idx, parameterSelect] = crossover[idx, parameterSelect] + mutationValue<br>        if(crossover[idx, parameterSelect] &gt; minMaxValue[parameterSelect, 1]):<br>            crossover[idx, parameterSelect] = minMaxValue[parameterSelect, 1]<br>        if(crossover[idx, parameterSelect] &lt; minMaxValue[parameterSelect, 0]):<br>            crossover[idx, parameterSelect] = minMaxValue[parameterSelect, 0]    <br>    return crossover</pre><h3><strong>Implementation</strong></h3><p>We will implement the module discussed above to train on a dataset. The dataset is from <a href="https://archive.ics.uci.edu/ml/machine-learning-databases/musk/">UCI Machine Learning Repository</a>. It contains a set of 102 molecules, out of which 39 are identified by humans as having odor that can be used in perfumery and 69 not having the desired odor. The dataset contains 6,590 low-energy conformations of these molecules, containing 166 features. We are doing minimal prepossessing as the goal of this tutorial to understand genetic algorithm.</p><pre># Importing the libraries<br>import numpy as np<br>import pandas as pd<br>import geneticXGboost #this is the module we crated above<br>import xgboost as xgb</pre><pre>np.random.seed(723)</pre><pre># Importing the dataset<br>dataset = pd.read_csv(&#39;clean2.data&#39;, header=None)</pre><pre>X = dataset.iloc[:, 2:168].values #discard first two coloums as these are molecule&#39;s name and conformation&#39;s name</pre><pre>y = dataset.iloc[:, 168].values #extrtact last coloum as class (1 =&gt; desired odor, 0 =&gt; undesired odor)</pre><pre># Splitting the dataset into the Training set and Test set<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 97)</pre><pre># Feature Scaling<br>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><pre>#XGboost Classifier</pre><pre>#model xgboost<br>#use xgboost API now<br>xgDMatrix = xgb.DMatrix(X_train, y_train) #create Dmatrix<br>xgbDMatrixTest = xgb.DMatrix(X_test, y_test)</pre><p>We have 8 parents to start with and we select 4 fittest parents for mating. We will create 4 generations and monitor the fitness (F1-score). Half of the parents in the subsequent generation will be the fittest parents selected from the previous generation. This will allow us to keep the best fitness score at least same as the previous generation, in case the children fitness score is worse.</p><pre>numberOfParents = 8 #number of parents to start<br>numberOfParentsMating = 4 #number of parents that will mate<br>numberOfParameters = 7 #number of parameters that will be optimized<br>numberOfGenerations = 4 #number of genration that will be created</pre><pre>#define the population size</pre><pre>populationSize = (numberOfParents, numberOfParameters)</pre><pre>#initialize the population with randomly generated parameters<br>population = geneticXGboost.initilialize_poplulation(numberOfParents)</pre><pre>#define an array to store the fitness  hitory<br>fitnessHistory = np.empty([numberOfGenerations+1, numberOfParents])</pre><pre>#define an array to store the value of each parameter for each parent and generation<br>populationHistory = np.empty([(numberOfGenerations+1)*numberOfParents, numberOfParameters])</pre><pre>#insert the value of initial parameters in history<br>populationHistory[0:numberOfParents, :] = population</pre><pre>for generation in range(numberOfGenerations):<br>    print(&quot;This is number %s generation&quot; % (generation))<br>    <br>    #train the dataset and obtain fitness<br>    fitnessValue = geneticXGboost.train_population(population=population, dMatrixTrain=xgDMatrix, dMatrixtest=xgbDMatrixTest, y_test=y_test)<br>    fitnessHistory[generation, :] = fitnessValue<br>    <br>    #best score in the current iteration<br>    print(&#39;Best F1 score in the this iteration = {}&#39;.format(np.max(fitnessHistory[generation, :])))</pre><pre>#survival of the fittest - take the top parents, based on the fitness value and number of parents needed to be selected<br>    parents = geneticXGboost.new_parents_selection(population=population, fitness=fitnessValue, numParents=numberOfParentsMating)<br>    <br>    #mate these parents to create children having parameters from these parents (we are using uniform crossover)<br>    children = geneticXGboost.crossover_uniform(parents=parents, childrenSize=(populationSize[0] - parents.shape[0], numberOfParameters))<br>    <br>    #add mutation to create genetic diversity<br>    children_mutated = geneticXGboost.mutation(children, numberOfParameters)<br>    <br>    &#39;&#39;&#39;<br>    We will create new population, which will contain parents that where selected previously based on the<br>    fitness score and rest of them  will be children<br>    &#39;&#39;&#39;<br>    population[0:parents.shape[0], :] = parents #fittest parents<br>    population[parents.shape[0]:, :] = children_mutated #children<br>    <br>    populationHistory[(generation+1)*numberOfParents : (generation+1)*numberOfParents+ numberOfParents , :] = population #srore parent information</pre><p>Finally, we get the best score and associated parameters:</p><pre>#Best solution from the final iteration</pre><pre>fitness = geneticXGboost.train_population(population=population, dMatrixTrain=xgDMatrix, dMatrixtest=xgbDMatrixTest, y_test=y_test)<br>fitnessHistory[generation+1, :] = fitness</pre><pre>#index of the best solution<br>bestFitnessIndex = np.where(fitness == np.max(fitness))[0][0]</pre><pre>#Best fitness<br>print(&quot;Best fitness is =&quot;, fitness[bestFitnessIndex])</pre><pre>#Best parameters<br>print(&quot;Best parameters are:&quot;)<br>print(&#39;learning_rate&#39;, population[bestFitnessIndex][0])<br>print(&#39;n_estimators&#39;, population[bestFitnessIndex][1])<br>print(&#39;max_depth&#39;, int(population[bestFitnessIndex][2])) <br>print(&#39;min_child_weight&#39;, population[bestFitnessIndex][3])<br>print(&#39;gamma&#39;, population[bestFitnessIndex][4])<br>print(&#39;subsample&#39;, population[bestFitnessIndex][5])<br>print(&#39;colsample_bytree&#39;, population[bestFitnessIndex][6])</pre><p>Now let us visualize the change in fitness in the population with each generation (figure below). While we already started with high F1-score (~0.98), in two of the parents, in the randomly generated initial population, we were able to improve it further in the final generation. The lowest F1-score was 0.9143 for one parent in the initial population and the best score was 0.9947 for one of the parents in the final generation. This demonstrate that we can improve the performance metric in XGBoost, by simple implementation of genetic algorithm. The final code can be found at <a href="https://github.com/mjain72/Hyperparameter-tuning-in-XGBoost-using-genetic-algorithm">my github account</a>. It also contains code that will allow you to observe the change in various parameters, with each generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*WcmT4t8zxs5S6teMGSoZpg.png" /><figcaption>(Image by author)</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17bd2e581b17" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/hyperparameter-tuning-in-xgboost-using-genetic-algorithm-17bd2e581b17">Hyperparameter tuning in XGBoost using genetic algorithm</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>