Algorithm Search⌘K

Algorithmadvanced

Dynamic flux balance analysis

Also called dFBA.

Couple FBA at each time step with ODEs for biomass and external metabolites, so that uptake bounds change as the medium is used up.

Time
O(N (T + K m)) worst
Space
O(N K + T) extra
Where
K = the number of medium species; N = the number of time steps; T = the time of one FBA linear program; m = the number of reactions
Properties
deterministicnot exactofflineiterative
Origin
Radhakrishnan Mahadevan, Jeremy S. Edwards, Francis J. Doyle III, 2002

Dynamic flux balance analysis (dFBA) extends flux balance analysis from one steady state to a time course in a batch or fed-batch culture. Inside the cell, fluxes are assumed to be at a quasi steady state and optimal for growth. Outside the cell, the biomass and the concentrations of the medium species change slowly, by ordinary differential equations whose rates are the exchange fluxes times the biomass. In the static optimization approach of Mahadevan, Edwards and Doyle (2002), each time step solves one FBA problem with uptake bounds set by the current medium, for example by Michaelis-Menten kinetics, and then moves the biomass and the medium forward by one step of an ODE method. The method predicts growth curves, substrate depletion and by-product secretion, including switches between metabolic modes.

In plain words

FBA describes a cell at one moment. In a flask, the food runs out and waste piles up, so the best way to grow changes over time. dFBA cuts time into short steps.

At the start of each step, look at how much food is left. Less food means the cell can take it in more slowly, so the speed limit on the food door goes down. Solve FBA with that limit to get the growth rate and the rates of food use and waste output. Then move the clock forward: the cells grow a little, the food goes down a little, and the waste goes up a little. Repeat until the food is gone. The result is a curve over time for the cells, the food and the waste.

The problem

Input.

  • A network with matrix SS, flux bounds lb,ublb, ub and the biomass reaction bb, as for FBA.
  • Medium species k=1,…,Kk = 1, \ldots, K with initial concentrations zk(0)z_k(0) (mmol/L), and the initial biomass X(0)X(0) (gDW/L).
  • A matrix EE that maps the fluxes to the medium: (Ev)k(E v)_k is the rate of change of zkz_k per gram of biomass.
  • For each uptake reaction jj of species kk, a rate law for its upper bound, here the Michaelis-Menten form vjmax⁡zk/(Kj+zk)v^{\max}_j z_k / (K_j + z_k).
  • A step Δt\Delta t and a number of steps NN.

Output. The time course of XX and zz, and the flux vector at each step, approximating the solution of

dXdt=μ(z)X,dzdt=(Ev(z))X,\frac{dX}{dt} = \mu(z) X, \qquad \frac{dz}{dt} = (E v(z)) X,

where v(z)v(z) is an FBA optimum for the bounds set by zz, and μ(z)=vb(z)\mu(z) = v_b(z) is its growth rate.

The algorithm

  1. DFBA-SOA(S, lb, ub, b, E, uptakes, X0, z0, Δt, N)
  2. 1t ← 0; X ← X0; z ← z0
  3. 2for i ← 1 to N:
  4. 3for each uptake j of species k: ub_j ← min(vmax_j z_k / (K_j + z_k), z_k / (X Δt))
  5. 4v ← FBA(S, lb, ub, b)
  6. 5if the LP is infeasible then record the state and stop
  7. 6z ← z + Δt (E v) X; X ← X + Δt v_b X
  8. 7t ← t + Δt
  9. 8return the recorded time course

Line L3 sets the uptake bounds from the current medium. The second term in the minimum keeps the step from using more substrate than is left, so the concentration cannot become negative. Line L4 is one exact LP. Line L6 is one explicit Euler step. The code also has the variant of Varma and Palsson, which holds vv fixed over the step and integrates exactly: XX is multiplied by eμΔte^{\mu \Delta t}, and zkz_k changes by (Ev)kX(eμΔt−1)/μ(E v)_k X (e^{\mu \Delta t} - 1)/\mu.

Example

The overflow network has four internal metabolites, a substrate AA, oxygen OO, an energy carrier EE and a by-product PP, and six reactions:

reaction equation bound
EX_A ∅→A\emptyset \to A Monod uptake, vmax⁡=10v^{\max} = 10, K=1K = 1
EX_O ∅→O\emptyset \to O at most 1
RESP A+O→2EA + O \to 2E
FERM A→E+PA \to E + P
EX_P P→∅P \to \emptyset secreted into the medium
BIO 5A+5E→∅5A + 5E \to \emptyset growth rate

