Algorithm Search⌘K

Algorithmadvanced

OptKnock

Also called bilevel knockout optimization.

Choose reaction deletions that couple product secretion to growth, as a bilevel mixed-integer program with FBA as the inner problem.

Time
O((c + 1)^K T) worst
Space
O((m + n)^2) extra
Where
K = the largest number of knockouts; T = the time of one LP with 2m + n variables; c = the number of candidate reactions; m = the number of reactions; n = the number of metabolites
Properties
deterministicexactofflineiterative
Origin
Anthony P. Burgard, Priti Pharkya, Costas D. Maranas, 2003

OptKnock searches for a set of reaction deletions that makes a microbe secrete a chosen product as a side effect of growing. A wild-type cell that maximizes growth usually secretes little of a useful product, because making the product costs carbon and energy. OptKnock removes up to KK reactions so that, in the mutant, every way of growing at the best rate must also secrete the product. Then selection for growth also selects for production. Burgard, Pharkya and Maranas (2003) wrote this as a bilevel program: the outer level chooses the deletions to maximize the product flux, and the inner level is the FBA problem of the mutant, which maximizes growth. The inner LP is replaced by its dual and a strong duality equation, which gives one mixed-integer program.

In plain words

You want a factory that makes a product, but the factory manager only cares about one thing: producing as much new factory as possible. You cannot give orders to the manager. You can only remove some machines before the manager starts.

OptKnock looks for the machines to remove so that the manager's best plan, chosen only for growth, also makes a lot of your product. If you remove the right machines, the only good way left to grow is a way that gives off the product as waste. The method checks this by solving the manager's problem inside your own problem. A trick from linear programming turns the two nested problems into one problem that a standard solver can handle.

The problem

Input. An n×mn \times m stoichiometric matrix SS; flux bounds lb≤v≤ublb \le v \le ub; the index bb of the biomass reaction and pp of the product secretion; a set CC of candidate reactions that may be deleted; a limit KK; and optionally a growth floor μmin⁡\mu_{\min}.

Output. A set D⊆CD \subseteq C with ∣D∣≤K|D| \le K that solves the bilevel program

max⁡D  vpwherev∈arg⁡max⁡u{ub:Su=0,  lbD≤u≤ubD},vb≥μmin⁡,\max_{D} \; v_p \quad \text{where} \quad v \in \arg\max_{u} \{ u_b : S u = 0, \; lb^D \le u \le ub^D \}, \quad v_b \ge \mu_{\min},

with lbjD=ubjD=0lb^D_j = ub^D_j = 0 for j∈Dj \in D, together with the flux vector vv. When the inner problem has several optima, the original formulation takes the one with the largest product. This is the optimistic version: it is the best case among the states that the cell might choose.

The algorithm

For a fixed DD, the inner LP max⁡{ub:Su=0,  lb≤u≤ub}\max \{u_b : S u = 0, \; lb \le u \le ub\} has the dual

min⁡  ubTα−lbTβsubject toSTλ+α−β=eb,α,β≥0,\min \; ub^{\mathsf T} \alpha - lb^{\mathsf T} \beta \quad \text{subject to} \quad S^{\mathsf T} \lambda + \alpha - \beta = e_b, \quad \alpha, \beta \ge 0,

with free λ\lambda, one αj\alpha_j for each finite upper bound and one βj\beta_j for each finite lower bound. By weak duality every dual feasible point bounds ubu_b from above. So vv is an optimum of the inner LP exactly when vv is primal feasible and some dual feasible point has vb=ubTα−lbTβv_b = ub^{\mathsf T} \alpha - lb^{\mathsf T} \beta. Putting these rows together gives one LP in (v,λ,α,β)(v, \lambda, \alpha, \beta) for each DD. Burgard and co-authors add binary variables yjy_j for the deletions, which makes the products ubjyjαjub_j y_j \alpha_j appear; they linearize them with bounds on the dual variables, as in a big-M formulation, and solve one MILP. The implementation here enumerates the sets DD instead of using binaries.

  1. OPTKNOCK(S, lb, ub, b, p, K, C, μ_min)
  2. 1best ← none
  3. 2for each D ⊆ C with |D| ≤ K, by size:
  4. 3(lb_D, ub_D) ← lb, ub with lb_j = ub_j = 0 for j in D
  5. 4solve max v_p subject to S v = 0, lb_D ≤ v ≤ ub_D, v_b ≥ μ_min, S^T λ + α - β = e_b, α, β ≥ 0, v_b = ub_D^T α - lb_D^T β
  6. 5if the LP is infeasible then continue
  7. 6if best is none or v_p > the product of best then best ← (D, v)
  8. 7return best

