Skip to main content

10  Perturbations to metabolic networks

One of the most common uses of a metabolic model is to predict what happens when something is taken away: a gene knocked out, an enzyme inhibited by a drug. Which reactions can the cell not do without? Which pairs of reactions back each other up, so that either can be lost but not both? Constraint-based models answer such questions quickly, at the scale of whole genomes, and these predictions are used to find drug targets in pathogens and to design strains for metabolic engineering. This chapter builds on Chapter 8, and mostly uses the same E. coli core model; for single gene deletions, we also move up to the genome-scale model iML1515, to see how the picture changes when the whole of metabolism is included.

10.1 Knock-outs

To delete a reaction from a constraint-based model, we fix its flux to zero by setting both its lower and upper bounds to zero (book, Eq. 10.2), and solve the FBA problem again. If the maximum growth rate falls below some small fraction of the wild type, 1% here, the deletion is called lethal, and the reaction essential.

Experiments delete genes, whereas our models are written in terms of reactions, and the two do not map one to one. Each reaction in the model carries a gene–protein–reaction (GPR) rule, a Boolean expression of the genes needed for it. An enzyme made of several subunits needs all of them (AND); isozymes can stand in for one another (OR). A gene deletion removes exactly those reactions whose rule becomes false. COBRApy and the COBRA Toolbox evaluate these rules for us.

We delete each of the 74 internal reactions of the model in turn (leaving out exchange reactions and the biomass reaction), and then each of its 137 genes, in the standard aerobic glucose medium.

Needs the COBRA Toolbox; run initCobraToolbox once per session before this script.

%% Single reaction and gene deletions in the E. coli core model
% A reaction is deleted by fixing its flux to zero (lower and upper bounds
% both 0; book Eq. 10.2); the maximum growth rate is then found by FBA. A
% deletion is called lethal if growth falls below 1% of the wild type.
% Genes are deleted through the gene-protein-reaction (GPR) rules, which
% the COBRA Toolbox evaluates for us: a reaction is lost only if the
% deletion makes its rule false, so isozymes can stand in for one another.
% Requires: COBRA Toolbox (run initCobraToolbox once per session first).

model = readCbModel(fullfile(sbp.data_dir(), 'e_coli_core.mat'));
sol = optimizeCbModel(model, 'max');
wt = sol.f;
% Delete internal reactions only: no exchange reactions, no biomass
rxns = sort(model.rxns(~startsWith(model.rxns, {'EX_', 'Biomass'})));

%% Reaction deletions
ratio = zeros(numel(rxns), 1);
for k = 1:numel(rxns)
    m = changeRxnBounds(model, rxns{k}, 0, 'b');
    sol = optimizeCbModel(m, 'max');
    if sol.stat == 1
        ratio(k) = sol.f / wt;
    end                        % infeasible: no growth, ratio stays 0
end
essential_rxns = rxns(ratio < 0.01);
n_reduced = sum(ratio >= 0.01 & ratio < 0.99);

%% Gene deletions (the GPR rules decide which reactions are lost)
grRatio = singleGeneDeletion(model, 'FBA');
grRatio(isnan(grRatio)) = 0;   % infeasible: no growth
[essential_genes, idx] = sort(model.genes(grRatio < 0.01));
names = model.geneNames(grRatio < 0.01);
names = names(idx);

fprintf('Wild-type growth %.4f /h; %d reactions tested\n', wt, numel(rxns));
fprintf('%d essential reactions: %s\n', numel(essential_rxns), ...
    strjoin(essential_rxns, ', '));
fprintf('%d reactions whose loss reduces growth, but not below 1%%\n', ...
    n_reduced);
fprintf('%d essential genes, of %d: %s\n', numel(essential_genes), ...
    numel(model.genes), strjoin(strcat(essential_genes, ' (', names, ...
    ')'), ', '));

%% Plot: growth after each reaction deletion, sorted
[values, order] = sort(ratio);
colors = repmat([0.000 0.447 0.698], numel(values), 1);       % no effect
colors(values < 0.99, :) = repmat([0.902 0.624 0.000], ...
    sum(values < 0.99), 1);                                   % reduced
colors(values < 0.01, :) = repmat([0.835 0.369 0.000], ...
    sum(values < 0.01), 1);                                   % lethal
fig = figure('Position', [100 100 1000 400]);
b = bar(values, 'FaceColor', 'flat', 'EdgeColor', 'none');
b.CData = colors;
hold on
lethal = find(values < 0.01);               % zero-height bars: mark them
plot(lethal, 0.03 * ones(size(lethal)), 'v', 'Color', [0.835 0.369 0.000], ...
    'MarkerFaceColor', [0.835 0.369 0.000], 'MarkerSize', 5);
ax = gca;
set(ax, 'XTick', 1:numel(values), 'XTickLabel', rxns(order), ...
    'XTickLabelRotation', 90, 'TickLabelInterpreter', 'none', ...
    'TickDir', 'out');
ax.XAxis.FontSize = 7;
ylabel('Growth relative to wild type');
title('Single reaction deletions, E. coli core model, aerobic glucose');
legend_colours = [0.835 0.369 0.000; 0.902 0.624 0.000; 0.000 0.447 0.698];
h = gobjects(1, 3);
for k = 1:3                                 % empty patches for the legend
    h(k) = patch(NaN, NaN, legend_colours(k, :), 'EdgeColor', 'none');
end
legend(h, {'lethal (< 1%)', 'reduced', 'no effect'}, ...
    'Location', 'northwest', 'Box', 'off');
sbp.save_figure(fig, mfilename('fullpath'), 'fig-single-deletions');

