Skip to main content

12  Designing biological circuits

Synthetic biology designs gene circuits with a function in mind, much as an engineer designs an electronic circuit, and modelling has been part of it from the start. In this chapter, we simulate the first two model-driven circuits, a clock and a switch, both built in E. coli in 2000, and then look at circuits that adapt. At the end of the chapter, in §12.A and §12.B, we go a little beyond the book, to the stability of steady states and to hysteresis, the ideas on which the design of such circuits rests.

12.1 What is synthetic biology?

12.1.1 From LEGO bricks to biobricks

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

12.2 Classic circuit design experiments

Both circuits below are analysed through their steady states and the stability of those states. §12.A, at the end of this chapter, summarises the ideas needed.

12.2.1 Designing an oscillator: the repressilator

Three repressors in a ring, each repressing the next, make a clock (Elowitz and Leibler 2000). With \(m_i\) and \(p_i\) the mRNA and protein of gene \(i\),

\[ \frac{dm_i}{dt} = -m_i + \frac{\alpha}{1 + p_j^n} + \alpha_0, \qquad \frac{dp_i}{dt} = -\beta\,(p_i - m_i), \]

where \(p_j\) is the protein repressing gene \(i\), \(\alpha_0\) the leak, the rate of transcription from a fully repressed promoter, \(\alpha + \alpha_0\) the rate from a free one, and \(\beta\) the ratio of the protein and mRNA decay rates. Time is measured in units of the mRNA lifetime. (Note that the book, in §12.2.1, swaps the roles of \(\alpha\) and \(\alpha_0\); here we follow the original paper.) By symmetry, the only steady state has \(m_i = p_i = s\) for all \(i\), with \(s\) the root of \(s = \alpha/(1 + s^n) + \alpha_0\).

Core MATLAB only.

%% Oscillations from a ring of three repressors: the repressilator
% Elowitz and Leibler (2000), in dimensionless form. Gene i makes mRNA m_i
% and protein p_i, and each protein represses the next gene round the ring
% (p3 represses gene 1, p1 gene 2, p2 gene 3):
%     dm_i/dt = -m_i + alpha/(1 + p_j^n) + alpha0
%     dp_i/dt = -beta (p_i - m_i)
% The single steady state is unstable for these parameters, and the system
% settles onto a limit cycle. We find the steady state and its eigenvalues,
% simulate, measure the period, and map where in the (alpha, beta) plane
% the steady state is unstable.
% Requires: core MATLAB only.

alpha = 216; alpha0 = 0.216; beta = 5; n = 2;
repressor = [3 1 2];    % gene i is repressed by protein repressor(i)

s = steady_state(alpha, alpha0, n);
max_real = max(real(eig(jacobian(s, alpha, beta, n, repressor))));
state = 'stable';
if max_real > 0, state = 'unstable'; end
fprintf(['Steady state m = p = %.4f; largest real part of an ' ...
    'eigenvalue = %.4f (%s)\n'], s, max_real, state);

%% Simulate from a slightly asymmetric start, and find the period from
% successive upward crossings of p1 through its steady value
rhs = @(t, y) [-y(1:3) + alpha ./ (1 + y(3 + repressor).^n) + alpha0;
               -beta * (y(4:6) - y(1:3))];
crossing = @(t, y) upward(y(4) - s);
opts = odeset('RelTol', 1e-8, 'AbsTol', 1e-10, 'Events', crossing);
y0 = [1 0 0 2 1 3];
sol = ode45(rhs, [0 300], y0, opts);
t_up = sol.xe(sol.xe > 150);               % after the transient
period = mean(diff(t_up));
t = linspace(0, 50, 1001);
Y = deval(sol, t);
late = deval(sol, linspace(150, 300, 3001), 4);
amplitude = [min(late) max(late)];
fprintf('Period = %.4f; p1 oscillates between %.4f and %.4f\n', ...
    period, amplitude(1), amplitude(2));

%% Where is the steady state unstable? A grid in the (alpha, beta) plane
alphas = logspace(0, 4, 41);
betas = logspace(-1, 3, 41);
unstable = false(numel(betas), numel(alphas));   % rows: beta
for r = 1:numel(betas)
    for c = 1:numel(alphas)
        ss = steady_state(alphas(c), alpha0, n);
        J = jacobian(ss, alphas(c), betas(r), n, repressor);
        unstable(r, c) = max(real(eig(J))) > 0;
    end
end
fprintf('Steady state unstable at %d of %d grid points\n', ...
    nnz(unstable), numel(unstable));

%% Plot
fig = figure('Position', [100 100 1000 400]);
subplot(1, 2, 1)
colours = sbp.palette();
hold on
for i = 1:3
    plot(t, Y(3 + i, :), 'Color', colours(i, :));
end
xlim([0 50]); ylim([0 75]);
xlabel('Time'); ylabel('Protein level'); title('Oscillations');
legend({'p1', 'p2', 'p3'}, 'Location', 'north', 'Orientation', ...
    'horizontal', 'Box', 'off');
box off
subplot(1, 2, 2)
% Fill the band 0.5-1 (unstable) in light blue, the band 0-0.5 in white
contourf(alphas, betas, double(unstable), [0 0.5 1], 'LineStyle', 'none');
colormap(gca, [1 1 1; 0.776 0.859 0.937]);
clim([0 1]);
hold on
contour(alphas, betas, double(unstable), [0.5 0.5], 'k');
plot(alpha, beta, 'p', 'Color', [0.835 0.369 0.000], ...
    'MarkerFaceColor', [0.835 0.369 0.000], 'MarkerSize', 12);
set(gca, 'XScale', 'log', 'YScale', 'log');
xlabel('\alpha (maximum transcription)');
ylabel('\beta (mRNA / protein lifetime)');
title('Steady state unstable (shaded)');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-repressilator');

results.steady_state = s;
results.max_real_eigenvalue = max_real;
results.period = period;
results.amplitude = amplitude;
results.n_unstable = nnz(unstable);
results.unstable = double(unstable);
sbp.save_results(mfilename('fullpath'), results);

%% Local functions
function [value, isterminal, direction] = upward(value)
% Event function for ode45: report (do not stop at) upward zero crossings.
isterminal = 0;
direction = 1;
end

