<?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 Reinis Cimurs on Medium]]></title>
        <description><![CDATA[Stories by Reinis Cimurs on Medium]]></description>
        <link>https://medium.com/@reinis_86651?source=rss-51bb2de1006a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pWxc2-VUSKmZDFtlKLY6gA.jpeg</url>
            <title>Stories by Reinis Cimurs on Medium</title>
            <link>https://medium.com/@reinis_86651?source=rss-51bb2de1006a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:37:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@reinis_86651/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[Learning Graphs for MARL “On-The-Fly”]]></title>
            <link>https://medium.com/@reinis_86651/learning-graphs-for-marl-on-the-fly-9fe44c356808?source=rss-51bb2de1006a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fe44c356808</guid>
            <category><![CDATA[graph-neural-networks]]></category>
            <category><![CDATA[marl]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[lrs]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Reinis Cimurs]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 18:36:47 GMT</pubDate>
            <atom:updated>2026-03-30T18:36:47.512Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I had the pleasure of attending the European Robotics Forum 2026 in Stavanger and sharing our scientific work on graph creation for MARL execution under the title <strong>“In-Graph Softmax for Hard-Soft Attention in Multi-Agent Reinforcement Learning”</strong>. The forum is a great place to connect and present your ideas, but the scientific track does not allow for a lot of room to explain your contributions in detail and give all the intricacies of training such models. Therefore, I aim to add additional context here for those who may be inclined to reproduce our work.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSGl7sil_dpo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSGl7sil_dpo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSGl7sil_dpo%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff1874d1a0fc76bb9191dd38260beb14/href">https://medium.com/media/ff1874d1a0fc76bb9191dd38260beb14/href</a></iframe><h3>Motivation</h3><p>The motivation of this work is fairly straightforward — we want to train a reinforcement learning agent that knows about other agents in the scene, but we cannot be sure how many agents there are and how much information they can provide. So, we want to create a neural network that can figure out which agents it can/should communicate with and how much they care about this. For this, we implement a 2-stage graph creation mechanism with hard and soft attention. The hard attention first decides which agents will form a graph, then soft attention weighs the connections, how much they should contribute to the current state of the agent (we do this with a <strong>softmax</strong> <strong>in</strong> the created <strong>graph</strong>). Finally, the updated state information is decoded into an action for each individual robot. For more background, theory and problem statements, see our paper (To be published soon). But here, I want to focus on the code implementation and training procedures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qvi_BWasS1Y8OlN7Lgqv5w.png" /><figcaption>In-Graph Softmax to action pipeline in MARL</figcaption></figure><h3>Code</h3><p>The code for training is freely available in this <a href="https://github.com/reiniscimurs/DRL-robot-navigation-IR-SIM">repository</a>. The repository itself consists of multiple algorithm implementations for DRL robot navigation in a simple Python simulator <a href="https://github.com/hanruihua/ir-sim">IR-SIM</a>, which is a great tool for experimentation, learning and algorithm prototyping. But we will only focus on the MARL algorithms. For dependency control, we use Poetry, so the repository installation is very simple.</p><p>First, install Poetry (if needed) with:</p><pre>pip install poetry</pre><p>Then, download the repo:</p><pre>git clone https://github.com/reiniscimurs/DRL-robot-navigation.git</pre><p>Then navigate to the repo directory and simply execute:</p><pre>poetry install</pre><p>This will automatically create a virtual environment and install all the required dependencies with compatible versions.</p><p>You can start the training of a simple model right away with:</p><pre>poetry run python robot_nav/marl_train.py</pre><p>The files in the code that we will be covering here are:</p><pre>robot_nav/models/MARL/Attention/iga.py<br>robot_nav/models/MARL/marlTD3/marlTD3.py<br>robot_nav/marl_train.py</pre><p>The main thing we will be covering is the implementation of the “Attention” class in the ‘iga.py’ file</p><h3><strong>Hard Attention</strong></h3><p>The point of hard attention is to establish which robots have a connection with each other. The output of it should be a “hard” label (binary decision 1 or 0) defining if there is or isn’t a connection. For this, we have the implementation in the ‘iga.py’ file.</p><p>The forward pass of the Attention class expects an input of:</p><pre>embedding (B, N, D)</pre><p>Where B is the batch size, N is the number of agents and D is the dimensions of input features from the scene observation. Now we unpack the structure of the input. Instead of treating the embedding as a monolithic vector, the code slices it into meaningful parts:</p><pre>embed = embedding[:, :, 4:9]<br>position = embedding[:, :, :2]<br>heading = embedding[:, :, 2:4]<br>action = embedding[:, :, 7:9]<br>goal = embedding[:, :, -2:]</pre><p>Here we have position → where the agent is in the scene (global coordinates), heading → which direction it’s facing (cos, sin), action → its current (linear and angular) action, goal → where the goal is, and embed → as agent features. We encode agent features for all the robots in the scene:</p><pre>agent_embed = self.encode_agent_features(embed)<br>agent_embed = agent_embed.view(batch_size, n_agents, self.embedding_dim)</pre><p>This gives us an embedding of the agent (robot) internal features.</p><p>Now the interesting part begins: building pairwise relationships and calculating the edge information. We will use this edge information as features to decide on a connection between agents. We construct all pairs (i, j) using broadcasting:</p><pre>pos_i = position.unsqueeze(2)  # (B, N, 1, 2)<br>pos_j = position.unsqueeze(1)  # (B, 1, N, 2)<br>rel_vec = pos_j - pos_i        # (B, N, N, 2)</pre><p>This produces a matrix where each entry [i, j] is the vector from the agent i to agent j. This is a pairwise connectivity matrix. Here, we also calculated the relative position vector rel_vec. From this, we calculate the distance and normalize it with a hardcoded “max distance” value. We actually do not know the max distance, but a good guess is good enough for most applications to get the values between 0 and approximately 1.</p><pre>rel_dist = torch.linalg.vector_norm(rel_vec, dim=-1, keepdim=True) / 12</pre><p>The next step is to calculate the relative angles:</p><pre>dx, dy = rel_vec[..., 0], rel_vec[..., 1]<br>angle = torch.atan2(dy, dx) - torch.atan2(heading_i[..., 1], heading_i[..., 0])<br>angle = (angle + np.pi) % (2 * np.pi) - np.pi</pre><p>Instead of keeping the raw angle, it converts it into sine and cosine, as this avoids discontinuities around π and -π:</p><pre>rel_angle_sin = torch.sin(angle)<br>rel_angle_cos = torch.cos(angle)</pre><p>We also take the other agents&#39; heading:</p><pre>heading_j_cos = heading_j[..., 0]<br>heading_j_sin = heading_j[..., 1]</pre><p>And expand actions so every pair (i, j) includes agent j’s action:</p><pre>action.unsqueeze(1).expand(-1, n_agents, -1, -1)</pre><p>So the final edge feature for every pair (i, j) is described by the distance to j , j relative position toi , what direction j is facing, the current action of j . We concatenate all these features together to obtain edge_features:</p><pre>edge_features = torch.cat(<br>            [<br>                rel_dist,  # (B, N, N, 1)<br>                rel_angle_cos.unsqueeze(-1),  # (B, N, N, 1)<br>                rel_angle_sin.unsqueeze(-1),  # (B, N, N, 1)<br>                heading_j_cos.unsqueeze(-1),  # (B, N, N, 1)<br>                heading_j_sin.unsqueeze(-1),  # (B, N, N, 1)<br>                action.unsqueeze(1).expand(-1, n_agents, -1, -1),  # (B, N, N, 2)<br>            ],<br>            dim=-1,<br>        )</pre><p>Now comes a subtle but important step. The embedding of the agent i is repeated for all j:</p><pre>h_i = agent_embed.unsqueeze(2)             # (B, N, 1, D)<br>h_i_expanded = h_i.expand(-1, -1, n_agents, -1)</pre><p>Then everything is flattened:</p><pre>h_i_flat = h_i_expanded.reshape(batch_size * n_agents, n_agents, self.embedding_dim)<br>edge_flat = edge_features.reshape(batch_size * n_agents, n_agents, -1)</pre><p>Now we combine the agent features with the pairwise edge features:</p><pre>hard_input = torch.cat([h_i_flat, edge_flat], dim=-1)</pre><p>Now we have created all the information to decide if a connection needs to be established based on agent features and relative edge features to all other agents in the scene. We figure this out by passing this information through a neural network:</p><pre>h_hard = self.hard_mlp(hard_input)<br>hard_logits = self.hard_encoding(h_hard)</pre><p>The output for hard_logits is 2 scalar numbers. At this point, for each (i, j)we get two scores:</p><ul><li>score for “ignore”</li><li>score for “attend”</li></ul><p>The next line is where the decision is made for a binary class:</p><pre>hard_weights = F.gumbel_softmax(hard_logits, hard=False, tau=0.2, dim=-1)[..., 1]</pre><p>Let’s say for a specific pair (i, j), the logits are [2.0, 0.5]. After Gumbel-Softmax, this might turn into something like [0.9, 0.1], meaning, 90% to ignore and 10% to keep the connection. So then we take only the second value ([..., 1]), which corresponds to “attend.”</p><p>Gumbel-Softmax operation behaves like a soft sampling process during training, but it approximates a discrete decision. The temperature parameter (tau=0.2) makes the distribution sharp, pushing the outputs closer to 0 or 1. Over time, the model effectively learns to switch interactions on or off. It is important to use Gumbel-Softmax because it allows for differentiability while sampling discrete decisions.</p><h3>Soft Attention</h3><p>The hard attention gave us the information with which agents the connection should be kept. Now, with soft attention, we want to figure out how much attention we should actually pay to each kept connection. Instead of considering all pairs (i, j), we now only deal with the subset where the hard mask is active and calculate the soft attention only over such limited graph. Effectively only performing attention <strong>softmax in-graph</strong>. For this, we will use a cross-attention mechanism.</p><p>First, we initialize a few containers:</p><pre>attention_outputs = []<br>entropy_list = []<br>combined_w = []</pre><p>These will store the attended embeddings per batch, the entropy of attention distributions, and the reconstructed attention matrices.</p><p>Since we have established through hard attention that a connection can be established between the agents, we can add new information features as passed information. We add an additional feature specifically for soft attention: <strong>goal-relative features</strong>.</p><pre>goal_rel_dist = torch.linalg.vector_norm(goal_rel_vec, dim=-1, keepdim=True)</pre><p>This gives, for each pair (i, j), the distance between the agenti and agent j&#39;s goal.</p><p>Then angles are computed:</p><pre>goal_angle_global = torch.atan2(goal_rel_vec[..., 1], goal_rel_vec[..., 0])<br>heading_angle = torch.atan2(heading_i[..., 1], heading_i[..., 0])<br>goal_rel_angle = goal_angle_global - heading_angle<br>goal_rel_angle = (goal_rel_angle + np.pi) % (2 * np.pi) - np.pi</pre><p>Again, the angle is converted into sine and cosine:</p><pre>goal_rel_angle_cos = torch.cos(goal_rel_angle).unsqueeze(-1)<br>goal_rel_angle_sin = torch.sin(goal_rel_angle).unsqueeze(-1)</pre><p>And everything is concatenated to obtain goal polar feature:</p><pre>goal_polar = torch.cat(<br>    [goal_rel_dist, goal_rel_angle_cos, goal_rel_angle_sin], dim=-1<br>)</pre><p>So now each pair (i, j) has additional information about where is agent j actually going.</p><p>These new features are appended to the earlier edge features:</p><pre>soft_edge_features = torch.cat([edge_features, goal_polar], dim=-1)</pre><p>Now we have to loop over the batch:</p><pre>for b in range(batch_size):</pre><p>This is done because each environment can have a different interaction graph depending on the hard attention mask.</p><p>Inside the loop, we extract per-scenario data:</p><pre>node_feats = agent_embed[b]   # [n, emb_dim]<br>soft_feats = soft_edge_features[b]  # [n, n, edge_dim]<br>hard_mask = hard_weights[b]   # [n, n]</pre><p>Afterwards, we need to build a sparse graph:</p><pre>for i in range(n_agents):<br>    for j in range(n_agents):<br>        if i != j and hard_mask[i, j] &gt; 0.5:<br>            edge_index_list.append([j, i])<br>            edge_attr_list.append(soft_feats[i, j])</pre><p>This creates an individual graph for each agent with directional edges that bring relational information from selected agents j to agent i.</p><p>Once the lists are built, they are converted into tensors:</p><pre>edge_index = torch.tensor(edge_index_list).t()  # [2, num_edges]<br>edge_attr = torch.stack(edge_attr_list, dim=0)</pre><p>If no edges exist, empty tensors are created instead. This avoids runtime errors.</p><p>To facilitate the message passing to the agent (query) from the edge information (key and value pair) we use MessagePassing implementation from torch_geometric which is our message_graph. We pass the graph into this message passing module:</p><pre>attn_out, attn_weights = self.message_graph(<br>    node_feats, edge_index, edge_attr<br>)</pre><p>Immediately after, entropy is computed:</p><pre>batch_entropy = entropy_from_attention(<br>    attn_weights, edge_index[1], num_nodes=n_agents<br>)</pre><p>This measures how “spread out” the attention is. We will use this later to force the model to explore different kinds of connections in the training phase (similarly to how entropy is used in SAC algorithm).</p><p>Next, attention weights are mapped back into a dense matrix:</p><pre>combined_weights = torch.zeros((n_agents, n_agents))<br>for idx in range(edge_index.shape[1]):<br>    j = edge_index[0, idx].item()<br>    i = edge_index[1, idx].item()<br>    combined_weights[i, j] = attn_weights[idx]</pre><p>So if attn_weights = [0.7, 0.2, 0.1], this reconstructs to something like:</p><pre>[[0.0, 0.7, 0.0],<br> [0.2, 0.0, 0.1],<br> [0.0, 0.0, 0.0]]</pre><p>This is useful for debugging or visualization in the simulator.</p><p>After processing all batches, the results are stacked:</p><pre>attn_stack = torch.stack(attn_outputs, dim=0).reshape(batch_size * n_agents, -1)<br>self_embed = agent_embed.reshape(batch_size * n_agents, -1)</pre><p>So now we have original embeddings and attention-aggregated embeddings. These are then concatenated into:</p><pre>concat_embed = torch.cat([self_embed, attn_stack], dim=-1)</pre><p>Finally, this goes through another MLP to obtain a new agent state representation that combines not only its internal features but also weighted information of the connected agents:</p><pre>x = F.leaky_relu(self.decode_1(concat_embed))<br>att_embedding = F.leaky_relu(self.decode_2(x))</pre><p>Putting it all together, the soft attention implementation does the following in sequence:</p><ul><li>add goal-relative information</li><li>filter interactions using the hard attention mask</li><li>construct a sparse graph of agent edges</li><li>perform message passing with learned attention weights</li><li>aggregate neighbor information into updated embeddings</li><li>combine original and attended features into a final state representation</li></ul><h3>Attention as Encoder Module</h3><p>From the in-graph softmax attention mechanism, we get a single-dimensional output combining the agent features and weighted incoming edge features from other agents. Since the input is raw features from the scene and the output is a latent space representation of this information, we can this attention mechanism as an encoder module. By doing so, we can attach it to any algorithm or neural network that takes in some state representation and decodes it into an action. It may be some hardcoded action module, or a DRL algorithm, like TD3, which we choose to use in this implementation.</p><p>In practice, it works like this: take in all of the scene information → encode each agent in the scene with our attention mechanism → decode to action for each agent (at this point, we can just treat the graph as a batch of agent states) with a TD3 network.</p><p>In code (robot_nav/models/MARL/marlTD3/marlTD3.py) it means that we create an attention encoder for both the actor and critic networks:</p><pre>self.attention = Attention(embedding_dim)</pre><p>And the first thing we do, before we start calculating for action (in actor) or Q-value (in critic) we encode the agent information:</p><pre> (embedding_with_attention, hard_logits, unnorm_rel_dist, mean_entropy, hard_weights, _) = self.attention(embedding)</pre><p>The rest of the decoder works exactly the same as in the standard TD3 algorithm, just now our input is a batch of encoded agents in embedding_with_attention .</p><h3>Losses</h3><p>As mentioned in the paper, we use a couple of more losses to help train the graph creation better. If we were to use just the reward from the environment, we would soon find mode collapse in graph creation. That is, all the agents would either be fully connected or disconnected and weights would be fairly similar. This is due to the training being rather unstable in the beginning and no explicit information for graph performance can be extracted from it, the graph would need to train implicitly. So we want to add the explicit information.</p><p>In our approach, we specify a BCE loss for hard attention. I know, I know, this means that we need a target label and where would we get that in a somewhat dubious reinforcement learning task? Here, we will just specify the distance at which we expect there to be a connection between agents and after which we expect the agents to be disconnected using our best judgment.</p><p>As an example from the critic network:</p><pre>(current_Q1, current_Q2, mean_entropy, hard_logits, unnorm_rel_dist, hard_weights) = self.critic(state, action)<br>targets = (unnorm_rel_dist.flatten() &lt; connection_proximity_threshold).float()<br>flat_logits = hard_logits.flatten()<br>bce_loss = F.binary_cross_entropy_with_logits(flat_logits, targets)</pre><p>So we control the initial hard attention with connection_proximity_threshold</p><p>But this will only allow us to learn the distribution for the hard attention. What about the soft attention? How can we make sure that the weights are meaningful and that different weight structures are explored? As mentioned before, SAC already introduces entropy as a measurement of how much exploration is being done. So we also borrow the same method to force the model to explore different values in the soft attention. Luckily, we already calculated the mean entropy in the Attention module so we can simply use the mean_entropy value returned from there.</p><p>Putting it all together, we get our final loss for the end-to-end training:</p><pre>total_loss = critic_loss - entropy_weight * mean_entropy + bce_weight * bce_loss</pre><p>The same loss setup repeats for the actor network loss.</p><h3>Training</h3><p>Now comes the most important part of why this write-up is necessary. In previous sections we introduced the idea and the setup of how the attention mechanism encodes the information. However, we do not just set up the weights of each loss element and just let it train. In fact, we train the model in 2 distinct phases in a curriculum learning manner:</p><p><strong>Phase 1<br></strong>First, we aim to train a navigation policy that learns to navigate towards the given goal while trying to avoid other agents in the scene. To enable this, we form a reward function that highly evaluates reaching a goal and gives a positive reward to approaching a goal with increased velocity. We set a higher bce_weightvalue to encourage connecting and disconnecting edges in the hard-attention stage.</p><p><strong>Phase 2</strong><br>Once the policy has learned to navigate to the goal, we aim to learn a more intelligent navigation policy by relaxing the reward structure. In phase 2, we reduce the goal reward and remove the positive reward of the linear velocity to give more freedom for the policy to learn more intelligent obstacle avoidance. We also relax the bce_weight coefficient to allow the model to learn the connections in the hard-attention stage based mainly on the policy performance, instead of predefined target labels. The distance penalty to other robots is increased to increase the collision cost.</p><p>You can see a full list of coefficients and their values for each phase here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*31C8EMQMaBHuEHo2Zs7m7g.png" /><figcaption>Coefficients and their value at each training phase</figcaption></figure><p>where the coefficients are as follows (in order):</p><ul><li>Decoder loss (base critic and actor losses)</li><li>BCE loss for hard attention</li><li>Entropy loss for soft attention</li><li>Reward for reaching the goal</li><li>Collision reward</li><li>Linear velocity reward</li><li>Angular velocity reward</li><li>Distance to another robot reward</li><li>Distance to goal reward</li></ul><p>In mathematical terms, the final end-to-end loss is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*3aSIuS6izL-DLj4t-ep7Ng.png" /></figure><p>Where the first term is the decoder loss obtained directly from the reward function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*CJhcnU_T5mFetey2B7cHtw.png" /></figure><p>where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*-hxFUdwFwn97ZpEG8ObjtA.png" /></figure><p>Here, goal reward is applied if distance to goal is below threshold, collision reward is applied if distance to another agent is below the 2x radius of the robot and the immediate timestep reward r_t is an expression that combines positive reward for high linear velocity, negative reward for angular velocities as well as checking the distance to any robot (with max mumber of robots = M) and the goal.</p><p>I hope this helps understand our approach better and recreate the performance that we observe. There are probably still many intricacies that could be explained but that is what the code is for. While commented, it is not entirely clean so please bare with some minor unused variables here and there. Hope this helps and thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fe44c356808" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using TurtleBot in Deep Reinforcement Learning]]></title>
            <link>https://medium.com/@reinis_86651/using-turtlebot-in-deep-reinforcement-learning-4749946e1c15?source=rss-51bb2de1006a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4749946e1c15</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[mobile-robot]]></category>
            <category><![CDATA[roses]]></category>
            <category><![CDATA[simulator]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Reinis Cimurs]]></dc:creator>
            <pubDate>Thu, 19 Jan 2023 23:12:11 GMT</pubDate>
            <atom:updated>2023-01-19T23:12:11.986Z</atom:updated>
            <content:encoded><![CDATA[<p>In a previous set of tutorial articles (<a href="https://medium.com/@reinis_86651/deep-reinforcement-learning-in-mobile-robot-navigation-tutorial-part1-installation-d62715722303">Part 1</a> of the tutorial), I explored an implementation of TD3 network architecture in combination with ROS simulator for learning how to navigate a mobile robot from direct sensor inputs. While the network architecture and the simulator are (in theory) robot model agnostic, it did use a specific Pioneer 3DX mobile robot platform. There are certain implications that come with using a specific robot model. Mainly, the inferred kinematics. The learned actions are dependent on the expectation of how will they be executed. There is a learned understanding, that making a certain motion will result in a specific state of the environment. This, of course, depends on such parameters as the robot’s length, width, wheel diameter, wheel location, etc. That means that, if you learn a motion policy with one type of robot model, it is not trivial to transfer this policy to a different type of robot with different sizes and wheel diameters. While coefficients and strange mathematical equations can be found to do this, it is much better and simpler to just learn the motion policy with the same robot platform in simulation as will be used in real life. Unfortunately, Pioneer 3DX is already quite an old mobile robot platform and is not popular with many researchers anymore. (The can of worms that is getting ROSARIA to work is not helping either). Therefore, probably one of the most frequent questions I get asked is “<em>How do I use TurtleBot instead?</em>”. So here I will explain how to use TurtleBot model in learning mobile robot navigation policy through our Deep Reinforcement Learning pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*dSZxgMuhRELVlFI37LdZLw.png" /><figcaption>Turtlebot3 Burger model in simulation with Velodyne Puck sensor</figcaption></figure><p>Luckily, not a lot of changes have to be made when we want to use a different robot platform. So, regarding the programmatic implementation of the network architecture and how it works together with ROS simulator, feel free to refer to the aforementioned tutorial — <a href="https://medium.com/@reinis_86651/deep-reinforcement-learning-in-mobile-robot-navigation-tutorial-part1-installation-d62715722303">Part 1</a>. Almost the only thing that will change is the call to the robot model when launching the simulator. Here, to describe the implementation, I will use this GitHub repository and specifically the Noetic-Turtlebot branch:</p><p><a href="https://github.com/reiniscimurs/DRL-robot-navigation/tree/Noetic-Turtlebot">GitHub - reiniscimurs/DRL-robot-navigation at Noetic-Turtlebot</a></p><p>For the installation guide, please follow the commands in the Installation section of the repository.</p><p>The nice people from ROBOTIS have provided the turtlebot 3 models for ROS on their <a href="https://github.com/ROBOTIS-GIT/turtlebot3">GitHub</a> that we will be using in our implementation.</p><p><strong>Calling The Robot Model Launch</strong></p><p>After successfully cloning and compiling the repository, we should have all our required files set up, including a directory consisting of select folders and files from the original Turtlebot 3 repository.</p><p>When starting the training in ROS simulator, the first thing the program does is execute the launch file. The launch file is located in:</p><pre>DRL-robot-navigation/TD3/assets/</pre><p>in file multi_robot_scenario.launch</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fdcb952a52371616b08b21ddd68ab66/href">https://medium.com/media/5fdcb952a52371616b08b21ddd68ab66/href</a></iframe><p>This file takes care of launching the gazebo simulator and its world in line 7. In line 18 we launch the Rviz node with the specified configuration. So in between, starting from line 11, is where we launch our robot model. With the &lt;include&gt; tag, we specify additional launch fines that we want to launch when launching our training. In this case, we are specifying our turtlebot3 model launch file. We have set a couple of arguments, that we might want to specify when launching the selected model.</p><pre>  &lt;arg name=&quot;model&quot; value=&quot;waffle&quot; /&gt;</pre><p>The turtlebot3 repository has provided implementation for 3 types of turtlebot robots. They are — burger, waffle, and waffle_pi. To specify, which robot model we want to use in our simulation, we can simply set the argument with the name “model” to a value with the type of robot we want to use.</p><pre>&lt;arg name=&quot;multi_robot_name&quot; value=&quot;r1&quot;/&gt;</pre><p>The “multi_robot_name” argument with set the name used for this specific robot instance.</p><pre>&lt;arg name=&quot;robot_position&quot; value=&quot;-x 0.0 -y 0.0 -z 0.01 -R 0 -P 0 -Y +0.0&quot; /&gt;</pre><p>“robot_position” will set the location where the robot will be spawned for the first time when starting the simulator.</p><p><strong>Launching the Robot Model</strong></p><p>From the path in the call to robot model launch, we see that we are calling a turtlebot3_model.launch file, located in:</p><pre>DRL-robot-navigation/catkin_ws/src/turtlebot3/turtlebot3_bringup/launch/</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99924ebd728c97f3a4036ab934dc1b1d/href">https://medium.com/media/99924ebd728c97f3a4036ab934dc1b1d/href</a></iframe><p>First, we have specified the arguments and their default values that we would need to launch the file (we set their real values in the multi_robot_scenario.launch file).</p><p>Then we set the parameter of the robot description that we will actually use in the simulator in line 7. We specify the path to the xacro file of the robot description. Notice that we are using the file:</p><pre>turtlebot3_$(arg model).urdf.xacro</pre><p>Here, the <em>$(arg model) </em>is an argument that we had set in the multi_robot_scenario.launch file. If we set the robot model to waffle, our robot description will call a file with the name:</p><pre>turtlebot3_waffle.urdf.xacro</pre><p>These robot description parameters are then passed into the urdf spawner node in line 10, which will take care of adding our model to the simulator. Afterward, we start the robot state publisher and robot joint publisher nodes that will take care of keeping track of different connections and joint transforms of our robot.</p><p><strong>Robot Description</strong></p><p>The robot description file (if calling a waffle type of robot) is located here:</p><pre>DRL-robot-navigation/catkin_ws/src/turtlebot3/turtlebot3_description/urdf/turtlebot3_waffle.urdf.xacro</pre><p>This file specifies the robot construction and adds the sensors to the robot model. The DRL method used for obtaining motion policy is based on sensor data from Velodyne Puck 16-channel LiDAR. This is not originally included with the turtlebot robot in the original repository. Luckily, adding this sensor is very easy. Simply include the sensor in this xacro file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5bc51cc8dfa27eab407428fb0b10408/href">https://medium.com/media/e5bc51cc8dfa27eab407428fb0b10408/href</a></iframe><p>The &lt;origin&gt; tag will specify the location of the sensor in relation to the parent link (in this case “base_link”). Here, we are placing the sensor at a location where a laser scan was located in the original turtlebot repository. That means that the height of the velodyne puck is different than on our original Pioneer 3DX model. This brings us to the only code change. When obtaining data from the Velodyne LiDAR, we filtered out points that are 20 cm lower than the plane of the sensor. By placing the sensor at a different height, we also need to adjust this value. Simply, set the appropriate height value in:</p><pre>DRL-robot-navigation/TD3/velodyne_env.py</pre><p>By setting the filtering parameter according to the height of the sensor on your robot model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6625566d1e2440b9523c917c4f451266/href">https://medium.com/media/6625566d1e2440b9523c917c4f451266/href</a></iframe><p>And that is it! This should allow you to use and modify the turtlebot robot model call stack. If there are any questions, do not hesitate to open an issue in the repository.</p><p><strong>Quick Note</strong></p><p>For the mobile robot platform to work in ROS Noetic, I also slightly modified the gazebo files (waffle robot file for reference):</p><pre>DRL-robot-navigation/catkin_ws/src/turtlebot3/turtlebot3_description/urdf/turtlebot3_waffle.gazebo.xacro</pre><p>Changes were made in the differential drive plugin:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4782de75aac65873447666a898c5b80c/href">https://medium.com/media/4782de75aac65873447666a898c5b80c/href</a></iframe><p>The following tags were inserted into the plugin:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea4d3efe10a76176fde355bd30bb1808/href">https://medium.com/media/ea4d3efe10a76176fde355bd30bb1808/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4749946e1c15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Reinforcement Learning in Mobile Robot Navigation Tutorial — Part5: Some Extra Stuff]]></title>
            <link>https://medium.com/@reinis_86651/deep-reinforcement-learning-in-mobile-robot-navigation-tutorial-part5-some-extra-stuff-b744852345ac?source=rss-51bb2de1006a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b744852345ac</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[robot-navigation]]></category>
            <category><![CDATA[roses]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[mobile-robot]]></category>
            <dc:creator><![CDATA[Reinis Cimurs]]></dc:creator>
            <pubDate>Sun, 06 Nov 2022 14:37:55 GMT</pubDate>
            <atom:updated>2022-11-06T14:38:45.408Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Reinforcement Learning in Mobile Robot Navigation Tutorial — Part5: Some Extra Stuff</h3><p>In this series of articles, I aimed to go over the python code parts of the repository, explain the code, and give some insights so that it would be easier for others to use, change, refactor, repurpose or disregard it. Mainly, I wished to go over the code implementation of the TD3 neural network and how it connects to the Gazebo simulator. I feel that the previous 4 parts should be sufficient. But there are also some other extra bits and pieces of information, that might help to use the repository better.</p><p><strong>Increase the Speed of the Simulation</strong></p><p>The way that the neural network training is conducted follows these steps:</p><pre>Collect motion samples -&gt; Train policy on samples -&gt; Update Policy</pre><p>The training and updating speed will depend on the capabilities of your hardware, but generally, it should not take more than a second. But what about the collection of samples in the simulation? Each step is propagated with 0.1 second rate and we can have maximum 500 steps (with default parameters) in our implementation. That means a single episode can run for more than 50 seconds. It is quite evident that in order for us to speed up the whole training process, speeding up this part would bring the most benefit. Gazebo simulator innately does not support running simulations faster than real time, but there is a way to ‘overclock’ it.</p><p>The simulation can be sped up by changing the &lt;real_time_update_rate&gt; value in your world file. In our repository, you will find the world file in the directory:</p><pre>DRL-robot-navigation/catkin_ws/src/multi_robot_scenario/launch</pre><p>The (default) world file is:</p><pre>TD3.world</pre><p>Here you can find the &lt;real_time_update_rate&gt; in the <em>physics</em> part of the file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a78d1f41d00c608109e28e5e75994aa/href">https://medium.com/media/6a78d1f41d00c608109e28e5e75994aa/href</a></iframe><p>The update rate is given in milliseconds and by default 1 second in real time is executed as 1000 ms in the simulation. We can increase this number to execute the simulation faster. For instance, (by changing it to 2000) 1 second in real-time will be executed as 2000 ms in simulation.</p><p><strong>Note</strong>: Use this method at your own discretion. Using too high of a frequency often causes problems in the simulation, as sensors and other plugins just cannot keep up with it. So try it out, and see what frequencies do not cause issues in your implementation.</p><p><strong>Starting the Gazebo Simulator Visualization</strong></p><p>If the installation was carried out successfully, you should be able to launch the training and see a Rviz window pop up automatically. You will notice, however, the Gazebo simulator does not open. The Gazebo simulator uses up a lot of GPU resources and (depending on how powerful your machine is) may even crash the simulation. So, by default, the simulator GUI is not launched. The Rviz is usually enough to evaluate the progress of the training, but if you wish to launch the Gazebo simulator GUI, there are 2 ways to do it.</p><p><strong><em>1.) Run during runtime:</em></strong></p><p>Launch the training as usual. This will only launch the Rviz as previously explained. Then open a new terminal, and execute the command:</p><pre>gzclient</pre><p>This will open the GUI of the currently running Gazebo simulation.</p><p><strong><em>2.) Launch GUI when starting the training</em></strong></p><p>You can automatically start the Gazebo GUI, by changing the default behavior, when launching the training. Open the file <em>empty_world.launch</em> in the directory:</p><pre>DRL-robot-navigation/catkin_ws/src/multi_robot_scenario/launch</pre><p>And change the line:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9aa9c0b9a3d3f8c0a3c2aad2bac0f369/href">https://medium.com/media/9aa9c0b9a3d3f8c0a3c2aad2bac0f369/href</a></iframe><p>to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c9ed401843d6531a0d90e0fa026e00f/href">https://medium.com/media/4c9ed401843d6531a0d90e0fa026e00f/href</a></iframe><p><strong>Changing Velodyne Sensor Settings</strong></p><p>As you have noticed by now, we use a simulated Velodyne Puck 16-channel LiDAR to record the environment around the robot. Our basic implementation assumes that the laser sensor only has a 180-degree FOV in front of the robot. That means that the robot can only move forward, as it does not see anything behind itself. If a view behind the robot is necessary, the default Velodyne sensor settings should be changed. The configuration file of the Velodyne Puck, you will find here:</p><pre>DRL-robot-navigation/catkin_ws/src/velodyne_simulator/velodyne_description/urdf</pre><p>The changeable parameters can be found at the top of the VLP-16.urdf.xacro file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dede672e0f86d3314f76cb20a898339/href">https://medium.com/media/9dede672e0f86d3314f76cb20a898339/href</a></iframe><p>We set these parameters when we call the plugin in the robot setup. Robot plugin setup is available in:</p><pre>DRL-robot-navigation/catkin_ws/src/multi_robot_scenario/xacro/p3dx</pre><p>in file:</p><pre>pioneer3dx.xacro</pre><p>The parameters are set in the Velodyne section:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27198ddbb99938e170d0380a2fd49466/href">https://medium.com/media/27198ddbb99938e170d0380a2fd49466/href</a></iframe><p>Here, we can set the number of samples we want to receive, the frequency of observations as well as FOV (among other things). The FOV is set in the range from minimum to maximum value, from left to right with respect to the heading of the robot (if you do not change the “rpy” values in origin). These values are set in radians.</p><p>Another thing to note is that we can set the origin. This will specify the location of the sensor on the robot and is described in meters with respect to the robot&#39;s origin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b744852345ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Reinforcement Learning in Mobile Robot Navigation Tutorial — Part4: Environment]]></title>
            <link>https://medium.com/@reinis_86651/deep-reinforcement-learning-in-mobile-robot-navigation-tutorial-part4-environment-7e4bc672f590?source=rss-51bb2de1006a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e4bc672f590</guid>
            <category><![CDATA[roses]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Reinis Cimurs]]></dc:creator>
            <pubDate>Wed, 19 Oct 2022 20:40:26 GMT</pubDate>
            <atom:updated>2022-11-17T19:01:04.863Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Reinforcement Learning in Mobile Robot Navigation Tutorial — Part4: Environment</h3><p>In the previous parts (<a href="https://medium.com/@reinis_86651/deep-reinforcement-learning-in-mobile-robot-navigation-tutorial-part1-installation-d62715722303">Part 1</a>, <a href="https://medium.com/@reinis_86651/deep-reinforcement-learning-in-mobile-robot-navigation-tutorial-part2-network-82aea28b0e0f">Part 2</a>, and <a href="https://medium.com/@reinis_86651/deep-reinforcement-learning-in-mobile-robot-navigation-tutorial-part3-training-13b2875c7b51">Part 3</a>) of this tutorial, we have installed and trained our neural network to move a mobile robot platform. We observe the environment and then take action that will eventually lead the robot to our goal. But until now the environment has been something rather abstract. We specified that actions are taken in the ROS gazebo simulator, but how does this interaction actually happen? And how can we control it? To find the answer to this, we will be looking into the environment code in:</p><pre>velodyne_env.py</pre><p><strong>Class Initialization</strong></p><p>As mentioned, we will be using the ROS Gazebo simulator as the backbone, to execute the actions with the robot and collect the environment observations. For this, we will create a python class, to facilitate this exchange between the neural network code and the simulator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f781c8631b1b11a254a38aea34ca7518/href">https://medium.com/media/f781c8631b1b11a254a38aea34ca7518/href</a></iframe><p>First, we will initialize our class. This will set up and automatically launch our simulator with the described settings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ab249b7dff00f71ab4edf14845a15c6/href">https://medium.com/media/0ab249b7dff00f71ab4edf14845a15c6/href</a></iframe><p>As input parameters, the initialization function takes the name of the “launchfile”. A <em>launchfile</em> is a ROS file, that describes the launching parameters of the simulations and is located in:</p><pre>TD3/assets</pre><p>In our example in Part 3, we passed in the “multi_robot_scenario.launch” file. The other parameter we pass in is the environment_dim value that we specified in our training file. Recall, that it is the number of laser readings that we want to describe the surrounding environment with (in our case, 20 readings). During the initialization, we set up the initial class variables. We set up the starting odometry information in X and Y coordinates. Then we also set up the placeholder for goal X and Y coordinates. The <em>self.upper </em>and <em>self.lower </em>variables, designate the maximum and minimum values of how far the random goal location can be placed from the robot (we will touch upon this later). Afterward, we create <em>self.velodyne_state</em> variable that will store our state observations. Initially, we fill it with values of 10. We choose 10, as that will be the maximum distance in meters that we specify for the laser readings. Create a placeholder for the last received odometry data. Then, create placeholders for specifying the set location of the robot (we will call these values when resetting the robot at specific locations).</p><p>In the next part, we create the <em>gaps</em> for binning of laser data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da21599a3bb42f597ff1ab919039de64/href">https://medium.com/media/da21599a3bb42f597ff1ab919039de64/href</a></iframe><p>Consider a laser reading with a field of view of 180 degrees (as is our case). Each laser value is recorded at a specific angle, and we could have many such recordings. Let us assume that we record 180 values in a 180-degree field of view. But we specified that we want to represent the environment with only 20 values (because a network trains faster with fewer input parameters). That means we need to somehow reduce the amount of 180 values to 20. We do this by splitting the 180-degree field of view into 20 gaps to record the minimum laser value per each gap. So during the initialization, we calculate the starting and ending angles for each gap and save them for later use.</p><p>Now that we have set up our placeholders, we can start initializing and launching our simulator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/760c6b2f8079c8f222954f3713fb727e/href">https://medium.com/media/760c6b2f8079c8f222954f3713fb727e/href</a></iframe><p>We launch roscore at port 11311 by calling for this process within our initialization function.</p><p>Then launch the simulator with the input <em>launchfile</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87d942b575a2bb31d6b1de6f7e651b35/href">https://medium.com/media/87d942b575a2bb31d6b1de6f7e651b35/href</a></iframe><p>Now we can set up our ROS publishers and subscribers, which will allow us to send and receive the information from the simulator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/886e0bd7be83726539180875fb04dbb7/href">https://medium.com/media/886e0bd7be83726539180875fb04dbb7/href</a></iframe><p>The <em>self.vel_pub</em> publisher will send the action information to the robot in the simulator in the form of linear and angular velocities via a Twist() (twist is a ROS message type) message. <em>self.set_state</em> will publish and place the robot in a specified location within the simulator. We will use this to randomly place the robot at each start of a new episode. <em>self.unpause</em> and <em>self.pause</em> functions will pause and unpause the simulator. <em>self.reset_proxy</em> resets the whole simulation. Publishers <em>self.publisher / self.publisher2 / self.publisher3</em> will visually publish the information about the location of the goal, current linear and current angular velocities in Rviz visualization of the simulation. We will receive the laser data from the velodyne puck LiDAR by using the <em>self.velodyne</em> subscriber (Notice, it receives point cloud data instead of laser distances). Finally, we obtain the robot location within the simulator with <em>self.odom</em> subscriber.</p><p>A thing of note here is that the <em>self.velodyne</em> and <em>self.odom</em> subscribers invoke callback functions — <em>self.velodyne_callback</em> and <em>self.odom_callback</em>, respectively. Simply put, a callback is a function that will be called every time new data is available from this subscriber. Usually, this is done to process and prepare the data in some way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5da1f11ecbe805af3c00eb3fd6583aa9/href">https://medium.com/media/5da1f11ecbe805af3c00eb3fd6583aa9/href</a></iframe><p>The <em>odom_callback</em> simply stores the last received odometry data in the <em>last_odom</em> variable.</p><p>The velodyne_callback is a bit more involved.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/206bb8464730721a0cca3a59a29c8d9c/href">https://medium.com/media/206bb8464730721a0cca3a59a29c8d9c/href</a></iframe><p>We pointed out that the velodyne subscriber returns data as a point cloud. That means that each recorded point returns an X,Y,Z coordinate of each laser reading for each point. However, we want the laser readings to be represented just like a 2D LiDAR, where each laser value returns the distance to an obstacle. This means we need to process and then “<em>flatten</em>” the velodyne data before we can use it. First, we read the X, Y, and Z values from the incoming data. Then create a placeholder for where we will store the processed velodyne data. This data now will be set to 10, representing the maximum measurement distance. (<strong>Note</strong>: If a laser is pointed to an empty space, no measurement will be returned, and the data point will be set to NaN. However, the neural network can not process NaNs, so in such cases, we need to replace these values with a maximum measuring range.) Once we have read our data, we can start filtering each incoming data point. First, we filter out the ground by checking if the z coordinate of the data point is larger than -0.2 (the point of origin for the data is the velodyne sensor). Then we calculate the distance to the data point. Once we have the distance, we calculate to which gap this measurement belongs. If the distance to the data point is smaller than the existing distance for this gap, we save this distance as the representative measure for this gap. This allows us to use a 3D velodyne puck LiDAR sensor to record obstacles at multiple heights, but still, get the laser distance representation as a 1D vector. Simply put, we just keep the minimum value for each gap and thus “<em>flatten</em>” the 3D laser data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*c8yGuw9KVRUlutxG_ohazw.png" /><figcaption>Environment representation by a 16-channel 3D Velodyne LiDAR</figcaption></figure><p><strong>Single Step</strong></p><p>Once we have initialized our class, we can specify the function that will carry out a single motion step in the simulator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a20b44b23a6c3e50af83fd1bebb2a549/href">https://medium.com/media/a20b44b23a6c3e50af83fd1bebb2a549/href</a></iframe><p>For a single step, we pass in an action to take and publish this action as a Twist() message to our robot. We also visualize the actions and the goal position by publishing the markers. Since we do not want the simulation to be running while we perform some calculations in the background, we pause it, when we are not carrying out an action. This means that to propagate the state with the current action, we must unpause our simulation. Then propagate it for TIME_DELTA amount of time (0.1 seconds in this implementation) and pause it again. This sequence of actions will perform the action for 0.1 seconds, and allow us to read the new state after it.</p><p>Now we read the state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06793bd68c5ff8ab0b7b30f528ccb5f3/href">https://medium.com/media/06793bd68c5ff8ab0b7b30f528ccb5f3/href</a></iframe><p>Our callback functions constantly update the velodyne_data in the background with a high frequency, so we will have received the newest laser observations right after propagating the state. With this information, we can calculate, if a collision has occurred and do some quick data manipulation to save the laser_state (we copy it so as not to mutate velodyne data, and prepare the correct list form). From the odometry subscriber, we obtain the location information of the robot. The robot&#39;s heading is returned in a form of a quaternion. To turn it into something that a human can actually comprehend, we translate it into an Euler angle and round it to 4 digits after the decimal.</p><p>Now that we know the location and heading direction of the robot, we can calculate the polar coordinates of the goal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f565ac3462c6aaa8d687c157cb75ade/href">https://medium.com/media/1f565ac3462c6aaa8d687c157cb75ade/href</a></iframe><p>For distance to the goal, we use the <em>numpy.linalg.norm()</em> function that will return a length of the given vector. If we give coordinates of the goal, with respect to the robot&#39;s location, that will give us the distance information. Then we implement a bit of a hacky way to calculate the difference in heading between a vector towards the goal and the robot heading (feel free to update this part of the code and get back to me with a better solution). Essentially, we need to align the coordinate frames and obtain the difference in the angles. This gives us distance and theta to represent the polar coordinate of the goal in the robot&#39;s frame.</p><p>With the obtained distance information, we can see if we have reached the goal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8356617ec8d6cb95c65d782aeabe3bb4/href">https://medium.com/media/8356617ec8d6cb95c65d782aeabe3bb4/href</a></iframe><p>If the distance is smaller than the GOAL_REACHED_DIST threshold (here it is 0.3 meters), we have arrived at our goal.</p><p>Finally, we can combine the full state information and return it along with other relevant information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d06704d045f8aa6566ff36219e47927/href">https://medium.com/media/7d06704d045f8aa6566ff36219e47927/href</a></iframe><p>We combine the robot state with the laser state. Then obtain the reward. In the end, we return the state, the reward, whether the episode has concluded for some reason, and if we have reached the target.</p><p><strong>Note</strong>: You will notice, we used a couple of class functions here. First, we had the function, to see if we have collided with anything.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b9f9914b5a53c78e14b2b344c4b279e/href">https://medium.com/media/5b9f9914b5a53c78e14b2b344c4b279e/href</a></iframe><p>We check laser data and select the minimum value. Naturally, if the minimum number is smaller than the COLLISION_DIST threshold, we return that a collision has happened. We also return the minimum laser value that will be used in the reward calculation.</p><p>Speaking of reward calculation…</p><p><strong>Reward</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c14aa2df9756fb4404a607534950fd71/href">https://medium.com/media/c14aa2df9756fb4404a607534950fd71/href</a></iframe><p>We give a high reward if the robot arrived at the goal, a negative reward if the robot collided with anything, and an immediate reward otherwise. Immediate reward in its basic form can be expressed as:</p><pre>r = v - |ω|</pre><p>The idea behind it is that the robot needs to realize that it should be moving around and not just sitting in a single spot. By setting a positive reward for linear motion robot first learns that moving forward is good and rotating is not. Even though it crashes a lot in the beginning, the episode reward is still higher than just sitting in one spot and rotating. Soon it learns, that taking a turn near obstacles is more beneficial than crashing, even though it still might be a negative action, it is less negative than crashing. With this, the robot soon learns to avoid obstacles with a smooth motion as the smaller the rotation the smaller the penalty for turning. While running around the environment the robot randomly will end up reaching the goals and in time realize that the benefit of reaching the goal outweighs the penalty for turning. Even if it ends up in a pocket, the robot will still know that being in forward motion will give it a positive reward and thus will unintentionally look for a way out of the pocket. However, this method does not give you the shortest possible path to the goal as the robot will prefer to also have linear motion while having rotational motion as that will give a better reward. That means that the robot will take a larger turn just to turn around, if possible, which will increase the total path length. But it generally gives a very smooth motion to the robot. The size of the turn though can be minimized by giving a smaller penalty for turning.</p><p>Additionally, we add the term <em>r3</em> which is calculated by our lambda function. This gives an additional negative reward if the robot is closer to any obstacle than 1 meter. Using this ‘repulsion’ makes the robot wearier of obstacles in general and move around them with a larger gap.</p><p><strong>Reset</strong></p><p>If an episode has concluded (recall, that an episode is a collection of sequential steps until a collision, reaching a target, or reaching the maximum number of steps), we need to reset the simulation. We can do this with a class function <em>reset</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b2631135244b21d4fcbc81f2351ff3e/href">https://medium.com/media/3b2631135244b21d4fcbc81f2351ff3e/href</a></iframe><p>Here, we reset the simulation environment to its initial state.</p><p>However, we would like each episode to start with a different initial position and pose of the robot. This would allow us to vary the experiences that the robot will encounter and generalize our network better.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5426015f2c806640398c655c91b2729/href">https://medium.com/media/d5426015f2c806640398c655c91b2729/href</a></iframe><p>For this reason, we sample a random Euler angle value and turn it into a quaternion. This will serve as a random robot heading direction. Afterward, we need to sample random X and Y coordinates as the robot starting location of the episode. Our simulation environment is a walled section of size 10 by 10 meters. That means, that we would like the robot to be randomly spawned within this walled section. Therefore, we want the random values to be in the range from -4.5 to 4.5 meters around the point of origin of the environment (with keeping a 0.5-meter distance from the walls). But we also have other obstacles in the environment and we would not want to spawn our robot on top of them. So we randomly select X and Y coordinates until they are not located within the ‘dead zones’ around the obstacles. Now that we have our coordinates and heading, we update the robot position and place it there with the <em>set_state</em> publisher. Finally, save the coordinates as the odometry information.</p><p>Randomly place a goal in the environment by calling a function that we will explain in detail a bit later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/045e52a6ddb2e388d9c3a43e9087836d/href">https://medium.com/media/045e52a6ddb2e388d9c3a43e9087836d/href</a></iframe><p>We have placed 4 cardboard boxes in our simulation. To vary the environment for each episode even more, we can randomly change their position at the start of each episode as well. We will also explain this function in detail in a bit. Now we just reset the markers that publish the action information. Since we do not take any action when resetting the environment, we can simply pass in zeros as action values here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yT-LcBD-oWfA1UyCOeSedQ.png" /><figcaption>Random starting position and poses of the robot after every reset call. Cardboard boxes also change their location on every reset.</figcaption></figure><p>After placing the robot, goal, and boxes in the environment, we can observe it to return to the first state. The observation is very similar to what we already saw in the <em>step</em> function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5566c872cf57cdf2903e3194780c5362/href">https://medium.com/media/5566c872cf57cdf2903e3194780c5362/href</a></iframe><p>Propagate the state again to get the values back from our subscribers. Do the calculations, combine the laser and robot state information, and return the state.</p><p>Here we used 3 additional functions first of which was the <em>change_goal.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1fb0004715dc70ac226863a71b8e8b0/href">https://medium.com/media/c1fb0004715dc70ac226863a71b8e8b0/href</a></iframe><p>We set up our class variables <em>upper</em> and <em>lower</em> during the initialization. The <em>upper</em> and <em>lower</em> values describe the range in which the goal can be randomly placed. This was done to allow us to use a simple ‘<em>bootstrapping</em>’ method, to help the network to learn that it needs to navigate to the goal. By placing the goal near the robot early on in the training, it has a higher chance to stumble upon it. This means that it will collect more experiences of navigating to the goal, which will help the network to learn from good samples. So when placing the random goal, we place it in the vicinity of the randomly placed robot position of range from <em>lower</em> to <em>upper. </em>Every time we place a new goal, we increase the lower and upper limits. But before accepting the goal position, here we also need to check if it is not placed on any known obstacles.</p><p>Next, we have the random_box function, which places the boxes in random locations in the environment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff53abb5e509e52b8008e4e71888f771/href">https://medium.com/media/ff53abb5e509e52b8008e4e71888f771/href</a></iframe><p>The logic here is very similar to the <em>change_goal</em> function, except we also want to check if the box placement is not too close to the robot or the goal. This is done sequentially for all 4 boxes we have in our environment.</p><p>We also have the publish_markers function, which publishes visual information in the Rviz of the action values as well as the goal position.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/748023795f750aa45078e69468b77feb/href">https://medium.com/media/748023795f750aa45078e69468b77feb/href</a></iframe><p>The final function that we need to look at is the <em>check_pos</em>. This function simply checks if the passed-in X and Y values are located in the range of any of the obstacles in the environment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3c9037daa0b7768deaec33eab89c21a/href">https://medium.com/media/e3c9037daa0b7768deaec33eab89c21a/href</a></iframe><p><strong>Note</strong>: These ranges are determined manually and are specific to the default map used in the repository. If you would like to use any other map for training, you need to manually input the ranges of ‘dead zones’ around the obstacles in this function.</p><p>This concludes the code overview of this repository and I hope it is sufficient to start your own research in the field of Reinforcement Learning for mobile robot navigation in ROS simulator. If anything, I hope it can help to guide your own ideas and give a sort of an overview of why certain things are done or just how to even connect your network to the ROS simulator.</p><p>In <a href="https://medium.com/@reinis_86651/deep-reinforcement-learning-in-mobile-robot-navigation-tutorial-part5-some-extra-stuff-b744852345ac">Part 5</a>, we will not be looking at the code anymore, but we will look at some tips and tricks on how to speed up training and other miscellaneous information.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e4bc672f590" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Reinforcement Learning in Mobile Robot Navigation Tutorial — Part3: Training]]></title>
            <link>https://medium.com/@reinis_86651/deep-reinforcement-learning-in-mobile-robot-navigation-tutorial-part3-training-13b2875c7b51?source=rss-51bb2de1006a------2</link>
            <guid isPermaLink="false">https://medium.com/p/13b2875c7b51</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[mobile-robot]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Reinis Cimurs]]></dc:creator>
            <pubDate>Sun, 02 Oct 2022 08:32:05 GMT</pubDate>
            <atom:updated>2022-10-19T20:41:28.613Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Reinforcement Learning in Mobile Robot Navigation Tutorial — Part3: Training</h3><p>In <a href="https://medium.com/@reinis_86651/deep-reinforcement-learning-in-mobile-robot-navigation-tutorial-part1-installation-d62715722303">Part 1</a> of this tutorial, we cloned and installed the GitHub repository and successfully launched our robot navigation training for the first time. In <a href="https://medium.com/@reinis_86651/deep-reinforcement-learning-in-mobile-robot-navigation-tutorial-part2-network-82aea28b0e0f">Part 2</a> we looked, in detail, at what the training neural network actually consists of. Now in this part, my fellow researcher, it is time to see how the training of the neural network is actually called in a mobile robot motion setting. Once again, we will be looking at the code from the python file:</p><pre>train_velodyne_td3.py</pre><p>Located in:</p><pre>~&lt;PATH_TO_FOLDER&gt;/DRL-robot-navigation/TD3</pre><p><strong>The Robot and The World</strong></p><p>Before we start the actual motion policy training of a mobile robot, we must first understand the task that we are trying to solve. To put it in human language, we are trying to “<strong><em>find the optimal sequence of actions that lead the robot to a given goal</em></strong>”. But how do we form this problem into something that a computer can understand and execute? There are two things to consider — the action and the environment that the action reacts to. In a mobile robot setting, it is quite easy to express the action in a mathematical form. It is the force applied to each actuator for the controllable degree of freedom. To put it simply, it is how much we want to move in any controllable direction.</p><p>In this tutorial, we will be using a Pioneer P3DX simulated mobile robot platform. It is a non-holonomic, differential-drive mobile robot base, that is capable of either moving back and forth or rotating around its axis. This means, that we have 2 directions that we can control — linear motion (moving forward/backward) and angular motion (rotating left/right). Both of these controls can be numerically expressed as linear velocity in meters per second and angular velocity in radians per second, which then can be easily processed by a neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*R3lx1ynR3UqxWIvGfBcZPw.jpeg" /></figure><p>To get a reaction to environmental states, it needs to be observed in a logical and numerical way. One of the simplest forms of detecting the environment (in robotics) is by using a LiDAR or laser sensor. The logic here is very simple — the closer an object is to the laser sensor, the faster the emitted light will be returned to the photoreceptor. This speed then can be directly used to calculate the distance to the object. Logically, we can speculate that a robot will make decisions based on how far it is from obstacles and a motion policy can be derived from that. This gives a simple numerical representation of the environment of the surroundings of the laser sensor (and, subsequently, the robot).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*8jiH1RQt3ZoodYVelRVc_Q.jpeg" /></figure><p>One last thing to consider is, how will the robot know where it needs to go. We have a specific goal point in mind that the robot needs to reach, therefore this information needs to be communicated to it. To learn an ego policy, this information should be given centered on the robot&#39;s position. We will express this in polar coordinates in the form of distance to the goal position and the difference of angles between the robot heading and the heading towards the goal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*uTb5xZX3IB-0c_aeWQToWA.png" /></figure><p>Now that we have formed a numeric expression of the environment and the agent, we can describe our <em>state</em> and <em>action</em>. As discussed, action is a tuple:</p><pre>a = (v, ω)</pre><p>where v is the linear velocity, and ω is the angular velocity.</p><p>For the <em>state</em>, however, things get a bit more complicated. We first need to represent the surroundings of the environment. This we will do with the laser readings. Then the goal will be given in polar coordinates. But we also might want to give the current internal state of the robot to the neural network, for it to know how fast we are already moving. Therefore, we will represent the <em>state</em> also with the action taken at the previous time-step. So our final state representation will become a 1D vector combining:</p><pre>s = (<em>laser_state</em> + <em>polar_goal_coordinates</em> + <em>previous_action</em>)</pre><p>We will be using 20 laser readings (we will explain how we obtain them in detail in Part 4). That means our final state representation will consist of 20 + 2 + 2 = 24 feature 1D vector.</p><p><strong>Setting up the Training Network</strong></p><p>So now that we have installed our repository, created a TD3 neural network, and understood how to represent a state, let us get to the meat and potatoes of actually training the mobile robot motion policy.</p><p>First, let&#39;s set up a bunch of parameters for the training. Hopefully, they are self-explanatory, or the comments explain their purpose.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2245b04a9b6f777c64077f3be52afc5c/href">https://medium.com/media/2245b04a9b6f777c64077f3be52afc5c/href</a></iframe><p>Afterward, we will set up some more parameters and directories.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/639ed9c82998cc825a3664f15992c7fe/href">https://medium.com/media/639ed9c82998cc825a3664f15992c7fe/href</a></iframe><p>We will create a folder to store the network if it does not already exist. Then we specify how many laser readings we will require from the simulation in the <em>environment_dim</em> variable. The <em>robot_dim</em> will specify the number of “internal robot parameters” such as the combination of polar coordinate features (2) + previous action features (2). In line 10 we will actually call the creation of the simulation environment. The simulation environment creation parameters are stored in the file “multi_robot_scenario.launch”. To create the environment, we also need to pass in the number of laser readings we want it to return for each step. When creating the environment, some time might be required to start all the background processes in Gazebo simulation. Therefore, we need to give it a little time by putting our program to sleep for 5 seconds. (This should be enough on most systems, but might require a longer sleep time if issues arise.) Then set the seeds for reproducibility, set the state_dim as discussed in the aforementioned chapter, specify the number of actions our network needs to calculate in <em>action_dim</em>, and set the maximum possible action value that can be returned by the neural network.</p><p>Next, we finally create and initialize the TD3 model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f8824707798a2e2908f99b36960c07a/href">https://medium.com/media/4f8824707798a2e2908f99b36960c07a/href</a></iframe><p>Additionally, we create a replay buffer that will store the experiences that the robot has encountered in the simulation and that will be used as a dynamic dataset that the neural network will be optimized for. If we have set the load_model parameter as True, previously trained model parameters will be loaded for our model (if they exist). If not, then the model will be initialized with random parameter values.</p><p>Before starting the training loop, some last parameters need to be set up.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ec7cde13fc46d29a0b23ffb4ace1033/href">https://medium.com/media/3ec7cde13fc46d29a0b23ffb4ace1033/href</a></iframe><p>We first create a list to store the results from evaluations and create variables for counting the elapsed time, steps, and epochs. Finally, create variables for later use, when we will require to perform random actions near obstacles.</p><p><strong>Training Loop</strong></p><p>Now that everything has been set up, we can start our training loop. We will base the amount of training on the maximum training steps, but other methods (such as the maximum number of epochs, elapsed time, etc.) can also be easily set up.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96eb44b3e58688bd77e4f439b6317801/href">https://medium.com/media/96eb44b3e58688bd77e4f439b6317801/href</a></iframe><p>All the following code (unless stated otherwise) will be located within this loop.</p><p><strong>Note</strong>:<br>We will use notations of the episode and epoch in the text.</p><p><strong>Episode</strong> — a collection of subsequent steps, until one of the termination conditions is reached (termination conditions are — reaching a goal, colliding with an obstacle, or reaching the maximum number of steps set in <em>max_ep</em> parameter)</p><p><strong>Epoch</strong> — a number of subsequent episodes or timesteps between performing an evaluation (set in <em>eval_freq</em> parameter).</p><p>Let us set up the code that will execute at the conclusion of every episode. We need to set it at the beginning of the loop, as we want to already do the first reset of the environment to obtain the first observation of it (this is why we set the done parameter as True earlier).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/399396bc80315c5a8b74766a527a1a26/href">https://medium.com/media/399396bc80315c5a8b74766a527a1a26/href</a></iframe><p>On the first execution of the code, the timestep value will still be 0, so the network training will not take place (as we do not have anything yet to train on). However, in every subsequent completion of an episode, a neural network training will be run. That means, that we train the neural network after every episode. The training cycles are determined by the <em>episode_timesteps</em> value we pass in. The reasoning is, that if there were more timesteps in the episode, we have collected more new samples, and we have more new data to optimize for. If we do not have a lot of new samples, fewer training cycles will be carried out. After this, we check if it is time to perform an evaluation of the current model. If it is so, we perform the evaluation, record the results and save our model. Once these checks are complete, we need to reset our environment. This will place the robot in a new random starting position and orientation, will give a new randomly placed goal position, and start a new episode. From the reset state, we will obtain an observation of the new environment. Then we just simply set our counting variables back to 0, and start executing a new episode.</p><p>In DRL, it is common to follow a greedy strategy. That means, that the neural network is tasked to select the best-calculated outcome for any input. Unfortunately, while training, this may cause a vicious cycle of first calculating a good outcome, then following it, and reinforcing the good result, without looking for possible better alternatives. This is often referred to as an <strong>exploitation</strong> strategy. To find the best possible outcome, we must force the neural network to explore the alternatives (<strong>exploration</strong> strategy). A common way to do this is to add random noise to the neural network output and observe the result in the environment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/378d800ebb10ca8eb89f1884517c3073/href">https://medium.com/media/378d800ebb10ca8eb89f1884517c3073/href</a></iframe><p>We calculate the amount of noise we want to add to the action calculated by the neural network and save it as <em>expl_noise</em>. The noise level will decrease over the <em>expl_decay_steps</em> until it reaches the minimum <em>expl_min</em> value. We calculate the action with a neural network and update this value by adding the noise to it. However, robots have physical limitations in their maximum and minimum velocities. So we clip the action value in this range to obtain the final action value to test out in the environment.</p><p>If you notice the way we obtained the random value to add to the action, you will see we used the <em>numpy.random.normal</em> function. This gives us a random value with Gaussian distribution. That means that if we would average out the mean value of the noise, it would be very close to 0 as minus values are just as likely to be given as plus ones. However, if the robot has already found itself in a critical position, it needs decisive action to get out of it, and random Gaussian noise on each step is not sufficient. Let us imagine that the robot has found itself directly facing an obstacle. If it simply continues going forward, it will crash. Adding Gaussian noise will not help, as it will even itself out over sequential steps. Therefore, we implement an idea, to force the robot to take a single decisive action for a random number of sequential steps. This will force the robot to randomly experience a sequence of actions that will take it out of the critical position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*diUQGJskcJokq8XqMHth2g.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf37cac1f18437102a6d3b8fd3e3e208/href">https://medium.com/media/cf37cac1f18437102a6d3b8fd3e3e208/href</a></iframe><p>If we choose to use this method (it can be turned off by setting <em>random_near_obstacle</em> to False), we might not want to use it at every interaction near an obstacle. So we query a random value and go on with this method only if the random value is larger than 0.85. Also, we check if the obstacle in front of the robot is closer than 0.6 meters. Remember, our state is represented by 20 + 2 + 2 values, where the first 20 are the laser sensor state. To check if an obstacle is in front of the robot (and not on the sides) we check the values from 4 until 16 in our state representation (state[4:-8]). We also check if we are already locked into the sequential execution of this method. If all of this passes, we select a random number between 8 and 15 for how many steps we will execute this random action. Then sample the random action. Update the action value, and count down the counter of random actions.</p><p><strong>Note</strong>:<br>Here we set <em>action[0] = -1</em> to force the robot to take only a random rotation. To set a fully random action, this line should be commented out or deleted.</p><p>Next, we need to ‘fix’ our action value. Our TD3 neural network model outputs 2 action values in range -1, 1. But our laser sensor records only at a 180-degree field of view in front of the robot. That means, it would be irresponsible of us to allow it to move backward, as there is no way for the robot to know what is behind it. So we must ensure that our robot has the minimum linear velocity value of 0 m per second. We do this in the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d05a571c63aa5dd294544d59ec5f08e/href">https://medium.com/media/2d05a571c63aa5dd294544d59ec5f08e/href</a></iframe><p>The first value in <em>action</em> represents the linear velocity and we squeeze it in the range 0,1. This value we can pass to our gazebo simulator environment, where it is executed. A new state is returned along with the state-action pair reward and two boolean values of whether the state concluded (in <em>done</em>) and if the target was reached (in <em>target</em>). Next, we check if the maximum number of steps is reached and update <em>done</em> and <em>done_bool</em> values here accordingly (in Python <em>int</em> and <em>bool</em> values can be used interchangeably, but here we use <em>int</em> as we use the numeric value in the Bellman equation as the terminality of the state). Afterward, simply update the current running state (for which we will calculate the action value in the next iteration of the training loop) and update the training counters.</p><p>This loop will run, calculate actions for each state, gather experiences and train the neural network model until it concludes… or we stop explicitly stop it by pressing CTRL+C in the terminal (which is my favored approach).</p><p>Once the loop concludes, we save the evaluation data and the final network parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9c1e36d2389bd217ce4028af9c9d066/href">https://medium.com/media/e9c1e36d2389bd217ce4028af9c9d066/href</a></iframe><p><strong>Evaluation</strong></p><p>One final thing that we did not look at just yet is how to perform an evaluation. For this, we create a separate evaluation function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebf984bd992d0a45138884241a61253a/href">https://medium.com/media/ebf984bd992d0a45138884241a61253a/href</a></iframe><p>Recall, that this is called after the completion of every epoch. Let us set some variables that will collect the data we might want to look at, such as average reward and the collision rate. Then we start the evaluation loop that will execute <em>eval_episodes</em> number of random evaluation runs. Here, the steps are the same as during the training, except we do not apply random noise to the calculated actions, as we are interested in knowing how well the current model performs. Additionally, we record the reward and whether or not we crashed in the run. A hardcoded reward for a crash is -100, so we can use the reward to see if a collision occurred (alternatively we can look if <em>done</em> is True while <em>target</em> is False). After executing all of the evaluation runs, we calculate the average reward and collision rate. Then print them out in the terminal. Ideally, we should see a high positive average reward and collision rate that is close to 0. We return the average reward, to be added to the evaluation results.</p><p>This concludes the training of the neural network model that trains a mobile robot motion policy from laser, goal, and robot motion inputs. Theoretically, any simulation environment could be used in this code part. It does not need to be our Gazobo simulator nor would it need to be a laser sensor input that records the environment. The variable <em>env</em> should just have a different assigned simulation environment and setting different <em>environment_dim </em>value<em> </em>would allow using a sensor with a different number of inputs. But we do have a working environment already available with Gazebo and ROS implementation, and that is exactly what we will be looking at in <a href="https://medium.com/@reinis_86651/deep-reinforcement-learning-in-mobile-robot-navigation-tutorial-part4-environment-7e4bc672f590">Part 4</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13b2875c7b51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Reinforcement Learning in Mobile Robot Navigation Tutorial — Part2: Network]]></title>
            <link>https://medium.com/@reinis_86651/deep-reinforcement-learning-in-mobile-robot-navigation-tutorial-part2-network-82aea28b0e0f?source=rss-51bb2de1006a------2</link>
            <guid isPermaLink="false">https://medium.com/p/82aea28b0e0f</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[mobile-robotics]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[robot-navigation]]></category>
            <category><![CDATA[mobile-robot]]></category>
            <dc:creator><![CDATA[Reinis Cimurs]]></dc:creator>
            <pubDate>Tue, 06 Sep 2022 20:18:41 GMT</pubDate>
            <atom:updated>2022-10-02T08:33:30.591Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Reinforcement Learning in Mobile Robot Navigation Tutorial — Part2: Network</h3><p>In <a href="https://medium.com/@reinis_86651/deep-reinforcement-learning-in-mobile-robot-navigation-tutorial-part1-installation-d62715722303">Part 1</a> of this tutorial, we cloned the repository, installed it, and set up the proper sources to run the training for the first time. This should allow us to run the full training of our TD3 architecture-based neural network in ROS simulation. In this part, we will look in detail at the TD3 network code itself.</p><p>The neural network code is located in a python file:</p><pre>train_velodyne_td3.py </pre><p>Located in:</p><pre>~&lt;PATH_TO_FOLDER&gt;/DRL-robot-navigation/TD3</pre><p>The naming convention here stands for:</p><ul><li>train — python file used for training</li><li>velodyne — sensor used to obtain surrounding environment</li><li>td3 — network architecture</li></ul><h3><strong>TD3 Network Implementation</strong></h3><p>TD3 is an actor-critic type of network similar to DDPG. That means that there is an “actor” network that calculates an action to perform, and a “critic” network, that estimates, how good is this action. In a simple form, TD3 architecture is an extension of DDPG architecture to solve the problem of overestimating the Q-value. It does so by introducing a second critic network within the loop and selecting the output from the one that produces the lower Q-value estimations. (Once again, a mathematical and algorithmic background overview can be obtained <a href="https://spinningup.openai.com/en/latest/algorithms/td3.html">here</a>.) Therefore, we need to create an actor-network that will take the environmental state as input and output action for the robot to take. Also, we need to create two critic networks that will take the environmental state as well as the action from the actor-network as inputs and will output the estimated value of this state-action pair.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ATomJYgS0Q-IyAypRt340A.png" /><figcaption>TD3 Neural Network Scheme</figcaption></figure><p><strong>Actor Network</strong></p><p>To create an actor model, we simply need to create a decoder that will map the state input to action as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3468562784679e100ec1e194e6ec03c/href">https://medium.com/media/a3468562784679e100ec1e194e6ec03c/href</a></iframe><p>We create an actor class, that consists of 3 linear, fully connected layers. In the class initialization, we define the layers that we will use in the forward pass. The input to the first layer will be a single-dimension vector representing the environmental state as <em>state_dim</em>. We will embed this state with 800 parameters. Since the layers will be called sequentially, we must assure that the number of parameters in the previous layer will be the same as in the following layer. Therefore, the next layer input needs to be the same number of 800 parameters. Then we will map them to 600 parameters. In the final layer, we will map the 600 parameters directly to the number of controllable actions our robot will have as <em>action_dim</em>. In our case, we will control a ground mobile robot that will have controllable linear and angular velocities. Since our robot has limited maximal and minimal possible velocities, the output of the neural network needs to be limited to a <em>min-max</em> range. We can achieve this by defining a Tanh activation function. Tanh function will cap the output in the -1, 1 range.</p><p>In the forward pass, we define the sequence, how the layers will be called and how the values will be propagated through it. First, we call the first defined layer, apply ReLU activation on it, then do the same with the second layer. After that, we call the third linear layer and apply the Tanh function to force the output in the -1, 1 range. The output of this simple actor network will be the basis for the linear and angular velocities of our robot.</p><p><strong>Critic Network</strong></p><p>Similarly, we will create a critic network. As mentioned, we require 2 critics in order to mitigate the Q-value overestimation. Fortunately, both of these critics will always be working at the same time, so they can be defined by a single critic class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51ae4987ad455efd644f04a7d8e00242/href">https://medium.com/media/51ae4987ad455efd644f04a7d8e00242/href</a></iframe><p>Here, the decoder for the Q-value is very similar to the one we saw in the actor class. However, since we need to evaluate not the state, but more so the actor&#39;s response to it, we will need not only the state information but also the action from the actor-network as inputs in our critic network. There are multiple ways to define the state-action par as an input. For instance, the simplest form is to simply concatenate (or just append) the action values at the end of the one-dimensional vector representing the state. Then we could use the same form of decoder we saw in the actor network. But we will use a slightly different approach inspired by the method described <a href="https://pemami4911.github.io/blog/2016/08/21/ddpg-rl.html">here</a>. Essentially, we treat the state and action as different inputs for the critic network. Embed the state information with a single linear, separately pass through the state embedding and action values in the second layer, combine them and obtain our value estimation in the final layer. Since we will create both critic networks with a single class, we will need to define these layers in the initialization twice. Layers 1,2,3 belong to the first critic and 4,5,6 to the second critic. Notice that layers <em>2_a</em> and <em>4_a</em> use the input size as <em>action_dim</em>, as this will be the first layer where actions will be embedded.</p><p>In the forward pass, we define how the propagation will take place. First, only the state input is passed through the first layer and ReLU activation is applied to it. Then, it is passed through the second layer. In parallel, the action values are also passed through a single layer with the same output size. State embedding and action are multiplied by the weights of the respective second layers. Each multiplication will output the same size of a tensor with 600 parameters. These tensors then can be summed and also the bias of the second action layer can be added to them. (This method of infusing the action inputs into the neural network has worked well in practice) Afterward, we use a final layer to map this combined state-action pair embedding to the Q-value estimation. Notice that there is no activation function here as the Q-value does not have a min or max value, so no capping is needed. As output, we will get both Q-values of both critic networks.</p><p><strong>TD3 Network</strong></p><p>Finally, we can implement the full TD3 network that will be the combination of our actor and critic networks. We can define a TD3 class and create our actors and critics in it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/474b3c4be9c04ecd942ea62e31508174/href">https://medium.com/media/474b3c4be9c04ecd942ea62e31508174/href</a></iframe><p>In TD3 network, we will implement something called the <em>soft update</em>. Every time that we will optimize the network parameters, we will only select a subset of data, called a batch. That means that the optimization parameters of each network will be highly tuned to these samples. This, however, does not mean that we will have found the best parameters for all the possible situations. In fact, if we use these optimized parameters directly, our learning will be highly unstable as each time network parameters will be optimized for different sets. That is why we will have a control or target network for each of our networks. On each training cycle, we will optimize our base network and obtain new parameters. Then we will <em>infuse</em> the target network with a small amount of these optimized parameters from the base network and reset the base network to have the same parameters as the newly updated target network. This way, on each update, the target network will be slightly nudged in the (hopefully) general direction of the optimal policy while keeping the training process stable. This is the reason why in the initialization of the TD3 class need to not only call our actor and critic classes but also create <em>actor_target</em> and <em>critic_target</em> calls. Afterward, we load any parameters that we might have already saved for each of the classes and set the Adam optimizer for each class. Next, we set the maximum possible action value, create a <em>writer</em> that will record our data for Tensorboard visualization, and set a training iteration counter in <em>iter_count</em>.</p><p>After initialization, we can define some additional helper functions in our TD3 class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee719f7d0e2ac01380d1b3de114bd1b7/href">https://medium.com/media/ee719f7d0e2ac01380d1b3de114bd1b7/href</a></iframe><p>The <em>get_action</em> function will obtain a single action, given an environmental state. For the processing in the neural network, the state tensor will be put on a device (cpu or cuda), but for use in ROS Simulator later, we require it to be placed specifically on cpu, turned into a NumPy array, and returned as a single dimension.</p><p>Calling <em>save</em> and <em>load</em> functions simply saves or loads the actor and critic network parameters.</p><p>Probably, the most important part we have to define in our class is the <em>train</em> function. This will be the crux of our TD3 implementation and will specify how the training of our robot motion is performed. First, let’s define the function and name input variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7e1c8eae6a42ba4dee428e0cf9f4f9a/href">https://medium.com/media/d7e1c8eae6a42ba4dee428e0cf9f4f9a/href</a></iframe><p><em>replay_buffer</em> will define where to get samples for training from, iterations will define how many trainings to run in this function call, <em>batch_size</em> defines how many samples to sample in each iteration, <em>discount</em> is the discount factor in Bellman equation (from <a href="https://spinningup.openai.com/en/latest/algorithms/td3.html">theory</a>), <em>tau</em> is how much of base network parameters we will add to target network in <em>soft update</em>. <em>policy_noise</em> is the standart deviation of noise to add to the actions in order to enable exploration, <em>noise_clip</em> is the min and max value to clip the noise with, and <em>policy_freq</em> is how often to update the actor-network parameters. Additionally, define variables to store the average and max Q values as well as average loss for displaying in Tensorbord.</p><p>Next, we start the training process, by running network optimization for <em>iteration</em> number of iterations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10886841e0529004ffe640b27f3d8beb/href">https://medium.com/media/10886841e0529004ffe640b27f3d8beb/href</a></iframe><p>We sample a batch from the recorded robot motion experiences that are stored in the replay buffer. Then we calculate the next possible action for each state in the batch and add some noise to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aca8198df968cea5e214156d185583fe/href">https://medium.com/media/aca8198df968cea5e214156d185583fe/href</a></iframe><p>Then estimate the possible Q values of this next state-action pair for both critic networks using the target networks, and select the minimum value of both outputs for each sample in the batch. From the minimum values, we obtain the target Q value using the Bellman equation. Subsequently, we obtain the Q values of base critic networks. By calculating the mean squared error between the base network critic values and the target Q value, we can estimate how far off is our base network. The trick here is that with base network we are estimating the current state reward + discounted all future state rewards. But target Q value uses already known current state reward and uses an estimation for future rewards. Therefore, the target value should be closer to the real estimation, and calculating the loss against it should nudge the network in the right optimization direction. Then simply optimize the critic network from gradients in the loss.</p><p>Meanwhile, we also collect the average and max Q values in <em>av_Q</em> and <em>max_Q</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3abe7ee324363a5912199b23aae2d326/href">https://medium.com/media/3abe7ee324363a5912199b23aae2d326/href</a></iframe><p>The <em>Delayed</em> part in Twin <strong>Delayed</strong> DDPG (TD3) comes into play next. Essentially, we delay the updates of the actor network if compared to the critic network as well as delay the <em>soft update</em> of network parameters by executing this step only every <em>policy_freq</em> iterations. This should increase the network stability as well as give better actor parameter updates (as critic would be more precise). During the actor update, we calculate the Q value for the state-action pair. We optimize the network parameters in the direction that will give us the highest possible Q value. This might seem strange, that at first we use fixed actor parameters to obtain critic network loss, but then use the same critic to obtain Q value for the actor updates. While this method might be unstable, the constant “pulling” of the policies of each network back and forth eventually leads in the right direction, and we obtain the (hopefully) optimal actor as well as critic networks.</p><p>Then we simply slightly update both network parameters with <em>soft update</em>.</p><p>Finally, simply record our Q and loss value variables for display in Tensorboard.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1d21320bb6bcfacac748a27cd999aed/href">https://medium.com/media/b1d21320bb6bcfacac748a27cd999aed/href</a></iframe><p>This should create a TD3 neural network that can be used for learning robot motion. In the next part (<a href="https://medium.com/@reinis_86651/deep-reinforcement-learning-in-mobile-robot-navigation-tutorial-part3-training-13b2875c7b51">Part 3</a>), we will look at how to actually call this network in a mobile robot setting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82aea28b0e0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Reinforcement Learning in Mobile Robot Navigation Tutorial — Part1: Installation]]></title>
            <link>https://medium.com/@reinis_86651/deep-reinforcement-learning-in-mobile-robot-navigation-tutorial-part1-installation-d62715722303?source=rss-51bb2de1006a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d62715722303</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[robot-navigation]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[mobile-robot]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Reinis Cimurs]]></dc:creator>
            <pubDate>Tue, 30 Aug 2022 20:25:18 GMT</pubDate>
            <atom:updated>2022-10-23T09:13:17.427Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Reinforcement Learning in Mobile Robot Navigation Tutorial — Part1: Installation</h3><p>Deep Reinforcement Learning (DRL) has long been speculated to be able to solve all sorts of tasks in various fields. It has a rather impressive CV ranging from keeping pendulum swings upright to being able to play video games directly from the image input. The rule of thumb is — if it has a state, an action, and a way to determine how to reward this pair, we can learn whatever problem is put in front of us. Naturally, this includes robot motion. Or specifically for our case here — wheeled mobile ground robot motion (in simulation). I think we can all admit that given sensor data, a robot should be able to learn how to determine its next move. The math is there (I will not go into details here but some good overviews of the DRL methods used here are available on openai website <a href="https://spinningup.openai.com/en/latest/algorithms/ddpg.html">here</a> and <a href="https://spinningup.openai.com/en/latest/algorithms/td3.html">here</a>), the development tools are there, but what about the implementation? Well, that is exactly what we will be looking over here — the implementation of twin-delayed deep deterministic policy gradient (TD3) architecture for learning mobile robot motion with Pytorch and ROS Noetic in python.</p><p>As the basis for this tutorial, I will use the GitHub repository:</p><p><a href="https://github.com/reiniscimurs/DRL-robot-navigation">GitHub - reiniscimurs/DRL-robot-navigation: Deep Reinforcement Learning for mobile robot navigation in ROS Gazebo simulator. Using Twin Delayed Deep Deterministic Policy Gradient (TD3) neural network, a robot learns to navigate to a random goal point in a simulated environment while avoiding obstacles.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dBmtF_YzXg0ZYbLbjTWdg.gif" /><figcaption>Training Example</figcaption></figure><p><strong>PART 1: The Installation</strong></p><p>To simplify the tutorial description, I will assume some familiarity with the software used in the development of this repository, such as:</p><ul><li><a href="https://ubuntu.com/tutorials/install-ubuntu-desktop#1-overview">Ubuntu</a> 20.04</li><li><a href="https://www.python.org/downloads/">Python</a> 3.8.10</li><li><a href="https://pytorch.org/get-started/locally/">Pytorch</a> 1.10</li><li><a href="http://wiki.ros.org/noetic/Installation/Ubuntu">ROS Noetic</a></li><li><a href="https://github.com/tensorflow/tensorboard">Tensorboard</a></li></ul><p>These are the main dependencies for the installation of this repository. Their installation should be fairly straightforward following the information in the provided links.</p><p>Assuming that all of this is set up, we can clone and install our repository. First, open a terminal and navigate to the folder where you would like to clone the repository. (Here, and everywhere else in the code, replace the &lt;PATH_TO_FOLDER&gt; with the absolute path to your folder)</p><pre>cd &lt;PATH_TO_FOLDER&gt;</pre><p>Clone the repository:</p><pre>git clone https://github.com/reiniscimurs/DRL-robot-navigation</pre><p>The repository requires compilation. To do so, navigate to the following folder and compile:</p><pre>cd ~&lt;PATH_TO_FOLDER&gt;/DRL-robot-navigation/catkin_ws<br>catkin_make_isolated</pre><p>To run the neural network training in ROS, some variables first need to be exported and sourced. This can be done by executing the following lines in the terminal:</p><pre>export ROS_HOSTNAME=localhost<br>export ROS_MASTER_URI=http://localhost:11311<br>export ROS_PORT_SIM=11311<br>export GAZEBO_RESOURCE_PATH=~&lt;PATH_TO_FOLDER&gt;/DRL-robot-navigation/catkin_ws/src/multi_robot_scenario/launch<br>source ~/.bashrc<br>cd ~&lt;PATH_TO_FOLDER&gt;/DRL-robot-navigation/catkin_ws<br>source devel_isolated/setup.bash</pre><p>(<strong>Note</strong>: These commands set up the sources in your terminal. Remember to run them, every time you open a new terminal window.)</p><p>This should be sufficient to install and source the repository in order to be able to run the neural network training. You can start the training by navigating to the respective folder and running the train_velodyne_TD3.py file by executing the following commands in the terminal:</p><pre>cd ~&lt;PATH_TO_FOLDER&gt;/DRL-robot-navigation/TD3<br>python3 train_velodyne_td3.py</pre><p>While training is running, you can see the progress in tensorboard visualization opening a new terminal and executing:</p><pre>cd ~&lt;PATH_TO_FOLDER&gt;/DRL-robot-navigation/TD3<br>tensorboard --logdir runs</pre><p>The terminal will output something similar to the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*WOtYgj29Jcjglf9CobEQtg.png" /><figcaption>Terminal output after starting tensorboard</figcaption></figure><p>Copy the &lt;http://localhost:6006/&gt; (or equivalent) and paste it into your browser of choice to see the tensorboard output. Alternatively, you can hold CTRL and simply click on &lt;http://localhost:6006/&gt; and the page will open automatically.</p><p>To stop the training before it has been completed, simply press CTRL+c in the terminal where the training was started. However, this will not stop all the background processes. To stop the processes running in the background, open a new terminal and execute:</p><pre>killall -9 rosout roslaunch rosmaster gzserver nodelet robot_state_publisher gzclient python python3</pre><p>Once training has been completed, you can test the trained neural network by executing the test script:</p><pre>cd ~&lt;PATH_TO_FOLDER&gt;/DRL-robot-navigation/TD3<br>python3 test_velodyne_td3.py</pre><p>This should be enough to run and test the neural network training in ROS simulation. However, for clean installs, there might be some things to take note of:</p><ol><li><strong>Missing Packages</strong></li></ol><p>In this tutorial, I have only mentioned the main dependencies, but there are also additional packages that might need to be installed separately if they are not already present in your system (numpy, collections, squaternion, etc.). If the training does not run, check the terminal log for missing packages. The message displayed will be similar to:</p><pre>ModuleNotFoundError: No module named &#39;&lt;MISSING_PACKAGE&gt;&#39;</pre><p>To fix this error, simply install the package:</p><pre>sudo apt update<br>pip3 install &lt;MISSING_PACKAGE&gt;</pre><p>(a quick note, the package name will not always be the same as displayed in the log output. If PIP is unable to find such a package, see if it does not go by a different name in PIP. Here, google is your friend and you can easily find the right name of the package by googling - “ModuleNotFoundError: No module named ‘&lt;MISSING_PACKAGE&gt;’”)</p><p>2. <strong>The training starts, but nothing is happening.</strong></p><p>It just so happens to be, that the ROS simulation environment uses 3D models that do not come already downloaded with the ROS installation. This means, that they will be downloaded the first time there will be a need for them, as in, the first time you run the training. In such a case, you just might need to wait for some time until ROS has finished downloading them in the background.</p><p>For other issues, please use the possibility to submit an issue in the repository.</p><p>In the <a href="https://medium.com/@reinis_86651/82aea28b0e0f">Part 2</a>, we will look at the TD3 network code in detail.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d62715722303" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>