Skip to main content

9  Extending constraint-based approaches

Flux balance analysis, as in Chapter 8, makes two strong assumptions: that the cell has had time to optimise its metabolism for growth, and that the environment does not change. In this chapter, we relax each of them. MoMA and ROOM predict how a mutant behaves if it changes as little as possible from the wild type after losing a gene, and dynamic FBA follows a culture as it uses up its nutrients and changes its own environment. We then design strains with OptKnock, bring gene expression data into a model with E-Flux, and enumerate the elementary flux modes of a small network.

The examples write the optimisation problems out explicitly, with the stoichiometric matrix \(\mathbf{S}\) and the bounds of the E. coli core model, and solve them with general-purpose solvers: linprog and quadprog in MATLAB (Optimization Toolbox), and SciPy’s linprog and the interior-point solver Clarabel in Python, with intlinprog and SciPy’s milp for ROOM. The COBRA Toolbox and COBRApy provide the same methods ready-made; writing them out once shows exactly what they compute.

9.1 Minimisation of Metabolic Adjustment (MoMA)

When a gene is deleted, FBA predicts the fastest growth the remaining network allows. Laboratory evolution experiments show that mutants often do reach this rate, but only after many generations. Right after the deletion, the cell’s regulation is still tuned to the wild type. Segrè, Vitkup and Church proposed that a fresh mutant instead keeps its fluxes as close as possible to those of the wild type (Segrè et al. 2002). If \(\mathbf{w}\) is the wild-type flux distribution, MoMA solves (book, Eq. 9.1)

\[ \min_{\mathbf{v}} \ \lVert \mathbf{v} - \mathbf{w} \rVert^2 \quad \text{subject to} \quad \mathbf{S}\mathbf{v} = \mathbf{0}, \quad \mathbf{lb} \le \mathbf{v} \le \mathbf{ub}, \]

with the bounds of the deleted reaction set to zero. Its objective is quadratic, so this is a quadratic programme (QP; book, Eqs. 9.2 and 9.3), and since the squared distance is strictly convex, its solution is unique. MoMA needs a reference \(\mathbf{w}\), but FBA has many optimal solutions (Chapter 8). We take the one of smallest Euclidean norm, which is also unique and is found by the same QP with \(\mathbf{w} = \mathbf{0}\) and growth held at its maximum. The code compares FBA and MoMA for each of the 74 internal reactions of the model, and then looks at the fluxes after deleting phosphofructokinase (PFK).

Needs the Optimization Toolbox.

%% Predicting the fluxes of a mutant: FBA and MoMA
% FBA assumes that a mutant, like the wild type, grows as fast as its
% network allows. MoMA (minimisation of metabolic adjustment) assumes that
% a freshly made mutant stays as close as possible to the wild-type flux
% distribution w: it minimises the distance ||v - w||^2, subject to the
% same constraints S v = 0 and lb <= v <= ub, with the deleted reaction
% fixed at zero. That is a quadratic programme (QP). We write both
% problems out with the stoichiometric matrix, solve them with linprog and
% quadprog, and compare FBA and MoMA for every deletion of an internal
% reaction of the E. coli core model.
% Requires: Optimization Toolbox (the COBRA Toolbox is not needed).

s = load(fullfile(sbp.data_dir(), 'e_coli_core.mat'));
model = s.e_coli_core;
S = model.S; lb = model.lb; ub = model.ub; ids = model.rxns;
n = numel(ids);
bio = find(strcmp(ids, 'Biomass_Ecoli_core'));

% Wild type. Many flux distributions achieve the maximum growth rate; as
% reference we take the one with the smallest Euclidean norm, which is
% unique.
mu_wt = fba(S, lb, ub, bio);
[l, u] = at_growth(mu_wt, lb, ub, bio);
w = nearest(S, zeros(n, 1), l, u);
fprintf('Wild-type growth rate %.4f /h\n', mu_wt);

%% Every deletion of an internal reaction
internal = ~startsWith(ids, {'EX_', 'Biomass'});
rxns = sort(ids(internal));
growth_fba = zeros(1, numel(rxns)); growth_moma = zeros(1, numel(rxns));
for k = 1:numel(rxns)
    j = strcmp(ids, rxns{k});
    lb_d = lb; ub_d = ub;
    lb_d(j) = 0; ub_d(j) = 0;
    mu = fba(S, lb_d, ub_d, bio);
    if isempty(mu)          % no flux distribution meets the constraints,
        continue            % e.g. the ATP maintenance demand: growth 0
    end
    growth_fba(k) = mu / mu_wt;
    if abs(w(j)) < 1e-9       % w already meets the new constraints, so
        v = w;                % it is its own nearest point
    else
        v = nearest(S, w, lb_d, ub_d);
    end
    growth_moma(k) = v(bio) / mu_wt;
end
fprintf(['%d deletions; MoMA predicts slower growth than FBA for %d ' ...
    'of them\n'], numel(rxns), nnz(growth_moma < growth_fba - 0.01));
for r = {'PGI', 'PFK', 'TPI', 'G6PDH2r', 'PYK', 'CS'}
    k = strcmp(rxns, r{1});
    fprintf('  %-8s FBA %.3f, MoMA %.3f of wild-type growth\n', r{1}, ...
        growth_fba(k), growth_moma(k));
end

%% Fluxes after deleting phosphofructokinase (PFK)
show = {'PGI', 'PFK', 'FBA', 'G6PDH2r', 'GND', 'TKT1', 'TALA', 'GAPD', 'PYK'};
[~, idx] = ismember(show, ids);
lb_d = lb; ub_d = ub;
lb_d(strcmp(ids, 'PFK')) = 0; ub_d(strcmp(ids, 'PFK')) = 0;
[l, u] = at_growth(fba(S, lb_d, ub_d, bio), lb_d, ub_d, bio);
v_fba = nearest(S, zeros(n, 1), l, u);
v_moma = nearest(S, w, lb_d, ub_d);
pfk.wild_type = w(idx)'; pfk.fba = v_fba(idx)'; pfk.moma = v_moma(idx)';

%% Plot
fig = figure('Position', [100 100 1000 420]);
subplot(1, 5, 1:2)
plot([0 1.05], [0 1.05], ':', 'Color', [0.6 0.6 0.6]);
hold on
scatter(growth_fba, growth_moma, 36, [0.000 0.447 0.698], 'filled', ...
    'MarkerFaceAlpha', 0.7);
axis padded
xlabel('FBA (fraction of wild type)');
ylabel('MoMA (fraction of wild type)');
title('Growth after 74 deletions');
subplot(1, 5, 3:5)
b = bar(categorical(show, show), [pfk.wild_type; pfk.fba; pfk.moma]', ...
    'EdgeColor', 'none');
b(1).FaceColor = [0.6 0.6 0.6];
b(2).FaceColor = [0.902 0.624 0.000];
b(3).FaceColor = [0.000 0.447 0.698];
set(gca, 'TickDir', 'out', 'XTickLabelRotation', 45);
ylabel('Flux (mmol/gDW/h)'); title('Fluxes after deleting PFK');
legend({'wild type', 'FBA', 'MoMA'}, 'Box', 'off');
sbp.save_figure(fig, mfilename('fullpath'), 'fig-moma');

results.growth_wild_type = mu_wt;
results.reactions = rxns';
results.growth_fba = growth_fba;
results.growth_moma = growth_moma;
results.pfk_reactions = show;
results.pfk_fluxes = pfk;
sbp.save_results(mfilename('fullpath'), results);

%% Local functions
function mu = fba(S, lb, ub, bio)
% Maximum growth rate, or [] if the constraints cannot be met.
c = zeros(size(lb)); c(bio) = -1;              % linprog minimises
opts = optimoptions('linprog', 'Display', 'none');
[~, f, exitflag] = linprog(c, [], [], S, zeros(size(S, 1), 1), lb, ub, ...
    opts);
mu = [];
if exitflag == 1
    mu = max(0, -f);
end
end

function v = nearest(S, target, lb, ub)
% The flux vector closest to target: minimise ||v - target||^2 / 2, that
% is v'v/2 - target'v, subject to S v = 0 and lb <= v <= ub. Some rows of
% S are linear combinations of others; dropping them, and using the
% active-set algorithm, makes quadprog exact and reliable here.
n = numel(lb);
S = full(S);
[~, R, order] = qr(S', 'vector');               % independent rows of S
independent = order(abs(diag(R)) > 1e-9 * abs(R(1, 1)));
S = S(sort(independent), :);
opts = optimoptions('quadprog', 'Algorithm', 'active-set', ...
    'Display', 'none');
x0 = min(max(target, lb), ub);                  % a starting point
[v, ~, exitflag, output] = quadprog(eye(n), -target, [], [], S, ...
    zeros(size(S, 1), 1), lb, ub, x0, opts);
assert(exitflag > 0, 'quadprog stopped (exit flag %d): %s', exitflag, ...
    output.message);
end

function [lb, ub] = at_growth(mu, lb, ub, bio)
% Bounds that hold growth at (just below) mu.
lb(bio) = mu * (1 - 1e-9);
ub(bio) = mu;
end

Needs COBRApy (to read the model) and Clarabel.

"""Predicting the fluxes of a mutant: FBA and MoMA.

FBA assumes that a mutant, like the wild type, grows as fast as its
network allows. MoMA (minimisation of metabolic adjustment) assumes that
a freshly made mutant stays as close as possible to the wild-type flux
distribution w: it minimises the distance ||v - w||^2, subject to the
same constraints S v = 0 and lb <= v <= ub, with the deleted reaction
fixed at zero. That is a quadratic programme (QP). We write both
problems out with the stoichiometric matrix, solve the linear programmes
with SciPy and the QPs with Clarabel, and compare FBA and MoMA for every
deletion of an internal reaction of the E. coli core model.
"""
import numpy as np
import clarabel
from scipy.optimize import linprog
from scipy import sparse
import matplotlib.pyplot as plt
import cobra
from cobra.util import create_stoichiometric_matrix
import sbp

model = cobra.io.read_sbml_model(str(sbp.DATA / "e_coli_core.xml"))
S = create_stoichiometric_matrix(model)
lb = np.array([r.lower_bound for r in model.reactions])
ub = np.array([r.upper_bound for r in model.reactions])
ids = [r.id for r in model.reactions]
bio = ids.index("Biomass_Ecoli_core")
n = len(ids)


def fba(lb, ub):
    """Maximum growth rate, or None if the constraints cannot be met."""
    c = np.zeros(n)
    c[bio] = -1                          # linprog minimises
    res = linprog(c, A_eq=S, b_eq=np.zeros(S.shape[0]),
                  bounds=np.c_[lb, ub], method="highs")
    return max(0.0, -res.fun) if res.status == 0 else None


def nearest(target, lb, ub):
    """The flux vector closest to target: minimise ||v - target||^2 / 2,
    that is v'v/2 - target'v, subject to S v = 0 and lb <= v <= ub.
    Clarabel takes constraints as A v + s = b, with s = 0 for equalities
    and s >= 0 for inequalities: here v <= ub and -v <= -lb."""
    m = S.shape[0]
    eye = sparse.identity(n, format="csc")
    A = sparse.vstack([sparse.csc_matrix(S), eye, -eye], format="csc")
    b = np.r_[np.zeros(m), ub, -lb]
    cones = [clarabel.ZeroConeT(m), clarabel.NonnegativeConeT(2 * n)]
    settings = clarabel.DefaultSettings()
    settings.verbose = False
    settings.tol_gap_abs = settings.tol_gap_rel = settings.tol_feas = 1e-10
    solution = clarabel.DefaultSolver(eye, -np.asarray(target, dtype=float),
                                      A, b, cones, settings).solve()
    assert str(solution.status) == "Solved"
    return np.array(solution.x)


def at_growth(mu, lb, ub):
    """Bounds that hold growth at (just below) mu."""
    lb, ub = lb.copy(), ub.copy()
    lb[bio], ub[bio] = mu * (1 - 1e-9), mu
    return lb, ub


# Wild type. Many flux distributions achieve the maximum growth rate;
# as reference we take the one with the smallest Euclidean norm, which
# is unique.
mu_wt = fba(lb, ub)
w = nearest(np.zeros(n), *at_growth(mu_wt, lb, ub))
print(f"Wild-type growth rate {mu_wt:.4f} /h")

# Every deletion of an internal reaction
rxns = sorted(r for r in ids if not r.startswith(("EX_", "Biomass")))
growth_fba, growth_moma = [], []
for r in rxns:
    lb_d, ub_d = lb.copy(), ub.copy()
    lb_d[ids.index(r)] = ub_d[ids.index(r)] = 0
    mu = fba(lb_d, ub_d)
    if mu is None:            # no flux distribution meets the constraints,
        growth_fba.append(0.0)    # e.g. the ATP maintenance demand
        growth_moma.append(0.0)
        continue
    growth_fba.append(mu / mu_wt)
    if abs(w[ids.index(r)]) < 1e-9:   # w already meets the new constraints,
        v = w                         # so it is its own nearest point
    else:
        v = nearest(w, lb_d, ub_d)
    growth_moma.append(v[bio] / mu_wt)
growth_fba, growth_moma = np.array(growth_fba), np.array(growth_moma)
lower = growth_moma < growth_fba - 0.01
print(f"{len(rxns)} deletions; MoMA predicts slower growth than FBA for "
      f"{lower.sum()} of them")
for r in ["PGI", "PFK", "TPI", "G6PDH2r", "PYK", "CS"]:
    i = rxns.index(r)
    print(f"  {r:8s} FBA {growth_fba[i]:.3f}, MoMA {growth_moma[i]:.3f} "
          f"of wild-type growth")

# Fluxes after deleting phosphofructokinase (PFK)
show = ["PGI", "PFK", "FBA", "G6PDH2r", "GND", "TKT1", "TALA", "GAPD", "PYK"]
lb_d, ub_d = lb.copy(), ub.copy()
lb_d[ids.index("PFK")] = ub_d[ids.index("PFK")] = 0
v_fba = nearest(np.zeros(n), *at_growth(fba(lb_d, ub_d), lb_d, ub_d))
v_moma = nearest(w, lb_d, ub_d)
pfk = {name: [v[ids.index(r)] for r in show]
       for name, v in [("wild_type", w), ("fba", v_fba), ("moma", v_moma)]}

# --- Plot
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4.2),
                               gridspec_kw={"width_ratios": [2, 3]})