The LP of line L4 is infeasible exactly when the mutant has no steady state, when its growth is unbounded, or when its optimal growth is below μmin⁡\mu_{\min}.

Example

Take network N of the FBA page: uptake EX_A of a substrate AA (at most 10), two respiration reactions RESP1 and RESP2 (A→2EA \to 2E), fermentation FERM (A→E+PA \to E + P), secretion EX_P of the product PP, and growth BIO (A+E→A + E \to). The candidates are RESP1, RESP2 and FERM, and the product is the flux of EX_P.

  • K=0K = 0. The wild type grows at 203\frac{20}{3} by respiration only, and every optimum has zero fermentation, so the product is 0.
  • K=1K = 1. Deleting one respiration reaction leaves the other one, and growth stays at 203\frac{20}{3} with no product. Deleting FERM removes the product route. So the best product is still 0.
  • K=2K = 2. Deleting RESP1 and RESP2 leaves fermentation as the only source of EE. The mutant grows at 5, and its only optimal state is v=(10,0,0,5,5,5)v = (10, 0, 0, 5, 5, 5): it must secrete 5 units of PP. Growth and production are now coupled. OptKnock returns D={RESP1,RESP2}D = \{\text{RESP1}, \text{RESP2}\}.
  • Growth floor. With μmin⁡=6\mu_{\min} = 6, the coupled design grows too slowly, and the best design keeps respiration, with product 0 and growth 203\frac{20}{3}. With μmin⁡=7\mu_{\min} = 7, above the wild-type optimum, no design is feasible.

Optimistic and guaranteed values. Change the network so that it has one respiration reaction A→EA \to E and the fermentation A→E+PA \to E + P, with the same yield of EE. Then growth is the same for any split between the two, and the optimal face of the inner LP contains states with any product from 0 to 5. The OptKnock value without deletions is 5, but the cell may choose the state with product 0. The tests check this case, which is the reason for the max-min variant RobustKnock.

On random small networks, the tests check that the inner LP and its dual have the same optimum, which also equals the best growth over the vertices of the flux polytope. They check that the LP of line L4 has the same value as a two-step solve that uses no duality: first FBA for the optimal growth, then the maximum product with growth fixed at that value. Finally they compare optknock with a direct enumeration that uses those two-step solves.

Correctness

For a fixed DD, weak duality says that ub≤ubTα−lbTβu_b \le ub^{\mathsf T} \alpha - lb^{\mathsf T} \beta for every primal feasible uu and dual feasible (λ,α,β)(\lambda, \alpha, \beta). So a feasible point of the LP of line L4 has a vv that is optimal for the inner problem. Conversely, if vv is optimal for the inner problem, strong duality gives a dual solution with the same value, so vv extends to a feasible point of the LP. The LP therefore maximizes vpv_p over exactly the inner optima with vb≥μmin⁡v_b \ge \mu_{\min}, which is the optimistic bilevel value for DD. Line L2 visits every allowed set, so the best set found is a solution of the bilevel program. The full proof is below.

Proof: The single-level LP equals the optimistic OptKnock value for each knockout setfull

Fix an n×mn \times m matrix SS, bounds lb≤ublb \le ub (entries may be infinite), a biomass index bb, a product index pp, a growth floor μmin⁡\mu_{\min}, a candidate list CC and a limit KK. For a knockout set D⊆CD \subseteq C let lbD,ubDlb^D, ub^D be the bounds with lbjD=ubjD=0lb^D_j = ub^D_j = 0 for j∈Dj \in D, and let