For an uptake uu, respiration gives 215\frac{2}{15} units of growth per unit of AA and fermentation gives 110\frac{1}{10}, but respiration is limited by oxygen. So the FBA optimum has a closed form. If u≤3u \le 3, all substrate is respired and μ=2u15\mu = \frac{2u}{15}. If u>3u > 3, oxygen is at its bound, the rest is fermented, and μ=u+110\mu = \frac{u + 1}{10} with the secretion u−32\frac{u - 3}{2} of PP. This is overflow metabolism: at high uptake the cell secretes a by-product even with oxygen present.

Start with X=0.05X = 0.05, a substrate s=10s = 10 and no PP, and take Δt=0.01\Delta t = 0.01 h:

tt XX ss pp mode
0 0.05 10 0 overflow, μ≈1.009\mu \approx 1.009
1 0.1361 9.2247 0.2593 overflow
2 0.3655 7.1623 0.9432 overflow
3 0.9160 2.2617 2.4868 overflow
3.34 1.1359 0.4131 2.8856 respiration only from here
4 1.1909 0.0002 2.8856 substrate used up

While ss is high, the uptake is above 3 and the cells secrete PP. When ss falls below 37\frac{3}{7}, the uptake drops below 3 and the cells switch to respiration only, so pp stops rising. A reference solution of the same ODE by RK4 with step 10−310^{-3} gives X=1.1915X = 1.1915 and p=2.8775p = 2.8775 at t=4t = 4. The Euler errors for Δt=0.04,0.02,0.01\Delta t = 0.04, 0.02, 0.01 are about 0.035, 0.017 and 0.0087, so the error halves when the step halves, as expected for a first-order method.

The tests check the code against a hand Euler run of the closed-form ODE, the switch from overflow to respiration, this first-order convergence, the conservation of X+215sX + \frac{2}{15} s when oxygen is not limiting, the exact exponential solution when the uptake is constant, and that the medium never becomes negative with a large step.

Correctness

Each step solves the FBA problem for the current bounds exactly, so the growth rate and the fluxes are an exact FBA optimum for those bounds. The update is the explicit Euler step of the ODE with the flux vector of the step, or, in the variant, the exact solution of the ODE with the flux vector held constant over the step. With the cap in line L3, the uptake in one step is at most what is in the medium, so the substrate concentration stays non-negative when the uptake reaction is its only consumer. When the growth yield is constant, the Euler update keeps the biomass plus the yield times the substrate exactly constant. If the map from the medium to the FBA optimum is Lipschitz, the Euler method converges with error of order Δt\Delta t; this is the standard theorem for the Euler method, and it holds for the overflow network away from depletion. The full proof is below.

Proof: Each step of static optimization dFBA is an exact FBA solve followed by an Euler stepfull

Fix a network with matrix SS, bounds lb,ublb, ub, a biomass index bb, and a medium with species k=1,…,Kk = 1, \ldots, K. The matrix EE gives the change of species kk per unit flux of reaction jj and per unit biomass. Each uptake reaction jj of species kk has the parameters vjmax⁡>0v^{\max}_j > 0 and Kj≥0K_j \ge 0. The state at step ii is (ti,Xi,zi)(t_i, X_i, z_i) with biomass Xi≥0X_i \ge 0 and concentrations zi∈RKz_i \in \mathbb{R}^K.

The code does the following at step ii (lines L3 to L7). For each uptake reaction jj of species kk, with s=max⁡(zi,k,0)s = \max(z_{i,k}, 0), it sets the upper bound

uˉj=min⁡(vjmax⁡sKj+s,  sXiΔt)\bar u_j = \min\left( \frac{v^{\max}_j s}{K_j + s}, \; \frac{s}{X_i \Delta t} \right)

(the second term only when Xi>0X_i > 0, and uˉj=0\bar u_j = 0 when Kj+s=0K_j + s = 0). It solves the FBA problem max⁡{vb:Sv=0,  lb≤v≤ubˉ}\max \{v_b : S v = 0, \; lb \le v \le \bar{ub}\}, where ubˉ\bar{ub} is ubub with these entries replaced. If the LP is not optimal, it stops. Otherwise, with the optimal v(i)v^{(i)} and μi=vb(i)\mu_i = v^{(i)}_b, the Euler update is

