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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 , flux bounds and the biomass reaction , as for FBA.
- Medium species with initial concentrations (mmol/L), and the initial biomass (gDW/L).
- A matrix that maps the fluxes to the medium: is the rate of change of per gram of biomass.
- For each uptake reaction of species , a rate law for its upper bound, here the Michaelis-Menten form .
- A step and a number of steps .
Output. The time course of and , and the flux vector at each step, approximating the solution of
where is an FBA optimum for the bounds set by , and is its growth rate.
The algorithm
DFBA-SOA(S, lb, ub, b, E, uptakes, X0, z0, Δt, N)- 1
t ← 0; X ← X0; z ← z0 - 2
for i ← 1 to N: - 3
for each uptake j of species k: ub_j ← min(vmax_j z_k / (K_j + z_k), z_k / (X Δt)) - 4
v ← FBA(S, lb, ub, b) - 5
if the LP is infeasible then record the state and stop - 6
z ← z + Δt (E v) X; X ← X + Δt v_b X - 7
t ← t + Δt - 8
return 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 fixed over the step and integrates exactly: is multiplied by , and changes by .
Example
The overflow network has four internal metabolites, a substrate , oxygen , an energy carrier and a by-product , and six reactions:
| reaction | equation | bound |
|---|---|---|
| EX_A | Monod uptake, , | |
| EX_O | at most 1 | |
| RESP | ||
| FERM | ||
| EX_P | secreted into the medium | |
| BIO | growth rate |
For an uptake , respiration gives units of growth per unit of and fermentation gives , but respiration is limited by oxygen. So the FBA optimum has a closed form. If , all substrate is respired and . If , oxygen is at its bound, the rest is fermented, and with the secretion of . This is overflow metabolism: at high uptake the cell secretes a by-product even with oxygen present.
Start with , a substrate and no , and take h:
| mode | ||||
|---|---|---|---|---|
| 0 | 0.05 | 10 | 0 | overflow, |
| 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 is high, the uptake is above 3 and the cells secrete . When falls below , the uptake drops below 3 and the cells switch to respiration only, so stops rising. A reference solution of the same ODE by RK4 with step gives and at . The Euler errors for 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 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 ; 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 , bounds , a biomass index , and a medium with species . The matrix gives the change of species per unit flux of reaction and per unit biomass. Each uptake reaction of species has the parameters and . The state at step is with biomass and concentrations .
The code does the following at step (lines L3 to L7). For each uptake reaction of species , with , it sets the upper bound
(the second term only when , and when ). It solves the FBA problem , where is with these entries replaced. If the LP is not optimal, it stops. Otherwise, with the optimal and , the Euler update is
The exponential update replaces the factor by (or if ) in the update, multiplies by , and cuts each 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 is infeasible or unbounded, and otherwise is an optimal solution and is the optimal growth rate.
Proof. The bound 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 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.
Lemma 2 (the update is the Euler step of the ODE). Let be the flux vector that the method uses on . The Euler update is one explicit Euler step of
with step from . The exponential update is the exact solution of this ODE on when is held at 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 constant, solves the first equation, and then for , and for . At these are the formulas of the code.
Lemma 3 (the medium does not become negative). Assume that species is used only by its uptake reaction , that is, and for every and every feasible (as in the overflow network of the page). If and , then the Euler update gives . If , then and .
Proof. With , . So , since the other terms of are not negative. With both updates add 0.
Lemma 4 (biomass stays non-negative). If , then for all for the exponential update. For the Euler update, holds whenever at every step, in particular whenever every (for example when ).
Proof. in the first case, and in the second.
Lemma 5 (a constant yield conserves mass). Let the substrate be species with uptake reaction , and assume that every LP of the run has and for a constant . Then the Euler update keeps constant, exactly in real arithmetic.
Proof. .
In the overflow network of the page, a large oxygen bound gives for every uptake , so Lemma 5 holds with . The test checks it to , which is the effect of float rounding only.
Theorem. Run dfba for steps. Every record with not None holds an exact FBA optimum for the bounds of step (rounded to float), and is the Euler step (or the exponential step) of the ODE of Lemma 2 with on . 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.
Remark (convergence). If the map 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 ; 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 is Lipschitz whenever the uptake bounds are Lipschitz in (the Monod term is, for ). 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 , so the theorem applies away from depletion, where the cap is not active. The test measures the error ratio for halved steps, which is close to 2.
Complexity
- Per step. One LP in time and an update in for . The total time is for 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 , 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. 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 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 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 is in grams per liter, so 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.
# 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
- 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)
- 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
- 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.
| 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 4C9MZV Edit this page History Report an error Markdown