results.wild_type_growth = wt;
results.growth_ratio = cell2struct(num2cell(ratio), rxns, 1);
results.essential_reactions = essential_rxns';
results.essential_genes = essential_genes';
sbp.save_results(mfilename('fullpath'), results);

Needs COBRApy.

"""Single reaction and gene deletions in the E. coli core model.

A reaction is deleted by fixing its flux to zero (lower and upper bounds
both 0; book Eq. 10.2); the maximum growth rate is then found by FBA. A
deletion is called lethal if growth falls below 1% of the wild type.
Genes are deleted through the gene-protein-reaction (GPR) rules, which
COBRApy evaluates for us: a reaction is lost only if the deletion makes
its rule false, so isozymes can stand in for one another.
"""
import numpy as np
import matplotlib.pyplot as plt
import cobra
from cobra.flux_analysis import single_gene_deletion
import sbp

model = cobra.io.read_sbml_model(str(sbp.DATA / "e_coli_core.xml"))
wt = model.slim_optimize()
cutoff = 0.01 * wt
# Delete internal reactions only: no exchange reactions, no biomass
rxns = sorted(r.id for r in model.reactions
              if not r.id.startswith(("EX_", "Biomass")))

# --- Reaction deletions
ratio = {}
for rid in rxns:
    with model:                                 # undone after the block
        model.reactions.get_by_id(rid).bounds = (0, 0)
        ratio[rid] = model.slim_optimize(error_value=0.0) / wt
essential_rxns = [r for r in rxns if ratio[r] < 0.01]
reduced = [r for r in rxns if 0.01 <= ratio[r] < 0.99]

# --- Gene deletions (the GPR rules decide which reactions are lost)
gd = single_gene_deletion(model)
gene_ratio = {next(iter(ids)): (g if np.isfinite(g) else 0.0) / wt
              for ids, g in zip(gd["ids"], gd["growth"])}
essential_genes = sorted(g for g, r in gene_ratio.items() if r < 0.01)
names = [model.genes.get_by_id(g).name for g in essential_genes]

print(f"Wild-type growth {wt:.4f} /h; {len(rxns)} reactions tested")
print(f"{len(essential_rxns)} essential reactions: "
      f"{', '.join(essential_rxns)}")
print(f"{len(reduced)} reactions whose loss reduces growth, but not below 1%")
print(f"{len(essential_genes)} essential genes, of {len(model.genes)}: "
      f"{', '.join(f'{g} ({n})' for g, n in zip(essential_genes, names))}")

# --- Plot: growth after each reaction deletion, sorted
order = sorted(rxns, key=lambda r: ratio[r])
values = np.array([ratio[r] for r in order])
colors = np.where(values < 0.01, "#D55E00",
                  np.where(values < 0.99, "#E69F00", "#0072B2"))
sbp.style()
fig, ax = plt.subplots(figsize=(10, 4))
ax.bar(range(len(order)), values, color=colors)
lethal = np.flatnonzero(values < 0.01)      # zero-height bars: mark them
ax.plot(lethal, np.full(lethal.size, 0.03), "v", color="#D55E00", ms=5)
ax.set_xticks(range(len(order)), order, rotation=90, fontsize=7)
ax.set_ylabel("Growth relative to wild type")
ax.set_title("Single reaction deletions, E. coli core model, aerobic glucose")
for col, lab in [("#D55E00", "lethal (< 1%)"), ("#E69F00", "reduced"),
                 ("#0072B2", "no effect")]:
    ax.bar(0, 0, color=col, label=lab)
ax.legend(frameon=False, loc="upper left")
sbp.save_figure(fig, __file__, "fig-single-deletions")

sbp.save_results(__file__, {
    "wild_type_growth": wt,
    "growth_ratio": ratio,
    "essential_reactions": essential_rxns,
    "essential_genes": essential_genes,
})
sbp.show()

Thirteen reactions are essential (vermillion), among them the glucose uptake system (GLCpts), the lower steps of glycolysis (GAPD, PGK, PGM, ENO), the first steps of the TCA cycle (CS, ACONTa/b, ICDHyr), and the uptake of ammonium and phosphate. Losing another 23 reactions slows growth without stopping it (orange): the network reroutes flux, at a cost. Deleting the ATP maintenance reaction, ATPM, even increases growth slightly, since the ATP it consumes is freed for biosynthesis.

Only seven genes are essential, although thirteen reactions are. The difference comes from the GPR rules. Aconitase (ACONTa and ACONTb), for example, is encoded by two genes, acnA and acnB, either of which suffices, so neither gene is essential although the reaction is. In the other direction, ptsH and ptsI are each essential because the glucose transport system needs both. Predictions about genes, which are what experiments test, can therefore differ substantially from predictions about reactions.

A genome-scale example: E. coli iML1515

The core model leaves out most of metabolism, and with it most of the genes that experiments test. The genome-scale reconstruction iML1515 (Monk et al. 2017) has 2712 reactions and 1516 genes. The code is the same as before; only the model changes, and deleting all 1516 genes one at a time takes well under a minute.

Needs the COBRA Toolbox; run initCobraToolbox once per session before this script.

%% Single gene deletions in a genome-scale model: E. coli iML1515
% The same procedure as for the core model (single_deletions), on the
% genome-scale reconstruction iML1515 (Monk et al., 2017): 1516 genes and
% 2712 reactions, in its default medium (aerobic, glucose uptake up to
% 10 mmol/gDW/h). A gene deletion removes the reactions whose GPR rule it
% makes false, and is lethal if growth falls below 1% of the wild type.
% Requires: COBRA Toolbox (run initCobraToolbox once per session first).

