Algorithmcore
Flux variability analysis
Also called FVA.
For each reaction, minimize and maximize its flux by linear programming over all solutions within a fraction of the optimal objective.
- Time
- O(m T) worst2m + 1 linear_programs
- Space
- O(n m) extra
- Where
- T = the time of one FBA linear program; m = the number of reactions; n = the number of metabolites
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Radhakrishnan Mahadevan, Christophe H. Schilling, 2003
Flux variability analysis (FVA) answers the question that one flux balance analysis solution leaves open: how much can each flux change while the network still reaches the optimal objective, or a given fraction of it? FBA returns one optimal flux vector, but the set of optimal vectors is often a whole face of the flux polyhedron. FVA first solves the FBA problem for its optimum . Then, for each of the reactions, it solves two more linear programs: the minimum and the maximum of that flux over all steady states with objective at least a threshold near . The result is one interval per reaction. A reaction with the interval is blocked, a reaction whose interval does not contain 0 is required, and a wide interval shows a choice of routes.
In plain words
FBA tells you how fast the cell can grow and gives one way to get there. Often there are many ways. FVA takes each reaction in turn and asks two questions: what is the least flux this reaction can carry while the cell still grows at the best rate, and what is the most? Each question is a small optimization problem of the same kind as FBA.
The answer is a range for each reaction. If the range is only zero, the reaction is never used. If the range does not include zero, the cell must use it. If the range is wide, other reactions can take its place. You can also allow a little less than the best growth, which usually makes the ranges wider.
The problem
Input. An stoichiometric matrix , flux bounds (some may be infinite), an objective , and a fraction .
Output. The FBA optimum and, for each reaction ,
with the threshold . For , is the set of FBA optima. For the threshold is . A minimum or maximum can be or when the bounds do not close the polyhedron.
The algorithm
FVA(S, lb, ub, c, f)- 1
z* ← FBA(S, lb, ub, c); stop if it is infeasible or unbounded - 2
t ← z* - (1 - f) |z*| - 3
for j ← 1 to m: - 4
lo_j ← min v_j subject to S v = 0, lb ≤ v ≤ ub, c v ≥ t (or -∞ if unbounded) - 5
hi_j ← max v_j subject to the same constraints (or +∞ if unbounded) - 6
append [lo_j, hi_j] to the result - 7
return (z*, the list of intervals)
The LPs of lines L4 and L5 have the same constraints and differ only in the objective. They are never infeasible, because the FBA optimum of line L1 satisfies all of them. The code solves every LP from scratch with the exact simplex method of the FBA page.
Example
Take network N of the FBA page: uptake EX_A of a substrate (at most 10), two parallel respiration reactions RESP1 and RESP2 (), fermentation FERM (), secretion EX_P of , and growth BIO (). The FBA optimum is . The intervals for three fractions are:
| reaction | |||
|---|---|---|---|
| EX_A | |||
| RESP1 | |||
| RESP2 | |||
| FERM | |||
| EX_P | |||
| BIO |
At the uptake and the growth are fixed, and fermentation is off. But each respiration reaction can carry anything from 0 to , because the other one takes the rest: the optimum that FBA returns, with RESP1 at and RESP2 at 0, is one end of a segment. The intervals do not say that every combination is possible: RESP1 and RESP2 together must carry exactly . At the growth may drop to 6. Growth is , so with allows up to 2 units of fermentation, and the uptake may drop to 9. At the threshold is 0, and the ranges are those of all steady states: the fermentation alone can carry at most 5, with split as 5 for FERM and 5 for growth.
The tests check these ranges against the minimum and maximum of each flux over the vertices of the polyhedron , found by brute force, and check that the FBA optimum lies in every interval.
Correctness
The minimization and the maximization of over the polyhedron are linear programs, and the exact simplex method solves them, with the status "unbounded" for an infinite end. None of them is infeasible, since and the FBA optimum is in . is convex, so the set of values of on it is an interval, and every value between and is the flux of some vector in . For , on the feasible set means , so is the optimal face. The full proof is below.
Proof: FVA returns the exact range of each flux over the near-optimal flux setfull
Fix an matrix , bounds (entries may be infinite), an objective and a fraction . Write . Assume that the FBA problem has a finite optimum ; otherwise the code raises an error at line L1 and returns nothing. Let and
For each reaction , the claim is that the code returns with and , where None stands for or when the minimum or the maximum does not exist, and that every value strictly between and (and each finite end) is the flux of some .
Lemma 1 (the LP solver). For a rational LP or of subject to , and , solve_lp returns "infeasible" if the feasible set is empty, "unbounded" if the objective has no finite optimum on a non-empty feasible set, and otherwise an optimal and its value.
Proof. solve_lp makes the same change of variables as lines L1 to L4 of FBA (lower bound offset, reflection for an upper bound only, a split for a free variable, a slack row for each pair of finite bounds), and adds one slack for each row of , which turns into . A maximization is the minimization of . By Lemma 1 of the correctness proof of flux balance analysis, extended by the slack rows in the same way as the bound rows, the feasible set of the new standard form LP maps onto the feasible set of the original LP, and the objectives differ by a constant and a sign. Lemmas 2 to 4 of that proof show that simplex_standard returns the right status and an optimum of the standard form. The status and the optimum carry over as in the theorem there.
Lemma 2 (the set is not empty). , and the FBA optimum of line L1 is in . So no LP of lines L4 and L5 is infeasible.
Proof. and , so , and .
Lemma 3 (the ranges). For each , line L4 returns if it exists, and None otherwise. Line L5 returns if it exists, and None otherwise.
Proof. Line L4 calls solve_lp with the objective , the rows , the single row (that is, ) and the bounds . Its feasible set is exactly . By Lemma 2 it is not empty, so by Lemma 1 the status is "optimal" with the value , or "unbounded" when has no lower bound on . Line L6 stores the value or None. A linear function bounded below on a non-empty polyhedron attains its minimum there (a standard fact of linear programming, which also follows from the simplex method of Lemma 1, which stops at an optimal basis whenever the LP is bounded). So "the minimum does not exist" and "unbounded" are the same case. Line L5 is the same with maximize.
Lemma 4 (every value in the range is attained). If , with finite , then some has .
Proof. is an intersection of half spaces and hyperplanes, so it is convex. If both ends are finite, take with and (they exist by Lemma 3), and a point on the segment between them with the flux . If an end is infinite, take a point of with beyond on that side, which exists because is unbounded there, and the same segment argument applies.
Theorem. For , fva returns the optimum and, for each reaction in the list, the exact interval , with None for an infinite end. For , , and is the set of optimal flux vectors of the FBA problem, so the ranges are the ranges of the fluxes over all FBA optima.
Proof. Lemmas 2 to 4. For , , and with means , since is the maximum.
Remark (the threshold for a negative optimum). The code uses in . If , then , the usual "at least the fraction of the optimum". If , then , which still loosens the constraint as decreases. The form would instead make the constraint stricter than the optimum when and , and then would be empty. Lemma 2 needs only , which holds for both signs of .
Remark (blocked reactions). blocked_reactions calls fva with . Then whenever is not empty, , and . A reaction is reported as blocked exactly when its range over is , that is, when for every steady state that obeys the bounds.
Complexity
- Number of LPs. One FBA problem and range problems, so LPs. Each has variables and rows, plus the bound rows. With an LP time , the total time is , and the LPs are polynomial (LP in P). This is a theorem.
- Warm starts. The range LPs share their constraints with each other and with the FBA problem, so a solver can start each one from the optimal basis of the last. Gudmundsson and Thiele (2010) do this and solve the LPs in parallel; on genome-scale models they report large speed-ups over a plain loop. This is a measurement on their test models.
- Fewer LPs. Each optimal vertex found on the way gives a lower bound for every and an upper bound for every . Reactions whose bound already meets the bound in or need no LP. This is a heuristic: it saves LPs in practice but not in the worst case.
- Space. One LP at a time, for the dense tableau.
Properties
- Exact. With exact arithmetic the intervals are exact. With a floating point solver they are exact up to the solver tolerance.
- Projection, not shape. The intervals are the projections of onto each axis. They lose the coupling between fluxes: the box of all intervals is larger than , as the example shows for RESP1 and RESP2.
- Monotone in the fraction. If , then , so and every interval for contains the interval for .
- Blocked reactions. With , is the set of all steady states that obey the bounds, and a reaction with interval is blocked. The code gives this as blocked_reactions. Blocked reactions are the starting point of gap filling.
- Deterministic. The intervals do not depend on the order of the reactions or the solver, unlike the single vector that FBA returns.
Variants and improvements
- Fast FVA. Warm starts from the last basis and parallel LPs (Gudmundsson and Thiele 2010).
- Loopless FVA. With internal cycles, a flux can grow without bound around the cycle, which gives infinite or very wide intervals. Adding the loopless constraints removes these and gives the ranges over thermodynamically feasible states, at the cost of a mixed-integer program per bound.
- Flux coupling. The ratio of two fluxes can be minimized and maximized over the flux cone with LPs of the same kind. This finds pairs of reactions that always carry flux together.
- Sampling. Random sampling of points in estimates the distribution of each flux inside its interval. FVA gives only the ends.
- Range of the objective under a constraint. A production envelope, the maximum product flux as a function of the growth rate, is a sequence of LPs of the same form. It shows whether a product is coupled to growth, which OptKnock tries to achieve.
When to use it
Use FVA after every FBA study that draws conclusions about single fluxes, because one optimal vector is not unique. It is the standard way to find blocked reactions, reactions required for growth on a medium, and reactions whose flux is fixed by the optimum. Use a fraction below 1 when the cell may not grow at the exact optimum, as is usual in experiments. If you need the joint distribution of fluxes or the coupling between them, use sampling or flux coupling analysis instead.
Pitfalls
- Reading the box as the feasible set. Each interval is attained, but the ends of different intervals are not attained together.
- Infinite intervals. A reversible cycle with no net effect can carry any flux. FVA shows this as an infinite or a very large interval, set only by the default bound of the model (often 1000).
- The fraction for a negative optimum. The threshold is stricter than the optimum when . The form of this page avoids that.
- Tolerances. With a floating point solver, the constraint can be infeasible by rounding. Solvers relax it by a small tolerance, which can widen the intervals a little.
- Counting LPs. LPs on a model with ten thousand reactions take long without warm starts or parallel runs.
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-variability-analysis/. The authors are listed in prov/3ZQX3G.jsonl.
"""Flux variability analysis with exact linear programs.
A network has n metabolites and m reactions, with the n x m stoichiometric
matrix S, the flux bounds lb and ub (None is infinite) and the objective c.
FVA first solves the FBA problem max c v, S v = 0, lb <= v <= ub, for the
optimum z. Then for each reaction j it solves two LPs, the minimum and the
maximum of v_j over the set
S v = 0, lb <= v <= ub, c v >= t, with t = z - (1 - f) |z|.
f = 1 gives the optimal face of the FBA problem. f < 1 keeps every flux
vector whose objective is within the fraction 1 - f of the optimum. Each LP
is solved exactly by the simplex method of sy3lp.py.
"""
from __future__ import annotations
from fractions import Fraction
from typing import List, Optional, Sequence, Tuple
from sy3lp import frac, solve_lp
Range = Tuple[Optional[Fraction], Optional[Fraction]]
def fva(S: Sequence[Sequence], lb: Sequence, ub: Sequence, c: Sequence,
fraction=1, reactions: Optional[Sequence[int]] = None):
"""Return (z, ranges): the FBA optimum and the range of each flux.
ranges[k] = (lo, hi) for reaction reactions[k] (all reactions by
default). lo is None if v_j is unbounded below over the set, and hi is
None if it is unbounded above. Raises ValueError if the FBA problem is
infeasible or unbounded.
"""
m = len(c)
zeros = [0] * len(S)
base = solve_lp(c, A_eq=S, b_eq=zeros, lb=lb, ub=ub, maximize=True) # @line L1
if base.status != "optimal":
raise ValueError("the FBA problem is " + base.status)
z = base.value
f = frac(fraction)
t = z - (1 - f) * abs(z) # @line L2
A_le = [[-frac(x) for x in c]]
b_le = [-t]
out: List[Range] = []
for j in (range(m) if reactions is None else reactions): # @line L3
e = [0] * m
e[j] = 1
lo = solve_lp(e, A_eq=S, b_eq=zeros, A_le=A_le, b_le=b_le, # @line L4
lb=lb, ub=ub)
hi = solve_lp(e, A_eq=S, b_eq=zeros, A_le=A_le, b_le=b_le, # @line L5
lb=lb, ub=ub, maximize=True)
out.append((lo.value if lo.status == "optimal" else None, # @line L6
hi.value if hi.status == "optimal" else None))
return z, out # @line L7
def blocked_reactions(S, lb, ub):
"""Reactions with v_j = 0 in every steady state: FVA with c = 0."""
_, ranges = fva(S, lb, ub, [0] * len(lb))
return [j for j, (lo, hi) in enumerate(ranges) if lo == 0 and hi == 0]
# The toy network N of the flux-balance-analysis page.
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_variability_analysis.py 98 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/flux-variability-analysis/. The authors are listed in prov/3ZQX3G.jsonl.
"""Tests of fva() against enumeration of the vertices of the polytope.
The set {S v = 0, lb <= v <= ub, c v >= t} is a polytope when the bounds are
finite. A linear function takes its minimum and its maximum over a polytope
at vertices, so the range of v_j is the range of v_j over the vertices.
The constraint c v >= t is written with a slack s = c v - t in [0, U].
"""
import random
from fractions import Fraction as F
from flux_variability_analysis import (C_N, LB_N, S_N, UB_N,
blocked_reactions, fva)
from sy3lp import polytope_vertices, solve_lp
def brute_ranges(S, lb, ub, c, t, big):
"""Ranges of each v_j over the vertices, with a slack in [0, big]."""
m = len(c)
A = [list(row) + [0] for row in S] + [list(c) + [-1]]
b = [0] * len(S) + [t]
verts = polytope_vertices(A, b, list(lb) + [0], list(ub) + [big])
return [(min(v[j] for v in verts), max(v[j] for v in verts))
for j in range(m)]
def test_network_n_fraction_one():
z, ranges = fva(S_N, LB_N, UB_N, C_N)
assert z == F(20, 3)
assert ranges == [(10, 10), (0, F(10, 3)), (0, F(10, 3)), (0, 0),
(0, 0), (F(20, 3), F(20, 3))]
def test_network_n_fraction_09():
z, ranges = fva(S_N, LB_N, UB_N, C_N, fraction=F(9, 10))
assert z == F(20, 3)
# c v >= 6. With uptake a, respiration r and fermentation f:
# growth = 2r + f, a = 3r + 2f <= 10.
assert ranges[5] == (6, F(20, 3))
assert ranges[3] == (0, 2)
assert ranges[0] == (9, 10)
big = 100
ub = [x if x is not None else big for x in UB_N]
assert ranges == brute_ranges(S_N, LB_N, ub, C_N, 6, big)
def test_unbounded_range():
# A free internal cycle A -> B -> A with no bound gives an infinite range.
S = [[1, -1, 1, -1], [0, 1, -1, 0]]
lb = [0, 0, 0, 0]
ub = [5, None, None, None]
c = [0, 0, 0, 1]
z, ranges = fva(S, lb, ub, c)
assert z == 5
assert ranges[1] == (0, None) and ranges[2] == (0, None)
assert ranges[3] == (5, 5)
def test_blocked():
# The third reaction makes D, which nothing uses.
S = [[1, -1, -1], [0, 0, 1]]
assert blocked_reactions(S, [0, 0, 0], [4, 4, 4]) == [2]
def random_case(rng):
n, m = rng.randint(1, 3), rng.randint(3, 6)
S = [[rng.randint(-2, 2) for _ in range(m)] for _ in range(n)]
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_against_vertices():
rng = random.Random(7)
for _ in range(25):
S, lb, ub, c = random_case(rng)
f = rng.choice([F(1), F(1), F(9, 10), F(1, 2)])
z, ranges = fva(S, lb, ub, c, fraction=f)
t = z - (1 - f) * abs(z)
big = sum(abs(ci) * max(abs(lo), abs(hi))
for ci, lo, hi in zip(c, lb, ub)) + abs(t) + 1
assert ranges == brute_ranges(S, lb, ub, c, t, big)
def test_optimal_vertex_inside_ranges():
rng = random.Random(8)
for _ in range(25):
S, lb, ub, c = random_case(rng)
z, ranges = fva(S, lb, ub, c)
v = solve_lp(c, A_eq=S, b_eq=[0] * len(S), lb=lb, ub=ub,
maximize=True).x
assert all(lo <= x <= hi for x, (lo, hi) in zip(v, ranges))
# The objective is fixed on the optimal face.
if c == [0] * (len(c) - 1) + [1]:
assert ranges[-1] == (z, z)
History
Mahadevan and Schilling (2003) showed that FBA problems on genome-scale models have many alternate optima, and they defined the two LPs per reaction to measure the range of each flux over the optimal set. They applied it to a genome-scale model of Escherichia coli and studied how far the fluxes can vary at maximal growth. Gudmundsson and Thiele (2010) made it fast with warm starts and parallel LPs. FVA is now a standard function of the COBRA Toolbox and COBRApy.
References
- Radhakrishnan Mahadevan and Christophe H. Schilling, The effects of alternate optimal solutions in constraint-based genome-scale metabolic models, Metabolic Engineering 5(4), 2003, 264-276, the definition of the two LPs per reaction over the optimal set, and their use on the E. coli model
- Steinn Gudmundsson and Ines Thiele, Computationally efficient flux variability analysis, BMC Bioinformatics 11, 2010, 489, the fast implementation that reuses the optimal basis between the LPs
- Jeffrey D. Orth, Ines Thiele and Bernhard O. Palsson, What is flux balance analysis?, Nature Biotechnology 28(3), 2010, 245-248, the section on the types of analysis built on FBA, including flux variability
- Bernhard O. Palsson, Systems Biology, Constraint-based Reconstruction and Analysis, Cambridge University Press, 2015, the chapter on the capabilities of reconstructed networks (alternate optima and flux ranges)
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 3ZQX3G Edit this page History Report an error Markdown