11 Modelling cellular interactions
Microbes rarely live alone. In the gut, the soil and the ocean, they live in communities, where one organism’s waste is another’s food, and many species cannot be grown in the laboratory at all without their partners. Constraint-based models extend naturally to such communities: each organism keeps its own metabolic network, and the networks are coupled through the metabolites they take up from and release into a shared environment. In this chapter, we build a community model of two E. coli mutants that can grow only together. We also look at two other ways of modelling communities: association networks, inferred from the co-occurrence of microbes, and the generalised Lotka–Volterra model of interacting populations. Finally, we turn to infections, with a classic model of viral dynamics within a host.
11.1 Microbial communities
11.1.1 Network-based approaches
Microbial association networks are inferred from the co-occurrence of taxa across many samples. There is a serious pitfall, however: sequencing measures relative abundances, which must add up to one. If one taxon blooms, all the others must fall, as fractions of the whole, even if their numbers do not change at all. To see how much this matters, we simulate 10 taxa whose absolute abundances vary entirely independently across 200 samples, one of them dominant, and look for associations in three ways: in the absolute abundances, in the relative abundances, and after the centred log-ratio (CLR) transformation used by methods such as SparCC.
Core MATLAB only.
%% Association networks from relative abundances: beware of compositionality
% Microbial association networks (book §11.1.1.1) are built from the
% co-occurrence of taxa across many samples. Sequencing, however, gives
% relative abundances: the reads of each taxon as a fraction of the total.
% Fractions must add up to one, so if one taxon rises, the others must
% fall, even if they are entirely unaffected. Here, we simulate 10 taxa
% whose absolute abundances vary *independently* across 200 samples
% (log-normally, with one dominant taxon), and compare the correlations
% between taxa computed from
% * the absolute abundances (no true associations at all),
% * the relative abundances, and
% * the centred log-ratio (CLR) transform of the relative abundances,
% log(x_i) - mean_j log(x_j), used by SparCC-like methods.
% An "edge" is a pair of taxa with |r| > 0.2 (p < 0.005 for 200 samples).
% The Gaussian numbers are made from sbp.uniform (Box-Muller), so they are
% identical in MATLAB and Python.
taxa = 10; samples = 200;
mean_log = [4.0, ones(1, taxa - 1)]; % taxon 1 dominates
sd_log = ones(1, taxa);
u = sbp.uniform(77, 2 * samples * taxa);
z = sqrt(-2 * log(u(1:2:end))) .* cos(2 * pi * u(2:2:end));
z = reshape(z, taxa, samples)'; % samples x taxa
absolute = exp(mean_log + sd_log .* z);
relative = absolute ./ sum(absolute, 2);
log_rel = log(relative);
clr = log_rel - mean(log_rel, 2);
upper = triu(true(taxa), 1);
names = {'absolute', 'relative', 'clr'};
titles = {'Absolute abundances', 'Relative abundances', 'CLR-transformed'};
data = {absolute, relative, clr};
fig = figure('Position', [100 100 1200 400]);
tiledlayout(1, 3, 'TileSpacing', 'compact');
for d = 1:3
R = corrcoef(data{d});
r = R(upper);
results.(names{d}) = struct('mean_r', mean(r), ...
'edges', sum(abs(r) > 0.2), 'dominant_mean_r', mean(R(1, 2:end)));
fprintf(['%-9s mean r = %+.3f; edges (|r| > 0.2): %2d of %d; mean r ' ...
'with the dominant taxon = %+.3f\n'], names{d}, mean(r), ...
sum(abs(r) > 0.2), sum(upper, 'all'), mean(R(1, 2:end)));
nexttile
R(logical(eye(taxa))) = NaN;
imagesc(R, 'AlphaData', ~isnan(R), [-0.6, 0.6]); axis square
xticks(1:taxa); yticks(1:taxa);
edges = results.(names{d}).edges;
label = sprintf('%d edges', edges);
if edges == 1, label = '1 edge'; end
title({titles{d}, label});
end
colormap(fig, sbp.colormap('RdBu_r'));
cb = colorbar; cb.Layout.Tile = 'east'; cb.Label.String = 'Pearson r';
sbp.save_figure(fig, mfilename('fullpath'), 'fig-compositional');
sbp.save_results(mfilename('fullpath'), results);
Needs NumPy only.
"""Association networks from relative abundances: beware of compositionality.
Microbial association networks (book §11.1.1.1) are built from the
co-occurrence of taxa across many samples. Sequencing, however, gives
relative abundances: the reads of each taxon as a fraction of the total.
Fractions must add up to one, so if one taxon rises, the others must
fall, even if they are entirely unaffected. Here, we simulate 10 taxa
whose absolute abundances vary *independently* across 200 samples
(log-normally, with one dominant taxon), and compare the correlations
between taxa computed from
* the absolute abundances (no true associations at all),
* the relative abundances, and
* the centred log-ratio (CLR) transform of the relative abundances,
log(x_i) - mean_j log(x_j), used by SparCC-like methods.
An "edge" is a pair of taxa with |r| > 0.2 (p < 0.005 for 200 samples).
The Gaussian numbers are made from sbp.uniform (Box-Muller), so they are
identical in MATLAB and Python.
"""
import numpy as np
import matplotlib.pyplot as plt
import sbp
taxa, samples = 10, 200
mean_log = np.array([4.0] + [1.0] * (taxa - 1)) # taxon 1 dominates
sd_log = np.full(taxa, 1.0)
u = sbp.uniform(77, 2 * samples * taxa)
z = (np.sqrt(-2 * np.log(u[0::2])) * np.cos(2 * np.pi * u[1::2]))
z = z.reshape(samples, taxa)
absolute = np.exp(mean_log + sd_log * z) # samples x taxa
relative = absolute / absolute.sum(axis=1, keepdims=True)
log_rel = np.log(relative)
clr = log_rel - log_rel.mean(axis=1, keepdims=True)
upper = np.triu(np.ones((taxa, taxa), dtype=bool), 1)
results = {}
for name, data in (("absolute", absolute), ("relative", relative),
("clr", clr)):
r = np.corrcoef(data.T)[upper]
results[name] = {"mean_r": r.mean(),
"edges": int(np.sum(np.abs(r) > 0.2)),
"dominant_mean_r": np.corrcoef(data.T)[0, 1:].mean()}
print(f"{name:9s} mean r = {r.mean():+.3f}; edges (|r| > 0.2): "
f"{results[name]['edges']:2d} of {upper.sum()}; mean r with the "
f"dominant taxon = {results[name]['dominant_mean_r']:+.3f}")
# --- Plot: correlation matrices
sbp.style()
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
titles = {"absolute": "Absolute abundances",
"relative": "Relative abundances", "clr": "CLR-transformed"}
for ax, (name, data) in zip(axes, (("absolute", absolute),
("relative", relative), ("clr", clr))):
R = np.corrcoef(data.T)
np.fill_diagonal(R, np.nan)
im = ax.imshow(R, cmap="RdBu_r", vmin=-0.6, vmax=0.6)
ax.set_xticks(range(taxa), range(1, taxa + 1))
ax.set_yticks(range(taxa), range(1, taxa + 1))
edges = results[name]["edges"]
label = "1 edge" if edges == 1 else f"{edges} edges"
ax.set_title(f"{titles[name]}\n{label}")
fig.colorbar(im, ax=axes, shrink=0.8, label="Pearson r")
sbp.save_figure(fig, __file__, "fig-compositional")
sbp.save_results(__file__, results)
sbp.show()
Let us call a pair of taxa an “edge” if their correlation exceeds 0.2 in magnitude (\(p < 0.005\) for 200 samples). The absolute abundances show essentially no associations, as they should (one edge, by chance). The relative abundances show 11, and every taxon appears to be negatively associated with the dominant one (\(r = -0.42\), on average), although none of them is. The CLR transformation removes most of this artefact (3 edges), but leaves a small negative bias in every correlation, close to \(-1/(D-1) \approx -0.11\) for \(D = 10\) taxa. Compositionality is one reason why association networks inferred from relative abundances must be interpreted with great care (Friedman and Alm 2012).
11.1.2 Population-based and agent-based approaches
The generalised Lotka–Volterra (gLV) model extends the predator–prey model of §1.5.1 to any number of species, \(\dot{x}_i = x_i\left(r_i + \sum_j a_{ij}x_j\right)\). Here, \(r_i\) is the growth rate of species \(i\) on its own, \(a_{ii} < 0\) limits its growth, and \(a_{ij}\) captures the effect of species \(j\) on species \(i\): negative for competition, positive for, say, cross-feeding. We simulate a community of three species, find the steady state at which all three coexist, and check its stability. Then, as one must with real data, we turn the problem around: from noisy time courses of three experiments, we estimate \(r\) and \(A\) by linear regression, since \(\mathrm{d}\ln x_i/\mathrm{d}t\) is linear in the parameters (Stein et al. 2013).
Core MATLAB only.
%% A generalised Lotka-Volterra (gLV) model of a three-species community,
% and estimating its parameters from time courses.
%
% dx_i/dt = x_i (r_i + sum_j a_ij x_j)
%
% r_i is the growth rate of species i on its own, a_ii < 0 limits its
% growth, and a_ij (i ~= j) is the effect of species j on species i:
% negative for competition, positive for cross-feeding. We find the
% steady state where all three species coexist, x* = -A^-1 r, and its
% stability, from the eigenvalues of the Jacobian diag(x*) A.
%
% Then we turn the problem around, as one does with real abundance data
% (book §11.1.2): we simulate three experiments that start from different
% mixtures, "measure" the abundances every half day with 5% noise, and
% estimate r and A by linear regression, since
% d ln x_i / dt = r_i + sum_j a_ij x_j
% is linear in the parameters. The noise is Gaussian, made from
% sbp.uniform by the Box-Muller method, so that it is identical in MATLAB
% and Python.
species = {'A', 'B', 'C'};
r = [1.0; 0.8; 0.6];
A = [-1.0, -0.4, 0.3;
-0.5, -1.0, 0.0;
0.2, -0.3, -0.8];
x_star = -A \ r;
ev = eig(diag(x_star) * A);
[~, order] = sortrows([real(ev), imag(ev)]);
ev = ev(order);
fprintf('Coexistence steady state: %s\n', strjoin(compose('%s = %.3f', ...
string(species'), x_star), ', '));
fprintf(['Eigenvalues of the Jacobian: %s (all real parts negative: ' ...
'stable)\n'], strjoin(compose('%.3f%+.3fi', real(ev), imag(ev)), ', '));
% Three experiments, sampled every half day for 10 days, with 5% noise
t = 0:0.5:10;
starts = [0.05, 0.05, 0.05; 0.5, 0.02, 0.1; 0.02, 0.6, 0.3];
K = size(starts, 1); T = numel(t);
u = sbp.uniform(5, 2 * K * T * 3);
gauss = sqrt(-2 * log(u(1:2:end))) .* cos(2 * pi * u(2:2:end));
gauss = reshape(gauss, 3, T, K); % species x time x experiment
data = cell(1, K);
for k = 1:K
data{k} = simulate(r, A, starts(k, :), t) ...
.* (1 + 0.05 * gauss(:, :, k)');
end
% Regression: (ln x(t + dt) - ln x(t)) / dt = r + A x(t)
X = []; Y = [];
for k = 1:K
X = [X; ones(T - 1, 1), data{k}(1:end - 1, :)]; %#ok<AGROW>
Y = [Y; diff(log(data{k})) ./ diff(t)']; %#ok<AGROW>
end
theta = X \ Y; % one column per species
r_hat = theta(1, :);
A_hat = theta(2:end, :)';
fprintf('Estimated growth rates: %s (true %s)\n', ...
strjoin(compose('%.2f', r_hat), ', '), ...
strjoin(compose('%.2f', r'), ', '));
fprintf('Estimated interactions:\n');
for i = 1:3
fprintf(' %s: %s (true %s)\n', species{i}, ...
strjoin(compose('%+.2f', A_hat(i, :)), ' '), ...
strjoin(compose('%+.2f', A(i, :)), ' '));
end
%% Plot: data, and the fitted model's predictions
fig = figure('Position', [100 100 1200 360]);
tt = linspace(0, 10, 201);
colours = [0.000 0.447 0.698; 0.902 0.624 0.000; 0.000 0.620 0.451];
ax = gobjects(1, K);
for k = 1:K
ax(k) = subplot(1, 3, k); hold on
fitted = simulate(r_hat', A_hat, data{k}(1, :), tt);
for i = 1:3
plot(t, data{k}(:, i), 'o', 'Color', colours(i, :), ...
'MarkerFaceColor', colours(i, :), 'MarkerSize', 3, ...
'HandleVisibility', 'off');
plot(tt, fitted(:, i), 'Color', colours(i, :), ...
'DisplayName', species{i});
end
xticks(0:2:10);
xlabel('Time (days)'); title(sprintf('Experiment %d', k)); box off
if k == 1
ylabel('Abundance');
legend('Box', 'off', 'Location', 'northwest');
end
end
linkaxes(ax, 'y');
sbp.save_figure(fig, mfilename('fullpath'), 'fig-glv');
results.steady_state = x_star';
results.eigenvalues_real = real(ev)';
results.eigenvalues_imag = imag(ev)';
results.r_hat = r_hat;
results.A_hat = A_hat;
sbp.save_results(mfilename('fullpath'), results);
%% Local functions
function x = simulate(r, A, x0, t)
% Rows: times; columns: species.
opts = odeset('RelTol', 1e-10, 'AbsTol', 1e-12);
[~, x] = ode45(@(~, x) x .* (r + A * x), t, x0(:), opts);
end
Needs SciPy.
"""A generalised Lotka-Volterra (gLV) model of a three-species community,
and estimating its parameters from time courses.
dx_i/dt = x_i (r_i + sum_j a_ij x_j)
r_i is the growth rate of species i on its own, a_ii < 0 limits its
growth, and a_ij (i != j) is the effect of species j on species i:
negative for competition, positive for cross-feeding. We find the
steady state where all three species coexist, x* = -A^-1 r, and its
stability, from the eigenvalues of the Jacobian diag(x*) A.
Then we turn the problem around, as one does with real abundance data
(book §11.1.2): we simulate three experiments that start from different
mixtures, "measure" the abundances every half day with 5% noise, and
estimate r and A by linear regression, since
d ln x_i / dt = r_i + sum_j a_ij x_j
is linear in the parameters. The noise is Gaussian, made from
sbp.uniform by the Box-Muller method, so that it is identical in MATLAB
and Python.
"""
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
import sbp
species = ["A", "B", "C"]
r = np.array([1.0, 0.8, 0.6])
A = np.array([[-1.0, -0.4, 0.3],
[-0.5, -1.0, 0.0],
[0.2, -0.3, -0.8]])
def simulate(x0, t):
sol = solve_ivp(lambda _, x: x * (r + A @ x), [0, t[-1]], x0, t_eval=t,
method="LSODA", rtol=1e-10, atol=1e-12)
return sol.y.T # time x species
x_star = -np.linalg.solve(A, r)
eigenvalues = np.linalg.eigvals(np.diag(x_star) @ A)
eigenvalues = eigenvalues[np.lexsort((eigenvalues.imag, eigenvalues.real))]
print("Coexistence steady state: " + ", ".join(
f"{s} = {x:.3f}" for s, x in zip(species, x_star)))
print("Eigenvalues of the Jacobian: " + ", ".join(
f"{e.real:.3f}{e.imag:+.3f}i" for e in eigenvalues)
+ " (all real parts negative: stable)")
# Three experiments, sampled every half day for 10 days, with 5% noise
t = np.arange(0, 10.01, 0.5)
starts = [[0.05, 0.05, 0.05], [0.5, 0.02, 0.1], [0.02, 0.6, 0.3]]
u = sbp.uniform(5, 2 * len(starts) * len(t) * 3)
gauss = (np.sqrt(-2 * np.log(u[0::2])) * np.cos(2 * np.pi * u[1::2]))
gauss = gauss.reshape(len(starts), len(t), 3)
data = [simulate(x0, t) * (1 + 0.05 * gauss[k])
for k, x0 in enumerate(starts)]
# Regression: (ln x(t + dt) - ln x(t)) / dt = r + A x(t)
rows, targets = [], []
for x in data:
rows.append(np.c_[np.ones(len(t) - 1), x[:-1]])
targets.append(np.diff(np.log(x), axis=0) / np.diff(t)[:, None])
X, Y = np.vstack(rows), np.vstack(targets)
theta = np.linalg.lstsq(X, Y, rcond=None)[0] # one column per species
r_hat, A_hat = theta[0], theta[1:].T
print("Estimated growth rates: " + ", ".join(f"{x:.2f}" for x in r_hat)
+ " (true " + ", ".join(f"{x:.2f}" for x in r) + ")")
print("Estimated interactions:")
for i, s in enumerate(species):
print(f" {s}: " + " ".join(f"{a:+.2f}" for a in A_hat[i])
+ " (true " + " ".join(f"{a:+.2f}" for a in A[i]) + ")")
# --- Plot: data, and the fitted model's predictions
sbp.style()
fig, axes = plt.subplots(1, 3, figsize=(12, 3.6), sharey=True)
tt = np.linspace(0, 10, 201)
colours = ["#0072B2", "#E69F00", "#009E73"]
for k, ax in enumerate(axes):
fitted = solve_ivp(lambda _, x: x * (r_hat + A_hat @ x), [0, 10],
data[k][0], t_eval=tt, rtol=1e-8).y.T
for i in range(3):
ax.plot(t, data[k][:, i], "o", color=colours[i], ms=3)
ax.plot(tt, fitted[:, i], color=colours[i], label=species[i])
ax.set_xticks(range(0, 11, 2))
ax.set_xlabel("Time (days)")
ax.set_title(f"Experiment {k + 1}")
axes[0].set_ylabel("Abundance")
axes[0].legend(frameon=False, loc="upper left")
sbp.save_figure(fig, __file__, "fig-glv")
sbp.save_results(__file__, {
"steady_state": x_star, "eigenvalues_real": eigenvalues.real,
"eigenvalues_imag": eigenvalues.imag, "r_hat": r_hat, "A_hat": A_hat,
})
sbp.show()
All three species coexist at a stable steady state (all eigenvalues of the Jacobian are negative). The regression recovers the growth rates to within 6%, and every non-zero interaction with the correct sign, but some interactions are noticeably off: species A is estimated to suffer more from competition with B (\(a_{AB} = -0.59\), against \(-0.40\)), and to benefit more from C (\(a_{AC} = +0.52\), against \(+0.30\)). The finite differences used to estimate \(\mathrm{d}\ln x/\mathrm{d}t\) amplify the measurement noise, and with only three experiments, some combinations of parameters are poorly determined. Approaches such as MDSINE address these problems with regularisation and Bayesian inference. Note, however, that the curves in the figure, simulated with the fitted parameters, still follow the data closely: quite different parameters can describe the same time courses equally well.
11.1.3 Constraint-based approaches
Let us build a community of two mutants of the E. coli core model, each unable to grow on its own. Strain A lacks both routes to glutamate (glutamate dehydrogenase, GLUDy, and glutamate synthase, GLUSy). Strain B lacks both anaplerotic routes that replenish the TCA cycle (PEP carboxylase, PPC, and the glyoxylate shunt, through isocitrate lyase, ICL), so it cannot make the oxaloacetate and 2-oxoglutarate it needs for biosynthesis. On glucose alone, FBA predicts that neither grows. Such pairs of auxotrophs, which rescue each other by cross-feeding, are a standard way to build synthetic communities in the laboratory (Mee et al. 2014).
Community models must decide how the organisms’ growth is coupled. Here we follow the idea behind community FBA and SteadyCom (Chan et al. 2017) (book, §11.1.3.2 and §11.1.3.6): in a community that persists, every member must grow at the same rate \(\mu\), or the faster one would take over. Let us fix the fraction \(x\) of strain A in the community, and express all fluxes per gram of the whole community. Strain A then makes biomass at rate \(x\mu\) and strain B at \((1-x)\mu\), and each strain’s flux bounds scale with its abundance. For fixed \(x\), maximising \(\mu\) is a single linear programme over the fluxes \(\mathbf{u}_A\) and \(\mathbf{u}_B\) of both strains:
\[ \begin{aligned} \max_{\mathbf{u}_A,\, \mathbf{u}_B,\, \mu} \quad & \mu \\ \text{subject to} \quad & \mathbf{S}\mathbf{u}_A = \mathbf{0}, \quad \mathbf{S}\mathbf{u}_B = \mathbf{0}, \\ & u_{A,\text{biomass}} = x\mu, \quad u_{B,\text{biomass}} = (1-x)\mu, \\ & x\,\mathbf{lb}_A \le \mathbf{u}_A \le x\,\mathbf{ub}_A, \quad (1-x)\,\mathbf{lb}_B \le \mathbf{u}_B \le (1-x)\,\mathbf{ub}_B, \\ & u_{A,j} + u_{B,j} \ge 0 \quad \text{for every metabolite } j \text{ the medium does not supply.} \end{aligned} \]
The last constraint couples the strains: a metabolite that the medium does not supply can be taken up by one strain only if the other secretes it. Each strain can exchange at most 10 mmol/gDW/h of each organic metabolite, which keeps the exchanges realistic. We scan \(x\) from 0.01 to 0.99, and then, for a 1:1 community, find the smallest total exchange between the strains that still allows the maximum growth rate, to see which metabolites must change hands.
Needs the Optimization Toolbox.
%% Two E. coli mutants that can only grow together
% Strain A cannot make glutamate (GLUDy and GLUSy deleted); strain B
% cannot replenish its TCA cycle (PPC and ICL deleted). Neither grows
% alone on glucose. In a community model, each strain keeps its own
% network, and both exchange metabolites through a shared medium. With
% the fraction x of strain A fixed, both strains growing at the same rate
% mu (as they must in a stable community), and fluxes per gram of the
% whole community, the problem is a linear programme:
% maximise mu
% subject to S u_A = 0, S u_B = 0,
% u_A(biomass) = x mu, u_B(biomass) = (1 - x) mu,
% x lb_A <= u_A <= x ub_A,
% (1 - x) lb_B <= u_B <= (1 - x) ub_B,
% what the community takes from the medium is available.
% 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); m = size(S, 1);
bio = find(strcmp(ids, 'Biomass_Ecoli_core'));
ex = find(startsWith(ids, 'EX_'))';
% The medium supplies glucose, oxygen, ammonium, phosphate, water and
% protons, and takes up CO2; other metabolites come only from the cells
medium = {'EX_glc__D_e', 'EX_o2_e', 'EX_nh4_e', 'EX_pi_e', ...
'EX_h2o_e', 'EX_h_e', 'EX_co2_e'};
in_medium = ismember(ids, medium);
A = strain({'GLUDy', 'GLUSy'}, ids, ex, medium, lb0, ub0);
B = strain({'PPC', 'ICL'}, ids, ex, medium, lb0, ub0);
net = struct('S', S, 'bio', bio, 'ex', ex, 'in_medium', in_medium);
fprintf('Alone: strain A grows at %.4f /h, strain B at %.4f /h\n', ...
alone(net, A.lb, A.ub), alone(net, B.lb, B.ub));
fractions = round(0.01:0.01:0.99, 10);
growth = zeros(size(fractions));
for k = 1:numel(fractions)
[~, f] = community(net, A, B, fractions(k), false, []);
growth(k) = max(0, -f);
end
best = max(growth);
plateau = fractions(growth > best - 1e-6);
fprintf(['Community growth up to %.4f /h, for fractions of A from ' ...
'%.2f to %.2f\n'], best, min(plateau), max(plateau));
% What must be exchanged? At x = 0.5, hold growth at its maximum and
% find the smallest total exchange of metabolites between the strains
x = 0.5;
[~, f] = community(net, A, B, x, false, []);
mu = -f;
[z, least] = community(net, A, B, x, true, [mu * (1 - 1e-7), mu]);
uA = z(1:n); uB = z(n + 1:2 * n);
fprintf(['At x = 0.5 (growth %.4f /h), the least exchange needed, in ' ...
'mmol per gram of community per hour (+ secreted, - taken up):\n'], ...
mu);
traded = ex(~in_medium(ex) & max(abs(uA(ex)), abs(uB(ex))) > 1e-4);
for i = traded
fprintf(' %-12s A %+.3f B %+.3f\n', ids{i}, uA(i), uB(i));
end
%% Plot
fig = figure('Position', [100 100 1000 400]);
subplot(1, 5, 1:3)
plot(fractions, growth, 'Color', [0.000 0.447 0.698]);
yline(alone(net, lb0, ub0), ':', 'wild type alone', ...
'Color', [0.6 0.6 0.6], 'LabelHorizontalAlignment', 'center');
xlim([0 1]); ylim([0 1]);
xticks(0:0.2:1); yticks(0:0.2:1);
xlabel('Fraction of strain A in the community');
ylabel('Community growth rate (1/h)');
title('Growth depends on composition');
box off
subplot(1, 5, 4:5)
label = containers.Map({'EX_akg_e', 'EX_glu__L_e', 'EX_lac__D_e', ...
'EX_succ_e', 'EX_mal__L_e', 'EX_fum_e'}, {'2-oxoglutarate', ...
'glutamate', 'D-lactate', 'succinate', 'malate', 'fumarate'});
names = ids(traded);
for k = 1:numel(names)
if isKey(label, names{k}), names{k} = label(names{k}); end
end
y = (1:numel(traded))';
hold on
barh(y + 0.2, uA(traded), 0.4, 'FaceColor', [0.902 0.624 0.000], ...
'EdgeColor', 'none', 'DisplayName', 'strain A');
barh(y - 0.2, uB(traded), 0.4, 'FaceColor', [0.000 0.620 0.451], ...
'EdgeColor', 'none', 'DisplayName', 'strain B');
yticks(y); yticklabels(names);
xline(0, 'k', 'HandleVisibility', 'off');
xlim([-4.5 4.5]); ylim([0.4, numel(traded) + 1.2]);
xlabel('Exchange flux (+ secreted, - taken up)');
title('Least cross-feeding, x = 0.5');
legend('Location', 'north', 'Orientation', 'horizontal', 'Box', 'off');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-cross-feeding');
results.growth_alone = [alone(net, A.lb, A.ub) alone(net, B.lb, B.ub)];
results.fractions = fractions;
results.growth = growth;
results.best_growth = best;
results.plateau = [min(plateau) max(plateau)];
results.least_exchange_total = least;
sbp.save_results(mfilename('fullpath'), results);
%% Local functions
function b = strain(deleted, ids, ex, medium, lb, ub)
% Bounds per gram of a strain. Each cell can take up or secrete at most
% 10 mmol/gDW/h of each metabolite other than the inorganic ones, and
% glucose uptake is limited to 10 as before.
for i = ex
if ismember(ids{i}, medium(2:end))
lb(i) = -1000;
else
lb(i) = -10; ub(i) = 10;
end
end
del = ismember(ids, deleted);
lb(del) = 0; ub(del) = 0;
b = struct('lb', lb, 'ub', ub);
end
function [z, f] = community(net, A, B, x, minimise_exchange, mu_fixed)
% Variables: u_A (n), u_B (n), mu, and, to minimise cross-feeding,
% t_A and t_B >= |exchange fluxes| (one per exchange reaction).
[m, n] = size(net.S);
ex = net.ex;
k = numel(ex) * minimise_exchange;
N = 2 * n + 1 + 2 * k;
Aeq = zeros(2 * m + 2, N);
Aeq(1:2 * m, 1:2 * n) = blkdiag(net.S, net.S);
Aeq(2 * m + 1, [net.bio, 2 * n + 1]) = [1, -x];
Aeq(2 * m + 2, [n + net.bio, 2 * n + 1]) = [1, -(1 - x)];
beq = zeros(2 * m + 2, 1);
% Shared medium: net uptake by the community of a metabolite the medium
% does not supply must be zero or negative
shared = ex(~net.in_medium(ex));
Aub = zeros(numel(shared), N);
for j = 1:numel(shared)
Aub(j, [shared(j), n + shared(j)]) = -1;
end
lb = [x * A.lb; (1 - x) * B.lb; 0; zeros(2 * k, 1)];
ub = [x * A.ub; (1 - x) * B.ub; Inf; Inf(2 * k, 1)];
c = zeros(N, 1);
if ~minimise_exchange
c(2 * n + 1) = -1; % maximise mu
else
lb(2 * n + 1) = mu_fixed(1); ub(2 * n + 1) = mu_fixed(2);
c(2 * n + 2:end) = 1; % minimise sum t
extra = zeros(0, N);
offsets = [0 n];
for s = 1:2
for j = 1:numel(ex)
if net.in_medium(ex(j)), continue; end
t = 2 * n + 1 + (s - 1) * k + j;
for sgn = [1 -1] % sgn * u <= t
r = zeros(1, N);
r([offsets(s) + ex(j), t]) = [sgn, -1];
extra(end + 1, :) = r; %#ok<AGROW>
end
end
end
Aub = [Aub; extra];
end
opts = optimoptions('linprog', 'Display', 'none');
[z, f, exitflag] = linprog(c, Aub, zeros(size(Aub, 1), 1), Aeq, beq, ...
lb, ub, opts);
if exitflag ~= 1
z = []; f = 0;
end
end
function mu = alone(net, lb, ub)
% Growth of one strain on its own: it can take up only what the medium
% supplies.
for i = net.ex
if ~net.in_medium(i), lb(i) = max(lb(i), 0); end
end
c = zeros(numel(lb), 1); c(net.bio) = -1;
opts = optimoptions('linprog', 'Display', 'none');
[~, f, exitflag] = linprog(c, [], [], net.S, zeros(size(net.S, 1), 1), ...
lb, ub, opts);
mu = 0;
if exitflag == 1, mu = max(0, -f); end
end
Needs COBRApy (to read the model).
"""Two E. coli mutants that can only grow together.
Strain A cannot make glutamate (GLUDy and GLUSy deleted); strain B
cannot replenish its TCA cycle (PPC and ICL deleted). Neither grows
alone on glucose. In a community model, each strain keeps its own
network, and both exchange metabolites through a shared medium. With
the fraction x of strain A fixed, both strains growing at the same rate
mu (as they must in a stable community), and fluxes per gram of the
whole community, the problem is a linear programme:
maximise mu
subject to S u_A = 0, S u_B = 0,
u_A[biomass] = x mu, u_B[biomass] = (1 - x) mu,
x lb_A <= u_A <= x ub_A,
(1 - x) lb_B <= u_B <= (1 - x) ub_B,
what the community takes from the medium is available.
"""
import numpy as np
from scipy.optimize import linprog
from scipy.linalg import block_diag
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]
n, m = len(ids), S.shape[0]
bio = ids.index("Biomass_Ecoli_core")
ex = [i for i, r in enumerate(ids) if r.startswith("EX_")]
# The medium supplies glucose, oxygen, ammonium, phosphate, water and
# protons, and takes up CO2; other metabolites come only from the cells
medium = ["EX_glc__D_e", "EX_o2_e", "EX_nh4_e", "EX_pi_e", "EX_h2o_e",
"EX_h_e", "EX_co2_e"]
def strain(deleted):
"""Bounds per gram of a strain. Each cell can take up or secrete at
most 10 mmol/gDW/h of each metabolite other than the inorganic ones,
and glucose uptake is limited to 10 as before."""
lb, ub = lb0.copy(), ub0.copy()
for i in ex:
if ids[i] in medium[1:]:
lb[i] = -1000.0
else:
lb[i], ub[i] = -10.0, 10.0
for r in deleted:
lb[ids.index(r)] = ub[ids.index(r)] = 0
return lb, ub
A = strain(["GLUDy", "GLUSy"])
B = strain(["PPC", "ICL"])
def community(x, minimise_exchange=False, mu_fixed=None):
"""Variables: u_A (n), u_B (n), mu, and, to minimise cross-feeding,
t_A and t_B >= |exchange fluxes| (one per exchange reaction)."""
k = len(ex) if minimise_exchange else 0
N = 2 * n + 1 + 2 * k
Aeq = np.zeros((2 * m + 2, N))
Aeq[:2 * m, :2 * n] = block_diag(S, S)
Aeq[2 * m, bio], Aeq[2 * m, 2 * n] = 1, -x
Aeq[2 * m + 1, n + bio], Aeq[2 * m + 1, 2 * n] = 1, -(1 - x)
beq = np.zeros(2 * m + 2)
# Shared medium: net uptake by the community of a metabolite the
# medium does not supply must be zero or negative
rows = []
for i in ex:
if ids[i] not in medium:
r = np.zeros(N)
r[i] = r[n + i] = -1
rows.append(r)
Aub, bub = np.array(rows), np.zeros(len(rows))
bounds = np.r_[np.c_[x * A[0], x * A[1]],
np.c_[(1 - x) * B[0], (1 - x) * B[1]],
[[0, np.inf]], np.tile([0, np.inf], (2 * k, 1))]
c = np.zeros(N)
if not minimise_exchange:
c[2 * n] = -1 # maximise mu
else:
bounds[2 * n] = mu_fixed
c[2 * n + 1:] = 1 # minimise sum t
extra = []
for s, offset in enumerate([0, n]):
for j, i in enumerate(ex):
if ids[i] in medium:
continue
t = 2 * n + 1 + s * k + j
for sign in (1, -1): # sign * u <= t
r = np.zeros(N)
r[offset + i], r[t] = sign, -1
extra.append(r)
Aub = np.vstack([Aub, extra])
bub = np.zeros(len(Aub))
res = linprog(c, A_ub=Aub, b_ub=bub, A_eq=Aeq, b_eq=beq, bounds=bounds,
method="highs")
return res
def alone(lb, ub):
"""Growth of one strain on its own: it can take up only what the
medium supplies."""
lb = lb.copy()
for i in ex:
if ids[i] not in medium:
lb[i] = max(lb[i], 0.0)
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 0.0
print(f"Alone: strain A grows at {alone(*A):.4f} /h, strain B at "
f"{alone(*B):.4f} /h")
fractions = np.round(np.arange(0.01, 1.0, 0.01), 10)
growth = np.array([max(0.0, -community(x).fun) for x in fractions])
best = growth.max()
plateau = fractions[growth > best - 1e-6]
print(f"Community growth up to {best:.4f} /h, for fractions of A from "
f"{plateau.min():.2f} to {plateau.max():.2f}")
# What must be exchanged? At x = 0.5, hold growth at its maximum and
# find the smallest total exchange of metabolites between the strains
x = 0.5
mu = -community(x).fun
res = community(x, minimise_exchange=True, mu_fixed=[mu * (1 - 1e-7), mu])
uA, uB = res.x[:n], res.x[n:2 * n]
traded = {ids[i]: [uA[i], uB[i]] for i in ex
if ids[i] not in medium and max(abs(uA[i]), abs(uB[i])) > 1e-4}
print(f"At x = 0.5 (growth {mu:.4f} /h), the least exchange needed, in "
f"mmol per gram of community per hour (+ secreted, - taken up):")
for r, (a, b) in traded.items():
print(f" {r:12s} A {a:+.3f} B {b:+.3f}")
# --- Plot
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
gridspec_kw={"width_ratios": [3, 2],
"wspace": 0.45})
ax1.plot(fractions, growth, color="#0072B2")
ax1.axhline(alone(lb0, ub0), color="#999999", ls=":", lw=1)
ax1.text(0.5, 0.9, "wild type alone", ha="center", color="#666666",
fontsize=9)
ax1.set_xlim(0, 1)
ax1.set_ylim(0, 1)
ax1.set_xlabel("Fraction of strain A in the community")
ax1.set_ylabel("Community growth rate (1/h)")
ax1.set_title("Growth depends on composition")
label = {"EX_akg_e": "2-oxoglutarate", "EX_glu__L_e": "glutamate",
"EX_lac__D_e": "D-lactate", "EX_succ_e": "succinate",
"EX_mal__L_e": "malate", "EX_fum_e": "fumarate"}
names = [label.get(r, r) for r in traded]
y = np.arange(len(traded))
ax2.barh(y + 0.2, [v[0] for v in traded.values()], 0.4,
color="#E69F00", label="strain A")
ax2.barh(y - 0.2, [v[1] for v in traded.values()], 0.4,
color="#009E73", label="strain B")
ax2.set_yticks(y, names)
ax2.axvline(0, color="black", lw=0.5)
ax2.set_xlim(-4.5, 4.5)
ax2.set_xlabel("Exchange flux (+ secreted, − taken up)")
ax2.set_title("Least cross-feeding, x = 0.5")
ax2.set_ylim(-0.6, len(traded) + 0.2)
ax2.legend(frameon=False, loc="upper center", ncol=2)
sbp.save_figure(fig, __file__, "fig-cross-feeding")
sbp.save_results(__file__, {
"growth_alone": [alone(*A), alone(*B)],
"fractions": fractions, "growth": growth, "best_growth": best,
"plateau": [plateau.min(), plateau.max()],
"least_exchange_total": res.fun,
})
sbp.show()
Together, the two strains grow, and over a wide range of compositions almost as fast as the wild type: at exactly the wild-type rate, 0.874 per hour, for fractions of strain A from 0.43 to 0.62, and within 2% of it from about 0.14 to 0.69. Outside this range, growth falls steeply, because the rarer strain cannot supply enough of what its partner needs. The model thus predicts which compositions a stable community can have, and that it tolerates a fair imbalance between its members.
The least cross-feeding needed at a 1:1 ratio is simple to interpret. Strain A, which has a complete TCA cycle and anaplerosis, secretes 2-oxoglutarate; strain B takes it up, converts some of it to glutamate with the glutamate dehydrogenase it still has, and passes glutamate back to strain A. Strain B also passes D-lactate to strain A, sharing carbon and energy. Other, equally good, exchanges exist, which is why the automated checks compare only the total. The 2-oxoglutarate–glutamate exchange is the heart of the mutualism: allowing only these two metabolites to pass between the strains still gives 88% of the maximum growth rate.
That the pair can grow as fast as the wild type is a reminder of what the model leaves out. Exchanging metabolites costs nothing here, whereas real cells pay to export and import them, and they release only some of what their partners could use. Real cross-feeding communities usually grow more slowly than a prototrophic strain, and how fast depends on which metabolites are exchanged (Mee et al. 2014). Adding such costs, or limits on secretion measured in experiments, is the way to make the model quantitative.
11.2 Host–pathogen interactions (HPIs)
11.2.1 Network models
There is no code for this section; see the book.
11.2.2 Dynamic models
The simplest ODE model of an infection within a host is the target-cell-limited model, described in Perelson’s reviews: virus \(V\) infects target cells \(T\), at a rate \(\beta TV\); infected cells \(I\) produce virus at a rate \(p\) and die at a rate \(\delta\); and free virus is cleared at a rate \(c\). We use the parameters estimated by Baccam et al. for influenza A infection in people (Baccam et al. 2006), and ask how much it matters when an antiviral is started.
Core MATLAB only.
%% Within-host dynamics of an infection: the target-cell-limited model
% The simplest model of viral dynamics in a host (book §11.2.2.2, after
% Perelson): target cells T are infected by virus V, at rate beta T V;
% infected cells I produce virus at rate p and die at rate delta; free
% virus is cleared at rate c.
% dT/dt = -beta T V
% dI/dt = beta T V - delta I
% dV/dt = p I - c V
% The parameters are those estimated by Baccam et al. (2006) for influenza
% A in people. The basic reproductive number, R0 = beta p T0 / (c delta),
% is the number of cells infected by the virus from one infected cell, at
% the start. An antiviral (a neuraminidase inhibitor) that blocks virus
% release with a given efficacy multiplies p by (1 - efficacy); we
% compare treatment started on day 1, 2 and 3 of the infection.
% Rates per day; V in TCID50/mL
par.beta = 2.7e-5; par.p = 1.2e-2; par.c = 3.0; par.delta = 4.0;
T0 = 4e8; V0 = 9.3e-2;
R0 = par.beta * par.p * T0 / (par.c * par.delta);
fprintf('R0 = %.1f\n', R0);
results.R0 = R0;
names = {'untreated', 'day_1', 'day_2', 'day_3'};
starts = [Inf, 1, 2, 3];
efficacy = 0.98;
fig = figure('Position', [100 100 650 450]);
colours = {[0 0 0], [0.000 0.620 0.451], [0.000 0.447 0.698], ...
[0.835 0.369 0.000]};
styles = {'-', '--', '-.', ':'};
for s = 1:numel(names)
[t, y] = simulate(par, [T0; 0; V0], starts(s), efficacy);
T = y(1, :); V = y(3, :);
[peak, k] = max(V);
dt = t(2) - t(1);
% (the day of the peak is printed, but not stored: on a grid of
% 0.01 days, two solvers could disagree about which point is highest)
results.(names{s}) = struct('peak_virus', peak, ...
'target_cells_left', T(end) / T0, ...
'virus_area', sum((V(2:end) + V(1:end - 1)) / 2) * dt);
fprintf(['%-10s peak %.3g TCID50/mL on day %.2f; %.1f%% of target ' ...
'cells left on day 10\n'], names{s}, peak, t(k), 100 * T(end) / T0);
label = strrep(strrep(names{s}, '_', ' '), 'day', 'treated, day');
semilogy(t, max(V, 1e-3), styles{s}, 'Color', colours{s}, ...
'LineWidth', 1.5, 'DisplayName', label);
hold on
end
xlim([0 10]); ylim([1e-2, 1e7]); yticks(10.^(-2:2:6));
xlabel('Time (days)'); ylabel('Virus (TCID50/mL)');
legend('Box', 'off');
title(sprintf('Influenza A, target-cell-limited model (R0 = %.1f)', R0));
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-viral-dynamics');
sbp.save_results(mfilename('fullpath'), results);
%% Local functions
function [t, y] = simulate(par, y0, start, efficacy)
% Up to day `start`, untreated; from then on, virus production is reduced
% by the antiviral. Returns T, I and V (rows) every 0.01 days.
t = linspace(0, 10, 1001);
before = t <= start;
y = zeros(3, numel(t));
opts = odeset('RelTol', 1e-10, 'AbsTol', 1e-8);
rhs = @(production) @(~, x) [-par.beta * x(1) * x(3);
par.beta * x(1) * x(3) - par.delta * x(2);
production * x(2) - par.c * x(3)];
tb = t(before);
[~, x] = ode15s(rhs(par.p), tb, y0, opts);
y(:, before) = x';
if start < t(end)
[~, x] = ode15s(rhs(par.p * (1 - efficacy)), [start, t(~before)], ...
x(end, :)', opts);
y(:, ~before) = x(2:end, :)';
end
end
Needs SciPy.
"""Within-host dynamics of an infection: the target-cell-limited model.
The simplest model of viral dynamics in a host (book §11.2.2.2, after
Perelson): target cells T are infected by virus V, at rate beta T V;
infected cells I produce virus at rate p and die at rate delta; free
virus is cleared at rate c.
dT/dt = -beta T V
dI/dt = beta T V - delta I
dV/dt = p I - c V
The parameters are those estimated by Baccam et al. (2006) for influenza
A in people. The basic reproductive number, R0 = beta p T0 / (c delta),
is the number of cells infected by the virus from one infected cell, at
the start. An antiviral (a neuraminidase inhibitor) that blocks virus
release with efficacy eps multiplies p by (1 - eps); we compare
treatment started on day 1, 2 and 3 of the infection.
"""
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
import sbp
beta, p, c, delta = 2.7e-5, 1.2e-2, 3.0, 4.0 # per day; V in TCID50/mL
T0, V0 = 4e8, 9.3e-2
R0 = beta * p * T0 / (c * delta)
def rhs(t, y, production):
T, I, V = y
return [-beta * T * V, beta * T * V - delta * I, production * I - c * V]
def simulate(start=np.inf, eps=0.0):
"""Up to day `start`, untreated; from then on, virus production is
reduced by the antiviral. Returns T, I and V every 0.01 days."""
t = np.linspace(0, 10, 1001)
before = t <= start
y = np.zeros((3, len(t)))
sol = solve_ivp(rhs, [0, t[before][-1]], [T0, 0, V0], t_eval=t[before],
args=(p,), method="LSODA", rtol=1e-10, atol=1e-8)
y[:, before] = sol.y
if start < t[-1]:
sol = solve_ivp(rhs, [start, t[-1]], sol.y[:, -1],
t_eval=t[~before], args=(p * (1 - eps),),
method="LSODA", rtol=1e-10, atol=1e-8)
y[:, ~before] = sol.y
return t, y
results = {"R0": R0}
print(f"R0 = {R0:.1f}")
scenarios = {"untreated": (np.inf, 0.0), "day_1": (1.0, 0.98),
"day_2": (2.0, 0.98), "day_3": (3.0, 0.98)}
curves = {}
for name, (start, eps) in scenarios.items():
t, (T, I, V) = simulate(start, eps)
k = np.argmax(V)
dt = t[1] - t[0]
# (the day of the peak is printed, but not stored: on a grid of
# 0.01 days, two solvers could disagree about which point is highest)
results[name] = {"peak_virus": V[k], "target_cells_left": T[-1] / T0,
"virus_area": np.sum((V[1:] + V[:-1]) / 2) * dt}
curves[name] = V
print(f"{name:10s} peak {V[k]:.3g} TCID50/mL on day {t[k]:.2f}; "
f"{100 * T[-1] / T0:.1f}% of target cells left on day 10")
# --- Plot
sbp.style()
fig, ax = plt.subplots(figsize=(6.5, 4.5))
colours = {"untreated": "black", "day_1": "#009E73", "day_2": "#0072B2",
"day_3": "#D55E00"}
styles = {"untreated": "-", "day_1": "--", "day_2": "-.", "day_3": ":"}
for name, V in curves.items():
ax.semilogy(t, np.maximum(V, 1e-3), styles[name], color=colours[name],
label=name.replace("_", " ").replace("day", "treated, day"))
ax.set_xlim(0, 10)
ax.set_ylim(1e-2, 1e7)
ax.set_yticks(10.0 ** np.arange(-2, 7, 2))
ax.set_xlabel("Time (days)")
ax.set_ylabel("Virus (TCID50/mL)")
ax.legend(frameon=False)
ax.set_title(f"Influenza A, target-cell-limited model (R0 = {R0:.1f})")
sbp.save_figure(fig, __file__, "fig-viral-dynamics")
sbp.save_results(__file__, results)
sbp.show()
The basic reproductive number is \(R_0 = \beta pT_0/(c\delta) = 10.8\): early on, each infected cell leads to the infection of about 11 more. Untreated, the virus peaks on day 2.3, by which time almost every target cell has been infected. An antiviral that blocks 98% of virus production, started on day 1, stops the infection in its tracks: 99.8% of the target cells are spared. Started on day 2, it spares only 5%, and started on day 3, after the peak, none at all, although it still shortens the shedding a little. Note also that there is no immune response in this model: the infection ends only when the target cells run out. Models of the immune system (§11.2.2.2) add exactly that.
11.2.3 Constraint-based models
There is no code for this section; see the book.
11.3 Summary
There is no code for this section; see the book.
11.4 Software tools
There is no code for this section; see the book.
Exercises
- Remove the limit of 10 mmol/gDW/h on the exchange of each organic metabolite. How does the range of compositions that support near-maximal growth change, and why? Look at the exchange fluxes for extreme compositions.
- Instead of fixing \(x\), find the largest \(\mu\) for which some composition is feasible (book, Eq. 11.3), by bisection on \(\mu\): for each trial value, solve a linear feasibility problem with \(x\) (in the form of the abundance-scaled bounds) as a variable. This is the SteadyCom algorithm (Chan et al. 2017).
- Replace strain B by a strain that cannot take up glucose (GLCpts deleted). Can the community grow? What does the glucose consumer feed its partner, and does oxygen limitation (Chapter 9) change the answer?
- Combine this model with dynamic FBA: start from equal amounts of the two strains in 20 mM glucose and follow the biomass of each, allowing them to grow at different rates. Does the community approach a stable composition?
- Book Exercise 11.2: two genome-scale models are combined into a compartmentalised community model. Work out how many reactions, metabolites and exchange reactions the community model has. How many does our two-strain model have, counted the same way?
Going further
The first constraint-based model of a community, of a sulphate-reducing bacterium and a methanogen, was built by Stolyar et al. (2007); it maximised a weighted sum of the two biomass fluxes (book, §11.1.3.1). Since then, many methods have been developed, which differ in how they couple the members: by a common growth rate, as here, by optimising the community and its members at different levels, or dynamically, by extending dynamic FBA. Models of hundreds of gut microbes, and of microbes interacting with their hosts, are now used to study the microbiome (book, Chapter 11).