model = readCbModel(fullfile(sbp.data_dir(), 'iML1515.mat'));
sol = optimizeCbModel(model, 'max');
wt = sol.f;

[grRatio, ~, ~, ~, delRxns] = singleGeneDeletion(model, 'FBA');
grRatio(isnan(grRatio)) = 0;   % infeasible: no growth
[genes, order] = sort(model.genes);
grRatio = grRatio(order);
delRxns = delRxns(order);

essential = genes(grRatio < 0.01);
n_reduced = sum(grRatio >= 0.01 & grRatio < 0.99);
no_rxn = genes(cellfun(@isempty, delRxns));

fprintf('Wild-type growth %.4f /h; %d genes deleted one by one\n', ...
    wt, numel(genes));
fprintf('%d essential genes (%.1f%%)\n', numel(essential), ...
    100 * numel(essential) / numel(genes));
fprintf('%d genes whose loss reduces growth, but not below 1%%\n', n_reduced);
fprintf('%d genes whose loss removes no reaction (isozymes)\n', numel(no_rxn));

%% Plot
counts = [numel(essential), n_reduced, ...
          numel(genes) - numel(essential) - n_reduced];
fig = figure('Position', [100 100 500 450]);
b = bar(counts, 'FaceColor', 'flat', 'EdgeColor', 'none');
b.CData = [0.835 0.369 0.000; 0.902 0.624 0.000; 0.000 0.447 0.698];
text(1:3, counts, string(counts), 'HorizontalAlignment', 'center', ...
    'VerticalAlignment', 'bottom');
set(gca, 'XTickLabel', {'lethal (< 1%)', 'reduced', 'no effect'}, ...
    'TickDir', 'out');
xlim([0.4, 3.6]);
ylabel('Genes');
title('Single gene deletions, iML1515');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-genome-scale-deletions');

results.wild_type_growth = wt;
results.growth_ratio = cell2struct(num2cell(grRatio), genes, 1);
results.essential_genes = essential';
results.n_reduced = n_reduced;
results.no_reaction_lost = no_rxn';
sbp.save_results(mfilename('fullpath'), results);

Needs COBRApy.

"""Single gene deletions in a genome-scale model: E. coli iML1515.

The same procedure as for the core model (single_deletions), on the
genome-scale reconstruction iML1515 (Monk et al., 2017): 1516 genes and
2712 reactions, in its default medium (aerobic, glucose uptake up to
10 mmol/gDW/h). A gene deletion removes the reactions whose GPR rule it
makes false, and is lethal if growth falls below 1% of the wild type.
We also record the genes whose deletion removes no reaction at all,
because an isozyme or another subunit can stand in for them.
"""
import numpy as np
import matplotlib.pyplot as plt
import cobra
import sbp

model = cobra.io.read_sbml_model(str(sbp.DATA / "iML1515.xml.gz"))
wt = model.slim_optimize()
genes = sorted(g.id for g in model.genes)

ratio, lost = {}, {}
for gid in genes:
    gene = model.genes.get_by_id(gid)
    with model:                                 # undone after the block
        gene.knock_out()
        lost[gid] = sorted(r.id for r in gene.reactions if not r.functional)
        ratio[gid] = model.slim_optimize(error_value=0.0) / wt
essential = [g for g in genes if ratio[g] < 0.01]
reduced = [g for g in genes if 0.01 <= ratio[g] < 0.99]
no_rxn = [g for g in genes if not lost[g]]

print(f"Wild-type growth {wt:.4f} /h; {len(genes)} genes deleted one by one")
print(f"{len(essential)} essential genes "
      f"({100 * len(essential) / len(genes):.1f}%)")
print(f"{len(reduced)} genes whose loss reduces growth, but not below 1%")
print(f"{len(no_rxn)} genes whose loss removes no reaction (isozymes)")

# --- Plot
sbp.style()
fig, ax = plt.subplots(figsize=(5, 4.5))
counts = [len(essential), len(reduced),
          len(genes) - len(essential) - len(reduced)]
ax.bar(["lethal (< 1%)", "reduced", "no effect"], counts,
       color=["#D55E00", "#E69F00", "#0072B2"])
for x, k in enumerate(counts):
    ax.text(x, k, str(k), ha="center", va="bottom")
ax.set_ylabel("Genes")
ax.set_title("Single gene deletions, iML1515")
sbp.save_figure(fig, __file__, "fig-genome-scale-deletions")

sbp.save_results(__file__, {
    "wild_type_growth": wt,
    "growth_ratio": ratio,
    "essential_genes": essential,
    "n_reduced": len(reduced),
    "no_reaction_lost": no_rxn,
})
sbp.show()

In its default medium (aerobic, glucose), iML1515 grows at 0.877 h−1. Of its genes, 196 (13%) are predicted to be essential, and only 48 more slow growth by more than 1%; deleting any one of the remaining 1272 leaves growth practically unchanged. Note that for 451 genes, almost a third, the deletion removes no reaction at all, because an isozyme or another subunit covers for it. Most of the network is robust to the loss of any single gene, a theme we return to in Chapter 13.

10.1.1 Gene deletions vs. reaction deletions

The examples of §10.1 delete genes as well as reactions. Remember that the two give different answers for the core model, seven essential genes against thirteen essential reactions, and the GPR rules explain why.

10.2 Synthetic lethals

Two reactions form a synthetic lethal pair if deleting either one alone leaves the cell viable, but deleting both is lethal (book, §10.2). Such pairs reveal how a network backs itself up, and they are attractive targets for combination drugs.

