Skip to main content
Open In Colab The gridworld and the recycling robot in the MDP chapter have a handful of states that you can list in a table. A mobile robot does not. In this section you write a real navigation task as a Markov decision process: a TurtleBot3 Waffle must drive to a goal in a room with obstacles, using only its lidar and the goal’s position relative to itself. You will meet every element of the MDP again (state, action, transition, reward, discount) in the chapter’s notation, and see which choices each one forces on you. The room is small enough that you can also build a finite version of this MDP and run the chapter’s dynamic programming algorithms on it: policy evaluation, policy iteration and value iteration. That shows what each algorithm computes for a robot, and which of its assumptions the learning methods have to give up. The TurtleBot navigation chapter of the reinforcement learning part solves this MDP without a model, first with tabular Q-learning, then with DDPG and its successor TD3. This is the task of the turtlebot3_drlnav project, which trains navigation policies in Gazebo with ROS 2. Here the room is a 2D simulation small enough to run in seconds, so you can see every number the agent sees.

The robot and its room

The room is 4 m on a side, with four round obstacles at fixed places. Each episode puts the robot and the goal at random free positions at least 1.5 m apart, with a random heading. The robot is a TurtleBot3 Waffle, modeled as a disk of radius 0.2 m. It accepts a forward speed vv of at most 0.26 m/s and a turn rate ω\omega of at most 1.82 rad/s, the limits the TurtleBot kinematics assignment uses. Its lidar returns 24 ranges, one every 15 degrees around the robot, each clipped to the sensor’s 0.12 to 3.5 m span. The code below builds this simulator. The next two sections use the same code.
Output from cell 3 Left: the robot (blue circle, with a line along its heading), its 24 lidar beams and the goal (star). Right: the same 24 ranges in the robot’s own frame, where 0 degrees is straight ahead. Beams that reach the dotted line hit nothing within 3.5 m.

State

The agent never sees the pose (x,y,ϕ)(x, y, \phi). Its state StS_t is 28 numbers, each scaled to roughly [−1,1][-1, 1], the same layout as the turtlebot3_drlnav state:
  • the 24 lidar ranges,
  • the distance dtd_t to the goal and its bearing βt\beta_t relative to the heading,
  • the previous command (vt−1,ωt−1)(v_{t-1}, \omega_{t-1}).
The state set S\mathcal S is therefore a region of R28\mathbb R^{28} with infinitely many elements, not a list you can enumerate. Everything here is in the robot’s own frame. A policy that has learned “steer away from short beams on the left” can therefore use that rule in any room, while a policy that learned values for map coordinates would only work in this one. The real TurtleBot can measure all 28 numbers: the lidar gives the ranges, and odometry or a localization system such as AMCL gives the goal’s distance and bearing. This state is not strictly Markov. The world state is the pose plus the room, and two different poses can produce nearly the same scan, for example in two corners of an empty room. The next scan then depends on which pose the robot really occupies. The MDP introduction noted the same problem with single Atari frames, where DeepMind stacked four frames to recover the missing information. The previous command in the state plays a similar role: on a real robot with inertia, the last command tells the agent how it is already moving. Formally the problem is a partially observable MDP, and the learning methods of the TurtleBot navigation chapter treat the observation as if it were the state.

Actions

An action At=(vt,ωt)A_t = (v_t, \omega_t) is a forward speed and a turn rate, held for one control period of Δt=0.2\Delta t = 0.2 s. The action set A\mathcal A is the rectangle [0,0.26]×[−1.82,1.82][0, 0.26] \times [-1.82, 1.82]. The Waffle can reverse, but the task does not need it, and leaving it out keeps the action space smaller. This action space is continuous. Tabular methods need a finite set, so the Q-learning navigation section replaces it with five steering commands, and the DDPG section keeps the full rectangle.

Transition model

Given the pose and the action, the robot moves by the unicycle model with a little noise on each command: xt+1=xt+v~tcos⁡ϕt Δt,yt+1=yt+v~tsin⁡ϕt Δt,ϕt+1=ϕt+ω~t Δt,\begin{aligned} x_{t+1} &= x_t + \tilde v_t \cos\phi_t \, \Delta t, \\ y_{t+1} &= y_t + \tilde v_t \sin\phi_t \, \Delta t, \\ \phi_{t+1} &= \phi_t + \tilde\omega_t \, \Delta t, \end{aligned} where v~t=vt+ϵv\tilde v_t = v_t + \epsilon_v and ω~t=ωt+ϵω\tilde\omega_t = \omega_t + \epsilon_\omega, with ϵv,ϵω∼N(0,0.022)\epsilon_v, \epsilon_\omega \sim \mathcal N(0, 0.02^2). The new state then follows by ray casting from the new pose. Together these define the transition density p(s′∣s,a)p(s' \mid s, a). It is the continuous counterpart of the MDP chapter’s transition probabilities Pss′a=Pr⁡[St+1=s′∣St=s,At=a].\mathcal P^a_{ss'} = \Pr[S_{t+1} = s' \mid S_t = s, A_t = a]. Nobody writes this density down. The simulator can only sample from it, and on the real robot even the simulator is gone. Reinforcement learning is built for that setting, because the agent learns from sampled transitions. The dynamic programming algorithms of the MDP chapter need Pss′a\mathcal P^a_{ss'} as a table. Later in this section you build such a table for a gridded version of the room.

