Constraints and linear programming

Part 10 — Optimisation and model fitting

Numerical analysis for biologists

About this lecture

So far every optimiser was free to try any parameter value. Biology says no: rates are positive, proportions sum to 1, a cell takes up at most so much glucose.

  • Simple fixes for simple constraints: bounds (L-BFGS-B) and reparameterisation (e^\theta, softmax). Each has a failure.
  • Lagrange multipliers in one picture: at the optimum the gradient of f is parallel to the gradient of the constraint, and the multiplier is a shadow price.
  • Linear programming: linear objective, linear constraints. The optimum is at a corner; the simplex method walks from corner to corner.
  • Biology: flux balance analysis (FBA). Which fluxes maximise growth of a toy metabolic network, which fluxes are not determined, what a knock-out does, and which nutrient limits growth.

Three kinds of constraint

constraint example written as
sign / bound a degradation rate, a background signal k \ge 0, c \ge 0
sum to one diet fractions, cell-type proportions p_i \ge 0,\ \sum_i p_i = 1
capacity uptake of glucose, enzyme or ribosome budget v_\text{glc} \le 10
balance metabolites at steady state S\mathbf v = \mathbf 0

We have already met answers that break them:

A constraint is active at a solution if it holds with equality there (c = 0, v_\text{glc} = 10). Inactive constraints do not change the answer.

A fit that wants a negative background

mRNA decay after a transcription block: signal y = A e^{-kt} + c, background c \ge 0 (synthetic data).

t <- 0:8                                          # hours
y <- c(1.020, 0.577, 0.378, 0.243, 0.125, 0.062, 0.020, 0.010, -0.012)
sse <- function(p) sum((y - (p[1] * exp(-p[2] * t) + p[3]))^2)   # p = (A, k, c)
fit <- optim(c(1, 0.3, 0.1), sse, method = "BFGS")
round(fit$par, 4)
# [1]  1.0366  0.4788 -0.0294
  • The best unconstrained fit has a negative background. The noise in the last points pulled it down.
  • That is not a numerical error: the minimum of the SSE really is at c < 0. The model needs to be told that c \ge 0.

Fix 1: bounds

fitb <- optim(c(1, 0.3, 0.1), sse, method = "L-BFGS-B", lower = c(0, 0, 0))
round(fitb$par, 4)
# [1] 1.0152 0.5214 0.0000
  • optim(method = "L-BFGS-B") takes lower and upper: steps that would leave the box are cut back (projected) onto it.
  • The background sits at the bound, and the half-life changes from 1.45 h to 1.33 h.

At a bound, the gradient is not zero

round(numDeriv::grad(sse, fitb$par), 4)
# [1] 0.0000 0.0000 0.1054
  • In A and k (free) the gradient is 0, as usual. In c it is positive: the SSE would fall if c could decrease, but the bound stops it.
  • That number is the multiplier of the bound: how fast the SSE would fall per unit we relax c \ge 0.
  • Check: after a bounded fit, list the parameters that sit at a bound. The standard errors of Identifiability and uncertainty of fitted parameters assume an interior minimum with zero gradient: for them they are meaningless, and the result depends on the bound you chose.

Fix 2: reparameterise

Optimise an unconstrained \theta and map it into the allowed set:

  • Positive: c = e^{\theta}, as for rate constants in Nonlinear least squares and ODE fitting.
  • Proportions: p = \text{softmax}(\theta) = e^{\theta_i} / \sum_j e^{\theta_j}, with \theta_1 = 0 fixed. Every p_i > 0 and they sum to 1.
sse_log <- function(q) sse(c(q[1], q[2], exp(q[3])))      # c = exp(theta)
fitl <- optim(c(1, 0.3, log(0.1)), sse_log, method = "BFGS")
round(fitl$par, 3); signif(exp(fitl$par[3]), 3); fitl$convergence
# [1]  1.015  0.523 -7.116
# [1] 0.000812
# [1] 1                         # 1 = hit the iteration limit
  • Failure: the best c is 0, which needs \theta = -\infty. BFGS walks towards it until it runs out of iterations; \theta is wherever it stopped (Python stops at -14, Rust at -29).