(IND)max⁡  vbsubject toSv=0,lbD≤v≤ubD\text{(IN}_D\text{)} \qquad \max \; v_b \quad \text{subject to} \quad S v = 0, \quad lb^D \le v \le ub^D

be the inner FBA problem. Let ODO_D be the set of optimal solutions of (IND_D), empty if (IND_D) is infeasible or unbounded. The optimistic OptKnock value of DD is

ϕ(D)=max⁡{vp:v∈OD,  vb≥μmin⁡},\phi(D) = \max \{ v_p : v \in O_D, \; v_b \ge \mu_{\min} \},

with ϕ(D)=−∞\phi(D) = -\infty if this set is empty. OptKnock asks for DD with ∣D∣≤K|D| \le K that maximizes ϕ(D)\phi(D). We assume that vpv_p is bounded above on ODO_D for each DD; this holds, for example, when the bounds make the flux polyhedron bounded. (If it fails for some DD, solve_lp reports "unbounded" for that DD and the code skips it.)

For fixed bounds lb,ublb, ub (we drop the index DD), let U={j:ubj<∞}U = \{j : ub_j < \infty\} and L={j:lbj>−∞}L = \{j : lb_j > -\infty\}. The dual of the inner LP is

(DU)min⁡  ∑j∈Uubjαj−∑j∈Llbjβjsubject toSTλ+α−β=eb,α,β≥0,\text{(DU)} \qquad \min \; \sum_{j \in U} ub_j \alpha_j - \sum_{j \in L} lb_j \beta_j \quad \text{subject to} \quad S^{\mathsf T} \lambda + \alpha - \beta = e_b, \quad \alpha, \beta \ge 0,

with λ∈Rn\lambda \in \mathbb{R}^n free, αj\alpha_j present only for j∈Uj \in U and βj\beta_j only for j∈Lj \in L. single_level_lp builds the LP

(SL)max⁡  vpsubject toSv=0,  lb≤v≤ub,  vb≥μmin⁡,  (λ,α,β) feasible for (DU),  vb=ubTα−lbTβ.\text{(SL)} \qquad \max \; v_p \quad \text{subject to} \quad S v = 0, \; lb \le v \le ub, \; v_b \ge \mu_{\min}, \; (\lambda, \alpha, \beta) \text{ feasible for (DU)}, \; v_b = ub^{\mathsf T} \alpha - lb^{\mathsf T} \beta .

Lemma 1 (weak duality). For every vv feasible for the inner LP and every (λ,α,β)(\lambda, \alpha, \beta) feasible for (DU), vb≤ubTα−lbTβv_b \le ub^{\mathsf T} \alpha - lb^{\mathsf T} \beta.

Proof. vb=ebTv=(STλ+α−β)Tv=λTSv+∑j∈Uαjvj−∑j∈Lβjvjv_b = e_b^{\mathsf T} v = (S^{\mathsf T} \lambda + \alpha - \beta)^{\mathsf T} v = \lambda^{\mathsf T} S v + \sum_{j \in U} \alpha_j v_j - \sum_{j \in L} \beta_j v_j. The first term is 0. For j∈Uj \in U, αj≥0\alpha_j \ge 0 and vj≤ubjv_j \le ub_j, so αjvj≤αjubj\alpha_j v_j \le \alpha_j ub_j. For j∈Lj \in L, βj≥0\beta_j \ge 0 and vj≥lbjv_j \ge lb_j, so −βjvj≤−βjlbj-\beta_j v_j \le -\beta_j lb_j. □\square

Lemma 2 (the projection of (SL)). A vector vv is the vv part of a feasible point of (SL) if and only if v∈Ov \in O and vb≥μmin⁡v_b \ge \mu_{\min}, where OO is the set of optimal solutions of the inner LP.