10.2.1 Exhaustive enumeration

The example in §10.2.3 runs the exhaustive search alongside Fast-SL, so that we can check one against the other.

10.2.2 Bi-level optimisation

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

10.2.3 Fast-SL: massively pruning the search space

The obvious way to find synthetic lethal pairs is to test every pair of non-essential reactions (book, §10.2.1). For the core model that is \(\binom{61}{2} = 1830\) double deletions, which is easy; for a genome-scale model with 2000 reactions it is about two million, and for triplets more than a billion. The Fast-SL algorithm, developed in our group, cuts down the search with a simple argument (Pratapa et al. 2015). If some flux distribution that supports growth uses neither reaction of a pair, deleting both leaves that distribution intact, so the pair cannot be lethal. Hence:

  • at least one reaction of a lethal pair, call it \(i\), must carry flux in a wild-type solution; and
  • the other reaction, \(j\), must carry flux in a solution that remains once \(i\) is deleted.

The sparser these solutions, the fewer pairs need to be tested, so Fast-SL uses solutions that achieve the maximum growth with the minimum total flux, \(\sum_j |v_j|\): the minimal-norm solution of book Eq. 10.5 (§10.2.3.2), closely related to parsimonious FBA (§8.8.5). The code below finds all synthetic lethal pairs both ways, and checks that the answers agree.

Needs the COBRA Toolbox.

%% Synthetic lethal reaction pairs in the E. coli core model
% A pair of reactions is synthetic lethal if deleting both stops growth
% (below 1% of wild type) while deleting either one alone does not. We
% find all such pairs twice:
%   1. exhaustively, testing every pair of non-essential reactions;
%   2. as in Fast-SL (Pratapa et al., 2015), testing only pairs that can
%      possibly be lethal. If a growing flux distribution uses neither
%      reaction of a pair, deleting both leaves it intact, so the pair is
%      not lethal. Hence at least one reaction of a lethal pair carries flux
%      in the wild-type solution, and the other carries flux once the first
%      is deleted. Using sparse solutions (minimal total flux) keeps the
%      number of pairs to test small.
% Requires: COBRA Toolbox (run initCobraToolbox once per session first).

model = readCbModel(fullfile(sbp.data_dir(), 'e_coli_core.mat'));
sol = optimizeCbModel(model, 'max');
cutoff = 0.01 * sol.f;
rxns = sort(model.rxns(~startsWith(model.rxns, {'EX_', 'Biomass'})));

is_essential = false(size(rxns));
for k = 1:numel(rxns)
    is_essential(k) = growth_without(model, rxns(k)) < cutoff;
end
candidates = rxns(~is_essential);

%% 1. Exhaustive: every pair of non-essential reactions
pairs = nchoosek(1:numel(candidates), 2);
lethal_exhaustive = {};
for p = 1:size(pairs, 1)
    pair = candidates(pairs(p, :))';
    if growth_without(model, pair) < cutoff
        lethal_exhaustive(end + 1, :) = pair; %#ok<SAGROW>
    end
end

%% 2. Fast-SL: only pairs (i, j) with i active in the wild type and j
% active once i is deleted
tested = {};
lethal_fastsl = {};
for i = active_without(model, {}, candidates)'
    for j = active_without(model, i, candidates)'
        pair = sort([i, j]);
        key = strjoin(pair, ' ');
        if ~strcmp(i{1}, j{1}) && ~ismember(key, tested)
            tested{end + 1} = key; %#ok<SAGROW>
            if growth_without(model, pair) < cutoff
                lethal_fastsl(end + 1, :) = pair; %#ok<SAGROW>
            end
        end
    end
end
lethal_fastsl = sortrows(lethal_fastsl);
same = isequal(lethal_fastsl, sortrows(lethal_exhaustive));

fprintf('%d non-essential reactions\n', numel(candidates));
fprintf('Exhaustive: %d pairs tested, %d synthetic lethal\n', ...
    size(pairs, 1), size(lethal_exhaustive, 1));
fprintf('Fast-SL:    %d pairs tested, %d synthetic lethal\n', ...
    numel(tested), size(lethal_fastsl, 1));