function s = steady_state(alpha, alpha0, n)
% By symmetry m_i = p_i = s, with s = alpha/(1 + s^n) + alpha0.
s = fzero(@(s) alpha / (1 + s^n) + alpha0 - s, [0 alpha + alpha0]);
end

function J = jacobian(s, alpha, beta, n, repressor)
X = alpha * n * s^(n - 1) / (1 + s^n)^2;   % -d(repression)/dp
J = zeros(6);
for i = 1:3
    J(i, i) = -1;
    J(i, 3 + repressor(i)) = -X;
    J(3 + i, i) = beta;
    J(3 + i, 3 + i) = -beta;
end
end

Needs SciPy.

"""Oscillations from a ring of three repressors: the repressilator.

Elowitz and Leibler (2000), in dimensionless form. Gene i makes mRNA m_i
and protein p_i, and each protein represses the next gene round the ring
(p3 represses gene 1, p1 gene 2, p2 gene 3):
    dm_i/dt = -m_i + alpha/(1 + p_j^n) + alpha0
    dp_i/dt = -beta (p_i - m_i)
The single steady state is unstable for these parameters, and the system
settles onto a limit cycle. We find the steady state and its eigenvalues,
simulate, measure the period, and map where in the (alpha, beta) plane
the steady state is unstable.
"""
import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import brentq
import matplotlib.pyplot as plt
import sbp

alpha, alpha0, beta, n = 216.0, 0.216, 5.0, 2
repressor = [2, 0, 1]   # gene i is repressed by protein repressor[i]


def rhs(t, y, alpha=alpha, beta=beta):
    m, p = y[:3], y[3:]
    dm = -m + alpha / (1 + p[repressor] ** n) + alpha0
    dp = -beta * (p - m)
    return np.r_[dm, dp]


def steady_state(alpha, beta):
    """By symmetry m_i = p_i = s, with s = alpha/(1 + s^n) + alpha0."""
    return brentq(lambda s: alpha / (1 + s ** n) + alpha0 - s, 0,
                  alpha + alpha0)


def jacobian(s, alpha, beta):
    X = alpha * n * s ** (n - 1) / (1 + s ** n) ** 2   # -d(repression)/dp
    J = np.zeros((6, 6))
    for i in range(3):
        J[i, i] = -1
        J[i, 3 + repressor[i]] = -X
        J[3 + i, i] = beta
        J[3 + i, 3 + i] = -beta
    return J


s = steady_state(alpha, beta)
eig = np.linalg.eigvals(jacobian(s, alpha, beta))
max_real = eig.real.max()
state = "unstable" if max_real > 0 else "stable"
print(f"Steady state m = p = {s:.4f}; largest real part of an "
      f"eigenvalue = {max_real:.4f} ({state})")

# --- Simulate from a slightly asymmetric start, and find the period from
# successive upward crossings of p1 through its steady value
def crossing(t, y):
    return y[3] - s
crossing.direction = 1

y0 = [1.0, 0.0, 0.0, 2.0, 1.0, 3.0]
sol = solve_ivp(rhs, [0, 300], y0, rtol=1e-8, atol=1e-10,
                events=crossing, dense_output=True)
t_up = sol.t_events[0]
t_up = t_up[t_up > 150]                  # after the transient has died away
period = np.mean(np.diff(t_up))
t = np.linspace(0, 50, 1001)
Y = sol.sol(t)
late = sol.sol(np.linspace(150, 300, 3001))[3]
amplitude = [late.min(), late.max()]
print(f"Period = {period:.4f}; p1 oscillates between {amplitude[0]:.4f} "
      f"and {amplitude[1]:.4f}")

# --- Where is the steady state unstable? A grid in the (alpha, beta) plane
alphas = np.logspace(0, 4, 41)
betas = np.logspace(-1, 3, 41)
unstable = np.zeros((len(betas), len(alphas)), dtype=bool)  # rows: beta
for r, b in enumerate(betas):
    for c, a in enumerate(alphas):
        ss = steady_state(a, b)
        unstable[r, c] = np.linalg.eigvals(jacobian(ss, a, b)).real.max() > 0
print(f"Steady state unstable at {unstable.sum()} of {unstable.size} "
      f"grid points")

# --- Plot
sbp.style()
fig, axes = plt.subplots(1, 2, figsize=(10, 4))
for i, name in enumerate(["p1", "p2", "p3"]):
    axes[0].plot(t, Y[3 + i], color=sbp.PALETTE[i], label=name)
axes[0].set_xlabel("Time")
axes[0].set_ylabel("Protein level")
axes[0].set_title("Oscillations")
axes[0].set_xlim(0, 50)
axes[0].set_ylim(0, 75)
axes[0].legend(frameon=False, loc="upper center", ncol=3)
axes[1].contourf(alphas, betas, unstable.astype(float), levels=[0.5, 1.5],
                 colors=["#c6dbef"])
axes[1].contour(alphas, betas, unstable.astype(float), levels=[0.5],
                colors="k", linewidths=1)
axes[1].plot(alpha, beta, "*", color="#D55E00", ms=12)
axes[1].set_xscale("log")
axes[1].set_yscale("log")
axes[1].set_xlabel(r"$\alpha$ (maximum transcription)")
axes[1].set_ylabel(r"$\beta$ (mRNA / protein lifetime)")
axes[1].set_title("Steady state unstable (shaded)")
sbp.save_figure(fig, __file__, "fig-repressilator")

sbp.save_results(__file__, {
    "steady_state": s, "max_real_eigenvalue": max_real,
    "period": period, "amplitude": amplitude,
    "n_unstable": int(unstable.sum()), "unstable": unstable.astype(int),
})
sbp.show()

With the parameters of the original paper, the steady state, at \(s \approx 6.02\), is unstable: a pair of complex eigenvalues has a positive real part, 0.21, so small deviations spiral outwards. With nowhere stable to settle, the system approaches a limit cycle, in which the three proteins peak in turn and the pattern repeats every 8.7 time units. Unlike the closed loops of the Lotka–Volterra model (Chapter 1), the limit cycle is the same from every starting point, and the system returns to it after a disturbance.