Lagrange multipliers in one picture

Counts n = (30, 10) of two cell types. Maximise the log-likelihood f(p) = 30 \log p_1 + 10 \log p_2 subject to g(p) = p_1 + p_2 = 1.

  • Grey curves: contours of f. Blue line: the constraint.
  • At the orange point, \nabla f has a component along the line: sliding along it improves f.
  • At the optimum the contour touches the line: \nabla f is parallel to \nabla g: \nabla f = \lambda \nabla g

The multiplier is a shadow price

\nabla f = (30/p_1,\ 10/p_2) and \nabla g = (1, 1), so 30/p_1 = 10/p_2 = \lambda. With p_1 + p_2 = 1: \lambda = 40, p = (0.75, 0.25).

n <- c(30, 10)
f <- function(p) sum(n * log(p))
p_hat <- n / sum(n)
n / p_hat                            # gradient of f at the optimum
# [1] 40 40                          # = lambda * (1, 1)
f(1.01 * p_hat) - f(p_hat)           # relax the constraint: sum = 1.01
# [1] 0.3980132                      # about lambda * 0.01 = 0.4
  • \lambda = how much the best f improves per unit the constraint is relaxed. Economists call it the shadow price of the constraint.
  • Inequalities: the multiplier is \ge 0, and zero if the constraint is inactive (relaxing it changes nothing). These are the KKT conditions; the bounded decay fit and NNLS are examples.

Linear programming

Objective and constraints all linear. A cell makes ATP by respiration (x_1) or fermentation (x_2) (toy numbers):

\max\ 6x_1 + 3x_2 \quad\text{subject to}\quad \begin{aligned} x_1 + x_2 &\le 6 &&\text{carbon supply}\\ 4x_1 + x_2 &\le 12 &&\text{proteome: respiration enzymes are costly}\\ x_1,\ x_2 &\ge 0 \end{aligned}

  • Respiration gives twice the ATP per carbon, but needs four times the enzyme per unit flux.
  • A linear function has no interior maximum: its gradient (6, 3) is never zero. The answer is always on the boundary.
  • Gradient methods are the wrong tool; LP has its own algorithms, exact in a finite number of steps.

The feasible polygon

  • Each constraint keeps one side of a line. Together: a convex polygon (in n dimensions a polytope).
  • Orange: lines of equal ATP, 6x_1 + 3x_2 = z. Push z up until the line leaves the polygon.
  • The last point touched is a corner (vertex): (2, 4), ATP = 24. A mix of both pathways.
  • Fundamental fact: if an LP has an optimum, one of the corners is optimal.

The simplex idea: walk along edges

  1. Start at a corner: (0, 0), ATP 0.
  2. Along which edge does ATP increase? x_1: +6 per unit. Go until a constraint stops you: proteome at x_1 = 3 (carbon would allow 6). Corner (3, 0), ATP 18.
  3. Along the proteome edge, x_2 up by 1 means x_1 down by \tfrac14: ATP changes by 3 - 6/4 = +1.5. Go until carbon stops you: (2, 4), ATP 24.
  4. Along the carbon edge: x_2 up 1, x_1 down 1: 3 - 6 = -3 per unit x_2 (or -1 per unit of proteome freed). Back along the proteome edge: -1.5 per unit x_2 (-2 per unit of carbon freed). No improving edge: optimal.

How many corners?

  • With n variables and m constraints, a corner is where n constraints are active: up to \binom{m}{n} candidates.
  • \binom{4}{2} = 6 here, \binom{100}{50} \approx 10^{29} for a modest problem. Checking every corner is hopeless.
  • The simplex method visits only a short path of improving corners: in practice a small multiple of m steps (in rare worst cases exponentially many).
  • Interior-point methods cut through the inside of the polytope with Newton steps (Newton for systems of equations) and are polynomial in the worst case.
  • Modern solvers (HiGHS, GLPK, Gurobi) have both and pick one.