fprintf('Same pairs found: %d\n', same);
partners = cellfun(@(r) sum(strcmp(lethal_fastsl(:), r)), candidates);
[~, order] = sortrows([-partners, (1:numel(candidates))']);
top = order(1:5);
fprintf('Reactions in the most pairs: %s\n', strjoin(strcat( ...
    candidates(top), ' (', arrayfun(@num2str, partners(top), ...
    'UniformOutput', false), ')'), ', '));

%% Plot: which reactions form lethal pairs
involved = unique(lethal_fastsl(:));
M = zeros(numel(involved));
for p = 1:size(lethal_fastsl, 1)
    a = strcmp(involved, lethal_fastsl{p, 1});
    b = strcmp(involved, lethal_fastsl{p, 2});
    M(a, b) = 1; M(b, a) = 1;
end
fig = figure('Position', [100 100 1100 500]);
subplot(1, 3, [1 2])
imagesc(M, [0 1]);
colormap([0.969 0.984 1.000; 0.000 0.447 0.698]);
axis square
ax = gca;
set(ax, 'XTick', 1:numel(involved), 'XTickLabel', involved, ...
    'XTickLabelRotation', 90, 'YTick', 1:numel(involved), ...
    'YTickLabel', involved, 'TickLabelInterpreter', 'none', ...
    'TickDir', 'out');
ax.XAxis.FontSize = 7;
ax.YAxis.FontSize = 7;
title(sprintf('%d synthetic lethal pairs', size(lethal_fastsl, 1)));
subplot(1, 3, 3)
b = bar([size(pairs, 1), numel(tested)], 'FaceColor', 'flat', ...
    'EdgeColor', 'none');
b.CData = [0.6 0.6 0.6; 0.000 0.447 0.698];
set(gca, 'XTickLabel', {'exhaustive', 'Fast-SL'}, 'TickDir', 'out');
xlim([0.4, 2.6]);
ylabel('Double deletions simulated');
title('Cost of the search');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-synthetic-lethals');

results.n_candidates = numel(candidates);
results.n_pairs_exhaustive = size(pairs, 1);
results.lethal_pairs = num2cell(lethal_fastsl, 2)';
results.same_as_exhaustive = same;
results.n_pairs_fastsl = numel(tested);
sbp.save_results(mfilename('fullpath'), results);

%% Local functions
function g = growth_without(model, deleted)
model = changeRxnBounds(model, deleted, 0, 'b');
sol = optimizeCbModel(model, 'max');
g = 0;
if sol.stat == 1
    g = sol.f;
end
end

function active = active_without(model, deleted, candidates)
% Candidate reactions carrying flux in a minimal-total-flux solution
if ~isempty(deleted)
    model = changeRxnBounds(model, deleted, 0, 'b');
end
sol = optimizeCbModel(model, 'max', 'one');
v = sol.x(findRxnIDs(model, candidates));
active = candidates(abs(v) > 1e-9);
end

Needs COBRApy.

"""Synthetic lethal reaction pairs in the E. coli core model.

A pair of reactions is synthetic lethal if deleting both stops growth
(below 1% of wild type) while deleting either one alone does not. We
find all such pairs twice:
  1. exhaustively, testing every pair of non-essential reactions;
  2. as in Fast-SL (Pratapa et al., 2015), testing only pairs that can
     possibly be lethal. If a growing flux distribution uses neither
     reaction of a pair, deleting both leaves it intact, so the pair is
     not lethal. Hence at least one reaction of a lethal pair carries flux
     in the wild-type solution, and the other carries flux once the first
     is deleted. Using sparse solutions (minimal total flux, pFBA) keeps
     the number of pairs to test small.
"""
import itertools
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import cobra
from cobra.flux_analysis import pfba
import sbp

model = cobra.io.read_sbml_model(str(sbp.DATA / "e_coli_core.xml"))
wt = model.slim_optimize()
cutoff = 0.01 * wt
rxns = sorted(r.id for r in model.reactions
              if not r.id.startswith(("EX_", "Biomass")))


def growth_without(deleted):
    with model:
        for rid in deleted:
            model.reactions.get_by_id(rid).bounds = (0, 0)
        return model.slim_optimize(error_value=0.0)


def active_without(deleted, candidates):
    """Candidate reactions carrying flux in a minimal-total-flux solution."""
    with model:
        for rid in deleted:
            model.reactions.get_by_id(rid).bounds = (0, 0)
        v = pfba(model).fluxes
    return [r for r in candidates if abs(v[r]) > 1e-9]


essential = [r for r in rxns if growth_without([r]) < cutoff]
candidates = [r for r in rxns if r not in essential]

# --- 1. Exhaustive: every pair of non-essential reactions
pairs = list(itertools.combinations(candidates, 2))
lethal_exhaustive = [p for p in pairs if growth_without(p) < cutoff]

# --- 2. Fast-SL: only pairs (i, j) with i active in the wild type and j
# active once i is deleted
tested = set()
lethal_fastsl = set()
for i in active_without([], candidates):
    for j in active_without([i], candidates):
        pair = tuple(sorted((i, j)))
        if j != i and pair not in tested:
            tested.add(pair)
            if growth_without(pair) < cutoff:
                lethal_fastsl.add(pair)
lethal_fastsl = sorted(lethal_fastsl)

print(f"{len(candidates)} non-essential reactions")
print(f"Exhaustive: {len(pairs)} pairs tested, "
      f"{len(lethal_exhaustive)} synthetic lethal")
print(f"Fast-SL:    {len(tested)} pairs tested, "
      f"{len(lethal_fastsl)} synthetic lethal")
print(f"Same pairs found: {lethal_fastsl == sorted(lethal_exhaustive)}")
partners = {r: sum(r in p for p in lethal_fastsl) for r in candidates}
top = sorted(partners, key=lambda r: (-partners[r], r))[:5]
print("Reactions in the most pairs: "
      + ", ".join(f"{r} ({partners[r]})" for r in top))

# --- Plot: which reactions form lethal pairs
involved = sorted({r for p in lethal_fastsl for r in p})
idx = {r: k for k, r in enumerate(involved)}
M = np.zeros((len(involved), len(involved)))
for a, b in lethal_fastsl:
    M[idx[a], idx[b]] = M[idx[b], idx[a]] = 1
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 5),
                               gridspec_kw={"width_ratios": [2.2, 1]})
ax1.imshow(M, cmap=ListedColormap(["#F7FBFF", "#0072B2"]), vmin=0, vmax=1)
ax1.set_xticks(range(len(involved)), involved, rotation=90, fontsize=7)
ax1.set_yticks(range(len(involved)), involved, fontsize=7)
ax1.set_title(f"{len(lethal_fastsl)} synthetic lethal pairs")
for spine in ax1.spines.values():
    spine.set_visible(False)
ax2.bar(["exhaustive", "Fast-SL"], [len(pairs), len(tested)],
        color=["#999999", "#0072B2"])