Proof. Let (v,λ,α,β)(v, \lambda, \alpha, \beta) be feasible for (SL). For any inner feasible uu, Lemma 1 gives ub≤ubTα−lbTβ=vbu_b \le ub^{\mathsf T} \alpha - lb^{\mathsf T} \beta = v_b. So vv is optimal, and vb≥μmin⁡v_b \ge \mu_{\min} is a row of (SL). Conversely, let v∈Ov \in O with vb≥μmin⁡v_b \ge \mu_{\min}. The inner LP has a finite optimum, so by the strong duality theorem of linear programming, (DU) has an optimal solution (λ,α,β)(\lambda, \alpha, \beta) with the same value ubTα−lbTβ=vbub^{\mathsf T} \alpha - lb^{\mathsf T} \beta = v_b. (The inner LP is in the form max⁡{ebTv:Sv=0,  vj≤ubj  (j∈U),  −vj≤−lbj  (j∈L)}\max \{e_b^{\mathsf T} v : S v = 0, \; v_j \le ub_j \; (j \in U), \; -v_j \le -lb_j \; (j \in L)\}, and (DU) is its dual: λ\lambda for the equations, αj\alpha_j for the rows vj≤ubjv_j \le ub_j, and βj\beta_j for the rows −vj≤−lbj-v_j \le -lb_j. A free variable vjv_j gives the equation (STλ+α−β)j=(eb)j(S^{\mathsf T}\lambda + \alpha - \beta)_j = (e_b)_j.) So (v,λ,α,β)(v, \lambda, \alpha, \beta) is feasible for (SL). □\square

Lemma 3 (the value for one set). For each DD, single_level_lp on the bounds lbD,ubDlb^D, ub^D returns "optimal" with vp=ϕ(D)v_p = \phi(D) and some v∈ODv \in O_D when ϕ(D)>−∞\phi(D) > -\infty, and "infeasible" when ϕ(D)=−∞\phi(D) = -\infty.

Proof. By Lemma 2 the set of vv parts of the feasible points of (SL) is {v∈OD:vb≥μmin⁡}\{v \in O_D : v_b \ge \mu_{\min}\}, and the objective of (SL) is vpv_p. If this set is empty, (SL) is infeasible, and ϕ(D)=−∞\phi(D) = -\infty. Otherwise the maximum of vpv_p over it is ϕ(D)\phi(D), finite by the assumption, and attained, since ODO_D is a polyhedron (a face of the inner polyhedron) and a linear function bounded above on a non-empty polyhedron attains its maximum. solve_lp returns the correct status and an optimum (Lemma 1 of the proof on the flux variability analysis page). The code sets the lower bound of vbv_b in (SL) to max⁡(lbb,μmin⁡)\max(lb_b, \mu_{\min}), which is the same as the two rows vb≥lbbv_b \ge lb_b and vb≥μmin⁡v_b \ge \mu_{\min}. □\square

Theorem. optknock returns None if ϕ(D)=−∞\phi(D) = -\infty for every D⊆CD \subseteq C with ∣D∣≤K|D| \le K. Otherwise it returns (D∗,v∗)(D^*, v^*) with ∣D∗∣≤K|D^*| \le K, ϕ(D∗)=max⁡∣D∣≤Kϕ(D)\phi(D^*) = \max_{|D| \le K} \phi(D), v∗∈OD∗v^* \in O_{D^*}, vb∗≥μmin⁡v^*_b \ge \mu_{\min} and vp∗=ϕ(D∗)v^*_p = \phi(D^*).

Proof. Lines L2 and L3 visit every D⊆CD \subseteq C with ∣D∣≤K|D| \le K exactly once, by size and then in the order of combinations. For each, line L4 computes ϕ(D)\phi(D) and an optimal vv by Lemma 3, and line L5 skips the sets with ϕ(D)=−∞\phi(D) = -\infty. Line L6 keeps a set with the largest vpv_p seen so far and replaces it only on a strict increase, so at line L7 it holds a maximizer of ϕ\phi, the first one in the visiting order. If no set passes line L5, best stays None. □\square