The map on the right shows where in the \((\alpha, \beta)\) plane the steady state is unstable, and the circuit oscillates. Oscillation needs strong transcription, \(\alpha\) above about 8 here, and protein and mRNA lifetimes that are not too different. Elowitz and Leibler used this analysis to design their circuit: they added tags that made the repressor proteins degrade quickly, bringing \(\beta\) into the oscillating region.

12.2.2 Toggle switch

Gardner, Cantor and Collins built a switch from two genes that repress each other (Gardner et al. 2000). In dimensionless form,

\[ \frac{du}{dt} = \frac{a_1}{1 + v^n} - u, \qquad \frac{dv}{dt} = \frac{a_2}{1 + u^n} - v , \]

where \(u\) and \(v\) are the two repressors, \(a_1\) and \(a_2\) the strengths of their promoters, and \(n\) the cooperativity of repression. The nullclines are the curves on which one of the derivatives is zero; steady states lie where they cross. On the \(v\)-nullcline, \(v = a_2/(1 + u^n)\), so the steady values of \(u\) are the roots of a single equation in \(u\), which the code finds by scanning for sign changes and refining each with fzero or brentq.

Core MATLAB only.

%% Steady states, stability and the phase plane: a genetic toggle switch
% Two genes repress each other (Gardner, Cantor and Collins, 2000):
%     du/dt = a1/(1 + v^n) - u
%     dv/dt = a2/(1 + u^n) - v
% We find every steady state, classify each by the eigenvalues of the
% Jacobian matrix there, and draw the phase plane.
% Requires: core MATLAB only.

a1 = 10; a2 = 10; n = 2;
toggle = @(t, y) [a1 / (1 + y(2)^n) - y(1); a2 / (1 + y(1)^n) - y(2)];
jacobian = @(u, v) [-1, -a1 * n * v^(n - 1) / (1 + v^n)^2;
                    -a2 * n * u^(n - 1) / (1 + u^n)^2, -1];

% Steady states: on the v-nullcline v = a2/(1 + u^n), so the steady values
% of u are the roots of g(u) = a1/(1 + v(u)^n) - u, which lie in [0, a1].
g = @(u) a1 ./ (1 + (a2 ./ (1 + u.^n)).^n) - u;
grid = linspace(0, a1, 10001);
vals = g(grid);
roots = [];
for k = find(sign(vals(1:end-1)) ~= sign(vals(2:end)))
    u = fzero(g, [grid(k) grid(k + 1)]);
    if isempty(roots) || u - roots(end) > 1e-6  % a root on a grid point is
        roots(end + 1) = u; %#ok<AGROW>          % found twice; keep it once
    end
end
for k = 1:numel(roots)
    u = roots(k);
    v = a2 / (1 + u^n);
    e = sort(real(eig(jacobian(u, v))))';
    states(k) = struct('u', u, 'v', v, 'eigenvalues', e, ...
        'stable', max(e) < 0); %#ok<SAGROW>
    kinds = {'unstable (saddle)', 'stable'};
    fprintf(['Steady state u = %.4f, v = %.4f: eigenvalues %.4f, ' ...
        '%.4f -> %s\n'], ...
        u, v, e(1), e(2), kinds{states(k).stable + 1});
end

%% Trajectories from a grid of starting points (off the diagonal u = v,
% which by symmetry leads to the saddle)
[U0, V0] = ndgrid(linspace(0.25, 11.75, 8), linspace(0.5, 12, 8));
opts = odeset('RelTol', 1e-8, 'AbsTol', 1e-10);
trajs = cell(numel(U0), 1);
ends_high_u = false(numel(U0), 1);
for k = 1:numel(U0)
    [~, trajs{k}] = ode45(toggle, linspace(0, 20, 401), [U0(k) V0(k)], opts);
    ends_high_u(k) = trajs{k}(end, 1) > trajs{k}(end, 2);
end

%% Plot
fig = figure('Position', [100 100 600 550]);
[U, V] = meshgrid(linspace(0, 12, 25));
quiver(U, V, a1 ./ (1 + V.^n) - U, a2 ./ (1 + U.^n) - V, ...
    'Color', [0.8 0.8 0.8]);
hold on
for k = 1:numel(trajs)
    c = [0.902 0.624 0.000];                  % orange: ends with V high
    if ends_high_u(k), c = [0.000 0.447 0.698]; end   % blue: U high
    plot(trajs{k}(:, 1), trajs{k}(:, 2), '-', 'Color', c, 'LineWidth', 0.8);
end
x = linspace(0, 12, 400);
h1 = plot(a1 ./ (1 + x.^n), x, 'k-', 'LineWidth', 2);
h2 = plot(x, a2 ./ (1 + x.^n), 'k--', 'LineWidth', 2);
for k = 1:numel(states)
    if states(k).stable, fc = 'k'; else, fc = 'w'; end
    plot(states(k).u, states(k).v, 'o', 'MarkerSize', 10, ...
        'MarkerEdgeColor', 'k', 'MarkerFaceColor', fc, 'LineWidth', 1.5);
end
axis([0 12 0 12]);
xlabel('Repressor 1, u'); ylabel('Repressor 2, v');
title('Two stable states (filled) and a saddle (open)');
legend([h1 h2], {'u-nullcline (du/dt = 0)', 'v-nullcline (dv/dt = 0)'}, ...
    'Location', 'northeast', 'FontSize', 9);
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-toggle-switch');

results.steady_states = states;
results.fraction_to_high_u = mean(ends_high_u);
sbp.save_results(mfilename('fullpath'), results);

Needs SciPy.

"""Steady states, stability and the phase plane: a genetic toggle switch.

Two genes repress each other (Gardner, Cantor and Collins, 2000):
    du/dt = a1/(1 + v^n) - u
    dv/dt = a2/(1 + u^n) - v
We find every steady state, classify each by the eigenvalues of the
Jacobian matrix there, and draw the phase plane.
"""
import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import brentq
import matplotlib.pyplot as plt
import sbp

a1, a2, n = 10.0, 10.0, 2


def toggle(t, y):
    u, v = y
    return [a1 / (1 + v ** n) - u, a2 / (1 + u ** n) - v]