ax2.set_ylabel("Double deletions simulated")
ax2.set_title("Cost of the search")
sbp.save_figure(fig, __file__, "fig-synthetic-lethals")

sbp.save_results(__file__, {
    "n_candidates": len(candidates),
    "n_pairs_exhaustive": len(pairs),
    "lethal_pairs": [list(p) for p in lethal_fastsl],
    "same_as_exhaustive": lethal_fastsl == sorted(lethal_exhaustive),
    "n_pairs_fastsl": len(tested),
})
sbp.show()

Both searches find the same 88 synthetic lethal pairs, but Fast-SL simulates only about a quarter as many double deletions (437, against 1830). The saving grows rapidly with the size of the network and with the order of the deletions, which is what makes searches for lethal triplets and quadruplets in genome-scale models feasible.

Many of the pairs make biological sense. The reactions of upper glycolysis (PGI, PFK, FBA, TPI) are each paired with reactions of the pentose phosphate pathway (G6PDH2r, PGL, GND, RPE, TALA, TKT1, TKT2): the two pathways are alternative routes from glucose 6-phosphate into lower glycolysis, and the cell can use either, but not neither. Glutamate can be made by glutamate dehydrogenase (GLUDy) or by glutamate synthase (GLUSy), and anaplerotic PEP carboxylase (PPC) is backed up by the glyoxylate shunt (ICL, MALS). Other pairs, such as those involving water transport (H2Ot), arise from the way the model is written, and are a reminder that every prediction must be checked against biology (book, §10.7).

The exact number of double deletions that Fast-SL needs depends on which of several equally sparse solutions the solver returns, so it can differ slightly between MATLAB and Python; the set of lethal pairs cannot, and the automated checks require it to be identical.

10.3 Over-expression

10.3.1 Flux Scanning based on Enforced Objective Flux (FSEOF)

FSEOF asks which fluxes rise as the cell is forced to make more of a product. Here the product is succinate, secreted by the E. coli core model on glucose. Succinate secretion is fixed at increasing fractions of its maximum (16.4 mmol/gDW/h), and growth is maximised each time. Each of these problems has many optimal flux distributions, so the code takes the one of smallest Euclidean norm, which is unique, as for MoMA (§9.1).

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

%% Over-expression targets by FSEOF, and the production envelope
% Flux Scanning based on Enforced Objective Flux (FSEOF; book Section
% 10.3.1) for succinate secretion by the E. coli core model on glucose:
%   1. find the maximum growth rate, and the maximum succinate secretion;
%   2. enforce succinate secretion at fractions f = 0, 0.1, ..., 0.9 of its
%      maximum, and maximise growth each time;
%   3. pick the reactions whose flux rises steadily with f: candidates for
%      over-expression.
% Each FBA problem has many optimal flux distributions, so at each step we
% take the one with the smallest Euclidean norm, which is unique (as for
% MoMA in Section 9.1). The production envelope (Section 10.6.1) shows the
% largest and smallest succinate secretion possible at each growth rate.
% 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 = full(model.S); lb = model.lb; ub = model.ub; ids = model.rxns;
n = numel(ids);
bio = find(strcmp(ids, 'Biomass_Ecoli_core'));
prod = find(strcmp(ids, 'EX_succ_e'));

mu_max = optimum(S, bio, lb, ub, 1);
succ_max = optimum(S, prod, lb, ub, 1);
fprintf(['Maximum growth %.4f /h; maximum succinate secretion %.4f ' ...
    'mmol/gDW/h\n'], mu_max, succ_max);

%% FSEOF
fractions = round(0:0.1:0.9, 10);
growth = zeros(size(fractions)); F = zeros(numel(fractions), n);
for k = 1:numel(fractions)
    lb_f = lb; lb_f(prod) = fractions(k) * succ_max;   % enforce succinate
    mu = optimum(S, bio, lb_f, ub, 1);
    lb_f(bio) = mu * (1 - 1e-9);
    ub_f = ub; ub_f(bio) = mu;
    growth(k) = mu;
    F(k, :) = abs(nearest(S, zeros(n, 1), lb_f, ub_f))';
end
internal = ~startsWith(ids, {'EX_', 'Biomass'})';
steps = diff(F, 1, 1);
up = ids(internal & all(steps > 1e-4, 1))';
down = ids(internal & all(steps < -1e-4, 1))';
fprintf(['Growth falls from %.3f to %.3f /h as succinate secretion is ' ...
    'enforced\n'], growth(1), growth(end));
fprintf('Fluxes that rise with succinate secretion (%d): %s\n', ...
    numel(up), strjoin(up, ', '));
fprintf('Fluxes that fall (%d): %s\n', numel(down), strjoin(down, ', '));

%% Production envelope
mu_grid = linspace(0, mu_max, 21);
env_max = zeros(size(mu_grid)); env_min = zeros(size(mu_grid));
for k = 1:numel(mu_grid)
    lb_m = lb; lb_m(bio) = mu_grid(k) * (1 - 1e-9);
    env_max(k) = optimum(S, prod, lb_m, ub, 1);
    env_min(k) = optimum(S, prod, lb_m, ub, -1);
end

%% Plot
fig = figure('Position', [100 100 1000 400]);
subplot(1, 2, 1)
fill([mu_grid fliplr(mu_grid)], [env_min fliplr(env_max)], ...
    [0.776 0.859 0.937], 'EdgeColor', 'none');
hold on
plot(mu_grid, env_max, 'Color', [0.000 0.447 0.698]);
h = plot(growth, fractions * succ_max, 'o', 'Color', [0.835 0.369 0.000], ...
    'MarkerFaceColor', [0.835 0.369 0.000]);
