Algorithm Search⌘K

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
Properties
deterministicexactofflineiterative
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 ww 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 n×mn \times m stoichiometric matrix SS; a wild-type flux vector ww, usually an FBA optimum of the wild type with Sw=0S w = 0; and the bounds lb≤v≤ublb \le v \le ub of the mutant, where each knocked-out reaction has lbj=ubj=0lb_j = ub_j = 0.

Output. The flux vector

vMOMA=arg⁡min⁡v  ∥v−w∥2subject toSv=0,lb≤v≤ub,v^{\text{MOMA}} = \arg\min_{v} \; \|v - w\|^2 \quad \text{subject to} \quad S v = 0, \quad lb \le v \le ub,

or a report that the mutant has no steady state within the bounds. The predicted growth rate is the biomass flux of vMOMAv^{\text{MOMA}}.

vMOMAv^{\text{MOMA}} is the orthogonal projection of ww onto the mutant flux polyhedron PP. Expanding the square gives the standard QP form min⁡12vTv−wTv\min \frac{1}{2} v^{\mathsf T} v - w^{\mathsf T} v over PP.

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 ww onto an affine subspace, given by one linear system, and the KKT conditions decide whether the candidate is the minimizer.

  1. MOMA(S, lb, ub, w)
  2. 1for each state σ in {LOW, UP, FREE}^m, with the most FREE entries first:
  3. 2set v_j ← lb_j if σ_j = LOW and v_j ← ub_j if σ_j = UP; let F be the free set
  4. 3r ← - Σ over j not in F of S_j v_j
  5. 4solve x - w_F + S_F^T μ = 0, S_F x = r; skip σ if there is no solution; v_F ← x
  6. 5skip σ if some free v_j is outside [lb_j, ub_j]
  7. 6if some λ gives g = v - w + S^T λ with g_j = 0 on F, g_j ≥ 0 on LOW, g_j ≤ 0 on UP:
  8. 7return v
  9. 8return "no feasible flux vector"

A reaction with lbj=ubjlb_j = ub_j gets only the state LOW, and its sign condition is dropped. Line L4 is the projection of wFw_F onto {x:SFx=r}\{x : S_F x = r\}: its solution xx is unique when it exists, though μ\mu need not be. Line L6 is a small LP feasibility problem in λ\lambda, because λ\lambda is not unique when SS has dependent rows.

Example

Take network N of the FBA page, with reactions EX_A (uptake at most 10), RESP1 and RESP2 (A→2EA \to 2E), FERM (A→E+PA \to E + P), EX_P and BIO (A+E→A + E \to). The wild type is the FBA vertex w=(10,103,0,0,0,203)w = (10, \frac{10}{3}, 0, 0, 0, \frac{20}{3}).

Both respiration reactions knocked out. The mutant steady states are v=(2g,0,0,g,g,g)v = (2g, 0, 0, g, g, g) with 0≤g≤50 \le g \le 5: all growth must come from fermentation. FBA predicts g=5g = 5. MOMA minimizes

(2g−10)2+(103)2+g2+g2+(g−203)2,(2g - 10)^2 + \left(\tfrac{10}{3}\right)^2 + g^2 + g^2 + \left(g - \tfrac{20}{3}\right)^2,

whose derivative 14g−160314 g - \frac{160}{3} is zero at g=8021≈3.81g = \frac{80}{21} \approx 3.81. So MOMA predicts the flux vector (16021,0,0,8021,8021,8021)(\frac{160}{21}, 0, 0, \frac{80}{21}, \frac{80}{21}, \frac{80}{21}), with growth about 24 percent below the FBA value. The squared distance to ww 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 203≈6.67\frac{20}{3} \approx 6.67. That state has the squared distance 2009≈22.2\frac{200}{9} \approx 22.2 from ww. MOMA finds a closer state, v=(48551,0,4517,4051,4051,31051)v = (\frac{485}{51}, 0, \frac{45}{17}, \frac{40}{51}, \frac{40}{51}, \frac{310}{51}), at squared distance about 19.93: RESP2 takes over only part of the flux, a little fermentation appears, and growth drops to 31051≈6.08\frac{310}{51} \approx 6.08. So MOMA predicts a small loss of growth and some secretion of PP where FBA predicts neither.

RESP2 or FERM knocked out. Both carry no flux in ww, so ww itself is feasible for the mutant and MOMA returns v=wv = w.

The tests check the exact solver on a one-dimensional and a two-dimensional family against a fine grid of feasible points, check that v=wv = w when ww is feasible, and check on random networks that the result satisfies the projection inequality (w−v)T(p−v)≤0(w - v)^{\mathsf T}(p - v) \le 0 for every vertex pp 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 n×mn \times m matrix SS, a wild-type vector w∈Qmw \in \mathbb{Q}^m, and mutant bounds lbj≤ubjlb_j \le ub_j (entries may be infinite). Let P={v:Sv=0,  lb≤v≤ub}P = \{v : S v = 0, \; lb \le v \le ub\} and consider

