Algorithmadvanced
Elementary flux mode enumeration
Also called double description method for elementary modes.
List all elementary flux modes of a network by the double description method, as the extreme rays of the flux cone after each reversible reaction is split.
- Time
- O(m^2 d^2 R^2) worstO(m d^2 R^2) per_step
- Space
- O(m R) extra
- Where
- R = the largest number of rays kept after a step; d = the dimension of the kernel of the split matrix; m = the number of reactions after splitting
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Stefan Schuster, Claus Hilgetag, 1994
Elementary flux mode enumeration lists every elementary flux mode of a metabolic network: every minimal set of reactions that can carry a steady flux in the allowed directions. The standard method is the double description method, applied to the flux cone. First each reversible reaction is split into a forward and a backward irreversible copy, so that the modes become the extreme rays of a pointed cone. The method starts from a kernel basis of the stoichiometric matrix and adds the sign constraints one by one. At each step it keeps the rays that satisfy the new constraint and joins each adjacent pair of rays with opposite signs into a new ray. The output can be exponential in the size of the network, and counting the modes is #P-complete, so no method is fast on all networks. On networks of moderate size the method is practical, and it is the core of the standard tools.
In plain words
A metabolic network can usually run in many ways. Some of these ways are as small as possible: if you remove any one reaction from them, they stop working. These smallest routes are called elementary flux modes. Every way the network can run is a mix of them, so a list of all of them describes the whole network.
The method builds the list step by step. It starts with a few simple routes that balance every metabolite but may run some reactions the wrong way. Then it fixes one reaction at a time. Routes that run that reaction the right way are kept. Pairs of routes that run it in opposite directions are added together so that the reaction cancels, but only for pairs that are close neighbours. At the end, every route left is a correct smallest route, and none is missing.
The problem
Input. An stoichiometric matrix with rational entries and the set of reversible reactions.
Output. All elementary flux modes of the flux cone , that is, the non-zero vectors of whose support is minimal. Each mode is given once, as the vector of coprime integers in its ray. A mode made only of reversible reactions and its negative are two different modes.
The algorithm
EFM-ENUMERATION(S, rev)- 1
S' ← S with a column -S_j added for each reversible j; record which column came from which reaction - 2
compute the reduced row echelon form of S', with pivot columns Π and free columns F, and the kernel basis that is the identity on F; let K be the matrix of this basis and d = |F|- 3
rays ← the d basis vectors; done ← F - 4
for each pivot column p in Π: - 5
split rays into pos (x_p > 0), zero (x_p = 0) and neg (x_p < 0) - 6
new ← empty list - 7
for each x in pos and each y in neg: - 8
if the rows K_i with i in done, x_i = 0 and y_i = 0 have rank d - 2: append x_p y - y_p x to new- 9
rays ← pos + zero + new; add p to done - 10
drop the rays whose support is the two copies of one reaction, and map each other ray back to the original reactions - 11
return the modes, each scaled to coprime integers, sorted
Every stored vector lies in the kernel of , and its coordinate is the value of the constraint , so the zero set of a ray is its set of tight constraints. In the kernel basis of line L2 the free coordinates are the identity, so the starting cone, the part of the kernel with , is a simplicial cone whose extreme rays are the basis vectors. The rank test of line L8 is the adjacency test of the double description method. The code first skips pairs with fewer than common zeros, which cannot pass the test. The new ray is a positive combination of and (since ), and its coordinate is zero. The code works with exact fractions.
Example
Take network E of the definition page, with metabolites , , and reactions R1 (), R2 (), R3 (, reversible), R4 (), R5 () and R6 (). Line L1 adds the column R3b, the backward copy of R3, so has seven columns in the order R1, ..., R6, R3b. The pivot columns are R1, R2, R3 and the free columns are R4, R5, R6, R3b, so . The kernel basis, written as , is:
| ray | R1 | R2 | R3 | R4 | R5 | R6 | R3b |
|---|---|---|---|---|---|---|---|
| 0 | 1 | -1 | 1 | 0 | 0 | 0 | |
| 1 | 0 | 1 | 0 | 1 | 0 | 0 | |
| 1 | 1 | 0 | 0 | 0 | 1 | 0 | |
| 0 | 0 | 1 | 0 | 0 | 0 | 1 |
The constraints for R1 and R2 change nothing, because no ray is negative there. For R3, is negative, and are positive, and is zero. The pair has the common zeros R6 and R3b among the processed constraints, and these two rows of have rank , so the pair is adjacent. It gives , the route R1, R2, R4, R5. The pair has the common zeros R1, R5, R6, also of rank 2, and gives , the cycle R2, R4, R3b. The list now has five rays. Line L10 drops , which runs R3 forward and backward, and maps R3b back to R3 with a minus sign. The result is the four modes of the definition page: , , and the cycle .
On network N of the FBA page the code finds the three modes for growth by RESP1, by RESP2 and by fermentation. On a chain of diamonds, with reactions, it finds modes. The tests check these cases, a cycle of three reversible reactions (two modes, one in each direction), and 60 random networks against a brute force search over all supports.
Correctness
The proof has three parts. Splitting is a bijection between the modes of the original network and the modes of the split network that are not two-cycles. In the split network every reaction is irreversible, so the cone is pointed and its extreme rays are exactly its modes, by the rank test for modes. The double description step is correct: when a constraint is added to a pointed cone, the extreme rays of the new cone are the old extreme rays with , together with one new ray for each adjacent pair with opposite signs, and no ray appears twice. Adjacency means that the common tight constraints have rank , so the two rays span a two-dimensional face. By induction over the pivots, the final list holds each extreme ray of the split cone once. Both are theorems, and the full proof is below.
Proof: The nullspace double description method lists every elementary flux mode exactly oncefull
Fix an matrix and a set of reversible reactions. The flux cone is , and the elementary flux modes (EFMs) are its non-zero vectors of minimal support, counted up to a positive factor (see the definition page). We show that efm_enumeration returns each EFM exactly once, as a vector of coprime integers.
Throughout, a ray is a non-zero vector up to a positive factor, and for a pointed polyhedral cone with and a vector , the tight set is , where is row of . We write for the rows of in .
Step 1: splitting
Line L1 builds , with the columns of followed by for each reversible , so that column of is with . Let and . A two-cycle is a vector of whose support is the two copies of one reversible reaction. For an EFM of , let put on the forward copy of and on the backward copy.
Lemma 1 (the support rank test). Let be the support of a non-zero . Then is an EFM of if and only if . The same holds for and .
Proof. If , take independent of , with the sign chosen so that some has . Let . Then (zero outside ) has , is not zero because is independent of , has for some , and has the sign of or 0 on every other . So and , and is not an EFM. Conversely, if and is non-zero with , then , so with , and then , a contradiction. The argument for is the same with , since is the flux cone of with all reactions irreversible.
Lemma 2 (the splitting correspondence). maps the EFMs of to the EFMs of that are not two-cycles, and maps these back, with and .
Proof. Let be an EFM of . Then , , and never uses both copies of a reaction. Its support columns in are the columns for , so , and is an EFM of by Lemma 1. It is not a two-cycle, since it uses one copy per reaction. Clearly .
Now let be an EFM of that is not a two-cycle. If had both copies of some reversible in its support, the two-cycle on these copies would be a vector of with support inside , so by minimality would be these two copies, and would be the two-cycle. So uses at most one copy of each reaction. Then has , the sign of each irreversible flux is that of (non-negative), and the support columns of in are, up to sign, the support columns of in . By Lemma 1 for and then for , is an EFM of , and .
So it suffices to list the EFMs of , drop the two-cycles and apply , which is what line L10 does.
Step 2: the cone in kernel coordinates
Let be the number of columns of . Line L2 computes the reduced row echelon form of with pivot columns and free columns , , and the kernel basis whose vector is 1 at the -th free column and 0 at the other free columns. Let be the matrix with these vectors as columns. Then is a bijection from onto , and the rows of in form the identity matrix. So
and is pointed, since its constraints contain . The coordinate is 0 exactly when constraint is tight. The code keeps every ray as the vector , so the tight set of a ray is its zero set, and all operations below are linear, so they commute with .
Lemma 3 (extreme rays by rank). Let be pointed, with . A non-zero spans an extreme ray of if and only if . A ray is extreme in if and only if its support is minimal, so the extreme rays of are its EFMs.
Proof. The set is the smallest face of that contains , and is in its relative interior. Its linear span is , because near every vector of satisfies the other constraints strictly. So the face is the ray of if and only if has dimension 1, that is, rank . For , with , the tight set of is the complement of its support , and . So is extreme if and only if , which is the EFM test of Lemma 1.
Call two extreme rays of that are not multiples of each other adjacent if . This is the test of line L8, where the rows are the rows of for the processed constraints on which both rays are zero.
Lemma 4 (the double description step). Let be pointed with , let hold one vector for each extreme ray of , and let be a row vector. Split into , , by the sign of . Then the extreme rays of are, each exactly once,
Proof. is pointed and its matrix has rank . Write for tight sets in .
(a) Each is in , and , so . All these rows vanish on , so the rank is at most . By Lemma 3, is extreme in .
(b) For adjacent and , let with and . Then , , and since are independent. For a row of , is a sum of two non-negative terms, so it is 0 if and only if . So . The kernel of has dimension 2 and contains and , so it is their span, and shows that is not a combination of these rows. So , and is extreme in by Lemma 3.
(c) Let be extreme in . If , then , so is extreme in by Lemma 3, and . If and is extreme in , then . Otherwise , and : it is at least because adding the one row gives rank , and at most because is not extreme in . The face of then has a two-dimensional span and is pointed, so it is the cone over two extreme rays of , which are extreme rays of (a face of a face is a face). Their common tight set contains , so its rank is at least , and at most because both lie in its kernel; so they are adjacent. As is in the relative interior of , with . From , either , but then vanishes on the span of , so is a combination of the rows and , a contradiction; or one of is positive and the other negative, say . In the plane spanned by , the vectors of with form one ray, which contains both and . So is in the third set.
(d) No ray appears twice. The rays of are distinct extreme rays of , and the new rays are not extreme in (each is a positive combination of two independent rays). Two different adjacent pairs span two different two-dimensional faces of , and each new ray lies in the relative interior of its face, so different pairs give different rays.
Step 3: the loop
Lemma 5 (the invariant). Let and let be plus the first pivot columns processed by line L4. After rounds of the loop, the list rays holds exactly one vector for each extreme ray of .
Proof. By induction on . For , , the orthant, whose extreme rays are the unit vectors , and is the kernel basis vector of line L3. Each is pointed and its matrix has rank , because it contains the identity rows of . For the step from to with pivot , the new constraint is , and for the stored vector . Line L5 splits the rays by the sign of . Lines L7 and L8 test each pair of a positive and a negative ray for adjacency in : the rows for with and are , and the code compares their rank with . (The test that skips pairs with fewer than common zeros only saves time, since fewer rows cannot have rank .) For an adjacent pair, line L7 forms with , which is the vector of Lemma 4. Line L9 keeps and the new vectors. By Lemma 4 this is exactly one vector for each extreme ray of .
Theorem. efm_enumeration returns the sorted list of the EFMs of , each exactly once, as the primitive integer vector of its ray.
Proof. If , then , so , has no EFMs, and the code returns the empty list. Otherwise, after the last pivot, is all coordinates, so and . By Lemma 5 the list holds one vector for each extreme ray of , and by Lemma 3 these are the EFMs of . Line L10 drops the two-cycles and maps the others by ; by Lemma 2 this gives each EFM of exactly once, up to a positive factor. The function primitive divides by the positive gcd after clearing denominators, so it keeps the sign and maps each ray to one integer vector, and the set removes nothing that is not a repeat.
Remark (signs and reversible modes). A mode whose support has only reversible reactions gives two EFMs, and , which are different rays of . They come from two different extreme rays of , one on the forward copies and one on the backward copies, so both are returned.
Complexity
- Output size. The number of modes can be exponential in the size of the network: the chain of diamonds has reactions and modes. So no algorithm lists the modes in time polynomial in the input alone. This is a theorem.
- Counting. Counting the modes is #P-complete (Acuña and co-authors 2009, Section 3.2), by a reduction from counting perfect matchings of a bipartite graph. So even the number of modes is hard to compute. This is a theorem.
- Polynomial delay. If every reaction is reversible, the supports of the modes are the circuits of a linear matroid, and they can be listed with polynomial delay. Acuña and co-authors (2009) note that the question is open for networks with irreversible reactions. This is a theorem for the reversible case.
- Cost of this method. Each of the at most steps tests at most pairs, and each rank test is a Gaussian elimination on at most rows with columns, which costs operations. So the time is arithmetic operations, where is the largest list of rays after a step, and the space is . This is a theorem.
- Intermediate lists. is at least the number of modes and can be much larger, because the cones of the middle steps can have more extreme rays than the final cone. How large it gets depends on the order of the pivots, and Fukuda and Prodon (1996) discuss orders for the double description method in general. This is a heuristic: no order is known to be good on all inputs.
- Exact arithmetic. With fractions, the entries can grow during the run. Scaling each new ray to coprime integers keeps them small in practice, which is a heuristic.
Properties
- Exact and complete. With exact arithmetic the method returns every mode once and nothing else.
- Not output sensitive. The work depends on the intermediate lists, not only on the output.
- Deterministic. The set of modes does not depend on the order of the pivots, though the work does.
- Generates the cone. The modes generate the flux cone by non-negative combinations with matching signs. The tests check that a random steady-state vector is a non-negative combination of the modes.
- Splitting doubles some work. Each reversible reaction adds one column and one two-cycle to the split cone, and the two-cycle is removed at the end.
Variants and improvements
- The original tableau method. Schuster and Hilgetag (1994) started from a tableau of the transposed stoichiometric matrix with an identity block and cancelled one metabolite at a time. It is also a double description method, with a different start.
- The nullspace approach. Wagner (2004) started from a kernel basis, as this page does, so that only the sign constraints of reactions remain. The number of steps is then the rank of the matrix, which is at most the number of metabolites.
- Combinatorial adjacency. Instead of the rank test, two rays are adjacent if no third ray is zero on all their common zeros. This test needs only the zero sets, and it can be stored as bit vectors. Gagneur and Klamt (2004) compare the two tests and describe the binary approach, which stores the zero sets as bit vectors to save memory.
- Reversible reactions without splitting. Many tools treat reversible reactions directly: they process the irreversible constraints and handle the lineality space of the cone separately. This avoids the extra columns.
- Partial lists. When the full list is too large, a mixed-integer program can find modes one at a time, for example the shortest modes or the modes that use a given reaction. Finding one mode is polynomial, but finding a shortest one is NP-hard (Acuña and co-authors 2009).
- Related enumerations. Vertex enumeration of polytopes and Fourier-Motzkin elimination use the same pairing step.
When to use it
Use it to list all routes of a small or medium network, such as central carbon metabolism, to find the routes with the best yield, the reactions that every route needs, or the minimal cut sets. For a genome-scale model the list is usually far too large, and flux balance analysis or flux variability analysis answer most questions with linear programs. If you need only some modes, compute them one at a time instead.
Pitfalls
- Forgetting the two-cycles. After splitting, each reversible reaction gives a two-cycle that is an extreme ray of the split cone but not a mode. It must be removed.
- Exchange reactions. Whether exchange reactions are in changes the answer. Without them, only internal cycles are modes.
- Floating point. The rank test with a tolerance can give wrong adjacency on large networks. Exact or integer arithmetic avoids this at a cost.
- Memory. The intermediate lists, not the output, usually decide whether the run finishes.
- Reading modes as fluxes. A mode is a direction, not a flux that the cell uses. Real flux vectors are combinations of many modes.
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/elementary-flux-mode-enumeration/. The authors are listed in prov/E5TT1K.jsonl.
"""Elementary flux modes by the nullspace form of the double description method.
Input: the n x m stoichiometric matrix S and a list rev of m booleans
(rev[j] is True if reaction j is reversible). Output: every elementary flux
mode, as a tuple of coprime integers, so each mode appears once up to a
positive factor. A mode e and its negative -e are two modes when both are
sign-feasible (a cycle of reversible reactions).
Steps:
1. Split each reversible reaction j into a forward copy (column S_j) and a
backward copy (column -S_j). Every reaction of the new matrix S' is
irreversible, so the modes of S' are the extreme rays of the pointed cone
C = {x : S' x = 0, x >= 0}.
2. Take a kernel basis K of S' with an identity block on the free
coordinates F. The cone {x in ker S' : x_F >= 0} has the columns of K as
its extreme rays.
3. Add the constraints x_p >= 0 for the other coordinates p, one at a time,
by the double description step: keep the rays with x_p >= 0, and combine
each adjacent pair of a ray with x_p > 0 and a ray with x_p < 0 into a
ray with x_p = 0. Two rays are adjacent if the matrix of the processed
constraints that both satisfy with equality has rank d - 2, where
d = dim ker S'.
4. Drop the two-cycles (forward and backward copy of one reaction) and map
each ray back to the original reactions.
"""
from __future__ import annotations
from fractions import Fraction
from math import gcd
from typing import List, Sequence, Tuple
from sy3lp import nullspace, rank, rref
def primitive(x: Sequence[Fraction]) -> Tuple[int, ...]:
"""Scale a rational vector to coprime integers, keeping the sign."""
den = 1
for v in x:
den = den * v.denominator // gcd(den, v.denominator)
ints = [int(v * den) for v in x]
g = 0
for v in ints:
g = gcd(g, abs(v))
return tuple(v // g for v in ints) if g else tuple(ints)
def split_reversible(S, rev):
"""Return S' and back, where back[k] = (j, +1 or -1) for column k."""
cols = list(range(len(rev)))
back = [(j, 1) for j in cols]
for j in cols:
if rev[j]:
back.append((j, -1))
Sp = [[row[j] * s for j, s in back] for row in S]
return Sp, back
def efm_enumeration(S: Sequence[Sequence[int]], rev: Sequence[bool]):
"""All elementary flux modes of (S, rev), sorted."""
m = len(rev)
Sp, back = split_reversible(S, rev) # @line L1
mp = len(back)
if Sp and any(any(x != 0 for x in row) for row in Sp):
_, piv = rref(Sp)
else:
piv = []
free = [j for j in range(mp) if j not in piv]
basis = nullspace(Sp, mp) if Sp else nullspace([], mp) # @line L2
d = len(basis)
if d == 0:
return []
# The kernel matrix K (mp x d): row j gives x_j as a function of t.
K = [[basis[b][j] for b in range(d)] for j in range(mp)]
rays = [list(v) for v in basis] # @line L3
done = list(free)
for p in piv: # @line L4
pos = [r for r in rays if r[p] > 0] # @line L5
zero = [r for r in rays if r[p] == 0]
neg = [r for r in rays if r[p] < 0]
new = [] # @line L6
for a in pos: # @line L7
za = {i for i in done if a[i] == 0}
for b in neg:
common = [i for i in za if b[i] == 0]
if len(common) < d - 2:
continue
if rank([K[i] for i in common]) == d - 2: # @line L8
new.append([a[p] * y - b[p] * x for x, y in zip(a, b)])
rays = pos + zero + new # @line L9
done.append(p)
modes = set() # @line L10
for r in rays:
supp = [k for k in range(mp) if r[k] != 0]
if len(supp) == 2 and back[supp[0]][0] == back[supp[1]][0]:
continue # a two-cycle j forward + j backward
v = [Fraction(0)] * m
for k in supp:
j, s = back[k]
v[j] += s * r[k]
modes.add(primitive(v))
return sorted(modes) # @line L11
def brute_force_efms(S, rev):
"""EFMs by brute force over all supports.
A sign-feasible steady-state vector e is an EFM if and only if the
columns of S on supp(e) have a kernel of dimension 1. So for every
support Q: if ker S_Q has dimension 1 and its basis vector has full
support on Q, the vector or its negative (or both) is a mode when it is
non-negative on the irreversible reactions.
"""
from itertools import combinations
m = len(rev)
out = set()
for size in range(1, m + 1):
for Q in combinations(range(m), size):
SQ = [[row[j] for j in Q] for row in S]
B = nullspace(SQ, size) if S else nullspace([], size)
if len(B) != 1 or any(x == 0 for x in B[0]):
continue
for sign in (1, -1):
e = [sign * x for x in B[0]]
if all(rev[j] or x > 0 for j, x in zip(Q, e)):
v = [Fraction(0)] * m
for j, x in zip(Q, e):
v[j] = x
out.add(primitive(v))
return sorted(out)
# Network E of the page: R1 -> A, R2 A -> B, R3 A <-> C, R4 B -> C,
# R5 C ->, R6 B ->. Metabolites A, B, C.
S_E = [
[1, -1, -1, 0, 0, 0], # A
[0, 1, 0, -1, 0, -1], # B
[0, 0, 1, 1, -1, 0], # C
]
REV_E = [False, False, True, False, False, False]
def diamond_chain(k):
"""A chain of k diamonds: 2k + 2 irreversible reactions and 2^k EFMs.
Metabolites M_0, ..., M_k. Uptake -> M_0, two parallel reactions
M_{i-1} -> M_i for each i, and secretion M_k ->.
"""
n, m = k + 1, 2 * k + 2
S = [[0] * m for _ in range(n)]
S[0][0] = 1
for i in range(1, k + 1):
for c in (2 * i - 1, 2 * i):
S[i - 1][c] = -1
S[i][c] = 1
S[k][m - 1] = -1
return S, [False] * m
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_elementary_flux_mode_enumeration.py 89 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/elementary-flux-mode-enumeration/. The authors are listed in prov/E5TT1K.jsonl.
"""Tests of efm_enumeration() against brute force over all supports."""
import random
from fractions import Fraction as F
from elementary_flux_mode_enumeration import (REV_E, S_E, brute_force_efms,
diamond_chain, efm_enumeration,
primitive)
from sy3lp import solve_lp
S_N = [
[1, -1, -1, -1, 0, -1],
[0, 2, 2, 1, 0, -1],
[0, 0, 0, 1, -1, 0],
]
def is_steady(S, v):
return all(sum(a * b for a, b in zip(row, v)) == 0 for row in S)
def test_network_e():
modes = efm_enumeration(S_E, REV_E)
assert modes == sorted([
(1, 1, 0, 0, 0, 1), # R1 + R2 + R6
(1, 0, 1, 0, 1, 0), # R1 + R3 + R5
(1, 1, 0, 1, 1, 0), # R1 + R2 + R4 + R5
(0, 1, -1, 1, 0, 0), # the cycle R2 + R4 - R3
])
# R1 + R2 + R4 + R5 is the sum of two other modes, yet it is a mode.
assert tuple(a + b for a, b in zip((1, 0, 1, 0, 1, 0), (0, 1, -1, 1, 0, 0))) \
== (1, 1, 0, 1, 1, 0)
# The sum of the first two modes is steady but not elementary.
s = tuple(a + b for a, b in zip((1, 1, 0, 0, 0, 1), (1, 0, 1, 0, 1, 0)))
assert is_steady(S_E, s) and primitive([F(x) for x in s]) not in modes
def test_network_n():
modes = efm_enumeration(S_N, [False] * 6)
assert modes == [(2, 0, 0, 1, 1, 1), (3, 0, 1, 0, 0, 2), (3, 1, 0, 0, 0, 2)]
def test_diamond_chain_doubles():
for k in range(1, 6):
S, rev = diamond_chain(k)
assert len(efm_enumeration(S, rev)) == 2 ** k
def test_all_reversible_cycle_counts_both_directions():
# A <-> B <-> C <-> A: one cycle, in two directions.
S = [[-1, 0, 1], [1, -1, 0], [0, 1, -1]]
assert efm_enumeration(S, [True] * 3) == [(-1, -1, -1), (1, 1, 1)]
def random_network(rng):
n, m = rng.randint(1, 3), rng.randint(3, 7)
S = [[rng.choice([-1, -1, 0, 0, 0, 1, 1, 2]) for _ in range(m)]
for _ in range(n)]
rev = [rng.random() < 0.3 for _ in range(m)]
return S, rev
def test_random_against_brute_force():
rng = random.Random(31)
for _ in range(60):
S, rev = random_network(rng)
modes = efm_enumeration(S, rev)
assert modes == brute_force_efms(S, rev)
for e in modes:
assert is_steady(S, e)
assert all(rev[j] or x >= 0 for j, x in enumerate(e))
def test_modes_generate_the_cone():
# Every sign-feasible steady state is a non-negative combination of modes.
rng = random.Random(32)
for _ in range(20):
S, rev = random_network(rng)
modes = efm_enumeration(S, rev)
if not modes:
continue
m = len(rev)
weights = [rng.randint(0, 3) for _ in modes]
v = [sum(w * e[j] for w, e in zip(weights, modes)) for j in range(m)]
A = [[e[j] for e in modes] for j in range(m)]
res = solve_lp([0] * len(modes), A_eq=A, b_eq=v)
assert res.status == "optimal"
History
Schuster and Hilgetag (1994) defined elementary flux modes and gave the first algorithm, which combines pairs of rows of a tableau to cancel one coordinate at a time. Schuster, Fell and Dandekar (2000) made modes a general definition of a metabolic pathway and computed them for example networks. In 2004 Wagner started the iteration from a kernel basis, and Gagneur and Klamt showed that the known algorithms are forms of the double description method, which comes from the study of polyhedral cones in the 1950s. Acuña and co-authors (2009) proved that counting the modes is #P-complete.
References
- Stefan Schuster and Claus Hilgetag, On elementary flux modes in biochemical reaction systems at steady state, Journal of Biological Systems 2(2), 1994, 165-182, the definition of elementary flux modes and the first algorithm that combines pairs of vectors to cancel one coordinate at a time
- Stefan Schuster, David A. Fell and Thomas Dandekar, A general definition of metabolic pathways useful for systematic organization and analysis of complex metabolic networks, Nature Biotechnology 18(3), 2000, 326-332, the use of elementary modes as metabolic pathways, with the computation of modes for example networks
- Clemens Wagner, Nullspace approach to determine the elementary modes of chemical reaction systems, Journal of Physical Chemistry B 108(7), 2004, 2425-2431, the start of the iteration from a kernel basis of the stoichiometric matrix
- Julien Gagneur and Steffen Klamt, Computation of elementary modes, a unifying framework and the new binary approach, BMC Bioinformatics 5, 2004, 175, the description of the known algorithms as the double description method, the splitting of reversible reactions, the adjacency tests, and the binary approach
- Komei Fukuda and Alain Prodon, Double description method revisited, Combinatorics and Computer Science, Lecture Notes in Computer Science 1120, 1996, 91-111, the double description step, the adjacency test by tight constraints, and the effect of the order in which constraints are added
- Vicente Acuña, Flavio Chierichetti, Vincent Lacroix, Alberto Marchetti-Spaccamela, Marie-France Sagot and Leen Stougie, Modes and cuts in metabolic networks, complexity and algorithms, BioSystems 95(1), 2009, 51-60, Section 3.2 (counting elementary modes is
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 E5TT1K Edit this page History Report an error Markdown