def jacobian(u, v):
    return np.array([[-1, -a1 * n * v ** (n - 1) / (1 + v ** n) ** 2],
                     [-a2 * n * u ** (n - 1) / (1 + u ** n) ** 2, -1]])


# Steady states: on the v-nullcline v = a2/(1 + u^n), so the steady values
# of u are the roots of g(u) = a1/(1 + v(u)^n) - u, which lie in [0, a1].
def g(u):
    return a1 / (1 + (a2 / (1 + u ** n)) ** n) - u


grid = np.linspace(0, a1, 10001)
vals = g(grid)
roots = []
for k in np.flatnonzero(np.sign(vals[:-1]) != np.sign(vals[1:])):
    u = brentq(g, grid[k], grid[k + 1])
    if not roots or u - roots[-1] > 1e-6:   # a root on a grid point is
        roots.append(u)                     # found twice; keep it once
states = []
for u in roots:
    v = a2 / (1 + u ** n)
    eig = np.sort(np.linalg.eigvals(jacobian(u, v)).real)
    kind = "stable" if eig.max() < 0 else "unstable (saddle)"
    states.append({"u": u, "v": v, "eigenvalues": eig,
                   "stable": bool(eig.max() < 0)})
    print(f"Steady state u = {u:.4f}, v = {v:.4f}: eigenvalues "
          f"{eig[0]:.4f}, {eig[1]:.4f} -> {kind}")

# --- Trajectories from a grid of starting points (off the diagonal u = v,
# which by symmetry leads to the saddle)
starts = [(u0, v0) for u0 in np.linspace(0.25, 11.75, 8)
          for v0 in np.linspace(0.5, 12, 8)]
trajs = [solve_ivp(toggle, [0, 20], y0, rtol=1e-8, atol=1e-10,
                   t_eval=np.linspace(0, 20, 401)).y for y0 in starts]
ends_high_u = [bool(Y[0, -1] > Y[1, -1]) for Y in trajs]

# --- Plot
sbp.style()
fig, ax = plt.subplots(figsize=(6, 5.5))
U, V = np.meshgrid(np.linspace(0, 12, 25), np.linspace(0, 12, 25))
dU, dV = a1 / (1 + V ** n) - U, a2 / (1 + U ** n) - V
ax.quiver(U, V, dU, dV, color="#cccccc", angles="xy")
for Y, high in zip(trajs, ends_high_u):
    ax.plot(Y[0], Y[1], "-", lw=0.8,
            color="#0072B2" if high else "#E69F00")
x = np.linspace(0, 12, 400)
ax.plot(a1 / (1 + x ** n), x, "k-", lw=2, label="u-nullcline (du/dt = 0)")
ax.plot(x, a2 / (1 + x ** n), "k--", lw=2, label="v-nullcline (dv/dt = 0)")
for s in states:
    ax.plot(s["u"], s["v"], "o", ms=10, mec="k", mew=1.5, clip_on=False,
            color="k" if s["stable"] else "white", zorder=3)
ax.set_xlim(0, 12)
ax.set_ylim(0, 12)
ax.set_xlabel("Repressor 1, u")
ax.set_ylabel("Repressor 2, v")
ax.set_title("Two stable states (filled) and a saddle (open)")
ax.legend(frameon=True, loc="upper right", fontsize=9)
sbp.save_figure(fig, __file__, "fig-toggle-switch")

sbp.save_results(__file__, {
    "steady_states": states,
    "fraction_to_high_u": np.mean(ends_high_u),
})
sbp.show()

With \(a_1 = a_2 = 10\) and \(n = 2\), the nullclines cross three times. Two of the steady states are stable, one with \(u\) high and \(v\) low, the other the reverse. Between them lies a saddle at \(u = v = 2\), with one positive eigenvalue. Every trajectory ends at one of the two stable states (blue if it reaches high \(u\), orange if it reaches high \(v\)), and the line through the saddle along which trajectories approach it, here the diagonal \(u = v\), divides the plane into their two basins of attraction. The cell carrying the circuit thus has two distinct states, and stays in whichever it is put.

Bistability needs cooperativity: with \(n = 1\), the nullclines cross only once, whatever the promoter strengths (Exercise 1). §12.B follows the switch as it is flipped back and forth.

12.3 Designing modules

12.3.1 Exploring the design space

Many sensory systems adapt: after a change in their input, the output responds and then returns to its original level, ready to detect the next change. Bacterial chemotaxis is the classic example. When the concentration of an attractant rises, E. coli tumbles less often, but within minutes its tumbling frequency returns to where it was. Barkai and Leibler showed in a model that this adaptation could be exact for any values of the rate constants of the circuit (Barkai and Leibler 1997), and experiments confirmed that the precision of adaptation stayed nearly the same when the levels of the chemotaxis proteins were changed many-fold, while the time taken to adapt varied widely (Alon et al. 1999). The underlying principle is integral feedback (Yi et al. 2000).

A minimal circuit shows how it works. A signal \(u\) makes an output \(y\), which is removed by a controller \(x\); \(y\) makes \(x\), and \(x\) is degraded by an enzyme with Michaelis constant \(K\):

\[ \frac{dy}{dt} = cu - exy, \qquad \frac{dx}{dt} = ay - \frac{bx}{K + x}. \]

When the enzyme is saturated, \(K \ll x\), the second equation becomes \(dx/dt \approx a(y - b/a)\): the controller accumulates the time integral of the deviation of \(y\) from \(b/a\). It can therefore come to rest only when \(y = b/a\), whatever the signal and whatever the values of \(c\) and \(e\). The code compares \(K = 0.01\), close to this limit, with \(K = 1\), first by simulating a doubling of the signal, then by computing the steady states for 81 combinations of the four rate constants, each at half, once and twice its nominal value.

Core MATLAB only.

%% Robust adaptation by integral feedback
% A signal u drives an output y, which is removed by a controller x; y in
% turn makes x, and x is degraded by an enzyme with Michaelis constant K:
%     dy/dt = c u - e x y
%     dx/dt = a y - b x / (K + x)
% When the enzyme is saturated (K small), x integrates the difference
% between a y and b, and y returns to b/a after any change in u, whatever
% the other parameters: perfect adaptation. We compare K = 0.01 with
% K = 1, first in time, then for 81 combinations of a, b, c and e, each
% at half, once and twice its nominal value of 1.
% Requires: core MATLAB only.

