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

# Value Iteration for the Recycling Robot

> Solving the recycling robot by repeated optimality backups.

[![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/dynamic-programming-algorithms/value-iteration/recycling-robot/index.ipynb)

The [Recycling Robot](https://aegean.ai/aiml-common/lectures/mdp/bellman-optimality-backup/mdp-tree-expansion/mdp-tree-expansion.md) section described a two-state robot, wrote down its Bellman optimality equations, and solved them by evaluating all six of its deterministic policies. Checking every policy works only because the robot is tiny: a problem with $|\mathcal S|$ states and $|\mathcal A|$ actions has $|\mathcal A|^{|\mathcal S|}$ deterministic policies. This section solves the same robot with value iteration, which needs no enumeration. The dynamics, rewards and parameters ($\alpha = 0.8$, $\beta = 0.4$, $r_{\text{search}} = 2$, $r_{\text{wait}} = 1$, $\gamma = 0.9$) are the ones in that section.

Value iteration starts from $v_0 = 0$ and applies the optimality backup to every state in each sweep:

$$
v_{k+1}(s) = \max_a \sum_{s'} p(s' \mid s, a) \left[ r + \gamma\, v_k(s') \right].
$$

One sweep does for every state what one level of the lookahead tree in the Recycling Robot section does for the root, but each state is computed once and its value reused, instead of once per tree node.

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

```python theme={null}
HIGH, LOW = 0, 1
SEARCH, WAIT, RECHARGE = 0, 1, 2
STATE_NAMES = ["high", "low"]
ACTION_NAMES = ["search", "wait", "recharge"]

# T[s][a] lists the outcomes of action a in state s as (p, s', reward),
# where p = p(s' | s, a) is the transition probability of that outcome.
alpha, beta, r_search, r_wait, gamma = 0.8, 0.4, 2.0, 1.0, 0.9
T = {
    HIGH: {SEARCH: [(alpha, HIGH, r_search), (1 - alpha, LOW, r_search)],
           WAIT: [(1.0, HIGH, r_wait)]},
    LOW: {SEARCH: [(beta, LOW, r_search), (1 - beta, HIGH, -3.0)],
          WAIT: [(1.0, LOW, r_wait)],
          RECHARGE: [(1.0, HIGH, 0.0)]},
}


def q_value(s, a, v):
    """Action value of taking action a in state s, given state values v.

    Args:
        s: current state (HIGH or LOW).
        a: action available in s.
        v: array of state values, indexed by state.

    Returns:
        sum over outcomes of p(s_next | s, a) * (r + gamma * v[s_next]).
    """
    return sum(p * (r + gamma * v[s2]) for p, s2, r in T[s][a])


def sweep(v):
    """One synchronous sweep of value iteration.

    Every state is backed up from the same v_k, so the update order does not matter.

    Args:
        v: array of state values v_k.

    Returns:
        (v_next, greedy): the array v_{k+1} and the greedy action in each state
        with respect to v_k, as a tuple (action in HIGH, action in LOW).
    """
    q = {s: {a: q_value(s, a, v) for a in T[s]} for s in (HIGH, LOW)}
    v_next = np.array([max(q[s].values()) for s in (HIGH, LOW)])
    greedy = tuple(max(q[s], key=q[s].get) for s in (HIGH, LOW))
    return v_next, greedy


v, history, policies = np.zeros(2), [np.zeros(2)], []
while True:
    v_next, greedy = sweep(v)
    history.append(v_next)
    policies.append(greedy)
    if np.max(np.abs(v_next - v)) < 1e-8:
        break
    v = v_next

for k in [1, 2, 3, 4, 5, 10, 20, 50, len(history) - 1]:
    a_h, a_l = policies[k - 1]
    print(f"k = {k:>3}   v_k = {np.round(history[k], 3)}   "
          f"greedy: high -> {ACTION_NAMES[a_h]}, low -> {ACTION_NAMES[a_l]}")
```

```output theme={null}
k =   1   v_k = [2. 1.]   greedy: high -> search, low -> wait
k =   2   v_k = [3.62 1.9 ]   greedy: high -> search, low -> wait
k =   3   v_k = [4.948 3.258]   greedy: high -> search, low -> recharge
k =   4   v_k = [6.149 4.454]   greedy: high -> search, low -> recharge
k =   5   v_k = [7.229 5.534]   greedy: high -> search, low -> recharge
k =  10   v_k = [11.21   9.515]   greedy: high -> search, low -> recharge
k =  20   v_k = [14.948 13.253]   greedy: high -> search, low -> recharge
k =  50   v_k = [16.864 15.169]   greedy: high -> search, low -> recharge
k = 181   v_k = [16.949 15.254]   greedy: high -> search, low -> recharge
```

The `sweep` function computes the action values of every state from the same $v_k$ and keeps the largest one. The loop stops when no value changes by more than $10^{-8}$. The values reach $v_* = (16.949, 15.254)$, the solution found in the Recycling Robot section by checking every policy.

![Output from cell 3](https://mintcdn.com/aegeanaiinc/EWdLakRxTohE40VE/aiml-common/lectures/mdp/dynamic-programming-algorithms/value-iteration/recycling-robot/images/cell_3_output_1.svg?fit=max\&auto=format\&n=EWdLakRxTohE40VE\&q=85\&s=166244deebee3f7b9db782f045023e40)

*Left: the two state values approach $v_*$ (dashed lines). Right: the largest error shrinks by about a factor of $\gamma = 0.9$ per sweep, so it falls on a straight line on the log scale.*

The error shrinks by a factor of $\gamma$ per sweep because the optimality backup is a contraction: it brings any two value functions at least a factor $\gamma$ closer in the largest state difference. With $\gamma = 0.9$ that is slow, and the loop needs 181 sweeps to reach $10^{-8}$.

The greedy policy settles much sooner than the values. After one and two sweeps the low state prefers to wait, because with so few steps left the benefit of recharging is out of reach. From the third sweep on, the greedy policy is search in high and recharge in low, the optimal policy, while the values still have far to go. The greedy policy is already optimal once $v_k$ is close enough to $v_*$ to rank the actions in every state correctly, which here happens after three sweeps.

**Key references**: (Sutton & Barto, 2018)

## References

* Sutton, R., Barto, A. (2018). *Reinforcement Learning: An Introduction*. [Link](https://www.andrew.cmu.edu/course/10-703/textbook/BartoSutton.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/mdp/dynamic-programming-algorithms/value-iteration/recycling-robot).


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