xlabel('Growth rate (1/h)'); ylabel('Succinate secretion (mmol/gDW/h)');
title('Production envelope');
legend(h, {'FSEOF steps'}, 'Box', 'off');
box off
subplot(1, 2, 2)
show = {'PPC', 'PFK', 'GAPD', 'SUCCt3', 'CS', 'AKGDH'};
markers = {'o', 's', '^', 'v', '<', '>'};
colours = sbp.palette();
hold on
for k = 1:numel(show)
    plot(fractions * succ_max, F(:, strcmp(ids, show{k})), '-', ...
        'Marker', markers{k}, 'Color', colours(k, :), ...
        'MarkerFaceColor', colours(k, :), 'MarkerSize', 4);
end
ylim([0 26]);
xlabel('Enforced succinate secretion (mmol/gDW/h)');
ylabel('|flux| (mmol/gDW/h)');
title('Fluxes as succinate is enforced');
legend(show, 'Location', 'northwest', 'NumColumns', 2, 'Box', 'off');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-fseof');

results.growth_max = mu_max;
results.succinate_max = succ_max;
results.fseof_growth = growth;
results.up = up;
results.down = down;
results.envelope_growth = mu_grid;
results.envelope_max = env_max;
results.envelope_min = env_min;
sbp.save_results(mfilename('fullpath'), results);

%% Local functions
function f = optimum(S, j, lb, ub, sense)
% Largest (sense = 1) or smallest (sense = -1) value of flux j.
c = zeros(size(S, 2), 1); c(j) = -sense;
opts = optimoptions('linprog', 'Display', 'none');
[~, f] = linprog(c, [], [], S, zeros(size(S, 1), 1), lb, ub, opts);
f = -sense * f;
end

function v = nearest(S, target, lb, ub)
% argmin ||v - target||^2 with S v = 0 and lb <= v <= ub. Dependent rows
% of S are dropped, and the active-set algorithm makes quadprog exact.
n = numel(lb);
[~, R, order] = qr(S', 'vector');
S = S(sort(order(abs(diag(R)) > 1e-9 * abs(R(1, 1)))), :);
opts = optimoptions('quadprog', 'Algorithm', 'active-set', ...
    'Display', 'none');
x0 = min(max(target, lb), ub);
[v, ~, exitflag] = quadprog(eye(n), -target, [], [], S, ...
    zeros(size(S, 1), 1), lb, ub, x0, opts);
assert(exitflag > 0, 'quadprog stopped (exit flag %d)', exitflag);
end

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

"""Over-expression targets by FSEOF, and the production envelope.

Flux Scanning based on Enforced Objective Flux (FSEOF; book §10.3.1) for
succinate secretion by the E. coli core model on glucose:
  1. find the maximum growth rate, and the maximum succinate secretion;
  2. enforce succinate secretion at fractions f = 0, 0.1, ..., 0.9 of its
     maximum, and maximise growth each time;
  3. pick the reactions whose flux rises steadily with f: candidates for
     over-expression.
Each FBA problem has many optimal flux distributions, so at each step we
take the one with the smallest Euclidean norm, which is unique (as for
MoMA in §9.1). The production envelope (§10.6.1) shows the largest and
smallest succinate secretion possible at each growth rate.
"""
import numpy as np
from scipy.optimize import linprog
from scipy import sparse
import clarabel
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]
n = len(ids)
bio, prod = ids.index("Biomass_Ecoli_core"), ids.index("EX_succ_e")


def optimum(j, lb, ub, sense=1):
    """Largest (sense = 1) or smallest (sense = -1) value of flux j."""
    c = np.zeros(n)
    c[j] = -sense
    res = linprog(c, A_eq=S, b_eq=np.zeros(S.shape[0]), bounds=np.c_[lb, ub],
                  method="highs")
    return -sense * res.fun


def nearest(target, lb, ub):
    """argmin ||v - target||^2 with S v = 0 and lb <= v <= ub (Clarabel)."""
    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]
    settings = clarabel.DefaultSettings()
    settings.verbose = False
    settings.tol_gap_abs = settings.tol_gap_rel = settings.tol_feas = 1e-10
    sol = clarabel.DefaultSolver(eye, -np.asarray(target, dtype=float), A, b,
                                 [clarabel.ZeroConeT(m),
                                  clarabel.NonnegativeConeT(2 * n)],
                                 settings).solve()
    return np.array(sol.x)


mu_max = optimum(bio, lb, ub)
succ_max = optimum(prod, lb, ub)
print(f"Maximum growth {mu_max:.4f} /h; maximum succinate secretion "
      f"{succ_max:.4f} mmol/gDW/h")

# --- FSEOF
fractions = np.round(np.arange(0, 0.91, 0.1), 10)
growth, fluxes = [], []
for f in fractions:
    lb_f = lb.copy()
    lb_f[prod] = f * succ_max                  # enforce succinate secretion
    mu = optimum(bio, lb_f, ub)
    lb_f[bio] = mu * (1 - 1e-9)
    ub_f = ub.copy()
    ub_f[bio] = mu
    growth.append(mu)
    fluxes.append(nearest(np.zeros(n), lb_f, ub_f))
growth, F = np.array(growth), np.abs(np.array(fluxes))
internal = [j for j in range(n) if not ids[j].startswith(("EX_", "Biomass"))]
steps = np.diff(F, axis=0)
up = [ids[j] for j in internal if np.all(steps[:, j] > 1e-4)]
down = [ids[j] for j in internal if np.all(steps[:, j] < -1e-4)]
print(f"Growth falls from {growth[0]:.3f} to {growth[-1]:.3f} /h as "
      f"succinate secretion is enforced")
