Algorithmcore
Flux balance analysis
Also called FBA.
Find the steady-state fluxes of a metabolic network that maximize an objective such as growth, as a linear program over S v = 0 and bounds.
- Time
- O(2^(3m + n) (n + m) m) worstO((n + m) m) per_pivot
- Space
- O(n m) extra
- Where
- m = the number of reactions; n = the number of metabolites
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Amit Varma, Bernhard O. Palsson, 1994
Flux balance analysis (FBA) computes the reaction rates of a metabolic network at steady state without any kinetic constants. It uses only the stoichiometric matrix , lower and upper bounds on each flux, and an objective, most often the flux of a biomass reaction that stands for growth. Steady state means : each internal metabolite is made as fast as it is used. FBA picks, among all flux vectors that satisfy these linear constraints, one that maximizes the objective. This is one linear program with variables (one per reaction) and equality rows (one per metabolite), so it is solved exactly and fast, also for genome-scale networks with thousands of reactions. The optimal value is unique. The optimal flux vector often is not, and flux variability analysis measures how much it can change.
In plain words
Think of a cell as a factory with many machines. Each machine turns some parts into other parts. Parts that stay inside the factory must not pile up and must not run out, so for every inside part the machines that make it and the machines that use it must balance. Some machines have a speed limit, for example the door that lets food in.
Among all the ways to run the machines that keep every part in balance and obey the limits, FBA picks one that makes the most of one chosen output, usually new cell material. It does not need to know how each machine works inside, only what goes in and what comes out. The answer says how fast the cell can grow, and one way to run the machines that gets there. Often many other ways reach the same growth.
The problem
Input. A network with internal metabolites and reactions, given by:
- the stoichiometric matrix , where is the number of molecules of metabolite that reaction makes (negative if it uses them);
- bounds for each flux, where may be and may be . An irreversible reaction has . An uptake reaction has an upper bound set by the medium. A knocked-out gene sets for its reactions;
- an objective vector , usually the unit vector of the biomass reaction.
Fluxes are in mmol per gram of dry weight per hour, and the biomass flux is then the growth rate in 1/h.
Output. The status (optimal, infeasible or unbounded), and in the optimal case an optimal flux vector and the optimum of
Exchange reactions with the medium (one side of the reaction is empty) are columns of like any other, so the network is open and has non-zero solutions.
The algorithm
FBA is the LP above. The work is in the LP solver. The version here writes the LP in the standard form , , , and solves it with the two-phase simplex method and Bland's rule, in exact rational arithmetic.
FBA(S, lb, ub, c)- 1
for each reaction j: v_j ← lb_j + y_j if lb_j is finite, else v_j ← ub_j - y_j if ub_j is finite, else v_j ← y_j' - y_j'' - 2
rewrite each row of S v = 0 in the variables y, with the constant terms moved to the right side b - 3
for each j with lb_j and ub_j finite: add the row y_j + s_j = ub_j - lb_j with a slack s_j ≥ 0 - 4
d ← the cost of -c v in the variables y - 5
(status, y) ← TWO-PHASE-SIMPLEX(A, b, d) with Bland's rule - 6
if status is infeasible or unbounded then return status - 7
v ← the fluxes from y by the formulas of line L1 - 8
return (v, c v)
Line L1 makes every variable non-negative. A reaction with only an upper bound is reflected, and a free reaction with no finite bound is split into a forward and a backward part. Line L3 turns each finite upper bound into an equation. Line L4 changes the maximization into a minimization. Phase 1 of line L5 finds a feasible basis or shows that none exists. Phase 2 moves from vertex to vertex of the feasible polyhedron. Bland's rule picks the entering variable with the smallest index among those with a negative reduced cost, and the leaving variable with the smallest index among the tied rows of the ratio test, so the method cannot cycle on a degenerate vertex.
Example
Take the toy network N with three internal metabolites: a substrate , an energy carrier and a by-product .
| reaction | equation | bounds |
|---|---|---|
| EX_A | ||
| RESP1 | ||
| RESP2 | ||
| FERM | ||
| EX_P | ||
| BIO |
RESP1 and RESP2 are two isozymes or two routes with the same net equation. The objective is the flux of BIO. Write for the uptake, for the total respiration , for the fermentation and for growth. The balance of gives , the balance of gives , and the balance of gives . So , which is largest with and :
The exact simplex method of the implementation returns the vertex with . The optimum is a whole segment, not a point: the growth rate is determined, but the split between RESP1 and RESP2 is not.
The LP dual explains the numbers. The shadow price of the uptake bound is : one more unit of gives more growth, and . The reduced cost of FERM is : each unit of fermentation flux costs a third of a unit of growth, which matches .
Knockouts change the bounds only. With RESP1 knocked out, RESP2 takes over and again. With both RESP1 and RESP2 knocked out, the only route left is fermentation: and , so with , and the cell now secretes 5 units of . With EX_A knocked out, . The tests check these values, and on random small networks they compare the result with the best vertex of the flux polytope found by brute force and with the value of the dual LP.
Correctness
The substitution of line L1 maps the box onto the set (with the rows of line L3 for the finite upper bounds), and it is linear plus a constant, so the feasible sets of the two LPs correspond and the objectives differ only by a constant and a sign. A split free variable is covered because every real number is a difference of two non-negative numbers. So the LP of line L5 is infeasible, unbounded or optimal exactly when the FBA problem is, and an optimal maps to an optimal . The two-phase simplex method with Bland's rule ends after finitely many pivots (Bland 1977), with a proof of infeasibility after phase 1, a ray of unbounded improvement, or a basis whose reduced costs are all non-negative, which is optimal by weak duality. The full proof is below.
Proof: FBA by the exact two-phase simplex method returns the status and an optimum of the flux LPfull
Fix the data of the page: an matrix , bounds and , and . Write for the flux polyhedron and (FBA) for the problem . We show that the code returns "infeasible" if is empty, "unbounded" if has no upper bound on , and otherwise a vector with . All arithmetic is exact in , so no rounding enters the argument.
Lemma 1 (the change of variables). Let lines L1 to L4 build , , and the affine map of line L7, and let . If some , then is empty. Otherwise , and for all , with a constant that the code does not need.
Proof. If , no satisfies , and the code returns "infeasible" before line L2. Otherwise, line L1 writes as when is finite, as when only is finite, and as when both bounds are infinite. In the first case is the same as , and line L3 adds the row with when is finite, which is the same as . In the second case is the same as . In the third case every real is for some , for example and . So for every with the bound rows satisfied, obeys the bounds, and every that obeys the bounds is for such a . Line L2 writes the row as , that is, , which is row of . So if and only if , and . Line L4 sets , so , and .
By Lemma 1, is empty if and only if is empty, has no lower bound on if and only if has no upper bound on , and minimizes on if and only if maximizes on : for any pick with , then . It remains to show that line L5 solves .
Lemma 2 (Bland's rule terminates). Let a simplex tableau be in canonical form for a feasible basis, and let each pivot choose the entering column as the smallest index with a negative reduced cost and the leaving row by the minimum ratio test, ties broken by the smallest index of the basic variable. Then after finitely many pivots the method stops, either with all reduced costs non-negative or with an entering column that has no positive entry.
Proof. This is Bland's theorem (Bland 1977). We give the standard argument. There are finitely many bases, and each pivot keeps the basis feasible because of the ratio test, and does not increase the objective. A non-degenerate pivot decreases it strictly, so a basis seen once can come back only within a run of degenerate pivots, where the objective and the vertex stay fixed. Assume such a cycle exists. Call a variable fickle if it enters or leaves the basis during the cycle, and let be the largest fickle index. Take a tableau of the cycle where leaves, with entering variable , , and a tableau of the cycle where enters. In the reduced costs satisfy and for , since is the smallest index with a negative reduced cost. Consider the direction of that increases by 1, keeps the other non-basic variables at 0, and changes the basic variables so that . Then . The reduced costs of differ from by a row combination of , so . So some index has . Then is not basic in (basic reduced costs are 0), and , so or is basic in . If , then and . If is basic in and non-basic in , then is fickle. So in both cases is fickle and . For : and , since leaves in , which needs a positive pivot entry, and is minus that entry; then , a contradiction. So , and forces and . As , , so is basic in . A fickle basic variable of a degenerate cycle has the value 0 in every tableau of the cycle, so in , and means that row of has a positive entry in column with ratio 0, the same ratio as the row of . The tie rule then picks the smaller index to leave, not . This contradicts the choice of . So no cycle exists, and the method stops after finitely many pivots.
Lemma 3 (the stopping conditions). If the method of Lemma 2 stops with all reduced costs non-negative, the basic solution is optimal. If it stops at an entering column with no positive entry, the objective has no lower bound on the feasible set.
Proof. Let be the basic solution and the reduced costs, with the simplex multipliers. For every feasible , , since , , and is 0 on the basic columns. This is weak duality with the dual solution . In the second case, increasing by and moving the basic variables along the column keeps , and every basic variable changes by times a non-positive entry, so it stays non-negative. The objective changes by .
Lemma 4 (phase 1). Line L5 first flips the rows with , then minimizes over , , from the feasible basis . The phase 1 optimum is 0 if and only if is non-empty. After the cleanup, the code has a feasible basis of in canonical form, for the matrix without some redundant rows, and these rows have the same solution set as .
Proof. Flipping a row multiplies an equation by , which keeps the solution set. The phase 1 LP is feasible and bounded below by 0, so by Lemmas 2 and 3 its simplex run ends at an optimum. If contains some , then is phase 1 feasible with value 0, so the optimum is 0. If the optimum is 0, the basic solution has and so . Then the code returns "infeasible" exactly when is empty. In the case of value 0, every artificial variable that is still basic has the value 0. If its row has a non-zero entry in some column of , a pivot on that entry makes basic. The right side of the row is 0, so the pivot changes no value and the basis stays feasible. If the row has only zeros in the columns, then this row of the current tableau, which is a combination of the original rows, says on the variables. So the original row is a combination of the other rows, and deleting it keeps the solution set. After this, all basic variables are variables, and the code drops the artificial columns.
Theorem. For every input, the code returns "infeasible" if and only if is empty, "unbounded" if and only if has no upper bound on , and otherwise with and .
Proof. If some , Lemma 1 gives the answer. Otherwise, by Lemma 4 phase 1 decides whether is empty, and by Lemma 1 this decides whether is empty. If is not empty, phase 2 starts from a feasible basis, and with the row of reduced costs set from in the code, it stops after finitely many pivots by Lemma 2. By Lemma 3 it returns either "unbounded", with no lower bound for on , or an optimal . In the empty-row case, and is optimal exactly when ; otherwise one coordinate with can grow without bound, and the code returns these two answers. By the remark after Lemma 1, the answers carry over to (FBA), and line L7 maps to , which is optimal. Line L8 computes from itself, so it does not need the constant .
Remark (uniqueness). The theorem says that is the optimum and is one optimal vector. The set of optimal vectors is the face , which can contain more than one point, as in the example of the page. The code returns the vertex of that Bland's rule reaches first, so a different order of the reactions can return a different optimal vector with the same .
Complexity
- Size. The LP has flux variables and equality rows, plus one variable for each free reaction and one row and one slack for each reaction with two finite bounds. So the standard form has at most columns and rows.
- Polynomial time. Linear programming is in P (LP in P), by the ellipsoid method and by interior point methods. So FBA takes time polynomial in , and the encoding length of the data. This is a theorem about the worst case.
- Simplex. Each pivot costs arithmetic operations on the tableau. With Bland's rule no basis comes back within a phase, so the number of pivots is at most the number of bases. Phase 1 has at most columns, which gives the crude bound of the front matter. The number of pivots can be exponential in the worst case (Avis and Chvátal 1978 gave such examples for Bland's rule, as the Klee-Minty cube does for Dantzig's rule). On metabolic networks the simplex method is fast in practice; this is an observation, not a bound.
- Exact arithmetic. With rational data, the code works with fractions. The size of the numbers stays polynomial in the input if the tableau is kept in reduced form, but the constant is much larger than in floating point.
- Space. for the tableau, which is when the bound rows are kept implicit, as bounded simplex codes do.
Properties
- Exact. The optimal value is exact. With floating point LP solvers it is exact up to the solver tolerance.
- One value, many solutions. The optimum is unique, but the set of optimal flux vectors is a face of the polyhedron, often of positive dimension. Parallel routes, isozymes and internal cycles are the usual causes.
- No kinetics. FBA uses no rate laws and no concentrations. Its predictions depend on the bounds and the objective, which are modeling choices.
- Steady state only. It gives one time-independent state. Changes in the medium over time need dynamic FBA.
- The objective is a hypothesis. Maximal growth is a heuristic about what the cell does. Ibarra, Edwards and Palsson (2002) measured that E. coli grown for many generations on glycerol reached the growth rate that FBA predicted; this is a measurement under those conditions, not a law.
Variants and improvements
- Flux variability analysis. The range of each flux over the optimal face (FVA, Mahadevan and Schilling 2003).
- Parsimonious FBA. After maximizing growth, minimize the total flux at that growth. It picks a sparse optimum and removes most internal cycles.
- Loopless FBA. Forbid flux around internal cycles with no net reaction, which breaks the second law of thermodynamics, by adding integer variables (Schellenberger, Lewis and Palsson 2011).
- Knockout analysis. Set the bounds of the reactions of a gene to zero and solve again. MOMA replaces the objective by the distance to the wild type, and OptKnock searches for the knockout set that couples a product to growth.
- Dynamic FBA. Solve one FBA problem per time step and update the medium (dynamic FBA).
- Regulatory and thermodynamic constraints. Add Boolean rules that switch reactions off, or bounds from the Gibbs energies of the reactions.
When to use it
Use FBA when the network is known but the kinetics are not, which is the usual case for whole-cell metabolism. It answers questions about capacity: the highest growth rate on a medium, the highest yield of a product, whether a knockout is lethal, which nutrients are essential. It is the base of the other constraint-based methods on the constraint-based modeling page. Do not use one FBA solution as the flux state of the cell: report the optimum and the ranges from FVA, or add data that fix the fluxes. For concentrations, transients or regulation, a kinetic model is needed.
Pitfalls
- Reading one optimal vector. The solver returns one vertex of the optimal face, and another solver or another reaction order may return another. Conclusions about single fluxes need FVA.
- Missing uptake bounds. If no exchange reaction is bounded, the LP is often unbounded, as in network N without the bound on EX_A.
- Internal cycles. A cycle of reversible reactions with no net effect can carry any flux without changing growth. It shows up as huge fluxes in the solution and as infinite ranges in FVA.
- Signs of exchange reactions. Conventions differ: in many models the exchange is written , and uptake is a negative flux with a negative lower bound. Mixing the conventions gives a wrong medium.
- Units of the biomass reaction. The biomass flux is a growth rate only if the coefficients of the biomass reaction are in mmol per gram of dry weight.
- Tolerances. Floating point solvers report values such as for zero fluxes. Use a tolerance, or exact arithmetic on small models.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/flux-balance-analysis/. The authors are listed in prov/TC2TH5.jsonl.
"""Flux balance analysis as one exact linear program.
A network has n metabolites and m reactions. S is the n x m stoichiometric
matrix (a list of n rows of length m), lb and ub are the flux bounds (None
means minus or plus infinity) and c is the objective vector, usually the unit
vector of the biomass reaction. FBA solves
maximize c v subject to S v = 0, lb <= v <= ub.
fba() writes this LP in the standard form min d y, A y = b, y >= 0, and
solves it with the exact two-phase simplex method with Bland's rule of
sy3lp.py. All arithmetic is in Fraction.
"""
from __future__ import annotations
from fractions import Fraction
from typing import List, Optional, Sequence
from sy3lp import frac, simplex_standard
class FBAResult:
"""status is 'optimal', 'infeasible' or 'unbounded'.
For 'optimal', v is one optimal flux vector and z = c v the optimum.
"""
def __init__(self, status: str, v: Optional[List[Fraction]] = None,
z: Optional[Fraction] = None):
self.status = status
self.v = v
self.z = z
def __repr__(self) -> str:
return f"FBAResult({self.status!r}, {self.v!r}, {self.z!r})"
def fba(S: Sequence[Sequence], lb: Sequence, ub: Sequence,
c: Sequence) -> FBAResult:
"""Maximize c v subject to S v = 0 and lb <= v <= ub, exactly."""
m = len(c)
# Each flux is v_j = off_j + sum of sign * y_k over its columns k, y >= 0.
off: List[Fraction] = [] # @line L1
cols: List[List[tuple]] = []
ny = 0
for j in range(m):
if lb[j] is not None and ub[j] is not None and frac(lb[j]) > frac(ub[j]):
return FBAResult("infeasible")
if lb[j] is not None:
off.append(frac(lb[j]))
cols.append([(ny, 1)])
ny += 1
elif ub[j] is not None:
off.append(frac(ub[j]))
cols.append([(ny, -1)])
ny += 1
else:
off.append(Fraction(0))
cols.append([(ny, 1), (ny + 1, -1)])
ny += 2
caps = [j for j in range(m) if lb[j] is not None and ub[j] is not None]
N = ny + len(caps)
A: List[List[Fraction]] = [] # @line L2
b: List[Fraction] = []
for row in S:
r = [Fraction(0)] * N
shift = Fraction(0)
for j in range(m):
a = frac(row[j])
if a != 0:
shift += a * off[j]
for k, s in cols[j]:
r[k] += a * s
A.append(r)
b.append(-shift)
for t, j in enumerate(caps): # @line L3
r = [Fraction(0)] * N
r[cols[j][0][0]] = Fraction(1)
r[ny + t] = Fraction(1)
A.append(r)
b.append(frac(ub[j]) - frac(lb[j]))
d = [Fraction(0)] * N # @line L4
for j in range(m):
for k, s in cols[j]:
d[k] -= frac(c[j]) * s
res = simplex_standard(A, b, d) # @line L5
if res.status != "optimal": # @line L6
return FBAResult(res.status)
v = [off[j] + sum(s * res.x[k] for k, s in cols[j]) for j in range(m)] # @line L7
z = sum(frac(cj) * vj for cj, vj in zip(c, v))
return FBAResult("optimal", v, z) # @line L8
def knockout_bounds(lb: Sequence, ub: Sequence, knocked: Sequence[int]):
"""Bounds of a mutant: each reaction in knocked gets lb = ub = 0."""
lb2, ub2 = list(lb), list(ub)
for j in knocked:
lb2[j] = 0
ub2[j] = 0
return lb2, ub2
# The toy network N of the page. Metabolites: A, E (energy), P (product).
# Reactions: EX_A (uptake of A, at most 10), RESP1 and RESP2 (A -> 2 E, two
# parallel routes), FERM (A -> E + P), EX_P (secretion of P), BIO (A + E -> ).
NAMES = ["EX_A", "RESP1", "RESP2", "FERM", "EX_P", "BIO"]
S_N = [
[1, -1, -1, -1, 0, -1], # A
[0, 2, 2, 1, 0, -1], # E
[0, 0, 0, 1, -1, 0], # P
]
LB_N = [0, 0, 0, 0, 0, 0]
UB_N = [10, None, None, None, None, None]
C_N = [0, 0, 0, 0, 0, 1]
sy3lp.py 327 lines
# SPDX-License-Identifier: MIT
# Shared module of the constraint-based metabolic pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Exact linear algebra and an exact simplex method in Fraction.
The reference copy is in biology/systems-biology/flux-balance-analysis/
impl/python/. The other constraint-based pages hold byte-identical copies.
Contents:
- rref(M), rank(M), nullspace(M, ncols), solve_linear(A, b): Gaussian
elimination over the rationals.
- simplex_standard(A, b, c): minimize c x subject to A x = b, x >= 0, by the
two-phase simplex method with Bland's rule.
- solve_lp(c, ...): a linear program with bounds, equality rows and <= rows,
reduced to the standard form and solved by simplex_standard.
- polytope_vertices(A, b, lb, ub): all vertices of {x : A x = b,
lb <= x <= ub} with finite bounds, by brute force. Tests use it as an
independent reference.
A bound of None means minus or plus infinity. Every number is converted to
Fraction, so the results are exact.
"""
from __future__ import annotations
from fractions import Fraction
from itertools import combinations, product
from typing import List, Optional, Sequence, Tuple
Matrix = List[List[Fraction]]
def frac(x) -> Fraction:
"""Convert an int, a Fraction, a float or a string to Fraction."""
return x if isinstance(x, Fraction) else Fraction(x)
def rref(M: Sequence[Sequence]) -> Tuple[Matrix, List[int]]:
"""Return the reduced row echelon form of M and its pivot columns."""
R = [[frac(x) for x in row] for row in M]
pivots: List[int] = []
if not R:
return R, pivots
rows, cols = len(R), len(R[0])
r = 0
for col in range(cols):
if r == rows:
break
p = next((i for i in range(r, rows) if R[i][col] != 0), None)
if p is None:
continue
R[r], R[p] = R[p], R[r]
inv = 1 / R[r][col]
R[r] = [x * inv for x in R[r]]
for i in range(rows):
if i != r and R[i][col] != 0:
f = R[i][col]
R[i] = [a - f * b for a, b in zip(R[i], R[r])]
pivots.append(col)
r += 1
return R, pivots
def rank(M: Sequence[Sequence]) -> int:
"""The rank of M (0 for an empty matrix)."""
if not M or not M[0]:
return 0
return len(rref(M)[1])
def nullspace(M: Sequence[Sequence], ncols: int) -> Matrix:
"""A basis of {x : M x = 0}, one vector for each free column.
The vector of free column f has x_f = 1 and x_g = 0 at the other free
columns. M may have no rows; then the basis is the unit vectors.
"""
if not M:
return [[Fraction(int(i == j)) for i in range(ncols)] for j in range(ncols)]
R, piv = rref(M)
free = [j for j in range(ncols) if j not in piv]
basis = []
for f in free:
x = [Fraction(0)] * ncols
x[f] = Fraction(1)
for i, p in enumerate(piv):
x[p] = -R[i][f]
basis.append(x)
return basis
def solve_linear(A: Sequence[Sequence], b: Sequence) -> Optional[List[Fraction]]:
"""One solution of A x = b (free variables set to 0), or None if none."""
if not A:
return None if any(frac(x) != 0 for x in b) else []
n = len(A[0])
aug = [list(row) + [bi] for row, bi in zip(A, b)]
R, piv = rref(aug)
if n in piv:
return None
x = [Fraction(0)] * n
for i, p in enumerate(piv):
x[p] = R[i][n]
return x
class LPResult:
"""status is 'optimal', 'infeasible' or 'unbounded'."""
def __init__(self, status: str, x=None, value=None):
self.status = status
self.x = x
self.value = value
def __repr__(self) -> str:
return f"LPResult({self.status!r}, {self.x!r}, {self.value!r})"
def _pivot(T: Matrix, basis: List[int], r: int, c: int) -> None:
inv = 1 / T[r][c]
T[r] = [x * inv for x in T[r]]
for i in range(len(T)):
if i != r and T[i][c] != 0:
f = T[i][c]
T[i] = [a - f * b for a, b in zip(T[i], T[r])]
basis[r] = c
def _run(T: Matrix, basis: List[int], allowed: int) -> str:
"""Simplex iterations with Bland's rule on columns 0 .. allowed - 1.
The last row of T holds the reduced costs and minus the objective value.
Enter: the smallest column with a negative reduced cost. Leave: the row
with the smallest ratio, ties broken by the smallest basic column.
"""
m = len(T) - 1
while True:
obj = T[m]
c = next((j for j in range(allowed) if obj[j] < 0), None)
if c is None:
return "optimal"
best = None
for i in range(m):
if T[i][c] > 0:
key = (T[i][-1] / T[i][c], basis[i])
if best is None or key < best[0]:
best = (key, i)
if best is None:
return "unbounded"
_pivot(T, basis, best[1], c)
def simplex_standard(A: Sequence[Sequence], b: Sequence, c: Sequence) -> LPResult:
"""Minimize c x subject to A x = b and x >= 0, exactly.
Phase 1 minimizes the sum of one artificial variable per row. Phase 2
starts from the basis that phase 1 finds. Bland's rule makes both phases
terminate.
"""
n = len(c)
cc = [frac(x) for x in c]
rows = []
for row, bi in zip(A, b):
r = [frac(x) for x in row]
bi = frac(bi)
if bi < 0:
r, bi = [-x for x in r], -bi
rows.append(r + [bi])
m = len(rows)
if m == 0:
if any(x < 0 for x in cc):
return LPResult("unbounded")
return LPResult("optimal", [Fraction(0)] * n, Fraction(0))
# Phase 1 tableau: [A | I | b], objective row = minus the sum of the rows.
T = []
for i, r in enumerate(rows):
T.append(r[:n] + [Fraction(int(k == i)) for k in range(m)] + [r[n]])
obj = [-sum(T[i][j] for i in range(m)) for j in range(n)] + [Fraction(0)] * m
obj.append(-sum(T[i][-1] for i in range(m)))
T.append(obj)
basis = [n + i for i in range(m)]
_run(T, basis, n + m)
if T[m][-1] != 0:
return LPResult("infeasible")
# Drive the artificial variables out of the basis, or drop redundant rows.
i = 0
while i < len(T) - 1:
if basis[i] >= n:
j = next((j for j in range(n) if T[i][j] != 0), None)
if j is None:
del T[i]
del basis[i]
continue
_pivot(T, basis, i, j)
i += 1
m = len(T) - 1
T = [row[:n] + [row[-1]] for row in T]
obj = list(cc) + [Fraction(0)]
for i in range(m):
cb = cc[basis[i]]
if cb != 0:
obj = [a - cb * t for a, t in zip(obj, T[i])]
T[m] = obj
status = _run(T, basis, n)
if status == "unbounded":
return LPResult("unbounded")
x = [Fraction(0)] * n
for i in range(m):
x[basis[i]] = T[i][-1]
return LPResult("optimal", x, sum(a * v for a, v in zip(cc, x)))
def solve_lp(c, A_eq=(), b_eq=(), A_le=(), b_le=(), lb=None, ub=None,
maximize=False) -> LPResult:
"""Optimize c x subject to A_eq x = b_eq, A_le x <= b_le, lb <= x <= ub.
lb defaults to 0 for every variable and ub to None (no upper bound). A
bound of None is infinite. The result holds x and the value in the
original variables.
"""
n = len(c)
lb = [0] * n if lb is None else lb
ub = [None] * n if ub is None else ub
# x_j = off_j + sum over k of coef[j][k] * y_k with y >= 0.
cols: List[List[Tuple[int, int]]] = []
off: List[Fraction] = []
ny = 0
for j in range(n):
lo = None if lb[j] is None else frac(lb[j])
hi = None if ub[j] is None else frac(ub[j])
if lo is not None and hi is not None and lo > hi:
return LPResult("infeasible")
if lo is not None:
off.append(lo)
cols.append([(ny, 1)])
ny += 1
elif hi is not None:
off.append(hi)
cols.append([(ny, -1)])
ny += 1
else:
off.append(Fraction(0))
cols.append([(ny, 1), (ny + 1, -1)])
ny += 2
caps = [(j, frac(ub[j]) - frac(lb[j])) for j in range(n)
if lb[j] is not None and ub[j] is not None]
nslack = len(A_le) + len(caps)
N = ny + nslack
A: List[List[Fraction]] = []
b: List[Fraction] = []
def expand(row) -> Tuple[List[Fraction], Fraction]:
out = [Fraction(0)] * N
shift = Fraction(0)
for j in range(n):
a = frac(row[j])
if a == 0:
continue
shift += a * off[j]
for k, s in cols[j]:
out[k] += a * s
return out, shift
for row, bi in zip(A_eq, b_eq):
r, s = expand(row)
A.append(r)
b.append(frac(bi) - s)
s_idx = ny
for row, bi in zip(A_le, b_le):
r, s = expand(row)
r[s_idx] = Fraction(1)
s_idx += 1
A.append(r)
b.append(frac(bi) - s)
for j, cap in caps:
r = [Fraction(0)] * N
r[cols[j][0][0]] = Fraction(1)
r[s_idx] = Fraction(1)
s_idx += 1
A.append(r)
b.append(cap)
sign = -1 if maximize else 1
cy, _ = expand([sign * frac(x) for x in c])
res = simplex_standard(A, b, cy)
if res.status != "optimal":
return LPResult(res.status)
x = []
for j in range(n):
x.append(off[j] + sum(s * res.x[k] for k, s in cols[j]))
return LPResult("optimal", x, sum(frac(a) * v for a, v in zip(c, x)))
def polytope_vertices(A: Sequence[Sequence], b: Sequence, lb: Sequence,
ub: Sequence) -> List[Tuple[Fraction, ...]]:
"""All vertices of {x : A x = b, lb <= x <= ub}, with finite bounds.
A point is a vertex if and only if the columns of A at the coordinates
strictly between their bounds are linearly independent. So try every set
F of such columns and every choice of a bound for the other coordinates.
The cost is exponential; use it only on small examples.
"""
n = len(lb)
lo = [frac(x) for x in lb]
hi = [frac(x) for x in ub]
r = rank(A) if A else 0
found = set()
for size in range(r + 1):
for F in combinations(range(n), size):
AF = [[row[j] for j in F] for row in A]
if size and rank(AF) < size:
continue
rest = [j for j in range(n) if j not in F]
for choice in product((0, 1), repeat=len(rest)):
x = [Fraction(0)] * n
for j, ch in zip(rest, choice):
x[j] = hi[j] if ch else lo[j]
rhs = [frac(bi) - sum(frac(row[j]) * x[j] for j in rest)
for row, bi in zip(A, b)]
if size:
sol = solve_linear(AF, rhs)
if sol is None:
continue
for j, v in zip(F, sol):
x[j] = v
elif any(v != 0 for v in rhs):
continue
if all(lo[j] <= x[j] <= hi[j] for j in range(n)):
found.add(tuple(x))
return sorted(found)
test_flux_balance_analysis.py 196 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/flux-balance-analysis/. The authors are listed in prov/TC2TH5.jsonl.
"""Tests of the shared module sy3lp.py and of fba().
The reference for fba() is the maximum of c v over all vertices of the flux
polytope, found by brute force, and the value of the dual LP.
"""
import random
from fractions import Fraction as F
from flux_balance_analysis import (C_N, LB_N, S_N, UB_N, fba,
knockout_bounds)
from sy3lp import (nullspace, polytope_vertices, rank, rref, simplex_standard,
solve_linear, solve_lp)
def matvec(M, x):
return [sum(F(a) * b for a, b in zip(row, x)) for row in M]
def random_matrix(rng, rows, cols, lo=-2, hi=2):
return [[rng.randint(lo, hi) for _ in range(cols)] for _ in range(rows)]
# Tests of sy3lp.py.
def test_rref_and_rank():
R, piv = rref([[1, 2, 3], [2, 4, 6], [1, 0, 1]])
assert piv == [0, 1]
assert R == [[1, 0, 1], [0, 1, 1], [0, 0, 0]]
assert rank([[1, 2], [2, 4]]) == 1
assert rank([]) == 0
def test_nullspace_random():
rng = random.Random(1)
for _ in range(60):
rows, cols = rng.randint(1, 4), rng.randint(1, 6)
M = random_matrix(rng, rows, cols)
B = nullspace(M, cols)
assert len(B) == cols - rank(M)
for x in B:
assert all(v == 0 for v in matvec(M, x))
if B:
assert rank(B) == len(B)
def test_solve_linear():
rng = random.Random(2)
for _ in range(60):
rows, cols = rng.randint(1, 4), rng.randint(1, 5)
A = random_matrix(rng, rows, cols)
x0 = [rng.randint(-3, 3) for _ in range(cols)]
b = matvec(A, x0)
x = solve_linear(A, b)
assert x is not None and matvec(A, x) == b
assert solve_linear([[1, 1], [1, 1]], [1, 2]) is None
def test_beale_cycling_example():
# Beale (1955): Dantzig's rule with the lowest-index tie break cycles here.
A = [[1, 0, 0, F(1, 4), -8, -1, 9],
[0, 1, 0, F(1, 2), -12, F(-1, 2), 3],
[0, 0, 1, 0, 0, 1, 0]]
c = [0, 0, 0, F(-3, 4), 20, F(-1, 2), 6]
res = simplex_standard(A, [0, 0, 1], c)
assert res.status == "optimal"
assert res.value == F(-5, 4)
def test_simplex_status():
assert simplex_standard([[1, 1]], [-1], [1, 1]).status == "infeasible"
assert simplex_standard([[1, -1]], [0], [-1, 0]).status == "unbounded"
# A redundant row is dropped after phase 1.
res = simplex_standard([[1, 1], [2, 2]], [1, 2], [1, 2])
assert res.status == "optimal" and res.x == [1, 0]
def test_solve_lp_against_vertices():
rng = random.Random(3)
for _ in range(40):
n = rng.randint(2, 5)
rows = rng.randint(1, 2)
A = random_matrix(rng, rows, n)
lb = [rng.randint(-3, 0) for _ in range(n)]
ub = [lo + rng.randint(0, 4) for lo in lb]
x0 = [rng.randint(lo, hi) for lo, hi in zip(lb, ub)]
b = matvec(A, x0)
c = [rng.randint(-3, 3) for _ in range(n)]
verts = polytope_vertices(A, b, lb, ub)
assert verts
best = min(sum(F(ci) * vi for ci, vi in zip(c, v)) for v in verts)
res = solve_lp(c, A_eq=A, b_eq=b, lb=lb, ub=ub)
assert res.status == "optimal" and res.value == best
res = solve_lp(c, A_le=A, b_le=b, lb=lb, ub=ub, maximize=True)
assert res.status == "optimal"
assert all(a <= bi for a, bi in zip(matvec(A, res.x), b))
def test_solve_lp_free_and_upper_only():
# minimize x0 - x1 with x0 free, x1 <= 2, x0 + x1 = 1: x1 = 2, x0 = -1.
res = solve_lp([1, -1], A_eq=[[1, 1]], b_eq=[1], lb=[None, None],
ub=[None, 2])
assert res.status == "optimal" and res.x == [-1, 2] and res.value == -3
# Tests of fba().
def test_network_n():
res = fba(S_N, LB_N, UB_N, C_N)
assert res.status == "optimal"
assert res.z == F(20, 3)
v = res.v
assert v[0] == 10 and v[1] + v[2] == F(10, 3) and v[3] == 0 and v[4] == 0
assert all(x == 0 for x in matvec(S_N, v))
def test_network_n_knockouts():
lb, ub = knockout_bounds(LB_N, UB_N, [1, 2])
res = fba(S_N, lb, ub, C_N)
assert res.z == 5 and res.v == [10, 0, 0, 5, 5, 5]
lb, ub = knockout_bounds(LB_N, UB_N, [1])
assert fba(S_N, lb, ub, C_N).z == F(20, 3)
lb, ub = knockout_bounds(LB_N, UB_N, [0])
res = fba(S_N, lb, ub, C_N)
assert res.z == 0 and res.v == [0] * 6
def test_infeasible_and_unbounded():
# A forced secretion of P with no source of P.
lb = list(LB_N)
lb[4] = 1
lb2, ub2 = knockout_bounds(lb, UB_N, [3])
assert fba(S_N, lb2, ub2, C_N).status == "infeasible"
# Without the uptake bound the growth is unbounded.
ub = list(UB_N)
ub[0] = None
assert fba(S_N, LB_N, ub, C_N).status == "unbounded"
assert fba([[1]], [2], [1], [1]).status == "infeasible"
def dual_value(S, lb, ub, c):
"""min ub alpha - lb beta s.t. S^T lam + alpha - beta = c, alpha, beta >= 0.
All bounds are finite here. Variables: lam (free, one per metabolite),
then alpha, then beta (one per reaction each).
"""
n, m = len(S), len(c)
cost = [0] * n + list(ub) + [-x for x in lb]
A = []
for j in range(m):
row = [S[i][j] for i in range(n)]
row += [int(k == j) for k in range(m)] + [-int(k == j) for k in range(m)]
A.append(row)
lo = [None] * n + [0] * (2 * m)
return solve_lp(cost, A_eq=A, b_eq=c, lb=lo)
def random_network(rng):
n, m = rng.randint(1, 3), rng.randint(3, 6)
S = random_matrix(rng, n, m)
lb = [rng.choice([0, 0, -1, -2]) for _ in range(m)]
ub = [rng.randint(0, 3) for _ in range(m)]
c = [rng.randint(-1, 2) for _ in range(m)]
return S, lb, ub, c
def test_random_networks_against_vertices_and_dual():
rng = random.Random(4)
for _ in range(50):
S, lb, ub, c = random_network(rng)
res = fba(S, lb, ub, c)
verts = polytope_vertices(S, [0] * len(S), lb, ub)
# v = 0 lies in the box and satisfies S v = 0, so the LP is feasible.
assert verts and res.status == "optimal"
best = max(sum(F(ci) * vi for ci, vi in zip(c, v)) for v in verts)
assert res.z == best
assert all(x == 0 for x in matvec(S, res.v))
assert all(lo <= x <= hi for lo, x, hi in zip(lb, res.v, ub))
dual = dual_value(S, lb, ub, c)
assert dual.status == "optimal" and dual.value == res.z
def test_fba_matches_solve_lp_with_infinite_bounds():
rng = random.Random(5)
for _ in range(40):
S, lb, ub, c = random_network(rng)
lb = [None if rng.random() < 0.3 else x for x in lb]
ub = [None if rng.random() < 0.3 else x for x in ub]
res = fba(S, lb, ub, c)
ref = solve_lp(c, A_eq=S, b_eq=[0] * len(S), lb=lb, ub=ub,
maximize=True)
assert res.status == ref.status
if res.status == "optimal":
assert res.z == ref.value
History
Linear programming over reaction stoichiometry appeared in biochemical engineering in the 1980s, for example in the work of Papoutsakis on fermentations of butyric acid bacteria (1984) and of Fell and Small on fat synthesis in adipose tissue (1986). Varma and Palsson built stoichiometric models of E. coli in the early 1990s and showed in 1994 that the LP with an uptake bound and a growth objective predicts the growth rate and the secretion of acetate in aerobic and anaerobic cultures. Genome-scale reconstructions since 2000 made FBA a standard tool, and the COBRA Toolbox and COBRApy are common implementations. Orth, Thiele and Palsson (2010) wrote a short primer on the method.
References
- Jeffrey D. Orth, Ines Thiele and Bernhard O. Palsson, What is flux balance analysis?, Nature Biotechnology 28(3), 2010, 245-248, the whole primer (the constraints, the objective and the LP)
- Amit Varma and Bernhard O. Palsson, Stoichiometric flux balance models quantitatively predict growth and metabolic by-product secretion in wild-type Escherichia coli W3110, Applied and Environmental Microbiology 60(10), 1994, 3724-3731, the LP model and the comparison with measured growth and secretion
- Bernhard O. Palsson, Systems Biology, Constraint-based Reconstruction and Analysis, Cambridge University Press, 2015, the chapters on constraints and on optimization
- Robert G. Bland, New finite pivoting rules for the simplex method, Mathematics of Operations Research 2(2), 1977, 103-107, the smallest index rule and its proof of termination
- Rafael U. Ibarra, Jeremy S. Edwards and Bernhard O. Palsson, Escherichia coli K-12 undergoes adaptive evolution to achieve in silico predicted optimal growth, Nature 420(6912), 2002, 186-189, the measured growth of evolved strains against the FBA prediction
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag TC2TH5 Edit this page History Report an error Markdown