Solving MDPs with Linear Programming
Value iteration and policy iteration are iterative. There's a third way that solves the MDP in one shot with an off-the-shelf solver: write it as a linear program (LP). This matters for three reasons. It gives polynomial-time guarantees, it makes adding constraints easy (for example "keep the expected battery use below X"), and its dual has a beautiful interpretation. It is also a standard MDL assignment topic.
A 60-second LP refresher
A linear program optimizes a linear objective subject to linear constraints:
$$ \min_{x}\ c^\top x \quad \text{s.t.}\quad A_{ub}\,x \le b_{ub},\quad A_{eq}\,x = b_{eq},\quad \text{bounds on } x. $$Every LP (the primal) has a dual LP. At the optimum both have the same objective value (strong duality). Solvers like scipy.optimize.linprog, PuLP and CVXPY handle thousands of variables easily.
The primal LP: utilities as variables
The Bellman equation says \(V(s) = \max_a [\,r(s,a) + \gamma\sum_{s'} P(s'|s,a)V(s')\,]\). A max is not linear, but "\(V(s)\) is at least each option" is:
$$ V(s) \;\ge\; r(s,a) + \gamma \sum_{s'} P(s' \mid s,a)\, V(s') \qquad \text{for every } s \text{ and every } a. $$Many vectors \(V\) satisfy these constraints. Any upper bound on the true values does. The smallest one is exactly the optimal value function, so:
Primal LP
$$ \min_{V}\ \sum_s \alpha(s)\, V(s) \quad \text{s.t.}\quad V(s) - \gamma \sum_{s'} P(s'\mid s,a)\, V(s') \;\ge\; r(s,a)\quad \forall s, a $$with any positive weights \(\alpha(s)\) (often all 1, or a start-state distribution). There are \(|S|\) variables and \(|S|\cdot|A|\) constraints.
Each constraint pushes \(V(s)\) up to at least the value of every action. Minimizing pushes it down as far as possible. The two meet exactly at \(V(s) = \max_a(\dots)\), the Bellman equation. For every state, the constraint of the best action is tight (holds with equality), and that tight constraint identifies the optimal action.
The dual LP: flows of probability
The dual has one variable \(x(s,a) \ge 0\) per state–action pair, and an elegant meaning: \(x(s,a)\) is the expected (discounted) number of times the agent is in state \(s\) and takes action \(a\). It's often called the occupancy measure.
Dual LP
$$ \max_{x \ge 0}\ \sum_{s,a} x(s,a)\, r(s,a) \quad\text{s.t.}\quad \sum_{a} x(s',a) - \gamma \sum_{s,a} P(s' \mid s,a)\, x(s,a) = \alpha(s') \quad \forall s'. $$Read the constraint as flow conservation, like water in pipes. The flow out of \(s'\) (the total times you act there) equals the flow that starts at \(s'\) (\(\alpha\)) plus the discounted flow that arrives from other states. The objective adds up the reward collected by all that flow. The optimal policy is recovered as
$$ \pi^*(s) = \arg\max_a x(s,a), $$since at the optimum, essentially all the flow through a state goes through its best action.
In matrix form, which is how assignments usually phrase it, the constraint is \(A x = \alpha\), where \(A\) has one row per state and one column per (state, action) pair:
$$ A[s', (s,a)] = \mathbb{1}[s = s'] - \gamma\, P(s' \mid s,a). $$A column of \(A\) holds "+1 for the state you leave, minus the (discounted) probability mass for each state you might land in." With \(\gamma = 1\) and terminal states that exit the system, each non-terminal column sums to 0 (probability is conserved), and terminal columns have just the +1.
Both LPs in code
The same 4×3 world, now with \(\gamma = 0.9\). Each terminal state has a single EXIT action that collects its reward and leaves the world.
import numpy as np
from scipy.optimize import linprog
# ---- the same 4x3 world as §5.3, written as matrices ----
COLS, ROWS, WALL = 4, 3, (1, 1)
TERMINAL = {(3, 2): +1.0, (3, 1): -1.0}
STATES = [(c, r) for c in range(COLS) for r in range(ROWS) if (c, r) != WALL]
MOVES = {"N": (0, 1), "S": (0, -1), "E": (1, 0), "W": (-1, 0)}
SIDE = {"N": "EW", "S": "EW", "E": "NS", "W": "NS"}
GAMMA = 0.9
n = len(STATES)
idx = {s: i for i, s in enumerate(STATES)}
def step(s, a):
nxt = (s[0] + MOVES[a][0], s[1] + MOVES[a][1])
return nxt if nxt in idx else s
# list every (state, action) pair; terminals get a single EXIT action that leaves the world
pairs, P, r = [], [], []
for s in STATES:
acts = ["EXIT"] if s in TERMINAL else list(MOVES)
for a in acts:
row = np.zeros(n)
if a != "EXIT":
for prob, d in [(0.8, a), (0.1, SIDE[a][0]), (0.1, SIDE[a][1])]:
row[idx[step(s, d)]] += prob
pairs.append((s, a)); P.append(row); r.append(TERMINAL.get(s, -0.04))
P, r = np.array(P), np.array(r) # P: (pairs x states), r: reward of each pair
# ---------- PRIMAL: min sum_s V(s) s.t. V(s) >= r(s,a) + gamma * sum_s' P(s'|s,a) V(s') ----------
E = np.array([[1.0 if s == t else 0.0 for t in STATES] for s, a in pairs]) # picks V(s) for each pair
primal = linprog(c=np.ones(n), A_ub=-(E - GAMMA * P), b_ub=-r, bounds=[(None, None)] * n)
V = primal.x
# ---------- DUAL: max sum x(s,a) r(s,a) s.t. flow conservation, x >= 0 ----------
alpha = np.ones(n) / n # start-state distribution (any positive vector works)
A_eq = (E - GAMMA * P).T # one row per state s': out-flow - discounted in-flow
dual = linprog(c=-r, A_eq=A_eq, b_eq=alpha, bounds=[(0, None)] * len(pairs))
x = dual.x
policy = {}
for s in STATES:
if s not in TERMINAL:
cands = [(x[i], a) for i, (t, a) in enumerate(pairs) if t == s]
policy[s] = max(cands)[1] # the action carrying the most "flow"
for row_ in reversed(range(ROWS)):
cells = []
for c in range(COLS):
s = (c, row_)
cells.append(" #### " if s == WALL else f"{V[idx[s]]:6.3f} {policy.get(s, ' ')}")
print(" ".join(cells))
print("primal objective sum V =", round(primal.fun, 4))
print("dual objective =", round(-dual.fun, 4), " = alpha . V =", round(alpha @ V, 4)) 0.509 E 0.650 E 0.795 E 1.000
0.399 N #### 0.486 N -1.000
0.296 N 0.254 E 0.345 N 0.130 W
primal objective sum V = 3.8645
dual objective = 0.3513 = alpha . V = 0.3513
Three things to notice:
- Strong duality. The dual objective equals \(\sum_s \alpha(s) V(s)\). It's the same optimization seen from the other side. (The primal objective printed uses weights of 1 instead of \(\alpha = 1/n\), hence the factor of 11.)
- The policy changed with γ! At \(\gamma = 0.9\), cells (1,0) and (2,0) now choose E and N, risking the route past the pit, where at \(\gamma=1\) they chose W and took the long safe route. With discounting, a long detour costs more, because the +1 at the end is worth less the later it arrives. Running value iteration with \(\gamma = 0.9\) gives exactly these numbers.
- Using a solver lets you add constraints. For example, "probability of ever entering the pit ≤ 5%" is a linear constraint on \(x\). This is a constrained MDP, which value iteration can't handle directly.
LP-for-MDP assignments typically ask you to output the A matrix, the R vector (reward per state–action pair), the α vector (initial state distribution, e.g. 1 at the start state and 0 elsewhere), the optimal x, the derived deterministic policy and the objective value. Tips:
- Fix an ordering of (state, action) pairs once, and use it everywhere: columns of A, entries of R and of x.
- Include only valid actions per state (for example, no "shoot" action without arrows). Each terminal state gets one NOOP/exit action.
- Sanity check: with \(\gamma=1\), every non-terminal column of A should sum to 0, because probability is conserved. Assert this.
- Many states have \(x(s,\cdot) = 0\) because they're never visited from the start distribution. Their "policy" is arbitrary. Say so in your report.
- The dual is a maximization.
linprogminimizes, so passc = -Rand negate the result.