K_values = [0.01 1];
u_of_t = @(t) 1 + (t >= 20 && t < 60);   % u doubles at t = 20, falls at 60

%% Time courses with the nominal parameters
t = linspace(0, 100, 2001);
courses = zeros(2, numel(t)); peaks = zeros(1, 2);
opts = odeset('RelTol', 1e-8, 'AbsTol', 1e-10, 'MaxStep', 0.1);
for k = 1:2
    K = K_values(k);
    y0 = steady_y(1, 1, 1, 1, 1, K);
    x0 = 1 / y0;                         % from c u = e x y
    rhs = @(t, z) [u_of_t(t) - z(2) * z(1); z(1) - z(2) / (K + z(2))];
    [~, Z] = ode15s(rhs, t, [y0 x0], opts);
    courses(k, :) = Z(:, 1)';
    peaks(k) = max(courses(k, t >= 20 & t < 60));
    fprintf(['K = %g: y = %.4f before the step, peak %.4f, %.4f just ' ...
        'before u falls again\n'], K, y0, peaks(k), ...
        courses(k, abs(t - 59.95) < 1e-9));
end

%% 81 parameter sets: how much does the steady-state y change when u
% doubles?
factors = [0.5 1 2];
[e_, c_, b_, a_] = ndgrid(factors);      % a varies slowest, as in Python
params = [a_(:) b_(:) c_(:) e_(:)];
ratio = zeros(81, 2); level = zeros(81, 2);
for k = 1:2
    for i = 1:81
        p = num2cell(params(i, :));
        level(i, k) = steady_y(1, p{:}, K_values(k));
        ratio(i, k) = steady_y(2, p{:}, K_values(k)) / level(i, k);
    end
    fprintf(['K = %g: y(u = 2) / y(u = 1) ranges from %.4f to %.4f; ' ...
        'the level y(u = 1) from %.3f to %.3f\n'], K_values(k), ...
        min(ratio(:, k)), max(ratio(:, k)), min(level(:, k)), ...
        max(level(:, k)));
end

%% Plot
colours = [0.000 0.447 0.698; 0.902 0.624 0.000];
styles = {'-', '--'};
markers = {'o', 's'};
fig = figure('Position', [100 100 1000 400]);
subplot(1, 2, 1)
patch([20 60 60 20], [0.3 0.3 2.2 2.2], [0.93 0.93 0.93], ...
    'EdgeColor', 'none');
hold on
h = gobjects(1, 2);
for k = 1:2
    h(k) = plot(t, courses(k, :), styles{k}, 'Color', colours(k, :));
end
text(40, 2.05, 'u = 2', 'HorizontalAlignment', 'center', ...
    'Color', [0.4 0.4 0.4]);
xlim([0 100]); ylim([0.3 2.2]);
yticks([0.5 1 1.5 2]);
xlabel('Time'); ylabel('Output y');
title('Response to a step in the signal');
legend(h, {'K = 0.01', 'K = 1'}, 'Box', 'off');
box off
subplot(1, 2, 2)
hold on
for k = 1:2
    scatter(level(:, k), ratio(:, k), 36, colours(k, :), markers{k}, ...
        'filled', 'MarkerFaceAlpha', 0.7);
end
yline(1, ':', 'Color', [0.6 0.6 0.6]);
set(gca, 'XScale', 'log', 'XMinorTick', 'off');
xlim([0.15 5]); ylim([0.98 1.36]);
xticks([0.2 0.5 1 2 4]);
xlabel('Steady-state y before the step'); ylabel('y after / y before');
title('81 parameter sets');
legend({'K = 0.01', 'K = 1'}, 'Box', 'off', 'Location', 'northwest');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-integral-feedback');

results.peak = peaks;
results.ratio_K001 = ratio(:, 1)';
results.ratio_K1 = ratio(:, 2)';
results.level_K001 = level(:, 1)';
results.level_K1 = level(:, 2)';
sbp.save_results(mfilename('fullpath'), results);

%% Local function
function y = steady_y(u, a, b, c, e, K)
% At steady state, r = x / (K + x) = a y / b solves
% e K b r^2 + a c u r - a c u = 0.
p = a * c * u;
r = (-p + sqrt(p^2 + 4 * e * K * b * p)) / (2 * e * K * b);
y = r * b / a;
end

Needs SciPy.

"""Robust adaptation by integral feedback.

A signal u drives an output y, which is removed by a controller x; y in
turn makes x, and x is degraded by an enzyme with Michaelis constant K:
    dy/dt = c u - e x y
    dx/dt = a y - b x / (K + x)
When the enzyme is saturated (K small), x integrates the difference
between a y and b, and y returns to b/a after any change in u, whatever
the other parameters: perfect adaptation. We compare K = 0.01 with
K = 1, first in time, then for 81 combinations of a, b, c and e, each
at half, once and twice its nominal value of 1.
"""
import itertools
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
import sbp

K_values = [0.01, 1.0]


def steady_y(u, a, b, c, e, K):
    """At steady state, r = x / (K + x) = a y / b solves
    e K b r^2 + a c u r - a c u = 0."""
    p = a * c * u
    r = (-p + np.sqrt(p ** 2 + 4 * e * K * b * p)) / (2 * e * K * b)
    return r * b / a


def u_of_t(t):
    return 2.0 if 20 <= t < 60 else 1.0


def rhs(t, z, K, a=1, b=1, c=1, e=1):
    y, x = z
    return [c * u_of_t(t) - e * x * y, a * y - b * x / (K + x)]