LP in R: lpSolve::lp

library(lpSolve)
res <- lp("max", objective.in = c(6, 3),
          const.mat = rbind(c(1, 1), c(4, 1)),
          const.dir = c("<=", "<="), const.rhs = c(6, 12),
          compute.sens = TRUE)
res$status; res$solution; res$objval
# [1] 0                    # 0 = success
# [1] 2 4
# [1] 24
res$duals[1:2]             # shadow prices of carbon and proteome
# [1] 2 1
  • lp assumes x \ge 0. Python: scipy.optimize.linprog (HiGHS, minimises); Rust: the minilp crate.
  • Shadow prices: one more unit of carbon gives +2 ATP, one more unit of proteome +1 ATP.

When an LP goes wrong

  • Tie (objective 8x_1 + 2x_2): a whole edge is optimal. The solver returns one corner and does not tell you.
  • Unbounded: a missing constraint. Infeasible: constraints that contradict each other.
  • Check the status every time. lpSolve is not reliable here: on the middle LP it returns status 0 (“success”) with x_2 = 10^{30}, its internal infinity. Look for absurd values.

Try it: corners, edges and shadow prices

Flux balance analysis: the network

Toy network: 6 metabolites, 9 reactions. Glucose (G) is split into pyruvate (P) by two routes (GLY, or BYP1 + BYP2 via X). P is respired (RES, needs O2), fermented to acetate (FER), or built into biomass (BIO).

The stoichiometric matrix

Row = metabolite, column = reaction, entry = how many molecules the reaction makes (+) or uses (−).

rxn <- c("EX_glc", "EX_o2", "GLY", "BYP1", "BYP2", "RES", "FER", "EX_ac", "BIO")
S <- rbind(G   = c(1, 0, -1, -1,  0,  0,  0,  0,  0),
           O2  = c(0, 1,  0,  0,  0, -2,  0,  0,  0),
           X   = c(0, 0,  0,  1, -1,  0,  0,  0,  0),
           P   = c(0, 0,  2,  0,  2, -1, -1,  0, -1),
           ATP = c(0, 0,  2,  0,  2, 11,  1,  0, -5),
           Ac  = c(0, 0,  0,  0,  0,  0,  1, -1,  0))
colnames(S) <- rxn
qr(S)$rank
# [1] 6
  • \frac{d}{dt}(\text{concentrations}) = S\mathbf v. Steady state: S\mathbf v = \mathbf 0: every metabolite is made as fast as it is used.
  • 6 independent equations, 9 unknowns: elimination (as in Gaussian elimination as LU) leaves 3 free fluxes, a 3-dimensional null space of solutions.

FBA as a linear program

\max_{\mathbf v}\ v_\text{BIO} \quad\text{subject to}\quad S\mathbf v = \mathbf 0,\quad \mathbf v \ge \mathbf 0,\quad v_\text{glc} \le 10,\quad v_{\text{O}_2} \le 15

fba <- function(ub = c(10, 15), ko = integer(0)) {
  B <- diag(9)[c(1, 2, ko), , drop = FALSE]     # rows picking v_glc, v_o2, knock-outs
  lp("max", objective.in = c(rep(0, 8), 1),      # maximise v_BIO
     const.mat = rbind(S, B), const.dir = c(rep("=", 6), rep("<=", nrow(B))),
     const.rhs = c(rep(0, 6), ub, rep(0, length(ko))), compute.sens = TRUE)
}
sol <- fba(); sol$objval
# [1] 15
setNames(sol$solution, rxn)
# EX_glc  EX_o2    GLY   BYP1   BYP2    RES    FER  EX_ac    BIO
#     10     10     10      0      0      5      0      0     15
  • All glucose used, pure respiration, no acetate; oxygen uptake 10 of the 15 allowed.

The optimum is not unique: flux variability