ax1.plot([0, 1.05], [0, 1.05], ":", color="#999999")
ax1.plot(growth_fba, growth_moma, "o", color="#0072B2", alpha=0.7)
ax1.set_xlabel("FBA (fraction of wild type)")
ax1.set_ylabel("MoMA (fraction of wild type)")
ax1.set_title("Growth after 74 deletions")
x = np.arange(len(show))
for k, (name, colour) in enumerate([("wild_type", "#999999"),
                                    ("fba", "#E69F00"),
                                    ("moma", "#0072B2")]):
    ax2.bar(x + (k - 1) * 0.27, pfk[name], 0.27, color=colour,
            label={"wild_type": "wild type", "fba": "FBA",
                   "moma": "MoMA"}[name])
ax2.set_xticks(x, show, rotation=45)
ax2.axhline(0, color="black", lw=0.5)
ax2.set_ylabel("Flux (mmol/gDW/h)")
ax2.set_title("Fluxes after deleting PFK")
ax2.legend(frameon=False)
sbp.save_figure(fig, __file__, "fig-moma")

sbp.save_results(__file__, {
    "growth_wild_type": mu_wt, "reactions": rxns,
    "growth_fba": growth_fba, "growth_moma": growth_moma,
    "pfk_reactions": show, "pfk_fluxes": pfk,
})
sbp.show()

MoMA never predicts faster growth than FBA, since FBA gives the maximum; for 27 of the 74 deletions it predicts noticeably slower growth. The differences are largest in glycolysis. Without PFK, FBA predicts that the cell grows at 81% of the wild-type rate, by running phosphoglucose isomerase (PGI) backwards and sending more than five times the wild-type flux through the pentose phosphate pathway (G6PDH2r, GND). That is a drastic rerouting, which a cell could reach only after adapting. MoMA predicts a much smaller rearrangement, and growth at only 24% of the wild type. These are exactly the deletions, of PFK, FBA and TPI (the genes pfkAB, fba and tpiA), for which MoMA has been shown to correct predictions made by FBA (book, §9.1), and Segrè and colleagues found that MoMA also predicted the fluxes measured in a pyruvate kinase mutant better than FBA did (Segrè et al. 2002). Which of the two predictions applies depends on the history of the mutant: MoMA for a freshly made strain, FBA for one that has evolved.

9.1.1 Fitting experimentally measured fluxes

There is no code for this section; see the book.

9.2 Regulatory On-Off Minimisation (ROOM)

ROOM (Shlomi et al. 2005) counts changes instead of measuring distance. A flux has changed significantly if it leaves a band around its wild-type value, \([w - \delta|w| - \epsilon,\ w + \delta|w| + \epsilon]\), and ROOM minimises the number of such changes (book, Eq. 9.5). Each flux gets a binary variable \(y_i\), which is 1 if it changes, so this is a mixed-integer linear programme (MILP): intlinprog in MATLAB and SciPy’s milp in Python. Many flux distributions reach the fewest changes, so the code then reports the fastest growth among them. We use \(\delta = 0.03\) and \(\epsilon = 0.001\), the values used for flux predictions in the book, and the same wild-type reference as MoMA.

MILPs are much harder than LPs or QPs, and the solution time grows quickly with the number of binary variables. Two choices keep this example fast: we look at only five deletions, and we replace the bounds in Eq. 9.5, which act as “big-M” constants, by the tightest bounds the network allows, from FVA, in place of ±1000.

Needs the Optimization Toolbox (for linprog, quadprog and intlinprog).

%% Regulatory on-off minimisation (ROOM) for single deletions
% ROOM (book §9.2, Eq. 9.5) assumes that a mutant changes as few fluxes as
% possible, compared with the wild type w. A change is significant if the
% flux leaves the range [w_l, w_u], with w_l = w - delta|w| - epsilon and
% w_u = w + delta|w| + epsilon. A binary variable y_i is 1 if flux i changes
% significantly, and ROOM minimises sum(y): a mixed-integer linear
% programme (MILP). Many flux distributions reach that minimum, so we then
% report the fastest growth among them, which is unique. The wild type w is
% the flux distribution of smallest norm at optimal growth, as for MoMA.
% Binary variables make ROOM much slower than FBA or MoMA, so we look at
% five deletions in glycolysis and the pentose phosphate pathway,
% including pyruvate kinase (PYK), the example of the book. To keep the
% MILP well conditioned, the bounds lb and ub in Eq. 9.5 are the tightest
% the network allows, found by flux variability analysis (FVA), rather
% than the nominal +/-1000.
% Requires: Optimization Toolbox (the COBRA Toolbox is not needed).

s = load(fullfile(sbp.data_dir(), 'e_coli_core.mat'));
model = s.e_coli_core;
S = model.S; lb = model.lb; ub = model.ub; ids = model.rxns;
[m, n] = size(S);
bio = find(strcmp(ids, 'Biomass_Ecoli_core'));
delta = 0.03; epsilon = 0.001;        % as Shlomi et al. used for fluxes

% Wild type: optimal growth, smallest norm
mu_wt = fba(S, lb, ub, bio);
lb_wt = lb; ub_wt = ub;
lb_wt(bio) = mu_wt * (1 - 1e-9); ub_wt(bio) = mu_wt;
w = min_norm(S, lb_wt, ub_wt);
w(abs(w) < 1e-9) = 0;
fprintf('Wild-type growth %.4f /h; %d reactions carry flux\n', mu_wt, nnz(w));

% Tightest bounds the network allows (FVA, at any growth rate)
lo = zeros(n, 1); hi = zeros(n, 1);
opts = optimoptions('linprog', 'Display', 'none');
for j = 1:n
    c = zeros(n, 1); c(j) = 1;
    [~, lo(j)] = linprog(c, [], [], S, zeros(m, 1), lb, ub, opts);
    [~, f] = linprog(-c, [], [], S, zeros(m, 1), lb, ub, opts);
    hi(j) = -f;
end

rxns = {'PGI', 'PFK', 'TPI', 'G6PDH2r', 'PYK'};
growth_fba = zeros(1, numel(rxns)); growth_room = growth_fba;
changes = growth_fba;
for k = 1:numel(rxns)
    j = strcmp(ids, rxns{k});
    lb_d = lo; ub_d = hi;
    lb_d(j) = 0; ub_d(j) = 0;
    [changes(k), mu_room] = solve_room(S, w, lb_d, ub_d, bio, delta, epsilon);
    growth_fba(k) = fba(S, lb_d, ub_d, bio) / mu_wt;
    growth_room(k) = mu_room / mu_wt;
    fprintf(['  %-8s %2d significant changes; growth FBA %.3f, ROOM ' ...
        '%.3f of wild type\n'], rxns{k}, changes(k), growth_fba(k), ...
        growth_room(k));
end

%% Plot
fig = figure('Position', [100 100 1000 400]);
subplot(1, 2, 1)
b = bar(categorical(rxns, rxns), [growth_fba; growth_room]', ...
    'EdgeColor', 'none');
b(1).FaceColor = [0.902 0.624 0.000];
b(2).FaceColor = [0.000 0.447 0.698];
set(gca, 'TickDir', 'out', 'XTickLabelRotation', 45);
ylabel('Growth (fraction of wild type)');
ylim([0, 1.25]);   % room for the legend
title('Growth after each deletion');
legend({'FBA', 'ROOM'}, 'Box', 'off', 'Location', 'north', ...
    'Orientation', 'horizontal');
subplot(1, 2, 2)
bar(categorical(rxns, rxns), changes, 'FaceColor', [0.000 0.447 0.698], ...
    'EdgeColor', 'none');
set(gca, 'TickDir', 'out', 'XTickLabelRotation', 45);
ylabel('Significant flux changes'); title('Fewest flux changes (ROOM)');
sbp.save_figure(fig, mfilename('fullpath'), 'fig-room');

results.growth_wild_type = mu_wt;
results.reactions = rxns;
results.growth_fba = growth_fba;
results.growth_room = growth_room;
results.changes = changes;
sbp.save_results(mfilename('fullpath'), results);

%% Local functions
function mu = fba(S, lb, ub, bio)
% Maximum growth rate.
c = zeros(size(lb)); c(bio) = -1;              % linprog minimises
opts = optimoptions('linprog', 'Display', 'none');
[~, f, exitflag] = linprog(c, [], [], S, zeros(size(S, 1), 1), lb, ub, ...
    opts);
assert(exitflag == 1, 'linprog failed');
mu = max(0, -f);
end