Remark (the optimistic value). For a fixed DD, the inner LP may have many optimal vv with different vpv_p. (SL) picks the one with the largest product, so ϕ(D)\phi(D) is the best case for the engineer. The worst case min⁡{vp:v∈OD}\min \{v_p : v \in O_D\} is also an LP of the same form with the objective reversed; it is the guaranteed product of the design. The test with one respiration route shows a set DD where the two values are 5 and 0.

Remark (the MILP). Burgard, Pharkya and Maranas write the same problem with binary variables yjy_j (yj=0y_j = 0 if j∈Dj \in D), the bounds lbjyj≤vj≤ubjyjlb_j y_j \le v_j \le ub_j y_j, and the dual variables of the bounds switched off by big constants when yj=0y_j = 0. For each fixed yy, that MILP is the LP (SL) for the corresponding DD, so the enumeration here and the MILP have the same optimum, provided the big constants are large enough not to cut off the optimal dual solutions.

Complexity

  • This code. The number of sets is ∑k≤K(ck)≤(c+1)K\sum_{k \le K} \binom{c}{k} \le (c + 1)^K for cc candidates, and each needs one LP with 2m+n2m + n or fewer variables and n+m+1n + m + 1 equality rows. So the time is O((c+1)KT)O((c + 1)^K T) for an LP time TT. This is exact, and it is practical only for small KK or few candidates.
  • The MILP. The MILP of Burgard and co-authors has cc binary variables. Mixed-integer programming is NP-hard in general, so no polynomial bound is known for the solver. Branch and bound and branch and cut codes solve it for genome-scale models with small KK in practice; this is an observation, not a bound.
  • Reductions of the candidate set. Removing essential reactions, blocked reactions and reactions without gene association before the search makes cc much smaller. This is the usual preprocessing step.
  • Space. O((m+n)2)O((m + n)^2) for one LP tableau.

Properties

  • Exact for its model. For each DD the LP value is the exact optimistic bilevel value, and the enumeration finds the best set.
  • Optimistic. The design is evaluated at the inner optimum that is best for the product. The cell may choose another optimum with less product. FVA on the product flux of the mutant at its optimal growth gives the guaranteed value.
  • Growth coupling. A good design makes the product flux positive at every optimal state of the mutant, not only at one. The production envelope of the mutant shows this.
  • Assumes an optimal mutant. OptKnock uses FBA as the inner model, so it assumes that the mutant grows at its optimum, for example after adaptive evolution. Right after a deletion, MOMA is the usual model instead.
  • Monotone in K. A larger KK never gives a smaller optimum, since every set allowed for KK is allowed for K+1K + 1.

Variants and improvements

  • RobustKnock. Tepper and Shlomi (2010) maximize the guaranteed product, the minimum of vpv_p over the inner optima. This is a max-min program, and they reduce it to a MILP with a second dual.
  • OptStrain and OptReg. Extensions that add reactions from a database or up- and down-regulate fluxes instead of deleting them.
  • OptGene. A genetic algorithm searches the knockout sets and evaluates each one by FBA or MOMA. It allows nonlinear objectives, but it is a heuristic with no guarantee of finding the best set.
  • Gene-level deletions. Deleting a gene removes all the reactions that depend on it, through the gene-protein-reaction rules. The candidate set is then a set of genes, and one binary variable switches off several reactions.
  • Minimal cut sets. Sets of reactions whose removal blocks a given flux, often computed from elementary flux modes, are a related approach to coupling.

When to use it

Use OptKnock to propose knockout strategies for growth-coupled production in a genome-scale model, before laboratory work. Check every proposed design with FVA for its guaranteed production, and prefer designs that couple the product at all optimal states. For small models or small KK, the enumeration of this page gives the exact answer and a list of all good designs. For designs that must not depend on optimal growth, use MOMA or a robust formulation.

Pitfalls

  • Optimistic designs. A design with high OptKnock value but zero guaranteed product often fails in the laboratory, as in the tie example.
  • Big constants. In the MILP, the bounds on the dual variables must be large enough. Too small values cut off the true dual solution and give a wrong design.
  • Unbounded product. If the product can grow without bound on the optimal face (for example through a cycle), the outer problem is unbounded. Bound every flux in the model.
  • Wrong candidates. Exchange reactions, spontaneous reactions and reactions without a gene are not real deletion targets. Remove them from the candidate set.
  • Model gaps. Missing reactions in the model can make a design look coupled when the real cell has a bypass. Gap filling and FVA on the mutant reduce this risk.

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.

