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

# Navigation with Imperfect State Estimation

> The navigation policies driven by an EKF SLAM pose estimate.

[![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-ekf-slam/index.ipynb)

The [navigation MDP](https://aegean.ai/aiml-common/lectures/reinforcement-learning/robot-navigation/navigation-mdp/index.md) assumed exact sensor readings and gave each policy the robot's true pose. A physical robot has neither. It must infer its pose from noisy wheel odometry and lidar, and the error changes as it moves. The experiments here keep the same room, robot, and policies but replace the true pose with a pose estimate.

[EKF SLAM](https://aegean.ai/aiml-common/lectures/rse/ekf-slam/index.md) estimates the pose while mapping landmarks. Dead reckoning, which integrates wheel odometry without correcting it from lidar, provides a useful comparison. Results obtained from the true pose remain in the tables as a baseline. In the final experiment, QMDP weights actions over the filter's Gaussian belief, so pose uncertainty affects the choice.

> [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 room and the robot

The experiment uses the same environment as the finite navigation MDP: a 4 m square room, four circular obstacles, and a goal at $(3.5,3.5)$. The TurtleBot3 Waffle is represented by a disk with a 0.2 m radius and follows the same noisy unicycle model. Each commanded speed receives Gaussian noise with standard deviation 0.02. Reaching within 0.25 m of the goal or colliding ends the episode; otherwise it is truncated after 200 steps of 0.2 s.

The simulator also records the achieved twist $(\tilde v_t,\tilde\omega_t)$, including actuation noise, because that motion determines the wheel-encoder readings. The dynamics are unchanged from the navigation MDP; only the sensing and state estimation are new.

> [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)
> GOAL = np.array([3.5, 3.5])
>
> # 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):
>         """Create the environment.
>
>         Args:
>             seed: seed for starts, goals and the motion noise of each episode.
>             noise: standard deviation of the noise added to v and w at each step.
>             collision_cost: penalty for a collision (kept for the same interface as the MDP page)."""
>         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
>
>     def _free_point(self, margin):
>         """Random point in the room at least `margin` meters from every wall and obstacle."""
>         while True:
>             p = self.rng.uniform(margin, ARENA - margin, size=2)
>             if clearance(*p) > margin:
>                 return p
>
>     def reset(self, start=None, goal=None):
>         """Start a new episode from start and goal, or from random ones if they are 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.t = 0
>
>     def goal_distance(self):
>         """Distance from the robot's position to the goal, in meters."""
>         return float(np.hypot(*(self.goal - self.pose[:2])))
>
>     def step(self, v, w):
>         """Apply the command (v, w) for one control period with motion noise.
>
>         The twist the robot really achieved is stored in self.twist.
>
>         Returns:
>             'goal', 'collision', 'timeout', or None while the episode continues."""
>         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()
>         self.twist = np.array([vn, wn])  # what the robot really did
>         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.t += 1
>         if self.goal_distance() < GOAL_TOL:
>             return "goal"
>         if clearance(x, y) < RADIUS:
>             return "collision"
>         if self.t >= T_MAX:
>             return "timeout"
>         return None
> ```

## Wheel odometry

The Waffle's nominal wheel radius is $r=0.033$ m, and each wheel sits $d=0.1435$ m from the centerline. Under the [differential-drive model](https://aegean.ai/aiml-common/lectures/kinematics/nonholonomic-robots/index.md), a twist $(v,\omega)$ corresponds to $u_L=(v-d\omega)/r$ and $u_R=(v+d\omega)/r$. The encoders report the wheel rotations associated with the achieved twist $(\tilde v_t,\tilde\omega_t)$ plus noise. As in the EKF SLAM chapter, the standard deviation for a wheel rotating at $u$ is $\alpha|u|+\beta$, with $\alpha=0.05$ and $\beta=0.1$ rad/s.

Odometry converts the reported wheel speeds back to a twist using the nominal radius. This conversion is exact only when both physical wheels have radius $r$. Wear or an uneven load can change the effective radius; model the right wheel as $r_R=(1+\delta)r$, following the example in [EKF localization](https://aegean.ai/aiml-common/lectures/rse/ekf-localization/index.md#motion-model). Its angular speed is then

$$
u_R = \frac{\tilde v_t + d\,\tilde\omega_t}{(1 + \delta)\, r},
$$

Odometry multiplies this measurement by $r$, producing a distance error by the factor $1/(1+\delta)$. Because the bias keeps the same sign, it accumulates over the trajectory instead of averaging away. The filter does not include $\delta$ in its model.

The filter's motion model $g$ integrates the twist from the reported wheel speeds over one step, the same Euler step the simulator takes. Its Jacobians $G_t$ (with respect to the pose) and $V_t$ (with respect to the wheel speeds) give the motion noise $Q_t = V_t M_t V_t^\top$, where $M_t$ is the diagonal covariance of the encoder noise. The course writes motion noise as $Q_t$ and measurement noise as $R_t$, the reverse of the letters in Thrun, Burgard and Fox (Thrun et al., 2005).

> [accordion] Code
>
> ```python theme={null}
> r_w, d = 0.033, 0.1435  # nominal wheel radius, half the wheel separation (m)
> ALPHA_U, BETA_U = 0.05, 0.1  # encoder noise: alpha |u| + beta (rad/s)
>
>
> def wrap(angle):
>     """Wrap an angle to [-pi, pi)."""
>     return (angle + np.pi) % (2 * np.pi) - np.pi
>
>
> def twist(a):
>     """Twist (v, w) that odometry computes from wheel speeds a."""
>     u_L, u_R = a
>     return r_w / 2 * (u_L + u_R), r_w / (2 * d) * (u_R - u_L)
>
>
> def encoders(vw, rng, delta, alpha=ALPHA_U, beta=BETA_U):
>     """Wheel speeds reported for the achieved twist vw, when the right
>     wheel's true radius is (1 + delta) r."""
>     v, w = vw
>     u = np.array([(v - d * w) / r_w, (v + d * w) / (r_w * (1 + delta))])
>     return u + rng.normal(0, alpha * np.abs(u) + beta)
>
>
> def wheel_noise(a, alpha=ALPHA_U, beta=BETA_U):
>     """M_t, the covariance of the encoder noise."""
>     return np.diag((alpha * np.abs(a) + beta) ** 2)
>
>
> def g(a, s):
>     """Motion model: the pose after one control period from pose s with wheel speeds a."""
>     v, w = twist(a)
>     x, y, th = s
>     return np.array(
>         [
>             x + v * DT * np.cos(th),
>             y + v * DT * np.sin(th),
>             wrap(th + w * DT),
>         ]
>     )
>
>
> def G(a, s):
>     """Jacobian of the motion model g with respect to the pose s."""
>     v, _ = twist(a)
>     th = s[2]
>     return np.array(
>         [
>             [1, 0, -v * DT * np.sin(th)],
>             [0, 1, v * DT * np.cos(th)],
>             [0, 0, 1],
>         ]
>     )
>
>
> def V(a, s):
>     """Jacobian of g with respect to the wheel speeds a; it maps the encoder noise M_t into pose noise."""
>     th = s[2]
>     dg_dvw = np.array(
>         [[np.cos(th) * DT, 0], [np.sin(th) * DT, 0], [0, DT]]
>     )
>     dvw_du = np.array(
>         [[r_w / 2, r_w / 2], [-r_w / (2 * d), r_w / (2 * d)]]
>     )
>     return dg_dvw @ dvw_du
> ```

## Landmarks from the lidar

Each lidar scan contains 360 ranges, one per degree, with 1 cm Gaussian range noise. The four circular obstacles serve as landmarks; the walls do not. Their radii range from 0.20 to 0.30 m, compared with the 0.10 m pillars used in the EKF SLAM chapter, so the detection front end needs two adjustments.

A range jump larger than 15 cm separates adjacent clusters. A candidate landmark must curve toward the robot: its midpoint must lie at least 8 cm in front of the chord joining its endpoints. Flat wall segments and inward-facing corners fail this test. A geometric circle fit is then applied to the cluster. The detector accepts radii from 0.1 to 0.4 m and centers within 2.5 m, and reports the center's range and bearing. Minimizing radial distances avoids the roughly 1 cm inward bias produced by an algebraic fit on these short arcs.

> [accordion] Code
>
> ```python theme={null}
> SIGMA_LIDAR = 0.01  # m, range noise
> N_SCAN = 360
> MAX_RANGE = 2.5  # m, landmarks farther than this are not used
> SCAN_ANGLES = np.arange(N_SCAN) * 2 * np.pi / N_SCAN
>
>
> def fit_circle(p):
>     """Circle that minimizes the squared distances of the points p
>     (n x 2) to it: center and radius."""
>     # an algebraic fit for a start, then Gauss-Newton on the distances
>     A = np.column_stack([p, np.ones(len(p))])
>     c, *_ = np.linalg.lstsq(A, (p**2).sum(axis=1), rcond=None)
>     center = c[:2] / 2
>     rho = np.sqrt(c[2] + center @ center)
>     for _ in range(5):
>         diff = p - center
>         dist = np.linalg.norm(diff, axis=1)
>         J = np.column_stack([-diff / dist[:, None], -np.ones(len(p))])
>         step, *_ = np.linalg.lstsq(J, rho - dist, rcond=None)
>         center, rho = center + step[:2], rho + step[2]
>     return center, rho
>
>
> def scan(s, rng):
>     """One 360-beam scan from pose s."""
>     ranges = ray_cast(s[0], s[1], s[2] + SCAN_ANGLES)
>     return ranges + rng.normal(0, SIGMA_LIDAR, N_SCAN)
>
>
> def landmarks_in_scan(ranges):
>     """Range and bearing of each obstacle center found in a scan, and
>     the fitted circles in the robot frame."""
>     breaks = np.flatnonzero(
>         np.abs(np.diff(np.r_[ranges, ranges[0]])) > 0.15
>     )
>     z, circles = [], []
>     if len(breaks) == 0:
>         return z, circles
>     starts = breaks + 1
>     for a, b in zip(starts, np.r_[starts[1:], starts[0] + N_SCAN]):
>         idx = np.arange(a, b) % N_SCAN
>         if len(idx) < 5:
>             continue
>         rr, bb = ranges[idx], SCAN_ANGLES[idx]
>         pts = rr[:, None] * np.column_stack([np.cos(bb), np.sin(bb)])
>         # bulge: how far the cluster's middle lies in front of the
>         # line through its end points, toward the robot
>         p0, p1 = pts[0], pts[-1]
>         n = np.array([p0[1] - p1[1], p1[0] - p0[0]])
>         n /= np.linalg.norm(n)
>         if n @ p0 > 0:
>             n = -n
>         if np.max((pts - p0) @ n) < 0.08:
>             continue  # a wall or a corner
>         center, rho = fit_circle(pts)
>         dist = np.linalg.norm(center)
>         if not 0.1 < rho < 0.4 or dist > MAX_RANGE:
>             continue
>         z.append(np.array([dist, np.arctan2(center[1], center[0])]))
>         circles.append((center, rho))
>     return z, circles
>
>
> def lidar_landmarks(s, rng, fov=2 * np.pi):
>     """Landmarks in one scan from pose s. With fov < 2 pi, the lidar sees
>     only the sector of that width ahead of the robot, and an obstacle
>     whose outline the sector's edge cuts is dropped."""
>     z, circles = landmarks_in_scan(scan(s, rng))
>     if fov >= 2 * np.pi:
>         return z
>     return [
>         z_i
>         for z_i, (_, rho) in zip(z, circles)
>         if abs(z_i[1]) + np.arcsin(min(rho / z_i[0], 1.0)) <= fov / 2
>     ]
> ```

![Output from cell 5](https://mintcdn.com/aegeanaiinc/A5GqO6yYMxo7BV4G/aiml-common/lectures/reinforcement-learning/robot-navigation/navigation-ekf-slam/images/cell_5_output_1.svg?fit=max\&auto=format\&n=A5GqO6yYMxo7BV4G\&q=85\&s=4179627bd65006161bebbd28b76f84de)

*A simulated scan from the blue pose. Gray points show the 360 lidar returns; orange circles show accepted fits, and crosses mark their reported centers. The dashed circle indicates the 2.5 m landmark cutoff.*

Measurement noise $R_t$ is calibrated by comparing the reported range and bearing with the true obstacle centers at 400 random poses:

> [accordion] Code
>
> ```python theme={null}
> def front_end_errors(n_poses=400, seed=1):
>     """Errors of the lidar landmark front end at random free poses.
>
>     For each landmark found in a scan, compares its measured range and bearing
>     with those of the nearest true obstacle center.
>
>     Returns:
>         (errs, per_scan): an array of (range error, bearing error) rows and the
>         mean number of landmarks found per scan."""
>     rng = np.random.default_rng(seed)
>     errs, per_scan = [], []
>     for _ in range(n_poses):
>         while True:
>             s = np.r_[rng.uniform(0.3, 3.7, 2), rng.uniform(-np.pi, np.pi)]
>             if clearance(*s[:2]) > RADIUS:
>                 break
>         z = lidar_landmarks(s, rng)
>         per_scan.append(len(z))
>         for r_i, b_i in z:
>             p = s[:2] + r_i * np.array([np.cos(b_i + s[2]), np.sin(b_i + s[2])])
>             k = np.argmin(np.linalg.norm(OBSTACLES[:, :2] - p, axis=1))
>             dx, dy = OBSTACLES[k, :2] - s[:2]
>             errs.append(
>                 [r_i - np.hypot(dx, dy), wrap(b_i - np.arctan2(dy, dx) + s[2])]
>             )
>     return np.array(errs), np.mean(per_scan)
>
>
> errs, per_scan = front_end_errors()
> print(f"landmarks per scan: {per_scan:.2f}")
> print(
>     f"range error mean {1000 * errs[:, 0].mean():+.1f} mm, "
>     f"std {1000 * errs[:, 0].std():.1f} mm; "
>     f"bearing error std {np.degrees(errs[:, 1].std()):.2f} deg"
> )
> ```

```output theme={null}
landmarks per scan: 2.94
range error mean -1.7 mm, std 8.4 mm; bearing error std 0.13 deg
```

The detector returns an average of 2.94 landmarks per scan, so the filter usually observes three obstacles at once. Range error has a mean of $-1.7$ mm and a standard deviation of 8.4 mm; bearing error has a standard deviation of 0.13 degrees. The filter retains the more conservative noise values from the EKF SLAM chapter: 2 cm for range and 0.75 degrees for bearing. This larger $R_t$ reduces the weight of each observation and broadens the association gate.

## EKF SLAM on the navigation run

The filter is the EKF SLAM section's step, unchanged. The prediction moves the pose with $g$ and grows the covariance with $G_t$ and $Q_t$. Each landmark observation is then associated with the mapped landmark at the smallest Mahalanobis distance, or starts a new landmark with `add_landmark` if no mapped landmark passes the 99.9% gate. The correspondences are unknown, as in that section.

Initialization uses the true start pose with zero pose covariance, aligning the map frame with the room and making the goal at $(3.5,3.5)$ known in filter coordinates. The filter processes the first scan before any motion. Those initial landmarks are placed from an exact pose, so the map orientation inherits only the bearing noise in that scan. Delaying the first correction until after motion would rotate the entire map by the first-step heading error, which later relative landmark measurements could not remove. Dead reckoning shares the prediction step but omits all corrections; its covariance records how quickly the encoder-noise model expects the pose to drift.

> [accordion] Code
>
> ```python theme={null}
> def h_lm(s, m_k):
>     """Range and bearing from pose s to a landmark at m_k."""
>     dx, dy = m_k - s[:2]
>     return np.array(
>         [np.hypot(dx, dy), wrap(np.arctan2(dy, dx) - s[2])]
>     )
>
>
> def H_lm(s, m_k):
>     """Jacobians of h_lm with respect to the pose (2x3) and to the
>     landmark (2x2)."""
>     dx, dy = m_k - s[:2]
>     q = dx**2 + dy**2
>     sq = np.sqrt(q)
>     Hs = np.array([[-sq * dx, -sq * dy, 0], [dy, -dx, -q]]) / q
>     Hm = np.array([[sq * dx, sq * dy], [-dy, dx]]) / q
>     return Hs, Hm
>
>
> def innov(z, zhat):
>     """Innovation z - zhat, with the bearing difference wrapped to [-pi, pi)."""
>     nu = z - zhat
>     nu[1] = wrap(nu[1])
>     return nu
>
>
> def add_landmark(mu, Sigma, z, R):
>     """Append a landmark initialized from measurement z, with the
>     insertion Jacobians."""
>     x, y, th = mu[:3]
>     rng_, phi = z
>     c, s_ = np.cos(phi + th), np.sin(phi + th)
>     m_new = np.array([x + rng_ * c, y + rng_ * s_])
>     Gs = np.array([[1, 0, -rng_ * s_], [0, 1, rng_ * c]])
>     Gz = np.array([[c, -rng_ * s_], [s_, rng_ * c]])
>     n = len(mu)
>     Sigma_new = np.zeros((n + 2, n + 2))
>     Sigma_new[:n, :n] = Sigma
>     cross = Gs @ Sigma[:3, :]
>     Sigma_new[n:, :n] = cross
>     Sigma_new[:n, n:] = cross.T
>     Sigma_new[n:, n:] = Gs @ Sigma[:3, :3] @ Gs.T + Gz @ R @ Gz.T
>     return np.r_[mu, m_new], Sigma_new
>
>
> # new-landmark threshold: the 99.9% point of chi-squared with 2 dof
> ALPHA = -2 * np.log(0.001)
> R_MEAS = np.diag([0.02**2, np.deg2rad(0.75) ** 2])
>
>
> def predict(mu, Sigma, a, M):
>     """Prediction step; on its own, this is dead reckoning."""
>     G_t, V_t = G(a, mu[:3]), V(a, mu[:3])
>     mu_bar = mu.copy()
>     mu_bar[:3] = g(a, mu[:3])
>     Sigma_bar = Sigma.copy()
>     Sigma_bar[:3, :] = G_t @ Sigma[:3, :]
>     Sigma_bar[:, :3] = Sigma_bar[:, :3] @ G_t.T
>     Sigma_bar[:3, :3] += V_t @ M @ V_t.T  # Q_t, the motion noise
>     return mu_bar, Sigma_bar
>
>
> def correct(mu_bar, Sigma_bar, z, R):
>     """Correction step with unknown correspondences."""
>     for z_i in z:
>         N = (len(mu_bar) - 3) // 2
>         best_d2, best = ALPHA, None
>         for k in range(N):
>             j = 3 + 2 * k
>             Hs, Hm = H_lm(mu_bar[:3], mu_bar[j : j + 2])
>             H_full = np.zeros((2, len(mu_bar)))
>             H_full[:, :3], H_full[:, j : j + 2] = Hs, Hm
>             Psi = H_full @ Sigma_bar @ H_full.T + R
>             nu = innov(z_i, h_lm(mu_bar[:3], mu_bar[j : j + 2]))
>             d2_k = nu @ np.linalg.solve(Psi, nu)  # Mahalanobis
>             if d2_k < best_d2:
>                 best_d2, best = d2_k, (H_full, Psi, nu)
>         if best is None:  # no landmark explains z_i: a new one
>             mu_bar, Sigma_bar = add_landmark(mu_bar, Sigma_bar, z_i, R)
>             continue
>         H_full, Psi, nu = best
>         K = Sigma_bar @ H_full.T @ np.linalg.inv(Psi)
>         mu_bar = mu_bar + K @ nu
>         mu_bar[2] = wrap(mu_bar[2])
>         Sigma_bar = (np.eye(len(mu_bar)) - K @ H_full) @ Sigma_bar
>         Sigma_bar = (Sigma_bar + Sigma_bar.T) / 2
>     return mu_bar, Sigma_bar
>
>
> def ekf_slam(mu, Sigma, a, z, M, R):
>     """One step of EKF SLAM: prediction, then correction."""
>     mu_bar, Sigma_bar = predict(mu, Sigma, a, M)
>     return correct(mu_bar, Sigma_bar, z, R)
> ```

## Policies on an estimated pose

The experiment reuses two policies without retraining. Go-to-goal turns toward the target and moves forward once aligned; it needs only goal distance and bearing computed from the supplied pose. The second policy is the finite model's optimum $\pi^*$, a table over $36\times36\times16$ pose cells and five steering commands. Rebuilding that table also preserves $Q^*(s,a)$, denoted $q_*$ in the MDP chapter, for the later QMDP experiment.

Both policies use certainty equivalence: they act as though the supplied pose were exact and ignore its covariance. Three pose sources are tested. Ground truth provides the ideal baseline; dead reckoning and the EKF SLAM mean provide estimates. Episode outcomes are always evaluated from the true pose, regardless of which pose drives the policy.

> [accordion] Code
>
> ```python theme={null}
> 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])
> gamma = 0.99
>
>
> 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))
>     d0 = np.hypot(GOAL[0] - x, GOAL[1] - y)
>     d2 = np.hypot(GOAL[0] - x2, GOAL[1] - y2)
>     r = 2.0 * (d0 - 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))
>
> 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)
>
>
> def q_values(v):
>     """q(s, a) for every state and action, from a value table."""
>     return R + gamma * np.append(v, [0.0, 0.0])[NEXT].mean(axis=2)
>
>
> v = np.zeros(N_S)
> for sweep in range(1, 10_000):
>     v_new = q_values(v).max(axis=1)  # Bellman optimality backup
>     v_new[~valid] = 0.0
>     if np.abs(v_new - v).max() < 1e-4:
>         break
>     v = v_new
> Q_star = q_values(v_new)
> pi_star = Q_star.argmax(axis=1)
> print(f"{valid.sum()} states, value iteration converged in {sweep} sweeps")
> ```

```output theme={null}
16229 states, value iteration converged in 164 sweeps
```

> [accordion] Code
>
> ```python theme={null}
> def go_to_goal(mu, Sigma):
>     """Go-to-goal on the pose mu (Sigma is ignored)."""
>     x, y, phi = mu[:3]
>     b = wrap(np.arctan2(GOAL[1] - y, GOAL[0] - x) - phi)
>     v = V_MAX * max(0.0, np.cos(b))
>     return v, float(np.clip(2.0 * b, -W_MAX, W_MAX))
>
>
> def table_policy(mu, Sigma):
>     """pi* of the cell that contains the pose mu."""
>     a = pi_star[state_index(*mu[:3])]
>     return V_ACT[a], W_ACT[a]
>
>
> def run(env, policy, source, delta, alpha=ALPHA_U, beta=BETA_U,
>         record=False, fov=2 * np.pi):
>     """One episode with the goal fixed. source is the pose the policy
>     reads: "true", "odometry" or "ekf". fov is the lidar's field of
>     view. Returns the outcome, the mean position error of that pose,
>     and with record=True the history."""
>     env.reset(goal=GOAL)
>     # separate noise streams, so the encoder readings do not depend on
>     # whether the lidar is simulated
>     enc_rng, lidar_rng = (
>         np.random.default_rng(env.noise_rng.integers(2**63)) for _ in "el"
>     )
>     mu, Sigma = env.pose.copy(), np.zeros((3, 3))  # EKF SLAM
>     dr, S_dr = env.pose.copy(), np.zeros((3, 3))  # dead reckoning
>     if source == "ekf" or record:  # map the landmarks before moving
>         z = lidar_landmarks(env.pose, lidar_rng, fov)
>         mu, Sigma = correct(mu, Sigma, z, R_MEAS)
>     errors, history = [], []
>     while True:
>         if source == "true":
>             est, cov = env.pose, np.zeros((3, 3))
>         elif source == "odometry":
>             est, cov = dr, S_dr
>         else:
>             est, cov = mu[:3], Sigma[:3, :3]
>         errors.append(np.hypot(*(est[:2] - env.pose[:2])))
>         event = env.step(*policy(est, cov))
>         a = encoders(env.twist, enc_rng, delta, alpha, beta)
>         M = wheel_noise(a, alpha, beta)
>         dr, S_dr = predict(dr, S_dr, a, M)
>         if source == "ekf" or record:
>             z = lidar_landmarks(env.pose, lidar_rng, fov)
>             mu, Sigma = ekf_slam(mu, Sigma, a, z, M, R_MEAS)
>         if record:
>             history.append(
>                 (env.pose.copy(), dr.copy(), S_dr.copy(),
>                  mu[:3].copy(), Sigma[:3, :3].copy(), (len(mu) - 3) // 2,
>                  len(z))
>             )
>         if event is not None:
>             return event, np.mean(errors), history
>
>
> N_EPISODES = 500
>
>
> def evaluate(policy, source, delta, **kw):
>     """Outcomes over the same N_EPISODES episodes (seed 99): the rates,
>     the mean position error, each episode's outcome and its final
>     distance to the goal."""
>     env = NavEnv(seed=99)
>     events, errors, final_dist = [], [], []
>     for _ in range(N_EPISODES):
>         event, err, _ = run(env, policy, source, delta, **kw)
>         events.append(event)
>         errors.append(err)
>         final_dist.append(env.goal_distance())
>     rates = {k: events.count(k) / N_EPISODES
>              for k in ("goal", "collision", "timeout")}
>     return rates, np.mean(errors), events, np.array(final_dist)
> ```

## Choosing the wheel radius error

A plausible wheel-radius error should reflect its physical source. The EKF localization example uses a wheel that is 1% smaller than the model assumes, representing tire wear or uneven loading. For the Waffle, 1% is 0.33 mm of the 33 mm nominal radius. The experiments therefore set the right wheel to $\delta=-0.01$. At full speed, this bias makes odometry overestimate the turn rate by about 0.5 degrees per second.

The following sweep drives $\pi^*$ from dead reckoning across several values of $\delta$, including zero, to show how quickly the bias matters.

> [accordion] Code
>
> ```python theme={null}
> print("delta    goal  collision  timeout  mean error (m)")
> for delta in (0.0, -0.005, -0.01, -0.02, -0.03):
>     rates, err, *_ = evaluate(table_policy, "odometry", delta)
>     print(f"{delta:+.3f}   {rates['goal']:.2f}       {rates['collision']:.2f}"
>           f"     {rates['timeout']:.2f}           {err:.3f}")
> ```

```output theme={null}
delta    goal  collision  timeout  mean error (m)
+0.000   0.72       0.28     0.00           0.054
-0.005   0.70       0.30     0.00           0.056
-0.010   0.63       0.37     0.00           0.061
-0.020   0.44       0.56     0.00           0.074
-0.030   0.25       0.75     0.00           0.090
```

Dead reckoning limits $\pi^*$ to a 72% success rate even when the wheel radii are correct. Encoder noise accumulates in the heading estimate and gradually separates the believed pose from the true pose. A 0.5% radius error has little additional effect; success falls to 63% at 1% error and 25% at 3%. Across the same sweep, mean position error rises from 5.4 cm to 9.0 cm. Although both are well below the 0.25 m goal tolerance, every failure is a collision: $\pi^*$ often passes close enough to an obstacle for a few centimeters of localization error to matter.

## Results over 500 episodes

Both policies are evaluated on the same 500 seeded episodes with $\delta=-0.01$. Starts are sampled from free space at least 1.5 m from the goal, and every pose source receives the same starts and actuation noise. The final column reports the position error seen by the policy, averaged first over the steps in each episode and then across episodes.

> [accordion] Code
>
> ```python theme={null}
> DELTA = -0.01
> SOURCES = {
>     "true": "true pose (ideal baseline)",
>     "odometry": "dead reckoning",
>     "ekf": "EKF SLAM mean",
> }
> events = {}
> print(f"{'policy':<11} {'pose source':<27} goal  collision  timeout  mean error (m)")
> for name, policy in (("go-to-goal", go_to_goal), ("pi*", table_policy)):
>     for source, label in SOURCES.items():
>         rates, err, events[name, source], _ = evaluate(
>             policy, source, DELTA
>         )
>         print(f"{name:<11} {label:<27} {rates['goal']:.2f}  "
>               f"     {rates['collision']:.2f}     {rates['timeout']:.2f}"
>               f"           {err:.3f}")
> ```

```output theme={null}
policy      pose source                 goal  collision  timeout  mean error (m)
go-to-goal  true pose (ideal baseline)  0.31       0.69     0.00           0.000
go-to-goal  dead reckoning              0.22       0.78     0.00           0.032
go-to-goal  EKF SLAM mean               0.31       0.69     0.00           0.005
pi*         true pose (ideal baseline)  1.00       0.00     0.00           0.000
pi*         dead reckoning              0.63       0.37     0.00           0.061
pi*         EKF SLAM mean               1.00       0.00     0.00           0.006
```

Ground truth supplies the ideal baseline. Go-to-goal succeeds in 31% of the episodes, while $\pi^*$ succeeds in all of them. The earlier 300-episode experiment measured 34% for go-to-goal, a difference consistent with sampling variation.

Dead reckoning reduces go-to-goal success from 31% to 22% and $\pi^*$ success from 100% to 63%. Every additional failure is a collision. Go-to-goal shows a smaller mean pose error only because many of its episodes terminate before the drift has time to grow.

Using the EKF SLAM mean restores both policies to the baseline: 31% for go-to-goal and 100% for $\pi^*$. Mean position error stays at 0.5 to 0.6 cm, between one sixth and one tenth of the dead-reckoning error. This performance depends on landmark coverage. The lidar usually sees three obstacles, allowing a correction at every step and preventing wheel-radius bias from accumulating. Long gaps in landmark visibility would leave the filter running on odometry and allow the error to grow.

## One episode in detail

The first episode in which dead reckoning causes $\pi^*$ to collide while EKF SLAM reaches the goal provides a representative comparison. Both runs begin from the same pose and use the same actuation noise.

> [accordion] Code
>
> ```python theme={null}
> k_ep = next(
>     k for k in range(N_EPISODES)
>     if events["pi*", "odometry"][k] == "collision"
>     and events["pi*", "ekf"][k] == "goal"
> )
> episode = {}
> for source in ("odometry", "ekf"):
>     env = NavEnv(seed=99)
>     for _ in range(k_ep):
>         env.reset(goal=GOAL)  # skip to episode k_ep
>     event, _, hist = run(env, table_policy, source, DELTA, record=True)
>     episode[source] = event, hist
> print("episode", k_ep)
> for source, (event, hist) in episode.items():
>     print(f"driven by {SOURCES[source]}: {event} after {len(hist)} steps")
>     true = hist[-1][0]
>     for name, i in (("dead reckoning", 1), ("EKF SLAM", 3)):
>         est, cov = hist[-1][i], hist[-1][i + 1]
>         print(f"  {name:<15} final error {np.hypot(*(est[:2] - true[:2])):.3f} m, "
>               f"heading {np.degrees(abs(wrap(est[2] - true[2]))):4.1f} deg, "
>               f"2 sqrt(Sxx + Syy) = {2 * np.sqrt(cov[0, 0] + cov[1, 1]):.3f} m")
> ```

```output theme={null}
episode 2
driven by dead reckoning: collision after 72 steps
  dead reckoning  final error 0.176 m, heading 11.0 deg, 2 sqrt(Sxx + Syy) = 0.479 m
  EKF SLAM        final error 0.006 m, heading  0.1 deg, 2 sqrt(Sxx + Syy) = 0.060 m
