8 Introduction to constraint-based modelling
Kinetic models need rate laws and parameters that are rarely known for more than a handful of reactions. Constraint-based modelling sidesteps this. It asks only for the stoichiometry of a metabolic network, and a few bounds on the fluxes, and then asks: of all the flux distributions the network can support at steady state, which ones are possible, and which one is best for a given objective, such as growth?
This chapter works through flux balance analysis (FBA) and flux variability analysis (FVA), first on a small toy network that you can check by hand, and then on a real metabolic model of E. coli.
8.1 What are constraints?
8.1.1 Types of constraints
There is no code for this section; see the book.
8.1.2 Mathematical representation of constraints
There is no code for this section; see the book.
8.1.3 Why are constraints useful?
There is no code for this section; see the book.
8.2 The stoichiometric matrix
We use the small network of the book’s Figure 8.1 and Table 8.2: eight metabolites, seven internal reactions, two exchange reactions that connect the cell to its surroundings, and a “biomass” reaction that drains the building blocks the cell needs to grow.
| Reaction | Equation | Flux | Bounds |
|---|---|---|---|
| R1 | A → ATP + B | \(v_1\) | [0, 1000] |
| R2 | A → C | \(v_2\) | [0, 1000] |
| R3 | C → ATP + B | \(v_3\) | [0, 1000] |
| R4 | B \(\rightleftharpoons\) 2 D | \(v_4\) | [−1000, 1000] |
| R5 | B → F | \(v_5\) | [0, 1000] |
| R6 | D \(\rightleftharpoons\) E | \(v_6\) | [−1000, 1000] |
| R7 | D + ATP → G | \(v_7\) | [0, 1000] |
| E1 | → A | \(b_1\) | [0, 1000] |
| E2 | E \(\rightleftharpoons\) | \(b_2\) | [−1000, 1000] |
| Biomass | F + 2 G + 10 ATP → | \(v_\text{bio}\) | [0, 1000] |
Each reaction becomes a column of the stoichiometric matrix \(\mathbf{S}\), with one row per metabolite: negative entries for what a reaction consumes and positive entries for what it produces. At steady state, every metabolite is produced exactly as fast as it is consumed, so any feasible flux vector \(\mathbf{v}\) satisfies
\[ \mathbf{S}\mathbf{v} = \mathbf{0}. \]
With eight equations and ten unknowns, this system has infinitely many solutions. FBA picks one by optimising an objective, here the biomass flux.
8.3 Steady-state mass balance: Flux Balance Analysis (FBA)
There is no code for this section; see the book.
8.4 The objective function
8.4.1 The biomass objective function
There is no code for this section; see the book.
8.5 Optimisation to compute flux distribution
There is no code for this section; see the book.
8.6 An illustration
FBA is a linear program (LP):
\[ \max_{\mathbf{v}}\ \mathbf{c}^\top\mathbf{v} \quad\text{subject to}\quad \mathbf{S}\mathbf{v} = \mathbf{0},\qquad \mathbf{v}_\text{lb} \le \mathbf{v} \le \mathbf{v}_\text{ub}, \]
where \(\mathbf{c}\) picks out the objective; it has a 1 in the position of \(v_\text{bio}\) and zeros elsewhere. Any LP solver will do. Both linprog functions minimise, so we minimise \(-\mathbf{c}^\top\mathbf{v}\) instead.
Needs the Optimization Toolbox (for linprog).
%% Flux balance analysis of a toy metabolic network
% The network is the one in Fig. 8.1 / Table 8.2 of the book: 8 metabolites,
% 7 internal reactions, 2 exchange reactions and a 'biomass' reaction.
% FBA is solved directly as a linear program with linprog.
% Requires: Optimization Toolbox (for linprog).
%% The network
rxns = {'v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'b1', 'b2', 'vbio'};
mets = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'ATP'};
% Stoichiometric matrix: one row per metabolite, one column per reaction
% v1 v2 v3 v4 v5 v6 v7 b1 b2 vbio
S = [-1 -1 0 0 0 0 0 1 0 0 % A
1 0 1 -1 -1 0 0 0 0 0 % B
0 1 -1 0 0 0 0 0 0 0 % C
0 0 0 2 0 -1 -1 0 0 0 % D
0 0 0 0 0 1 0 0 -1 0 % E
0 0 0 0 1 0 0 0 0 -1 % F
0 0 0 0 0 0 1 0 0 -2 % G
1 0 1 0 0 0 -1 0 0 -10]; % ATP
% Bounds (mmol/gDW/h): reversible reactions v4, v6 and b2 may run backwards
lb = [0 0 0 -1000 0 -1000 0 0 -1000 0]';
ub = 1000 * ones(numel(rxns), 1);
% Objective: maximise the biomass flux vbio
c = zeros(numel(rxns), 1);
c(strcmp(rxns, 'vbio')) = 1;
%% Solve: max c'v s.t. Sv = 0, lb <= v <= ub
% linprog minimises, so we minimise -c'v
opts = optimoptions('linprog', 'Display', 'none');
beq = zeros(numel(mets), 1);
[v, fval, exitflag] = linprog(-c, [], [], S, beq, lb, ub, opts);
growth = -fval;
fprintf('Exit flag: %d (1 means optimal)\n', exitflag);
fprintf('Maximum biomass flux vbio = %g\n', growth);
for k = 1:numel(rxns)
fprintf(' %4s = %8.1f\n', rxns{k}, v(k));
end
fprintf('Largest mass-balance violation |Sv| = %.1e\n', max(abs(S*v)));
%% Plot the flux distribution
fig = figure;
bar(categorical(rxns, rxns), v, 'FaceColor', [0.000 0.447 0.698], ...
'EdgeColor', 'none');
ylim([0, 1.05 * max(v)]); % a little room above the tallest bar
set(gca, 'TickDir', 'out');
xlabel('Reaction');
ylabel('Flux (mmol/gDW/h)');
title(sprintf('An optimal flux distribution (vbio = %g)', growth));
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-toy-fba');
results.growth = growth;
results.fluxes = cell2struct(num2cell(v), rxns, 1);
results.max_mass_balance_error = max(abs(S*v));
sbp.save_results(mfilename('fullpath'), results);
Needs SciPy (for linprog).
"""Flux balance analysis of a toy metabolic network.
The network is the one in Fig. 8.1 / Table 8.2 of the book: 8 metabolites,
7 internal reactions, 2 exchange reactions and a 'biomass' reaction.
FBA is solved directly as a linear program with SciPy.
"""
import numpy as np
from scipy.optimize import linprog
import matplotlib.pyplot as plt
import sbp
# --- The network
rxns = ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "b1", "b2", "vbio"]
mets = ["A", "B", "C", "D", "E", "F", "G", "ATP"]
# Stoichiometric matrix: one row per metabolite, one column per reaction
# v1 v2 v3 v4 v5 v6 v7 b1 b2 vbio
S = np.array([[-1, -1, 0, 0, 0, 0, 0, 1, 0, 0], # A
[ 1, 0, 1, -1, -1, 0, 0, 0, 0, 0], # B
[ 0, 1, -1, 0, 0, 0, 0, 0, 0, 0], # C
[ 0, 0, 0, 2, 0, -1, -1, 0, 0, 0], # D
[ 0, 0, 0, 0, 0, 1, 0, 0, -1, 0], # E
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, -1], # F
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, -2], # G
[ 1, 0, 1, 0, 0, 0, -1, 0, 0, -10]]) # ATP
# Bounds (mmol/gDW/h): reversible reactions v4, v6 and b2 may run backwards
lb = np.array([0, 0, 0, -1000, 0, -1000, 0, 0, -1000, 0])
ub = np.full(len(rxns), 1000)
# Objective: maximise the biomass flux vbio
c = np.zeros(len(rxns))
c[rxns.index("vbio")] = 1
# --- Solve: max c'v s.t. Sv = 0, lb <= v <= ub
# linprog minimises, so we minimise -c'v
res = linprog(-c, A_eq=S, b_eq=np.zeros(len(mets)),
bounds=list(zip(lb, ub)), method="highs")
v = res.x + 0.0 # (+ 0.0 turns any -0.0 into 0.0 for printing)
growth = -res.fun
print(f"Status: {res.message}")
print(f"Maximum biomass flux vbio = {growth:g}")
for r, flux in zip(rxns, v):
print(f" {r:>4s} = {flux:8.1f}")
print(f"Largest mass-balance violation |Sv| = {np.abs(S @ v).max():.1e}")
# --- Plot the flux distribution
sbp.style()
fig, ax = plt.subplots()
ax.bar(rxns, v, color="#0072B2")
ax.set_xlabel("Reaction")
ax.set_ylabel("Flux (mmol/gDW/h)")
ax.set_title(f"An optimal flux distribution (vbio = {growth:g})")
sbp.save_figure(fig, __file__, "fig-toy-fba")
sbp.save_results(__file__, {
"growth": growth,
"fluxes": dict(zip(rxns, v)),
"max_mass_balance_error": np.abs(S @ v).max(),
})
sbp.show()
The maximum biomass flux is \(v_\text{bio} = 50\), the same as in the book (Eq. 8.9). What limits it? Follow the stoichiometry: every unit of biomass needs 2 G, and so 2 units of flux through R7, and 10 ATP. Balancing ATP, B and D in turn shows that \(v_4 = 11\,v_\text{bio}\) and \(v_6 = 20\,v_\text{bio}\), so the upper bound of 1000 on \(v_6\) (and on \(b_2\), which must equal \(v_6\)) caps growth at 50.
R1 and the route R2 → R3 both turn A into ATP + B, so the cell can split the 600 units of A between them in any proportion and grow equally well. The book shows two such solutions (Eqs. 8.9 and 8.10). Which one you get depends on the solver, and the MATLAB and Python versions above may print different values of \(v_1\), \(v_2\) and \(v_3\). Both are correct. This is why our automated checks compare only the growth rate for this example, and why the next section matters.
A genome-scale example: E. coli core
The same ideas carry over unchanged to real networks. The E. coli core model (Orth et al. 2010) has 95 reactions, 72 metabolites and 137 genes, covering glycolysis, the pentose phosphate pathway, the TCA cycle and oxidative phosphorylation. At this scale we no longer write \(\mathbf{S}\) by hand. A standard model file (SBML) is read by a modelling package, COBRApy in Python and the COBRA Toolbox in MATLAB, which builds and solves the LP for us.
Note two things before we read the code:
- Exchange reactions such as
EX_glc__D_e(glucose) andEX_o2_e(oxygen) are written as secretion, so uptake is a negative flux. Allowing up to 10 mmol/gDW/h of glucose uptake therefore means setting the lower bound to −10. - The model includes an ATP maintenance reaction,
ATPM, with a lower bound of 8.39 mmol/gDW/h: ATP the cell must spend just to stay alive, whether it grows or not.
Needs the COBRA Toolbox; run initCobraToolbox once per session before this script.
%% FBA on the E. coli core metabolic model with the COBRA Toolbox
% 1. Predict growth with and without oxygen.
% 2. Vary the glucose uptake rate and watch growth respond.
% Requires: COBRA Toolbox (run initCobraToolbox once per session first).
% The .mat file is the same model as the SBML file the Python version reads
% (made by tools/make_mat_model.py); reading SBML in MATLAB needs libSBML.
model = readCbModel(fullfile(sbp.data_dir(), 'e_coli_core.mat'));
fprintf('%d reactions, %d metabolites, %d genes\n', ...
numel(model.rxns), numel(model.mets), numel(model.genes));
fprintf('Objective: %s\n', strjoin(model.rxns(model.c ~= 0), ', '));
%% 1. Aerobic vs anaerobic growth
% Default medium: glucose uptake up to 10 mmol/gDW/h, oxygen unlimited.
% Uptake is a negative flux through an exchange reaction, hence lower bounds.
aerobic = optimizeCbModel(model, 'max');
fprintf('Aerobic growth rate: %.4f /h\n', aerobic.f);
modelAnaerobic = changeRxnBounds(model, 'EX_o2_e', 0, 'l'); % no oxygen uptake
anaerobic = optimizeCbModel(modelAnaerobic, 'max');
fprintf('Anaerobic growth rate: %.4f /h\n', anaerobic.f);
%% 2. Growth as a function of glucose uptake
uptake = 0:0.5:20; % mmol/gDW/h
growthAer = growth_curve(model, 1000, uptake); % O2 effectively unlimited
growthO2_10 = growth_curve(model, 10, uptake); % O2 uptake at most 10
growthAnaer = growth_curve(model, 0, uptake); % no O2
%% Plot
blue = [0.000 0.447 0.698];
green = [0.000 0.620 0.451];
orange = [0.902 0.624 0.000];
fig = figure;
plot(uptake, growthAer, 'o-', 'Color', blue, ...
'MarkerFaceColor', blue, 'MarkerSize', 4);
hold on
plot(uptake, growthO2_10, '^-', 'Color', green, ...
'MarkerFaceColor', green, 'MarkerSize', 4);
plot(uptake, growthAnaer, 's-', 'Color', orange, ...
'MarkerFaceColor', orange, 'MarkerSize', 4);
xlabel('Maximum glucose uptake (mmol/gDW/h)');
ylabel('Growth rate (1/h)');
title('E. coli core: growth vs glucose uptake');
legend({'O_2 unlimited', 'O_2 uptake \leq 10', 'no O_2'}, ...
'Location', 'northwest', 'Box', 'off');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-ecoli-glucose');
results.n_reactions = numel(model.rxns);
results.growth_aerobic = aerobic.f;
results.growth_anaerobic = anaerobic.f;
results.glucose_uptake = uptake;
results.growth_vs_glucose_aerobic = growthAer;
results.growth_vs_glucose_o2_10 = growthO2_10;
results.growth_vs_glucose_anaerobic = growthAnaer;
sbp.save_results(mfilename('fullpath'), results);
%% Local function
function growth = growth_curve(model, o2UptakeLimit, uptake)
% Maximum growth for each glucose uptake limit; NaN where the LP is infeasible.
model = changeRxnBounds(model, 'EX_o2_e', -o2UptakeLimit, 'l');
growth = nan(size(uptake));
for k = 1:numel(uptake)
m = changeRxnBounds(model, 'EX_glc__D_e', -uptake(k), 'l');
sol = optimizeCbModel(m, 'max');
if sol.stat == 1 % 1 means an optimal solution was found
growth(k) = sol.f;
end
end
end
Needs COBRApy.
"""FBA on the E. coli core metabolic model with COBRApy.
1. Predict growth with and without oxygen.
2. Vary the glucose uptake rate and watch growth respond.
"""
import math
import numpy as np
import matplotlib.pyplot as plt
import cobra
import sbp
model = cobra.io.read_sbml_model(str(sbp.DATA / "e_coli_core.xml"))
print(f"{model.id}: {len(model.reactions)} reactions, "
f"{len(model.metabolites)} metabolites, {len(model.genes)} genes")
objective = cobra.util.solver.linear_reaction_coefficients(model)
print("Objective:", ", ".join(r.id for r in objective))
# --- 1. Aerobic vs anaerobic growth
# Default medium: glucose uptake up to 10 mmol/gDW/h, oxygen unlimited.
# Uptake is a negative flux through an exchange reaction, hence lower bounds.
aerobic = model.optimize()
print(f"Aerobic growth rate: {aerobic.objective_value:.4f} /h")
with model: # changes inside 'with' are undone afterwards
model.reactions.EX_o2_e.lower_bound = 0 # no oxygen uptake
anaerobic = model.optimize()
print(f"Anaerobic growth rate: {anaerobic.objective_value:.4f} /h")
# --- 2. Growth as a function of glucose uptake
uptake = np.arange(0, 20.5, 0.5) # mmol/gDW/h
def growth_curve(o2_uptake_limit):
"""Maximum growth for each glucose uptake limit; NaN where infeasible."""
growth = []
with model:
model.reactions.EX_o2_e.lower_bound = -o2_uptake_limit
for u in uptake:
model.reactions.EX_glc__D_e.lower_bound = -u
# slim_optimize returns NaN when the LP is infeasible
growth.append(model.slim_optimize(error_value=math.nan))
return np.array(growth)
growth_aer = growth_curve(1000) # oxygen effectively unlimited
growth_o2_10 = growth_curve(10) # oxygen uptake at most 10 mmol/gDW/h
growth_anaer = growth_curve(0) # no oxygen
# --- Plot
sbp.style()
fig, ax = plt.subplots()
ax.plot(uptake, growth_aer, "o-", color="#0072B2", ms=4,
label="O$_2$ unlimited")
ax.plot(uptake, growth_o2_10, "^-", color="#009E73", ms=4,
label="O$_2$ uptake ≤ 10")
ax.plot(uptake, growth_anaer, "s-", color="#E69F00", ms=4,
label="no O$_2$")
ax.set_xlabel("Maximum glucose uptake (mmol/gDW/h)")
ax.set_ylabel("Growth rate (1/h)")
ax.set_title("E. coli core: growth vs glucose uptake")
ax.legend(frameon=False)
sbp.save_figure(fig, __file__, "fig-ecoli-glucose")
sbp.save_results(__file__, {
"n_reactions": len(model.reactions),
"growth_aerobic": aerobic.objective_value,
"growth_anaerobic": anaerobic.objective_value,
"glucose_uptake": uptake,
"growth_vs_glucose_aerobic": growth_aer,
"growth_vs_glucose_o2_10": growth_o2_10,
"growth_vs_glucose_anaerobic": growth_anaer,
})
sbp.show()
With glucose uptake capped at 10 mmol/gDW/h, the predicted growth rate is 0.874 h−1 with oxygen and 0.212 h−1 without it: aerobic respiration extracts far more ATP from each glucose than fermentation does. The growth curves show three more things.
- At zero glucose the problem is infeasible. With no carbon source, nothing can meet the ATP maintenance demand, so no flux vector satisfies all the constraints, and FBA cannot return any growth rate, even zero. The curves start only once glucose uptake covers maintenance, which takes more glucose without oxygen than with it.
- When glucose is the only limit, growth rises in a straight line. This is a general property of linear programs: scaling the one binding constraint scales the solution.
- When oxygen is also limited (the middle curve), the line bends where oxygen runs out, at about 4 mmol/gDW/h of glucose, and beyond it each extra unit of glucose buys less growth. A different constraint has become binding.
8.7 Flux Variability Analysis (FVA)
FVA maps out all the optimal (or near-optimal) solutions at once. First solve the FBA problem to get the optimal objective \(f^*\). Then, for each reaction \(j\) in turn, find the smallest and the largest flux it can carry while growth stays at least a fraction \(\alpha\) of the optimum:
\[ \min_{\mathbf{v}} / \max_{\mathbf{v}}\ v_j \quad\text{subject to}\quad \mathbf{S}\mathbf{v} = \mathbf{0},\quad \mathbf{v}_\text{lb} \le \mathbf{v} \le \mathbf{v}_\text{ub},\quad \mathbf{c}^\top\mathbf{v} \ge \alpha f^*. \]
That is two LPs per reaction. Let us run FVA on the toy network at \(\alpha = 1\) (exactly optimal growth) and \(\alpha = 0.9\).
Needs the Optimization Toolbox (for linprog).
%% Flux variability analysis (FVA) of the toy metabolic network
% FBA gives one optimal flux distribution, but often many exist. FVA finds,
% for every reaction, the smallest and largest flux compatible with
% (a chosen fraction of) the optimal growth rate.
% Requires: Optimization Toolbox (for linprog).
%% The network (same as toy_fba.m; book Fig. 8.1)
rxns = {'v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'b1', 'b2', 'vbio'};
% v1 v2 v3 v4 v5 v6 v7 b1 b2 vbio
S = [-1 -1 0 0 0 0 0 1 0 0 % A
1 0 1 -1 -1 0 0 0 0 0 % B
0 1 -1 0 0 0 0 0 0 0 % C
0 0 0 2 0 -1 -1 0 0 0 % D
0 0 0 0 0 1 0 0 -1 0 % E
0 0 0 0 1 0 0 0 0 -1 % F
0 0 0 0 0 0 1 0 0 -2 % G
1 0 1 0 0 0 -1 0 0 -10]; % ATP
lb = [0 0 0 -1000 0 -1000 0 0 -1000 0]';
ub = 1000 * ones(numel(rxns), 1);
n = numel(rxns);
c = zeros(n, 1);
c(strcmp(rxns, 'vbio')) = 1;
opts = optimoptions('linprog', 'Display', 'none');
%% Step 1: FBA, to find the optimal growth rate f*
[~, fval] = linprog(-c, [], [], S, zeros(size(S, 1), 1), lb, ub, opts);
f_star = -fval;
%% Step 2: FVA at 100% and at 90% of the optimum
[vmin100, vmax100] = fva(S, lb, ub, c, 1.0 * f_star, opts);
[vmin90, vmax90] = fva(S, lb, ub, c, 0.9 * f_star, opts);
fprintf('Optimal growth f* = %g\n', f_star);
fprintf('%5s %8s %8s (at 100%% of f*)\n', 'rxn', 'min', 'max');
for j = 1:n
fprintf('%5s %8.1f %8.1f\n', rxns{j}, vmin100(j), vmax100(j));
end
%% Plot: flux ranges at 100% and 90% of optimal growth
blue = [0.000 0.447 0.698];
orange = [0.902 0.624 0.000];
fig = figure;
hold on
y = 1:n;
for j = 1:n
plot([vmin90(j) vmax90(j)], y(j) + [0.15 0.15], '-', ...
'Color', orange, 'LineWidth', 6);
plot([vmin100(j) vmax100(j)], y(j) - [0.15 0.15], '-', ...
'Color', blue, 'LineWidth', 6);
end
% Fixed fluxes have zero width, so mark both ends
plot(vmin100, y - 0.15, '|', 'Color', blue, 'MarkerSize', 10);
plot(vmin90, y + 0.15, '|', 'Color', orange, 'MarkerSize', 10);
set(gca, 'YTick', y, 'YTickLabel', rxns, 'YDir', 'reverse');
ylim([0.5, n + 0.5]);
xlabel('Flux (mmol/gDW/h)');
title('Flux variability analysis');
h = [plot(NaN, NaN, '-', 'Color', orange, 'LineWidth', 6), ...
plot(NaN, NaN, '-', 'Color', blue, 'LineWidth', 6)];
legend(h, {'90% of optimum', '100% of optimum'}, ...
'Location', 'south', 'Box', 'off');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-toy-fva');
results.growth = f_star;
results.fva100.min = cell2struct(num2cell(vmin100), rxns, 1);
results.fva100.max = cell2struct(num2cell(vmax100), rxns, 1);
results.fva90.min = cell2struct(num2cell(vmin90), rxns, 1);
results.fva90.max = cell2struct(num2cell(vmax90), rxns, 1);
sbp.save_results(mfilename('fullpath'), results);
%% Local function
function [vmin, vmax] = fva(S, lb, ub, c, f_min, opts)
% Min and max of every flux, subject to growth c'v >= f_min.
% The extra constraint is written as -c'v <= -f_min.
n = numel(lb);
vmin = zeros(n, 1);
vmax = zeros(n, 1);
beq = zeros(size(S, 1), 1);
for j = 1:n
e = zeros(n, 1);
e(j) = 1;
[~, vmin(j)] = linprog(e, -c', -f_min, S, beq, lb, ub, opts);
[~, fmax] = linprog(-e, -c', -f_min, S, beq, lb, ub, opts);
vmax(j) = -fmax;
end
end
Needs SciPy (for linprog).
"""Flux variability analysis (FVA) of the toy metabolic network.
FBA gives one optimal flux distribution, but often many exist. FVA finds,
for every reaction, the smallest and largest flux compatible with
(a chosen fraction of) the optimal growth rate.
"""
import numpy as np
from scipy.optimize import linprog
import matplotlib.pyplot as plt
import sbp
# --- The network (same as toy_fba.py; book Fig. 8.1)
rxns = ["v1", "v2", "v3", "v4", "v5", "v6", "v7", "b1", "b2", "vbio"]
# v1 v2 v3 v4 v5 v6 v7 b1 b2 vbio
S = np.array([[-1, -1, 0, 0, 0, 0, 0, 1, 0, 0], # A
[ 1, 0, 1, -1, -1, 0, 0, 0, 0, 0], # B
[ 0, 1, -1, 0, 0, 0, 0, 0, 0, 0], # C
[ 0, 0, 0, 2, 0, -1, -1, 0, 0, 0], # D
[ 0, 0, 0, 0, 0, 1, 0, 0, -1, 0], # E
[ 0, 0, 0, 0, 1, 0, 0, 0, 0, -1], # F
[ 0, 0, 0, 0, 0, 0, 1, 0, 0, -2], # G
[ 1, 0, 1, 0, 0, 0, -1, 0, 0, -10]]) # ATP
lb = np.array([0, 0, 0, -1000, 0, -1000, 0, 0, -1000, 0])
ub = np.full(len(rxns), 1000)
bounds = list(zip(lb, ub))
n = len(rxns)
c = np.zeros(n)
c[rxns.index("vbio")] = 1
zeros = np.zeros(S.shape[0])
# --- Step 1: FBA, to find the optimal growth rate f*
fba = linprog(-c, A_eq=S, b_eq=zeros, bounds=bounds, method="highs")
f_star = -fba.fun
def fva(fraction):
"""Min and max of every flux, subject to growth >= fraction * f*."""
# The extra constraint c'v >= fraction*f*, written as -c'v <= -fraction*f*
A_ub, b_ub = -c[np.newaxis, :], [-fraction * f_star]
vmin, vmax = np.zeros(n), np.zeros(n)
for j in range(n):
e = np.zeros(n)
e[j] = 1
vmin[j] = linprog(e, A_ub=A_ub, b_ub=b_ub, A_eq=S, b_eq=zeros,
bounds=bounds, method="highs").fun
vmax[j] = -linprog(-e, A_ub=A_ub, b_ub=b_ub, A_eq=S, b_eq=zeros,
bounds=bounds, method="highs").fun
return vmin, vmax
# --- Step 2: FVA at 100% and at 90% of the optimum
vmin100, vmax100 = fva(1.0)
vmin90, vmax90 = fva(0.9)
print(f"Optimal growth f* = {f_star:g}")
print(f"{'rxn':>5s} {'min':>8s} {'max':>8s} (at 100% of f*)")
for r, lo, hi in zip(rxns, vmin100, vmax100):
print(f"{r:>5s} {lo:8.1f} {hi:8.1f}")
# --- Plot: flux ranges at 100% and 90% of optimal growth
sbp.style()
fig, ax = plt.subplots()
y = np.arange(n)
ax.hlines(y + 0.15, vmin90, vmax90, color="#E69F00", lw=6,
label="90% of optimum")
ax.hlines(y - 0.15, vmin100, vmax100, color="#0072B2", lw=6,
label="100% of optimum")
# Fixed fluxes have zero width, so mark both ends
ax.plot(vmin100, y - 0.15, "|", color="#0072B2", ms=10)
ax.plot(vmin90, y + 0.15, "|", color="#E69F00", ms=10)
ax.set_yticks(y, rxns)
ax.invert_yaxis()
ax.set_xlabel("Flux (mmol/gDW/h)")
ax.set_title("Flux variability analysis")
ax.legend(loc="lower center", frameon=False)
sbp.save_figure(fig, __file__, "fig-toy-fva")
sbp.save_results(__file__, {
"growth": f_star,
"fva100": {"min": dict(zip(rxns, vmin100)),
"max": dict(zip(rxns, vmax100))},
"fva90": {"min": dict(zip(rxns, vmin90)),
"max": dict(zip(rxns, vmax90))},
})
sbp.show()
At optimal growth, \(v_1\), \(v_2\) and \(v_3\) can each take any value between 0 and 600, while every other flux is fixed. These are exactly the ranges in the book (Eq. 8.12), found by solving the problem of Eq. 8.11 for each flux. Relaxing growth to 90% of the optimum widens the other ranges too, because the reactions that limit growth no longer have to run at their maximum.
8.8 Understanding FBA
8.8.1 Blocked reactions and dead-end metabolites
A reaction is blocked if it cannot carry flux at steady state, whatever the bounds allow. For the small network of Figure 8.3, the reduced row echelon form of \(\mathbf{S}\) (Eq. 8.14) shows this directly: a row with a single non-zero entry forces that flux to zero. Our code finds \(v_3\) and \(b_3\) this way, and confirms them by FVA with no objective. It then looks for dead-end metabolites in the E. coli core model, metabolites that are only produced or only consumed.
Needs the Optimization Toolbox (for linprog; rref is built in); reads the model from data/e_coli_core.mat, so the COBRA Toolbox is not required.
%% Blocked reactions and dead-end metabolites
% 1. The small network of book Figure 8.3 (Eq. 8.13): find its blocked
% reactions from the reduced row echelon form of S (Eq. 8.14), and
% confirm them by FVA.
% 2. The E. coli core model: find dead-end metabolites from the
% stoichiometry alone, and the reactions that cannot carry flux, first
% with every exchange reaction open, then on glucose.
% Requires: Optimization Toolbox (the COBRA Toolbox is not needed).
%% 1. The network of book Figure 8.3
names = {'v1', 'v2', 'v3', 'b1', 'b2', 'b3'};
% v1 v2 v3 b1 b2 b3
S = [-1 0 -1 1 0 0; % A
-1 1 -1 0 0 0; % B
1 -1 0 0 0 0; % C
0 1 0 0 -1 0; % D
0 0 1 0 0 -1]; % E
R = rref(S);
disp('Reduced row echelon form of S (book Eq. 8.14):');
disp(R);
% A row with a single non-zero entry says that flux must be zero
single = sum(R ~= 0, 2) == 1;
[~, col] = max(R(single, :) ~= 0, [], 2);
by_rref = names(col);
[vmin, vmax] = fva(S, zeros(6, 1), 1000 * ones(6, 1));
by_fva = names(abs(vmin) < 1e-9 & abs(vmax) < 1e-9);
fprintf('Blocked, from the RREF: %s; from FVA: %s\n', ...
strjoin(by_rref, ', '), strjoin(by_fva, ', '));
%% 2. The E. coli core model
s = load(fullfile(sbp.data_dir(), 'e_coli_core.mat'));
model = s.e_coli_core;
S = full(model.S); lb = model.lb; ub = model.ub;
rxns = model.rxns; mets = model.mets;
exchange = startsWith(rxns, 'EX_');
% Every exchange reaction open. The ATP maintenance demand (a lower bound
% > 0) is relaxed to 0 here, since it asks for flux rather than allowing it.
lb_open = min(lb, 0);
lb_open(exchange) = -1000;
dead_ends = dead_end_metabolites(S, lb_open, ub, mets);
dead_ends_glucose = dead_end_metabolites(S, lb, ub, mets);
fprintf(['Dead-end metabolites with every exchange open: %d; on ' ...
'glucose: %s\n'], numel(dead_ends), strjoin(dead_ends_glucose, ', '));
[vmin, vmax] = fva(S, lb_open, ub);
blocked = rxns(abs(vmin) < 1e-9 & abs(vmax) < 1e-9);
fprintf('Reactions blocked in every condition: %d\n', numel(blocked));
% No flux on glucose (the model's default medium), at any growth rate
[vmin, vmax] = fva(S, lb, ub);
no_flux = rxns(abs(vmin) < 1e-9 & abs(vmax) < 1e-9);
fprintf('Reactions that cannot carry flux on glucose: %d\n %s\n', ...
numel(no_flux), strjoin(no_flux, ', '));
results.rref = R;
results.blocked_rref = by_rref;
results.blocked_fva = by_fva;
results.dead_ends = dead_ends;
results.dead_ends_glucose = dead_ends_glucose;
results.blocked_core = blocked;
results.no_flux_glucose = no_flux';
sbp.save_results(mfilename('fullpath'), results);
%% Local functions
function [vmin, vmax] = fva(S, lb, ub)
% Smallest and largest value of every flux, with S v = 0 and the bounds
% (no objective constraint).
n = size(S, 2);
opts = optimoptions('linprog', 'Display', 'none');
vmin = zeros(n, 1); vmax = zeros(n, 1);
for j = 1:n
c = zeros(n, 1); c(j) = 1;
[~, vmin(j)] = linprog(c, [], [], S, zeros(size(S, 1), 1), lb, ub, opts);
[~, f] = linprog(-c, [], [], S, zeros(size(S, 1), 1), lb, ub, opts);
vmax(j) = -f;
end
end
function d = dead_end_metabolites(S, lb, ub, mets)
% Metabolites that, given the directions the reactions can run, can only
% ever be produced or only ever be consumed.
can_make = (S > 0 & (ub > 0)') | (S < 0 & (lb < 0)');
can_use = (S < 0 & (ub > 0)') | (S > 0 & (lb < 0)');
d = mets(~(any(can_make, 2) & any(can_use, 2)))';
endNeeds COBRApy, SymPy (for the exact RREF) and SciPy.
"""Blocked reactions and dead-end metabolites.
1. The small network of book Figure 8.3 (Eq. 8.13): find its blocked
reactions from the reduced row echelon form of S (Eq. 8.14), and
confirm them by FVA.
2. The E. coli core model: find dead-end metabolites from the
stoichiometry alone, and the reactions that cannot carry flux, first
with every exchange reaction open, then on glucose.
"""
import numpy as np
import sympy
from scipy.optimize import linprog
import cobra
from cobra.util import create_stoichiometric_matrix
import sbp
def fva(S, lb, ub):
"""Smallest and largest value of every flux, with S v = 0 and the
bounds (no objective constraint), or None if infeasible."""
n = S.shape[1]
vmin, vmax = np.zeros(n), np.zeros(n)
for j in range(n):
c = np.zeros(n)
c[j] = 1
lo = linprog(c, A_eq=S, b_eq=np.zeros(S.shape[0]),
bounds=np.c_[lb, ub], method="highs")
hi = linprog(-c, A_eq=S, b_eq=np.zeros(S.shape[0]),
bounds=np.c_[lb, ub], method="highs")
vmin[j], vmax[j] = lo.fun, -hi.fun
return vmin, vmax
# --- 1. The network of book Figure 8.3
names = ["v1", "v2", "v3", "b1", "b2", "b3"]
# v1 v2 v3 b1 b2 b3
S = np.array([[-1, 0, -1, 1, 0, 0], # A
[-1, 1, -1, 0, 0, 0], # B
[ 1, -1, 0, 0, 0, 0], # C
[ 0, 1, 0, 0, -1, 0], # D
[ 0, 0, 1, 0, 0, -1]]) # E
R, _ = sympy.Matrix(S).rref()
R = np.array(R.tolist(), dtype=float)
print("Reduced row echelon form of S (book Eq. 8.14):")
print(R.astype(int))
# A row with a single non-zero entry says that flux must be zero
by_rref = [names[np.flatnonzero(r)[0]] for r in R
if np.count_nonzero(r) == 1]
vmin, vmax = fva(S, np.zeros(6), np.full(6, 1000.0))
by_fva = [n for n, lo, hi in zip(names, vmin, vmax)
if abs(lo) < 1e-9 and abs(hi) < 1e-9]
print(f"Blocked, from the RREF: {by_rref}; from FVA: {by_fva}")
# --- 2. The E. coli core model
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])
rxns = [r.id for r in model.reactions]
mets = [m.id for m in model.metabolites]
exchange = np.array([r.startswith("EX_") for r in rxns])
def dead_end_metabolites(lb, ub):
"""Metabolites that, given the directions the reactions can run, can
only ever be produced or only ever be consumed."""
can_make = ((S > 0) & (ub > 0)) | ((S < 0) & (lb < 0))
can_use = ((S < 0) & (ub > 0)) | ((S > 0) & (lb < 0))
return [m for m, mk, us in zip(mets, can_make.any(1), can_use.any(1))
if not (mk and us)]
# Every exchange reaction open. The ATP maintenance demand (a lower bound
# > 0) is relaxed to 0 here, since it asks for flux rather than allowing it.
lb_open = np.where(exchange, -1000.0, np.minimum(lb, 0.0))
dead_ends = dead_end_metabolites(lb_open, ub)
dead_ends_glucose = dead_end_metabolites(lb, ub)
print(f"Dead-end metabolites with every exchange open: {len(dead_ends)}; "
f"on glucose: {dead_ends_glucose}")
vmin, vmax = fva(S, lb_open, ub)
blocked = [r for r, lo, hi in zip(rxns, vmin, vmax)
if abs(lo) < 1e-9 and abs(hi) < 1e-9]
print(f"Reactions blocked in every condition: {len(blocked)}")
# No flux on glucose (the model's default medium), at any growth rate
vmin, vmax = fva(S, lb, ub)
no_flux = [r for r, lo, hi in zip(rxns, vmin, vmax)
if abs(lo) < 1e-9 and abs(hi) < 1e-9]
print(f"Reactions that cannot carry flux on glucose: {len(no_flux)}")
print(" " + ", ".join(no_flux))
sbp.save_results(__file__, {
"rref": R, "blocked_rref": by_rref, "blocked_fva": by_fva,
"dead_ends": dead_ends, "dead_ends_glucose": dead_ends_glucose,
"blocked_core": blocked,
"no_flux_glucose": no_flux,
})With every exchange reaction open, the core model has no dead-end metabolites and no blocked reactions. On glucose minimal medium, with the other carbon sources closed, four extracellular metabolites (fructose, fumarate, glutamine and malate) become dead ends, and their exchange and transport reactions, eight in all, can no longer carry flux. Whether a reaction is blocked depends on the medium as much as on the network.
8.8.2 Gaps in metabolic networks
Dead-end metabolites (§8.8.1) are where gap-filling starts: each one marks a reaction that may be missing from the network. Finding the missing reactions needs a database of candidate reactions, which is beyond the scope of these examples.
8.8.3 Multiple solutions
Remember, the toy example of §8.6 has many optimal flux distributions; FVA (§8.7) shows how far each flux can vary among them.
8.8.4 Loops
The network of Figure 8.4 contains a cycle, \(v_3\) and \(v_4\), that is balanced on its own and exchanges nothing with the outside. FVA shows that, at optimal \(b_2\), the cycle can carry anything from 0 to 990, and \(v_1\) anything from 10 to 1000. Such fluxes are not physiological. Minimising the total flux \(\sum_j |v_j|\) at optimal growth removes the cycle and fixes every flux. The code below does this for the toy network, then for the E. coli core model (§8.8.5).
Needs the Optimization Toolbox (for linprog); reads the model from data/e_coli_core.mat, so the COBRA Toolbox is not required.
%% Loops, parsimonious FBA (pFBA), and the pFBA classes of reactions
% 1. The network of book Figure 8.4, which contains a stoichiometrically
% balanced cycle: FVA shows the cycle can carry any flux, and minimising
% the total flux, sum_j |v_j|, removes it.
% 2. The E. coli core model on glucose: classify every internal reaction,
% as in book Section 8.8.5, as essential, pFBA optimal, enzymatically
% less efficient (ELE), metabolically less efficient (MLE), no flux in
% this medium, or blocked.
% Total flux is minimised as a linear programme, with variables t_j >= |v_j|.
% Requires: Optimization Toolbox (the COBRA Toolbox is not needed).
%% 1. Book Figure 8.4: A -> B -> C, and C -> D -> A closes a cycle
names = {'b1', 'v1', 'v2', 'b2', 'v3', 'v4'};
% b1 v1 v2 b2 v3 v4
S = [ 1 -1 0 0 0 1; % A
0 1 -1 0 0 0; % B
0 0 1 -1 -1 0; % C
0 0 0 0 1 -1]; % D
lb = zeros(6, 1); ub = [10; 1000; 1000; 1000; 1000; 1000];
c = zeros(6, 1); c(4) = -1; % maximise b2
best = -lp(c, S, lb, ub, [], []);
lb_opt = lb; lb_opt(4) = best; % hold b2 at its maximum
toy_fva = fva(S, lb_opt, ub, [], [], 1:6);
[S2, lb2, ub2, A, b] = with_abs(S, lb_opt, ub);
c2 = [zeros(6, 1); ones(6, 1)];
toy_min_total = lp(c2, S2, lb2, ub2, A, b);
% Every flux is fixed once the total is minimal: check with FVA
toy_pfba = fva(S2, lb2, ub2, [A; c2'], [b; toy_min_total * (1 + 1e-9)], 1:6);
fprintf('Figure 8.4: max b2 = %g\n', best);
for k = 1:6
fprintf(' %s: FVA [%g, %g]; with minimal total flux [%.4g, %.4g]\n', ...
names{k}, toy_fva(k, 1), toy_fva(k, 2), toy_pfba(k, 1), ...
toy_pfba(k, 2));
end
%% 2. pFBA classes for the E. coli core model
s = load(fullfile(sbp.data_dir(), 'e_coli_core.mat'));
model = s.e_coli_core;
S = full(model.S); lb = model.lb; ub = model.ub; rxns = model.rxns;
n = numel(rxns);
bio = find(strcmp(rxns, 'Biomass_Ecoli_core'));
internal = find(~startsWith(rxns, {'EX_', 'Biomass'}))';
c = zeros(n, 1); c(bio) = -1;
mu = -lp(c, S, lb, ub, [], []);
iszero = @(r) abs(r(1)) < 1e-6 && abs(r(2)) < 1e-6;
% Ranges: on glucose at any growth; at optimal growth; at optimal growth
% with minimal total flux
any_growth = fva(S, lb, ub, [], [], internal);
lb_mu = lb; lb_mu(bio) = mu * (1 - 1e-9);
at_optimum = fva(S, lb_mu, ub, [], [], internal);
[S2, lb2, ub2, A, b] = with_abs(S, lb_mu, ub);
c2 = [zeros(n, 1); ones(n, 1)];
min_total = lp(c2, S2, lb2, ub2, A, b);
parsimonious = fva(S2, lb2, ub2, [A; c2'], [b; min_total * (1 + 1e-9)], ...
internal);
% Essential: growth below 1% of wild type without the reaction
essential = false(size(internal));
for k = 1:numel(internal)
lb_d = lb; ub_d = ub;
lb_d(internal(k)) = 0; ub_d(internal(k)) = 0;
g = lp(c, S, lb_d, ub_d, [], []);
essential(k) = isempty(g) || -g < 0.01 * mu;
end
labels = {'essential', 'pFBA optima', 'ELE', 'MLE', 'no flux', 'blocked'};
fields = {'essential', 'pFBA_optima', 'ELE', 'MLE', 'no_flux', 'blocked'};
members = repmat({{}}, 1, 6);
for k = 1:numel(internal)
if essential(k)
cls = 1;
elseif ~iszero(parsimonious(k, :))
cls = 2;
elseif ~iszero(at_optimum(k, :))
cls = 3;
elseif ~iszero(any_growth(k, :))
cls = 4;
else
cls = 5; % the core model has no blocked reactions
end
members{cls}{end + 1} = rxns{internal(k)};
end
fprintf(['\nE. coli core on glucose: growth %.4f /h; minimal total flux ' ...
'%.2f mmol/gDW/h\n'], mu, min_total);
for k = 1:6
fprintf(' %-12s %3d %s\n', labels{k}, numel(members{k}), ...
strjoin(members{k}, ', '));
end
%% Plot
fig = figure('Position', [100 100 700 350]);
counts = cellfun(@numel, members);
barh(categorical(labels, fliplr(labels)), counts, ...
'FaceColor', [0.000 0.447 0.698], 'EdgeColor', 'none');
text(counts + 0.3, categorical(labels, fliplr(labels)), ...
string(counts), 'VerticalAlignment', 'middle');
xlabel('Number of internal reactions');
title('pFBA classes, E. coli core on glucose');
set(gca, 'TickDir', 'out', ...
'Position', [0.17 0.15 0.76 0.75]); % room for the labels
sbp.save_figure(fig, mfilename('fullpath'), 'fig-pfba');
results.toy_max_b2 = best;
results.toy_fva = toy_fva;
results.toy_pfba = toy_pfba;
results.toy_min_total = toy_min_total;
results.growth = mu;
results.min_total_flux = min_total;
for k = 1:6
results.classes.(fields{k}) = members{k};
end
sbp.save_results(mfilename('fullpath'), results);
%% Local functions
function f = lp(c, S, lb, ub, A, b)
% Minimum of c'v with S v = 0, A v <= b and the bounds; [] if infeasible.
opts = optimoptions('linprog', 'Display', 'none');
[~, f, exitflag] = linprog(c, A, b, S, zeros(size(S, 1), 1), lb, ub, opts);
if exitflag ~= 1, f = []; end
end
function [S2, lb2, ub2, A, b] = with_abs(S, lb, ub)
% Add variables t_j >= |v_j|: for the variables [v; t], the inequality
% rows are v - t <= 0 and -v - t <= 0.
[m, n] = size(S);
S2 = [S zeros(m, n)];
lb2 = [lb; zeros(n, 1)]; ub2 = [ub; 1000 * ones(n, 1)];
A = [eye(n) -eye(n); -eye(n) -eye(n)];
b = zeros(2 * n, 1);
end
function r = fva(S, lb, ub, A, b, which)
% Range of each of the variables listed in which.
r = zeros(numel(which), 2);
for k = 1:numel(which)
c = zeros(size(S, 2), 1); c(which(k)) = 1;
r(k, :) = [lp(c, S, lb, ub, A, b), -lp(-c, S, lb, ub, A, b)];
end
end
Needs COBRApy (to read the model) and SciPy.
"""Loops, parsimonious FBA (pFBA), and the pFBA classes of reactions.
1. The network of book Figure 8.4, which contains a stoichiometrically
balanced cycle: FVA shows the cycle can carry any flux, and minimising
the total flux, sum_j |v_j|, removes it.
2. The E. coli core model on glucose: classify every internal reaction,
as in book §8.8.5, as essential, pFBA optimal, enzymatically less
efficient (ELE), metabolically less efficient (MLE), no flux in this
medium, or blocked.
Total flux is minimised as a linear programme, with variables t_j >= |v_j|.
"""
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
def lp(c, S, lb, ub, A_ub=None, b_ub=None):
res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=S, b_eq=np.zeros(S.shape[0]),
bounds=np.c_[lb, ub], method="highs")
return res.fun if res.status == 0 else None
def with_abs(S, lb, ub):
"""Add variables t_j >= |v_j|: returns S, bounds and the inequality
rows (v - t <= 0, -v - t <= 0) for the variables [v, t]."""
m, n = S.shape
S2 = np.c_[S, np.zeros((m, n))]
lb2, ub2 = np.r_[lb, np.zeros(n)], np.r_[ub, np.full(n, 1000.0)]
eye = np.eye(n)
A = np.r_[np.c_[eye, -eye], np.c_[-eye, -eye]]
return S2, lb2, ub2, A, np.zeros(2 * n)
def fva(S, lb, ub, A_ub=None, b_ub=None, which=None):
"""Range of each of the first variables listed in which."""
out = []
for j in which:
c = np.zeros(S.shape[1])
c[j] = 1
out.append((lp(c, S, lb, ub, A_ub, b_ub),
-lp(-c, S, lb, ub, A_ub, b_ub)))
return np.array(out)
# --- 1. Book Figure 8.4: A -> B -> C, and C -> D -> A closes a cycle
names = ["b1", "v1", "v2", "b2", "v3", "v4"]
# b1 v1 v2 b2 v3 v4
S = np.array([[ 1, -1, 0, 0, 0, 1], # A
[ 0, 1, -1, 0, 0, 0], # B
[ 0, 0, 1, -1, -1, 0], # C
[ 0, 0, 0, 0, 1, -1]]) # D
lb, ub = np.zeros(6), np.array([10, 1000, 1000, 1000, 1000, 1000.0])
c = np.zeros(6)
c[3] = -1 # maximise b2
best = -lp(c, S, lb, ub)
lb_opt = lb.copy()
lb_opt[3] = best # hold b2 at its maximum
toy_fva = fva(S, lb_opt, ub, which=range(6))
S2, lb2, ub2, A, b = with_abs(S, lb_opt, ub)
c2 = np.r_[np.zeros(6), np.ones(6)]
toy_min_total = lp(c2, S2, lb2, ub2, A, b)
# Every flux is fixed once the total is minimal: check with FVA
toy_pfba = fva(S2, lb2, ub2, np.r_[A, c2[None, :]],
np.r_[b, toy_min_total * (1 + 1e-9)], which=range(6))
print(f"Figure 8.4: max b2 = {best:g}")
for nm, r, p in zip(names, toy_fva, toy_pfba):
print(f" {nm}: FVA [{r[0]:g}, {r[1]:g}]; with minimal total flux "
f"[{p[0]:.4g}, {p[1]:.4g}]")
# --- 2. pFBA classes for the E. coli core model
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])
rxns = [r.id for r in model.reactions]
n = len(rxns)
bio = rxns.index("Biomass_Ecoli_core")
internal = [j for j, r in enumerate(rxns)
if not r.startswith(("EX_", "Biomass"))]
c = np.zeros(n)
c[bio] = -1
mu = -lp(c, S, lb, ub)
def zero(r):
return abs(r[0]) < 1e-6 and abs(r[1]) < 1e-6
# Ranges: on glucose at any growth; at optimal growth; at optimal growth
# with minimal total flux
any_growth = fva(S, lb, ub, which=internal)
lb_mu = lb.copy()
lb_mu[bio] = mu * (1 - 1e-9)
at_optimum = fva(S, lb_mu, ub, which=internal)
S2, lb2, ub2, A, b = with_abs(S, lb_mu, ub)
c2 = np.r_[np.zeros(n), np.ones(n)]
min_total = lp(c2, S2, lb2, ub2, A, b)
parsimonious = fva(S2, lb2, ub2, np.r_[A, c2[None, :]],
np.r_[b, min_total * (1 + 1e-9)], which=internal)
# Essential: growth below 1% of wild type without the reaction
essential = []
for j in internal:
lb_d, ub_d = lb.copy(), ub.copy()
lb_d[j] = ub_d[j] = 0
g = lp(c, S, lb_d, ub_d)
essential.append(g is None or -g < 0.01 * mu)
classes = {k: [] for k in ["essential", "pFBA optima", "ELE", "MLE",
"no flux", "blocked"]}
for k, j in enumerate(internal):
if essential[k]:
cls = "essential"
elif not zero(parsimonious[k]):
cls = "pFBA optima"
elif not zero(at_optimum[k]):
cls = "ELE"
elif not zero(any_growth[k]):
cls = "MLE"
else:
cls = "no flux" # the core model has no blocked reactions
classes[cls].append(rxns[j])
print(f"\nE. coli core on glucose: growth {mu:.4f} /h; minimal total flux "
f"{min_total:.2f} mmol/gDW/h")
for k, v in classes.items():
print(f" {k:12s} {len(v):3d} {', '.join(v)}")
# --- Plot
sbp.style()
fig, ax = plt.subplots(figsize=(7, 3.5))
labels = list(classes)
ax.barh(labels[::-1], [len(classes[k]) for k in labels[::-1]],
color="#0072B2")
for y, k in enumerate(labels[::-1]):
ax.text(len(classes[k]) + 0.3, y, str(len(classes[k])), va="center")
ax.set_xlabel("Number of internal reactions")
ax.set_title("pFBA classes, E. coli core on glucose")
sbp.save_figure(fig, __file__, "fig-pfba")
sbp.save_results(__file__, {
"toy_max_b2": best, "toy_fva": toy_fva, "toy_pfba": toy_pfba,
"toy_min_total": toy_min_total, "growth": mu,
"min_total_flux": min_total,
"classes": {k.replace(" ", "_"): v for k, v in classes.items()},
})
sbp.show()
8.8.5 Parsimonious FBA (pFBA)
pFBA (Eq. 8.15) picks, among all flux distributions with optimal growth, one with the least total flux, on the argument that the cell avoids making enzymes it does not need. For the E. coli core model on glucose, the code above finds a growth rate of 0.874 h−1 and a minimal total flux of 518.4 mmol/gDW/h. It then classifies every internal reaction as in the book:
- essential (13): without it, growth falls below 1% of the optimum;
- pFBA optima (27): it can carry flux in a pFBA solution;
- enzymatically less efficient, ELE (1): it can carry flux at optimal growth, but not at minimal total flux;
- metabolically less efficient, MLE (29): it can carry flux on glucose, but not at optimal growth;
- no flux (4) in this medium, and blocked (0).
The one ELE reaction is fumarate reductase, FRD7, which runs the reverse of succinate dehydrogenase (SUCDi). Together they form a loop like the one in Figure 8.4, and at optimal growth FRD7 can carry almost 1000 mmol/gDW/h. Minimising total flux switches it off. MoMA (§9.1) and Fast-SL (§10.2.3) also use flux distributions of minimal norm.
8.8.6 ATP maintenance fluxes
The E. coli core example in §8.6 includes the ATP maintenance reaction, ATPM, with a lower bound of 8.39 mmol/gDW/h. Remember, this is why FBA is infeasible there at very low glucose uptake: nothing can meet the maintenance demand.
8.9 Troubleshooting
8.9.1 Zero growth rate
There is no code for this section; see the book.
8.9.2 Objective values vs. flux values
There is no code for this section; see the book.
8.10 Software tools
There is no code for this section; see the book.
Exercises
- In the toy network, raise the upper bound of \(v_6\) to 2000. Does the optimal growth change? Why not? What happens if you also raise the upper bound of \(b_2\)?
- Remove the reaction R2 from the toy network (set both its bounds to 0) and rerun FVA. What happens to the ranges of \(v_1\) and \(v_3\), and why?
- Run FVA on the E. coli core model under aerobic conditions (
flux_variability_analysisin COBRApy,fluxVariabilityin the COBRA Toolbox). Which reactions can carry no flux at all? (Book, §8.8.1.) - At glucose uptake 10 and oxygen uptake at most 10 mmol/gDW/h, which by-products does the model secrete? Are they unique? Use FVA on the exchange reactions to find out.
- Book Exercises 8.4 and 8.5: find the ATP maintenance reaction and its lower bound; plot growth against glucose uptake from 10 to 25 mmol/gDW/h with oxygen uptake fixed at 16; find the flux range of fumarate reductase (FRD7); and predict growth on acetate and on succinate (10 mmol/gDW/h each) in place of glucose.
- Book Exercise 8.3: set up the small network given there and solve it as an LP in both languages. Do your answers agree with a hand calculation?
Going further
Chapter 9 and Chapter 10 build on these tools, to predict how networks respond to perturbations: gene and reaction knock-outs, synthetic lethals and over-expression.