function v = min_norm(S, lb, ub)
% The flux vector of smallest Euclidean norm (QP, as in MoMA). Dropping
% dependent rows of S, and using the active-set algorithm, makes quadprog
% exact and reliable here.
n = numel(lb);
S = full(S);
[~, R, order] = qr(S', 'vector');               % independent rows of S
independent = order(abs(diag(R)) > 1e-9 * abs(R(1, 1)));
S = S(sort(independent), :);
opts = optimoptions('quadprog', 'Algorithm', 'active-set', ...
    'Display', 'none');
x0 = min(max(zeros(n, 1), lb), ub);
[v, ~, exitflag] = quadprog(eye(n), zeros(n, 1), [], [], S, ...
    zeros(size(S, 1), 1), lb, ub, x0, opts);
assert(exitflag > 0, 'quadprog failed');
end

function [changes, mu] = solve_room(S, w, lb, ub, bio, delta, epsilon)
% Fewest significant changes from w, and the fastest growth that keeps
% to that number. Variables are [v; y], y binary.
[m, n] = size(S);
wl = w - delta * abs(w) - epsilon;
wu = w + delta * abs(w) + epsilon;
I = speye(n);
% S v = 0;  v - y (lb - wl) >= wl;  v - y (ub - wu) <= wu
Aeq = [sparse(S), sparse(m, n)];
A = [-I, spdiags(lb - wl, 0, n, n);      % -(v - y (lb - wl)) <= -wl
      I, -spdiags(ub - wu, 0, n, n)];    %   v - y (ub - wu)  <=  wu
b = [-wl; wu];
lower = [lb; zeros(n, 1)]; upper = [ub; ones(n, 1)];
intcon = n + (1:n);
opts = optimoptions('intlinprog', 'Display', 'none', ...
    'RelativeGapTolerance', 0, 'AbsoluteGapTolerance', 0, ...
    'IntegerTolerance', 1e-6, 'ConstraintTolerance', 1e-9);
[~, f, exitflag] = intlinprog([zeros(n, 1); ones(n, 1)], intcon, A, b, ...
    Aeq, zeros(m, 1), lower, upper, opts);
assert(exitflag == 1, 'intlinprog failed (exit flag %d)', exitflag);
changes = round(f);
% Second step: fastest growth with at most that many changes
c = zeros(2 * n, 1); c(bio) = -1;
A = [A; zeros(1, n), ones(1, n)];
b = [b; changes];
[x, f, exitflag] = intlinprog(c, intcon, A, b, Aeq, zeros(m, 1), ...
    lower, upper, opts);
assert(exitflag == 1, 'intlinprog failed (exit flag %d)', exitflag);
v = x(1:n);
tol = 1e-6;                       % check: count the changes from v itself
assert(sum(v < wl - tol | v > wu + tol) <= changes);
mu = -f;
end

Needs COBRApy (to read the model), SciPy and Clarabel.

"""Regulatory on-off minimisation (ROOM) for single deletions.

ROOM (book §9.2, Eq. 9.5) assumes that a mutant changes as few fluxes as
possible, compared with the wild type w. A change is significant if the
flux leaves the range [w_l, w_u], with w_l = w - delta|w| - epsilon and
w_u = w + delta|w| + epsilon. A binary variable y_i is 1 if flux i changes
significantly, and ROOM minimises sum(y): a mixed-integer linear
programme (MILP). Many flux distributions reach that minimum, so we then
report the fastest growth among them, which is unique. The wild type w is
the flux distribution of smallest norm at optimal growth, as for MoMA.
Binary variables make ROOM much slower than FBA or MoMA, so we look at
five deletions in glycolysis and the pentose phosphate pathway,
including pyruvate kinase (PYK), the example of the book. To keep the
MILP well conditioned, the bounds lb and ub in Eq. 9.5 are the tightest
the network allows, found by flux variability analysis (FVA), rather
than the nominal +/-1000.
"""
import numpy as np
import clarabel
from scipy.optimize import linprog, milp, LinearConstraint, Bounds
from scipy import sparse
import matplotlib.pyplot as plt
import cobra
from cobra.util import create_stoichiometric_matrix
import sbp

model = cobra.io.read_sbml_model(str(sbp.DATA / "e_coli_core.xml"))
S = create_stoichiometric_matrix(model)
lb = np.array([r.lower_bound for r in model.reactions])
ub = np.array([r.upper_bound for r in model.reactions])
ids = [r.id for r in model.reactions]
bio = ids.index("Biomass_Ecoli_core")
m, n = S.shape
delta, epsilon = 0.03, 0.001          # as Shlomi et al. used for fluxes


def fba(lb, ub):
    """Maximum growth rate, or None if the constraints cannot be met."""
    c = np.zeros(n)
    c[bio] = -1
    res = linprog(c, A_eq=S, b_eq=np.zeros(m), bounds=np.c_[lb, ub],
                  method="highs")
    return max(0.0, -res.fun) if res.status == 0 else None


def min_norm(lb, ub):
    """The flux vector of smallest Euclidean norm (QP, as in MoMA)."""
    eye = sparse.identity(n, format="csc")
    A = sparse.vstack([sparse.csc_matrix(S), eye, -eye], format="csc")
    cones = [clarabel.ZeroConeT(m), clarabel.NonnegativeConeT(2 * n)]
    settings = clarabel.DefaultSettings()
    settings.verbose = False
    settings.tol_gap_abs = settings.tol_gap_rel = settings.tol_feas = 1e-10
    b = np.r_[np.zeros(m), ub, -lb]
    sol = clarabel.DefaultSolver(eye, np.zeros(n), A, b, cones,
                                 settings).solve()
    return np.array(sol.x)


def room(w, lb, ub):
    """Fewest significant changes from w, and the fastest growth that
    keeps to that number. Variables are [v, y], y binary."""
    wl = w - delta * np.abs(w) - epsilon
    wu = w + delta * np.abs(w) + epsilon
    eye = sparse.identity(n, format="csr")
    # S v = 0;  v - y (lb - wl) >= wl;  v - y (ub - wu) <= wu
    cons = [LinearConstraint(sparse.hstack([S, sparse.csr_matrix((m, n))]),
                             0, 0),
            LinearConstraint(sparse.hstack([eye, -sparse.diags(lb - wl)]),
                             wl, np.inf),
            LinearConstraint(sparse.hstack([eye, -sparse.diags(ub - wu)]),
                             -np.inf, wu)]
    bounds = Bounds(np.r_[lb, np.zeros(n)], np.r_[ub, np.ones(n)])
    integrality = np.r_[np.zeros(n), np.ones(n)]
    opts = {"mip_rel_gap": 0}
    res = milp(np.r_[np.zeros(n), np.ones(n)], constraints=cons, bounds=bounds,
               integrality=integrality, options=opts)
    assert res.status == 0
    changes = round(res.fun)
    # Second step: fastest growth with at most that many changes
    c = np.zeros(2 * n)
    c[bio] = -1
    cons.append(LinearConstraint(np.r_[np.zeros(n), np.ones(n)][None, :],
                                 -np.inf, changes))
    res = milp(c, constraints=cons, bounds=bounds, integrality=integrality,
               options=opts)
    v = res.x[:n]
    tol = 1e-6                       # check: count the changes from v itself
    assert np.sum((v < wl - tol) | (v > wu + tol)) <= changes
    return changes, -res.fun


# Wild type: optimal growth, smallest norm
mu_wt = fba(lb, ub)
lb_wt, ub_wt = lb.copy(), ub.copy()
lb_wt[bio], ub_wt[bio] = mu_wt * (1 - 1e-9), mu_wt
w = min_norm(lb_wt, ub_wt)
w[np.abs(w) < 1e-9] = 0
print(f"Wild-type growth {mu_wt:.4f} /h; "
      f"{np.sum(w != 0)} reactions carry flux")

# Tightest bounds the network allows (FVA, at any growth rate)
lo, hi = np.zeros(n), np.zeros(n)
for j in range(n):
    c = np.zeros(n)
    c[j] = 1
    lo[j] = linprog(c, A_eq=S, b_eq=np.zeros(m), bounds=np.c_[lb, ub],
                    method="highs").fun
    hi[j] = -linprog(-c, A_eq=S, b_eq=np.zeros(m), bounds=np.c_[lb, ub],
                     method="highs").fun

rxns = ["PGI", "PFK", "TPI", "G6PDH2r", "PYK"]
growth_fba, growth_room, changes = [], [], []
for r in rxns:
    j = ids.index(r)
    lb_d, ub_d = lo.copy(), hi.copy()
    lb_d[j] = ub_d[j] = 0
    k, mu_room = room(w, lb_d, ub_d)
    growth_fba.append(fba(lb_d, ub_d) / mu_wt)
    growth_room.append(mu_room / mu_wt)
    changes.append(k)
    print(f"  {r:8s} {k:2d} significant changes; growth FBA "
          f"{growth_fba[-1]:.3f}, ROOM {growth_room[-1]:.3f} of wild type")
growth_fba, growth_room = np.array(growth_fba), np.array(growth_room)
changes = np.array(changes)

# --- Plot
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
x = np.arange(len(rxns))
ax1.bar(x - 0.2, growth_fba, 0.4, color="#E69F00", label="FBA")
ax1.bar(x + 0.2, growth_room, 0.4, color="#0072B2", label="ROOM")
ax1.set_xticks(x, rxns, rotation=45)
ax1.set_ylabel("Growth (fraction of wild type)")
ax1.set_ylim(0, 1.25)   # room for the legend
ax1.set_title("Growth after each deletion")
ax1.legend(frameon=False, loc="upper center", ncol=2)
ax2.bar(x, changes, color="#0072B2")
ax2.set_xticks(x, rxns, rotation=45)
ax2.set_ylabel("Significant flux changes")
ax2.set_title("Fewest flux changes (ROOM)")
sbp.save_figure(fig, __file__, "fig-room")

sbp.save_results(__file__, {
    "growth_wild_type": mu_wt, "reactions": rxns,
    "growth_fba": growth_fba, "growth_room": growth_room,
    "changes": changes,
})
sbp.show()

9.2.1 ROOM vs. MoMA

For the deletion of pyruvate kinase (PYK), the example in the book, ROOM needs only five significant flux changes and growth barely changes. For PGI and G6PDH2r about 30 fluxes change, but the network still reroutes to almost wild-type growth, as FBA predicts. Without PFK or TPI, upper glycolysis is cut, 41 fluxes must change, and the fastest growth that keeps to 41 changes is only 34% of the wild type. That is well below FBA (81%), and close to MoMA (24% for PFK). ROOM and MoMA thus agree that this mutant cannot simply reroute without many adjustments. Where they differ is in what they minimise: MoMA prefers many small changes, ROOM a few large ones. In the original study, MoMA predicted the growth of mutants just after the deletion better, and ROOM their growth after adaptation (book, §9.2.1).

9.3 Bi-level optimisation

9.3.1 OptKnock

OptKnock (Burgard et al. 2003) nests two optimisation problems (book, Eq. 9.6). The outer problem chooses which reactions to knock out, so as to maximise the production of a metabolite; the inner problem is the cell, which, given those knock-outs, maximises its growth. A bi-level problem of this kind cannot be handed directly to a solver. However, the inner problem is a linear programme, and a linear programme is solved exactly when its primal and dual are both feasible and their objectives are equal. Writing these conditions as constraints turns OptKnock into a single MILP, with one binary variable \(y_j\) for every reaction that may be knocked out.

Here, we take up Exercise 9.6 of the book: the E. coli core model grows anaerobically, with glucose uptake of up to 18 mmol/gDW/h, and we seek up to three knock-outs that increase lactate secretion, while growth stays above 10% of the wild type. Note that OptKnock can be extremely slow for large models, and the choice of reactions that form its search space matters a great deal. We let it choose from 14 reactions of central metabolism and fermentation. With so few candidates, we can also evaluate every possible design directly, which gives us an independent check on the MILP.

Needs the Optimization Toolbox (for linprog and intlinprog); reads the model from data/e_coli_core.mat, so the COBRA Toolbox is not required.

%% OptKnock: knock-outs that make E. coli over-produce lactate
% This follows Exercise 9.6 of the book. The E. coli core model grows
% anaerobically on glucose (uptake up to 18 mmol/gDW/h), and we look for up
% to three reaction knock-outs that maximise lactate secretion, while
% keeping growth at no less than 10% of the wild type.
%
% OptKnock (book §9.3.1, Eq. 9.6) is a bi-level problem: the outer problem
% maximises lactate, over the choice of knock-outs, and the inner problem is
% the cell maximising its growth. Replacing the inner problem by its
% optimality conditions (primal feasibility, dual feasibility and strong
% duality) turns it into a single MILP. As the book notes, OptKnock is slow
% for large search spaces, so we let it choose from 14 reactions of central
% carbon metabolism and fermentation. The search space is small enough that
% we can also try every combination of knock-outs directly, and check the
% two answers against each other.
% Requires: Optimization Toolbox (the COBRA Toolbox is not needed).

s = load(fullfile(sbp.data_dir(), 'e_coli_core.mat'));
model = s.e_coli_core;
ids = model.rxns;
model.lb(strcmp(ids, 'EX_glc__D_e')) = -18;   % glucose uptake
model.lb(strcmp(ids, 'EX_o2_e')) = 0;         % anaerobic
net.S = full(model.S); net.lb = model.lb; net.ub = model.ub; net.ids = ids;
net.bio = find(strcmp(ids, 'Biomass_Ecoli_core'));
net.lac = find(strcmp(ids, 'EX_lac__D_e'));

candidates = sort({'ACALD', 'ACKr', 'ALCD2x', 'FRD7', 'FUM', 'ME1', 'ME2', ...
    'PDH', 'PFL', 'PPC', 'PTAr', 'PYK', 'SUCCt3', 'THD2'});

mu_wt = optimise(net, net.bio, net.lb, net.ub, -1);
net.mu_wt = mu_wt;
[~, lac_lo, lac_hi] = evaluate(net, {});
fprintf('Wild type: growth %.4f /h, lactate %.2f to %.2f\n', mu_wt, ...
    lac_lo, lac_hi);

% Every design of up to three knock-outs from the search space
designs = struct('K', {}, 'ko', {}, 'mu', {}, 'low', {}, 'high', {});
for K = 1:3
    combos = nchoosek(1:numel(candidates), K);
    for c = 1:size(combos, 1)
        ko = candidates(combos(c, :));
        [mu, low, high] = evaluate(net, ko);
        if ~isempty(mu)
            designs(end + 1) = struct('K', K, 'ko', {ko}, 'mu', mu, ...
                'low', low, 'high', high); %#ok<SAGROW>
        end
    end
end

results.growth_wild_type = mu_wt;
for K = 1:3
    [value, design] = solve_optknock(net, candidates, K);
    b = best(designs, K, 'high');
    assert(abs(value - b.high) < 1e-5);  % OptKnock finds the true optimum
    g = best(designs, K, 'low');
    fprintf('K = %d: OptKnock picks %s: up to %.2f lactate\n', K, ...
        strjoin(design, ', '), value);
    fprintf(['       such a design grows at %.3f /h, and secretes ' ...
        '%.2f to %.2f lactate\n'], b.mu, b.low, b.high);
    fprintf(['       most lactate guaranteed: %s: growth %.3f /h, ' ...
        'lactate %.2f to %.2f\n'], strjoin(g.ko, ', '), g.mu, g.low, g.high);
    results.(sprintf('K%d', K)) = struct('optknock_lactate', value, ...
        'growth', b.mu, 'lactate_min', b.low, 'lactate_max', b.high, ...
        'guaranteed_design', {g.ko}, 'guaranteed_growth', g.mu, ...
        'guaranteed_lactate', g.low);
end

%% Plot: production envelopes
b3 = best(designs, 3, 'high'); g3 = best(designs, 3, 'low');
g1 = best(designs, 1, 'low');
panels = {'Three knock-outs', ...
    {[strjoin(b3.ko, ', ') ' (OptKnock)'], b3.ko, [0.835 0.369 0.000]; ...
     strjoin(g3.ko, ', '), g3.ko, [0.000 0.447 0.698]}; ...
    'One knock-out', {strjoin(g1.ko, ', '), g1.ko, [0.000 0.620 0.451]}};
fig = figure('Position', [100 100 1100 430]);
for p = 1:2
    subplot(1, 2, p); hold on
    shown = [{'wild type', {}, [0.6 0.6 0.6]}; panels{p, 2}];
    h = gobjects(size(shown, 1), 1);
    for d = 1:size(shown, 1)
        [mus, low, high] = envelope(net, shown{d, 2});
        x = [mus, fliplr(mus), mus(1)];
        y = [high, fliplr(low), high(1)];
        fill(x, y, shown{d, 3}, 'FaceAlpha', 0.2, 'EdgeColor', 'none');
        h(d) = plot(x, y, 'Color', shown{d, 3}, 'LineWidth', 1.5);
    end
    xline(0.1 * mu_wt, ':k', 'LineWidth', 1);
    axis padded
    ylim([-2, 45]);   % room for the legend
    xlabel('Growth rate (1/h)'); title(panels{p, 1});
    if p == 1, ylabel('Lactate secretion (mmol/gDW/h)'); end
    legend(h, shown(:, 1), 'Box', 'off', 'Location', 'northeast');
    box off
end
sbp.save_figure(fig, mfilename('fullpath'), 'fig-optknock');

sbp.save_results(mfilename('fullpath'), results);

%% Local functions
function value = optimise(net, j, lb, ub, sense)
% Maximise (sense = -1) or minimise (sense = 1) flux j; [] if infeasible.
c = zeros(numel(lb), 1); c(j) = sense;
opts = optimoptions('linprog', 'Display', 'none');
[~, f, exitflag] = linprog(c, [], [], net.S, zeros(size(net.S, 1), 1), ...
    lb, ub, opts);
if exitflag == 1, value = sense * f; else, value = []; end
end

function [lb, ub] = knock_out(net, reactions)
lb = net.lb; ub = net.ub;
j = ismember(net.ids, reactions);
lb(j) = 0; ub(j) = 0;
end

function [mu, low, high] = evaluate(net, reactions)
% Growth of a design, and the least and most lactate it can secrete while
% growing at that rate.
[lb, ub] = knock_out(net, reactions);
mu = optimise(net, net.bio, lb, ub, -1);
low = []; high = [];
if isempty(mu) || mu < 0.1 * net.mu_wt, mu = []; return; end
lb(net.bio) = mu * (1 - 1e-9);
low = optimise(net, net.lac, lb, ub, 1);
high = optimise(net, net.lac, lb, ub, -1);
end

function [mus, low, high] = envelope(net, reactions)
% Production envelope: least and most lactate at each growth rate.
[lb, ub] = knock_out(net, reactions);
mus = linspace(0, optimise(net, net.bio, lb, ub, -1), 21);
low = zeros(size(mus)); high = low;
for i = 1:numel(mus)
    lb(net.bio) = mus(i); ub(net.bio) = mus(i);
    low(i) = optimise(net, net.lac, lb, ub, 1);
    high(i) = optimise(net, net.lac, lb, ub, -1);
end
end

function d = best(designs, K, field)
% The design with the most lactate ('high': at best, 'low': guaranteed),
% with ties broken alphabetically.
pool = designs([designs.K] <= K);
values = [pool.(field)];
d = pool(find(values > max(values) - 1e-6, 1));
end

function [value, design] = solve_optknock(net, candidates, K)
% OptKnock as one MILP. Variables, in order: fluxes v (n), dual variables
% of S v = 0 (m), of the upper and lower bounds (n each), slacks that free
% the dual constraint of a knocked-out reaction (nc), and y (nc), with
% y = 0 for a knock-out.
M = 1000;
S = net.S; lb = net.lb; ub = net.ub;
[m, n] = size(S);
cand = find(ismember(net.ids, candidates));    % same (sorted) order
[~, order] = sort(net.ids(cand)); cand = cand(order);
nc = numel(cand);
iu = n + m; il = 2 * n + m; isl = 3 * n + m; iy = 3 * n + m + nc;
N = iy + nc;
% Equalities: S v = 0; S'lam + mu_u - mu_l (+ slack) = c; strong duality
E = sparse(cand, 1:nc, 1, n, nc);
c = zeros(n, 1); c(net.bio) = 1;
duality = zeros(1, N);
duality(net.bio) = 1; duality(iu + (1:n)) = -ub'; duality(il + (1:n)) = lb';
Aeq = [sparse(S), sparse(m, N - n);
       sparse(n, n), sparse(S'), speye(n), -speye(n), E, sparse(n, nc);
       sparse(duality)];
beq = [zeros(m, 1); c; 0];
% Inequalities linking each candidate to its y
A = sparse(6 * nc + 1, N); b = zeros(6 * nc + 1, 1);
for k = 1:nc
    j = cand(k); r = 6 * (k - 1);
    A(r + 1, [j, iy + k]) = [1, -ub(j)];          % v_j <= ub_j y_k
    A(r + 2, [j, iy + k]) = [-1, lb(j)];          % v_j >= lb_j y_k
    A(r + 3, [iu + j, iy + k]) = [1, -M];         % bound duals vanish
    A(r + 4, [il + j, iy + k]) = [1, -M];         %   when knocked out
    A(r + 5, [isl + k, iy + k]) = [1, M];  b(r + 5) = M; % |slack| is 0
    A(r + 6, [isl + k, iy + k]) = [-1, M]; b(r + 6) = M; %   unless knocked out
end
A(end, iy + (1:nc)) = -1; b(end) = K - nc;        % at most K knock-outs
lower = [lb; -inf(m, 1); zeros(2 * n, 1); -inf(nc, 1); zeros(nc, 1)];
upper = [ub; inf(m + 2 * n + nc, 1); ones(nc, 1)];
lower(net.bio) = 0.1 * net.mu_wt;
f = zeros(N, 1); f(net.lac) = -1;                 % maximise lactate
opts = optimoptions('intlinprog', 'Display', 'none', ...
    'RelativeGapTolerance', 0, 'AbsoluteGapTolerance', 0, ...
    'IntegerTolerance', 1e-6, 'ConstraintTolerance', 1e-9);
[x, fval, exitflag] = intlinprog(f, iy + (1:nc), A, b, Aeq, beq, ...
    lower, upper, opts);
assert(exitflag == 1, 'intlinprog failed (exit flag %d)', exitflag);
value = -fval;
design = net.ids(cand(round(x(iy + (1:nc))) == 0))';
end

Needs COBRApy (to read the model) and SciPy (for linprog and milp).

"""OptKnock: knock-outs that make E. coli over-produce lactate.

This follows Exercise 9.6 of the book. The E. coli core model grows
anaerobically on glucose (uptake up to 18 mmol/gDW/h), and we look for up
to three reaction knock-outs that maximise lactate secretion, while
keeping growth at no less than 10% of the wild type.

OptKnock (book §9.3.1, Eq. 9.6) is a bi-level problem: the outer problem
maximises lactate, over the choice of knock-outs, and the inner problem is
the cell maximising its growth. Replacing the inner problem by its
optimality conditions (primal feasibility, dual feasibility and strong
duality) turns it into a single MILP. As the book notes, OptKnock is slow
for large search spaces, so we let it choose from 14 reactions of central
carbon metabolism and fermentation. The search space is small enough that
we can also try every combination of knock-outs directly, and check the
two answers against each other.
"""
import itertools
import numpy as np
from scipy.optimize import linprog, milp, LinearConstraint, Bounds
from scipy import sparse
import matplotlib.pyplot as plt
import cobra
from cobra.util import create_stoichiometric_matrix
import sbp

model = cobra.io.read_sbml_model(str(sbp.DATA / "e_coli_core.xml"))
model.reactions.EX_glc__D_e.lower_bound = -18     # glucose uptake
model.reactions.EX_o2_e.lower_bound = 0           # anaerobic
S = create_stoichiometric_matrix(model)
lb = np.array([r.lower_bound for r in model.reactions])
ub = np.array([r.upper_bound for r in model.reactions])
ids = [r.id for r in model.reactions]
m, n = S.shape
bio, lac = ids.index("Biomass_Ecoli_core"), ids.index("EX_lac__D_e")

candidates = ["ACALD", "ACKr", "ALCD2x", "FRD7", "FUM", "ME1", "ME2", "PDH",
              "PFL", "PPC", "PTAr", "PYK", "SUCCt3", "THD2"]
cand = [ids.index(r) for r in candidates]
nc = len(cand)


def optimise(j, lb, ub, sense=-1):
    """Maximise (sense=-1) or minimise (sense=1) flux j; None if infeasible."""
    c = np.zeros(n)
    c[j] = sense
    res = linprog(c, A_eq=S, b_eq=np.zeros(m), bounds=np.c_[lb, ub],
                  method="highs")
    return sense * res.fun if res.status == 0 else None


def knock_out(reactions):
    lb_k, ub_k = lb.copy(), ub.copy()
    for r in reactions:
        lb_k[ids.index(r)] = ub_k[ids.index(r)] = 0
    return lb_k, ub_k


def evaluate(reactions):
    """Growth of a design, and the least and most lactate it can secrete
    while growing at that rate."""
    lb_k, ub_k = knock_out(reactions)
    mu = optimise(bio, lb_k, ub_k)
    if mu is None or mu < 0.1 * mu_wt:
        return None
    lb_k[bio] = mu * (1 - 1e-9)
    return mu, optimise(lac, lb_k, ub_k, 1), optimise(lac, lb_k, ub_k)


def envelope(reactions, points=21):
    """Production envelope: least and most lactate at each growth rate."""
    lb_k, ub_k = knock_out(reactions)
    mus = np.linspace(0, optimise(bio, lb_k, ub_k), points)
    low, high = [], []
    for mu in mus:
        lb_k[bio] = ub_k[bio] = mu
        low.append(optimise(lac, lb_k, ub_k, 1))
        high.append(optimise(lac, lb_k, ub_k))
    return mus, np.array(low), np.array(high)


def solve_optknock(K, M=1000.0):
    """OptKnock as one MILP. Variables, in order: fluxes v (n), dual
    variables of S v = 0 (m), of the upper and lower bounds (n each),
    slacks that free the dual constraint of a knocked-out reaction (nc),
    and y (nc), with y = 0 for a knock-out."""
    iv, ilam, iu, il = 0, n, n + m, 2 * n + m
    isl, iy = 3 * n + m, 3 * n + m + nc
    N = iy + nc
    rows, lo, hi = [], [], []

    def add(block, low, high):
        block = sparse.csr_matrix(block)
        rows.append(block)
        lo.extend(np.broadcast_to(low, block.shape[0]))
        hi.extend(np.broadcast_to(high, block.shape[0]))

    # Primal feasibility: S v = 0
    add(sparse.hstack([S, sparse.csr_matrix((m, N - n))]), 0, 0)
    # Dual feasibility: S'lam + mu_u - mu_l (+ slack) = c, c picks biomass
    E = sparse.csr_matrix((np.ones(nc), (cand, np.arange(nc))), shape=(n, nc))
    c = np.zeros(n)
    c[bio] = 1
    add(sparse.hstack([sparse.csr_matrix((n, n)), S.T, sparse.identity(n),
                       -sparse.identity(n), E, sparse.csr_matrix((n, nc))]),
        c, c)
    # Strong duality: growth = ub'mu_u - lb'mu_l
    r = np.zeros(N)
    r[bio], r[iu:iu + n], r[il:il + n] = 1, -ub, lb
    add(r[None, :], 0, 0)
    for k, j in enumerate(cand):
        def link(entries, low, high):
            r = np.zeros(N)
            for col, val in entries:
                r[col] = val
            add(r[None, :], low, high)
        # v_j <= ub_j y_k and v_j >= lb_j y_k
        link([(iv + j, 1), (iy + k, -ub[j])], -np.inf, 0)
        link([(iv + j, 1), (iy + k, -lb[j])], 0, np.inf)
        # bound duals vanish when knocked out
        link([(iu + j, 1), (iy + k, -M)], -np.inf, 0)
        link([(il + j, 1), (iy + k, -M)], -np.inf, 0)
        # |slack| is 0 unless knocked out
        link([(isl + k, 1), (iy + k, M)], -np.inf, M)
        link([(isl + k, -1), (iy + k, M)], -np.inf, M)
    count = np.zeros(N)
    count[iy:] = 1  # at most K knock-outs
    constraints = [LinearConstraint(sparse.vstack(rows), lo, hi),
                   LinearConstraint(count[None, :], nc - K, np.inf)]
    low = np.r_[lb, np.full(m, -np.inf), np.zeros(2 * n), np.full(nc, -np.inf),
                np.zeros(nc)]
    high = np.r_[ub, np.full(m + 2 * n + nc, np.inf), np.ones(nc)]
    low[bio] = 0.1 * mu_wt
    objective = np.zeros(N)
    objective[lac] = -1                                     # maximise lactate
    integrality = np.r_[np.zeros(iy), np.ones(nc)]
    res = milp(objective, constraints=constraints, bounds=Bounds(low, high),
               integrality=integrality, options={"mip_rel_gap": 0})
    assert res.status == 0
    design = [candidates[k] for k in range(nc) if round(res.x[iy + k]) == 0]
    return -res.fun, design


mu_wt = optimise(bio, lb, ub)
_, lac_lo, lac_hi = evaluate([])
print(f"Wild type: growth {mu_wt:.4f} /h, "
      f"lactate {lac_lo:.2f} to {lac_hi:.2f}")

# Every design of up to three knock-outs from the search space
designs = []
for K in (1, 2, 3):
    for ko in itertools.combinations(sorted(candidates), K):
        e = evaluate(ko)
        if e is not None:
            designs.append((K, list(ko)) + e)


def best(K, column):
    """The design with the most lactate (column 4: at best, 3: guaranteed),
    with ties broken alphabetically."""
    pool = [d for d in designs if d[0] <= K]
    top = max(d[column] for d in pool)
    return [d for d in pool if d[column] > top - 1e-6][0]


results = {"growth_wild_type": mu_wt}
for K in (1, 2, 3):
    value, design = solve_optknock(K)
    _, _, mu, low, high = best(K, 4)
    assert abs(value - high) < 1e-5  # OptKnock finds the true optimum
    g = best(K, 3)
    print(f"K = {K}: OptKnock picks {', '.join(design)}: "
          f"up to {value:.2f} lactate")
    print(f"       such a design grows at {mu:.3f} /h, and secretes "
          f"{low:.2f} to {high:.2f} lactate")
    print(f"       most lactate guaranteed: {', '.join(g[1])}: growth "
          f"{g[2]:.3f} /h, lactate {g[3]:.2f} to {g[4]:.2f}")
    results[f"K{K}"] = {"optknock_lactate": value, "growth": mu,
                        "lactate_min": low, "lactate_max": high,
                        "guaranteed_design": g[1], "guaranteed_growth": g[2],
                        "guaranteed_lactate": g[3]}

# --- Plot: production envelopes
sbp.style()
fig, axes = plt.subplots(1, 2, figsize=(11, 4.3), sharey=True)
b3, g3, g1 = best(3, 4)[1], best(3, 3)[1], best(1, 3)[1]
panels = [("Three knock-outs",
           [(", ".join(b3) + " (OptKnock)", b3, "#D55E00"),
            (", ".join(g3), g3, "#0072B2")]),
          ("One knock-out", [(", ".join(g1), g1, "#009E73")])]
for ax, (title, shown) in zip(axes, panels):
    for label, ko, colour in [("wild type", [], "#999999")] + shown:
        mus, low, high = envelope(ko)
        ax.fill_between(mus, low, high, color=colour, alpha=0.2, lw=0)
        x = np.r_[mus, mus[::-1], mus[:1]]
        y = np.r_[high, low[::-1], high[:1]]
        ax.plot(x, y, color=colour, label=label)
    ax.axvline(0.1 * mu_wt, ls=":", color="black", lw=1)
    ax.set_ylim(-2, 45)   # room for the legend
    ax.set_xlabel("Growth rate (1/h)")
    ax.set_title(title)
    ax.legend(frameon=False, fontsize=9, loc="upper right")
axes[0].set_ylabel("Lactate secretion (mmol/gDW/h)")
sbp.save_figure(fig, __file__, "fig-optknock")

sbp.save_results(__file__, results)
sbp.show()

The wild type secretes no lactate at all at its optimal growth rate, 0.455 h−1. With three knock-outs, OptKnock finds a design (ACKr, PDH and PYK) that can secrete 33.9 mmol/gDW/h of lactate. Look closely at the production envelope of this design (left, in vermillion), though. At its maximal growth rate, lactate secretion can be anything from 33.9 down to zero! OptKnock is optimistic: it assumes that, among the many flux distributions with optimal growth, the cell will pick the one that suits us best. A design such as ACALD, FRD7 and PYK (blue) is far more useful: it gives up a little lactate, 33.7 instead of 33.9, but secretes it at every flux distribution with optimal growth. Lactate production is then coupled to growth, and adaptive evolution in the laboratory, which selects for faster growth, also selects for more lactate. Later methods, such as RobustKnock (Tepper and Shlomi 2010), address exactly this weakness, by maximising the guaranteed production.

The exercise also asks whether a subset of the knock-outs does nearly as well, at a higher growth rate. Indeed, knocking out ACALD alone (right) forces 30.7 mmol/gDW/h of lactate, at a growth rate of 0.328 h−1, more than twice that of the three-knock-out designs. Removing acetaldehyde dehydrogenase blocks the route to ethanol, and lactate becomes the main way for the cell to re-oxidise its NADH.

9.4 Integrating regulatory information

9.4.1 Embedding regulatory logic: Regulatory FBA (rFBA)

There is no code for this section; see the book.

9.4.2 Informing metabolic models with omic data

E-Flux (Colijn et al. 2009) is perhaps the simplest way to bring expression data into a constraint-based model. The level of mRNA is taken as an approximate upper bound on the amount of enzyme, and hence on the flux. The expression of a reaction follows its GPR association: for a complex (genes joined by and), we take the minimum of the expression values; for isozymes (genes joined by or), their sum. Every bound is then divided by the largest, so that all of them lie in \([-1, 1]\).

To try E-Flux on real data, we use RNA-seq profiles from the PRECISE compendium (Sastry et al. 2019): wild-type E. coli MG1655, grown aerobically in minimal medium on glucose, xylose, glycerol, fructose or acetate, with the growth rate measured in each experiment. For every sample, we constrain iML1515 with E-Flux bounds, allow uptake of that sample’s carbon source alone, and maximise growth. Note that the uptake rate itself is left open; only expression limits the fluxes. We also set the non-growth-associated ATP maintenance to zero, since a requirement of 6.86 mmol/gDW/h makes little sense once all fluxes are in arbitrary units below 1. Finally, the GPR rules are evaluated by a small parser, written out in full in both languages, so that you can see exactly how and and or are handled.

Needs the Optimization Toolbox (for linprog); reads iML1515 from data/iML1515.mat, so the COBRA Toolbox is not required.

%% E-Flux: constraining fluxes with gene expression data
% E-Flux (book §9.4.2) uses the expression of the genes behind a reaction
% as an approximate upper bound on its flux. The expression of a reaction
% follows its GPR rule: genes joined by 'and' (subunits of one complex)
% give the minimum of their expression, and genes joined by 'or'
% (isozymes) give the sum. The bounds of each reaction are then set to
% +/- this value, divided by the largest value over all reactions.
%
% The data are RNA-seq profiles of wild-type E. coli MG1655, grown
% aerobically in minimal medium on six carbon sources, from the PRECISE
% compendium (Sastry et al., 2019), with the growth rates measured in the
% same experiments. For each sample we build E-Flux bounds for the
% genome-scale model iML1515, open the uptake of that sample's carbon
% source, maximise growth, and compare the predictions with the measured
% growth rates. Expression is in log2(TPM + 1); we try both the raw TPM
% values, as in the original E-Flux, and the log values.
% Requires: Optimization Toolbox (the COBRA Toolbox is not needed).

s = load(fullfile(sbp.data_dir(), 'iML1515.mat'));
model = s.iML1515;
log_tpm = readtable(fullfile(sbp.data_dir(), 'precise_log_tpm.csv'), ...
    'ReadRowNames', true, 'VariableNamingRule', 'preserve');
samples = readtable(fullfile(sbp.data_dir(), 'precise_samples.csv'), ...
    'TextType', 'string');
uptake = containers.Map( ...
    {'glucose', 'xylose', 'glycerol', 'acetate', 'fructose'}, ...
    {'EX_glc__D_e', 'EX_xyl__D_e', 'EX_glyc_e', 'EX_ac_e', 'EX_fru_e'});

carbon = cellstr(extractBefore(samples.carbon_source, '('))';
measured = samples.growth_rate';
genes = log_tpm.Properties.RowNames;
transforms = {'TPM', 'log TPM'};
predicted = zeros(2, numel(carbon));
for t = 1:2
    for k = 1:numel(carbon)
        x = log_tpm.(samples.sample(k));
        if t == 1, x = 2 .^ x - 1; end
        expression = containers.Map(genes, num2cell(x));
        predicted(t, k) = eflux_growth(model, expression, carbon{k}, uptake);
    end
end
r = [corr1(measured, predicted(1, :)), corr1(measured, predicted(2, :))];

fprintf('carbon source    measured   E-Flux (TPM)   E-Flux (log TPM)\n');
for k = 1:numel(carbon)
    fprintf('%-12s  %8.2f   %12.3g   %14.3g\n', carbon{k}, measured(k), ...
        predicted(1, k), predicted(2, k));
end
for t = 1:2
    fprintf('Correlation with measured growth, %s: r = %.2f\n', ...
        transforms{t}, r(t));
end

%% Plot
fig = figure('Position', [100 100 1000 400]);
for t = 1:2
    subplot(1, 2, t)
    plot(measured, predicted(t, :), 'o', 'Color', [0.000 0.447 0.698], ...
        'MarkerFaceColor', [0.000 0.447 0.698]);
    text(measured, predicted(t, :), strcat({'  '}, carbon), ...
        'VerticalAlignment', 'middle', 'FontSize', 9);
    xlim([0.2, 0.8]);   % room for the labels
    xlabel('Measured growth rate (1/h)');
    ylabel('E-Flux growth (arbitrary units)');
    title(sprintf('Expression as %s: r = %.2f', transforms{t}, r(t)));
    box off
end
sbp.save_figure(fig, mfilename('fullpath'), 'fig-eflux');

results.carbon_source = carbon;
results.measured = measured;
results.eflux_tpm = predicted(1, :);
results.eflux_log_tpm = predicted(2, :);
results.r_tpm = r(1);
results.r_log_tpm = r(2);
sbp.save_results(mfilename('fullpath'), results);

%% Local functions
function mu = eflux_growth(model, expression, carbon, uptake)
% Maximum growth with E-Flux bounds, on one carbon source.
lb = model.lb; ub = model.ub;
level = nan(numel(model.rxns), 1);
for j = 1:numel(model.rxns)
    if ~isempty(model.grRules{j})
        level(j) = gpr_value(model.grRules{j}, expression);
    end
end
largest = max(level(isfinite(level)));
for j = find(isfinite(level))'
    bound = level(j) / largest;
    if lb(j) < 0, lb(j) = -bound; else, lb(j) = 0; end
    if ub(j) > 0, ub(j) = bound; else, ub(j) = 0; end
end
lb(ismember(model.rxns, values(uptake))) = 0;   % only this carbon source
lb(strcmp(model.rxns, uptake(carbon))) = -1000;
lb(strcmp(model.rxns, 'ATPM')) = 0;              % see the text
opts = optimoptions('linprog', 'Display', 'none');
[~, f, exitflag] = linprog(-model.c, [], [], model.S, ...
    zeros(size(model.S, 1), 1), lb, ub, opts);
assert(exitflag == 1, 'linprog failed');
mu = -f;
end

function value = gpr_value(rule, expression)
% Evaluate a GPR rule such as '(b1 and b2) or b3': 'and' takes the minimum,
% 'or' the sum. A gene without data does not constrain the reaction (its
% value is infinite).
tokens = regexp(rule, '\(|\)|[^\s()]+', 'match');
value = either(tokens, 1, expression);
end

function [v, pos] = either(tokens, pos, expression)
% 'and' groups joined by 'or'
[v, pos] = both(tokens, pos, expression);
while pos <= numel(tokens) && strcmp(tokens{pos}, 'or')
    [w, pos] = both(tokens, pos + 1, expression);
    v = v + w;
end
end

function [v, pos] = both(tokens, pos, expression)
% terms joined by 'and'
[v, pos] = term(tokens, pos, expression);
while pos <= numel(tokens) && strcmp(tokens{pos}, 'and')
    [w, pos] = term(tokens, pos + 1, expression);
    v = min(v, w);
end
end

function [v, pos] = term(tokens, pos, expression)
% a gene, or a bracketed rule
token = tokens{pos};
pos = pos + 1;
if strcmp(token, '(')
    [v, pos] = either(tokens, pos, expression);
    pos = pos + 1;                               % skip ')'
elseif isKey(expression, token)
    v = expression(token);
else
    v = inf;
end
end

function r = corr1(x, y)
% Pearson correlation coefficient.
c = corrcoef(x, y);
r = c(1, 2);
end

Needs COBRApy and pandas.

"""E-Flux: constraining fluxes with gene expression data.

E-Flux (book §9.4.2) uses the expression of the genes behind a reaction
as an approximate upper bound on its flux. The expression of a reaction
follows its GPR rule: genes joined by 'and' (subunits of one complex)
give the minimum of their expression, and genes joined by 'or'
(isozymes) give the sum. The bounds of each reaction are then set to
+/- this value, divided by the largest value over all reactions.

The data are RNA-seq profiles of wild-type E. coli MG1655, grown
aerobically in minimal medium on six carbon sources, from the PRECISE
compendium (Sastry et al., 2019), with the growth rates measured in the
same experiments. For each sample we build E-Flux bounds for the
genome-scale model iML1515, open the uptake of that sample's carbon
source, maximise growth, and compare the predictions with the measured
growth rates. Expression is in log2(TPM + 1); we try both the raw TPM
values, as in the original E-Flux, and the log values.
"""
import re
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cobra
import sbp

model = cobra.io.read_sbml_model(str(sbp.DATA / "iML1515.xml.gz"))
log_tpm = pd.read_csv(sbp.DATA / "precise_log_tpm.csv", index_col=0)
samples = pd.read_csv(sbp.DATA / "precise_samples.csv")
uptake = {"glucose": "EX_glc__D_e", "xylose": "EX_xyl__D_e",
          "glycerol": "EX_glyc_e", "acetate": "EX_ac_e",
          "fructose": "EX_fru_e"}


def gpr_value(rule, expression):
    """Evaluate a GPR rule such as '(b1 and b2) or b3': 'and' takes the
    minimum, 'or' the sum. A gene without data does not constrain the
    reaction (its value is infinite)."""
    tokens = re.findall(r"\(|\)|[^\s()]+", rule)
    position = 0

    def term():                      # a gene, or a bracketed rule
        nonlocal position
        token = tokens[position]
        position += 1
        if token == "(":
            value = either()
            position += 1            # skip ')'
            return value
        return expression.get(token, np.inf)

    def both():                      # terms joined by 'and'
        nonlocal position
        value = term()
        while position < len(tokens) and tokens[position] == "and":
            position += 1
            value = min(value, term())
        return value

    def either():                    # 'and' groups joined by 'or'
        nonlocal position
        value = both()
        while position < len(tokens) and tokens[position] == "or":
            position += 1
            value = value + both()
        return value

    return either()


def eflux_growth(expression, carbon):
    """Maximum growth with E-Flux bounds, on one carbon source."""
    with model:
        values = {r.id: gpr_value(r.gene_reaction_rule, expression)
                  for r in model.reactions if r.gene_reaction_rule}
        largest = max(v for v in values.values() if np.isfinite(v))
        for rid, v in values.items():
            if np.isfinite(v):
                r = model.reactions.get_by_id(rid)
                bound = v / largest
                r.bounds = (-bound if r.lower_bound < 0 else 0,
                            bound if r.upper_bound > 0 else 0)
        for ex in uptake.values():                 # only this carbon source
            model.reactions.get_by_id(ex).lower_bound = 0
        model.reactions.get_by_id(uptake[carbon]).lower_bound = -1000
        model.reactions.ATPM.lower_bound = 0       # see the text
        return model.slim_optimize()


carbon = samples["carbon_source"].str.split("(").str[0]
measured = samples["growth_rate"].to_numpy()
predicted = {}
for transform, data in [("TPM", 2 ** log_tpm - 1), ("log TPM", log_tpm)]:
    predicted[transform] = np.array([
        eflux_growth(data[s].to_dict(), c)
        for s, c in zip(samples["sample"], carbon)])
r = {t: np.corrcoef(measured, p)[0, 1] for t, p in predicted.items()}

print("carbon source    measured   E-Flux (TPM)   E-Flux (log TPM)")
for i, c in enumerate(carbon):
    print(f"{c:12s}  {measured[i]:8.2f}   {predicted['TPM'][i]:12.3g}"
          f"   {predicted['log TPM'][i]:14.3g}")
for t in predicted:
    print(f"Correlation with measured growth, {t}: r = {r[t]:.2f}")

# --- Plot
sbp.style()
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
for ax, t in zip(axes, predicted):
    ax.plot(measured, predicted[t], "o", color="#0072B2")
    for x, y, c in zip(measured, predicted[t], carbon):
        ax.annotate(c, (x, y), textcoords="offset points", xytext=(6, 0),
                    va="center", fontsize=9)
    ax.set_xlim(0.2, 0.8)   # room for the labels
    ax.set_xlabel("Measured growth rate (1/h)")
    ax.set_ylabel("E-Flux growth (arbitrary units)")
    ax.set_title(f"Expression as {t}: r = {r[t]:.2f}")
sbp.save_figure(fig, __file__, "fig-eflux")

sbp.save_results(__file__, {
    "carbon_source": list(carbon), "measured": measured,
    "eflux_tpm": predicted["TPM"], "eflux_log_tpm": predicted["log TPM"],
    "r_tpm": r["TPM"], "r_log_tpm": r["log TPM"],
})
sbp.show()

At first sight, E-Flux does well: its predicted growth rates correlate with the measured ones, with \(r = 0.78\) when expression is used as TPM, as in the original method, and \(r = 0.84\) with log-transformed values. Look closely at the plots, though. Both correlations come almost entirely from acetate: E-Flux correctly predicts that E. coli grows far more slowly on acetate than on any of the sugars, but it does not order the sugars and glycerol among themselves. With log-transformed values, glucose, the fastest in the experiments, is predicted to be the slowest of these four; with TPM, xylose falls well below the other three, although it is measured to grow faster than glycerol. Six samples are far too few to choose between the two transformations, and the choice clearly changes the predictions. This is typical of methods that integrate omic data: they capture large differences between conditions quite well, but the finer predictions depend on choices (normalisation, thresholds, how missing genes are treated) that are not dictated by the biology.

9.4.3 Tissue-specific models

There is no code for this section; see the book.

9.5 Compartmentalised models

There is no code for this section; see the book. Note, though, that the community model of §11.1.3 treats each organism as a compartment of a larger model.

9.6 Dynamic Flux Balance Analysis (dFBA)

In a batch culture, the cells change their environment as they grow. Dynamic FBA follows this by alternating FBA with the integration of simple ODEs for biomass \(X\) and the concentrations \(C_i\) of the substrates and products in the medium (Varma and Palsson 1994; Mahadevan et al. 2002). In the static optimisation approach (book, §9.6), at each short time step \(\Delta t\):

  1. the concentrations set the maximum uptake rates, here with Michaelis–Menten kinetics, \(v_i^{\max} C_i/(K_i + C_i)\), and never more than is left in the medium, \(C_i/(X\,\Delta t)\);
  2. FBA gives the growth rate \(\mu\) and the exchange fluxes \(v_i\);
  3. with these rates held constant over the step, \(dX/dt = \mu X\) and \(dC_i/dt = v_i X\) are integrated exactly: \(X \leftarrow X e^{\mu \Delta t}\) and \(C_i \leftarrow C_i + (v_i/\mu)\,X\,(e^{\mu \Delta t} - 1)\) (book, Eqs. 9.8 and 9.9; when \(\mu = 0\), the change is simply \(v_i X \Delta t\)).

We start with 0.01 g/L of cells in 20 mM glucose and limit oxygen uptake to 15 mmol/gDW/h, as happens in dense cultures.

Needs the Optimization Toolbox.

%% Dynamic FBA: E. coli growing on glucose in a batch culture
% FBA predicts steady-state rates. Dynamic FBA follows a culture through
% time by solving an FBA problem at each short time step: the current
% concentrations set the maximum uptake rates, FBA gives the growth rate
% and the exchange fluxes, and these update biomass and concentrations
% (the static optimisation approach of Mahadevan, Edwards and Doyle,
% 2002; book §9.6). Oxygen uptake is limited, as in a
% dense culture, so cells growing fast on glucose overflow acetate, which
% they consume once the glucose runs out.
% Requires: Optimization Toolbox (the COBRA Toolbox is not needed).

s = load(fullfile(sbp.data_dir(), 'e_coli_core.mat'));
model = s.e_coli_core;
S = model.S; lb0 = model.lb; ub0 = model.ub; ids = model.rxns;
n = numel(ids);
bio = find(strcmp(ids, 'Biomass_Ecoli_core'));
glc = find(strcmp(ids, 'EX_glc__D_e'));
ac = find(strcmp(ids, 'EX_ac_e'));
o2 = find(strcmp(ids, 'EX_o2_e'));

% Uptake kinetics (mmol/gDW/h, mM) and the oxygen limit
vmax_glc = 10; km_glc = 0.015;
vmax_ac = 5; km_ac = 0.015;
o2_max = 15;

dt = 0.01; t_end = 12;                 % h
X = 0.01; G = 20; A = 0;               % biomass (gDW/L), glucose, acetate
times = round(0:dt:t_end, 10);
traj = zeros(numel(times), 4);         % X, G, A, growth rate
c = zeros(n, 1); c(bio) = -1;          % linprog minimises
opts = optimoptions('linprog', 'Display', 'none');
for k = 1:numel(times)
    % Uptake is limited by kinetics, and by what is left in the medium
    lb = lb0; ub = ub0;
    lb(glc) = -min(vmax_glc * G / (km_glc + G), G / (X * dt));
    lb(ac) = -min(vmax_ac * A / (km_ac + A), A / (X * dt));
    lb(o2) = -o2_max;
    [v, f, exitflag] = linprog(c, [], [], S, zeros(size(S, 1), 1), ...
        lb, ub, opts);
    if exitflag == 1
        mu = max(0, -f);
    else                               % cannot even meet maintenance
        mu = 0; v = zeros(n, 1);
    end
    traj(k, :) = [X G A mu];
    % Integrate over the step with the fluxes held constant (book Eqs.
    % 9.8 and 9.9): X grows as exp(mu t), and dC/dt = v_exchange X
    growth = exp(mu * dt);
    if mu > 0
        produced = X * (growth - 1) / mu;
    else
        produced = X * dt;
    end
    G = max(0, G + v(glc) * produced);
    A = max(0, A + v(ac) * produced);
    X = X * growth;
end

X_t = traj(:, 1); G_t = traj(:, 2); A_t = traj(:, 3); mu_t = traj(:, 4);
t_glc = times(find(G_t < 1e-9, 1));            % glucose used up
[A_peak, k_peak] = max(A_t);
t_stop = times(find(mu_t > 0, 1, 'last') + 1);
fprintf(['Glucose runs out at t = %.2f h; acetate peaks at %.3f mM at ' ...
    't = %.2f h\n'], t_glc, A_peak, times(k_peak));
fprintf(['Growth on glucose at %.4f /h, then on acetate at %.4f /h; ' ...
    'growth stops at t = %.2f h with %.4f gDW/L\n'], mu_t(1), ...
    mu_t(find(times > t_glc + 0.1, 1)), t_stop, X_t(end));

%% Plot
fig = figure('Position', [100 100 1000 400]);
subplot(1, 2, 1)
semilogy(times, X_t, 'Color', [0.000 0.620 0.451]);
xline(t_glc, ':', 'Color', [0.6 0.6 0.6], 'LineWidth', 1);
ylim([min(X_t) / 1.3, 1.3 * max(X_t)]);   % room above the plateau
xlabel('Time (h)'); ylabel('Biomass (gDW/L)'); title('Biomass');
box off
subplot(1, 2, 2)
plot(times, G_t, 'Color', [0.000 0.447 0.698]);
hold on
plot(times, A_t, 'Color', [0.902 0.624 0.000]);
xline(t_glc, ':', 'Color', [0.6 0.6 0.6], 'LineWidth', 1, ...
    'HandleVisibility', 'off');
axis padded
xlabel('Time (h)'); ylabel('Concentration (mM)');
title('Substrates and by-products');
legend({'glucose', 'acetate'}, 'Box', 'off');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-dynamic-fba');

hourly = abs(times - round(times)) < 1e-9;
results.t_glucose_exhausted = t_glc;
results.acetate_peak = A_peak;
results.t_acetate_peak = times(k_peak);
results.t_growth_stops = t_stop;
results.growth_on_glucose = mu_t(1);
results.final_biomass = X_t(end);
results.hours = times(hourly);
results.biomass_hourly = X_t(hourly)';
results.glucose_hourly = G_t(hourly)';
results.acetate_hourly = A_t(hourly)';
sbp.save_results(mfilename('fullpath'), results);

Needs COBRApy (to read the model).

"""Dynamic FBA: E. coli growing on glucose in a batch culture.

FBA predicts steady-state rates. Dynamic FBA follows a culture through
time by solving an FBA problem at each short time step: the current
concentrations set the maximum uptake rates, FBA gives the growth rate
and the exchange fluxes, and these update biomass and concentrations
(the static optimisation approach of Mahadevan, Edwards and Doyle,
2002; book §9.6). Oxygen uptake is limited, as in a
dense culture, so cells growing fast on glucose overflow acetate, which
they consume once the glucose runs out.
"""
import numpy as np
from scipy.optimize import linprog
import matplotlib.pyplot as plt
import cobra
from cobra.util import create_stoichiometric_matrix
import sbp

model = cobra.io.read_sbml_model(str(sbp.DATA / "e_coli_core.xml"))
S = create_stoichiometric_matrix(model)
lb0 = np.array([r.lower_bound for r in model.reactions])
ub0 = np.array([r.upper_bound for r in model.reactions])
ids = [r.id for r in model.reactions]
bio, glc, ac, o2 = (ids.index(r) for r in
                    ["Biomass_Ecoli_core", "EX_glc__D_e", "EX_ac_e",
                     "EX_o2_e"])
n = len(ids)

# Uptake kinetics (mmol/gDW/h, mM) and the oxygen limit
vmax_glc, km_glc = 10.0, 0.015
vmax_ac, km_ac = 5.0, 0.015
o2_max = 15.0

dt, t_end = 0.01, 12.0                 # h
X, G, A = 0.01, 20.0, 0.0              # biomass (gDW/L), glucose, acetate
times = np.round(np.arange(0, t_end + dt / 2, dt), 10)
traj = np.zeros((len(times), 4))       # X, G, A, growth rate
for k, t in enumerate(times):
    # Uptake is limited by kinetics, and by what is left in the medium
    lb, ub = lb0.copy(), ub0.copy()
    lb[glc] = -min(vmax_glc * G / (km_glc + G), G / (X * dt))
    lb[ac] = -min(vmax_ac * A / (km_ac + A), A / (X * dt))
    lb[o2] = -o2_max
    c = np.zeros(n)
    c[bio] = -1
    res = linprog(c, A_eq=S, b_eq=np.zeros(S.shape[0]),
                  bounds=np.c_[lb, ub], method="highs")
    if res.status == 0:
        mu, v = max(0.0, -res.fun), res.x
    else:                              # cannot even meet maintenance
        mu, v = 0.0, np.zeros(n)
    traj[k] = X, G, A, mu
    # Integrate over the step with the fluxes held constant (book Eqs.
    # 9.8 and 9.9): X grows as exp(mu t), and dC/dt = v_exchange X
    growth = np.exp(mu * dt)
    produced = X * (growth - 1) / mu if mu > 0 else X * dt
    G = max(0.0, G + v[glc] * produced)
    A = max(0.0, A + v[ac] * produced)
    X = X * growth

X_t, G_t, A_t, mu_t = traj.T
t_glc = times[np.argmax(G_t < 1e-9)]          # glucose used up
k_peak = np.argmax(A_t)
growing = mu_t > 0
t_stop = times[np.flatnonzero(growing)[-1] + 1]
print(f"Glucose runs out at t = {t_glc:.2f} h; acetate peaks at "
      f"{A_t[k_peak]:.3f} mM at t = {times[k_peak]:.2f} h")
print(f"Growth on glucose at {mu_t[0]:.4f} /h, then on acetate at "
      f"{mu_t[times > t_glc + 0.1][0]:.4f} /h; growth stops at t = "
      f"{t_stop:.2f} h with {X_t[-1]:.4f} gDW/L")

# --- Plot
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.semilogy(times, X_t, color="#009E73")
ax1.set_xlabel("Time (h)")
ax1.set_ylabel("Biomass (gDW/L)")
ax1.set_title("Biomass")
ax2.plot(times, G_t, color="#0072B2", label="glucose")
ax2.plot(times, A_t, color="#E69F00", label="acetate")
ax2.set_xlabel("Time (h)")
ax2.set_ylabel("Concentration (mM)")
ax2.set_title("Substrates and by-products")
ax2.legend(frameon=False)
for ax in (ax1, ax2):
    ax.axvline(t_glc, color="#999999", ls=":", lw=1)
sbp.save_figure(fig, __file__, "fig-dynamic-fba")

hourly = np.isclose(times % 1, 0) | np.isclose(times % 1, 1)
sbp.save_results(__file__, {
    "t_glucose_exhausted": t_glc, "acetate_peak": A_t[k_peak],
    "t_acetate_peak": times[k_peak], "t_growth_stops": t_stop,
    "growth_on_glucose": mu_t[0], "final_biomass": X_t[-1],
    "hours": times[hourly], "biomass_hourly": X_t[hourly],
    "glucose_hourly": G_t[hourly], "acetate_hourly": A_t[hourly],
})
sbp.show()

The culture grows exponentially on glucose at 0.72 per hour. With oxygen limited, the fastest way to grow is to oxidise only part of the glucose, and to secrete the rest of its carbon as acetate. This overflow metabolism is well known in E. coli, and FBA predicts it quantitatively (Varma and Palsson 1994). By the time the glucose is used up, about 7 hours in, acetate has accumulated to 13.5 mM. The cells then switch to acetate, growing about ten times more slowly, until the acetate, too, runs out, at about 8.7 hours. This two-phase growth, or diauxie, emerges here from optimisation alone, without any model of the regulation that controls it in real cells.

The step size matters: each FBA problem assumes fluxes stay constant for \(\Delta t\), so the step must be short compared with the time over which concentrations change. At \(\Delta t = 0.01\) h, the simulation solves 1200 linear programmes, which takes a few seconds.

9.7 \(^{13}\)C-MFA

There is no code for this section; see the book.

9.8 Elementary Flux Modes and Extreme Pathways

The network of Figure 9.2 in the book is small enough that we can find its EFMs straight from the definition. Remember, an EFM must operate at steady state, run every irreversible reaction in its feasible direction, and be non-decomposable: no smaller set of its reactions can carry a steady flux. So, for every possible set of reactions, we ask whether the stoichiometric matrix restricted to that set admits exactly one steady-state flux distribution (up to scaling) that uses all of its reactions. The extreme pathways are then the EFMs that cannot be written as a non-negative combination of the other EFMs (systemic independence), which a linear programme with no objective can check.

9.8.1 Computing EFMs and EPs

Needs the Optimization Toolbox (for linprog).

%% Elementary flux modes (EFMs) and extreme pathways of a small network
% The network is that of Figure 9.2 of the book. A and C can be exchanged
% with the surroundings (v1, v4r), as can F and G (v10, v11); v3r and v4r
% are reversible, and every other reaction is irreversible.
%
% An EFM is a steady-state flux distribution that uses a minimal set of
% reactions (book §9.8): no smaller set of reactions can carry a steady
% flux. For a network this small, we can apply the definition directly.
% For every set of reactions, we ask whether the stoichiometric matrix,
% restricted to those reactions, has exactly one steady state (up to
% scaling) that uses all of them, with every irreversible reaction running
% forwards. Real networks need cleverer algorithms, such as the double
% description method of efmtool, because the number of sets doubles with
% every reaction.
% Requires: Optimization Toolbox (for linprog).

reactions = {'v1', 'v2', 'v3r', 'v4r', 'v5', 'v6', 'v7', 'v8', 'v9', 'v10', ...
             'v11'};
reversible = endsWith(reactions, 'r');
S = [
  % v1 v2 v3r v4r v5 v6 v7 v8 v9 v10 v11
     1 -1  0   0   0  0  0  0  0  0   0    % A
     0  1 -1   0  -1  0  0  0  0  0   0    % B
     0  0  1  -1   0  0  0  0 -1  0   0    % C
     0  0  0   0   1 -1  0 -1  0  0   0    % D
     0  0  0   0   0  1 -1  0  0  0   0    % E
     0  0  0   0   0  0  0  0  1 -1   0    % F
     0  0  0   0   0  0  1  2  1  0  -1];  % G
n = numel(reactions);

modes = zeros(0, n);
for mask = 1:2^n - 1
    support = logical(bitget(mask, 1:n));
    K = null(S(:, support));
    if size(K, 2) ~= 1, continue; end   % no steady state, or not a minimal one
    v = zeros(1, n);
    v(support) = K;
    if any(abs(v(support)) < 1e-9), continue; end   % a reaction is unused
    for sign = [1, -1]                  % a mode and its reverse
        w = sign * v;
        if all(w(~reversible) >= -1e-9)
            modes(end + 1, :) = w / min(abs(w(support))); %#ok<SAGROW>
        end
    end
end
modes = round(modes, 9) + 0;              % + 0 turns -0 into 0

% Systemic independence: is a mode a non-negative combination of the others?
extreme = false(size(modes, 1), 1);
opts = optimoptions('linprog', 'Display', 'none');
for i = 1:size(modes, 1)
    others = modes([1:i - 1, i + 1:end], :)';
    [~, ~, exitflag] = linprog(zeros(size(others, 2), 1), [], [], others, ...
        modes(i, :)', zeros(size(others, 2), 1), [], opts);
    extreme(i) = exitflag ~= 1;         % infeasible: not a combination
end

% Number the modes as the book does: extreme pathways first, the mode
% that only converts A to C first in each group, then by the last
% reaction used before v11 (v10, then v8, then v7)
keys = [~extreme, modes(:, 11) ~= 0, -abs(modes(:, 10:-1:5))];
[~, order] = sortrows(keys);
modes = modes(order, :); extreme = extreme(order);

% Yield of G on C, for the modes that take up C (v4r < 0)
fprintf(['%d elementary flux modes, %d of them extreme pathways ' ...
    '(marked *):\n'], size(modes, 1), sum(extreme));
fprintf('      %s   G/C\n', sprintf('%5s', reactions{:}));
yields = nan(1, size(modes, 1));     % NaN: the mode takes up no C
marks = {' ', '*'};
for k = 1:size(modes, 1)
    e = modes(k, :);
    line = sprintf('%2d%s   %s', k, marks{extreme(k) + 1}, ...
        sprintf('%5.0f', e));
    if e(4) < 0
        yields(k) = e(11) / -e(4);
        line = [line, sprintf('  %4.1f', yields(k))]; %#ok<AGROW>
    end
    fprintf('%s\n', line);
end

%% Plot: the modes as a matrix
fig = figure('Position', [100 100 700 360]);
imagesc(modes, [-2 2]);
colormap(sbp.colormap('RdBu_r'));
[rows, cols] = find(modes ~= 0);
for k = 1:numel(rows)   % white text on the dark cells
    z = modes(rows(k), cols(k));
    if abs(z) > 1.5, colour = 'white'; else, colour = 'black'; end
    text(cols(k), rows(k), sprintf('%.0f', z), ...
        'HorizontalAlignment', 'center', 'FontSize', 9, 'Color', colour);
end
labels = arrayfun(@(k) sprintf('EFM %d%s', k, marks{extreme(k) + 1}), ...
    1:size(modes, 1), 'UniformOutput', false);
set(gca, 'XTick', 1:n, 'XTickLabel', reactions, ...
    'YTick', 1:size(modes, 1), 'YTickLabel', strtrim(labels), ...
    'TickDir', 'out');
title('Elementary flux modes (* extreme pathways)');
sbp.save_figure(fig, mfilename('fullpath'), 'fig-efms');

results.reactions = reactions;
results.efms = modes;
results.extreme = extreme';
results.yield_G_on_C = yields;
sbp.save_results(mfilename('fullpath'), results);

Needs SciPy.

"""Elementary flux modes (EFMs) and extreme pathways of a small network.

The network is that of Figure 9.2 of the book. A and C can be exchanged
with the surroundings (v1, v4r), as can F and G (v10, v11); v3r and v4r
are reversible, and every other reaction is irreversible.

An EFM is a steady-state flux distribution that uses a minimal set of
reactions (book §9.8): no smaller set of reactions can carry a steady
flux. For a network this small, we can apply the definition directly.
For every set of reactions, we ask whether the stoichiometric matrix,
restricted to those reactions, has exactly one steady state (up to
scaling) that uses all of them, with every irreversible reaction running
forwards. Real networks need cleverer algorithms, such as the double
description method of efmtool, because the number of sets doubles with
every reaction.
"""
from itertools import product
import numpy as np
from scipy.linalg import null_space
from scipy.optimize import linprog
import matplotlib.pyplot as plt
import sbp

reactions = ["v1", "v2", "v3r", "v4r", "v5", "v6", "v7", "v8", "v9", "v10",
             "v11"]
metabolites = ["A", "B", "C", "D", "E", "F", "G"]
reversible = np.array([r.endswith("r") for r in reactions])
S = np.array([
    # v1 v2 v3r v4r v5 v6 v7 v8 v9 v10 v11
    [1, -1,  0,  0,  0,  0,  0,  0,  0,  0,  0],   # A
    [0,  1, -1,  0, -1,  0,  0,  0,  0,  0,  0],   # B
    [0,  0,  1, -1,  0,  0,  0,  0, -1,  0,  0],   # C
    [0,  0,  0,  0,  1, -1,  0, -1,  0,  0,  0],   # D
    [0,  0,  0,  0,  0,  1, -1,  0,  0,  0,  0],   # E
    [0,  0,  0,  0,  0,  0,  0,  0,  1, -1,  0],   # F
    [0,  0,  0,  0,  0,  0,  1,  2,  1,  0, -1],   # G
], dtype=float)
n = len(reactions)

modes = []
for mask in product([False, True], repeat=n):
    support = np.array(mask)
    if not support.any():
        continue
    K = null_space(S[:, support])
    if K.shape[1] != 1:              # no steady state, or not a minimal one
        continue
    v = np.zeros(n)
    v[support] = K[:, 0]
    if np.any(np.abs(v[support]) < 1e-9):
        continue                     # some reaction in the set is unused
    for sign in (1, -1):             # a mode and its reverse
        w = sign * v
        if np.all(w[~reversible] >= -1e-9):
            modes.append(w / np.min(np.abs(w[support])))
modes = np.round(np.array(modes), 9) + 0.0          # + 0.0 turns -0 into 0

# Systemic independence: is a mode a non-negative combination of the others?
extreme = []
for i, e in enumerate(modes):
    others = np.delete(modes, i, axis=0).T
    res = linprog(np.zeros(others.shape[1]), A_eq=others, b_eq=e,
                  bounds=(0, None), method="highs")
    extreme.append(res.status != 0)  # infeasible: not a combination
extreme = np.array(extreme)

# Number the modes as the book does: extreme pathways first, the mode
# that only converts A to C first in each group, then by the last
# reaction used before v11 (v10, then v8, then v7)
keys = ([-np.abs(modes[:, j]) for j in range(4, 10)]
        + [modes[:, 10] != 0, ~extreme])
order = np.lexsort(keys)          # the last key sorts first
modes, extreme = modes[order], extreme[order]

# Yield of G on C, for the modes that take up C (v4r < 0)
print(f"{len(modes)} elementary flux modes, {extreme.sum()} of them extreme "
      "pathways (marked *):")
print("      " + " ".join(f"{r:>4s}" for r in reactions) + "   G/C")
yields = []
for k, (e, x) in enumerate(zip(modes, extreme), start=1):
    y = e[10] / -e[3] if e[3] < 0 else None
    yields.append(y)
    print(f"{k:2d}{'*' if x else ' '}   " + " ".join(f"{z:4.0f}" for z in e)
          + (f"  {y:4.1f}" if y is not None else ""))

# --- Plot: the modes as a matrix
sbp.style()
fig, ax = plt.subplots(figsize=(7, 3.6))
ax.imshow(modes, cmap="RdBu_r", vmin=-2, vmax=2, aspect="auto")
for (i, j), z in np.ndenumerate(modes):
    if z != 0:   # white text on the dark cells
        ax.text(j, i, f"{z:.0f}", ha="center", va="center", fontsize=9,
                color="white" if abs(z) > 1.5 else "black")
ax.set_xticks(range(n), reactions)
labels = [f"EFM {k + 1}{'*' if x else ''}" for k, x in enumerate(extreme)]
ax.set_yticks(range(len(modes)), labels)
ax.set_title("Elementary flux modes (* extreme pathways)")
sbp.save_figure(fig, __file__, "fig-efms")

sbp.save_results(__file__, {
    "reactions": reactions, "efms": modes, "extreme": extreme,
    "yield_G_on_C": yields,
})
sbp.show()

The code finds the seven EFMs of Figure 9.2, numbered as in the book, and confirms that four of them (\(EFM1^*\) to \(EFM4^*\)) are extreme pathways. \(EFM5\), \(EFM6\) and \(EFM7\) are each the sum of \(EFM1^*\) and one of the others: in every such sum, the flux through \(v_{4r}\) cancels, and in \(EFM6\) and \(EFM7\) that through \(v_{3r}\) cancels as well. Note that this approach tests all \(2^{11} = 2048\) sets of reactions. The number of sets doubles with every reaction added, so even the E. coli core model, with 95 reactions, is far out of reach. Practical tools, such as efmtool (Terzer and Stelling 2008), use the double description method instead, and can enumerate the very large numbers of EFMs of networks of that size.

9.8.2 Applications

A very interesting application of EFMs is the calculation of maximal molar yields. The yield of G on C is simply the ratio of \(v_{11}\) to the uptake of C through \(v_{4r}\), for each EFM that takes up C. \(EFM3^*\), which runs D to G through \(v_8\), gives two moles of G per mole of C, twice the yield of \(EFM2^*\) and \(EFM4^*\). When C is the only substrate (\(v_1 = 0\)), every steady state of the network is a non-negative combination of \(EFM2^*\), \(EFM3^*\) and \(EFM4^*\), so no flux distribution can do better than the best of them: two moles of G per mole of C is the maximal yield of this network on C. (With A also available, \(EFM5\) to \(EFM7\) make G with no C at all, and the yield on C is no longer a meaningful measure.)

Exercises

  1. Use the linear version of MoMA, which minimises \(\sum_j |v_j - w_j|\), and compare its predictions with the quadratic version. (Write \(|v_j - w_j|\) with auxiliary variables, as in parsimonious FBA.) Why can its solution be non-unique?
  2. MoMA’s predictions depend on the reference \(\mathbf{w}\). Repeat the comparison with the parsimonious FBA solution (Chapter 8, §8.8.5) as reference. Which predictions change? (Book Exercise 9.1 asks how the reference should be chosen when wild-type fluxes have been measured, all or some of them; see also §9.1.1.)
  3. In dynamic FBA, raise the oxygen limit to 20 and then to 25 mmol/gDW/h. How do the acetate peak and the total biomass change? At what limit does acetate disappear altogether?
  4. Repeat the dynamic FBA simulation with step sizes of 0.1 and 0.5 h. How large can the step be before the results change noticeably?
  5. Simulate a fed-batch culture by adding glucose at a constant rate after the first 6 hours. Can you choose a feeding rate that avoids acetate production?
  6. Book Exercise 9.7: start from 0.025 g/L of cells in 15 mM glucose, with glucose and oxygen uptake both limited to 10 mmol/gDW/h, and follow glucose, acetate and formate for 8 hours. At this oxygen limit, FVA shows that the secretion rates of acetate and formate are not unique at maximum growth. How would you make the simulation give the same answer in any solver?
  7. Book Exercise 9.6, which we took up in §9.3.1, can also be approached by hand. Propose your own set of three deletions for anaerobic lactate production, and check it with FBA and FVA: what is the growth rate, and the range of lactate secretion at maximum growth? Is your design growth-coupled?

Going further

MoMA, ROOM and OptKnock are only a few of the many methods that predict how fluxes respond to perturbations; others integrate regulatory rules (rFBA, book §9.4.1) or build tissue-specific models from omic data (§9.4.3). The COBRA Toolbox implements the static-optimisation dFBA in dynamicFBA.m. Dynamic FBA has also been extended to communities of several species growing together; Chapter 11 builds a community model.