Xi+1=Xi+Δt μiXi,zi+1=zi+Δt (Ev(i))Xi.X_{i+1} = X_i + \Delta t \, \mu_i X_i, \qquad z_{i+1} = z_i + \Delta t \, (E v^{(i)}) X_i .

The exponential update replaces the factor Δt\Delta t by (eμiΔt−1)/μi(e^{\mu_i \Delta t} - 1)/\mu_i (or Δt\Delta t if μi=0\mu_i = 0) in the zz update, multiplies XX by eμiΔte^{\mu_i \Delta t}, and cuts each zi+1,kz_{i+1,k} at 0.

Lemma 1 (each LP is solved exactly). At each step the code stops if and only if the FBA problem with the bounds lb,ubˉlb, \bar{ub} is infeasible or unbounded, and otherwise v(i)v^{(i)} is an optimal solution and μi\mu_i is the optimal growth rate.

Proof. The bound uˉj\bar u_j is a float, and Fraction(float) is the exact rational value of that float, so the LP has rational data. solve_lp then returns the exact status and an exact optimum (Lemma 1 of the proof on the flux variability analysis page). The conversion of v(i)v^{(i)} to float for the update rounds each flux once, which is the only rounding in the step apart from the float arithmetic of the update itself. □\square

Lemma 2 (the update is the Euler step of the ODE). Let v(t)v(t) be the flux vector that the method uses on [ti,ti+1)[t_i, t_{i+1}). The Euler update is one explicit Euler step of

dXdt=vbX,dzdt=(Ev)X\frac{dX}{dt} = v_b X, \qquad \frac{dz}{dt} = (E v) X

with step Δt\Delta t from (Xi,zi)(X_i, z_i). The exponential update is the exact solution of this ODE on [ti,ti+1][t_i, t_{i+1}] when vv is held at v(i)v^{(i)} over the step, up to the cut at 0.

Proof. The first part is the definition of the explicit Euler method: the right side is evaluated at the start of the step. For the second, with v=v(i)v = v^{(i)} constant, X(t)=Xieμi(t−ti)X(t) = X_i e^{\mu_i (t - t_i)} solves the first equation, and then zk(t)=zi,k+(Ev(i))kXi∫0t−tieμiτ dτ=zi,k+(Ev(i))kXi(eμi(t−ti)−1)/μiz_k(t) = z_{i,k} + (E v^{(i)})_k X_i \int_0^{t - t_i} e^{\mu_i \tau} \, d\tau = z_{i,k} + (E v^{(i)})_k X_i (e^{\mu_i (t - t_i)} - 1)/\mu_i for μi≠0\mu_i \ne 0, and zi,k+(Ev(i))kXi(t−ti)z_{i,k} + (E v^{(i)})_k X_i (t - t_i) for μi=0\mu_i = 0. At t=ti+1t = t_{i+1} these are the formulas of the code. □\square

Lemma 3 (the medium does not become negative). Assume that species kk is used only by its uptake reaction jj, that is, Ekj=−1E_{k j} = -1 and Ekj′vj′≥0E_{k j'} v_{j'} \ge 0 for every j′≠jj' \ne j and every feasible vv (as in the overflow network of the page). If zi,k≥0z_{i,k} \ge 0 and Xi>0X_i > 0, then the Euler update gives zi+1,k≥0z_{i+1,k} \ge 0. If Xi=0X_i = 0, then Xi+1=0X_{i+1} = 0 and zi+1=ziz_{i+1} = z_i.

Proof. With Xi>0X_i > 0, vj(i)≤uˉj≤zi,k/(XiΔt)v^{(i)}_j \le \bar u_j \le z_{i,k} / (X_i \Delta t). So zi+1,k≥zi,k−Δt vj(i)Xi≥zi,k−zi,k=0z_{i+1,k} \ge z_{i,k} - \Delta t \, v^{(i)}_j X_i \ge z_{i,k} - z_{i,k} = 0, since the other terms of (Ev(i))k(E v^{(i)})_k are not negative. With Xi=0X_i = 0 both updates add 0. □\square

Lemma 4 (biomass stays non-negative). If X0≥0X_0 \ge 0, then Xi≥0X_i \ge 0 for all ii for the exponential update. For the Euler update, Xi≥0X_i \ge 0 holds whenever 1+Δt μi≥01 + \Delta t \, \mu_i \ge 0 at every step, in particular whenever every μi≥0\mu_i \ge 0 (for example when lbb≥0lb_b \ge 0).