optknock.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optknock/. The authors are listed in prov/K9KY6N.jsonl.
"""OptKnock with the inner problem replaced by its LP dual.

OptKnock is the bilevel program

    maximize v_prod over knockout sets D with |D| <= K
    where v solves  max v_bio  s.t.  S v = 0,  lb_D <= v <= ub_D,

and lb_D, ub_D are the bounds with lb_j = ub_j = 0 for j in D, plus an
outer floor v_bio >= mu_min. For a fixed D the inner LP has the dual

    minimize ub^T alpha - lb^T beta  s.t.  S^T lam + alpha - beta = e_bio,
    alpha, beta >= 0, lam free

(alpha_j is left out when ub_j is infinite and beta_j when lb_j is
infinite). By strong duality, v is optimal for the inner LP if and only if
some dual feasible (lam, alpha, beta) has v_bio = ub^T alpha - lb^T beta.
So the bilevel program for a fixed D is the single LP below. Burgard,
Pharkya and Maranas write the same thing with binary variables y_j for the
knockouts, which makes it a MILP. This code fixes y by enumerating every D
with |D| <= K, which is exact and only fit for small K and small networks.
"""

from __future__ import annotations

from fractions import Fraction
from itertools import combinations
from typing import List, Optional, Sequence, Tuple

from sy3lp import frac, solve_lp


def knockout(lb, ub, D):
    lb, ub = list(lb), list(ub)
    for j in D:
        lb[j] = 0
        ub[j] = 0
    return lb, ub


def single_level_lp(S, lb, ub, bio, prod, mu_min=0):
    """The OptKnock LP for fixed bounds: primal, dual and strong duality.

    Variables, in order: v (m), lam (n), alpha (one per finite ub),
    beta (one per finite lb). Returns the LPResult and the slice of v.
    """
    n, m = len(S), len(lb)
    A_idx = [j for j in range(m) if ub[j] is not None]
    B_idx = [j for j in range(m) if lb[j] is not None]
    N = m + n + len(A_idx) + len(B_idx)
    A_eq: List[List[Fraction]] = []
    b_eq: List[Fraction] = []
    for i in range(n):  # primal: S v = 0
        A_eq.append([frac(S[i][j]) for j in range(m)] + [Fraction(0)] * (N - m))
        b_eq.append(Fraction(0))
    for j in range(m):  # dual: S^T lam + alpha - beta = e_bio
        row = [Fraction(0)] * N
        for i in range(n):
            row[m + i] = frac(S[i][j])
        if j in A_idx:
            row[m + n + A_idx.index(j)] = Fraction(1)
        if j in B_idx:
            row[m + n + len(A_idx) + B_idx.index(j)] = Fraction(-1)
        A_eq.append(row)
        b_eq.append(Fraction(int(j == bio)))
    row = [Fraction(0)] * N  # strong duality: v_bio = ub^T alpha - lb^T beta
    row[bio] = Fraction(1)
    for k, j in enumerate(A_idx):
        row[m + n + k] = -frac(ub[j])
    for k, j in enumerate(B_idx):
        row[m + n + len(A_idx) + k] = frac(lb[j])
    A_eq.append(row)
    b_eq.append(Fraction(0))
    lo = list(lb) + [None] * n + [0] * (len(A_idx) + len(B_idx))
    hi = list(ub) + [None] * (N - m)
    if mu_min is not None:
        lo[bio] = mu_min if lo[bio] is None else max(frac(lo[bio]), frac(mu_min))
    c = [0] * N
    c[prod] = 1
    return solve_lp(c, A_eq=A_eq, b_eq=b_eq, lb=lo, ub=hi, maximize=True)