Flux variability analysis (FVA): fix growth at its maximum (15), then minimise and maximise each flux in turn, 2 \times 9 more LPs.

  • GLY and the bypass can share the glucose in any ratio: each ranges over [0, 10].
  • The solver’s GLY = 10 was one arbitrary corner.
  • Like a non-identifiable parameter (Identifiability and uncertainty of fitted parameters): the objective cannot tell the routes apart. Report ranges, not one flux vector.

Knock-outs

ko <- sapply(1:9, function(j) fba(ko = j)$objval)    # remove one reaction at a time
round(setNames(ko, rxn), 3)
# EX_glc  EX_o2    GLY   BYP1   BYP2    RES    FER  EX_ac    BIO
#  0.000  6.667 15.000 15.000 15.000  6.667 15.000 15.000  0.000
fba(ko = c(3, 4))$objval                              # GLY and BYP1 together
# [1] 0
  • Essential: glucose uptake (and BIO itself). No respiration: growth drops to 6.67, by fermentation alone (anaerobic growth).
  • GLY and BYP1 are each dispensable, but together lethal: a synthetic lethal pair, from redundancy.

Shadow prices: what limits growth?

fba()$duals[7:8]                        # rows 7, 8: glucose and oxygen bounds
# [1] 1.5 0.0
round(fba(ub = c(10, 4))$duals[7:8], 3)   # less oxygen
# [1] 0.667 0.833
  • Plenty of oxygen: one more glucose gives +1.5 growth, oxygen has price 0 (its bound is inactive: 10 used of 15). Glucose limits growth.
  • Oxygen limited to 4: both limit; growth 10, and acetate is secreted (8): overflow metabolism.

Scanning the oxygen limit

  • Below 10: each unit of oxygen gives 5/6 = 0.833 more growth and less acetate. Above 10: oxygen is in excess, price 0.
  • Shadow prices are local: they hold until another constraint becomes active (the kink at 10), where the price is not unique.

FBA checklist

  • Status first. Infeasible: the bounds contradict each other or the model misses a reaction. Unbounded: a forgotten uptake bound or an ATP-making cycle.
  • S\mathbf v = \mathbf 0 check on the returned fluxes, with a tolerance (fluxes of 10^{-12} are zeros).
  • Never trust one flux vector. Run FVA; a flux is determined only if its range is narrow.
  • Read the shadow prices to see which bounds matter; they only hold until the next kink.
  • Units and bounds decide the answer: an uptake bound of 10 vs 15 is a modelling choice, not a fact.

Production tools

  • COBRA Toolbox (MATLAB) and cobrapy (Python) are the standard: they read models in SBML, set bounds, run FBA, FVA, knock-out screens and parsimonious FBA, and call an LP solver (GLPK, HiGHS, Gurobi, CPLEX).
  • Genome-scale models: E. coli iML1515 has 2712 reactions and 1877 metabolites; human Recon3D about 13 000 reactions. S is sparse (Structure: symmetric, banded, sparse): a reaction touches a handful of metabolites.
  • The toy model is exactly what these tools do, at a size where you can check every number by hand.

Summary

  • Biological constraints: signs, sums to 1, capacities, steady state. A constraint is active if it holds with equality.
  • Bounds (L-BFGS-B): the answer can sit at a bound, where the gradient is not zero. Reparameterisation (e^\theta, softmax) fails when the answer is on the boundary: \theta runs to -\infty.
  • Lagrange: at a constrained optimum \nabla f = \lambda \nabla g; \lambda is the shadow price, 0 for inactive constraints.
  • LP: the optimum is at a corner of the feasible polytope; simplex walks along improving edges; solvers: lpSolve::lp, scipy.optimize.linprog (HiGHS), minilp. Check the status: tie, unbounded, infeasible.
  • FBA: maximise growth subject to S\mathbf v = \mathbf 0 and bounds. Optimal fluxes are often not unique (FVA), knock-outs are one LP each, shadow prices show which nutrient limits growth.

Next: Part 11, The diffusion (heat) equation by finite differences.