Proof. Xi+1=XieμiΔtX_{i+1} = X_i e^{\mu_i \Delta t} in the first case, and Xi+1=Xi(1+Δt μi)X_{i+1} = X_i (1 + \Delta t \, \mu_i) in the second. □\square

Lemma 5 (a constant yield conserves mass). Let the substrate be species kk with uptake reaction jj, and assume that every LP of the run has μi=Yvj(i)\mu_i = Y v^{(i)}_j and (Ev(i))k=−vj(i)(E v^{(i)})_k = -v^{(i)}_j for a constant Y>0Y > 0. Then the Euler update keeps Xi+Yzi,kX_i + Y z_{i,k} constant, exactly in real arithmetic.

Proof. Xi+1+Yzi+1,k=Xi+Δt Yvj(i)Xi+Yzi,k−YΔt vj(i)Xi=Xi+Yzi,kX_{i+1} + Y z_{i+1,k} = X_i + \Delta t \, Y v^{(i)}_j X_i + Y z_{i,k} - Y \Delta t \, v^{(i)}_j X_i = X_i + Y z_{i,k}. □\square

In the overflow network of the page, a large oxygen bound gives μ=215u\mu = \frac{2}{15} u for every uptake uu, so Lemma 5 holds with Y=215Y = \frac{2}{15}. The test checks it to 10−910^{-9}, which is the effect of float rounding only.

Theorem. Run dfba for NN steps. Every record (ti,Xi,zi,v(i))(t_i, X_i, z_i, v^{(i)}) with v(i)v^{(i)} not None holds an exact FBA optimum v(i)v^{(i)} for the bounds of step ii (rounded to float), and (Xi+1,zi+1)(X_{i+1}, z_{i+1}) is the Euler step (or the exponential step) of the ODE of Lemma 2 with v=v(i)v = v^{(i)} on [ti,ti+1)[t_i, t_{i+1}). The run stops early exactly when some LP is infeasible or unbounded. Under the hypotheses of Lemmas 3 and 4, the biomass and the substrate concentrations stay non-negative.

Proof. Induction over the steps with Lemmas 1 to 4. □\square

Remark (convergence). If the map z↦v(z)z \mapsto v(z) from the medium to the chosen FBA optimum is Lipschitz near the solution, the ODE of Lemma 2 has a unique solution, and the explicit Euler method converges to it with a global error of order Δt\Delta t; this is the standard convergence theorem of the Euler method. The optimal value of an LP is a continuous, piecewise linear function of the bounds, so μ\mu is Lipschitz whenever the uptake bounds are Lipschitz in zz (the Monod term is, for Kj>0K_j > 0). The other fluxes need not be: when the LP optimum is not unique, the solver may jump between optimal vertices. In the overflow network the optimum is unique and piecewise linear in uu, so the theorem applies away from depletion, where the cap s/(XΔt)s/(X \Delta t) is not active. The test measures the error ratio for halved steps, which is close to 2.

Complexity

  • Per step. One LP in time TT and an update in O(Km)O(K m) for EvE v. The total time is O(N(T+Km))O(N (T + K m)) for NN steps. This is a count of operations.
  • Warm starts. The bounds change a little from step to step, so the optimal basis often stays the same. A solver that starts from the last basis needs few or no pivots per step. Höffner, Harwood and Barton (2013) go further and integrate the ODE with a fixed basis until an event shows that the basis is no longer optimal; this gives an exact piecewise solution with adaptive steps.
  • Step size. The Euler error is of order Δt\Delta t, so halving the error doubles the number of LPs. An adaptive ODE method with the LP inside the right side is usual for large models.
  • Space. O(NK)O(N K) for the time course, plus the space of one LP.

Properties

  • Not exact. The time course is an approximation of the ODE with error of order Δt\Delta t for the Euler update. Each LP inside it is exact.
  • Quasi steady state. The method assumes that intracellular metabolism is much faster than the change of the medium, the same assumption as in the quasi-steady-state approximation.
  • Non-unique fluxes. When the FBA optimum is not unique, the solver picks one optimal vertex, and the secretion fluxes (not the growth rate) can jump between steps. The ODE is then not well defined by FBA alone. Höffner and co-authors fix this with a lexicographic order of secondary objectives.
  • Mode switches. Changes of the optimal basis show up as switches of metabolic mode, such as the switch from overflow to respiration in the example, or from glucose to acetate in diauxic growth.
  • Infeasible steps. If a lower bound, such as a maintenance flux, cannot be met with the medium left, the LP is infeasible and the static approach stops. Models usually relax such bounds or let the biomass decay.