def optknock(S: Sequence[Sequence], lb: Sequence, ub: Sequence, bio: int,
             prod: int, K: int, candidates: Sequence[int], mu_min=0):
    """Best knockout set of size at most K for the product, by enumeration.

    Returns (D, v) with the largest v_prod; among equal products the first
    set in the order of size, then lexicographic order, wins. Returns None
    if no set gives a feasible LP.
    """
    m = len(lb)
    best: Optional[Tuple[Tuple[int, ...], List[Fraction]]] = None  # @line L1
    for k in range(K + 1):
        for D in combinations(candidates, k):  # @line L2
            lbD, ubD = knockout(lb, ub, D)  # @line L3
            res = single_level_lp(S, lbD, ubD, bio, prod, mu_min)  # @line L4
            if res.status != "optimal":  # @line L5
                continue
            v = res.x[:m]
            if best is None or v[prod] > best[1][prod]:  # @line L6
                best = (D, v)
    return best  # @line L7


# 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]
BIO_N, PROD_N = 5, 4
CAND_N = [1, 2, 3]
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_optknock.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/optknock/. The authors are listed in prov/K9KY6N.jsonl.
"""Tests of optknock().

The reference is the bilevel program solved in two steps for every knockout
set D: first the inner FBA optimum z(D) = max v_bio, then the largest v_prod
over the inner optimal face (v_bio = z(D)). This uses no duality, so it
checks the single-level LP of optknock.py. Strong duality on each inner LP
is checked against an explicit dual LP, and the inner optimum against the
vertices of the flux polytope.
"""

import random
from fractions import Fraction as F
from itertools import combinations

from optknock import (BIO_N, CAND_N, LB_N, PROD_N, S_N, UB_N, knockout,
                      optknock, single_level_lp)
from sy3lp import polytope_vertices, solve_lp


def inner_fba(S, lb, ub, bio):
    c = [0] * len(lb)
    c[bio] = 1
    return solve_lp(c, A_eq=S, b_eq=[0] * len(S), lb=lb, ub=ub,
                    maximize=True)


def two_step(S, lb, ub, bio, prod, mu_min, pessimistic=False):
    """The bilevel value for fixed bounds, without duality."""
    res = inner_fba(S, lb, ub, bio)
    if res.status != "optimal" or res.value < mu_min:
        return None
    lo, hi = list(lb), list(ub)
    lo[bio] = hi[bio] = res.value
    c = [0] * len(lb)
    c[prod] = 1
    out = solve_lp(c, A_eq=S, b_eq=[0] * len(S), lb=lo, ub=hi,
                   maximize=not pessimistic)
    return out.value


def brute(S, lb, ub, bio, prod, K, cand, mu_min=0):
    best = None
    for k in range(K + 1):
        for D in combinations(cand, k):
            lbD, ubD = knockout(lb, ub, D)
            val = two_step(S, lbD, ubD, bio, prod, mu_min)
            if val is not None and (best is None or val > best):
                best = val
    return best


def test_toy_network():
    assert optknock(S_N, LB_N, UB_N, BIO_N, PROD_N, 0, CAND_N)[1][PROD_N] == 0
    D, v = optknock(S_N, LB_N, UB_N, BIO_N, PROD_N, 1, CAND_N)
    assert v[PROD_N] == 0
    D, v = optknock(S_N, LB_N, UB_N, BIO_N, PROD_N, 2, CAND_N)
    assert D == (1, 2)
    assert v == [10, 0, 0, 5, 5, 5]


def test_growth_floor():
    # With mu_min = 6 the double knockout (growth 5) is not allowed.
    D, v = optknock(S_N, LB_N, UB_N, BIO_N, PROD_N, 2, CAND_N, mu_min=6)
    assert v[PROD_N] == 0 and v[BIO_N] == F(20, 3)
    assert optknock(S_N, LB_N, UB_N, BIO_N, PROD_N, 2, CAND_N, mu_min=7) is None


