TExcelTAD
Home › Linear Programming & Duality for Algorithms › Building the Dual Mechanically

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 3x+2y3x + 2y subject to 2x+y≤102x + y \le 10, x+3y≤15x + 3y \le 15, x≤4x \le 4, x,y≥0x, y \ge 0. Every feasible point satisfies any non-negative combination of the constraints. Multiply them by y1,y2,y3≥0y_1, y_2, y_3 \ge 0 and add:

(2y1+y2+y3) x+(y1+3y2) y≤10y1+15y2+4y3.(2y_1 + y_2 + y_3)\, x + (y_1 + 3y_2)\, y \le 10y_1 + 15y_2 + 4y_3 .

If the coefficient of xx is at least 3 and that of yy at least 2, then, because x,y≥0x, y \ge 0, the left side is at least 3x+2y3x + 2y. So every such choice of multipliers proves an upper bound on the objective. For example y=(75,15,0)y = (\frac{7}{5}, \frac{1}{5}, 0) gives coefficients (3,2)(3, 2) and the bound 14+3=1714 + 3 = 17, which is exactly the optimum. Finding the best bound is itself an LP:

min⁡  10y1+15y2+4y3s.t.2y1+y2+y3≥3,y1+3y2≥2,y≥0.\min \; 10y_1 + 15y_2 + 4y_3 \quad \text{s.t.} \quad 2y_1 + y_2 + y_3 \ge 3, \quad y_1 + 3y_2 \ge 2, \quad y \ge 0 .

In matrix form, the dual of max⁡{cTx:Ax≤b, x≥0}\max \{ c^T x : Ax \le b,\ x \ge 0 \} is min⁡{bTy:ATy≥c, y≥0}\min \{ b^T y : A^T y \ge c,\ y \ge 0 \}: one dual variable per primal constraint, one dual constraint per primal variable, and the roles of bb and cc swapped.

The recipe for every kind of constraint

When the primal mixes ≤\le, ≥\ge 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: ≥0\ge 0 on a ≤\le row, ≤0\le 0 on a ≥\ge row, any sign on an equation. And a dual constraint must make the combination dominate the objective: ≥cj\ge c_j if xj≥0x_j \ge 0, ≤cj\le c_j if xj≤0x_j \le 0, =cj= c_j if xjx_j is free.

Primal (maximize cTxc^T x) Dual (minimize bTyb^T y)
row ii: aiTx≤bia_i^T x \le b_i yi≥0y_i \ge 0
row ii: aiTx≥bia_i^T x \ge b_i yi≤0y_i \le 0
row ii: aiTx=bia_i^T x = b_i yiy_i free
xj≥0x_j \ge 0 column jj: ∑iaijyi≥cj\sum_i a_{ij} y_i \ge c_j
xj≤0x_j \le 0 column jj: ∑iaijyi≤cj\sum_i a_{ij} y_i \le c_j
xjx_j free column jj: ∑iaijyi=cj\sum_i a_{ij} y_i = c_j

Read from right to left, the table gives the dual of a minimization. A useful mnemonic: "natural" constraints (a ≤\le row in a max problem, a ≥\ge 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.

python · try it yourself
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 ≥\ge row produced a non-positive dual variable, the equation a free one, and the free primal variable x3x_3 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: min⁡∑vxv\min \sum_v x_v, xu+xv≥1x_u + x_v \ge 1 per edge, x≥0x \ge 0 max⁡∑eye\max \sum_e y_e, ∑e∋vye≤1\sum_{e \ni v} y_e \le 1 per vertex, y≥0y \ge 0 fractional matching
fractional set cover: min⁡∑SwSxS\min \sum_S w_S x_S, ∑S∋exS≥1\sum_{S \ni e} x_S \ge 1 per element max⁡∑eye\max \sum_e y_e, ∑e∈Sye≤wS\sum_{e \in S} y_e \le w_S per set element prices that no set's weight can afford twice: a "packing" of elements
shortest ss-tt path: min⁡∑awafa\min \sum_a w_a f_a, one unit of flow from ss to tt max⁡dt−ds\max d_t - d_s, dv−du≤wuvd_v - d_u \le w_{uv} per arc, dd 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 dvd_v 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.

python · try it yourself
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 pvp_v with pu−pw≤wuwp_u - p_w \le w_{uw}; writing dv=ps−pvd_v = p_s - p_v turns them into the familiar distance labels with dw≤du+wuwd_w \le d_u + w_{uw}, the triangle inequality that Bellman-Ford enforces by relaxation. At the optimum, dtd_t 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 aiTx≥bia_i^T x \ge b_i. What sign does its dual variable yiy_i have?

  1. yi≥0y_i \ge 0
  2. yi≤0y_i \le 0
  3. free
  4. yi=0y_i = 0

A primal variable is free (unrestricted in sign). What is its dual constraint?

  1. An inequality ≥cj\ge c_j
  2. An equation ∑iaijyi=cj\sum_i a_{ij} y_i = c_j
  3. No constraint at all
  4. A non-negativity constraint

What is the dual of the fractional vertex cover LP of a graph?

  1. Fractional set cover
  2. Fractional matching: max⁡∑eye\max \sum_e y_e with ∑e∋vye≤1\sum_{e \ni v} y_e \le 1 for every vertex
  3. Shortest paths
  4. Maximum flow

Why are the dual variables of the shortest-path LP free?

  1. Because edge weights may be negative
  2. Because the primal constraints (flow conservation) are equations
  3. Because the primal variables are free
  4. They are not free