Variants and improvements

  • Static optimization approach (SOA). The method of this page: one LP per time step (Mahadevan, Edwards and Doyle 2002, following Varma and Palsson 1994).
  • Dynamic optimization approach (DOA). Optimize over the whole time course at once, for example the final biomass, as one nonlinear program after a discretization in time. It allows rate limits on how fast fluxes change, at a much higher cost.
  • Direct approach with an ODE solver. Put the LP inside the right side of an adaptive ODE solver, with event detection when the optimal basis changes (Höffner, Harwood and Barton 2013).
  • Community dFBA. Several species share one medium, each with its own FBA problem per step. This models cross-feeding and competition.
  • Spatial dFBA. One dFBA model per grid cell, coupled by diffusion of the medium species, models colonies and biofilms.

When to use it

Use dFBA when the medium changes during the experiment, as in batch and fed-batch cultures, and you want growth curves, substrate use and by-product profiles from a genome-scale model without a full kinetic model. It needs uptake kinetics for the limiting substrates and a growth objective. For one steady condition, plain FBA is enough. For fast transients inside the cell, such as the response to a pulse of substrate in seconds, a kinetic model is needed, since dFBA assumes that the cell is always at its optimum.

Pitfalls

  • Negative concentrations. Without the cap zk/(XΔt)z_k / (X \Delta t) on the uptake, a large step can use more substrate than is left.
  • Jumps from alternate optima. Secretion fluxes can change at random between steps if the FBA optimum is not unique. Fix them with a secondary objective, or report the growth rate only.
  • Stiffness. Near depletion, the uptake changes fast compared with the step. A fixed step that is too large gives oscillations; an adaptive step or event detection avoids them.
  • Units. Fluxes are per gram of biomass per hour, and XX is in grams per liter, so (Ev)X(E v) X is in mmol per liter per hour. Mixing time units between the uptake law and the step is a common error.
  • Infeasibility at the end. A maintenance requirement that the medium can no longer support makes the LP infeasible. Decide in advance what the model does then.

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.

dynamic_flux_balance_analysis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dynamic-flux-balance-analysis/. The authors are listed in prov/4C9MZV.jsonl.
"""Dynamic flux balance analysis by the static optimization approach.

The state is the biomass X (g/L) and the concentrations z of extracellular
species (mmol/L). At each time step of length dt:
1. each uptake reaction j of species k gets the upper bound
   min(vmax_j z_k / (Km_j + z_k), z_k / (X dt)), so that the step cannot use
   more than what is in the medium;
2. one FBA problem (max v_bio subject to S v = 0, lb <= v <= ub) gives the
   fluxes v in mmol/gDW/h and the growth rate mu = v_bio in 1/h;
3. the state moves by one explicit Euler step: X += dt mu X and
   z_k += dt (E v)_k X, where E maps the exchange fluxes to the medium.

update="exponential" is the variant of Varma and Palsson: X is multiplied by
exp(mu dt) and z_k changes by (E v)_k X (exp(mu dt) - 1) / mu. It is exact
when v stays constant over the step. With it, z_k is cut at 0.

The LP of each step is solved exactly by sy3lp.py on the exact rational
value of the float bounds; the state itself is in float.
"""

from __future__ import annotations

import math
from fractions import Fraction
from typing import List, Sequence, Tuple

from sy3lp import solve_lp