def test_optimistic_tie():
    # One respiration route A -> E. The growth optimum 5 does not fix the
    # split between respiration and fermentation, so the product at the
    # growth optimum is anything in [0, 5]. OptKnock reports the best case.
    S = [[1, -1, -1, 0, -1], [0, 1, 1, 0, -1], [0, 0, 1, -1, 0]]
    lb = [0] * 5
    ub = [10, None, None, None, None]
    D, v = optknock(S, lb, ub, 4, 3, 0, [1, 2])
    assert v[3] == 5 and v[4] == 5
    assert two_step(S, lb, ub, 4, 3, 0, pessimistic=True) == 0


def dual_value(S, lb, ub, bio):
    n, m = len(S), len(lb)
    A_idx = [j for j in range(m) if ub[j] is not None]
    B_idx = [j for j in range(m) if lb[j] is not None]
    cost = [0] * n + [ub[j] for j in A_idx] + [-lb[j] for j in B_idx]
    A = []
    for j in range(m):
        row = [S[i][j] for i in range(n)]
        row += [int(k == j) for k in A_idx] + [-int(k == j) for k in B_idx]
        A.append(row)
    b = [int(j == bio) for j in range(m)]
    lo = [None] * n + [0] * (len(A_idx) + len(B_idx))
    return solve_lp(cost, A_eq=A, b_eq=b, lb=lo)


def random_case(rng):
    n, m = rng.randint(1, 3), rng.randint(4, 6)
    S = [[rng.randint(-2, 2) for _ in range(m)] for _ in range(n)]
    lb = [rng.choice([0, 0, -1]) for _ in range(m)]
    ub = [rng.randint(1, 3) for _ in range(m)]
    bio, prod = rng.sample(range(m), 2)
    return S, lb, ub, bio, prod


def test_strong_duality_and_vertices():
    rng = random.Random(21)
    for _ in range(25):
        S, lb, ub, bio, prod = random_case(rng)
        for D in [(), (rng.randrange(len(lb)),)]:
            lbD, ubD = knockout(lb, ub, D)
            primal = inner_fba(S, lbD, ubD, bio)
            dual = dual_value(S, lbD, ubD, bio)
            assert primal.status == dual.status == "optimal"
            assert primal.value == dual.value
            verts = polytope_vertices(S, [0] * len(S), lbD, ubD)
            assert primal.value == max(v[bio] for v in verts)


def test_single_level_matches_two_step():
    rng = random.Random(22)
    for _ in range(25):
        S, lb, ub, bio, prod = random_case(rng)
        res = single_level_lp(S, lb, ub, bio, prod)
        ref = two_step(S, lb, ub, bio, prod, 0)
        assert res.status == "optimal" and res.x[prod] == ref


def test_against_enumeration():
    rng = random.Random(23)
    for _ in range(8):
        S, lb, ub, bio, prod = random_case(rng)
        cand = [j for j in range(len(lb)) if j not in (bio, prod)]
        for K in (1, 2):
            got = optknock(S, lb, ub, bio, prod, K, cand)
            assert got[1][prod] == brute(S, lb, ub, bio, prod, K, cand)

History

Burgard, Pharkya and Maranas published OptKnock in 2003. They wrote the inner FBA problem through its dual and a strong duality constraint, which turns the bilevel program into one MILP, and they applied it to the production of chemicals such as succinate and lactate in Escherichia coli. Later work from the same group extended the approach with reaction additions and regulation (OptStrain, OptReg), and Tepper and Shlomi (2010) gave the robust max-min version.

References

  1. Anthony P. Burgard, Priti Pharkya and Costas D. Maranas, OptKnock, a bilevel programming framework for identifying gene knockout strategies for microbial strain optimization, Biotechnology and Bioengineering 84(6), 2003, 647-657, the bilevel formulation, its reduction to a MILP through the dual of the inner LP, and the E. coli case studies
  2. Naama Tepper and Tomer Shlomi, Predicting metabolic engineering knockout strategies for chemical production, accounting for competing pathways, Bioinformatics 26(4), 2010, 536-543, RobustKnock, the max-min version that guarantees the product over all inner optima
  3. Jeffrey D. Orth, Ines Thiele and Bernhard O. Palsson, What is flux balance analysis?, Nature Biotechnology 28(3), 2010, 245-248, the inner FBA problem

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