print(f"Fluxes that rise with succinate secretion ({len(up)}): "
      f"{', '.join(up)}")
print(f"Fluxes that fall ({len(down)}): {', '.join(down)}")

# --- Production envelope
mu_grid = np.linspace(0, mu_max, 21)
env_max, env_min = [], []
for mu in mu_grid:
    lb_m = lb.copy()
    lb_m[bio] = mu * (1 - 1e-9)
    env_max.append(optimum(prod, lb_m, ub, 1))
    env_min.append(optimum(prod, lb_m, ub, -1))
env_max, env_min = np.array(env_max), np.array(env_min)

# --- Plot
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.fill_between(mu_grid, env_min, env_max, color="#c6dbef")
ax1.plot(mu_grid, env_max, color="#0072B2")
ax1.plot(growth, fractions * succ_max, "o", color="#D55E00",
         label="FSEOF steps")
ax1.set_xlabel("Growth rate (1/h)")
ax1.set_ylabel("Succinate secretion (mmol/gDW/h)")
ax1.set_title("Production envelope")
ax1.legend(frameon=False)
show = ["PPC", "PFK", "GAPD", "SUCCt3", "CS", "AKGDH"]
markers = ["o", "s", "^", "v", "<", ">"]
for r, colour, marker in zip(show, sbp.PALETTE, markers):
    ax2.plot(fractions * succ_max, F[:, ids.index(r)], "-", marker=marker,
             color=colour, ms=4, label=r)
ax2.set_xlabel("Enforced succinate secretion (mmol/gDW/h)")
ax2.set_ylabel("|flux| (mmol/gDW/h)")
ax2.set_title("Fluxes as succinate is enforced")
ax2.legend(frameon=False, fontsize=9, ncol=2, loc="upper left")
ax2.set_ylim(0, 26)
sbp.save_figure(fig, __file__, "fig-fseof")

sbp.save_results(__file__, {
    "growth_max": mu_max, "succinate_max": succ_max,
    "fseof_growth": growth, "up": up, "down": down,
    "envelope_growth": mu_grid, "envelope_max": env_max,
    "envelope_min": env_min,
})
sbp.show()

As enforced succinate rises to 90% of its maximum, growth falls from 0.874 to 0.090 h−1. Ten reactions rise at every step: the glycolytic reactions from PGI to ENO, phosphoenolpyruvate carboxylase (PPC), which feeds oxaloacetate towards succinate, and the succinate exporter SUCCt3. These are the candidates for over-expression. Fourteen fall at every step, all of them serving growth: respiration (NADH16, CYTBD, ATPS4r, O2t), the non-oxidative pentose phosphate pathway (RPE, RPI, TALA, TKT1), the uptake and assimilation of ammonium and phosphate (NH4t, GLNS, GLUDy, PIt2r), ICDHyr and water transport. The right panel shows a few of these fluxes; note that AKGDH, in the TCA cycle, falls to zero, and CS falls but not at every step, so neither is in the lists. The left panel is the production envelope (§10.6.1), on which the FSEOF steps lie along the upper edge.

10.4 Other perturbations

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

10.5 Evaluating and ranking perturbations

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

10.6 Applications of constraint-based models

10.6.1 Metabolic engineering

The production envelope, the largest and smallest product secretion possible at each growth rate, is drawn in the FSEOF example of §10.3.1. For succinate in the E. coli core model the smallest secretion is zero at every growth rate: nothing couples production to growth, and strain designs such as OptKnock (§9.3.1) aim to change that.

10.6.2 Drug target identification

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

10.7 Limitations of constraint-based approaches

10.7.1 Incorrect predictions

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

10.8 Troubleshooting

10.8.1 Interpreting gene deletion simulations

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

10.9 Software tools

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

Exercises

  1. Repeat the single deletions for anaerobic growth (oxygen uptake set to zero). Which reactions become essential, and why?
  2. Use the gene-deletion functions (single_gene_deletion in COBRApy, singleGeneDeletion in the COBRA Toolbox) to find essential genes, and the GPR rules to explain every case where a reaction is essential but none of its genes is.
  3. Change the lethality cut-off from 1% to 5% and to 50% of wild-type growth. How do the lists of essential reactions and synthetic lethal pairs change?
  4. Extend the Fast-SL code to find synthetic lethal triplets: three reactions whose joint deletion is lethal, when no pair among them is. How many triple deletions does it test, compared with the \(\binom{n}{3}\) of an exhaustive search? (For genome-scale models, use the full implementations at https://github.com/RamanLab/FastSL and https://github.com/RamanLab/FastSL-py.)
  5. A minimal reactome is a set of reactions that supports growth, from which no reaction can be removed without killing the cell. Starting from all reactions, remove reactions one at a time, in random order, keeping each removal only if the cell still grows. How large is the result, and does it change with the order? (This is the second problem of the BT5240 constraint-based assignment, and book Exercise 10.8 asks the same of the genome-scale model iML1515.)
  6. Book Exercises 10.3 and 10.4: delete the two transketolases, TKT1 and TKT2, singly and together. What do you infer? Compare the flux distributions when only one of them is active, using FBA with the minimal-norm solution so that the comparison does not depend on the solver.

Going further

Deletions are the simplest perturbations. Over-expression, enzyme inhibition and changes of medium can be modelled in the same framework, and methods such as MoMA and ROOM predict how fluxes redistribute after a perturbation, instead of assuming that the mutant immediately grows optimally (book, Chapters 9 and 10).