Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
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 z∗z^*. Then, for each of the mm 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 z∗z^*. The result is one interval per reaction. A reaction with the interval [0,0][0, 0] 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 n×mn \times m stoichiometric matrix SS, flux bounds lb≤v≤ublb \le v \le ub (some may be infinite), an objective cc, and a fraction f∈[0,1]f \in [0, 1].

Output. The FBA optimum z∗=max⁡{cTv:Sv=0,  lb≤v≤ub}z^* = \max \{c^{\mathsf T} v : S v = 0, \; lb \le v \le ub\} and, for each reaction jj,

vjmin⁡=min⁡v∈Pfvj,vjmax⁡=max⁡v∈Pfvj,Pf={v:Sv=0,  lb≤v≤ub,  cTv≥t},v_j^{\min} = \min_{v \in P_f} v_j, \qquad v_j^{\max} = \max_{v \in P_f} v_j, \qquad P_f = \{v : S v = 0, \; lb \le v \le ub, \; c^{\mathsf T} v \ge t\},

with the threshold t=z∗−(1−f)∣z∗∣t = z^* - (1 - f) |z^*|. For f=1f = 1, P1P_1 is the set of FBA optima. For z∗≥0z^* \ge 0 the threshold is t=fz∗t = f z^*. A minimum or maximum can be −∞-\infty or +∞+\infty when the bounds do not close the polyhedron.

The algorithm

  1. FVA(S, lb, ub, c, f)
  2. 1z* ← FBA(S, lb, ub, c); stop if it is infeasible or unbounded
  3. 2t ← z* - (1 - f) |z*|
  4. 3for j ← 1 to m:
  5. 4lo_j ← min v_j subject to S v = 0, lb ≤ v ≤ ub, c v ≥ t (or -∞ if unbounded)
  6. 5hi_j ← max v_j subject to the same constraints (or +∞ if unbounded)
  7. 6append [lo_j, hi_j] to the result
  8. 7return (z*, the list of intervals)

The 2m2m 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 AA (at most 10), two parallel respiration reactions RESP1 and RESP2 (A→2EA \to 2E), fermentation FERM (A→E+PA \to E + P), secretion EX_P of PP, and growth BIO (A+E→A + E \to). The FBA optimum is z∗=203z^* = \frac{20}{3}. The intervals for three fractions are:

reaction f=1f = 1 f=0.9f = 0.9 f=0f = 0
EX_A [10,10][10, 10] [9,10][9, 10] [0,10][0, 10]
RESP1 [0,103][0, \frac{10}{3}] [0,103][0, \frac{10}{3}] [0,103][0, \frac{10}{3}]
RESP2 [0,103][0, \frac{10}{3}] [0,103][0, \frac{10}{3}] [0,103][0, \frac{10}{3}]
FERM [0,0][0, 0] [0,2][0, 2] [0,5][0, 5]
EX_P [0,0][0, 0] [0,2][0, 2] [0,5][0, 5]
BIO [203,203][\frac{20}{3}, \frac{20}{3}] [6,203][6, \frac{20}{3}] [0,203][0, \frac{20}{3}]

At f=1f = 1 the uptake and the growth are fixed, and fermentation is off. But each respiration reaction can carry anything from 0 to 103\frac{10}{3}, because the other one takes the rest: the optimum that FBA returns, with RESP1 at 103\frac{10}{3} 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 103\frac{10}{3}. At f=0.9f = 0.9 the growth may drop to 6. Growth is g=23a−13vFERMg = \frac{2}{3}a - \frac{1}{3}v_{\text{FERM}}, so g≥6g \ge 6 with a≤10a \le 10 allows up to 2 units of fermentation, and the uptake may drop to 9. At f=0f = 0 the threshold is 0, and the ranges are those of all steady states: the fermentation alone can carry at most 5, with a=10a = 10 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 PfP_f, found by brute force, and check that the FBA optimum lies in every interval.

Correctness

The minimization and the maximization of vjv_j over the polyhedron PfP_f are linear programs, and the exact simplex method solves them, with the status "unbounded" for an infinite end. None of them is infeasible, since t≤z∗t \le z^* and the FBA optimum is in PfP_f. PfP_f is convex, so the set of values of vjv_j on it is an interval, and every value between vjmin⁡v_j^{\min} and vjmax⁡v_j^{\max} is the flux of some vector in PfP_f. For f=1f = 1, cTv≥z∗c^{\mathsf T} v \ge z^* on the feasible set means cTv=z∗c^{\mathsf T} v = z^*, so P1P_1 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 n×mn \times m matrix SS, bounds lb≤ublb \le ub (entries may be infinite), an objective c∈Qmc \in \mathbb{Q}^m and a fraction f∈[0,1]∩Qf \in [0, 1] \cap \mathbb{Q}. Write P={v:Sv=0,  lb≤v≤ub}P = \{v : S v = 0, \; lb \le v \le ub\}. Assume that the FBA problem max⁡PcTv\max_P c^{\mathsf T} v has a finite optimum zz; otherwise the code raises an error at line L1 and returns nothing. Let t=z−(1−f)∣z∣t = z - (1 - f) |z| and

Pf={v∈P:cTv≥t}.P_f = \{v \in P : c^{\mathsf T} v \ge t\} .

For each reaction jj, the claim is that the code returns (loj,hij)(lo_j, hi_j) with loj=min⁡Pfvjlo_j = \min_{P_f} v_j and hij=max⁡Pfvjhi_j = \max_{P_f} v_j, where None stands for −∞-\infty or +∞+\infty when the minimum or the maximum does not exist, and that every value strictly between lojlo_j and hijhi_j (and each finite end) is the flux vjv_j of some v∈Pfv \in P_f.

