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]}")