Algorithmadvanced
Minimization of metabolic adjustment
Also called MOMA.
Predict the fluxes of a knockout mutant as the feasible flux vector closest in Euclidean distance to the wild type, by a quadratic program.
- Time
- O(3^m (m + n)^3) worst
- Space
- O((m + n)^2) extra
- Where
- m = the number of reactions; n = the number of metabolites
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Daniel Segrè, Dennis Vitkup, George M. Church, 2002
Minimization of metabolic adjustment (MOMA) predicts the flux state of a mutant right after a gene knockout. Flux balance analysis predicts the mutant by maximizing growth again under the new bounds, which assumes that the mutant is already optimal. Segrè, Vitkup and Church (2002) proposed a different hypothesis: a fresh mutant has not evolved to its new optimum, and its fluxes stay as close as they can to the wild type. MOMA computes the steady-state flux vector of the mutant network that is nearest to the wild-type flux vector in the Euclidean norm. This is a quadratic program with a strictly convex objective, so its solution is unique, unlike the FBA optimum.
In plain words
When you remove one machine from a factory, the factory does not redesign itself at once. It keeps running in nearly the old way, with the smallest change that still works without that machine. MOMA uses this idea for a cell.
First, find a normal way to run the healthy cell. Then remove the reactions of the deleted gene. Among all ways to run the changed cell that keep every inside chemical in balance, choose the one that is closest to the old way, where "closest" means the smallest sum of squared changes over all reactions. The growth rate of that state is the prediction for the mutant. It is usually lower than the best growth that the mutant could reach.
The problem
Input. The stoichiometric matrix ; a wild-type flux vector , usually an FBA optimum of the wild type with ; and the bounds of the mutant, where each knocked-out reaction has .
Output. The flux vector
or a report that the mutant has no steady state within the bounds. The predicted growth rate is the biomass flux of .
is the orthogonal projection of onto the mutant flux polyhedron . Expanding the square gives the standard QP form over .
The algorithm
Practical MOMA codes call a convex QP solver. The implementation here solves the QP exactly for small networks by trying every active set: each reaction is at its lower bound, at its upper bound, or free. For each set, the free fluxes are the projection of onto an affine subspace, given by one linear system, and the KKT conditions decide whether the candidate is the minimizer.
MOMA(S, lb, ub, w)- 1
for each state σ in {LOW, UP, FREE}^m, with the most FREE entries first: - 2
set v_j ← lb_j if σ_j = LOW and v_j ← ub_j if σ_j = UP; let F be the free set - 3
r ← - Σ over j not in F of S_j v_j - 4
solve x - w_F + S_F^T μ = 0, S_F x = r; skip σ if there is no solution; v_F ← x - 5
skip σ if some free v_j is outside [lb_j, ub_j] - 6
if some λ gives g = v - w + S^T λ with g_j = 0 on F, g_j ≥ 0 on LOW, g_j ≤ 0 on UP: - 7
return v - 8
return "no feasible flux vector"
A reaction with gets only the state LOW, and its sign condition is dropped. Line L4 is the projection of onto : its solution is unique when it exists, though need not be. Line L6 is a small LP feasibility problem in , because is not unique when has dependent rows.
Example
Take network N of the FBA page, with reactions EX_A (uptake at most 10), RESP1 and RESP2 (), FERM (), EX_P and BIO (). The wild type is the FBA vertex .
Both respiration reactions knocked out. The mutant steady states are with : all growth must come from fermentation. FBA predicts . MOMA minimizes
whose derivative is zero at . So MOMA predicts the flux vector , with growth about 24 percent below the FBA value. The squared distance to is about 53.97, against about 63.89 for the FBA optimum.
RESP1 knocked out. FBA predicts that RESP2 takes over the whole flux and growth stays at . That state has the squared distance from . MOMA finds a closer state, , at squared distance about 19.93: RESP2 takes over only part of the flux, a little fermentation appears, and growth drops to . So MOMA predicts a small loss of growth and some secretion of where FBA predicts neither.
RESP2 or FERM knocked out. Both carry no flux in , so itself is feasible for the mutant and MOMA returns .
The tests check the exact solver on a one-dimensional and a two-dimensional family against a fine grid of feasible points, check that when is feasible, and check on random networks that the result satisfies the projection inequality for every vertex of the feasible polytope.
Correctness
The objective is strictly convex and the feasible set is a closed convex polyhedron, so if the set is not empty there is exactly one minimizer. With linear constraints, the KKT conditions are necessary and sufficient for a convex QP, so a vector is the minimizer if and only if it is feasible and some multipliers satisfy the sign conditions of line L6. Each returned vector passes those checks, so it is the minimizer. Conversely, the minimizer has KKT multipliers, and the state that puts each reaction with a positive bound multiplier at that bound and leaves the others free produces exactly the minimizer at line L4, since the projection in line L4 is unique. So the loop always returns when the set is not empty. The full proof is below.
Proof: The active set enumeration returns the unique MOMA flux vectorfull
Fix an matrix , a wild-type vector , and mutant bounds (entries may be infinite). Let and consider
The factor does not change the minimizer. The claim is that the code returns the unique minimizer of (MOMA) if is not empty, and None if is empty.
Lemma 1 (a unique minimizer). If is not empty, (MOMA) has exactly one minimizer .
Proof. is closed and convex. Pick . The set is closed, bounded and not empty, so the continuous function has a minimizer on it, and this point minimizes on all of . If were two minimizers with value , the midpoint is in , and , so its value is below , a contradiction.
For a vector and multipliers , write . Say that is a KKT point if and some gives, for every with : if , if , and if . (For there is no condition on .)
Lemma 2 (KKT is necessary and sufficient). A vector is the minimizer of (MOMA) if and only if it is a KKT point.
Proof. Sufficiency. Let be a KKT point with , and let . By convexity of , . Since , . Each term is non-negative: it is 0 if or (then ); if and , then ; if and , then . So .
Necessity. Let be the minimizer. For every and , , so , and letting gives for every in the cone of feasible directions . (Every is a feasible direction: for small , stays inside the bounds that are not tight.) So the linear program has the optimum 0 at . By LP duality (Farkas' lemma), its dual is feasible: there are and for the tight lower bounds, for the tight upper bounds, and free for the fixed reactions, with , where each of is 0 outside its index set. Then , which has the signs of the KKT conditions.
The code tries states: a state gives each reaction one of LOW, UP or FREE, where LOW needs a finite , UP a finite , and a fixed reaction () gets only LOW. Let be the free set of a state. Line L2 sets to its bound for , line L3 sets , and line L4 solves
Lemma 3 (the x part is unique). If this system has a solution, all its solutions have the same .
Proof. Let and be two solutions. Then is in the row space of , and , so it is in the null space of . These two spaces are orthogonal, so .
Lemma 4 (soundness). If the code returns at line L7, then is a KKT point, so .
Proof. . The bounds hold for by line L2 and for by the test of line L5, so . Line L6 accepts only if an LP in is feasible, with the rows for , for LOW, for UP, and none for fixed reactions. A free reaction with at a bound has , which satisfies its condition. A LOW reaction has and , and an UP reaction has and . So is a KKT point, and by Lemma 2 it is the minimizer, which is unique by Lemma 1. The LP of line L6 is decided correctly by solve_lp (Lemma 1 of the proof on the flux variability analysis page).
Lemma 5 (completeness). If is not empty, the code returns a vector.
Proof. Let be the minimizer, with KKT multipliers , , , from Lemma 2. Define the state : LOW for a fixed reaction; else LOW if ; else UP if ; else FREE. ( and cannot both hold for , since cannot be at both bounds.) This state is in the list. For it, line L2 sets each non-free to , so . For , , that is, . So solves the system of line L4, and by Lemma 3 solve_linear returns a solution with . Then passes line L5, and is a feasible point of the LP of line L6. So if the loop reaches , it returns there, and if it returns earlier, it returns a vector too.
Theorem. moma returns the unique minimizer of (MOMA) if is not empty, and None if is empty.
Proof. If is not empty, Lemma 5 says that the code returns some , and Lemma 4 says that . If is empty, every vector that passes lines L5 and L6 would be in by the proof of Lemma 4, so none passes and the code returns None at line L8. The order of the states (most free reactions first) changes only the running time.
Remark (cost). The number of states is at most , and each needs one linear system of size and one small LP. This is meant for toy networks and for checking a QP solver. On genome-scale networks, (MOMA) is solved by a convex quadratic programming solver, which needs no enumeration.
Complexity
- This code. At most states. Each one needs one linear system of size , in operations, and one LP in variables. This is exponential and meant for toy networks and tests.
- In practice. MOMA is a convex QP with variables, equality rows and bounds. Convex QPs can be solved in polynomial time, for example by interior point methods. This is a theorem. Active set QP solvers are fast on metabolic networks but have no polynomial bound in the worst case.
- Knockout screens. A screen of all single knockouts solves QPs with the same , one per reaction or gene.
- Space. for the KKT matrix of one state.
Properties
- Unique. For fixed , the answer is unique, because the objective is strictly convex. The FBA optimum of a mutant is often not unique.
- Depends on . The wild-type vector is often one of many FBA optima. Different choices of give different MOMA predictions. A from measured fluxes avoids this choice.
- Not optimal for growth. The MOMA growth rate is at most the FBA growth rate of the mutant, since both are computed over the same feasible set and FBA maximizes growth.
- Feasibility is the same as for FBA. MOMA has a solution exactly when the mutant has any steady state within the bounds.
- A hypothesis, not a law. That a fresh mutant stays close to the wild type is a heuristic. Segrè, Vitkup and Church compared MOMA and FBA with measured fluxes of a knockout mutant and with knockout growth data of E. coli, and reported that MOMA fits the mutant fluxes better; this is a measurement on their data.
Variants and improvements
- Linear MOMA. Replace the squared Euclidean norm by the sum of absolute differences . With one extra variable per reaction this is an LP, and it is often faster. Its solution need not be unique.
- ROOM. Regulatory on/off minimization (Shlomi, Berkman and Ruppin 2005) minimizes the number of reactions whose flux changes by more than a small tolerance, as a mixed-integer program. It models a cell that switches a few reactions instead of shifting all of them a little.
- Weighted MOMA. Weight each squared difference, for example by the inverse of the measurement variance of .
- Lethality prediction. A knockout is predicted lethal when the MOMA growth rate is below a small threshold, as with FBA, but the two methods can disagree on mutants with alternative routes.
When to use it
Use MOMA to predict the flux state or the growth of a mutant shortly after a knockout, when you have a good wild-type flux vector, ideally from measurements such as 13C flux analysis. Use FBA for the mutant after laboratory evolution, which often brings the mutant to its new optimum. For a strain design problem that needs the mutant to be optimal for growth, use OptKnock, whose inner problem is FBA.
Pitfalls
- An arbitrary . If is just the vertex that one LP solver returned, the MOMA prediction depends on that solver. Use measured fluxes, or a unique wild-type state such as the FBA optimum with the smallest norm.
- Units and scale. The Euclidean norm adds squared changes of all fluxes, so large fluxes dominate. A change of one unit in a large flux counts the same as a change of one unit in a small one.
- Exchange reactions. Including all exchange fluxes in the distance makes the result depend on the medium bounds. Some studies use only the internal fluxes in the objective.
- Numerics. With a floating point QP solver, fluxes that should be zero come out as small numbers. Use a tolerance before you read off which reactions are active.
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/minimization-of-metabolic-adjustment/. The authors are listed in prov/845EGQ.jsonl.
"""Minimization of metabolic adjustment (MOMA), solved exactly.
Given the wild-type flux vector w (an FBA optimum of the wild type) and the
bounds of a mutant (a knocked-out reaction has lb = ub = 0), MOMA returns the
mutant flux vector closest to w in the Euclidean norm:
minimize |v - w|^2 subject to S v = 0, lb <= v <= ub.
This is a strictly convex quadratic program, so the minimizer is unique. The
solver here is exact and meant for small networks: it tries every active set
(each reaction at its lower bound, at its upper bound, or free), solves the
equality-constrained problem for that set, and accepts the first candidate
that satisfies the KKT conditions. The cost is up to 3^m candidates.
KKT conditions, with lambda the multipliers of S v = 0 and
g = v - w + S^T lambda: g_j = 0 for a free reaction, g_j >= 0 at the lower
bound, g_j <= 0 at the upper bound (and any sign if lb_j = ub_j). lambda may
be not unique when S has dependent rows, so the sign test is a small LP
feasibility problem in lambda.
"""
from __future__ import annotations
from fractions import Fraction
from itertools import product
from typing import List, Optional, Sequence
from sy3lp import frac, solve_linear, solve_lp
LOW, UP, FREE = 0, 1, 2
def _choices(lo, hi):
if lo is not None and hi is not None and lo == hi:
return (LOW,)
out = []
if lo is not None:
out.append(LOW)
if hi is not None:
out.append(UP)
out.append(FREE)
return tuple(out)
def _multipliers_exist(S, v, w, state, lo, hi) -> bool:
"""Is there lambda with g = v - w + S^T lambda of the right signs?"""
n, m = len(S), len(v)
A_eq, b_eq, A_le, b_le = [], [], [], []
for j in range(m):
col = [frac(S[i][j]) for i in range(n)]
d = v[j] - w[j]
if lo[j] is not None and hi[j] is not None and lo[j] == hi[j]:
continue
if state[j] == FREE:
A_eq.append(col)
b_eq.append(-d)
elif state[j] == LOW: # d + col . lam >= 0
A_le.append([-x for x in col])
b_le.append(d)
else: # d + col . lam <= 0
A_le.append(col)
b_le.append(-d)
if n == 0:
return all(x == 0 for x in b_eq) and all(x >= 0 for x in b_le)
res = solve_lp([0] * n, A_eq=A_eq, b_eq=b_eq, A_le=A_le, b_le=b_le,
lb=[None] * n)
return res.status == "optimal"
def moma(S: Sequence[Sequence], lb: Sequence, ub: Sequence,
w: Sequence) -> Optional[List[Fraction]]:
"""The flux vector of the mutant closest to w, or None if infeasible."""
m = len(w)
w = [frac(x) for x in w]
lo = [None if x is None else frac(x) for x in lb]
hi = [None if x is None else frac(x) for x in ub]
n = len(S)
options = [_choices(lo[j], hi[j]) for j in range(m)]
# Try sets with more free reactions first: the answer is often interior.
states = sorted(product(*options), key=lambda s: -s.count(FREE))
for state in states: # @line L1
v = [Fraction(0)] * m
free = [j for j in range(m) if state[j] == FREE]
for j in range(m): # @line L2
if state[j] == LOW:
v[j] = lo[j]
elif state[j] == UP:
v[j] = hi[j]
# Project w_F onto {x : S_F x = r}: solve [I S_F^T; S_F 0] [x; mu] = [w_F; r].
r = [-sum(frac(S[i][j]) * v[j] for j in range(m) if state[j] != FREE) # @line L3
for i in range(n)]
k = len(free)
K = []
rhs = []
for a, j in enumerate(free):
K.append([Fraction(int(a == b)) for b in range(k)]
+ [frac(S[i][j]) for i in range(n)])
rhs.append(w[j])
for i in range(n):
K.append([frac(S[i][j]) for j in free] + [Fraction(0)] * n)
rhs.append(r[i])
sol = solve_linear(K, rhs) # @line L4
if sol is None:
continue
for a, j in enumerate(free):
v[j] = sol[a]
if any((lo[j] is not None and v[j] < lo[j]) or # @line L5
(hi[j] is not None and v[j] > hi[j]) for j in free):
continue
if _multipliers_exist(S, v, w, state, lo, hi): # @line L6
return v # @line L7
return None # @line L8
def sq_dist(v, w) -> Fraction:
return sum((frac(a) - frac(b)) ** 2 for a, b in zip(v, w))
# 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_minimization_of_metabolic_adjustment.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimization-of-metabolic-adjustment/. The authors are listed in prov/845EGQ.jsonl.
"""Tests of moma().
References:
- hand solutions on the toy network N, checked on a grid of feasible points;
- the projection inequality: v is the point of a convex set P closest to w
if and only if (w - v) . (p - v) <= 0 for every p in P. For a polytope it
is enough to test the vertices p, found by brute force.
"""
import random
from fractions import Fraction as F
from minimization_of_metabolic_adjustment import (C_N, LB_N, S_N, UB_N, moma,
sq_dist)
from sy3lp import polytope_vertices, solve_lp
W_N = [10, F(10, 3), 0, 0, 0, F(20, 3)]
def knockout(lb, ub, ko):
lb, ub = list(lb), list(ub)
for j in ko:
lb[j] = ub[j] = 0
return lb, ub
def test_wild_type_is_fba_optimum():
res = solve_lp(C_N, A_eq=S_N, b_eq=[0, 0, 0], lb=LB_N, ub=UB_N,
maximize=True)
assert res.x == W_N
def test_double_knockout_on_a_line():
lb, ub = knockout(LB_N, UB_N, [1, 2])
v = moma(S_N, lb, ub, W_N)
z = F(80, 21)
assert v == [2 * z, 0, 0, z, z, z]
# The feasible set is v = (2t, 0, 0, t, t, t) with 0 <= t <= 5.
best = sq_dist(v, W_N)
for k in range(0, 501):
t = F(k, 100)
assert best <= sq_dist([2 * t, 0, 0, t, t, t], W_N)
def test_single_knockout_on_a_grid():
lb, ub = knockout(LB_N, UB_N, [1])
v = moma(S_N, lb, ub, W_N)
assert v == [F(485, 51), 0, F(45, 17), F(40, 51), F(40, 51), F(310, 51)]
# FBA keeps the growth 20/3 here; MOMA predicts less.
assert v[5] < F(20, 3)
# Feasible set: v = (3a + 2b, 0, a, b, b, 2a + b), a, b >= 0, 3a + 2b <= 10.
best = sq_dist(v, W_N)
for i in range(0, 61):
for k in range(0, 61):
a, b = F(i, 18), F(k, 12)
if 3 * a + 2 * b <= 10:
p = [3 * a + 2 * b, 0, a, b, b, 2 * a + b]
assert best <= sq_dist(p, W_N)
def test_feasible_reference_is_returned():
lb, ub = knockout(LB_N, UB_N, [2])
assert moma(S_N, lb, ub, W_N) == W_N
def test_infeasible():
lb, ub = knockout(LB_N, UB_N, [5])
lb[5] = 1
ub[5] = 1
lb, ub = knockout(lb, ub, [0])
assert moma(S_N, lb, ub, W_N) is None
def test_random_against_projection_inequality():
rng = random.Random(11)
done = 0
while done < 30:
n, m = rng.randint(1, 2), rng.randint(3, 5)
S = [[rng.randint(-2, 2) for _ in range(m)] for _ in range(n)]
lb = [rng.choice([0, -1, -2]) for _ in range(m)]
ub = [rng.randint(0, 3) for _ in range(m)]
w = [F(rng.randint(-6, 6), rng.randint(1, 3)) for _ in range(m)]
v = moma(S, lb, ub, w)
verts = polytope_vertices(S, [0] * n, lb, ub)
assert v is not None and verts # v = 0 is always feasible here
assert all(sum(F(a) * b for a, b in zip(row, v)) == 0 for row in S)
assert all(lo <= x <= hi for lo, x, hi in zip(lb, v, ub))
for p in verts:
assert sum((wi - vi) * (pi - vi) for wi, vi, pi in zip(w, v, p)) <= 0
done += 1
History
Segrè, Vitkup and Church introduced MOMA in 2002. They noted that FBA assumes an optimal mutant, and that a mutant made in the laboratory has not been under selection for that optimum. They formulated the closest feasible flux vector as a quadratic program and compared it with FBA on knockouts in E. coli. Shlomi, Berkman and Ruppin (2005) proposed ROOM as a variant with a count of changed fluxes instead of a distance. MOMA and its linear form are standard functions of the COBRA tools.
References
- Daniel Segrè, Dennis Vitkup and George M. Church, Analysis of optimality in natural and perturbed metabolic networks, PNAS 99(23), 2002, 15112-15117, the definition of MOMA as a quadratic program and its comparison with FBA on E. coli knockouts
- Tomer Shlomi, Omer Berkman and Eytan Ruppin, Regulatory on/off minimization of metabolic flux changes after genetic perturbations, PNAS 102(21), 2005, 7695-7700, ROOM, the mixed-integer variant that minimizes the number of large flux changes
- Jeffrey D. Orth, Ines Thiele and Bernhard O. Palsson, What is flux balance analysis?, Nature Biotechnology 28(3), 2010, 245-248, the FBA problem that gives the wild-type flux vector
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 845EGQ Edit this page History Report an error Markdown