driven by EKF SLAM mean: goal after 79 steps
  dead reckoning  final error 0.266 m, heading 11.2 deg, 2 sqrt(Sxx + Syy) = 0.595 m
  EKF SLAM        final error 0.005 m, heading  0.4 deg, 2 sqrt(Sxx + Syy) = 0.070 m
```

![Output from cell 13](https://mintcdn.com/aegeanaiinc/A5GqO6yYMxo7BV4G/aiml-common/lectures/reinforcement-learning/robot-navigation/navigation-ekf-slam/images/cell_13_output_1.svg?fit=max\&auto=format\&n=A5GqO6yYMxo7BV4G\&q=85\&s=7f739af82b35bdd42010c9c75968060d)

*True trajectory (green) and the trajectory inferred by the policy (orange, dashed). A 2-sigma position ellipse is drawn every 10 steps, and the green circle marks the final true pose. Dead reckoning drives the left run; the EKF SLAM mean drives the right.*

The trajectories remain close for the first two meters, after which the dead-reckoning estimate drifts left of the true path. Because odometry credits the smaller right wheel with too much travel, it overestimates the robot's left turn; the final heading error is about 11 degrees. The estimated trajectory clears the obstacle at $(3,3)$, but the true robot is 18 cm away from that estimate and clips the obstacle after 72 steps. Growing heading uncertainty stretches the position ellipses across the direction of travel. With EKF SLAM, the ellipses remain small and the robot reaches the goal after 79 steps.

![Output from cell 14](https://mintcdn.com/aegeanaiinc/A5GqO6yYMxo7BV4G/aiml-common/lectures/reinforcement-learning/robot-navigation/navigation-ekf-slam/images/cell_14_output_1.svg?fit=max\&auto=format\&n=A5GqO6yYMxo7BV4G\&q=85\&s=80615d4c30b610e4cf0371a1dd2d6c32)

*Position error during the EKF-driven episode, compared with twice the root-mean-square position uncertainty reported by each covariance. Dead reckoning is propagated in parallel from the same encoder readings.*

Dead-reckoning error exceeds 10 cm after roughly 12 s and reaches 27 cm by the end of the run. Its covariance is more conservative, with a 60 cm bound that covers the drift despite omitting wheel-radius bias from the model. The EKF error remains much smaller, although its room-frame bound grows with distance from the start. Landmark observations constrain the robot relative to the map, but the map's orientation inherits the bearing uncertainty of the initial scan. A small angular error about the start creates a lateral displacement that increases with distance. The deliberately conservative $R_t$ further widens this bound.

The bound has no sharp drops because roughly three landmarks remain visible at every step. The dramatic covariance reduction seen at loop closure requires a landmark to disappear and later re-enter view; this room provides no comparable gap.

## Acting on the belief with QMDP

Certainty equivalence discards the covariance $\Sigma_t$. QMDP instead uses the Gaussian pose belief $b(s)\approx\mathcal N(\mu_t,\Sigma_t)$ (Thrun et al., 2005). It averages the fully observed optimal action values under that belief and selects the largest:

$$
a_t = \arg\max_a \sum_s b(s)\, Q^*(s, a).
$$

Here $s$ indexes cells in the finite model and $Q^*$ comes from value iteration. Monte Carlo sampling projects the continuous belief onto those cells: draw $N=200$ poses $s^{(i)}$ from $\mathcal N(\mu_t,\Sigma_t)$ and average the action values of their cells,

$$
\begin{aligned}
\sum_s b(s)\, Q^*(s, a)
&\approx \frac{1}{N} \sum_{i=1}^{N} Q^*\big(\text{cell}(s^{(i)}), a\big).
\end{aligned}
$$

Samples inside obstacles are discarded because the robot knows it has not collided. With a narrow covariance, the samples occupy the same cell as $\mu_t$ and QMDP reduces to $\pi^*(\mu_t)$. Its action changes only when appreciable belief mass reaches cells with different optimal actions, such as cells on opposite sides of an obstacle boundary.

With a full scan, roughly three landmarks are visible at every step and position uncertainty remains well within one 11 cm cell. QMDP therefore behaves almost exactly like $\pi^*(\mu_t)$. To create meaningful uncertainty without changing the dynamics, the next experiment blocks the rear half of the lidar, as a tall payload mounted behind the sensor might do. Only the forward half-plane remains visible. The detector also rejects an obstacle cut by the edge of the visible sector because the partial arc biases its circle fit. Encoder noise, wheel-radius bias, $R_t$, and episode seeds remain unchanged. During gaps in landmark visibility, the filter propagates from odometry alone and its covariance expands.

> [accordion] Code
>
> ```python theme={null}
> qmdp_rng = np.random.default_rng(5)
>
>
> def qmdp(mu, Sigma, n=200):
>     """argmax_a of the belief-weighted Q*(s, a), the belief sampled."""
>     poses = qmdp_rng.multivariate_normal(mu[:3], Sigma + 1e-12 * np.eye(3), n)
>     poses = poses[clearance_many(poses[:, 0], poses[:, 1]) >= RADIUS]  # no collision
>     cells = state_index(poses[:, 0], poses[:, 1], wrap(poses[:, 2]))
>     if len(cells) == 0:
>         return table_policy(mu, Sigma)
>     a = Q_star[cells].mean(axis=0).argmax()
>     return V_ACT[a], W_ACT[a]
> ```
>
> ```python theme={null}
> FOV_HALF = np.pi  # the payload blocks the rear half of every scan
>
>
> def longest_blind(seen):
>     """Longest stretch of steps with no landmark in view."""
>     longest = stretch = 0
>     for n in seen:
>         stretch = stretch + 1 if n == 0 else 0
>         longest = max(longest, stretch)
>     return longest
>
>
> env = NavEnv(seed=99)
> blind_frac, blind_long, half_hists = [], [], []
> for _ in range(50):
>     _, _, hist = run(env, table_policy, "ekf", DELTA, record=True, fov=FOV_HALF)
>     seen = np.array([h[6] for h in hist])
>     blind_frac.append(np.mean(seen == 0))
>     blind_long.append(longest_blind(seen))
>     half_hists.append(hist)
> k_blind = int(np.argmax(blind_long))
>
> env = NavEnv(seed=99)
> for _ in range(k_blind):
>     env.reset(goal=GOAL)  # skip to episode k_blind
> _, _, full_hist = run(env, table_policy, "ekf", DELTA, record=True)
>
> print(f"steps with no landmark in view: {np.mean(blind_frac):.0%}")
> print(f"longest blind stretch per episode: median "
>       f"{DT * np.median(blind_long):.1f} s, longest {DT * max(blind_long):.1f} s "
>       f"(episode {k_blind})")
> for label, hist in (("full scan", full_hist), ("half scan", half_hists[k_blind])):
>     bound = [2 * np.sqrt(h[4][0, 0] + h[4][1, 1]) for h in hist]
>     err = [np.hypot(*(h[3][:2] - h[0][:2])) for h in hist]
>     print(f"{label}: largest bound {max(bound):.3f} m, largest error {max(err):.3f} m")
> ```

```output theme={null}
steps with no landmark in view: 29%
longest blind stretch per episode: median 2.2 s, longest 4.6 s (episode 30)
full scan: largest bound 0.031 m, largest error 0.010 m
half scan: largest bound 0.099 m, largest error 0.037 m
```

![Output from cell 17](https://mintcdn.com/aegeanaiinc/A5GqO6yYMxo7BV4G/aiml-common/lectures/reinforcement-learning/robot-navigation/navigation-ekf-slam/images/cell_17_output_1.svg?fit=max\&auto=format\&n=A5GqO6yYMxo7BV4G\&q=85\&s=d7a73f21ab8b2a7cb37d681864d180f9)

*EKF SLAM position error and its 2-sigma bound with a full scan (left) and a blocked rear half (right). Gray bands indicate steps without a visible landmark. Among the first 50 trials, this episode has the longest blind interval.*

Blocking the rear half leaves the robot without a landmark on 29% of its steps; the median episode's longest blind interval is 2.2 s. In the episode shown, the 2-sigma bound reaches 9.9 cm, compared with 3.1 cm for the full scan. Both uncertainty and position error grow most quickly inside the gray bands, when the filter can only predict. Blind intervals also occur beside obstacles: as the robot passes one, the boundary of the visible half-plane cuts its arc and the detector rejects it.

> [accordion] Code
>
> ```python theme={null}
> blocked = {"fov": FOV_HALF}
> BELIEFS = {"ekf": "EKF, half scan", "odometry": "dead reckoning"}
> differs = {"ekf": [], "odometry": []}
>
>
> def counting_qmdp(source):
>     """QMDP that records whether it picks another action than pi*(mu)."""
>     def policy(mu, Sigma):
>         """QMDP action for the belief (mu, Sigma); records whether it differs from pi*(mu)."""
>         action = qmdp(mu, Sigma)
>         differs[source].append(action != table_policy(mu, Sigma))
>         return action
>     return policy
>
>
> print(f"{'belief':<16} {'policy':<10} goal  collision  timeout  mean error (m)")
> for source in ("ekf", "odometry"):  # dead reckoning does not use the lidar
>     for name, policy in (("pi*(mu)", table_policy), ("QMDP", counting_qmdp(source))):
>         rates, err, ev, dist = evaluate(policy, source, DELTA, **blocked)
>         print(f"{BELIEFS[source]:<16} {name:<10} {rates['goal']:.2f}  "
>               f"     {rates['collision']:.2f}     {rates['timeout']:.2f}"
>               f"           {err:.3f}")
>         timed_out = dist[np.array(ev) == "timeout"]
>         if len(timed_out):
>             print(f"{'':<27} {len(timed_out)} timeouts, ending "
>                   f"{timed_out.min():.2f} to {timed_out.max():.2f} m from the goal")
> print()
> for source, label in BELIEFS.items():
>     print(f"{label}: QMDP picks another action than pi*(mu) "
>           f"on {np.mean(differs[source]):.0%} of its steps")
> ```

```output theme={null}
belief           policy     goal  collision  timeout  mean error (m)
EKF, half scan   pi*(mu)    0.99       0.01     0.00           0.018
EKF, half scan   QMDP       1.00       0.00     0.00           0.018
dead reckoning   pi*(mu)    0.63       0.37     0.00           0.061
dead reckoning   QMDP       0.72       0.28     0.00           0.072

