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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 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 stoichiometric matrix ; flux bounds ; the index of the biomass reaction and of the product secretion; a set of candidate reactions that may be deleted; a limit ; and optionally a growth floor .
Output. A set with that solves the bilevel program
with for , together with the flux vector . 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 , the inner LP has the dual
with free , one for each finite upper bound and one for each finite lower bound. By weak duality every dual feasible point bounds from above. So is an optimum of the inner LP exactly when is primal feasible and some dual feasible point has . Putting these rows together gives one LP in for each . Burgard and co-authors add binary variables for the deletions, which makes the products 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 instead of using binaries.
OPTKNOCK(S, lb, ub, b, p, K, C, μ_min)- 1
best ← none - 2
for each D ⊆ C with |D| ≤ K, by size: - 3
(lb_D, ub_D) ← lb, ub with lb_j = ub_j = 0 for j in D - 4
solve 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 β - 5
if the LP is infeasible then continue - 6
if best is none or v_p > the product of best then best ← (D, v) - 7
return 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 .
Example
Take network N of the FBA page: uptake EX_A of a substrate (at most 10), two respiration reactions RESP1 and RESP2 (), fermentation FERM (), secretion EX_P of the product , and growth BIO (). The candidates are RESP1, RESP2 and FERM, and the product is the flux of EX_P.
- . The wild type grows at by respiration only, and every optimum has zero fermentation, so the product is 0.
- . Deleting one respiration reaction leaves the other one, and growth stays at with no product. Deleting FERM removes the product route. So the best product is still 0.
- . Deleting RESP1 and RESP2 leaves fermentation as the only source of . The mutant grows at 5, and its only optimal state is : it must secrete 5 units of . Growth and production are now coupled. OptKnock returns .
- Growth floor. With , the coupled design grows too slowly, and the best design keeps respiration, with product 0 and growth . With , above the wild-type optimum, no design is feasible.
Optimistic and guaranteed values. Change the network so that it has one respiration reaction and the fermentation , with the same yield of . 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 , weak duality says that for every primal feasible and dual feasible . So a feasible point of the LP of line L4 has a that is optimal for the inner problem. Conversely, if is optimal for the inner problem, strong duality gives a dual solution with the same value, so extends to a feasible point of the LP. The LP therefore maximizes over exactly the inner optima with , which is the optimistic bilevel value for . 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 matrix , bounds (entries may be infinite), a biomass index , a product index , a growth floor , a candidate list and a limit . For a knockout set let be the bounds with for , and let
be the inner FBA problem. Let be the set of optimal solutions of (IN), empty if (IN) is infeasible or unbounded. The optimistic OptKnock value of is
with if this set is empty. OptKnock asks for with that maximizes . We assume that is bounded above on for each ; this holds, for example, when the bounds make the flux polyhedron bounded. (If it fails for some , solve_lp reports "unbounded" for that and the code skips it.)
For fixed bounds (we drop the index ), let and . The dual of the inner LP is
with free, present only for and only for . single_level_lp builds the LP
Lemma 1 (weak duality). For every feasible for the inner LP and every feasible for (DU), .
Proof. . The first term is 0. For , and , so . For , and , so .
Lemma 2 (the projection of (SL)). A vector is the part of a feasible point of (SL) if and only if and , where is the set of optimal solutions of the inner LP.
Proof. Let be feasible for (SL). For any inner feasible , Lemma 1 gives . So is optimal, and is a row of (SL). Conversely, let with . The inner LP has a finite optimum, so by the strong duality theorem of linear programming, (DU) has an optimal solution with the same value . (The inner LP is in the form , and (DU) is its dual: for the equations, for the rows , and for the rows . A free variable gives the equation .) So is feasible for (SL).
Lemma 3 (the value for one set). For each , single_level_lp on the bounds returns "optimal" with and some when , and "infeasible" when .
Proof. By Lemma 2 the set of parts of the feasible points of (SL) is , and the objective of (SL) is . If this set is empty, (SL) is infeasible, and . Otherwise the maximum of over it is , finite by the assumption, and attained, since 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 in (SL) to , which is the same as the two rows and .
Theorem. optknock returns None if for every with . Otherwise it returns with , , , and .
Proof. Lines L2 and L3 visit every with exactly once, by size and then in the order of combinations. For each, line L4 computes and an optimal by Lemma 3, and line L5 skips the sets with . Line L6 keeps a set with the largest seen so far and replaces it only on a strict increase, so at line L7 it holds a maximizer of , the first one in the visiting order. If no set passes line L5, best stays None.
Remark (the optimistic value). For a fixed , the inner LP may have many optimal with different . (SL) picks the one with the largest product, so is the best case for the engineer. The worst case 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 where the two values are 5 and 0.
Remark (the MILP). Burgard, Pharkya and Maranas write the same problem with binary variables ( if ), the bounds , and the dual variables of the bounds switched off by big constants when . For each fixed , that MILP is the LP (SL) for the corresponding , 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 for candidates, and each needs one LP with or fewer variables and equality rows. So the time is for an LP time . This is exact, and it is practical only for small or few candidates.
- The MILP. The MILP of Burgard and co-authors has 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 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 much smaller. This is the usual preprocessing step.
- Space. for one LP tableau.
Properties
- Exact for its model. For each 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 never gives a smaller optimum, since every set allowed for is allowed for .
Variants and improvements
- RobustKnock. Tepper and Shlomi (2010) maximize the guaranteed product, the minimum of 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 , 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.
# 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
- 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
- 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
- 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.
| 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 K9KY6N Edit this page History Report an error Markdown