Lemma 1 (the LP solver). For a rational LP min⁡\min or max⁡\max of cTxc^{\mathsf T} x subject to Aeqx=beqA_{eq} x = b_{eq}, Alex≤bleA_{le} x \le b_{le} and lb≤x≤ublb \le x \le ub, 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 xx 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 si≥0s_i \ge 0 for each row of AleA_{le}, which turns aiTx≤bia_i^{\mathsf T} x \le b_i into aiTx+si=bia_i^{\mathsf T} x + s_i = b_i. A maximization is the minimization of −cTx-c^{\mathsf T} x. 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. □\square

Lemma 2 (the set is not empty). t≤zt \le z, and the FBA optimum v∗v^* of line L1 is in PfP_f. So no LP of lines L4 and L5 is infeasible.

Proof. 1−f≥01 - f \ge 0 and ∣z∣≥0|z| \ge 0, so t=z−(1−f)∣z∣≤z=cTv∗t = z - (1 - f)|z| \le z = c^{\mathsf T} v^*, and v∗∈Pv^* \in P. □\square

Lemma 3 (the ranges). For each jj, line L4 returns min⁡Pfvj\min_{P_f} v_j if it exists, and None otherwise. Line L5 returns max⁡Pfvj\max_{P_f} v_j if it exists, and None otherwise.

Proof. Line L4 calls solve_lp with the objective eje_j, the rows Sv=0S v = 0, the single row −cTv≤−t-c^{\mathsf T} v \le -t (that is, cTv≥tc^{\mathsf T} v \ge t) and the bounds lb,ublb, ub. Its feasible set is exactly PfP_f. By Lemma 2 it is not empty, so by Lemma 1 the status is "optimal" with the value min⁡Pfvj\min_{P_f} v_j, or "unbounded" when vjv_j has no lower bound on PfP_f. 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. □\square

Lemma 4 (every value in the range is attained). If loj≤x≤hijlo_j \le x \le hi_j, with finite xx, then some v∈Pfv \in P_f has vj=xv_j = x.

Proof. PfP_f is an intersection of half spaces and hyperplanes, so it is convex. If both ends are finite, take vlo,vhi∈Pfv^{lo}, v^{hi} \in P_f with vjlo=lojv^{lo}_j = lo_j and vjhi=hijv^{hi}_j = hi_j (they exist by Lemma 3), and a point λvlo+(1−λ)vhi\lambda v^{lo} + (1 - \lambda) v^{hi} on the segment between them with the flux xx. If an end is infinite, take a point of PfP_f with vjv_j beyond xx on that side, which exists because vjv_j is unbounded there, and the same segment argument applies. □\square

Theorem. For 0≤f≤10 \le f \le 1, fva returns the optimum zz and, for each reaction jj in the list, the exact interval {vj:v∈Pf}\{v_j : v \in P_f\}, with None for an infinite end. For f=1f = 1, t=zt = z, and P1P_1 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 f=1f = 1, t=zt = z, and v∈Pv \in P with cTv≥zc^{\mathsf T} v \ge z means cTv=zc^{\mathsf T} v = z, since zz is the maximum. □\square

Remark (the threshold for a negative optimum). The code uses ∣z∣|z| in tt. If z≥0z \ge 0, then t=fzt = f z, the usual "at least the fraction ff of the optimum". If z<0z < 0, then t=z−(1−f)(−z)=(2−f)z≤zt = z - (1 - f)(-z) = (2 - f) z \le z, which still loosens the constraint as ff decreases. The form t=fzt = f z would instead make the constraint stricter than the optimum when z<0z < 0 and f<1f < 1, and then PfP_f would be empty. Lemma 2 needs only t≤zt \le z, which holds for both signs of zz.

Remark (blocked reactions). blocked_reactions calls fva with c=0c = 0. Then z=0z = 0 whenever PP is not empty, t=0t = 0, and Pf=PP_f = P. A reaction is reported as blocked exactly when its range over PP is [0,0][0, 0], that is, when vj=0v_j = 0 for every steady state that obeys the bounds.

Complexity

  • Number of LPs. One FBA problem and 2m2m range problems, so 2m+12m + 1 LPs. Each has mm variables and n+1n + 1 rows, plus the bound rows. With an LP time TT, the total time is O(mT)O(m T), 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 vjmax⁡v_j^{\max} and an upper bound for every vjmin⁡v_j^{\min}. Reactions whose bound already meets the bound in lblb or ubub need no LP. This is a heuristic: it saves LPs in practice but not in the worst case.
  • Space. One LP at a time, O(nm)O(n m) 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 PfP_f onto each axis. They lose the coupling between fluxes: the box of all intervals is larger than PfP_f, as the example shows for RESP1 and RESP2.
  • Monotone in the fraction. If f′≤ff' \le f, then t′≤tt' \le t, so Pf⊆Pf′P_f \subseteq P_{f'} and every interval for f′f' contains the interval for ff.
  • Blocked reactions. With c=0c = 0, PfP_f is the set of all steady states that obey the bounds, and a reaction with interval [0,0][0, 0] 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 PfP_f 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 fz∗f z^* is stricter than the optimum when z∗<0z^* < 0. The form z∗−(1−f)∣z∗∣z^* - (1 - f)|z^*| of this page avoids that.
  • Tolerances. With a floating point solver, the constraint cTv≥z∗c^{\mathsf T} v \ge z^* can be infeasible by rounding. Solvers relax it by a small tolerance, which can widen the intervals a little.
  • Counting LPs. 2m2m 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.

flux_variability_analysis.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.linear_programs
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example