(MOMA)min⁡v∈P  q(v)=12∥v−w∥2.\text{(MOMA)} \qquad \min_{v \in P} \; q(v) = \tfrac{1}{2} \|v - w\|^2 .

The factor 12\frac{1}{2} does not change the minimizer. The claim is that the code returns the unique minimizer of (MOMA) if PP is not empty, and None if PP is empty.

Lemma 1 (a unique minimizer). If PP is not empty, (MOMA) has exactly one minimizer v∗v^*.

Proof. PP is closed and convex. Pick p∈Pp \in P. The set P∩{v:∥v−w∥≤∥p−w∥}P \cap \{v : \|v - w\| \le \|p - w\|\} is closed, bounded and not empty, so the continuous function qq has a minimizer on it, and this point minimizes qq on all of PP. If u≠u′u \ne u' were two minimizers with value q∗q^*, the midpoint 12(u+u′)\frac{1}{2}(u + u') is in PP, and ∥12(u+u′)−w∥2=12∥u−w∥2+12∥u′−w∥2−14∥u−u′∥2<2q∗\|\frac{1}{2}(u + u') - w\|^2 = \frac{1}{2}\|u - w\|^2 + \frac{1}{2}\|u' - w\|^2 - \frac{1}{4}\|u - u'\|^2 < 2 q^*, so its value is below q∗q^*, a contradiction. □\square

For a vector vv and multipliers λ∈Rn\lambda \in \mathbb{R}^n, write g=v−w+STλg = v - w + S^{\mathsf T} \lambda. Say that vv is a KKT point if v∈Pv \in P and some λ\lambda gives, for every jj with lbj<ubjlb_j < ub_j: gj=0g_j = 0 if lbj<vj<ubjlb_j < v_j < ub_j, gj≥0g_j \ge 0 if vj=lbjv_j = lb_j, and gj≤0g_j \le 0 if vj=ubjv_j = ub_j. (For lbj=ubjlb_j = ub_j there is no condition on gjg_j.)

Lemma 2 (KKT is necessary and sufficient). A vector vv is the minimizer of (MOMA) if and only if it is a KKT point.

Proof. Sufficiency. Let vv be a KKT point with λ\lambda, and let u∈Pu \in P. By convexity of qq, q(u)≥q(v)+(v−w)T(u−v)q(u) \ge q(v) + (v - w)^{\mathsf T}(u - v). Since Su=Sv=0S u = S v = 0, (v−w)T(u−v)=gT(u−v)(v - w)^{\mathsf T}(u - v) = g^{\mathsf T}(u - v). Each term gj(uj−vj)g_j (u_j - v_j) is non-negative: it is 0 if gj=0g_j = 0 or lbj=ubjlb_j = ub_j (then uj=vju_j = v_j); if vj=lbjv_j = lb_j and gj≥0g_j \ge 0, then uj−vj≥0u_j - v_j \ge 0; if vj=ubjv_j = ub_j and gj≤0g_j \le 0, then uj−vj≤0u_j - v_j \le 0. So q(u)≥q(v)q(u) \ge q(v).

Necessity. Let v=v∗v = v^* be the minimizer. For every u∈Pu \in P and θ∈(0,1]\theta \in (0, 1], v+θ(u−v)∈Pv + \theta(u - v) \in P, so q(v+θ(u−v))≥q(v)q(v + \theta (u - v)) \ge q(v), and letting θ→0\theta \to 0 gives (v−w)Th≥0(v - w)^{\mathsf T} h \ge 0 for every hh in the cone of feasible directions D={h:Sh=0,  hj≥0 if vj=lbj,  hj≤0 if vj=ubj,  hj=0 if lbj=ubj}D = \{h : S h = 0, \; h_j \ge 0 \text{ if } v_j = lb_j, \; h_j \le 0 \text{ if } v_j = ub_j, \; h_j = 0 \text{ if } lb_j = ub_j\}. (Every h∈Dh \in D is a feasible direction: for small θ>0\theta > 0, v+θhv + \theta h stays inside the bounds that are not tight.) So the linear program min⁡{(v−w)Th:h∈D}\min \{(v - w)^{\mathsf T} h : h \in D\} has the optimum 0 at h=0h = 0. By LP duality (Farkas' lemma), its dual is feasible: there are λ\lambda and αj≥0\alpha_j \ge 0 for the tight lower bounds, βj≥0\beta_j \ge 0 for the tight upper bounds, and free γj\gamma_j for the fixed reactions, with v−w=−STλ+α−β+γv - w = -S^{\mathsf T} \lambda + \alpha - \beta + \gamma, where each of α,β,γ\alpha, \beta, \gamma is 0 outside its index set. Then g=α−β+γg = \alpha - \beta + \gamma, which has the signs of the KKT conditions. □\square

The code tries states: a state gives each reaction one of LOW, UP or FREE, where LOW needs a finite lbjlb_j, UP a finite ubjub_j, and a fixed reaction (lbj=ubjlb_j = ub_j) gets only LOW. Let FF be the free set of a state. Line L2 sets vjv_j to its bound for j∉Fj \notin F, line L3 sets r=−∑j∉FS⋅jvjr = -\sum_{j \notin F} S_{\cdot j} v_j, and line L4 solves

(ISFTSF0)(xμ)=(wFr).\begin{pmatrix} I & S_F^{\mathsf T} \\ S_F & 0 \end{pmatrix} \begin{pmatrix} x \\ \mu \end{pmatrix} = \begin{pmatrix} w_F \\ r \end{pmatrix} .

Lemma 3 (the x part is unique). If this system has a solution, all its solutions have the same xx.

Proof. Let (x,μ)(x, \mu) and (x′,μ′)(x', \mu') be two solutions. Then x−x′=−SFT(μ−μ′)x - x' = -S_F^{\mathsf T}(\mu - \mu') is in the row space of SFS_F, and SF(x−x′)=0S_F(x - x') = 0, so it is in the null space of SFS_F. These two spaces are orthogonal, so x−x′=0x - x' = 0. □\square

Lemma 4 (soundness). If the code returns vv at line L7, then vv is a KKT point, so v=v∗v = v^*.

Proof. Sv=SFx+∑j∉FS⋅jvj=r−r=0S v = S_F x + \sum_{j \notin F} S_{\cdot j} v_j = r - r = 0. The bounds hold for j∉Fj \notin F by line L2 and for j∈Fj \in F by the test of line L5, so v∈Pv \in P. Line L6 accepts only if an LP in λ\lambda is feasible, with the rows gj=0g_j = 0 for j∈Fj \in F, gj≥0g_j \ge 0 for LOW, gj≤0g_j \le 0 for UP, and none for fixed reactions. A free reaction with vjv_j at a bound has gj=0g_j = 0, which satisfies its condition. A LOW reaction has vj=lbjv_j = lb_j and gj≥0g_j \ge 0, and an UP reaction has vj=ubjv_j = ub_j and gj≤0g_j \le 0. So vv 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). □\square

Lemma 5 (completeness). If PP is not empty, the code returns a vector.

Proof. Let v∗v^* be the minimizer, with KKT multipliers λ∗\lambda^*, α∗\alpha^*, β∗\beta^*, γ∗\gamma^* from Lemma 2. Define the state σ\sigma: LOW for a fixed reaction; else LOW if αj∗>0\alpha^*_j > 0; else UP if βj∗>0\beta^*_j > 0; else FREE. (αj∗>0\alpha^*_j > 0 and βj∗>0\beta^*_j > 0 cannot both hold for lbj<ubjlb_j < ub_j, since vj∗v^*_j cannot be at both bounds.) This state is in the list. For it, line L2 sets each non-free vjv_j to vj∗v^*_j, so r=SFvF∗r = S_F v^*_F. For j∈Fj \in F, gj∗=0g^*_j = 0, that is, vj∗−wj+(SFTλ∗)j=0v^*_j - w_j + (S_F^{\mathsf T} \lambda^*)_j = 0. So (x,μ)=(vF∗,λ∗)(x, \mu) = (v^*_F, \lambda^*) solves the system of line L4, and by Lemma 3 solve_linear returns a solution with x=vF∗x = v^*_F. Then v=v∗∈Pv = v^* \in P passes line L5, and λ∗\lambda^* is a feasible point of the LP of line L6. So if the loop reaches σ\sigma, it returns there, and if it returns earlier, it returns a vector too. □\square

Theorem. moma returns the unique minimizer of (MOMA) if PP is not empty, and None if PP is empty.

Proof. If PP is not empty, Lemma 5 says that the code returns some vv, and Lemma 4 says that v=v∗v = v^*. If PP is empty, every vector that passes lines L5 and L6 would be in PP 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. □\square

Remark (cost). The number of states is at most 3m3^m, and each needs one linear system of size ∣F∣+n|F| + n 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 3m3^m states. Each one needs one linear system of size ∣F∣+n≤m+n|F| + n \le m + n, in O((m+n)3)O((m + n)^3) operations, and one LP in nn variables. This is exponential and meant for toy networks and tests.
  • In practice. MOMA is a convex QP with mm variables, nn equality rows and 2m2m 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 mm QPs with the same ww, one per reaction or gene.
  • Space. O((m+n)2)O((m + n)^2) for the KKT matrix of one state.

Properties

  • Unique. For fixed ww, the answer is unique, because the objective is strictly convex. The FBA optimum of a mutant is often not unique.
  • Depends on ww. The wild-type vector is often one of many FBA optima. Different choices of ww give different MOMA predictions. A ww 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 ∑j∣vj−wj∣\sum_j |v_j - w_j|. 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 wjw_j.
  • 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 ww. If ww 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.

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

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

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