# --- Time courses with the nominal parameters: u doubles at t = 20 and
# returns to 1 at t = 60
t = np.linspace(0, 100, 2001)
courses, peaks = {}, []
for K in K_values:
    y0 = steady_y(1, 1, 1, 1, 1, K)
    x0 = 1 / y0                     # from c u = e x y
    sol = solve_ivp(rhs, [0, 100], [y0, x0], args=(K,), method="Radau",
                    t_eval=t, rtol=1e-8, atol=1e-10, max_step=0.1)
    courses[K] = sol.y[0]
    peaks.append(sol.y[0][(t >= 20) & (t < 60)].max())
    print(f"K = {K}: y = {y0:.4f} before the step, peak {peaks[-1]:.4f}, "
          f"{courses[K][t == 59.95][0]:.4f} just before u falls again")

# --- 81 parameter sets: how much does the steady-state y change when u
# doubles?
factors = [0.5, 1.0, 2.0]
params = np.array(list(itertools.product(factors, repeat=4)))   # a b c e
ratio = {K: np.array([steady_y(2, *p, K) / steady_y(1, *p, K)
                      for p in params]) for K in K_values}
level = {K: np.array([steady_y(1, *p, K) for p in params])
         for K in K_values}
for K in K_values:
    print(f"K = {K}: y(u = 2) / y(u = 1) ranges from {ratio[K].min():.4f} "
          f"to {ratio[K].max():.4f}; the level y(u = 1) from "
          f"{level[K].min():.3f} to {level[K].max():.3f}")

# --- Plot
sbp.style()
colours = {0.01: "#0072B2", 1.0: "#E69F00"}
styles = {0.01: "-", 1.0: "--"}
markers = {0.01: "o", 1.0: "s"}
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
for K in K_values:
    ax1.plot(t, courses[K], styles[K], color=colours[K],
             label=f"K = {K:g}")
ax1.axvspan(20, 60, color="#eeeeee", zorder=0)
ax1.text(40, 2.05, "u = 2", ha="center", color="#666666")
ax1.set_xlim(0, 100)
ax1.set_ylim(0.3, 2.2)
ax1.set_yticks([0.5, 1, 1.5, 2])
ax1.set_xlabel("Time")
ax1.set_ylabel("Output y")
ax1.set_title("Response to a step in the signal")
ax1.legend(frameon=False)
for K in K_values:
    ax2.semilogx(level[K], ratio[K], markers[K], color=colours[K],
                 alpha=0.7, label=f"K = {K:g}")
ax2.axhline(1, color="#999999", ls=":", lw=1)
ax2.set_xlim(0.15, 5)
ax2.set_ylim(0.98, 1.36)
ax2.set_xticks([0.2, 0.5, 1, 2, 4], labels=["0.2", "0.5", "1", "2", "4"])
ax2.minorticks_off()
ax2.set_xlabel("Steady-state y before the step")
ax2.set_ylabel("y after / y before")
ax2.set_title("81 parameter sets")
ax2.legend(frameon=False, loc="upper left")
sbp.save_figure(fig, __file__, "fig-integral-feedback")

sbp.save_results(__file__, {
    "peak": peaks,
    "ratio_K001": ratio[0.01], "ratio_K1": ratio[1.0],
    "level_K001": level[0.01], "level_K1": level[1.0],
})
sbp.show()

With \(K = 0.01\), the output jumps by about half when the signal doubles at \(t = 20\), and returns within a few time units to within 0.5% of its earlier level. With \(K = 1\), it settles 18% higher. When the signal falls back at \(t = 60\), both circuits dip and return to where they started. Across the 81 parameter sets, the circuit with the saturated enzyme always adapts to within about 6%, and in four cases out of five to within 1%, while the other changes its output by 3% to 34%, depending on the parameters.

Notice what is robust and what is not. The level to which the output returns, \(b/a\), varies sixteen-fold across the parameter sets, and the size and duration of the response vary too. What the structure of the circuit guarantees is the return to that level. Robustness is always robustness of a particular feature to particular perturbations, and a circuit can be robust in one respect and sensitive in another. Searching all 16,038 connected three-node enzyme circuits, Ma and colleagues found that only two families of topologies adapt well: negative feedback loops with a buffering node, such as this one, and incoherent feed-forward loops (Ma et al. 2009) (book, §12.3.1).

12.3.2 Systems-theoretic approaches

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

12.3.3 Automating circuit design

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

12.4 Design principles of biological networks

12.4.1 Redundancy

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

12.4.2 Modularity

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

12.4.3 Exaptation

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

12.4.4 Robustness

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

12.5 Computing with cells

12.5.1 Adleman’s classic experiment

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

12.5.2 Examples of circuits that can compute

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

12.5.3 DNA data storage

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

12.6 Challenges

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

12.7 Software tools

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

12.A Steady states and their stability

A steady state of \(d\mathbf{x}/dt = \mathbf{f}(\mathbf{x})\) is a point \(\mathbf{x}^*\) where \(\mathbf{f}(\mathbf{x}^*) = \mathbf{0}\). Whether the system returns to it after a small push depends on the Jacobian matrix, \(J_{ij} = \partial f_i / \partial x_j\), evaluated at \(\mathbf{x}^*\). Near the steady state, a small deviation \(\boldsymbol{\delta}\) obeys \(d\boldsymbol{\delta}/dt \approx J \boldsymbol{\delta}\), and so it grows or shrinks according to the eigenvalues of \(J\):

  • if every eigenvalue has a negative real part, all small deviations die away, and the steady state is stable;
  • if any eigenvalue has a positive real part, some deviation grows, and the steady state is unstable. If the other eigenvalues are negative, it is a saddle: the system approaches it along some directions and leaves along others.

Eigenvalues with an imaginary part make the deviations spiral.

12.B Bistability and hysteresis

In the experiments, the switch was flipped by an inducer that weakens one of the repressors, which in the model amounts to changing a promoter strength. We fix \(a_2 = 5\), vary \(a_1\) from 1 to 12, and find all the steady states for each value. Then we simulate the circuit while raising \(a_1\) in small steps, letting it settle at each step, and lowering it again.

Core MATLAB only.

%% Bistability and hysteresis in the toggle switch
% The same toggle switch,
%     du/dt = a1/(1 + v^n) - u,   dv/dt = a2/(1 + u^n) - v,
% now with a2 = 5 fixed and a1, the strength of the promoter making u,
% varied from 1 to 12 (in an experiment, an inducer does this). For each a1
% we find all steady states and their stability. Then we simulate the
% switch while slowly raising a1 and lowering it again: the state the
% switch is in depends on where it has been.
% Requires: core MATLAB only.

