> ## Documentation Index
> Fetch the complete documentation index at: https://aegean.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Robot Navigation as an MDP

> A TurtleBot3 driving to a goal, written as an MDP.

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pantelis/eng-ai-agents/blob/main/notebooks/reinforcement-learning/robot-navigation/navigation-mdp/index.ipynb)

The gridworld and the recycling robot in the [MDP chapter](https://aegean.ai/aiml-common/lectures/mdp/mdp-intro/index.md) 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](https://aegean.ai/aiml-common/lectures/reinforcement-learning/robot-navigation/q-learning-navigation/index.md), then with [DDPG](https://aegean.ai/aiml-common/lectures/reinforcement-learning/robot-navigation/ddpg-navigation/index.md) and its successor [TD3](https://aegean.ai/aiml-common/lectures/reinforcement-learning/robot-navigation/td3-navigation/index.md).

This is the task of the [turtlebot3\_drlnav](https://github.com/tomasvr/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.

> [accordion] Code
>
> ```python theme={null}
> import numpy as np
> import matplotlib.pyplot as plt
> from matplotlib.patches import Circle, Rectangle
>
> from cycler import cycler
> from matplotlib_inline.backend_inline import (
>     set_matplotlib_formats,
> )
>
> set_matplotlib_formats("svg")
> FIG_GRAY = "#808080"
> FIG_COLORS = [
>     "#0072B2",
>     "#D55E00",
>     "#009E73",
>     "#cb77a6",
>     "#c28600",
>     "#1d99e0",
>     "#7f7f7f",
> ]
> plt.rcParams.update(
>     {
>         "figure.facecolor": "none",
>         "axes.facecolor": "none",
>         "savefig.facecolor": "none",
>         "savefig.transparent": True,
>         "text.color": FIG_GRAY,
>         "axes.labelcolor": FIG_GRAY,
>         "axes.edgecolor": FIG_GRAY,
>         "xtick.color": FIG_GRAY,
>         "ytick.color": FIG_GRAY,
>         "grid.color": FIG_GRAY,
>         "grid.alpha": 0.25,
>         "legend.facecolor": "none",
>         "legend.edgecolor": FIG_GRAY,
>         "legend.framealpha": 0,
>         "axes.prop_cycle": cycler(color=FIG_COLORS),
>         "svg.hashsalt": "aiml",
>         "svg.fonttype": "path",
>     }
> )
> BLUE, ORANGE, GREEN, PINK, GOLD = FIG_COLORS[:5]
> ```

## 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 $v$ 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](https://aegean.ai/aiml-common/assignments/main/robotics-fall-2026/turtlebot-kinematics.md) 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.

> [accordion] Code
>
> ```python theme={null}
> V_MAX, W_MAX = 0.26, 1.82  # m/s, rad/s (Waffle limits)
> RADIUS = 0.2  # m, robot footprint
> DT = 0.2  # s, control period
> N_BEAMS = 24
> R_MIN, R_MAX = 0.12, 3.5  # m, lidar span
> ARENA = 4.0  # m, side of the square room
> GOAL_TOL = 0.25  # m
> T_MAX = 200  # steps per episode (40 s)
>
> # Obstacles: (x, y, radius) in meters
> OBSTACLES = np.array(
>     [
>         [1.2, 1.3, 0.25],
>         [2.8, 1.1, 0.20],
>         [2.0, 2.4, 0.30],
>         [3.0, 3.0, 0.20],
>     ]
> )
>
>
> def ray_cast(x, y, angles):
>     """Lidar range along each world-frame angle."""
>     dx, dy = np.cos(angles), np.sin(angles)
>     r = np.full(angles.shape, np.inf)
>     with np.errstate(divide="ignore", invalid="ignore"):
>         for wall, d, p in (
>             (0.0, dx, x),
>             (ARENA, dx, x),
>             (0.0, dy, y),
>             (ARENA, dy, y),
>         ):
>             t = (wall - p) / d
>             r = np.minimum(r, np.where(t > 0, t, np.inf))
>     for cx, cy, rho in OBSTACLES:
>         ox, oy = x - cx, y - cy
>         b = ox * dx + oy * dy
>         disc = b * b - (ox * ox + oy * oy - rho * rho)
>         t = -b - np.sqrt(np.maximum(disc, 0.0))
>         r = np.minimum(
>             r, np.where((disc >= 0) & (t > 0), t, np.inf)
>         )
>     return np.clip(r, R_MIN, R_MAX)
>
>
> def clearance(x, y):
>     """Distance from a point to the nearest surface."""
>     walls = min(x, ARENA - x, y, ARENA - y)
>     centers = np.hypot(OBSTACLES[:, 0] - x, OBSTACLES[:, 1] - y)
>     return min(walls, np.min(centers - OBSTACLES[:, 2]))
>
>
> class NavEnv:
>     """TurtleBot3 Waffle driving to a goal in a 4 m room."""
>
>     def __init__(self, seed=0, noise=0.02, collision_cost=20.0):
>         self.collision_cost = collision_cost
>         # Starts and goals. Each reset also seeds that episode's noise,
>         # so episode k is the same whatever the earlier episodes did.
>         self.rng = np.random.default_rng(seed)
>         self.noise = noise
>         self.beam_angles = np.linspace(
>             -np.pi, np.pi, N_BEAMS, endpoint=False
>         )
>
>     def _free_point(self, margin):
>         while True:
>             p = self.rng.uniform(margin, ARENA - margin, size=2)
>             if clearance(*p) > margin:
>                 return p
>
>     def reset(self, start=None, goal=None):
>         self.noise_rng = np.random.default_rng(self.rng.integers(2**63))
>         if goal is None:
>             goal = self._free_point(0.4)
>         self.goal = np.array(goal, float)
>         if start is None:
>             while True:
>                 p = self._free_point(0.4)
>                 if np.hypot(*(p - self.goal)) > 1.5:
>                     break
>             start = (*p, self.rng.uniform(-np.pi, np.pi))
>         self.pose = np.array(start, float)
>         self.prev = np.zeros(2)
>         self.t = 0
>         self.dist = self.goal_distance()
>         return self.observe()
>
>     def goal_distance(self):
>         return float(np.hypot(*(self.goal - self.pose[:2])))
>
>     def goal_bearing(self):
>         x, y, phi = self.pose
>         g = np.arctan2(self.goal[1] - y, self.goal[0] - x) - phi
>         return float(np.arctan2(np.sin(g), np.cos(g)))
>
>     def scan(self):
>         x, y, phi = self.pose
>         return ray_cast(x, y, phi + self.beam_angles)
>
>     def observe(self):
>         """The 28 numbers the agent receives."""
>         return np.concatenate(
>             [
>                 self.scan() / R_MAX,
>                 [
>                     min(self.dist, R_MAX) / R_MAX,
>                     self.goal_bearing() / np.pi,
>                     self.prev[0] / V_MAX,
>                     self.prev[1] / W_MAX,
>                 ],
>             ]
>         ).astype(np.float32)
>
>     def step(self, v, w):
>         v = float(np.clip(v, 0.0, V_MAX))
>         w = float(np.clip(w, -W_MAX, W_MAX))
>         vn = v + self.noise * self.noise_rng.standard_normal()
>         wn = w + self.noise * self.noise_rng.standard_normal()
>         x, y, phi = self.pose
>         x += vn * np.cos(phi) * DT
>         y += vn * np.sin(phi) * DT
>         phi = np.arctan2(
>             np.sin(phi + wn * DT), np.cos(phi + wn * DT)
>         )
>         self.pose = np.array([x, y, phi])
>         self.prev = np.array([v, w])
>         self.t += 1
>         d = self.goal_distance()
>         progress, self.dist = self.dist - d, d
>         r = 2.0 * progress - 0.05 * abs(w) / W_MAX - 0.01
>         event, terminated = None, False
>         if d < GOAL_TOL:
>             r, event, terminated = r + 20.0, "goal", True
>         elif clearance(x, y) < RADIUS:
>             r -= self.collision_cost
>             event, terminated = "collision", True
>         truncated = not terminated and self.t >= T_MAX
>         if truncated:
>             event = "timeout"
>         info = {"event": event}
>         return self.observe(), r, terminated, truncated, info
> ```

![Output from cell 3](https://mintcdn.com/aegeanaiinc/6_giSH0rl6DOPI2d/aiml-common/lectures/reinforcement-learning/robot-navigation/navigation-mdp/images/cell_3_output_1.svg?fit=max\&auto=format\&n=6_giSH0rl6DOPI2d\&q=85\&s=4445ab452333ddabea88bf4aa2a69b54)

*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, \phi)$. Its state $S_t$ is 28 numbers, each scaled to roughly $[-1, 1]$, the same layout as the turtlebot3\_drlnav state:

* the 24 lidar ranges,
* the distance $d_t$ to the goal and its bearing $\beta_t$ relative to the heading,
* the previous command $(v_{t-1}, \omega_{t-1})$.

The state set $\mathcal S$ is therefore a region of $\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](https://aegean.ai/aiml-common/lectures/rse/amcl/index.md) 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](https://aegean.ai/aiml-common/lectures/mdp/mdp-intro/index.md) 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 $A_t = (v_t, \omega_t)$ is a forward speed and a turn rate, held for one control period of $\Delta t = 0.2$ s. The action set $\mathcal A$ is the rectangle $[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](https://aegean.ai/aiml-common/lectures/reinforcement-learning/robot-navigation/q-learning-navigation/index.md) replaces it with five steering commands, and the [DDPG section](https://aegean.ai/aiml-common/lectures/reinforcement-learning/robot-navigation/ddpg-navigation/index.md) 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:

$$
\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 $\tilde v_t = v_t + \epsilon_v$ and $\tilde\omega_t = \omega_t + \epsilon_\omega$, with $\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' \mid s, a)$. It is the continuous counterpart of the [MDP chapter's](https://aegean.ai/aiml-common/lectures/mdp/mdp-intro/index.md) transition probabilities

$$
\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 $\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

$$
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 $s$ and $a$. The Bellman equations below use its mean, the expected reward $\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(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(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](https://aegean.ai/aiml-common/lectures/reinforcement-learning/robot-navigation/td3-navigation/index.md) 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 $t$ is the discounted sum of the rewards that follow:

$$
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 $\gamma = 0.99$. A reward $k$ steps ahead is weighted by $\gamma^k$, and these weights sum to $1/(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.

$$
\pi(s) = \big(v_{\max}\max(0, \cos\beta),\ \operatorname{clip}(2\beta, -\omega_{\max}, \omega_{\max})\big).
$$

It is a deterministic policy: $\pi(s)$ names one action, where a stochastic policy would give a distribution $\pi(a \mid s)$. It ignores the lidar entirely. The figure runs it from four start poses.

> [accordion] Code
>
> ```python theme={null}
> def go_to_goal(env):
>     b = env.goal_bearing()
>     v = V_MAX * max(0.0, np.cos(b))
>     return v, float(np.clip(2.0 * b, -W_MAX, W_MAX))
>
>
> def rollout(env, policy, start=None, goal=None):
>     env.reset(start=start, goal=goal)
>     poses, rewards = [env.pose.copy()], []
>     while True:
>         _, r, term, trunc, info = env.step(*policy(env))
>         poses.append(env.pose.copy())
>         rewards.append(r)
>         if term or trunc:
>             return np.array(poses), np.array(rewards), info
> ```

![Output from cell 5](https://mintcdn.com/aegeanaiinc/6_giSH0rl6DOPI2d/aiml-common/lectures/reinforcement-learning/robot-navigation/navigation-mdp/images/cell_5_output_1.svg?fit=max\&auto=format\&n=6_giSH0rl6DOPI2d\&q=85\&s=13923cf4732951e17fb657588b61ec92)

*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 $G_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:

> [accordion] Code
>
> ```python theme={null}
> def success_rate(policy, n=300, seed=99):
>     env = NavEnv(seed=seed)
>     events = {"goal": 0, "collision": 0, "timeout": 0}
>     for _ in range(n):
>         *_, info = rollout(env, policy)
>         events[info["event"]] += 1
>     return {k: v / n for k, v in events.items()}
>
>
> print(success_rate(go_to_goal))
> ```

```output theme={null}
{'goal': 0.26, 'collision': 0.74, 'timeout': 0.0}
```

## The value of a policy

The state-value function $v_\pi(s) = \mathbb E_\pi[G_t \mid S_t = s]$ says how good it is to start in $s$ and follow $\pi$. Substituting $G_t = R_{t+1} + \gamma G_{t+1}$ gives the [Bellman expectation equation](https://aegean.ai/aiml-common/lectures/mdp/bellman-expectation-backup/index.md). For a deterministic policy the sum over actions has one term:

$$
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](https://aegean.ai/aiml-common/lectures/mdp/policy-evaluation/index.md) solves this equation, either as a linear system or by applying it repeatedly as an update. Both need the sum over $s'$. Here $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_\pi(s) = \mathbb E_\pi[G_t \mid S_t = s]$, as the [Monte Carlo prediction](https://aegean.ai/aiml-common/lectures/reinforcement-learning/value-based-algorithms/prediction/monte-carlo.md) 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_\pi$: it varies the start position and fixes everything else.

> [accordion] Code
>
> ```python theme={null}
> def mc_value(policy, goal, n_grid=36, n_runs=4, seed=0):
>     env = NavEnv(seed=seed)
>     xs = np.linspace(0.15, ARENA - 0.15, n_grid)
>     V = np.full((n_grid, n_grid), np.nan)
>     for i, y in enumerate(xs):
>         for j, x in enumerate(xs):
>             if clearance(x, y) < RADIUS + 0.02:
>                 continue
>             phi = np.arctan2(goal[1] - y, goal[0] - x)
>             G = []
>             for _ in range(n_runs):
>                 _, rewards, _ = rollout(
>                     env, policy, (x, y, phi), goal
>                 )
>                 disc = gamma ** np.arange(len(rewards))
>                 G.append(np.sum(disc * rewards))
>             V[i, j] = np.mean(G)
>     return xs, V
>
>
> goal = (3.5, 3.5)
> xs, V_mc = mc_value(go_to_goal, goal)
> ```

![Output from cell 8](https://mintcdn.com/aegeanaiinc/6_giSH0rl6DOPI2d/aiml-common/lectures/reinforcement-learning/robot-navigation/navigation-mdp/images/cell_8_output_1.svg?fit=max\&auto=format\&n=6_giSH0rl6DOPI2d\&q=85\&s=7928ddda4f1402115cc0e0b029a1ae0b)

*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$, 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\gamma^T$. It is higher near the goal, where $T$ 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 $\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, \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)$ and cut the pose into cells:

* the position into a grid of $36 \times 36$ squares, each 11 cm on a side,
* the heading into 16 bins of 22.5 degrees.

That gives $36 \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](https://aegean.ai/aiml-common/lectures/reinforcement-learning/robot-navigation/q-learning-navigation/index.md), each a fixed pair $(v, \omega)$.

To estimate $\mathcal P^a_{ss'}$, take 24 poses spread at random over cell $s$, apply action $a$ to each for one control period, and record which cell each one lands in. Each landing counts for $1/24$ of the probability. The mean of the 24 rewards estimates $\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.

> [accordion] Code
>
> ```python theme={null}
> GOAL = np.array([3.5, 3.5])
> N_XY, N_H = 36, 16  # position cells per side, heading bins
> CELL, H_BIN = ARENA / N_XY, 2 * np.pi / N_H
> N_S = N_XY * N_XY * N_H
> GOAL_S, CRASH_S = N_S, N_S + 1  # absorbing terminal states
> K = 24  # sampled transitions per state and action
> W_ACT = np.array([-1.5, -0.75, 0.0, 0.75, 1.5])
> V_ACT = np.array([0.10, 0.18, 0.26, 0.18, 0.10])
>
>
> def state_index(x, y, phi):
>     """Index of the grid state that contains a pose."""
>     i = np.clip(np.floor(np.asarray(x) / CELL), 0, N_XY - 1)
>     j = np.clip(np.floor(np.asarray(y) / CELL), 0, N_XY - 1)
>     h = np.floor((np.asarray(phi) + np.pi) / H_BIN) % N_H
>     return ((j * N_XY + i) * N_H + h).astype(int)
>
>
> def clearance_many(x, y):
>     """clearance() for arrays of points."""
>     c = np.minimum.reduce([x, ARENA - x, y, ARENA - y])
>     for cx, cy, rho in OBSTACLES:
>         c = np.minimum(c, np.hypot(cx - x, cy - y) - rho)
>     return c
>
>
> def step_many(x, y, phi, v, w, rng):
>     """NavEnv.step for arrays of poses, with the goal fixed."""
>     vn = v + 0.02 * rng.standard_normal(x.shape)
>     wn = w + 0.02 * rng.standard_normal(x.shape)
>     x2 = x + vn * np.cos(phi) * DT
>     y2 = y + vn * np.sin(phi) * DT
>     phi2 = np.arctan2(np.sin(phi + wn * DT), np.cos(phi + wn * DT))
>     d = np.hypot(GOAL[0] - x, GOAL[1] - y)
>     d2 = np.hypot(GOAL[0] - x2, GOAL[1] - y2)
>     r = 2.0 * (d - d2) - 0.05 * np.abs(w) / W_MAX - 0.01
>     goal = d2 < GOAL_TOL
>     crash = ~goal & (clearance_many(x2, y2) < RADIUS)
>     r = r + 20.0 * goal - 20.0 * crash
>     s2 = np.where(
>         goal, GOAL_S, np.where(crash, CRASH_S, state_index(x2, y2, phi2))
>     )
>     return s2, r
>
>
> # K random poses in every cell; resample those inside an obstacle
> rng = np.random.default_rng(0)
> s = np.arange(N_S)
> ci, cj, ch = (s // N_H) % N_XY, s // (N_H * N_XY), s % N_H
> x, y, phi = (np.empty((N_S, K)) for _ in range(3))
> free = np.zeros((N_S, K), bool)
> for _ in range(100):
>     redo = ~free
>     u = rng.random((3, N_S, K))
>     x[redo] = ((ci[:, None] + u[0]) * CELL)[redo]
>     y[redo] = ((cj[:, None] + u[1]) * CELL)[redo]
>     phi[redo] = (-np.pi + (ch[:, None] + u[2]) * H_BIN)[redo]
>     free = clearance_many(x, y) >= RADIUS
> valid = free.any(axis=1)  # cells the robot can occupy
> first = np.argmax(free, axis=1)[:, None]
> x = np.where(free, x, np.take_along_axis(x, first, 1))
> y = np.where(free, y, np.take_along_axis(y, first, 1))
>
> # The model: K successor states and the mean reward for each (s, a)
> NEXT = np.empty((N_S, 5, K), dtype=np.int32)
> R = np.empty((N_S, 5))
> for a in range(5):
>     s2, r = step_many(x, y, phi, V_ACT[a], W_ACT[a], rng)
>     NEXT[:, a], R[:, a] = s2, r.mean(axis=1)
>
> stay = (NEXT == s[:, None, None])[valid].mean()
> print(f"{valid.sum()} states, self-loop probability {stay:.2f}")
> ```

```output theme={null}
16229 states, self-loop probability 0.27
```

## Policy evaluation

[Iterative policy evaluation](https://aegean.ai/aiml-common/lectures/mdp/policy-evaluation/index.md) turns the Bellman expectation equation into an update and applies it to every state at once:

$$
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'$ is the mean of $v_k$ over the 24 sampled successors of $s$, 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^{-4}$.

To evaluate the go-to-goal controller, its own action at each of the 24 sampled poses is used. That gives the table $\mathcal P^\pi_{ss'}$ for this policy directly, without rounding its action to one of the five commands.

> [accordion] Code
>
> ```python theme={null}
> def extend(v):
>     """Append the two terminal states, whose value is 0."""
>     return np.append(v, [0.0, 0.0])
>
>
> def evaluate(nxt, r, v=None, tol=1e-4):
>     """Iterative policy evaluation: sweep until the largest change < tol."""
>     v = np.zeros(N_S) if v is None else v
>     for sweep in range(1, 10_000):
>         v_new = r + gamma * extend(v)[nxt].mean(axis=-1)
>         v_new[~valid] = 0.0
>         if np.abs(v_new - v).max() < tol:
>             return v_new, sweep
>         v = v_new
>
>
> # Transitions under go-to-goal, from the same sampled poses
> b = np.arctan2(GOAL[1] - y, GOAL[0] - x) - phi
> b = np.arctan2(np.sin(b), np.cos(b))
> v_cmd = V_MAX * np.maximum(0.0, np.cos(b))
> w_cmd = np.clip(2.0 * b, -W_MAX, W_MAX)
> next_gtg, r_gtg = step_many(x, y, phi, v_cmd, w_cmd, rng)
> v_gtg, sweeps = evaluate(next_gtg, r_gtg.mean(axis=1))
> print("sweeps to converge:", sweeps)
>
>
> def value_slice(v):
>     """v at the Monte Carlo map's start points, robot facing the goal."""
>     X, Y = np.meshgrid(xs, xs)
>     face = np.arctan2(GOAL[1] - Y, GOAL[0] - X)
>     out = v[state_index(X, Y, face)]
>     return np.where(np.isnan(V_mc), np.nan, out)
>
>
> dp_map = value_slice(v_gtg)
> ok = ~np.isnan(V_mc)
> print(
>     "correlation with Monte Carlo:",
>     round(np.corrcoef(dp_map[ok], V_mc[ok])[0, 1], 3),
> )
> print(
>     "mean absolute difference:",
>     round(np.abs(dp_map[ok] - V_mc[ok]).mean(), 2),
> )
> ```

```output theme={null}
sweeps to converge: 130
correlation with Monte Carlo: 0.945
mean absolute difference: 4.14
```

![Output from cell 11](https://mintcdn.com/aegeanaiinc/6_giSH0rl6DOPI2d/aiml-common/lectures/reinforcement-learning/robot-navigation/navigation-mdp/images/cell_11_output_1.svg?fit=max\&auto=format\&n=6_giSH0rl6DOPI2d\&q=85\&s=0e3f8bd63ed0f6d133f2181c0bcf6e93)

*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_\pi$, the action value of taking $a$ in $s$ and following $\pi$ afterward is

$$
q_\pi(s, a) = \mathcal R^a_s + \gamma \sum_{s'} \mathcal P^a_{ss'} \, v_\pi(s').
$$

[Policy improvement](https://aegean.ai/aiml-common/lectures/mdp/policy-improvement/index.md) makes the policy greedy with respect to it, $\pi'(s) = \arg\max_a q_\pi(s, a)$. The policy improvement theorem guarantees $v_{\pi'}(s) \ge v_\pi(s)$ in every state. In the shadows, $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](https://aegean.ai/aiml-common/lectures/mdp/dynamic-programming-algorithms/policy-iteration/index.md) 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.

> [accordion] Code
>
> ```python theme={null}
> def q_values(v):
>     """q(s, a) for every state and action, from a value table."""
>     return R + gamma * extend(v)[NEXT].mean(axis=2)
>
>
> def table_policy(pi):
>     """Run a table policy on the continuous robot."""
>     def act(env):
>         a = pi[state_index(*env.pose)]
>         return V_ACT[a], W_ACT[a]
>     return act
>
>
> def fixed_goal_success(policy, n=300, seed=99):
>     env = NavEnv(seed=seed)
>     hits = [rollout(env, policy, None, GOAL)[2]["event"] == "goal"
>             for _ in range(n)]
>     return np.mean(hits)
>
>
> rows = s[valid]
> history = [("go-to-goal", v_gtg, fixed_goal_success(go_to_goal))]
> v, pi = v_gtg, None
> while True:
>     greedy_pi = q_values(v).argmax(axis=1)  # policy improvement
>     if pi is not None and np.array_equal(greedy_pi[rows], pi[rows]):
>         break
>     changed = "" if pi is None else (
>         f"{(greedy_pi[rows] != pi[rows]).sum()} states changed, ")
>     pi = greedy_pi
>     v, sweeps = evaluate(NEXT[s, pi], R[s, pi], v)  # evaluation
>     history.append((f"pi_{len(history)}", v, fixed_goal_success(
>         table_policy(pi))))
>     print(f"pi_{len(history) - 1}: {changed}"
>           f"{sweeps} sweeps, mean value {v[valid].mean():.2f}, "
>           f"success {history[-1][2]:.2f}")
> v_pi_final, pi_final = v, pi
> print(f"go-to-goal: mean value {v_gtg[valid].mean():.2f}, "
>       f"success {history[0][2]:.2f}")
> ```

```output theme={null}
pi_1: 290 sweeps, mean value 3.00, success 0.81
pi_2: 7294 states changed, 166 sweeps, mean value 10.23, success 1.00
pi_3: 3293 states changed, 125 sweeps, mean value 11.06, success 1.00
pi_4: 1691 states changed, 110 sweeps, mean value 11.21, success 1.00
pi_5: 594 states changed, 75 sweeps, mean value 11.24, success 1.00
pi_6: 138 states changed, 46 sweeps, mean value 11.24, success 1.00
pi_7: 18 states changed, 37 sweeps, mean value 11.24, success 1.00
pi_8: 2 states changed, 9 sweeps, mean value 11.24, success 1.00
go-to-goal: mean value -4.62, success 0.34
```

![Output from cell 13](https://mintcdn.com/aegeanaiinc/6_giSH0rl6DOPI2d/aiml-common/lectures/reinforcement-learning/robot-navigation/navigation-mdp/images/cell_13_output_1.svg?fit=max\&auto=format\&n=6_giSH0rl6DOPI2d\&q=85\&s=3390938db74835f9d37bff5b159b7032)

*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](https://aegean.ai/aiml-common/lectures/mdp/dynamic-programming-algorithms/value-iteration/index.md) reaches the same answer without keeping a policy. It applies the [Bellman optimality backup](https://aegean.ai/aiml-common/lectures/mdp/bellman-optimality-backup/index.md) to every state:

$$
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 $v_0 = 0$, the values converge to $v_*$, and the greedy policy $\pi_*(s) = \arg\max_a q_*(s, a)$ is optimal.

> [accordion] Code
>
> ```python theme={null}
> v = np.zeros(N_S)
> residual = []
> while True:
>     v_new = q_values(v).max(axis=1)  # Bellman optimality backup
>     v_new[~valid] = 0.0
>     residual.append(np.abs(v_new - v).max())
>     v = v_new
>     if residual[-1] < 1e-4:
>         break
> v_star = v
> pi_star = q_values(v_star).argmax(axis=1)
> print("sweeps:", len(residual))
> print(
>     "largest difference from policy iteration's value:",
>     f"{np.abs(v_star - v_pi_final).max():.4f}",
> )
> print("success of pi_*:", fixed_goal_success(table_policy(pi_star)))
> ```

```output theme={null}
sweeps: 164
largest difference from policy iteration's value: 0.0004
success of pi_*: 1.0
```

![Output from cell 15](https://mintcdn.com/aegeanaiinc/6_giSH0rl6DOPI2d/aiml-common/lectures/reinforcement-learning/robot-navigation/navigation-mdp/images/cell_15_output_1.svg?fit=max\&auto=format\&n=6_giSH0rl6DOPI2d\&q=85\&s=2b4c2835948589b851a4b0bf365c8e61)

*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 $\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](https://aegean.ai/aiml-common/lectures/reinforcement-learning/robot-navigation/q-learning-navigation/index.md) 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](https://aegean.ai/aiml-common/lectures/reinforcement-learning/robot-navigation/ddpg-navigation/index.md) and [TD3](https://aegean.ai/aiml-common/lectures/reinforcement-learning/robot-navigation/td3-navigation/index.md) drop the finite state and action sets. They replace the tables with neural networks over all 28 numbers and the continuous $(v, \omega)$.

***

Found an error on this page? [Report an issue](https://github.com/aegean-ai/eaia-feedback/issues/new?template=page-issue.yml\&page=/aiml-common/lectures/reinforcement-learning/robot-navigation/navigation-mdp).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.