TExcelTAD

Formulating Linear Programs

Many optimization problems can be written in one common language: choose real numbers x1,…,xnx_1, \ldots, x_n that maximize (or minimize) a linear function, subject to linear inequalities and equations. Such a problem is a linear program (LP). Linear programs can be solved in polynomial time, and very fast in practice, so writing a problem as an LP is often the quickest route to an efficient algorithm. This lesson is about the formulation: how to express a problem, the standard forms solvers expect, and what can go wrong. The geometry and the simplex method are taught in full in the Optimization course (Linear Programs, The Simplex Method).

A first example

A workshop makes tables and chairs. A table brings a profit of 3 and a chair 2. Each table needs 2 hours of cutting and 1 hour of finishing; each chair needs 1 hour of cutting and 3 hours of finishing. There are 10 hours of cutting and 15 hours of finishing per day, and the varnish suffices for at most 4 tables. With xx tables and yy chairs:

maximize3x+2ysubject to2x+y≤10cuttingx+3y≤15finishingx≤4varnishx,y≥0.\begin{aligned} \text{maximize} \quad & 3x + 2y \\ \text{subject to} \quad & 2x + y \le 10 && \text{cutting} \\ & x + 3y \le 15 && \text{finishing} \\ & x \le 4 && \text{varnish} \\ & x, y \ge 0 . \end{aligned}

The feasible region, the set of points satisfying every constraint, is a convex polygon. Each value zz of the objective defines a line 3x+2y=z3x + 2y = z; pushing that line in the objective's direction until it last touches the polygon gives the optimum, and it always last touches at a vertex (or along an edge, when the edge is parallel to the line). The lab shows this polygon; turn the objective with the angle slider.

00224466881010maximise 0.83x + 0.56ysubject to2x + y ≤ 10x + 3y ≤ 15x ≤ 4x ≥ 0, y ≥ 0LP optimum (a vertex)best integer pointlevel line c · v = z*

Since an optimum sits at a vertex, a two-variable LP can be solved by brute force: intersect every pair of constraint lines, keep the intersection points that satisfy all constraints, and evaluate the objective at each.

python · try it yourself
from fractions import Fraction
from itertools import combinations

# constraints a1*x + a2*y <= b, including x >= 0 and y >= 0 written as -x <= 0, -y <= 0
cons = [(2, 1, 10), (1, 3, 15), (1, 0, 4), (-1, 0, 0), (0, -1, 0)]
objective = (3, 2)

def intersect(c1, c2):
    (a, b, e), (c, d, f) = c1, c2
    det = a * d - b * c
    if det == 0:
        return None                              # parallel lines
    return (Fraction(e * d - b * f, det), Fraction(a * f - e * c, det))

vertices = set()
for c1, c2 in combinations(cons, 2):
    p = intersect(c1, c2)
    if p and all(a * p[0] + b * p[1] <= rhs for a, b, rhs in cons):
        vertices.add(p)
for v in sorted(vertices):
    print(f"vertex ({v[0]}, {v[1]}): profit {objective[0] * v[0] + objective[1] * v[1]}")
best = max(vertices, key=lambda v: objective[0] * v[0] + objective[1] * v[1])
print("optimum:", tuple(str(c) for c in best))
vertex (0, 0): profit 0
vertex (0, 5): profit 10
vertex (3, 4): profit 17
vertex (4, 0): profit 12
vertex (4, 2): profit 16
optimum: ('3', '4')

Three tables and four chairs give the best profit, 17, using all the cutting and finishing time. With nn variables and mm constraints this brute force examines up to (mn)\binom{m}{n} candidate vertices, which is exponential; the simplex method walks from vertex to better neighbouring vertex instead.

Standard and slack form

Solvers and proofs use fixed formats. An LP is in standard form if it maximizes cTxc^T x subject to Ax≤bAx \le b and x≥0x \ge 0. Every LP can be converted:

Feature Conversion
minimize cTxc^T x maximize −cTx-c^T x
a constraint aTx≥βa^T x \ge \beta −aTx≤−β-a^T x \le -\beta
an equation aTx=βa^T x = \beta two inequalities aTx≤βa^T x \le \beta and −aTx≤−β-a^T x \le -\beta
a free variable xjx_j (any sign) xj=xj′−xj′′x_j = x_j' - x_j'' with xj′,xj′′≥0x_j', x_j'' \ge 0

Slack form turns each inequality aiTx≤bia_i^T x \le b_i into an equation by adding a slack variable si=bi−aiTx≥0s_i = b_i - a_i^T x \ge 0. The simplex method works in this form: the slack variables measure how much room each constraint has left.

An LP is infeasible if no point satisfies the constraints, unbounded if the objective can grow without limit, and otherwise it has an optimal solution (with an optimal vertex, if the region has one). The next program solves the workshop LP and two broken variants with SciPy's linprog, which minimizes, so the objective is negated.

python · try it yourself
from scipy.optimize import linprog

def solve(c, A, b, name):
    res = linprog([-v for v in c], A_ub=A, b_ub=b, bounds=[(0, None)] * len(c), method="highs")
    if res.status == 0:
        print(f"{name:24} optimal, x = {[round(float(v), 6) for v in res.x]}, value {round(float(-res.fun), 6)}")
    else:
        print(f"{name:24} {['', 'iteration limit', 'infeasible', 'unbounded'][res.status]}")

solve([3, 2], [[2, 1], [1, 3], [1, 0]], [10, 15, 4], "workshop")
solve([3, 2], [[2, 1], [1, 3], [-1, -1]], [10, 15, -20], "need 20 items as well")
solve([3, 2], [[1, -1]], [4], "only x - y <= 4")
workshop                 optimal, x = [3.0, 4.0], value 17.0
need 20 items as well    infeasible
only x - y <= 4          unbounded