EKF, half scan: QMDP picks another action than pi*(mu) on 13% of its steps
dead reckoning: QMDP picks another action than pi*(mu) on 34% of its steps
```

With the half-scan EKF belief, QMDP succeeds in 100% of episodes and $\pi^*(\mu_t)$ in 99%; their collision rates are 0% and 1%. QMDP selects a different action on 13% of its steps. The gap is about five of the 500 episodes. It favors QMDP, but it is too small to rank the two policies with confidence. The widest 2-sigma bound in the episode above is 9.9 cm, close to one 11 cm cell, so the belief covers only a few neighboring cells even during a blind interval.

With dead reckoning, no landmark correction narrows the belief. QMDP changes the action on 34% of steps and succeeds in 72% of episodes, compared with 63% for $\pi^*(\mu_t)$. Their collision rates are 28% and 37%. A 9-point gain over 500 episodes is larger than sampling variation alone would explain.

QMDP assumes that state uncertainty disappears after the next action because $Q^*$ describes a fully observed MDP from that point onward. Consequently, it assigns no value to information-gathering actions. It will not turn to bring a landmark into view or slow down while localization improves. Planning those actions requires a policy over beliefs, which is the full POMDP problem.

## What the estimate costs

In this room, full-scan EKF SLAM introduces no measurable loss: go-to-goal and $\pi^*$ succeed as often from the filter mean as from the true pose because about three landmarks remain visible and mean error stays at 0.5 to 0.6 cm. Dead reckoning is much less forgiving. Random encoder noise alone reduces $\pi^*$ success by 28 percentage points; adding a 1% wheel-radius bias increases the loss to 37 points. With the rear half of the scan blocked, no landmark is visible during 29% of the run and uncertainty grows between sightings. Even so, $\pi^*(\mu_t)$ still reaches the goal in 99% of episodes with a mean error of 1.8 cm, which leaves QMDP almost nothing to recover. QMDP helps where the belief is wide: on dead reckoning it raises success from 63% to 72%. QMDP accounts for uncertainty when comparing actions but does not seek observations. A policy that deliberately looks before committing must plan over beliefs.

Key references: (Thrun et al., 2005)

## References

* Thrun, S., Burgard, W., Fox, D. (2005). *Probabilistic Robotics*. [Link](https://gaoyichao.com/Xiaotu/resource/refs/PR.MIT.en.pdf)

***

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-ekf-slam).


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