Building the Dual Mechanically
Every linear program comes with a second one, its dual, and in algorithm design the dual is often more useful than the primal: its feasible solutions are proofs of bounds. Writing the dual of a given LP should be a mechanical skill, done without thinking about geometry. This lesson derives the dual from one question ("what is the best bound I can prove by adding up constraints?"), turns the answer into a recipe table, implements the recipe as a program, and applies it to three combinatorial LPs. The Lagrangian view of the same construction is in The Lagrange Dual Problem and Duality in Linear Programming.
Bounds from combinations of constraints
Take the workshop LP: maximize subject to , , , . Every feasible point satisfies any non-negative combination of the constraints. Multiply them by and add:
If the coefficient of is at least 3 and that of at least 2, then, because , the left side is at least . So every such choice of multipliers proves an upper bound on the objective. For example gives coefficients and the bound , which is exactly the optimum. Finding the best bound is itself an LP:
In matrix form, the dual of is : one dual variable per primal constraint, one dual constraint per primal variable, and the roles of and swapped.
The recipe for every kind of constraint
When the primal mixes , and rows, and variables of any sign, the same reasoning fixes the sign of each multiplier. For a maximization, a multiplier must keep the inequality pointing the right way: on a row, on a row, any sign on an equation. And a dual constraint must make the combination dominate the objective: if , if , if is free.
| Primal (maximize ) | Dual (minimize ) |
|---|---|
| row : | |
| row : | |
| row : | free |
| column : | |
| column : | |
| free | column : |
Read from right to left, the table gives the dual of a minimization. A useful mnemonic: "natural" constraints (a row in a max problem, a row in a min problem, a non-negative variable) correspond to "natural" ones on the other side; equations correspond to free variables.
The program implements the table for both directions. It dualizes a mixed LP, dualizes the result again to check that the dual of the dual is the primal, and solves both with SciPy.
from scipy.optimize import linprog
FLIP = {"<=": ">=", ">=": "<=", "=": "="}
def dual(lp):
"""lp = (sense, c, rows [(a, op, rhs)], signs ['>=0' | '<=0' | 'free'])."""
sense, c, rows, signs = lp
m, n = len(rows), len(c)
natural_row = "<=" if sense == "max" else ">="
ysigns = [">=0" if op == natural_row else "free" if op == "=" else "<=0" for _, op, _ in rows]
natural_col = ">=" if sense == "max" else "<="
cols = []
for j in range(n):
op = natural_col if signs[j] == ">=0" else "=" if signs[j] == "free" else FLIP[natural_col]
cols.append(([rows[i][0][j] for i in range(m)], op, c[j]))
return ("min" if sense == "max" else "max", [r for _, _, r in rows], cols, ysigns)
def show(lp):
sense, c, rows, signs = lp
print(f" {sense} {c}")
for a, op, r in rows:
print(f" {a} {op} {r}")
print(" signs:", signs)
def solve(lp):
sense, c, rows, signs = lp
s = 1 if sense == "min" else -1
ub = [([s2 * v for v in a], s2 * r) for a, op, r in rows if op != "=" for s2 in [1 if op == "<=" else -1]]
eq = [(a, r) for a, op, r in rows if op == "="]
bnd = {">=0": (0, None), "<=0": (None, 0), "free": (None, None)}
res = linprog([s * v for v in c], A_ub=[a for a, _ in ub] or None, b_ub=[r for _, r in ub] or None,
A_eq=[a for a, _ in eq] or None, b_eq=[r for _, r in eq] or None,
bounds=[bnd[g] for g in signs], method="highs")
return round(float(s * res.fun), 6)
primal = ("max", [1, 2, -1], [([1, 1, 1], "<=", 6), ([1, -1, 0], ">=", -2), ([0, 1, 2], "=", 5)], [">=0", ">=0", "free"])
print("primal:"); show(primal)
d = dual(primal)
print("dual:"); show(d)
print("dual of the dual equals the primal:", dual(d) == primal)
print("optimal values:", solve(primal), solve(d))primal:
max [1, 2, -1]
[1, 1, 1] <= 6
[1, -1, 0] >= -2
[0, 1, 2] = 5
signs: ['>=0', '>=0', 'free']
dual:
min [6, -2, 5]
[1, 1, 0] >= 1
[1, -1, 1] >= 2
[1, 0, 2] = -1
signs: ['>=0', '<=0', 'free']
dual of the dual equals the primal: True
optimal values: 8.333333 8.333333
The row produced a non-positive dual variable, the equation a free one, and the free primal variable an equation in the dual. The two optima agree, as strong duality (next lesson) promises.
Duals of combinatorial LPs
Most duality theorems of combinatorics are a primal and its dual read aloud. The recipe gives three pairs immediately.
| Primal | Dual | Combinatorial reading |
|---|---|---|
| fractional vertex cover: , per edge, | , per vertex, | fractional matching |
| fractional set cover: , per element | , per set | element prices that no set's weight can afford twice: a "packing" of elements |
| shortest - path: , one unit of flow from to | , per arc, free | node potentials, the "pull the strings" picture |
The third pair shows the equation-to-free rule in action: the flow-conservation constraints are equations, so the potentials are free variables, and only differences of potentials matter. The program builds the shortest-path LP for a small graph, dualizes it with the recipe and solves both sides.
from scipy.optimize import linprog
arcs = [("s", "a", 4), ("s", "b", 1), ("b", "a", 2), ("a", "t", 1), ("b", "t", 5)]
nodes = ["s", "a", "b", "t"]
# primal: min sum w_a f_a, flow conservation (out - in) = 1 at s, -1 at t, 0 elsewhere, f >= 0
A_eq = [[(1 if u == v else 0) - (1 if w == v else 0) for u, w, _ in arcs] for v in nodes]
b_eq = [1 if v == "s" else -1 if v == "t" else 0 for v in nodes]
primal = linprog([w for _, _, w in arcs], A_eq=A_eq, b_eq=b_eq, bounds=[(0, None)] * len(arcs), method="highs")
used = [f"{u}->{w}" for (u, w, _), f in zip(arcs, primal.x) if f > 0.5]
print("shortest path length", round(float(primal.fun), 6), "using", used)
# dual (from the recipe): max sum b_v p_v, column per arc: p_u - p_w <= w_uw, p free
dual = linprog([-b for b in b_eq], A_ub=[[row[k] for row in A_eq] for k in range(len(arcs))],
b_ub=[w for _, _, w in arcs], bounds=[(None, None)] * len(nodes), method="highs")
p = {v: float(x) for v, x in zip(nodes, dual.x)}
print("dual value", round(float(-dual.fun), 6))
print("distances d(v) = p(s) - p(v):", {v: round(p["s"] - p[v], 6) for v in nodes})shortest path length 4.0 using ['s->b', 'b->a', 'a->t']
dual value 4.0
distances d(v) = p(s) - p(v): {'s': 0.0, 'a': 3.0, 'b': 1.0, 't': 4.0}
The recipe produced variables with ; writing turns them into the familiar distance labels with , the triangle inequality that Bellman-Ford enforces by relaxation. At the optimum, is the shortest-path distance.
Tip: When you write a dual by hand, write the primal matrix first, then read it column by column. Each primal column (variable) becomes one dual row, and the dual's right-hand side is the primal objective. Check your answer by dualizing back.
Test yourself
The primal is a maximization with a row . What sign does its dual variable have?
- free
A primal variable is free (unrestricted in sign). What is its dual constraint?
- An inequality
- An equation
- No constraint at all
- A non-negativity constraint
What is the dual of the fractional vertex cover LP of a graph?
- Fractional set cover
- Fractional matching: with for every vertex
- Shortest paths
- Maximum flow
Why are the dual variables of the shortest-path LP free?
- Because edge weights may be negative
- Because the primal constraints (flow conservation) are equations
- Because the primal variables are free
- They are not free