Asking for at least 20 items in total (written −x−y≤−20-x - y \le -20) contradicts the cutting limit, and with only the constraint x−y≤4x - y \le 4 both xx and yy can grow together forever.

Integers make it hard

The workshop's optimum happens to be an integer point. In general it is not, and rounding a fractional optimum can give an infeasible or poor point. The program uses the lab's second polygon ("fractional corners"), maximizes 2x+3y2x + 3y, and compares the LP optimum with the best integer point found by trying every lattice point.

python · try it yourself
from fractions import Fraction as F
from itertools import combinations

cons = [(1, 1, F(9, 2)), (-1, 2, 3), (2, -1, F(13, 2)), (-1, 0, 0), (0, -1, 0)]
obj = lambda p: 2 * p[0] + 3 * p[1]
feasible = lambda p: all(a * p[0] + b * p[1] <= r for a, b, r in cons)

points = []
for (a, b, e), (c, d, f) in combinations(cons, 2):
    det = a * d - b * c
    if det:
        p = ((e * d - b * f) / det, (a * f - e * c) / det)
        if feasible(p):
            points.append(p)
lp = max(points, key=obj)
ints = [(x, y) for x in range(10) for y in range(10) if feasible((x, y))]
ip = max(ints, key=obj)
print("LP optimum  ", tuple(str(v) for v in lp), "value", obj(lp))
print("integer opt.", ip, "value", obj(ip))
print("rounded LP point", (round(lp[0]), round(lp[1])), "feasible:", feasible((round(lp[0]), round(lp[1]))))
LP optimum   ('2', '5/2') value 23/2
integer opt. (2, 2) value 10
rounded LP point (2, 2) feasible: True

The LP optimum (2,5/2)(2, 5/2) is worth 23/223/2, the best integer point only 10; the difference is the integrality gap of this instance. Here rounding happens to land on the integer optimum (Python rounds 2.52.5 to the even number 2), but rounding up instead would give (2,3)(2, 3), which violates −x+2y≤3-x + 2y \le 3, and in higher dimensions rounded points are often infeasible or far from optimal. Requiring integer variables gives integer linear programming, which is NP-hard (the reduction from 3-CNF-SAT is a short exercise once NP-Completeness and NP-Hardness is in place). Yet LPs with integer variables relaxed to real ones are the starting point of most approximation algorithms: solve the LP, then round cleverly. That is the subject of Linear Programming & Duality for Algorithms.

How LPs are solved

  • Simplex (Dantzig, 1947) moves along edges between vertices. It is extremely fast in practice, but for the usual pivoting rules there are inputs (Klee-Minty cubes) on which it visits exponentially many vertices.
  • Ellipsoid method (Khachiyan, 1979): the first proof that linear programming is in polynomial time, important in theory, slow in practice.
  • Interior-point methods (Karmarkar, 1984) are polynomial and competitive with simplex on large problems (Interior-Point Methods).

So linear programming is in P: an LP whose numbers have LL bits in total can be solved in time polynomial in LL.

In C++

The vertex enumeration in C++, for the workshop LP. With double arithmetic the feasibility test needs a small tolerance.

cpp · try it yourself
#include <cstdio>
#include <vector>

struct Con { double a, b, rhs; };                 // a x + b y <= rhs

int main() {
    std::vector<Con> cons = {{2, 1, 10}, {1, 3, 15}, {1, 0, 4}, {-1, 0, 0}, {0, -1, 0}};
    double cx = 3, cy = 2, best = -1, bx = 0, by = 0;
    int vertices = 0;
    for (size_t i = 0; i < cons.size(); i++)
        for (size_t j = i + 1; j < cons.size(); j++) {
            double det = cons[i].a * cons[j].b - cons[i].b * cons[j].a;
            if (det == 0) continue;
            double x = (cons[i].rhs * cons[j].b - cons[i].b * cons[j].rhs) / det;
            double y = (cons[i].a * cons[j].rhs - cons[i].rhs * cons[j].a) / det;
            bool ok = true;
            for (auto& c : cons) ok = ok && c.a * x + c.b * y <= c.rhs + 1e-9;
            if (!ok) continue;
            vertices++;
            if (cx * x + cy * y > best) { best = cx * x + cy * y; bx = x; by = y; }
        }
    std::printf("%d feasible vertices, optimum (%.2f, %.2f) with profit %.2f\n", vertices, bx, by, best);
}
5 feasible vertices, optimum (3.00, 4.00) with profit 17.00

Test yourself

How is an equation aTx=βa^T x = \beta written in standard form?

  1. It cannot be
  2. As the two inequalities aTx≤βa^T x \le \beta and −aTx≤−β-a^T x \le -\beta
  3. As aTx≤βa^T x \le \beta alone
  4. With a free variable

Where is the optimum of a feasible, bounded LP whose feasible region has vertices?

  1. Always in the interior
  2. At some vertex (possibly along a whole edge or face that contains vertices)
  3. At the origin
  4. At the centre of gravity

What does a slack variable measure?

  1. The objective value
  2. How far a constraint is from being tight: si=bi−aiTxs_i = b_i - a_i^T x
  3. The number of iterations
  4. The integrality gap

Which statement is true?

  1. Linear programming and integer linear programming are both in P
  2. Linear programming is in P; integer linear programming is NP-hard
  3. Both are NP-hard
  4. The simplex method runs in polynomial time on every input