a2 = 5; n = 2;
a1_values = round(1:0.05:12, 10);

branches = cell(size(a1_values));
n_states = zeros(size(a1_values));
for k = 1:numel(a1_values)
    branches{k} = steady_states(a1_values(k), a2, n);
    n_states(k) = size(branches{k}, 1);
end
bistable = a1_values(n_states == 3);
fprintf('Bistable (three steady states) for a1 from %.2f to %.2f\n', ...
    min(bistable), max(bistable));

%% Hysteresis: raise a1 step by step, letting the switch settle each
% time from where it was, then lower it again
ramp = round(1:0.25:12, 10);
up = sweep(ramp, [0 a2], a2, n);                   % start with u off
down = flipud(sweep(fliplr(ramp), up(end, :), a2, n));
% u is 'on' when it exceeds v
switch_up = ramp(find(up(:, 1) > up(:, 2), 1));    % first a1 with u on
switch_down = ramp(find(down(:, 1) > down(:, 2), 1));  % lowest a1 with u on
fprintf(['Raising a1, u switches on at a1 = %g; lowering a1, u stays on ' ...
    'down to a1 = %g\n'], switch_up, switch_down);
up = up(:, 1)'; down = down(:, 1)';

%% Plot
fig = figure('Position', [100 100 700 450]);
hold on
xregion = [min(bistable) max(bistable)];
patch(xregion([1 2 2 1]), [-1 -1 13 13], [0.93 0.93 0.93], ...
    'EdgeColor', 'none');
for k = 1:numel(a1_values)
    b = branches{k};
    plot(a1_values(k) * ones(sum(b(:, 2)), 1), b(b(:, 2) == 1, 1), ...
        'k.', 'MarkerSize', 5);
    plot(a1_values(k) * ones(sum(~b(:, 2)), 1), b(b(:, 2) == 0, 1), ...
        '.', 'Color', [0.73 0.73 0.73], 'MarkerSize', 5);
end
h1 = plot(ramp, up, '^', 'Color', [0.000 0.447 0.698]);
h2 = plot(ramp, down, 'v', 'Color', [0.902 0.624 0.000]);
h3 = plot(NaN, NaN, 'k.', 'MarkerSize', 5);
h4 = plot(NaN, NaN, '.', 'Color', [0.73 0.73 0.73], 'MarkerSize', 5);
xlim([0.5 12.5]); ylim([-0.5 12.5]);
xlabel('Promoter strength a1'); ylabel('Steady-state level of u');
title('Bistability (shaded) and hysteresis');
legend([h1 h2 h3 h4], {'simulated, a1 increasing', ...
    'simulated, a1 decreasing', 'stable steady state', ...
    'unstable steady state'}, ...
    'Location', 'northwest', 'Box', 'off', 'FontSize', 9);
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-hysteresis');

results.bistable_range = [min(bistable) max(bistable)];
results.n_states = n_states;
results.switch_up = switch_up;
results.switch_down = switch_down;
results.up = up;
results.down = down;
sbp.save_results(mfilename('fullpath'), results);

%% Local functions
function out = steady_states(a1, a2, n)
% All steady values of u, as roots of g(u) on [0, a1], with stability:
% one row [u, is_stable] per steady state.
g = @(u) a1 ./ (1 + (a2 ./ (1 + u.^n)).^n) - u;
grid = linspace(0, a1, 4001);
vals = g(grid);
out = zeros(0, 2);
for k = find(sign(vals(1:end-1)) ~= sign(vals(2:end)))
    u = fzero(g, [grid(k) grid(k + 1)]);
    if ~isempty(out) && u - out(end, 1) <= 1e-6
        continue
    end
    v = a2 / (1 + u^n);
    J = [-1, -a1 * n * v^(n - 1) / (1 + v^n)^2;
         -a2 * n * u^(n - 1) / (1 + u^n)^2, -1];
    out(end + 1, :) = [u, max(real(eig(J))) < 0]; %#ok<AGROW>
end
end

function out = sweep(a1_path, y0, a2, n)
% Settle at each a1 in turn, starting from the previous state.
opts = odeset('RelTol', 1e-8, 'AbsTol', 1e-10);
y = y0;
out = zeros(numel(a1_path), 2);
for k = 1:numel(a1_path)
    a1 = a1_path(k);
    f = @(t, y) [a1 / (1 + y(2)^n) - y(1); a2 / (1 + y(1)^n) - y(2)];
    [~, Y] = ode45(f, [0 100], y, opts);
    y = Y(end, :);
    out(k, :) = y;
end
end

Needs SciPy.

"""Bistability and hysteresis in the toggle switch.

The same toggle switch,
    du/dt = a1/(1 + v^n) - u,   dv/dt = a2/(1 + u^n) - v,
now with a2 = 5 fixed and a1, the strength of the promoter making u,
varied from 1 to 12 (in an experiment, an inducer does this). For each a1
we find all steady states and their stability. Then we simulate the
switch while slowly raising a1 and lowering it again: the state the
switch is in depends on where it has been.
"""
import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import brentq
import matplotlib.pyplot as plt
import sbp

a2, n = 5.0, 2
a1_values = np.round(np.arange(1, 12.0001, 0.05), 10)


def steady_states(a1):
    """All steady values of u, as roots of g(u) on [0, a1], with stability."""
    def g(u):
        return a1 / (1 + (a2 / (1 + u ** n)) ** n) - u
    grid = np.linspace(0, a1, 4001)
    vals = g(grid)
    roots = []
    for k in np.flatnonzero(np.sign(vals[:-1]) != np.sign(vals[1:])):
        u = brentq(g, grid[k], grid[k + 1])
        if not roots or u - roots[-1] > 1e-6:
            roots.append(u)
    out = []
    for u in roots:
        v = a2 / (1 + u ** n)
        J = np.array([[-1, -a1 * n * v ** (n - 1) / (1 + v ** n) ** 2],
                      [-a2 * n * u ** (n - 1) / (1 + u ** n) ** 2, -1]])
        out.append((u, bool(np.linalg.eigvals(J).real.max() < 0)))
    return out