def dfba(S: Sequence[Sequence], lb: Sequence, ub: Sequence, bio: int,
         E: Sequence[Sequence], uptakes: Sequence[Tuple[int, int, float, float]],
         X0: float, z0: Sequence[float], dt: float, steps: int,
         update: str = "euler"):
    """Run the static optimization approach for steps steps of length dt.

    E[k][j] is the change of medium species k per unit flux of reaction j
    and per unit biomass. uptakes holds (j, k, vmax, Km) for each uptake
    reaction j of species k. Returns a list of (t, X, z, v); v is the flux
    vector used for the step that starts at t (None in the last record or
    when the LP is infeasible, which ends the run).
    """
    c = [0] * len(lb)
    c[bio] = 1
    zeros = [0] * len(S)
    t, X, z = 0.0, float(X0), [float(x) for x in z0]  # @line L1
    out: List[tuple] = []
    for _ in range(steps):  # @line L2
        hi = list(ub)
        for j, k, vmax, km in uptakes:  # @line L3
            s = max(z[k], 0.0)
            bound = vmax * s / (km + s) if km + s > 0 else 0.0
            if X > 0:
                bound = min(bound, s / (X * dt))
            hi[j] = Fraction(bound)
        res = solve_lp(c, A_eq=S, b_eq=zeros, lb=lb, ub=hi, maximize=True)  # @line L4
        if res.status != "optimal":  # @line L5
            out.append((t, X, list(z), None))
            return out
        v = [float(x) for x in res.x]
        mu = v[bio]
        out.append((t, X, list(z), v))
        rates = [sum(E[k][j] * v[j] for j in range(len(v))) for k in range(len(z))]
        if update == "euler":  # @line L6
            z = [zk + dt * rk * X for zk, rk in zip(z, rates)]
            X = X + dt * mu * X
        else:
            g = math.expm1(mu * dt) / mu if mu != 0 else dt
            z = [max(zk + rk * X * g, 0.0) for zk, rk in zip(z, rates)]
            X = X * math.exp(mu * dt)
        t += dt  # @line L7
    out.append((t, X, list(z), None))
    return out  # @line L8


# The overflow network of the page. Internal metabolites: A (substrate),
# O (oxygen), E (energy), P (by-product). Reactions:
# 0 EX_A: -> A (uptake of the medium substrate s, Monod bound)
# 1 EX_O: -> O, at most O_MAX
# 2 RESP: A + O -> 2 E
# 3 FERM: A -> E + P
# 4 EX_P: P -> (secretion into the medium)
# 5 BIO: 5 A + 5 E -> biomass (flux = growth rate in 1/h)
O_MAX = 1
VMAX, KM = 10.0, 1.0
S_OV = [
    [1, 0, -1, -1, 0, -5],  # A
    [0, 1, -1, 0, 0, 0],    # O
    [0, 0, 2, 1, 0, -5],    # E
    [0, 0, 0, 1, -1, 0],    # P
]
LB_OV = [0, 0, 0, 0, 0, 0]
UB_OV = [None, O_MAX, None, None, None, None]
BIO_OV = 5
# Medium species: 0 = substrate s, 1 = by-product p.
E_OV = [
    [-1, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 1, 0],
]
UPTAKES_OV = [(0, 0, VMAX, KM)]


def overflow_rates(u: float, o_max: float = O_MAX):
    """Closed form of the FBA optimum of the overflow network at uptake u.

    Returns (mu, secretion of P). Respiration only if u <= 3 o_max.
    """
    if u <= 3 * o_max:
        return 2 * u / 15, 0.0
    return (u + o_max) / 10, (u - 3 * o_max) / 2
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_dynamic_flux_balance_analysis.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dynamic-flux-balance-analysis/. The authors are listed in prov/4C9MZV.jsonl.
"""Tests of dfba() on the overflow network.

For this network the FBA optimum has a closed form (overflow_rates), so the
dynamic model reduces to an ODE in (X, s, p). References:
- the explicit Euler steps of that ODE, done by hand (same steps, so the
  results agree to rounding, tolerance 1e-9);
- an RK4 solution of the ODE with step 1e-3 (error far below the Euler
  error), to check that the Euler error halves when dt halves;
- conserved X + Y s when the yield Y is constant;
- the exact exponential solution when the uptake is constant (Km = 0).
"""

import math

from dynamic_flux_balance_analysis import (BIO_OV, E_OV, KM, LB_OV, S_OV,
                                           UB_OV, UPTAKES_OV, VMAX, dfba,
                                           overflow_rates)

X0, S0 = 0.05, 10.0


def rhs(y, o_max=1.0, vmax=VMAX, km=KM):
    X, s, p = y
    s = max(s, 0.0)
    u = vmax * s / (km + s)
    mu, sec = overflow_rates(u, o_max)
    return [mu * X, -u * X, sec * X]


def rk4(y, h, n):
    for _ in range(n):
        k1 = rhs(y)
        k2 = rhs([a + h / 2 * b for a, b in zip(y, k1)])
        k3 = rhs([a + h / 2 * b for a, b in zip(y, k2)])
        k4 = rhs([a + h * b for a, b in zip(y, k3)])
        y = [a + h / 6 * (b + 2 * c + 2 * d + e)
             for a, b, c, d, e in zip(y, k1, k2, k3, k4)]
    return y


