6 Parameter estimation
Every dynamic model carries parameters, such as rate constants, Michaelis constants and inhibition constants, and only a few of them can be looked up. The rest must be estimated from experimental data: we look for the parameter values that make the model’s predictions agree best with the measurements. In this chapter, we set up that problem for enzyme kinetics and for a small model of gene expression, and solve it in several ways. We also ask the questions that ought to follow every fit. Which of several models do the data actually support? How sensitive are the predictions to each parameter? And which parameters, or combinations of parameters, do the data determine at all?
6.1 Data-driven mechanistic modelling: an overview
6.1.1 Pre-processing the data
There is no code for this section; see the book.
6.1.2 Model identification
Both least-squares examples in §6.2.2 show what structural identifiability means in practice: a model can fit the data perfectly while some of its parameters remain undetermined.
6.2 Setting up an optimisation problem
6.2.1 Linear regression
Each of the three classical linearisations of the Michaelis–Menten equation turns the estimation of \(v_{max}\) and \(K_M\) into fitting a straight line. As the book points out, the catch is that the transformation also transforms the errors. Let us see how much this matters, first for the data of Exercise 6.5 (note that the column headers in the book are swapped: the first row lists \([S]\), and the second, \(v\)), and then for 200 simulated datasets, where we know the true parameters. The simulated rates carry Gaussian noise of a fixed standard deviation, 0.1 mM/s, and are stored in data/mm_replicates.csv, so that both languages analyse exactly the same numbers.
Needs the Optimization Toolbox (for lsqnonlin).
%% Linearising the Michaelis-Menten equation, and why we should not
% Three transformations turn v = vmax S / (KM + S) into a straight line
% (book §6.2.1):
% Lineweaver-Burk 1/v vs 1/S: 1/v = (KM/vmax)(1/S) + 1/vmax
% Eadie-Hofstee v vs v/S: v = -KM (v/S) + vmax
% Hanes-Woolf S/v vs S: S/v = S/vmax + KM/vmax
% We estimate vmax and KM from each line, and by non-linear least squares,
% first for the data of Exercise 6.5, and then for 200 simulated datasets
% with known parameters (vmax = 2.5 mM/s, KM = 0.8 mM, noise of standard
% deviation 0.1 mM/s), to see how the transformations distort the errors.
% Requires: Optimization Toolbox (for lsqnonlin).
methods = {'Lineweaver-Burk', 'Eadie-Hofstee', 'Hanes-Woolf', 'non-linear'};
% Exercise 6.5 (the column headers in the book are swapped: S is the
% first row, v the second)
S = [0.15, 0.35, 0.65, 1.2, 2.0, 3.0, 4.0, 5.0, 6.0];
v = [0.35, 0.70, 1.26, 1.62, 1.5, 2.21, 2.167, 2.33, 2.12];
exercise = estimate(S, v);
fprintf('Exercise 6.5:\n');
for k = 1:4
vm = exercise(k, 1); km = exercise(k, 2);
sse = sum((vm * S ./ (km + S) - v) .^ 2);
fprintf(' %-16s vmax = %.3f, KM = %.3f, SSE = %.4f\n', methods{k}, ...
vm, km, sse);
end
% 200 simulated datasets with known parameters
replicates = readmatrix(fullfile(sbp.data_dir(), 'mm_replicates.csv'));
true_values = [2.5, 0.8];
estimates = zeros(size(replicates, 1), 4, 2);
for r = 1:size(replicates, 1)
estimates(r, :, :) = estimate(S, replicates(r, :));
end
med = squeeze(median(estimates, 1)); % 4 x 2
err = squeeze(median(abs(estimates - reshape(true_values, 1, 1, 2)) ...
./ reshape(true_values, 1, 1, 2), 1)); % relative
fprintf('200 simulated datasets (vmax = 2.5, KM = 0.8):\n');
for k = 1:4
fprintf([' %-16s median vmax = %.3f, KM = %.3f; median error ' ...
'%.1f%%, %.1f%%\n'], methods{k}, med(k, 1), med(k, 2), ...
100 * err(k, 1), 100 * err(k, 2));
end
%% Plot: the Lineweaver-Burk line for Exercise 6.5, and the spread of the
% KM estimates across the simulated datasets
fig = figure('Position', [100 100 1000 400]);
subplot(1, 2, 1); hold on
x = linspace(0, 1 / min(S), 50);
vm = exercise(1, 1); km = exercise(1, 2);
plot(1 ./ S, 1 ./ v, 'ko', 'MarkerFaceColor', 'k');
plot(x, km / vm * x + 1 / vm, 'Color', [0.835 0.369 0.000], ...
'LineWidth', 1.5);
xlabel('1/S (1/mM)'); ylabel('1/v (s/mM)');
title('Lineweaver-Burk plot, Exercise 6.5'); box off
subplot(1, 2, 2); hold on
groups = categorical(repmat({'LB', 'EH', 'HW', 'non-linear'}, ...
size(estimates, 1), 1), {'LB', 'EH', 'HW', 'non-linear'});
boxchart(groups(:), reshape(estimates(:, :, 2), [], 1), ...
'MarkerStyle', 'none', 'BoxFaceColor', 'k', 'BoxFaceAlpha', 0, ...
'WhiskerLineColor', 'k'); % black outlines and medians, no fill
yline(true_values(2), ':k', 'LineWidth', 1.5);
ylim([0.3 1.8]);
ylabel('Estimated KM (mM)'); title('KM from 200 simulated datasets'); box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-linear-regression');
results.methods = methods;
results.exercise = exercise;
results.median = med;
results.median_error = err;
results.estimates = estimates;
sbp.save_results(mfilename('fullpath'), results);
%% Local functions
function est = estimate(S, v)
% vmax and KM by each of the four methods (one row per method).
c = polyfit(1 ./ S, 1 ./ v, 1);
lineweaver_burk = [1 / c(2), c(1) / c(2)];
c = polyfit(v ./ S, v, 1);
eadie_hofstee = [c(2), -c(1)];
c = polyfit(S, S ./ v, 1);
hanes_woolf = [1 / c(1), c(2) / c(1)];
% Non-linear least squares, started from the Hanes-Woolf estimate
opts = optimoptions('lsqnonlin', 'Display', 'off', ...
'FunctionTolerance', 1e-14, 'StepTolerance', 1e-14, ...
'OptimalityTolerance', 1e-14);
p = lsqnonlin(@(p) p(1) * S ./ (p(2) + S) - v, hanes_woolf, [], [], opts);
est = [lineweaver_burk; eadie_hofstee; hanes_woolf; p];
end
Needs SciPy.
"""Linearising the Michaelis-Menten equation, and why we should not.
Three transformations turn v = vmax S / (KM + S) into a straight line
(book §6.2.1):
Lineweaver-Burk 1/v vs 1/S: 1/v = (KM/vmax)(1/S) + 1/vmax
Eadie-Hofstee v vs v/S: v = -KM (v/S) + vmax
Hanes-Woolf S/v vs S: S/v = S/vmax + KM/vmax
We estimate vmax and KM from each line, and by non-linear least squares,
first for the data of Exercise 6.5, and then for 200 simulated datasets
with known parameters (vmax = 2.5 mM/s, KM = 0.8 mM, noise of standard
deviation 0.1 mM/s), to see how the transformations distort the errors.
"""
import numpy as np
from scipy.optimize import least_squares
import matplotlib.pyplot as plt
import sbp
methods = ["Lineweaver-Burk", "Eadie-Hofstee", "Hanes-Woolf", "non-linear"]
def estimate(S, v):
"""vmax and KM by each of the four methods (one row per method)."""
slope, intercept = np.polyfit(1 / S, 1 / v, 1)
lineweaver_burk = [1 / intercept, slope / intercept]
slope, intercept = np.polyfit(v / S, v, 1)
eadie_hofstee = [intercept, -slope]
slope, intercept = np.polyfit(S, S / v, 1)
hanes_woolf = [1 / slope, intercept / slope]
# Non-linear least squares, started from the Hanes-Woolf estimate
sol = least_squares(lambda p: p[0] * S / (p[1] + S) - v, hanes_woolf,
xtol=1e-14, ftol=1e-14, gtol=1e-14)
return np.array([lineweaver_burk, eadie_hofstee, hanes_woolf, sol.x])
# Exercise 6.5 (the column headers in the book are swapped: S is the
# first row, v the second)
S = np.array([0.15, 0.35, 0.65, 1.2, 2.0, 3.0, 4.0, 5.0, 6.0])
v = np.array([0.35, 0.70, 1.26, 1.62, 1.5, 2.21, 2.167, 2.33, 2.12])
exercise = estimate(S, v)
print("Exercise 6.5:")
for name, (vm, km) in zip(methods, exercise):
sse = np.sum((vm * S / (km + S) - v) ** 2)
print(f" {name:16s} vmax = {vm:.3f}, KM = {km:.3f}, SSE = {sse:.4f}")
# 200 simulated datasets with known parameters
replicates = np.loadtxt(sbp.DATA / "mm_replicates.csv", delimiter=",",
skiprows=1)
true = np.array([2.5, 0.8])
estimates = np.array([estimate(S, r) for r in replicates]) # 200 x 4 x 2
median = np.median(estimates, axis=0)
error = np.median(np.abs(estimates - true) / true, axis=0) # relative
print("200 simulated datasets (vmax = 2.5, KM = 0.8):")
for k, name in enumerate(methods):
print(f" {name:16s} median vmax = {median[k, 0]:.3f}, KM = "
f"{median[k, 1]:.3f}; median error {100 * error[k, 0]:.1f}%, "
f"{100 * error[k, 1]:.1f}%")
# --- Plot: the Lineweaver-Burk line for Exercise 6.5, and the spread of
# the KM estimates across the simulated datasets
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
x = np.linspace(0, 1 / S.min(), 50)
vm, km = exercise[0]
ax1.plot(1 / S, 1 / v, "o", color="black")
ax1.plot(x, km / vm * x + 1 / vm, color="#D55E00")
ax1.set_xlabel("1/S (1/mM)")
ax1.set_ylabel("1/v (s/mM)")
ax1.set_title("Lineweaver-Burk plot, Exercise 6.5")
ax2.boxplot([estimates[:, k, 1] for k in range(4)], showfliers=False,
medianprops={"color": "k"})
ax2.set_xticks(range(1, 5), ["LB", "EH", "HW", "non-linear"])
ax2.axhline(true[1], ls=":", color="black")
ax2.set_ylim(0.3, 1.8)
ax2.set_ylabel("Estimated KM (mM)")
ax2.set_title("KM from 200 simulated datasets")
sbp.save_figure(fig, __file__, "fig-linear-regression")
sbp.save_results(__file__, {
"methods": methods, "exercise": exercise,
"median": median, "median_error": error, "estimates": estimates,
})
sbp.show()
For the exercise data, the Lineweaver–Burk plot gives \(K_M = 1.04\) mM, whereas non-linear regression gives 0.82 mM; the other two plots fall in between. The simulations show that this is no accident. A reciprocal blows up the noise in the slowest rates, at the lowest substrate concentrations, and these points then dominate the fit (see the rightmost point in the double reciprocal plot, at the lowest substrate concentration). Across the 200 datasets, the median error in \(K_M\) is 28% for Lineweaver–Burk, against 9% for non-linear regression, and the spread of its estimates is far wider; for a few datasets, it even returns a negative \(K_M\). Hanes–Woolf comes surprisingly close to non-linear regression here; even so, with non-linear regression a few lines of code away, there is little reason to use any of the transformations.
6.2.2 Least squares
An enzyme follows Michaelis–Menten kinetics with a competitive inhibitor \(I\):
\[ v = \frac{v_\text{max}\,S}{K_M\left(1 + \dfrac{I}{K_I}\right) + S}. \]
We want \(v_\text{max}\), \(K_M\) and \(K_I\). The initial rate \(v\) was measured at 20 substrate concentrations, from 1 to 20 mM, once with the inhibitor at \(I = 10\) mM (dataset D1) and once at \(I = 20\) mM (dataset D2). The data are in data/competitive_inhibition.csv.
Each measurement is assumed to carry an error of about 10% of its value, \(\delta = 0.1\). A good fit should therefore be judged by relative errors, and the cost we minimise is the weighted sum of squared errors (book, Eq. 6.5):
\[ \text{SSE}(\Theta) = \sum_{i=1}^{n} \left( \frac{v_{\text{pred},i}(\Theta) - v_i}{\delta\, v_i} \right)^2, \qquad \Theta = (v_\text{max}, K_M, K_I). \]
If the measurement errors are independent and normally distributed with standard deviation \(\delta v_i\), minimising this SSE is the same as finding the maximum-likelihood estimate (book, §6.2.3).
Both MATLAB and SciPy have solvers made for least-squares problems. They take a function that returns the vector of weighted residuals, one per data point, and minimise the sum of their squares. They use the structure of the problem to converge quickly, but, like all local methods, they need a starting guess.
| MATLAB | Python (scipy.optimize) |
|
|---|---|---|
| Least squares (residual vector) | lsqnonlin (Optimization Toolbox) |
least_squares |
| General minimisation, no derivatives | fminsearch (core MATLAB) |
minimize(method="Nelder-Mead") |
| Global search | ga, particleswarm (Global Optimization Toolbox) |
differential_evolution |
We fit each dataset, D1, D2 and both together, from the same eight starting guesses.
Needs the Optimization Toolbox (for lsqnonlin).
%% Fitting a rate law to data by weighted least squares
% Competitive inhibition: v = vmax*S / (KM*(1 + I/KI) + S).
% Rates were measured at 20 substrate concentrations, with the inhibitor
% at I = 10 mM (dataset D1) and at I = 20 mM (dataset D2). We estimate
% vmax, KM and KI from D1 alone, and from both datasets together.
% Requires: Optimization Toolbox (for lsqnonlin).
data = readmatrix(fullfile(sbp.data_dir(), 'competitive_inhibition.csv'));
S = data(:, 1); v10 = data(:, 2); v20 = data(:, 3);
delta = 0.1; % relative measurement error (10%)
rate = @(p, S, I) p(1) * S ./ (p(2) * (1 + I / p(3)) + S);
% Weighted residuals; their sum of squares is the SSE (book Eq. 6.5)
residuals = @(p, S, I, v) (rate(p, S, I) - v) ./ (delta * v);
opts = optimoptions('lsqnonlin', 'Display', 'off', ...
'StepTolerance', 1e-12, 'FunctionTolerance', 1e-12, ...
'OptimalityTolerance', 1e-12);
% The same eight starting guesses for every fit: vmax = 20 and a spread
% of values for KM and KI
KM_KI = [1 1; 2 8; 5 2; 5 20; 10 5; 20 40; 40 10; 40 80];
starts = [20 * ones(8, 1), KM_KI];
names = {'D1', 'D2', 'D1_D2'};
datasets = {{S, 10 * ones(20, 1), v10}, ...
{S, 20 * ones(20, 1), v20}, ...
{[S; S], [10 * ones(20, 1); 20 * ones(20, 1)], [v10; v20]}};
for d = 1:3
[s, i, v] = datasets{d}{:};
P = zeros(8, 3);
SSE = zeros(8, 1);
for k = 1:8
[P(k, :), SSE(k)] = lsqnonlin(@(p) residuals(p, s, i, v), ...
starts(k, :), [0 0 0], [Inf Inf Inf], opts);
end
[~, best] = min(SSE);
% KM*(1 + I/KI) at the first inhibitor level of the dataset
KM_app = P(:, 2) .* (1 + i(1) ./ P(:, 3));
fprintf('%s: SSE = %.4f (spread over starts %.1e)\n', names{d}, ...
SSE(best), max(SSE) - min(SSE));
fprintf([' vmax = %.4f; KM ranges %.3g to %.3g; ' ...
'KI ranges %.3g to %.3g\n'], P(best, 1), min(P(:, 2)), ...
max(P(:, 2)), min(P(:, 3)), max(P(:, 3)));
% What every start agrees on; KM and KI only if they are pinned down
results.(names{d}) = struct('SSE', SSE(best), 'vmax', P(best, 1), ...
'KM_app', KM_app(best));
if strcmp(names{d}, 'D1_D2')
results.D1_D2.KM = P(best, 2);
results.D1_D2.KI = P(best, 3);
else
results.([names{d} '_estimates']) = struct('KM', P(:, 2)', ...
'KI', P(:, 3)');
end
end
%% Plot
fig = figure('Position', [100 100 1000 400]);
blue = [0.000 0.447 0.698]; orange = [0.902 0.624 0.000];
r = results.D1_D2;
p = [r.vmax r.KM r.KI];
S_fine = linspace(0, 21, 200);
subplot(1, 2, 1)
hold on
errorbar(S, v10, delta * v10, 'o', 'Color', blue, 'MarkerSize', 4, ...
'CapSize', 2, 'MarkerFaceColor', blue);
errorbar(S, v20, delta * v20, 'o', 'Color', orange, 'MarkerSize', 4, ...
'CapSize', 2, 'MarkerFaceColor', orange);
plot(S_fine, rate(p, S_fine, 10), '-', 'Color', blue);
plot(S_fine, rate(p, S_fine, 20), '-', 'Color', orange);
xlabel('S (mM)'); ylabel('v (mmol L^{-1} s^{-1})');
title('Fit to D1 and D2 together');
legend({'data, I = 10 mM', 'data, I = 20 mM'}, 'Location', 'southeast', ...
'Box', 'off');
box off
subplot(1, 2, 2)
KI_line = logspace(-1, 2.3, 200);
loglog(results.D1.KM_app ./ (1 + 10 ./ KI_line), KI_line, '-', ...
'Color', [0.6 0.6 0.6]);
hold on
est = results.D1_estimates;
loglog(est.KM, est.KI, 'o', 'Color', blue, 'MarkerFaceColor', blue);
loglog(p(2), p(3), 'p', 'Color', [0.835 0.369 0.000], ...
'MarkerFaceColor', [0.835 0.369 0.000], 'MarkerSize', 14);
xlabel('K_M (mM)'); ylabel('K_I (mM)');
title('Where the estimates land');
legend({'K_M(1 + 10/K_I) = best K_M^{app} for D1', ...
'estimates from D1, 8 starts', 'estimate from D1 and D2'}, ...
'Location', 'northwest', 'Box', 'off', 'FontSize', 9);
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-fit-inhibition');
sbp.save_results(mfilename('fullpath'), results);
Needs SciPy.
"""Fitting a rate law to data by weighted least squares.
Competitive inhibition: v = vmax*S / (KM*(1 + I/KI) + S).
Rates were measured at 20 substrate concentrations, with the inhibitor
at I = 10 mM (dataset D1) and at I = 20 mM (dataset D2). We estimate
vmax, KM and KI from D1 alone, and from both datasets together.
"""
import numpy as np
from scipy.optimize import least_squares
import matplotlib.pyplot as plt
import sbp
data = np.loadtxt(sbp.DATA / "competitive_inhibition.csv", delimiter=",",
skiprows=1)
S, v10, v20 = data[:, 0], data[:, 1], data[:, 2]
delta = 0.1 # relative measurement error (10%)
def rate(p, S, I):
vmax, KM, KI = p
return vmax * S / (KM * (1 + I / KI) + S)
def residuals(p, S, I, v):
"""Weighted residuals; their sum of squares is the SSE (book Eq. 6.5)."""
return (rate(p, S, I) - v) / (delta * v)
def fit(S, I, v, p0):
sol = least_squares(residuals, p0, args=(S, I, v), bounds=(0, np.inf),
xtol=1e-12, ftol=1e-12, gtol=1e-12)
return sol.x, np.sum(sol.fun ** 2)
# The same eight starting guesses for every fit: vmax = 20 and a spread
# of values for KM and KI
starts = [(20, km, ki) for km, ki in
[(1, 1), (2, 8), (5, 2), (5, 20), (10, 5), (20, 40), (40, 10),
(40, 80)]]
datasets = {
"D1": (S, np.full_like(S, 10.0), v10),
"D2": (S, np.full_like(S, 20.0), v20),
"D1_D2": (np.r_[S, S], np.r_[np.full_like(S, 10.0),
np.full_like(S, 20.0)], np.r_[v10, v20]),
}
results = {}
for name, (s, i, v) in datasets.items():
fits = [fit(s, i, v, p0) for p0 in starts]
P = np.array([p for p, _ in fits])
SSE = np.array([sse for _, sse in fits])
best = np.argmin(SSE)
# KM*(1 + I/KI) at the first inhibitor level of the dataset
KM_app = P[:, 1] * (1 + i[0] / P[:, 2])
print(f"{name}: SSE = {SSE[best]:.4f} (spread over starts "
f"{np.ptp(SSE):.1e})")
print(f" vmax = {P[best, 0]:.4f}; KM ranges {P[:, 1].min():.3g} to "
f"{P[:, 1].max():.3g}; KI ranges {P[:, 2].min():.3g} to "
f"{P[:, 2].max():.3g}")
# What every start agrees on; KM and KI only if they are pinned down
results[name] = {"SSE": SSE[best], "vmax": P[best, 0],
"KM_app": KM_app[best]}
if name == "D1_D2":
results[name].update(KM=P[best, 1], KI=P[best, 2])
else:
results[name + "_estimates"] = {"KM": P[:, 1], "KI": P[:, 2]}
# --- Plot
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
p = [results["D1_D2"][k] for k in ("vmax", "KM", "KI")]
S_fine = np.linspace(0, 21, 200)
for I, v, col in [(10, v10, "#0072B2"), (20, v20, "#E69F00")]:
ax1.errorbar(S, v, yerr=delta * v, fmt="o", color=col, ms=4,
capsize=2, label=f"data, I = {I} mM")
ax1.plot(S_fine, rate(p, S_fine, I), "-", color=col)
ax1.set_xlabel("S (mM)")
ax1.set_ylabel("v (mmol L$^{-1}$ s$^{-1}$)")
ax1.set_title("Fit to D1 and D2 together")
ax1.legend(frameon=False, loc="lower right")
KI_line = np.logspace(-1, 2.3, 200)
ax2.plot(results["D1"]["KM_app"] / (1 + 10 / KI_line), KI_line, "-",
color="#999999", label="$K_M(1 + 10/K_I)$ = best $K_M^{app}$ for D1")
est = results["D1_estimates"]
ax2.plot(est["KM"], est["KI"], "o", color="#0072B2", ms=6,
label="estimates from D1, 8 starts")
ax2.plot(p[1], p[2], "*", color="#D55E00", ms=14,
label="estimate from D1 and D2")
ax2.set_xscale("log")
ax2.set_yscale("log")
ax2.set_xlabel("$K_M$ (mM)")
ax2.set_ylabel("$K_I$ (mM)")
ax2.set_title("Where the estimates land")
ax2.legend(frameon=False, loc="upper left", fontsize=9)
sbp.save_figure(fig, __file__, "fig-fit-inhibition")
sbp.save_results(__file__, results)
sbp.show()
With both datasets, all eight starts arrive at the same answer, \(v_\text{max} = 25.8\) mmol L−1 s−1, \(K_M = 11.6\) mM and \(K_I = 36.8\) mM, and the curves follow the data well (left panel).
With D1 alone, something quite different happens. All eight starts again reach exactly the same SSE and the same \(v_\text{max}\), and every one of them reports a successful fit. Yet \(K_M\) ranges from about 1 to 15 mM, and \(K_I\) from below 1 mM to tens or even hundreds of mM; the two languages stop at different points, because their solvers take different paths. The right panel shows why. At a single inhibitor concentration, \(K_M\) and \(K_I\) enter the rate law only through the combination
\[ K_M^\text{app} = K_M\left(1 + \frac{I}{K_I}\right), \]
the apparent Michaelis constant. Every pair \((K_M, K_I)\) on the grey curve gives the same \(K_M^\text{app}\), and hence identical predictions for every data point. The data determine \(v_\text{max}\) and \(K_M^\text{app}\), and nothing more: \(K_M\) and \(K_I\) are structurally non-identifiable from D1. More data of the same kind would not help. A second inhibitor concentration does, because \(K_M^\text{app}\) changes with \(I\) in a way that depends on \(K_I\) (vermillion star).
Two lessons follow. First, a solver that reports success has found a minimum; it says nothing about whether the minimum is unique. Fitting from several starting points is a simple and effective check. Second, identifiability is a property of the model and the experiment together, and it is best examined before the experiments are done (book, §6.1.2).
Fitting an ODE model to a time course
So far the model was a single algebraic rate law. Fitting a system of ODEs to time-course data works in exactly the same way: the residual function calls the ODE solver of Chapter 5 for the trial parameters, and compares the solution with the data at the measured time points.
Our example follows a gene after it is switched on at \(t = 0\). Its mRNA \(m\) is made at rate \(k_m\) and degraded at rate \(g_m\) per molecule; each mRNA is translated at rate \(k_p\), and the protein \(p\) is degraded at rate \(g_p\):
\[ \frac{dm}{dt} = k_m - g_m m, \qquad \frac{dp}{dt} = k_p m - g_p p, \qquad m(0) = p(0) = 0 . \]
The data, measured every half hour for 12 hours with 10% error, are synthetic, made with known parameters (\(k_m = 10\) molecules/h, \(g_m = 1\)/h, \(k_p = 5\)/h, \(g_p = 0.2\)/h) by tools/make_expression_data.py. We fit the four parameters, first to both mRNA and protein, then to the protein alone, which is often all that can be measured, for instance with a fluorescent reporter. Each fit starts from the same eight guesses.
Needs the Optimization Toolbox.
%% Fitting an ODE model to a time course
% A gene is switched on at t = 0; its mRNA m and protein p follow
% dm/dt = k_m - g_m m, dp/dt = k_p m - g_p p, m(0) = p(0) = 0.
% We estimate the four parameters from measurements of both mRNA and
% protein, and then from the protein alone. Each evaluation of the
% residuals solves the ODEs; the fits start from the same eight guesses.
% Requires: Optimization Toolbox (for lsqnonlin).
data = readmatrix(fullfile(sbp.data_dir(), 'gene_expression_timecourse.csv'));
t = data(:, 1); m_obs = data(:, 2); p_obs = data(:, 3);
delta = 0.1; % relative measurement error (10%)
starts = [1 1 1 1; 5 0.5 5 0.5; 20 2 1 0.1; 1 0.1 20 2; 10 0.3 3 1;
3 3 3 0.3; 50 5 0.5 0.05; 0.5 0.05 50 5];
opts = optimoptions('lsqnonlin', 'Display', 'off', ...
'FunctionTolerance', 1e-12, 'StepTolerance', 1e-12, ...
'OptimalityTolerance', 1e-12);
names = {'mRNA and protein', 'protein only'};
fits = cell(1, 2);
for f = 1:2
use_mrna = (f == 1);
rows = zeros(size(starts, 1), 5);
for k = 1:size(starts, 1)
res = @(p) residuals(p, t, m_obs, p_obs, delta, use_mrna);
[p, sse] = lsqnonlin(res, starts(k, :), 1e-6 * ones(1, 4), ...
100 * ones(1, 4), opts);
rows(k, :) = [p sse];
end
fits{f} = rows;
fprintf('Fits to %s (k_m, g_m, k_p, g_p, SSE):\n', names{f});
fprintf(' %8.4f %8.4f %8.4f %8.4f %8.4f\n', rows');
end
% Best fits, and what the protein data alone can determine
both = fits{1};
[~, i] = min(both(:, 5));
best_both = both(i, :);
prot = fits{2};
good = prot(prot(:, 5) < min(prot(:, 5)) + 1e-6, :); % equally good fits
product = good(:, 1) .* good(:, 3); % k_m * k_p
rates = sort(good(:, [2 4]), 2); % {g_m, g_p}
fprintf(['Protein only: %d of %d fits reach the best SSE, %.4f; across ' ...
'them k_m*k_p = %.3f to %.3f, and the two degradation rates are ' ...
'%.4f and %.4f\n'], size(good, 1), size(prot, 1), min(prot(:, 5)), ...
min(product), max(product), mean(rates(:, 1)), mean(rates(:, 2)));
%% Plot
blue = [0.000 0.447 0.698]; orange = [0.902 0.624 0.000];
fig = figure('Position', [100 100 1000 400]);
subplot(1, 2, 1)
tt = linspace(0, 12, 241)';
Y = simulate(best_both(1:4), tt);
plot(t, p_obs, 'o', 'Color', blue, 'MarkerFaceColor', blue);
hold on
plot(tt, Y(:, 2), 'Color', blue);
plot(t, m_obs * 10, 's', 'Color', orange, 'MarkerFaceColor', orange, ...
'MarkerSize', 4);
plot(tt, Y(:, 1) * 10, 'Color', orange);
xlabel('Time (h)'); ylabel('Molecules per cell');
title('Fit to mRNA and protein');
legend({'protein (data)', 'protein (fit)', 'mRNA × 10 (data)', ...
'mRNA × 10 (fit)'}, 'Location', 'northwest', 'Box', 'off');
box off
subplot(1, 2, 2)
k = linspace(0.5, 100, 400);
loglog(k, mean(product) ./ k, ':', 'Color', [0.6 0.6 0.6]);
hold on
best = both(:, 5) < min(both(:, 5)) + 1e-6;
loglog(both(best, 1), both(best, 3), 's', 'Color', orange, ...
'MarkerFaceColor', orange, 'MarkerSize', 8);
loglog(good(:, 1), good(:, 3), 'o', 'Color', blue, ...
'MarkerFaceColor', blue, 'MarkerSize', 8);
xlim([0.5 100]); ylim([0.5 100]);
xlabel('k_m (molecules/h)'); ylabel('k_p (1/h)');
title('Estimates from eight starting points');
legend({'k_m k_p = constant', 'best fits, mRNA and protein', ...
'best fits, protein only'}, 'Box', 'off');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-fit-timecourse');
results.best_both = best_both(1:4);
results.sse_both = best_both(5);
results.sse_protein = min(prot(:, 5));
results.product_protein = mean(product);
results.rates_protein = mean(rates, 1);
sbp.save_results(mfilename('fullpath'), results);
%% Local functions
function Y = simulate(p, t)
% Columns: mRNA, protein, at the times t.
rhs = @(~, y) [p(1) - p(2) * y(1); p(3) * y(1) - p(4) * y(2)];
opts = odeset('RelTol', 1e-10, 'AbsTol', 1e-10);
[~, Y] = ode45(rhs, [0; t(:)], [0 0], opts);
Y = Y(2:end, :); % drop t = 0
end
function r = residuals(p, t, m_obs, p_obs, delta, use_mrna)
Y = simulate(p, t);
r = (Y(:, 2) - p_obs) ./ (delta * p_obs);
if use_mrna
r = [(Y(:, 1) - m_obs) ./ (delta * m_obs); r];
end
end
Needs SciPy.
"""Fitting an ODE model to a time course.
A gene is switched on at t = 0; its mRNA m and protein p follow
dm/dt = k_m - g_m m, dp/dt = k_p m - g_p p, m(0) = p(0) = 0.
We estimate the four parameters from measurements of both mRNA and
protein, and then from the protein alone. Each evaluation of the
residuals solves the ODEs; the fits start from the same eight guesses.
"""
import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import least_squares
import matplotlib.pyplot as plt
import sbp
data = np.loadtxt(sbp.DATA / "gene_expression_timecourse.csv",
delimiter=",", skiprows=1)
t, m_obs, p_obs = data.T
delta = 0.1 # relative measurement error (10%)
def simulate(p, t):
k_m, g_m, k_p, g_p = p
rhs = lambda _, y: [k_m - g_m * y[0], k_p * y[0] - g_p * y[1]]
sol = solve_ivp(rhs, [0, t[-1]], [0, 0], t_eval=t, rtol=1e-10,
atol=1e-10)
return sol.y # rows: mRNA, protein
def residuals(p, use_mrna):
m, prot = simulate(p, t)
r = (prot - p_obs) / (delta * p_obs)
if use_mrna:
r = np.r_[(m - m_obs) / (delta * m_obs), r]
return r
starts = [(1, 1, 1, 1), (5, 0.5, 5, 0.5), (20, 2, 1, 0.1),
(1, 0.1, 20, 2), (10, 0.3, 3, 1), (3, 3, 3, 0.3),
(50, 5, 0.5, 0.05), (0.5, 0.05, 50, 5)]
fits = {}
for use_mrna, name in [(True, "mRNA and protein"), (False, "protein only")]:
rows = []
for p0 in starts:
sol = least_squares(residuals, p0, args=(use_mrna,),
bounds=(1e-6, 100), xtol=1e-12, ftol=1e-12,
gtol=1e-12)
rows.append([*sol.x, np.sum(sol.fun ** 2)])
fits[name] = np.array(rows)
print(f"Fits to {name} (k_m, g_m, k_p, g_p, SSE):")
for r in fits[name]:
print(" " + " ".join(f"{x:8.4f}" for x in r))
# Best fits, and what the protein data alone can determine
both = fits["mRNA and protein"]
best_both = both[np.argmin(both[:, 4])]
prot = fits["protein only"]
good = prot[prot[:, 4] < prot[:, 4].min() + 1e-6] # equally good fits
product = good[:, 0] * good[:, 2] # k_m * k_p
rates = np.sort(good[:, [1, 3]], axis=1) # {g_m, g_p}
print(f"Protein only: {len(good)} of {len(prot)} fits reach the best SSE, "
f"{prot[:, 4].min():.4f}; across them k_m*k_p = "
f"{product.min():.3f} to {product.max():.3f}, and the two "
f"degradation rates are {rates[:, 0].mean():.4f} and "
f"{rates[:, 1].mean():.4f}")
# --- Plot
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
tt = np.linspace(0, 12, 241)
mm, pp = simulate(best_both[:4], tt)
ax1.plot(t, p_obs, "o", color="#0072B2", label="protein (data)")
ax1.plot(tt, pp, color="#0072B2", label="protein (fit)")
ax1.plot(t, m_obs * 10, "s", color="#E69F00", ms=4,
label="mRNA × 10 (data)")
ax1.plot(tt, mm * 10, color="#E69F00", label="mRNA × 10 (fit)")
ax1.set_xlabel("Time (h)")
ax1.set_ylabel("Molecules per cell")
ax1.set_title("Fit to mRNA and protein")
ax1.legend(frameon=False, fontsize=9)
k = np.linspace(0.5, 100, 400)
ax2.loglog(k, product.mean() / k, ":", color="#999999",
label=r"$k_m k_p$ = constant")
for name, marker, colour in [("mRNA and protein", "s", "#E69F00"),
("protein only", "o", "#0072B2")]:
f = fits[name]
best = f[:, 4] < f[:, 4].min() + 1e-6
ax2.loglog(f[best, 0], f[best, 2], marker, color=colour, ms=8,
alpha=0.7, label=f"best fits, {name}")
ax2.set_xlim(0.5, 100)
ax2.set_ylim(0.5, 100)
ax2.set_xlabel("$k_m$ (molecules/h)")
ax2.set_ylabel("$k_p$ (1/h)")
ax2.set_title("Estimates from eight starting points")
ax2.legend(frameon=False, fontsize=9)
sbp.save_figure(fig, __file__, "fig-fit-timecourse")
sbp.save_results(__file__, {
"best_both": best_both[:4], "sse_both": best_both[4],
"sse_protein": prot[:, 4].min(),
"product_protein": product.mean(),
"rates_protein": rates.mean(axis=0),
})
sbp.show()
With both species measured, all eight fits find the same estimates, close to the true values: \(k_m = 9.50\), \(g_m = 0.963\), \(k_p = 5.23\) and \(g_p = 0.205\). With the protein alone, all eight fits are equally good, but they disagree completely about \(k_m\) and \(k_p\), which range over a factor of 20 or more (right). Only their product is determined, \(k_m k_p \approx 55.6\). The reason is clear from the equations: doubling \(k_m\) doubles the mRNA, and halving \(k_p\) then restores the protein exactly. The two degradation rates are identifiable as a pair, 0.156 and 1.27 per hour, but the protein data cannot say which belongs to the mRNA and which to the protein: the solution for \(p(t)\) is unchanged when \(g_m\) and \(g_p\) are swapped, and the fits come out either way round. Note, too, that these estimates lie further from the true values than those from both species: with less information, the same noise moves the estimates more.
This is the time-course version of the lesson of the inhibition example: a model can fit the data perfectly while some of its parameters remain undetermined. Measuring a second species, or knowing one parameter from a separate experiment (an mRNA half-life, say), restores identifiability.
6.2.3 Maximum likelihood estimation
There is no code for this section; see the book.
6.3 Algorithms for optimisation
6.3.1 Desiderata
There is no code for this section; see the book.
6.3.2 Gradient-based methods
There is no code for this section; see the book.
6.3.3 Direct search methods
The simplest way to minimise a function is to evaluate it everywhere, on a grid, and keep the best point (book, §6.3.3). Grid search needs no starting guess and cannot be trapped by a local minimum, and it shows the whole error landscape, which makes it a good tool for seeing what is going on.
Here, one more trick keeps the grid small. The rate law is proportional to \(v_\text{max}\), so for given \(K_M\) and \(K_I\) the weighted residuals are linear in \(v_\text{max}\), and the best \(v_\text{max}\) follows from a one-line formula, just as in linear regression. The search is then over \(K_M\) and \(K_I\) only: whole numbers from 1 to 60 mM, 3600 points.
Core MATLAB only.
%% Grid search, and the shape of the error landscape
% The same competitive-inhibition model and data as in fit_inhibition.
% We evaluate the weighted SSE on a grid of whole-number values of KM and
% KI (1 to 60 mM). The rate is proportional to vmax, so for each (KM, KI)
% the best vmax can be computed exactly, as in linear regression, and the
% grid only needs two dimensions.
% Requires: core MATLAB only.
data = readmatrix(fullfile(sbp.data_dir(), 'competitive_inhibition.csv'));
S = data(:, 1); v10 = data(:, 2); v20 = data(:, 3);
delta = 0.1;
names = {'D1', 'D1_D2'};
datasets = {{S, 10 * ones(20, 1), v10}, ...
{[S; S], [10 * ones(20, 1); 20 * ones(20, 1)], [v10; v20]}};
KM_grid = 1:60;
KI_grid = 1:60;
for d = 1:2
[s, i, v] = datasets{d}{:};
grid = zeros(numel(KI_grid), numel(KM_grid)); % rows: KI, columns: KM
vmax = zeros(size(grid));
for r = 1:numel(KI_grid)
for c = 1:numel(KM_grid)
[vmax(r, c), grid(r, c)] = best_vmax_and_sse( ...
KM_grid(c), KI_grid(r), s, i, v, delta);
end
end
[best, idx] = min(grid(:));
[r, c] = ind2sub(size(grid), idx);
% How many grid points fit almost as well as the best (within 1 unit)?
n_close = sum(grid(:) < best + 1);
fprintf(['%s: best on grid KM = %d, KI = %d, vmax = %.4f, ' ...
'SSE = %.4f; %d grid points within 1 of the best SSE\n'], ...
names{d}, KM_grid(c), KI_grid(r), vmax(r, c), best, n_close);
SSE.(names{d}) = grid;
results.(names{d}) = struct('KM', KM_grid(c), 'KI', KI_grid(r), ...
'vmax', vmax(r, c), 'SSE', best, 'n_within_1', n_close, ...
'SSE_at_KI_20', grid(KI_grid == 20, :));
end
%% Plot: log10(SSE - best SSE + 1), so that the best point is at 0
fig = figure('Position', [100 100 1000 420]);
tiledlayout(1, 2, 'TileSpacing', 'compact');
titles = {'D1 only (I = 10 mM)', 'D1 and D2 together'};
for d = 1:2
nexttile
Z = log10(SSE.(names{d}) - min(SSE.(names{d})(:)) + 1);
contourf(KM_grid, KI_grid, min(Z, 3), linspace(0, 3, 13), ...
'LineStyle', 'none');
hold on
plot(results.(names{d}).KM, results.(names{d}).KI, 'p', ...
'Color', [0.835 0.369 0.000], ...
'MarkerFaceColor', [0.835 0.369 0.000], 'MarkerSize', 14);
colormap(sbp.colormap('viridis_r'));
clim([0 3]);
xlabel('K_M (mM)');
if d == 1, ylabel('K_I (mM)'); else, yticklabels({}); end
title(titles{d});
end
cb = colorbar;
cb.Layout.Tile = 'east';
cb.Label.String = 'log_{10}(SSE - best SSE + 1)';
sbp.save_figure(fig, mfilename('fullpath'), 'fig-sse-landscape');
sbp.save_results(mfilename('fullpath'), results);
%% Local function
function [vmax, sse] = best_vmax_and_sse(KM, KI, S, I, v, delta)
% Weighted residuals are vmax*a - b, so the best vmax is sum(a.*b)/sum(a.^2).
a = S ./ (KM * (1 + I / KI) + S) ./ (delta * v);
b = 1 / delta;
vmax = sum(a .* b) / sum(a .* a);
sse = sum((vmax * a - b) .^ 2);
end
Needs NumPy and Matplotlib.
"""Grid search, and the shape of the error landscape.
The same competitive-inhibition model and data as in fit_inhibition.
We evaluate the weighted SSE on a grid of whole-number values of KM and
KI (1 to 60 mM). The rate is proportional to vmax, so for each (KM, KI)
the best vmax can be computed exactly, as in linear regression, and the
grid only needs two dimensions.
"""
import numpy as np
import matplotlib.pyplot as plt
import sbp
data = np.loadtxt(sbp.DATA / "competitive_inhibition.csv", delimiter=",",
skiprows=1)
S, v10, v20 = data[:, 0], data[:, 1], data[:, 2]
delta = 0.1
datasets = {
"D1": (S, np.full_like(S, 10.0), v10),
"D1_D2": (np.r_[S, S], np.r_[np.full_like(S, 10.0),
np.full_like(S, 20.0)], np.r_[v10, v20]),
}
KM_grid = np.arange(1, 61)
KI_grid = np.arange(1, 61)
def best_vmax_and_sse(KM, KI, S, I, v):
"""Weighted residuals are vmax*a - b, so the best vmax is
sum(a*b) / sum(a^2)."""
a = S / (KM * (1 + I / KI) + S) / (delta * v)
b = 1 / delta
vmax = np.sum(a * b) / np.sum(a * a)
return vmax, np.sum((vmax * a - b) ** 2)
results = {}
SSE = {}
for name, (s, i, v) in datasets.items():
grid = np.zeros((len(KI_grid), len(KM_grid))) # rows: KI, columns: KM
vmax = np.zeros_like(grid)
for r, KI in enumerate(KI_grid):
for c, KM in enumerate(KM_grid):
vmax[r, c], grid[r, c] = best_vmax_and_sse(KM, KI, s, i, v)
r, c = np.unravel_index(np.argmin(grid), grid.shape)
# How many grid points fit almost as well as the best (within 1 unit)?
n_close = int(np.sum(grid < grid[r, c] + 1))
print(f"{name}: best on grid KM = {KM_grid[c]}, KI = {KI_grid[r]}, "
f"vmax = {vmax[r, c]:.4f}, SSE = {grid[r, c]:.4f}; "
f"{n_close} grid points within 1 of the best SSE")
SSE[name] = grid
results[name] = {"KM": KM_grid[c], "KI": KI_grid[r],
"vmax": vmax[r, c], "SSE": grid[r, c],
"n_within_1": n_close,
"SSE_at_KI_20": grid[KI_grid == 20, :].ravel()}
# --- Plot: log10(SSE - best SSE + 1), so that the best point is at 0
sbp.style()
fig, axes = plt.subplots(1, 2, figsize=(10, 4.2), sharey=True)
levels = np.linspace(0, 3, 13)
titles = {"D1": "D1 only (I = 10 mM)", "D1_D2": "D1 and D2 together"}
for ax, name in zip(axes, SSE):
Z = np.log10(SSE[name] - SSE[name].min() + 1)
cs = ax.contourf(KM_grid, KI_grid, Z, levels=levels, cmap="viridis_r",
extend="max")
ax.plot(results[name]["KM"], results[name]["KI"], "*", color="#D55E00",
ms=14)
ax.set_xlabel("$K_M$ (mM)")
ax.set_title(titles[name])
axes[0].set_ylabel("$K_I$ (mM)")
fig.colorbar(cs, ax=axes, label="log$_{10}$(SSE − best SSE + 1)")
sbp.save_figure(fig, __file__, "fig-sse-landscape")
sbp.save_results(__file__, results)
sbp.show()
For D1, the landscape has a long, curved valley with an almost flat floor: the curve of constant \(K_M^\text{app}\) from the previous section. The grid point that happens to be lowest (\(K_M = 12\), \(K_I = 33\)) is no better than many others along the valley; 185 grid points come within one unit of the best SSE, with \(K_I\) anywhere from 2 to 60 mM. For D1 and D2 together, the valley closes into a basin with a single minimum, at \(K_M = 12\), \(K_I = 39\) on the grid, close to the least-squares estimate. The basin is still long in the \(K_I\) direction: grid points from 28 to 54 mM fit almost as well. \(K_I\) is identifiable from these data, although only loosely determined.
Grid search becomes hopeless quickly as parameters are added. Sixty values for each of two parameters makes 3600 evaluations; sixty values for each of ten parameters would make about \(6 \times 10^{17}\). This is the curse of dimensionality (book, §6.5.5), and it is why grid search is used for small problems, for a first look at a landscape, or to choose starting points for a local method.
6.3.4 Evolutionary algorithms
Between local methods, which are fast but need a good starting guess, and grid search, which is thorough but expensive, lie stochastic global methods such as simulated annealing (book, §6.3.3.3) and evolutionary algorithms (§6.3.4). Evolutionary algorithms borrow the logic of natural selection: a population of parameter sets is varied at random, and the better ones are more likely to survive into the next generation.
The algorithm below is one of the simplest of them, a (10 + 40) evolution strategy. It keeps 10 parent parameter sets. In each generation it makes 40 children by adding small random changes (“mutations”) to copies of randomly chosen parents, and the best 10 of all 50 become the next parents. The mutations shrink slowly from one generation to the next, so the search moves from exploring widely to refining locally. The parameters are searched on a logarithmic scale, which suits parameters whose plausible values span orders of magnitude.
Core MATLAB only.
%% A simple evolutionary algorithm for parameter estimation
% The same model and data as in fit_inhibition (D1 and D2 together), but
% now estimated by a (10 + 40) evolution strategy, which needs no starting
% guess and no gradients:
% 1. start from 50 random parameter sets and keep the best 10 (parents);
% 2. each generation, make 40 children, each a copy of a random parent
% with small random changes to its parameters ('mutation');
% 3. keep the best 10 of parents and children; shrink the mutations a
% little; repeat.
% Parameters are searched on a log scale, from 0.1 to about 316.
% Requires: core MATLAB only.
data = readmatrix(fullfile(sbp.data_dir(), 'competitive_inhibition.csv'));
S = [data(:, 1); data(:, 1)];
I = [10 * ones(20, 1); 20 * ones(20, 1)];
v = [data(:, 2); data(:, 3)];
delta = 0.1;
sse = @(log_p) sum(((10^log_p(1) * S ./ ...
(10^log_p(2) * (1 + I / 10^log_p(3)) + S) - v) ./ (delta * v)) .^ 2);
rng(1); % fixed seed: the same run every time
lo = -1.0; hi = 2.5; % bounds on log10 of each parameter
n_parents = 10; n_children = 40; n_generations = 60;
sigma = 0.5; % initial mutation size (log10 units)
% 1. Random start; keep the best 10
pop = lo + (hi - lo) * rand(50, 3);
cost = arrayfun(@(k) sse(pop(k, :)), (1:50)');
[~, order] = sort(cost);
parents = pop(order(1:n_parents), :);
parent_cost = cost(order(1:n_parents));
snapshots = {parents};
snapshot_gens = 0;
best_per_generation = zeros(1, n_generations + 1);
best_per_generation(1) = parent_cost(1);
n_evaluations = 50;
for g = 1:n_generations
% 2. Children: mutated copies of randomly chosen parents
pick = randi(n_parents, n_children, 1);
children = parents(pick, :) + sigma * randn(n_children, 3);
children = min(max(children, lo), hi);
child_cost = arrayfun(@(k) sse(children(k, :)), (1:n_children)');
n_evaluations = n_evaluations + n_children;
% 3. Survival of the fittest, among parents and children together
everyone = [parents; children];
everyone_cost = [parent_cost; child_cost];
[~, order] = sort(everyone_cost);
parents = everyone(order(1:n_parents), :);
parent_cost = everyone_cost(order(1:n_parents));
sigma = sigma * 0.93;
best_per_generation(g + 1) = parent_cost(1);
if ismember(g, [5 20 n_generations])
snapshots{end + 1} = parents; %#ok<SAGROW>
snapshot_gens(end + 1) = g; %#ok<SAGROW>
end
end
p = 10 .^ parents(1, :);
fprintf(['Best after %d generations (%d SSE evaluations): vmax = %.3f, ' ...
'KM = %.3f, KI = %.3f, SSE = %.4f\n'], n_generations, n_evaluations, ...
p(1), p(2), p(3), parent_cost(1));
%% Plot
fig = figure('Position', [100 100 1000 400]);
subplot(1, 2, 1)
semilogy(0:n_generations, best_per_generation, 'o-', ...
'Color', [0.000 0.447 0.698], 'MarkerSize', 3, ...
'MarkerFaceColor', [0.000 0.447 0.698]);
hold on
yline(63.7765, '--', 'Color', [0.6 0.6 0.6], 'LineWidth', 1.5);
ylim([50 Inf]); % so the optimum is not on the axis
xlabel('Generation'); ylabel('Best SSE so far'); title('Convergence');
legend({'', 'least-squares optimum (fit\_inhibition)'}, 'Box', 'off');
box off
subplot(1, 2, 2)
colors = [0.733 0.733 0.733; 0.902 0.624 0.000;
0.000 0.620 0.451; 0.000 0.447 0.698];
for k = 1:numel(snapshots)
P = 10 .^ snapshots{k};
loglog(P(:, 2), P(:, 3), 'o', 'Color', colors(k, :), ...
'MarkerFaceColor', colors(k, :), 'MarkerSize', 5);
hold on
end
xlim([0.1 316]); ylim([0.1 316]);
xlabel('K_M (mM)'); ylabel('K_I (mM)');
title('The 10 parents, as the search proceeds');
legend(compose('generation %d', snapshot_gens), 'Location', 'southeast', ...
'Box', 'off');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-evolutionary');
results.best = struct('SSE', parent_cost(1), 'vmax', p(1), 'KM', p(2), ...
'KI', p(3));
results.n_evaluations = n_evaluations;
results.best_per_generation = best_per_generation;
sbp.save_results(mfilename('fullpath'), results);
Needs NumPy and Matplotlib.
"""A simple evolutionary algorithm for parameter estimation.
The same model and data as in fit_inhibition (D1 and D2 together), but
now estimated by a (10 + 40) evolution strategy, which needs no starting
guess and no gradients:
1. start from 50 random parameter sets and keep the best 10 (parents);
2. each generation, make 40 children, each a copy of a random parent
with small random changes to its parameters ('mutation');
3. keep the best 10 of parents and children; shrink the mutations a
little; repeat.
Parameters are searched on a log scale, from 0.1 to about 316.
"""
import numpy as np
import matplotlib.pyplot as plt
import sbp
data = np.loadtxt(sbp.DATA / "competitive_inhibition.csv", delimiter=",",
skiprows=1)
S = np.r_[data[:, 0], data[:, 0]]
I = np.r_[np.full(20, 10.0), np.full(20, 20.0)]
v = np.r_[data[:, 1], data[:, 2]]
delta = 0.1
def sse(log_p):
vmax, KM, KI = 10.0 ** log_p
v_pred = vmax * S / (KM * (1 + I / KI) + S)
return np.sum(((v_pred - v) / (delta * v)) ** 2)
rng = np.random.default_rng(1) # fixed seed: the same run every time
lo, hi = -1.0, 2.5 # bounds on log10 of each parameter
n_parents, n_children, n_generations = 10, 40, 60
sigma = 0.5 # initial mutation size (log10 units)
# 1. Random start; keep the best 10
pop = rng.uniform(lo, hi, size=(50, 3))
cost = np.array([sse(p) for p in pop])
keep = np.argsort(cost)[:n_parents]
parents, parent_cost = pop[keep], cost[keep]
snapshots = {0: parents.copy()}
best_per_generation = [parent_cost[0]]
n_evaluations = 50
for g in range(1, n_generations + 1):
# 2. Children: mutated copies of randomly chosen parents
pick = rng.integers(n_parents, size=n_children)
children = parents[pick] + sigma * rng.standard_normal((n_children, 3))
children = np.clip(children, lo, hi)
child_cost = np.array([sse(p) for p in children])
n_evaluations += n_children
# 3. Survival of the fittest, among parents and children together
everyone = np.vstack([parents, children])
everyone_cost = np.r_[parent_cost, child_cost]
keep = np.argsort(everyone_cost)[:n_parents]
parents, parent_cost = everyone[keep], everyone_cost[keep]
sigma *= 0.93
best_per_generation.append(parent_cost[0])
if g in (5, 20):
snapshots[g] = parents.copy()
snapshots[n_generations] = parents.copy()
vmax, KM, KI = 10.0 ** parents[0]
print(f"Best after {n_generations} generations ({n_evaluations} SSE "
f"evaluations): vmax = {vmax:.3f}, KM = {KM:.3f}, KI = {KI:.3f}, "
f"SSE = {parent_cost[0]:.4f}")
# --- Plot
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.semilogy(best_per_generation, "o-", color="#0072B2", ms=3)
ax1.axhline(63.7765, color="#999999", ls="--",
label="least-squares optimum (fit_inhibition)")
ax1.set_ylim(bottom=50) # so the optimum is not on the axis
ax1.set_xlabel("Generation")
ax1.set_ylabel("Best SSE so far")
ax1.set_title("Convergence")
ax1.legend(frameon=False)
colors = {0: "#bbbbbb", 5: "#E69F00", 20: "#009E73",
n_generations: "#0072B2"}
for g, P in snapshots.items():
ax2.plot(10.0 ** P[:, 1], 10.0 ** P[:, 2], "o", color=colors[g], ms=5,
label=f"generation {g}")
ax2.set_xscale("log")
ax2.set_yscale("log")
ax2.set_xlim(0.1, 316)
ax2.set_ylim(0.1, 316)
ax2.set_xlabel("$K_M$ (mM)")
ax2.set_ylabel("$K_I$ (mM)")
ax2.set_title("The 10 parents, as the search proceeds")
ax2.legend(frameon=False, loc="lower right")
sbp.save_figure(fig, __file__, "fig-evolutionary")
sbp.save_results(__file__, {
"best": {"SSE": parent_cost[0], "vmax": vmax, "KM": KM, "KI": KI},
"n_evaluations": n_evaluations,
"best_per_generation": best_per_generation,
})
sbp.show()
Starting from parameter sets scattered across more than three orders of magnitude, the population gathers into the basin we saw in the landscape and closes in on the least-squares estimate. After 60 generations, or 2450 evaluations of the SSE, the best parameter set is within a few per cent of the least-squares estimates, and its SSE is within 0.02% of the least-squares minimum. Note that, on the way, the parents spread out along the same valley as before: the algorithm finds \(K_M^\text{app}\) well before it pins down \(K_M\) and \(K_I\) separately.
MATLAB and Python draw different random numbers, so the two versions follow different paths and end at slightly different points; the automated checks require both to land within 5% of the least-squares optimum. Run either version with a few different seeds to see how much the result varies.
The trade-off is clear from this small problem. The evolutionary algorithm needed no starting guess and no derivatives, but it used about 2450 evaluations to reach an approximate answer, whereas the least-squares solver reached the exact optimum in a few dozen evaluations, counting those used to estimate derivatives. For larger models, a common strategy is to combine the two: a global method to find the right basin, followed by a local method to finish the job.
6.4 Post-regression diagnostics
6.4.1 Model selection
The inhibition data of §6.2.2 were collected for an enzyme with a competitive inhibitor. But do the data themselves tell us that? We fit four rate laws to both datasets together, competitive, uncompetitive and non-competitive inhibition (three parameters each), and mixed inhibition (four parameters), and compare them using the Akaike Information Criterion. For weighted least squares with known measurement errors, \(\text{AIC} = \chi^2 + 2k\), where \(\chi^2\) is the weighted SSE and \(k\) the number of parameters; the second term is the price of every additional parameter, much in the spirit of Occam’s razor. With only 40 data points, we use the corrected form, AICc. Akaike weights then express the relative support for each model. Finally, from the covariance matrix of the estimates, \(\hat{V} = (J^TJ)^{-1}\), we compute the cross-correlations of Eq. 6.11.
Needs the Optimization Toolbox (for lsqnonlin).
%% Model selection: which kind of inhibition do the data support?
% The data are those of fit_inhibition: initial rates at 20 substrate
% concentrations, with an inhibitor at 10 mM and at 20 mM. We fit four
% rate laws, with three or four parameters, by weighted least squares
% (10% relative error), and compare them by
% * the weighted SSE, chi^2 (book Eq. 6.9, with sigma = 0.1 v);
% * the Akaike Information Criterion, AIC = chi^2 + 2k, for k parameters,
% with the correction for small samples, AICc = AIC + 2k(k+1)/(n-k-1);
% * Akaike weights, the relative support for each model;
% * the cross-correlation of the parameter estimates (book Eq. 6.11),
% from the covariance matrix V = (J'J)^-1, where J is the Jacobian of
% the weighted residuals at the optimum.
% Requires: Optimization Toolbox (for lsqnonlin).
data = readmatrix(fullfile(sbp.data_dir(), 'competitive_inhibition.csv'));
S = [data(:, 1); data(:, 1)];
I = [repmat(10, 20, 1); repmat(20, 20, 1)];
v = [data(:, 2); data(:, 3)];
n = numel(v);
delta = 0.1;
names = {'competitive', 'uncompetitive', 'noncompetitive', 'mixed'};
params = {{'vmax', 'KM', 'KI'}, {'vmax', 'KM', 'KI'}, {'vmax', 'KM', 'KI'}, ...
{'vmax', 'KM', 'KI', 'KI2'}};
rates = {@(p, S, I) p(1) * S ./ (p(2) * (1 + I / p(3)) + S), ...
@(p, S, I) p(1) * S ./ (p(2) + S .* (1 + I / p(3))), ...
@(p, S, I) p(1) * S ./ ((p(2) + S) .* (1 + I / p(3))), ...
@(p, S, I) p(1) * S ./ (p(2) * (1 + I / p(3)) + S .* (1 + I / p(4)))};
opts = optimoptions('lsqnonlin', 'Display', 'off', ...
'FunctionTolerance', 1e-14, 'StepTolerance', 1e-14, ...
'OptimalityTolerance', 1e-14, 'MaxFunctionEvaluations', 1e5, ...
'MaxIterations', 1e4);
results = struct();
aicc = zeros(1, numel(names));
for m = 1:numel(names)
rate = rates{m};
k = numel(params{m});
resid = @(p) (rate(p, S, I) - v) ./ (delta * v);
best_p = []; best_cost = inf;
for scale_km = [0.2, 1, 5] % nine starting guesses
for scale_ki = [0.2, 1, 5]
p0 = [20, 5 * scale_km, repmat(5 * scale_ki, 1, k - 2)];
if k == 4, p0(4) = 10 * p0(4); end
[p, cost] = lsqnonlin(resid, p0, zeros(1, k), [], opts);
if cost < best_cost, best_p = p; best_cost = cost; end
end
end
p = best_p;
chi2 = sum(resid(p) .^ 2);
J = jacobian(resid, p);
V = inv(J' * J);
sd = sqrt(diag(V))';
kappa = V ./ (sd' * sd);
aic = chi2 + 2 * k;
aicc(m) = aic + 2 * k * (k + 1) / (n - k - 1);
results.(names{m}) = struct('parameters', p, 'sd', sd, 'chi2', chi2, ...
'aic', aic, 'aicc', aicc(m), 'kappa', kappa);
end
weights = exp(-(aicc - min(aicc)) / 2);
weights = weights / sum(weights);
for m = 1:numel(names)
r = results.(names{m});
results.(names{m}).weight = weights(m);
fprintf(['%-15s chi2 = %6.2f AIC = %6.2f AICc = %6.2f ' ...
'weight = %.2f\n'], ...
names{m}, r.chi2, r.aic, r.aicc, weights(m));
parts = arrayfun(@(j) sprintf('%s = %.3g ± %.2g', params{m}{j}, ...
r.parameters(j), r.sd(j)), 1:numel(params{m}), 'UniformOutput', false);
fprintf(' %s\n', strjoin(parts, ', '));
fprintf(' largest |cross-correlation| = %.3f\n', ...
max(max(abs(r.kappa - eye(numel(params{m}))))));
end
%% Plot: data and the two best models, and the Akaike weights
fig = figure('Position', [100 100 1000 400]);
tiledlayout(1, 5);
nexttile([1 3]); hold on
s_fine = linspace(0.5, 20, 200)';
markers = {'o', 's'}; levels = [10, 20];
colours = {[0.000 0.447 0.698], [0.835 0.369 0.000]};
styles = {'-', '--'};
shown = {'competitive', 'noncompetitive'};
for l = 1:2
for m = 1:2
rate = rates{strcmp(names, shown{m})};
h = plot(s_fine, ...
rate(results.(shown{m}).parameters, s_fine, levels(l)), ...
'Color', colours{m}, 'LineStyle', styles{m}, ...
'DisplayName', shown{m});
if l == 2, h.HandleVisibility = 'off'; end
end
keep = I == levels(l);
errorbar(S(keep), v(keep), delta * v(keep), markers{l}, ...
'Color', 'k', 'MarkerFaceColor', 'k', 'MarkerSize', 4, ...
'CapSize', 2, 'DisplayName', sprintf('data, I = %d mM', levels(l)));
end
xlabel('S (mM)'); ylabel('v (mmol/L/s)');
legend('Box', 'off', 'Location', 'northwest'); box off
nexttile([1 2])
bar(categorical(names, names), weights, 'FaceColor', [0.000 0.447 0.698]);
xtickangle(30);
ylabel('Akaike weight'); title('Support for each model'); box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-model-selection');
sbp.save_results(mfilename('fullpath'), results);
%% Local functions
function J = jacobian(resid, p)
% Central differences of the weighted residuals.
r0 = resid(p);
J = zeros(numel(r0), numel(p));
for j = 1:numel(p)
h = 1e-6 * p(j);
up = p; up(j) = up(j) + h;
down = p; down(j) = down(j) - h;
J(:, j) = (resid(up) - resid(down)) / (2 * h);
end
end
Needs SciPy.
"""Model selection: which kind of inhibition do the data support?
The data are those of fit_inhibition: initial rates at 20 substrate
concentrations, with an inhibitor at 10 mM and at 20 mM. We fit four
rate laws, with three or four parameters, by weighted least squares
(10% relative error), and compare them by
* the weighted SSE, chi^2 (book Eq. 6.9, with sigma = 0.1 v);
* the Akaike Information Criterion, AIC = chi^2 + 2k, for k parameters,
with the correction for small samples, AICc = AIC + 2k(k+1)/(n-k-1);
* Akaike weights, the relative support for each model;
* the cross-correlation of the parameter estimates (book Eq. 6.11),
from the covariance matrix V = (J'J)^-1, where J is the Jacobian of
the weighted residuals at the optimum.
"""
import numpy as np
from scipy.optimize import least_squares
import matplotlib.pyplot as plt
import sbp
data = np.loadtxt(sbp.DATA / "competitive_inhibition.csv", delimiter=",",
skiprows=1)
S = np.r_[data[:, 0], data[:, 0]]
I = np.r_[np.full(20, 10.0), np.full(20, 20.0)]
v = np.r_[data[:, 1], data[:, 2]]
n = len(v)
delta = 0.1
models = {
"competitive": (["vmax", "KM", "KI"],
lambda p, S, I: p[0] * S / (p[1] * (1 + I / p[2]) + S)),
"uncompetitive": (["vmax", "KM", "KI"],
lambda p, S, I: p[0] * S / (p[1] + S * (1 + I / p[2]))),
"noncompetitive": (["vmax", "KM", "KI"],
lambda p, S, I: p[0] * S
/ ((p[1] + S) * (1 + I / p[2]))),
"mixed": (["vmax", "KM", "KI", "KI2"],
lambda p, S, I: p[0] * S / (p[1] * (1 + I / p[2])
+ S * (1 + I / p[3]))),
}
def residuals(rate, p):
return (rate(p, S, I) - v) / (delta * v)
def jacobian(rate, p):
"""Central differences of the weighted residuals."""
J = np.zeros((n, len(p)))
for j in range(len(p)):
h = 1e-6 * p[j]
up, down = p.copy(), p.copy()
up[j] += h
down[j] -= h
J[:, j] = (residuals(rate, up) - residuals(rate, down)) / (2 * h)
return J
results = {}
for name, (names, rate) in models.items():
k = len(names)
best = None
for scale_km in (0.2, 1, 5): # nine starting guesses
for scale_ki in (0.2, 1, 5):
p0 = np.array([20, 5 * scale_km] + [5 * scale_ki] * (k - 2))
if k == 4:
p0[3] *= 10
sol = least_squares(lambda p: residuals(rate, p), p0,
bounds=(0, np.inf), xtol=1e-14, ftol=1e-14,
gtol=1e-14)
if best is None or sol.cost < best.cost:
best = sol
p = best.x
chi2 = np.sum(residuals(rate, p) ** 2)
V = np.linalg.inv(jacobian(rate, p).T @ jacobian(rate, p))
sd = np.sqrt(np.diag(V))
kappa = V / np.outer(sd, sd)
aic = chi2 + 2 * k
results[name] = {"parameters": p, "sd": sd, "chi2": chi2, "aic": aic,
"aicc": aic + 2 * k * (k + 1) / (n - k - 1),
"kappa": kappa}
aicc = np.array([r["aicc"] for r in results.values()])
weights = np.exp(-(aicc - aicc.min()) / 2)
weights /= weights.sum()
for (name, r), w in zip(results.items(), weights):
r["weight"] = w
names = models[name][0]
print(f"{name:15s} chi2 = {r['chi2']:6.2f} AIC = {r['aic']:6.2f} "
f"AICc = {r['aicc']:6.2f} weight = {w:.2f}")
print(" " + ", ".join(f"{a} = {b:.3g} ± {c:.2g}" for a, b, c
in zip(names, r["parameters"], r["sd"])))
worst = np.max(np.abs(r["kappa"] - np.eye(len(names))))
print(f" largest |cross-correlation| = {worst:.3f}")
# --- Plot: data and the two best models, and the Akaike weights
sbp.style()
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4),
gridspec_kw={"width_ratios": [1.4, 1]})
s_fine = np.linspace(0.5, 20, 200)
for level, marker in ((10, "o"), (20, "s")):
for name, colour, style in (("competitive", "#0072B2", "-"),
("noncompetitive", "#D55E00", "--")):
rate = models[name][1]
ax1.plot(s_fine, rate(results[name]["parameters"], s_fine, level),
color=colour, ls=style,
label=name if level == 10 else None)
keep = I == level
ax1.errorbar(S[keep], v[keep], yerr=delta * v[keep], fmt=marker,
color="black", ms=4, capsize=2,
label=f"data, I = {level} mM")
ax1.set_xlabel("S (mM)")
ax1.set_ylabel("v (mmol/L/s)")
ax1.legend(frameon=False, fontsize=9, loc="upper left")
ax2.bar(list(results), weights, color="#0072B2")
ax2.set_ylabel("Akaike weight")
ax2.tick_params(axis="x", rotation=30)
plt.setp(ax2.get_xticklabels(), ha="right", rotation_mode="anchor")
ax2.set_title("Support for each model")
sbp.save_figure(fig, __file__, "fig-model-selection")
sbp.save_results(__file__, results)
sbp.show()
The results are instructive. Uncompetitive inhibition fits worse, with an Akaike weight of only 0.09, and its parameters are strongly correlated (\(|\kappa| = 0.99\)). Mixed inhibition fits the data no better than the simpler models, despite its extra parameter, and its parameters are weakly determinable (\(|\kappa| > 0.95\); note the uncertainty in \(K_{I2}\)). However, competitive and non-competitive inhibition fit the data equally well: their AICc values differ by less than 0.4, and the Akaike weights are 0.36 and 0.42. These data simply cannot distinguish between the two mechanisms. This is exactly the question posed in Exercise 6.1(b): to discriminate, we need more informative experiments, for instance rates at higher substrate concentrations, where a competitive inhibitor is overcome and a non-competitive one is not, or rates without any inhibitor at all.
6.4.2 Sensitivity and robustness of biological models
We compute the local sensitivities of Eq. 6.12 for the gene expression model of §6.2.2, at the parameters fitted there to mRNA and protein. Each derivative \(\partial x_i/\partial \theta_j\) is obtained by central differences, by solving the ODEs with \(\theta_j\) raised and lowered by 0.01%. It is convenient to normalise the sensitivities, as \((\theta_j/x_i)\,\partial x_i/\partial \theta_j\): this is the percentage change in \(x_i\) for a 1% change in \(\theta_j\), and it can be compared across parameters with different units.
Core MATLAB only.
%% Local sensitivity analysis of a gene expression model
% The model is that of fit_timecourse: a gene switched on at t = 0, with
% dm/dt = k_m - g_m m, dp/dt = k_p m - g_p p, m(0) = p(0) = 0,
% at the parameters fitted there to mRNA and protein data. The local
% sensitivity of state x_i to parameter theta_j (book Eq. 6.12) is
% S_ij(t) = dx_i(t)/dtheta_j, which we compute by central differences:
% solve the ODEs with theta_j raised and lowered by 0.01%. We report the
% normalised sensitivity (theta_j / x_i) dx_i/dtheta_j, the percentage
% change in x_i for a 1% change in theta_j, which can be compared across
% parameters of different units.
names = {'k_m', 'g_m', 'k_p', 'g_p'};
theta = [9.4984, 0.96342, 5.2262, 0.20479]; % fit_timecourse
t = linspace(0.5, 24, 48);
x = simulate(theta, t);
normalised = zeros(2, numel(t), numel(theta)); % state x time x parameter
for j = 1:numel(theta)
h = 1e-4 * theta(j);
up = theta; up(j) = up(j) + h;
down = theta; down(j) = down(j) - h;
dx = (simulate(up, t) - simulate(down, t)) / (2 * h);
normalised(:, :, j) = theta(j) * dx ./ x;
end
fprintf('Normalised sensitivity of protein to each parameter:\n');
fprintf(' t (h) %s\n', sprintf('%8s', names{:}));
for k = [1, 4, 12, 24, 48]
fprintf(' %5.1f %s\n', t(k), ...
sprintf('%8.3f', squeeze(normalised(2, k, :))));
end
fprintf(['At steady state, p* = k_m k_p / (g_m g_p): the sensitivities ' ...
'approach +1, -1, +1, -1.\n']);
%% Plot
fig = figure('Position', [100 100 1000 400]);
tiledlayout(1, 2, 'TileSpacing', 'compact');
colours = [0.000 0.447 0.698; 0.902 0.624 0.000; 0.000 0.620 0.451; ...
0.835 0.369 0.000];
styles = {'-', '--', '-', '--'}; % dashed: degradation rates
titles = {'mRNA', 'Protein'};
for i = 1:2
ax(i) = nexttile; hold on
for j = 1:numel(names)
plot(t, normalised(i, :, j), 'Color', colours(j, :), ...
'LineStyle', styles{j}, 'LineWidth', 1.5);
end
yline(0, 'k');
xlabel('Time (h)'); title(titles{i}); box off
if i == 1, ylabel('Normalised sensitivity'); else, yticklabels({}); end
end
linkaxes(ax, 'y');
lgd = legend(names, 'Box', 'off', 'Interpreter', 'tex');
lgd.Layout.Tile = 'east';
sbp.save_figure(fig, mfilename('fullpath'), 'fig-sensitivity');
results.t = t;
results.mrna = squeeze(normalised(1, :, :));
results.protein = squeeze(normalised(2, :, :));
sbp.save_results(mfilename('fullpath'), results);
%% Local functions
function x = simulate(p, t)
% Rows: mRNA, protein, at the times t.
rhs = @(~, y) [p(1) - p(2) * y(1); p(3) * y(1) - p(4) * y(2)];
opts = odeset('RelTol', 1e-11, 'AbsTol', 1e-11);
[~, y] = ode45(rhs, [0, t], [0; 0], opts);
x = y(2:end, :)';
end
Needs SciPy.
"""Local sensitivity analysis of a gene expression model.
The model is that of fit_timecourse: a gene switched on at t = 0, with
dm/dt = k_m - g_m m, dp/dt = k_p m - g_p p, m(0) = p(0) = 0,
at the parameters fitted there to mRNA and protein data. The local
sensitivity of state x_i to parameter theta_j (book Eq. 6.12) is
S_ij(t) = dx_i(t)/dtheta_j, which we compute by central differences:
solve the ODEs with theta_j raised and lowered by 0.01%. We report the
normalised sensitivity (theta_j / x_i) dx_i/dtheta_j, the percentage
change in x_i for a 1% change in theta_j, which can be compared across
parameters of different units.
"""
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
import sbp
names = ["k_m", "g_m", "k_p", "g_p"]
theta = np.array([9.4984, 0.96342, 5.2262, 0.20479]) # fit_timecourse
t = np.linspace(0.5, 24, 48)
def simulate(p):
k_m, g_m, k_p, g_p = p
rhs = lambda _, y: [k_m - g_m * y[0], k_p * y[0] - g_p * y[1]]
sol = solve_ivp(rhs, [0, t[-1]], [0, 0], t_eval=t, method="LSODA",
rtol=1e-11, atol=1e-11)
return sol.y # rows: mRNA, protein
x = simulate(theta)
normalised = np.zeros((2, len(t), len(theta))) # state x time x parameter
for j in range(len(theta)):
h = 1e-4 * theta[j]
up, down = theta.copy(), theta.copy()
up[j] += h
down[j] -= h
dx = (simulate(up) - simulate(down)) / (2 * h)
normalised[:, :, j] = theta[j] * dx / x
print("Normalised sensitivity of protein to each parameter:")
print(" t (h) " + "".join(f"{n:>8s}" for n in names))
for k in (0, 3, 11, 23, 47):
print(f" {t[k]:5.1f} " + "".join(f"{s:8.3f}" for s in normalised[1, k]))
print("At steady state, p* = k_m k_p / (g_m g_p): the sensitivities "
"approach +1, -1, +1, -1.")
# --- Plot
sbp.style()
fig, axes = plt.subplots(1, 2, figsize=(10, 4), sharey=True)
colours = ["#0072B2", "#E69F00", "#009E73", "#D55E00"]
styles = ["-", "--", "-", "--"] # dashed: degradation rates
for ax, i, title in zip(axes, (0, 1), ("mRNA", "Protein")):
for j in range(len(names)):
ax.plot(t, normalised[i, :, j], color=colours[j], ls=styles[j],
label=f"${names[j]}$")
ax.axhline(0, color="black", lw=0.5)
ax.set_xlabel("Time (h)")
ax.set_title(title)
axes[0].set_ylabel("Normalised sensitivity")
axes[1].legend(frameon=False, loc="center left", bbox_to_anchor=(1, 0.5))
sbp.save_figure(fig, __file__, "fig-sensitivity")
sbp.save_results(__file__, {"t": t, "mrna": normalised[0],
"protein": normalised[1]})
sbp.show()
The two synthesis rates, \(k_m\) and \(k_p\), enter the model linearly, so the protein level is always exactly proportional to each (sensitivity 1; in the right panel, the two lines coincide). The degradation rates matter little early on, and increasingly so as the system approaches steady state, where \(p^* = k_mk_p/(g_mg_p)\) and the sensitivities tend to \(+1, -1, +1, -1\), a useful check on the code. Note also that the protein responds to \(g_m\) much sooner than to \(g_p\): mRNA turns over in about an hour, but protein takes several. Global sensitivity analyses (§6.4.2.2) repeat such calculations across many parameter sets, sampled from the whole parameter space.
6.5 Troubleshooting
6.5.1 Regularisation
There is no code for this section; see the book.
6.5.2 Sloppiness
Near the optimum, the cost function is approximately a quadratic form, with Hessian \(\approx J^TJ\), the Fisher Information Matrix, where \(J\) is the Jacobian of the weighted residuals. Following Gutenkunst et al., we differentiate with respect to \(\log\theta\), so that the eigenvalues measure relative changes in the parameters. Large eigenvalues correspond to stiff directions in parameter space, and small ones to sloppy directions. We compare two experiments on the gene expression model of §6.2.2: measuring both mRNA and protein, or protein alone.
Core MATLAB only.
%% Sloppiness: the eigenvalues of the Hessian of the cost function
% Near its minimum, the weighted SSE behaves like a quadratic form whose
% Hessian is approximated by J'J, where J is the Jacobian of the weighted
% residuals (the Fisher Information Matrix, FIM). Following Gutenkunst et
% al., we differentiate with respect to log(theta), so that the
% eigenvalues measure relative changes in the parameters. A model is
% sloppy if lambda_min / lambda_max < 1e-3 (book §6.5.2).
%
% The model and data are those of fit_timecourse, at the parameters fitted
% there, and we compare two experiments: measuring both mRNA and protein,
% or the protein alone.
names = {'k_m', 'g_m', 'k_p', 'g_p'};
theta = [9.4984, 0.96342, 5.2262, 0.20479]; % fit_timecourse
data = readmatrix(fullfile(sbp.data_dir(), 'gene_expression_timecourse.csv'));
t = data(:, 1)'; m_obs = data(:, 2)'; p_obs = data(:, 3)';
delta = 0.1;
keys = {'mrna_and_protein', 'protein_only'};
labels = {'mRNA and protein', 'protein only'};
results = struct();
for c = 1:2
use_mrna = c == 1;
resid = @(log_p) residuals(exp(log_p), t, m_obs, p_obs, delta, use_mrna);
log_p = log(theta);
J = zeros(numel(resid(log_p)), numel(theta));
for j = 1:numel(theta) % central differences
up = log_p; up(j) = up(j) + 1e-5;
down = log_p; down(j) = down(j) - 1e-5;
J(:, j) = (resid(up) - resid(down)) / 2e-5;
end
[V, D] = eig(J' * J);
[ev, order] = sort(diag(D), 'descend');
sloppiest = V(:, order(end));
first = sloppiest(find(abs(sloppiest) > 1e-3, 1)); % fix the sign:
sloppiest = sign(first) * sloppiest; % first clear entry positive
results.(keys{c}) = struct('eigenvalues', ev', ...
'ratio', ev(end) / ev(1), 'sloppiest', sloppiest');
fprintf('%s: eigenvalues %s; lambda_min/lambda_max = %.2g\n', keys{c}, ...
strjoin(compose('%.3g', ev'), ', '), ev(end) / ev(1));
fprintf(' sloppiest direction (in log parameters): %s\n', ...
strjoin(compose('%s %+.2f', string(names'), sloppiest), ', '));
end
%% Plot: the eigenvalue spectra
fig = figure('Position', [100 100 500 450]); hold on
for c = 1:2
ev = results.(keys{c}).eigenvalues;
ratio = max(ev / ev(1), 1e-12); % zero is drawn at 1e-12
for e = ratio
plot([c - 1.3, c - 0.7], [e, e], 'Color', [0.000 0.447 0.698], ...
'LineWidth', 1.5);
end
end
set(gca, 'YScale', 'log', 'XTick', [0, 1], 'XTickLabel', labels);
ylim([1e-13, 3]); xlim([-0.6, 1.6]);
yline(1e-3, ':k', 'LineWidth', 1);
ylabel('Eigenvalue / largest eigenvalue'); title('Eigenvalues of J''J');
box off
sbp.save_figure(fig, mfilename('fullpath'), 'fig-sloppiness');
sbp.save_results(mfilename('fullpath'), results);
%% Local functions
function r = residuals(p, t, m_obs, p_obs, delta, use_mrna)
rhs = @(~, y) [p(1) - p(2) * y(1); p(3) * y(1) - p(4) * y(2)];
opts = odeset('RelTol', 1e-11, 'AbsTol', 1e-11);
[~, y] = ode45(rhs, [0, t], [0; 0], opts);
y = y(2:end, :)';
r = (y(2, :) - p_obs) ./ (delta * p_obs);
if use_mrna
r = [(y(1, :) - m_obs) ./ (delta * m_obs), r];
end
r = r';
end
Needs SciPy.
"""Sloppiness: the eigenvalues of the Hessian of the cost function.
Near its minimum, the weighted SSE behaves like a quadratic form whose
Hessian is approximated by J'J, where J is the Jacobian of the weighted
residuals (the Fisher Information Matrix, FIM). Following Gutenkunst et
al., we differentiate with respect to log(theta), so that the
eigenvalues measure relative changes in the parameters. A model is
sloppy if lambda_min / lambda_max < 1e-3 (book §6.5.2).
The model and data are those of fit_timecourse, at the parameters fitted
there, and we compare two experiments: measuring both mRNA and protein,
or the protein alone.
"""
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
import sbp
names = ["k_m", "g_m", "k_p", "g_p"]
theta = np.array([9.4984, 0.96342, 5.2262, 0.20479]) # fit_timecourse
data = np.loadtxt(sbp.DATA / "gene_expression_timecourse.csv",
delimiter=",", skiprows=1)
t, m_obs, p_obs = data.T
delta = 0.1
def simulate(p):
k_m, g_m, k_p, g_p = p
rhs = lambda _, y: [k_m - g_m * y[0], k_p * y[0] - g_p * y[1]]
sol = solve_ivp(rhs, [0, t[-1]], [0, 0], t_eval=t, method="LSODA",
rtol=1e-11, atol=1e-11)
return sol.y
def residuals(log_p, use_mrna):
m, prot = simulate(np.exp(log_p))
r = (prot - p_obs) / (delta * p_obs)
if use_mrna:
r = np.r_[(m - m_obs) / (delta * m_obs), r]
return r
def fim(use_mrna):
"""J'J, by central differences in log(theta)."""
log_p = np.log(theta)
columns = []
for j in range(len(theta)):
up, down = log_p.copy(), log_p.copy()
up[j] += 1e-5
down[j] -= 1e-5
columns.append((residuals(up, use_mrna) - residuals(down, use_mrna))
/ 2e-5)
J = np.array(columns).T
return J.T @ J
results = {}
for key, use_mrna in (("mrna_and_protein", True), ("protein_only", False)):
eigenvalues, eigenvectors = np.linalg.eigh(fim(use_mrna))
order = np.argsort(eigenvalues)[::-1] # largest first
eigenvalues = eigenvalues[order]
stiffest = eigenvectors[:, order[0]]
sloppiest = eigenvectors[:, order[-1]]
first = sloppiest[np.abs(sloppiest) > 1e-3][0] # fix the sign: first
sign = 1 if first > 0 else -1 # clear entry positive
results[key] = {"eigenvalues": eigenvalues,
"ratio": eigenvalues[-1] / eigenvalues[0],
"sloppiest": sign * sloppiest}
print(f"{key}: eigenvalues " + ", ".join(f"{e:.3g}" for e in eigenvalues)
+ f"; lambda_min/lambda_max = {results[key]['ratio']:.2g}")
print(" sloppiest direction (in log parameters): "
+ ", ".join(f"{n} {c:+.2f}"
for n, c in zip(names, sign * sloppiest)))
# --- Plot: the eigenvalue spectra
sbp.style()
fig, ax = plt.subplots(figsize=(5, 4.5))
for x, (key, label) in enumerate([("mrna_and_protein", "mRNA and protein"),
("protein_only", "protein only")]):
ev = results[key]["eigenvalues"]
ratio = np.maximum(ev / ev[0], 1e-12) # zero is drawn at 1e-12
ax.hlines(ratio, x - 0.3, x + 0.3, color="#0072B2")
ax.set_yscale("log")
ax.set_ylim(1e-13, 3)
ax.axhline(1e-3, ls=":", color="black", lw=1)
ax.set_xticks([0, 1], ["mRNA and protein", "protein only"])
ax.set_ylabel("Eigenvalue / largest eigenvalue")
ax.set_title("Eigenvalues of J'J")
sbp.save_figure(fig, __file__, "fig-sloppiness")
sbp.save_results(__file__, results)
sbp.show()
With both mRNA and protein, the eigenvalues span two and a half orders of magnitude (\(\lambda_{min}/\lambda_{max} = 0.0034\)). By the criterion of the book (the dotted line, at \(10^{-3}\)), the model is just short of sloppy; even so, the sloppiest direction (all four parameters changing together, synthesis and degradation of protein against those of mRNA) is far less constrained than the stiffest. With protein data alone, one eigenvalue is zero, up to rounding error; since zero cannot be drawn on a logarithmic scale, the figure places it at \(10^{-12}\), at the bottom of the axis. Its eigenvector, \(\log k_m\) up and \(\log k_p\) down by the same amount, is a direction in which the cost does not change at all: the protein data fix only the product \(k_mk_p\), exactly as we found by fitting in §6.2.2. Here, sloppiness has become non-identifiability, and no amount of protein data can cure it; only a different measurement, of mRNA, can.
6.5.3 Choosing a search algorithm
There is no code for this section; see the book.
6.5.4 Model reduction
There is no code for this section; see the book.
6.5.5 The curse of dimensionality
The grid search of §6.3.3 shows the curse of dimensionality at work.
6.6 Software tools
There is no code for this section; see the book.
Exercises
- Fit D2 alone from the eight starting points. Which combination of \(K_M\) and \(K_I\) do all the fits agree on?
- Fit D1 and D2 together using the unweighted SSE (book, Eq. 6.2). How do the estimates change, and which data points now dominate the fit?
- Estimate the uncertainty of the parameters fitted to D1 and D2 together. Both least-squares solvers return the Jacobian \(J\) of the residuals at the solution; the covariance of the estimates is approximately \((J^\top J)^{-1}\). Compute the correlation between \(K_M\) and \(K_I\) (book, Eq. 6.11). Is it close to \(\pm 1\)? Repeat for D1 alone: what happens to \(J^\top J\)?
- Book Exercise 6.1: evaluate the SSE of the parameter sets \(\theta_1\), \(\theta_2\) and \(\theta_3\) given there. (The four data points are from the same experiment as D1; read the first column of the table as \(S\) and the second as \(v\).) Compute \(K_M(1 + I/K_I)\) for each set: what do you notice, and can any data at a single inhibitor concentration tell them apart?
- Run the evolutionary algorithm with ten different random seeds. How much do the final estimates vary? Then halve the number of generations, or start with a smaller mutation size, and repeat.
- In the time-course example, fix \(g_m = 1\)/h, as if the mRNA half-life had been measured separately, and fit the other three parameters to the protein data alone. Are they now identifiable?
- Regenerate the data with
tools/make_expression_data.pyusing different random seeds, and refit to both species each time. How much do the estimates vary from one data set to the next? Compare with the uncertainty estimated from \((J^\top J)^{-1}\) (Exercise 3).
Going further
For larger ODE models, with tens of parameters, each fit needs many simulations, and the questions of identifiability and of local versus global search become pressing. Profile likelihoods, which follow the best SSE as one parameter is varied and the others are refitted, are a practical way to see which parameters the data determine. Book §6.5.2 discusses a related idea, sloppiness: in many models, some combinations of parameters barely affect the fit.