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

# q-Value Iteration for a Cleaning Robot

> q-value iteration on a six-cell corridor, with deterministic and noisy moves.

[![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/mdp/mdp-workshop/cleaning-robot/index.ipynb)

A cleaning robot moves along a corridor of six cells. It has to collect a used can at one end, and it can recharge its batteries at the other. The problem is small enough to solve by hand, which makes it a good place to watch value iteration work on action values $q(x, u)$ instead of state values $v(x)$.

## The cleaning robot MDP

The state $x \in \{0, 1, 2, 3, 4, 5\}$ is the position of the robot, and the action $u \in \{-1, 1\}$ moves it one cell to the left or to the right. The charger is in state 0 and the can is in state 5. Both are terminal: once the robot reaches either one, it stays there whatever it does.

With deterministic moves, the next state is

$$
f(x, u) = \begin{cases} x + u & \text{if } 1 \le x \le 4, \\ x & \text{if } x = 0 \text{ or } x = 5. \end{cases}
$$

Reaching the can earns a reward of 5 and reaching the charger earns 1. Every other transition, including any action taken in a terminal state, earns 0:

$$
\rho(x, u) = \begin{cases} 5 & \text{if } x = 4 \text{ and } u = 1, \\ 1 & \text{if } x = 1 \text{ and } u = -1, \\ 0 & \text{otherwise.} \end{cases}
$$

The discount factor is $\gamma = 0.5$, so a reward one step later is worth half as much.

> [accordion] Code
>
> ```python theme={null}
> import numpy as np
> import matplotlib.pyplot as plt
> import matplotlib.patches as mpatches
> from cycler import cycler
> from matplotlib import colormaps
> 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",
> })
> ```

![Output from cell 2](https://mintcdn.com/aegeanaiinc/LMcSLTRAci9sGoEb/aiml-common/lectures/mdp/mdp-workshop/cleaning-robot/images/cell_2_output_1.svg?fit=max\&auto=format\&n=LMcSLTRAci9sGoEb\&q=85\&s=2777ad57409653d3e2bc1ffb7f31fc4d)

*The corridor. The robot at $x = 2$ can move left or right. The arrows above the corridor mark the two rewarding transitions, into the charger and into the can.*

## q-value iteration

The optimal action-value function $q_*(x, u)$ is the return of taking action $u$ in state $x$ and acting optimally afterwards. It satisfies the Bellman optimality equation for action values,

$$
q_*(x, u) = \sum_{x'} p(x' \mid x, u) \left[ r(x, u, x') + \gamma \max_{u'} q_*(x', u') \right].
$$

q-value iteration turns this equation into an update. Start from $q_0 = 0$ and apply the right-hand side to every pair $(x, u)$, using the previous table $q_k$ inside the max, to get $q_{k+1}$. Stop when no entry changes by more than a small tolerance. Once $q_*$ is known, the optimal policy needs no model at all: in each state, pick the action with the larger $q_*(x, u)$.

This is value iteration with the action values kept. [Value Iteration](https://aegean.ai/aiml-common/lectures/mdp/dynamic-programming-algorithms/value-iteration/index.md) stores one number per state, $v_k(x)$, and computes action values only briefly inside each backup. q-value iteration stores one number per state and action. The two produce the same sequence: with $v_k(x) = \max_u q_k(x, u)$, the update above is exactly the value iteration update. Keeping $q$ costs more memory, but it removes the model from policy extraction. From $v_*$ you need the model $p$ again to look one step ahead, while from $q_*$ you only take the argmax in each state. Q-learning estimates the same table from experience, without $p$; its capital $Q$ marks a learned estimate.

The function below implements the update for any model given as arrays: `P[x, a, y]` is the probability of moving from `x` to `y` under action `a`, and `R[x, a, y]` is the reward of that transition.

> [accordion] Code
>
> ```python theme={null}
> states = np.arange(6)         # positions 0 to 5
> actions = np.array([-1, 1])   # move left, move right
> terminal = {0, 5}
> gamma = 0.5
>
>
> def q_value_iteration(P, R, gamma, tol=1e-3, max_sweeps=50):
>     """Synchronous q-value iteration.
>
>     P[x, a, y] is the probability of moving from x to y under action a, and
>     R[x, a, y] is the reward of that transition. Returns the table q_k after
>     every sweep, starting from q_0 = 0.
>     """
>     q = np.zeros(P.shape[:2])
>     history = [q.copy()]
>     for _ in range(max_sweeps):
>         # sum over y of P(y | x, a) * (r(x, a, y) + gamma * max_b q(y, b))
>         q_new = np.einsum("xay,xay->xa", P, R + gamma * q.max(axis=1)[None, None, :])
>         history.append(q_new)
>         if np.abs(q_new - q).max() < tol:
>             break
>         q = q_new
>     return history
>
>
> def greedy_policy(q):
>     return {int(x): ("left" if q[x, 0] > q[x, 1] else "right") for x in states if x not in terminal}
> ```

## Deterministic moves

In the deterministic model, each action leads to exactly one next state, so the sum in the update has a single term: $q_{k+1}(x, u) = \rho(x, u) + \gamma \max_{u'} q_k(f(x, u), u')$.

> [accordion] Code
>
> ```python theme={null}
> def deterministic_model():
>     P = np.zeros((6, 2, 6))
>     R = np.zeros((6, 2, 6))
>     for x in states:
>         for a, u in enumerate(actions):
>             y = x if x in terminal else x + u
>             P[x, a, y] = 1.0
>             if x not in terminal:
>                 R[x, a, y] = 5.0 if y == 5 else (1.0 if y == 0 else 0.0)
>     return P, R
>
>
> history_det = q_value_iteration(*deterministic_model(), gamma)
> q_det = history_det[-1]
> print(f"converged after {len(history_det) - 1} sweeps")
> print("q* (rows x = 0..5, columns left, right):")
> print(np.round(q_det, 3))
> print("greedy policy:", greedy_policy(q_det))
> ```

```output theme={null}
converged after 5 sweeps
q* (rows x = 0..5, columns left, right):
[[0.    0.   ]
 [1.    0.625]
 [0.5   1.25 ]
 [0.625 2.5  ]
 [1.25  5.   ]
 [0.    0.   ]]
greedy policy: {1: 'left', 2: 'right', 3: 'right', 4: 'right'}
```

![Output from cell 5](https://mintcdn.com/aegeanaiinc/LMcSLTRAci9sGoEb/aiml-common/lectures/mdp/mdp-workshop/cleaning-robot/images/cell_5_output_1.svg?fit=max\&auto=format\&n=LMcSLTRAci9sGoEb\&q=85\&s=f7b8f0886e5138cca0131bf2d15e5b82)

Each sweep carries the rewards one cell further from the terminal states. Moving right, the value halves with every cell between the robot and the can: $q_*(4, 1) = 5$, $q_*(3, 1) = 2.5$, $q_*(2, 1) = 1.25$ and $q_*(1, 1) = 0.625$. The table reaches $q_*$ after four sweeps, and the fifth changes nothing, which ends the loop.

The greedy policy moves right everywhere except in state 1. There, the charger one step away is worth 1, more than the can four steps away, which is worth $5 \cdot 0.5^3 = 0.625$. In the early sweeps, state 2 also prefers to move left, because the value of the can has not reached it yet. One sweep later, moving right wins.

## Noisy moves

In the stochastic version of the problem the robot can slip. An action in a nonterminal state moves the robot in the intended direction with probability 0.8, leaves it where it is with probability 0.15, and moves it the opposite way with probability 0.05. The rewards stay attached to the transitions: 5 for any move into the can and 1 for any move into the charger. The update now averages over the three possible next states.

> [accordion] Code
>
> ```python theme={null}
> def stochastic_model(p_intended=0.8, p_stay=0.15, p_back=0.05):
>     P = np.zeros((6, 2, 6))
>     R = np.zeros((6, 2, 6))
>     for x in states:
>         for a, u in enumerate(actions):
>             if x in terminal:
>                 P[x, a, x] = 1.0
>                 continue
>             for y, p in [(x + u, p_intended), (x, p_stay), (x - u, p_back)]:
>                 P[x, a, y] += p
>                 R[x, a, y] = 5.0 if y == 5 else (1.0 if y == 0 else 0.0)
>     return P, R
>
>
> history_sto = q_value_iteration(*stochastic_model(), gamma)
> q_sto = history_sto[-1]
> print(f"converged after {len(history_sto) - 1} sweeps")
> print("q* (rows x = 0..5, columns left, right):")
> print(np.round(q_sto, 3))
> print("greedy policy:", greedy_policy(q_sto))
> ```

```output theme={null}
converged after 8 sweeps
q* (rows x = 0..5, columns left, right):
[[0.    0.   ]
 [0.888 0.457]
 [0.467 0.852]
 [0.594 1.915]
 [1.344 4.376]
 [0.    0.   ]]
greedy policy: {1: 'left', 2: 'right', 3: 'right', 4: 'right'}
```

![Output from cell 7](https://mintcdn.com/aegeanaiinc/LMcSLTRAci9sGoEb/aiml-common/lectures/mdp/mdp-workshop/cleaning-robot/images/cell_7_output_1.svg?fit=max\&auto=format\&n=LMcSLTRAci9sGoEb\&q=85\&s=f200c10eda79d7dfbf66d8959b20b615)

The greedy policy is the same as with deterministic moves, and almost every value is lower. A move can fail or go backwards, so on average the robot needs more steps to reach a terminal state, and each extra step halves the reward it collects. The one exception is moving left from state 4, worth 1.34 instead of 1.25: the 0.05 chance of slipping backwards lands the robot in the can. Convergence also takes longer, eight sweeps instead of five, because a value now feeds back into its own state through the 0.15 chance of staying put.

The cleaning robot and its stochastic variant come from Buşoniu, Babuška, De Schutter and Ernst, *Reinforcement Learning and Dynamic Programming Using Function Approximators* (Busoniu, 2017), where the deterministic version is Example 2.1.

## References

* Busoniu, L. (2017). *Reinforcement learning and dynamic programming using function approximators*. [DOI](https://doi.org/10.1201/9781439821091)

***

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/mdp/mdp-workshop/cleaning-robot).


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