Reward

The reward after each step is Rt+1=2 (dt−dt+1)−0.05 ∣ωt∣ωmax⁡−0.01+20 1[goal]−20 1[collision].R_{t+1} = 2\,(d_t - d_{t+1}) - 0.05\,\frac{|\omega_t|}{\omega_{\max}} - 0.01 + 20\,\mathbb 1[\text{goal}] - 20\,\mathbb 1[\text{collision}]. The reward depends on the pose before and after the step, so it is random given ss and aa. The Bellman equations below use its mean, the expected reward Rsa=E[Rt+1∣St=s,At=a]\mathcal R^a_s = \mathbb E[R_{t+1} \mid S_t = s, A_t = a]. Each term has a job. The goal bonus and the collision penalty define the task. If they were the only terms, the agent would see a nonzero reward only at the end of an episode, and a random policy would almost never reach the goal to learn from. The progress term 2(dt−dt+1)2(d_t - d_{t+1}) gives a signal on every step: driving the full 5.2 cm of one step straight at the goal earns about 0.1. Over an episode these terms add up to 2(d0−dT)2(d_0 - d_T), so they reward getting closer without preferring any particular path. Its weight is kept small so that the goal bonus, not the distance covered, decides which starts are good. The turn penalty discourages a policy that wobbles left and right, which a real robot’s motors and odometry handle poorly. The time penalty of 0.01 per step makes waiting in place slightly worse than moving. These weights are design choices. The turtlebot3_drlnav project uses the same structure with different numbers: a goal bonus of 2500, a collision penalty of 2000, and dense penalties on the heading error and on driving slower than full speed. The TD3 section shows what happens to the learned behavior when the collision penalty is ten times larger.

Episodes, termination and discount

An episode ends in one of three ways. Reaching within 0.25 m of the goal and colliding are terminal. In the chapter’s terms they lead to absorbing states that pay no further reward, so their value is zero and every Bellman equation below stops there. Running out of time after 200 steps (40 s) is different. It is a truncation imposed for convenience, and the robot’s state at that moment still has a future. The learning algorithms must treat the two cases differently: they bootstrap from the next state’s value after a truncation and not after a terminal event. The return from step tt is the discounted sum of the rewards that follow: Gt=Rt+1+γRt+2+γ2Rt+3+⋯=Rt+1+γGt+1.G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \dots = R_{t+1} + \gamma G_{t+1}. The second form, one reward plus the discounted return from the next step, is what the Bellman equations are built on. The discount factor is γ=0.99\gamma = 0.99. A reward kk steps ahead is weighted by γk\gamma^k, and these weights sum to 1/(1−γ)=1001/(1-\gamma) = 100 steps, or 20 s. A typical trip of 2 to 3 m takes 8 to 12 s at full speed, so the goal bonus is still visible from the start of most episodes.

A hand-written policy

Before learning anything, try a simple controller: turn toward the goal, and drive forward only when roughly facing it. π(s)=(vmax⁡max⁡(0,cos⁡β), clip⁡(2β,−ωmax⁡,ωmax⁡)).\pi(s) = \big(v_{\max}\max(0, \cos\beta),\ \operatorname{clip}(2\beta, -\omega_{\max}, \omega_{\max})\big). It is a deterministic policy: π(s)\pi(s) names one action, where a stochastic policy would give a distribution π(a∣s)\pi(a \mid s). It ignores the lidar entirely. The figure runs it from four start poses.
Output from cell 5 Left: four trajectories of the go-to-goal policy, each ending at the robot’s final pose. Right: the running sum of rewards on each trajectory, with its outcome and discounted return G0G_0. The goal bonus adds 20 at the last step and a collision subtracts 20. When the straight line to the goal passes an obstacle, the trajectory ends in a collision, because the policy never looks at the lidar. Over 300 random episodes it reaches the goal about a quarter of the time:

The value of a policy