branches = [steady_states(a1) for a1 in a1_values]
n_states = np.array([len(b) for b in branches])
bistable = a1_values[n_states == 3]
print(f"Bistable (three steady states) for a1 from {bistable.min():.2f} to "
      f"{bistable.max():.2f}")


# --- Hysteresis: raise a1 step by step, letting the switch settle each
# time from where it was, then lower it again
def toggle(t, y, a1):
    u, v = y
    return [a1 / (1 + v ** n) - u, a2 / (1 + u ** n) - v]


def sweep(a1_path, y0):
    """Settle at each a1 in turn, starting from the previous state."""
    y, out = np.array(y0, dtype=float), []
    for a1 in a1_path:
        y = solve_ivp(toggle, [0, 100], y, args=(a1,), rtol=1e-8,
                      atol=1e-10).y[:, -1]
        out.append(y)
    return np.array(out)


ramp = np.round(np.arange(1, 12.0001, 0.25), 10)
up = sweep(ramp, [0.0, a2])                        # start with u off
down = sweep(ramp[::-1], up[-1])[::-1]
# u is 'on' when it exceeds v
switch_up = ramp[np.argmax(up[:, 0] > up[:, 1])]   # first a1 with u on
switch_down = ramp[np.argmax(down[:, 0] > down[:, 1])]  # lowest a1 with u on
print(f"Raising a1, u switches on at a1 = {switch_up:g}; lowering a1, u "
      f"stays on down to a1 = {switch_down:g}")
up, down = up[:, 0], down[:, 0]

# --- Plot
sbp.style()
fig, ax = plt.subplots(figsize=(7, 4.5))
for a1, b in zip(a1_values, branches):
    for u, stable in b:
        ax.plot(a1, u, ".", ms=3, color="k" if stable else "#bbbbbb")
ax.plot(ramp, up, "^", color="#0072B2", ms=6, mfc="none",
        label="simulated, a1 increasing")
ax.plot(ramp, down, "v", color="#E69F00", ms=6, mfc="none",
        label="simulated, a1 decreasing")
ax.plot([], [], ".", color="k", label="stable steady state")
ax.plot([], [], ".", color="#bbbbbb", label="unstable steady state")
ax.axvspan(bistable.min(), bistable.max(), color="#eeeeee", zorder=0)
ax.set_xlim(0.5, 12.5)
ax.set_ylim(-0.5, 12.5)
ax.set_xlabel("Promoter strength a1")
ax.set_ylabel("Steady-state level of u")
ax.set_title("Bistability (shaded) and hysteresis")
ax.legend(frameon=False, loc="upper left", fontsize=9)
sbp.save_figure(fig, __file__, "fig-hysteresis")

sbp.save_results(__file__, {
    "bistable_range": [bistable.min(), bistable.max()],
    "n_states": n_states,
    "switch_up": switch_up, "switch_down": switch_down,
    "up": up, "down": down,
})
sbp.show()

The steady states form an S-shaped curve, a bifurcation diagram. For \(a_1\) between about 3.7 and 8.7 (shaded), there are three steady states, two stable and one unstable; outside this range, only one. At each end of the range, a stable state and the unstable one meet and vanish, in what is called a saddle-node bifurcation.

As \(a_1\) rises, the circuit stays on the lower branch, with \(u\) low, until that branch disappears, and only then jumps up, at \(a_1 = 8.75\) in our steps. (The triangle at 8.75 lies a little below the upper branch: so close to the bifurcation the circuit moves slowly, and it has not quite settled in the time allowed for that step.) Lowered again, it stays on the upper branch down to \(a_1 = 3.75\). Between these values, the state of the circuit depends on its history as well as on the current value of \(a_1\): this is hysteresis, a form of memory. A brief pulse of inducer flips the switch, and it stays flipped after the inducer is gone.

Exercises

  1. Set \(n = 1\) in the toggle switch, and show that there is only one steady state for any \(a_1\) and \(a_2\). (Hint: write the steady-state condition as \(u = h(u)\), and show that \(h\) is increasing and concave.)
  2. Repeat the hysteresis example with \(n = 3\). How do the bistable range and the jumps change?
  3. In the toggle switch, add noise with the stochastic simulation methods of Chapter 5, treating \(u\) and \(v\) as numbers of molecules with \(a_1 = a_2 = 50\). How long does the switch stay in one state before noise flips it, and how does that depend on \(a_1\) and \(a_2\)?
  4. Compute the period and amplitude of the repressilator for \(\alpha\) from 10 to 1000 at \(\beta = 5\). What happens to the oscillations as \(\alpha\) approaches the edge of the shaded region?
  5. Make the ring four, and then five, repressors long (book Exercise 12.5). Which rings oscillate? Find the steady states and their eigenvalues, and explain the result.
  6. Book Exercise 12.4: vary \(\alpha\) and \(\alpha_0\) in the repressilator. How large can the leak \(\alpha_0\) be before the oscillations stop?
  7. In the integral feedback circuit, plot the adaptation precision \(y(u=2)/y(u=1)\) against \(K\) from 0.001 to 10, for the nominal parameters. How small must \(K\) be for adaptation to within 1%?
  8. Measure the adaptation time, the time after the step at which \(y\) first comes within 5% of its new steady state, for the 81 parameter sets with \(K = 0.01\). Is it robust?
  9. Replace the saturated degradation of \(x\) by first-order degradation, \(dx/dt = ay - bx\). Show that the steady-state output now rises by a factor \(\sqrt{2}\) whenever the signal doubles, whatever the parameters.
  10. Book Exercise 12.6: for an incoherent feed-forward loop of three enzymes, sample parameter sets at random and measure the fraction that give near-perfect adaptation, as Ma and colleagues did.

Going further

Bifurcation diagrams such as the one for hysteresis are usually computed by continuation, which follows a branch of steady states as a parameter changes, without scanning for roots. Tools such as AUTO, MatCont (MATLAB) and PyDSTool (Python) do this, and also follow limit cycles. Chapter 13 takes up the related question of how robust a circuit’s behaviour is to changes in its parameters and in its wiring.