def run(dt, steps, ub=UB_OV, uptakes=UPTAKES_OV, update="euler", s0=S0):
    return dfba(S_OV, LB_OV, ub, BIO_OV, E_OV, uptakes, X0, [s0, 0.0], dt,
                steps, update)


def test_matches_hand_euler():
    dt, steps = 0.01, 400
    tr = run(dt, steps)
    y = [X0, S0, 0.0]
    for t, X, z, v in tr:
        assert abs(X - y[0]) <= 1e-9 and abs(z[0] - y[1]) <= 1e-9
        assert abs(z[1] - y[2]) <= 1e-9
        d = rhs(y)
        y = [a + dt * b for a, b in zip(y, d)]


def test_overflow_then_respiration():
    tr = run(0.01, 400)
    first, late = tr[0][3], tr[350][3]
    assert first[3] > 0 and first[1] == 1.0  # overflow: oxygen at its bound
    assert late[3] == 0.0                    # respiration only at low s
    assert tr[-1][2][0] < 1e-3 and abs(tr[-1][2][1] - 2.8856) < 1e-3


def test_first_order_convergence():
    T = 4.0
    ref = rk4([X0, S0, 0.0], 1e-3, 4000)
    errs = []
    for dt in (0.04, 0.02, 0.01):
        tr = run(dt, int(round(T / dt)))
        _, X, z, _ = tr[-1]
        errs.append(abs(X - ref[0]) + abs(z[0] - ref[1]) + abs(z[1] - ref[2]))
    for a, b in zip(errs, errs[1:]):
        assert 1.6 <= a / b <= 2.4


def test_constant_yield_conserves_mass():
    # With a large oxygen bound there is no overflow: mu = (2/15) u.
    ub = list(UB_OV)
    ub[1] = 100
    Y = 2 / 15
    tr = run(0.05, 120, ub=ub)
    total = X0 + Y * S0
    for t, X, z, v in tr:
        assert abs(X + Y * z[0] - total) <= 1e-9
        assert z[0] >= -1e-12
    assert abs(tr[-1][1] - total) <= 1e-6


def test_exponential_update_is_exact_for_constant_uptake():
    uptakes = [(0, 0, VMAX, 0.0)]  # Km = 0: the uptake is VMAX while s > 0
    mu = (VMAX + 1) / 10
    tr = run(0.1, 20, uptakes=uptakes, update="exponential")
    for t, X, z, v in tr:
        assert abs(X - X0 * math.exp(mu * t)) <= 1e-12 * X
        s = S0 - VMAX / mu * X0 * math.expm1(mu * t)
        assert abs(z[0] - s) <= 1e-9
    # Euler underestimates the exponential growth.
    eu = run(0.1, 20, uptakes=uptakes)
    assert eu[-1][1] < tr[-1][1]


def test_empty_medium_and_large_step():
    tr = run(0.01, 10, s0=0.0)
    assert all(rec[1] == X0 for rec in tr)
    tr = run(0.5, 40)
    assert all(rec[2][0] >= -1e-12 for rec in tr)

History

Varma and Palsson (1994) predicted the time profiles of E. coli batch cultures, including by-product secretion, from an FBA model solved at successive time intervals with the medium updated between them. Mahadevan, Edwards and Doyle (2002) named this the static optimization approach, contrasted it with a dynamic optimization over the whole time course, and applied both to diauxic growth of E. coli on glucose and acetate. Höffner, Harwood and Barton (2013) gave a simulator that treats dFBA as an ODE with an embedded LP and handles changes of the optimal basis and alternate optima with events and lexicographic optimization.

References

  1. Radhakrishnan Mahadevan, Jeremy S. Edwards and Francis J. Doyle III, Dynamic flux balance analysis of diauxic growth in Escherichia coli, Biophysical Journal 83(3), 2002, 1331-1340, the static optimization approach (one LP per time step) and the dynamic optimization approach (one NLP over the whole time course)
  2. 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 time profiles of batch cultures computed from one LP per time interval
  3. Kai Höffner, Stuart M. Harwood and Paul I. Barton, A reliable simulator for dynamic flux balance analysis, Biotechnology and Bioengineering 110(3), 2013, 792-802, dFBA as an ODE with an embedded LP, solved with lexicographic optimization and event detection when the optimal basis changes

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.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