The state-value function vπ(s)=Eπ[Gt∣St=s]v_\pi(s) = \mathbb E_\pi[G_t \mid S_t = s] says how good it is to start in ss and follow π\pi. Substituting Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1} gives the Bellman expectation equation. For a deterministic policy the sum over actions has one term: vπ(s)=Rsπ(s)+γ∑s′Pss′π(s) vπ(s′).v_\pi(s) = \mathcal R^{\pi(s)}_s + \gamma \sum_{s'} \mathcal P^{\pi(s)}_{ss'} \, v_\pi(s'). The value of a state is the expected reward of the policy’s action plus the discounted value of where that action leads. Policy evaluation solves this equation, either as a linear system or by applying it repeatedly as an update. Both need the sum over s′s'. Here s′s' ranges over a continuous 28-dimensional set whose density nobody can write, so neither is possible. Monte Carlo estimation avoids the sum. It works from the definition vπ(s)=Eπ[Gt∣St=s]v_\pi(s) = \mathbb E_\pi[G_t \mid S_t = s], as the Monte Carlo prediction section does: start the robot at a point, run the policy, record the discounted return, and average over a few runs. The map below does this for a grid of start positions and a fixed goal, with the robot always facing the goal at the start. The full state has 28 dimensions, so this map is a two-dimensional slice of vπv_\pi: it varies the start position and fixes everything else.
Output from cell 8 Estimated value of the go-to-goal policy for each start position, with the goal at the star. Gray disks are obstacles. Dark regions are starts from which the policy drives into an obstacle. The map shows what the policy does wrong. Behind each obstacle, as seen from the goal, lies a dark shadow: the straight path from there crosses the obstacle, the robot hits it, and the return is about −20-20, discounted by the time it took to get there. From the other starts the robot arrives, and the value is mostly the goal bonus discounted by the trip time, 20γT20\gamma^T. It is higher near the goal, where TT is small. A better policy would raise the value in those shadows by steering around the obstacle. Finding it is the control problem. The MDP chapter solves the control problem with dynamic programming, which needs a finite state set and the table Pss′a\mathcal P^a_{ss'}. The rest of this section builds both for this room and runs the chapter’s algorithms on them.

A finite model of the room

Dynamic programming needs three things this MDP does not have: a finite state set, a finite action set and the transition probabilities as a table. You can build all three if you give up the lidar state and use the robot’s true pose (x,y,ϕ)(x, y, \phi) instead. The pose is a Markov state for this simulator. The room is fixed, the goal is fixed, and the unicycle model computes the next pose from the current pose and the action alone. The 28 lidar numbers are a function of the pose, so the pose carries everything they carry and more. Fix the goal at (3.5,3.5)(3.5, 3.5) and cut the pose into cells:
  • the position into a grid of 36×3636 \times 36 squares, each 11 cm on a side,
  • the heading into 16 bins of 22.5 degrees.
That gives 36×36×16=20,73636 \times 36 \times 16 = 20{,}736 cells. About a fifth of them lie inside an obstacle or too close to a wall for the robot to fit, which leaves 16,229 states. Two more states absorb the episodes that end at the goal and in a collision. The actions are the five steering commands of the Q-learning navigation section, each a fixed pair (v,ω)(v, \omega). To estimate Pss′a\mathcal P^a_{ss'}, take 24 poses spread at random over cell ss, apply action aa to each for one control period, and record which cell each one lands in. Each landing counts for 1/241/24 of the probability. The mean of the 24 rewards estimates Rsa\mathcal R^a_s. One step moves the robot at most 5.2 cm, less than half a cell, so about a quarter of the samples stay in the state they started from. The table then has a self-loop probability, which the algorithms below handle like any other transition. The code below builds the table. It applies the simulator’s motion and reward equations to all the sampled poses at once.

Policy evaluation

Iterative policy evaluation turns the Bellman expectation equation into an update and applies it to every state at once: vk+1(s)=Rsπ(s)+γ∑s′Pss′π(s) vk(s′).v_{k+1}(s) = \mathcal R^{\pi(s)}_s + \gamma \sum_{s'} \mathcal P^{\pi(s)}_{ss'} \, v_k(s'). Each sweep is one backup of the whole value table. In the code, the sum over s′s' is the mean of vkv_k over the 24 sampled successors of ss, which is exactly the sum weighted by the estimated probabilities. The terminal states keep the value 0. The update stops when no state changes by more than 10−410^{-4}. To evaluate the go-to-goal controller, its own action at each of the 24 sampled poses is used. That gives the table Pss′π\mathcal P^\pi_{ss'} for this policy directly, without rounding its action to one of the five commands.
Output from cell 11 The value of go-to-goal computed two ways. Left: the Monte Carlo map from above, averaged returns of simulated episodes. Right: the solution of the Bellman expectation equation on the finite model, read at the same start points with the robot facing the goal. The two maps are computed in different ways. Monte Carlo averages complete returns and never uses the Bellman equation. Policy evaluation never runs an episode: it only passes one-step rewards backward through the table until the values are consistent. Both show the same shadows behind the obstacles, with a correlation of about 0.95 between them, so the Bellman equation describes the robot up to the error of the finite model. That error is visible in two places. Along the top of the room and to the right of the lower right obstacle, policy evaluation gives lower values. Starts there drive past an obstacle at close range. In the finite model the robot’s position is known only to within a cell, so each step spreads it over neighboring cells, and over a long path the spread reaches the obstacle. The streaks on the left come from the heading bins: a cell’s value averages over headings up to 22.5 degrees apart, and the go-to-goal path depends on the heading.

Policy improvement and policy iteration

Given vπv_\pi, the action value of taking aa in ss and following π\pi afterward is qπ(s,a)=Rsa+γ∑s′Pss′a vπ(s′).q_\pi(s, a) = \mathcal R^a_s + \gamma \sum_{s'} \mathcal P^a_{ss'} \, v_\pi(s'). Policy improvement makes the policy greedy with respect to it, π′(s)=arg⁡max⁡aqπ(s,a)\pi'(s) = \arg\max_a q_\pi(s, a). The policy improvement theorem guarantees vπ′(s)≥vπ(s)v_{\pi'}(s) \ge v_\pi(s) in every state. In the shadows, qπq_\pi tells the robot that turning away from the obstacle now is worth more than driving at the goal, because go-to-goal recovers from a detour but not from a collision. Policy iteration alternates the two steps: evaluate the current policy, make it greedy, and repeat until the greedy policy stops changing. Here it starts from go-to-goal. Each policy is also run in the continuous simulator on 300 episodes with random starts and the fixed goal. The robot looks up the cell that contains its true pose and applies that cell’s action. The guarantee does not cover the first step. Go-to-goal sends continuous commands, and the greedy step chooses only among the five discrete commands, so go-to-goal’s own action is not one of the candidates. The proof of the theorem needs the current action to stay available. Without it, the first greedy policy can lower the value of some states even when the average value rises. From the second step on, every policy uses the five commands, and the theorem applies to each step.
Output from cell 13 Value of each policy in policy iteration, on the same slice as before. From left: go-to-goal, the first two greedy policies, and the final policy. The titles give the fraction of 300 simulated episodes that reach the goal. A single improvement step removes most of the shadows. The first greedy policy turns away from obstacles that go-to-goal drives into, and the success rate rises from 0.34 to 0.81. After the second step the robot reaches the goal in all 300 episodes. The later iterations change fewer and fewer states and mostly shorten paths, which raises the value without changing the outcome. Policy iteration stops when the greedy policy no longer changes. Its value then satisfies the Bellman optimality equation, so the final policy is optimal for this finite MDP.

Value iteration

Value iteration reaches the same answer without keeping a policy. It applies the Bellman optimality backup to every state: vk+1(s)=max⁡a(Rsa+γ∑s′Pss′a vk(s′)).v_{k+1}(s) = \max_a \Big( \mathcal R^a_s + \gamma \sum_{s'} \mathcal P^a_{ss'} \, v_k(s') \Big). This is one evaluation sweep with the greedy step folded into it. Starting from v0=0v_0 = 0, the values converge to v∗v_*, and the greedy policy π∗(s)=arg⁡max⁡aq∗(s,a)\pi_*(s) = \arg\max_a q_*(s, a) is optimal.
Output from cell 15 Left: the largest change in any state’s value at each sweep of value iteration, on a log scale. Right: the optimal table policy driving the continuous robot from the four starts of the go-to-goal figure. The largest change does not fall at a steady rate. Each sweep carries the goal’s value one step further out, so values near the goal settle first. The largest change falls slowly for about 100 sweeps while the value spreads to the far side of the room, and drops quickly once it has reached the farthest states. Value iteration ends at the same values as policy iteration, and π∗\pi_* reaches the goal from every start, including the two from which go-to-goal collided.

What dynamic programming needed

Dynamic programming solved this navigation problem completely, but only after three changes to it. First, it needed a model. The table Pss′a\mathcal P^a_{ss'} took 16,229 × 5 × 24, almost 2 million, simulated steps, each started from a pose chosen by the program. A real robot cannot be placed at an arbitrary pose a million times. It can only follow its own trajectory. Second, it needed a finite state set. The pose has three numbers, and cutting them into cells already gave 20,736 states. The lidar state has 28 numbers, and no grid over them would fit in memory. Third, it needed the true pose and a fixed goal. The table policy is tied to this room and this goal. A new goal means a new table and a new solution, and on a real robot the pose comes from a localization system with errors. The sections of the TurtleBot navigation chapter each remove one of these assumptions. Q-learning drops the model: its update is a sample of the value-iteration backup, taken along the trajectories the robot actually drives. It also works from a coarse lidar and goal-bearing state, which serves any goal in any room but is no longer Markov. DDPG and TD3 drop the finite state and action sets. They replace the tables with neural networks over all 28 numbers and the continuous (v,ω)(v, \omega).
Found an error on this page? Report an issue.