Worked example: designing an experiment#

Before fitting a kinetic model to data, it is worth asking two questions:

  1. Can the data determine the parameters at all? A model can fit a data set well while some of its parameters are almost arbitrary, because changing one can be compensated by changing another.

  2. Which experiment would determine them best? Sampling times, doses, and the choice of what to measure all change how much a run can tell us.

This page answers both for a small ozone-demand model, step by step. It starts from a first design that can determine only one of the four unknowns and ends with a calibrated model whose uncertainties are checked against the truth.

All the code on this page comes from the script examples/ozone_demand_design.py, and every output block is what that script prints. Each code block continues from the previous one, so the page can be followed as one program. The script takes a few minutes to run.

The model#

Ozone dosed into a water sample is consumed in two ways. A small amount of fast-reacting material D (the “instantaneous ozone demand”) is used up within seconds. Organic matter M reacts slowly and is present in large excess over ozone.

Reaction

Rate

True value

O₃ + D → products

k₁ [O₃][D]

k₁ = 0.01 L µmol⁻¹ s⁻¹

O₃ + M → products

k₂ [O₃][M]

k₂ = 2×10⁻⁶ L µmol⁻¹ s⁻¹

The model file is examples/ozone_demand.yaml. Concentrations are in µmol/L and time in seconds. The ozone dose is chosen by the experimenter (50 µmol/L to start with). There are four unknowns: the two rate constants and the initial concentrations of D and M, [D]₀ = 15 µmol/L and [M]₀ = 1000 µmol/L. These initial concentrations are not measured directly, so they are estimated along with the rate constants. The page calls them the initial pools.

Two quantities can be measured:

  • Dissolved ozone, with a standard deviation of 1 µmol/L.

  • UV254, the UV absorbance at 254 nm per centimetre of path length. Absorbance is proportional to concentration, so the example takes A₂₅₄ = ε[M] with a known specific absorbance ε = 2×10⁻⁴ cm⁻¹ per µmol/L, and a standard deviation of 0.001 cm⁻¹.

The data on this page are synthetic, generated from the true values above, so every result can be checked against the truth.

The script starts with its imports. aquakin is imported before JAX because importing it switches JAX to 64-bit floating point, which the stiff solves need; imported after JAX, it still does so but warns that it is overriding JAX’s default.

from pathlib import Path

# aquakin first: it enables JAX's 64-bit mode, which it needs, before JAX loads.
import aquakin

# isort: split
import jax.numpy as jnp
import numpy as np

UV254 is not a single species, so it is passed to aquakin as an observation function, a function that maps the concentration vector at one time, and the parameter vector, to the measured values. aquakin always calls it with those two arguments, f(C, p). Anything else it needs is bound in when it is created, here by a small factory that takes the model and ε:

def make_ozone_and_uv(model, eps):
    """Build the observation function for ozone and UV254.

    aquakin calls an observation function as ``f(C, p)``: the concentration
    vector at one time and the parameter vector. Everything else it needs
    (where ozone and M sit in ``C``, and the specific absorbance ``eps``) is
    bound here, so the returned function has no hidden inputs.
    """
    i_o3, i_m = model.species_index["O3"], model.species_index["M"]

    def ozone_and_uv(C, p):
        """Dissolved ozone (umol/L) and UV254 absorbance (1/cm) at one time."""
        return jnp.stack([C[i_o3], eps * C[i_m]])

    return ozone_and_uv


The setup code loads the model and defines the true composition, the unknowns, and the measurements:

# The model file sits next to this script.
model = aquakin.load_model_from_file(Path(__file__).parent / "ozone_demand.yaml")
settings = aquakin.SolverSettings(rtol=1e-8, atol=1e-8)
reactor = aquakin.BatchReactor(model, model.default_conditions(), settings=settings)

# The true composition of the sample, in umol/L, with a 50 umol/L ozone
# dose. The synthetic data in step 4 are generated from these values.
C0 = model.concentrations({"O3": 50.0, "D": 15.0, "M": 1000.0})
true_params = model.default_parameters()  # k1 = 0.01, k2 = 2e-6 L/umol/s

# The four unknowns: two rate constants and the two initial pools.
free_params = ["fast.k1", "slow.k2"]
free_ic = aquakin.FreeICConfig(["D", "M"], bounds=(1e-2, 1e5))

# Measurements. Ozone has a standard deviation of 1 umol/L. UV254 is the
# absorbance at 254 nm per cm of path; it is proportional to the organic
# matter, A254 = eps * [M], with eps assumed known.
sigma_o3 = 1.0  # umol/L
sigma_uv = 0.001  # 1/cm
eps = 2.0e-4  # 1/cm per umol/L
ozone_and_uv = make_ozone_and_uv(model, eps)
sigma_both = jnp.asarray([sigma_o3, sigma_uv])  # one per output of ozone_and_uv

def percent(x):
    """A relative standard deviation as text; inf means not identifiable."""
    if not np.isfinite(x):
        return "inf"
    return f"{100 * x:.0f}%" if x >= 1.0 else f"{100 * x:.2g}%"

def round_off(x):
    """A relative eigenvalue, with round-off (|x| < 1e-12) shown as 0."""
    return 0.0 if abs(x) < 1e-12 else x

Rate constants declared with transform: positive_log in the model file, and the initial pools, are analyzed on a log scale, so their standard deviations read as relative ones.

The steps below use the Fisher information, the Cramér-Rao bound, the eigen-directions of the information and the criteria that score a design. Key ideas: information, uncertainty and identifiability explains each of them; read it first if they are new to you.

Step 1: diagnose a simple design#

A natural first experiment doses 50 µmol/L of ozone and measures it five times between 60 and 600 s. Its Fisher information and identifiability report are:

# A run is the initial state, the sampling times (s), the measurement
# standard deviation, and what is measured.
base = aquakin.Experiment(
    C0, jnp.linspace(60.0, 600.0, 5), sigma=sigma_o3, observed_species=["O3"]
)
fim = aquakin.fisher_information(
    reactor, base, free_params, params=true_params, free_ic=free_ic
)
rep = aquakin.identifiability(fim)

print("Eigenvalues relative to the largest:")
for d in rep.directions:
    print(f"  {round_off(d.relative_eigenvalue):9.1e}  identifiable: {d.identifiable}")
print("Directions flagged as not identifiable (two largest loadings):")
for d in rep.unidentifiable:
    top = ", ".join(f"{n} {v:+.2f}" for n, v in list(d.loadings.items())[:2])
    print(f"  relative eigenvalue {round_off(d.relative_eigenvalue):8.1e}: {top}")
print("Relative standard deviations:")
for name, value in rep.relative_std.items():
    print(f"  {name:8s} {percent(value):>8s}")
Eigenvalues relative to the largest:
    0.0e+00  identifiable: False
    7.8e-07  identifiable: False
    8.8e-02  identifiable: True
    1.0e+00  identifiable: True
Directions flagged as not identifiable (two largest loadings):
  relative eigenvalue  0.0e+00: fast.k1 +1.00, ic[0].D +0.00
  relative eigenvalue  7.8e-07: slow.k2 -0.71, ic[0].M +0.70
Relative standard deviations:
  fast.k1       inf
  slow.k2     2142%
  ic[0].D       13%
  ic[0].M     2112%

In the output, ic[0].D and ic[0].M are the initial pools [D]₀ and [M]₀ of experiment 0, the only experiment here. Two of the four eigenvalues are far below the others, so two combinations of the unknowns are flagged. The loadings say which, and the standard deviations show that they are different kinds of problem:

  • k₁ on its own (structural). Its eigenvalue is zero (the script prints round-off below 10⁻¹² as 0), and its standard deviation is infinite. D is used up within about 20 s, before the first sample. The samples show how much ozone D removed, which is [D]₀, but not how fast it did so.

  • log k₂ − log [M]₀ (practical). The loadings are equal and opposite, so the data determine mainly the product k₂[M]₀. M is in such excess that it is barely consumed (about 3 % over 30 minutes), so ozone decays at almost the apparent first-order rate k₂[M]₀. Doubling k₂ and halving [M]₀ gives nearly the same ozone curve. The small consumption of M separates them in principle, which is why the eigenvalue is not exactly zero, but only to a relative standard deviation of about 2000 %.

Fitting data from this design would return some values of k₁, k₂, and [M]₀, and the fit could look good, but those values would mean almost nothing. Only [D]₀ is reasonably determined. The Fisher information shows this before any experiment is run.

Step 2: compare ways to improve the run#

A change to the design helps only if it adds information along the undetermined directions, that is, if the new measurements are sensitive to those combinations. The script compares four changes to the same run:

t_base = np.linspace(60.0, 600.0, 5)  # s
early = np.linspace(2.0, 20.0, 5)  # s
late = np.linspace(700.0, 1800.0, 5)  # s
designs = {
    "base": aquakin.Experiment(C0, t_base, sigma=sigma_o3, observed_species=["O3"]),
    "+ late samples": aquakin.Experiment(
        C0, np.r_[t_base, late], sigma=sigma_o3, observed_species=["O3"]
    ),
    "+ early samples": aquakin.Experiment(
        C0, np.r_[early, t_base], sigma=sigma_o3, observed_species=["O3"]
    ),
    "+ UV254": aquakin.Experiment(C0, t_base, sigma=sigma_both, observation_fn=ozone_and_uv),
    "+ early samples + UV254": aquakin.Experiment(
        C0, np.r_[early, t_base], sigma=sigma_both, observation_fn=ozone_and_uv
    ),
}

print(f"{'design':24s}" + "".join(f"{n:>10s}" for n in rep.names))
comparison = {}
for label, run in designs.items():
    fim = aquakin.fisher_information(
        reactor, run, free_params, params=true_params, free_ic=free_ic
    )
    rel = aquakin.identifiability(fim).relative_std
    comparison[label] = rel
    print(f"{label:24s}" + "".join(f"{percent(rel[n]):>10s}" for n in rep.names))

# The same designs ranked by the D-criterion (log det F, larger is better;
# -inf means the information matrix is singular).
ranked = aquakin.rank_experiments(
    reactor, list(designs.values()), free_params, params=true_params, free_ic=free_ic
)
labels = list(designs)
ranking = {labels[c.index]: c.value for c in ranked}
print("Ranked by the D-criterion:")
for label, value in ranking.items():
    print(f"  {label:24s} D = {value:7.2f}")

The table shows the relative standard deviation of each unknown (the Cramér-Rao bound, as a percentage):

design                     fast.k1   slow.k2   ic[0].D   ic[0].M
base                           inf     2142%       13%     2112%
+ late samples                 inf      963%       11%      945%
+ early samples                21%     1545%      4.6%     1526%
+ UV254                        inf      6.6%      7.9%     0.25%
+ early samples + UV254        20%        5%      3.7%     0.16%
Ranked by the D-criterion:
  + early samples + UV254  D =   29.33
  + early samples          D =   10.92
  base                     D =    -inf
  + late samples           D =    -inf
  + UV254                  D =    -inf
  • More late samples help very little. Every ozone sample after D is gone is sensitive almost only to the product k₂[M]₀, so their sensitivities nearly all point the same way. Five more of them, extending the run to 30 minutes, let a little more M be consumed. That halves the uncertainty of k₂ and [M]₀, but it is still far above 100 %, and k₁ stays undetermined.

  • Early samples (2–20 s) catch D being consumed, which determines k₁ and improves [D]₀. They barely help k₂ and [M]₀.

  • UV254 measures M directly. Its sensitivities point along [M]₀, a direction the ozone samples hardly reach, so it determines [M]₀ and, through the product k₂[M]₀, also k₂. It leaves k₁ unknown.

  • Both together make all four unknowns identifiable.

The last lines rank the same designs with aquakin.rank_experiments, which scores each one by the D-criterion (Scoring a design, larger is better). This is the quicker tool when there are many candidates. Early samples plus UV254 come first. The three designs that leave k₁ structurally undetermined all score −∞, however well they determine the other unknowns. The D-criterion cannot order such designs among themselves, so compare them by their standard deviations instead.

The general lesson is that more data of the same kind rarely fixes an identifiability problem (Combining measurements and experiments). A different measurement, or samples in a different time window, does.

Step 3: optimize the sampling times and dose#

Once every unknown is identifiable, the design can be improved further by moving the samples and changing the dose. aquakin.optimize_experiment maximizes a design criterion (D by default) over the design. It differentiates the criterion with respect to the sampling times and the initial concentrations, and moves them with a gradient-based optimizer, within bounds and keeping consecutive samples at least min_spacing apart. The number of samples stays fixed. Here the run measures ozone and UV254 at eight times, starting from evenly spaced samples between 5 and 900 s:

# Start from 8 evenly spaced samples of ozone and UV254.
start = aquakin.Experiment(
    C0, jnp.linspace(5.0, 900.0, 8), sigma=sigma_both, observation_fn=ozone_and_uv
)
opt = aquakin.optimize_experiment(
    reactor,
    start,
    free_params,
    params=true_params,
    free_ic=free_ic,
    criterion="D",
    time_bounds=(1.0, 1800.0),  # s
    min_spacing=5.0,  # s between consecutive samples
    initial_bounds={"O3": (20.0, 150.0)},  # dose range, umol/L
)
designed = opt.experiments[0]
print(f"converged: {opt.success}")
print(f"D-criterion: {opt.initial_value:.2f} -> {opt.value:.2f}")
print(f"sampling times (s): {np.round(np.asarray(designed.t_obs), 1).tolist()}")
print(f"ozone dose: {float(designed.C0[model.species_index['O3']]):.0f} umol/L")

rel_start = aquakin.identifiability(
    aquakin.fisher_information(reactor, start, free_params, params=true_params, free_ic=free_ic)
).relative_std
rel_designed = aquakin.identifiability(
    aquakin.fisher_information(
        reactor, designed, free_params, params=true_params, free_ic=free_ic
    )
).relative_std
print(f"{'':10s}{'start':>10s}{'designed':>10s}")
for n in rep.names:
    print(f"{n:10s}{percent(rel_start[n]):>10s}{percent(rel_designed[n]):>10s}")
converged: True
D-criterion: 26.67 -> 31.32
sampling times (s): [1.0, 6.0, 11.0, 517.0, 522.0, 527.0, 532.0, 537.0]
ozone dose: 150 umol/L
               start  designed
fast.k1          43%       23%
slow.k2         5.9%      1.1%
ic[0].D         9.6%      4.8%
ic[0].M        0.22%     0.18%
Ozone and UV254 curves with the base and designed sampling times.

True ozone and UV254 curves at the starting dose (solid) and the designed dose (dashed). Ticks mark the sampling times of the base design from step 1 (blue, bottom) and of the designed run (red, top).#

The D-criterion rises by 4.65. So det F grows by a factor of \(e^{4.65} \approx 100\), and the volume of the joint confidence region shrinks by a factor of \(e^{4.65/2} \approx 10\). The designed run roughly halves the uncertainty of k₁ and [D]₀ and reduces that of k₂ by a factor of five. Two features of the result are typical of D-optimal designs:

  • Samples cluster. Rather than spreading out, the samples sit where the measurements are most sensitive to the unknowns. The early cluster resolves the fast demand, and the cluster near 520 s is where ozone is most sensitive to k₂. Only the minimum spacing keeps them apart. Because the design trusts the model completely, in practice it is wise to add a few samples between the clusters, or a validation run, to check the model there.

  • The dose goes to its limit. A larger dose consumes more organic matter, so UV254 changes more and the slow phase lasts longer. The upper bound should reflect what is practical in the laboratory.

Step 4: calibrate and check the uncertainty#

To check the design, the script simulates noisy measurements of the designed run from the true values, then fits the model to them as if the truth were unknown.

# Synthetic measurements: solve with the true values, measure, add noise.
t_obs = jnp.asarray(designed.t_obs)
C0_designed = jnp.asarray(designed.C0)
sol = reactor.solve(
    C0_designed, t_span=(0.0, float(t_obs[-1])), t_eval=t_obs, params=true_params
)
clean = np.asarray(jnp.stack([ozone_and_uv(c, true_params) for c in sol.C]))
rng = np.random.default_rng(0)
data = clean + rng.standard_normal(clean.shape) * np.asarray(sigma_both)

Fitting and the Laplace approximation#

The fit minimizes the negative log-likelihood (loss="nll") and reports the uncertainty of its estimates by the Laplace approximation. With method="gauss_newton" the curvature it inverts is the Fisher information at the fitted values, so the uncertainty after the fit can be compared directly with the prediction made before the experiment.

# Start the fit away from the truth: the rate constants a factor of 2-3
# off and the pools at round guesses.
guess = true_params.at[model.param_index["fast.k1"]].set(0.003)
guess = guess.at[model.param_index["slow.k2"]].set(5.0e-6)
C0_guess = C0_designed.at[model.species_index["D"]].set(5.0)
C0_guess = C0_guess.at[model.species_index["M"]].set(500.0)

result = aquakin.calibrate(
    reactor,
    C0_guess,
    data,
    t_obs,
    free_params,
    initial_params=guess,
    observation_fn=ozone_and_uv,
    loss="nll",
    sigma=sigma_both,
    free_ic=free_ic,
    laplace=aquakin.LaplaceConfig(method="gauss_newton", include_ic=True),
    # Keep each rate constant within a factor of 100 of its starting
    # guess, so the optimizer cannot step into regions where the solve fails.
    optimizer=aquakin.OptimizerConfig(
        method="gauss_newton", n_starts=4, param_halfwidth=np.log(100.0)
    ),
)
truth = {"fast.k1": 0.01, "slow.k2": 2.0e-6, "D": 15.0, "M": 1000.0}
print(f"converged: {result.converged}")
print(f"{'':10s}{'estimate':>12s}{'std dev':>12s}{'relative':>10s}{'true':>12s}")
for n in free_params:
    est, sd = result.params_named[n], result.params_named_std[n]
    print(f"{n:10s}{est:12.4g}{sd:12.2g}{percent(sd / est):>10s}{truth[n]:12.4g}")
for s in ["D", "M"]:
    est, sd = result.ic_named[0][s], result.ic_named_std[0][s]
    name = f"ic[0].{s}"
    print(f"{name:10s}{est:12.4g}{sd:12.2g}{percent(sd / est):>10s}{truth[s]:12.4g}")
converged: True
              estimate     std dev  relative        true
fast.k1       0.009944      0.0023       23%        0.01
slow.k2      2.033e-06     2.2e-08      1.1%       2e-06
ic[0].D          14.86        0.72      4.8%          15
ic[0].M           1000         1.8     0.18%        1000

The fit starts a factor of 2–3 away from the true rate constants and still recovers every unknown within its uncertainty of the true value. The relative standard deviations match those predicted for the designed run in step 3.

Three settings in the call matter:

  • param_halfwidth=np.log(100.0) keeps each rate constant within a factor of 100 of its starting guess (the bound is on the log scale). Without it, an early optimizer step can jump by many orders of magnitude. The model is stiff, because it combines a very fast reaction (D) with a very slow one (M), and an extreme value of k₁ makes it so stiff that the solve fails. Bounds a factor of 100 either side of a reasonable guess rarely constrain the answer but make the fit much more reliable.

  • n_starts=4 runs the fit from the initial guess and from three randomly perturbed copies of it, and keeps the best. This guards against stopping in a local minimum. A start whose solve fails is skipped.

  • include_ic=True makes the uncertainty cover the initial pools as well as the rate constants. The rate uncertainties then allow for the trade-off between each rate and its pool. Without it, the pools would be treated as known and the rate uncertainties would be too small.

Checking with a profile likelihood#

The Laplace approximation assumes the objective is quadratic near its minimum. A profile likelihood checks this without that assumption, by refitting the other unknowns at each of a series of fixed values of k₂. Its 95 % interval is where the profile rises less than 1.92 above its minimum.

k2_hat = result.params_named["slow.k2"]
profile = aquakin.profile_likelihood(
    reactor,
    result.C0_fitted[0],
    data,
    t_obs,
    free_params,
    grid=jnp.asarray(k2_hat * np.exp(np.linspace(-0.05, 0.05, 11))),
    profile_param="slow.k2",
    initial_params=result.params,
    observation_fn=ozone_and_uv,
    loss="nll",
    sigma=sigma_both,
    free_ic=free_ic,
    optimizer=aquakin.OptimizerConfig(method="gauss_newton", param_halfwidth=np.log(100.0)),
)
lo, hi = profile.ci
sd = result.params_named_std["slow.k2"]
print("Profile likelihood:")
print(f"profile-likelihood 95% interval for k2: {lo:.4g} to {hi:.4g}")
print(
    f"Laplace 95% interval for k2:            {k2_hat - 1.96 * sd:.4g} to "
    f"{k2_hat + 1.96 * sd:.4g}"
)
profile-likelihood 95% interval for k2: 1.992e-06 to 2.076e-06
Laplace 95% interval for k2:            1.991e-06 to 2.076e-06
Profile likelihood of k2 with the Laplace interval and the true value.

Profile likelihood of k₂. The dashed line is the 95 % threshold, the shaded band is the Laplace 95 % interval and the vertical line is the true value.#

The profile is close to a parabola, and the two intervals agree and contain the true value, so the Laplace uncertainty can be trusted here. The minimum is not at the true value because the fit sees one noisy data set. Its estimate, 2.033×10⁻⁶, is 1.5 standard deviations from the truth, an ordinary miss. A different draw of the noise would move the minimum but leave the width of the profile almost unchanged.

Step 5: design the next run#

The design in step 3 was optimized for the true parameter values, which are never known in practice. A design depends on the values it is computed for. The best sampling times for a fast reaction differ from those for a slow one. A practical sequence is to run a first experiment, fit it, and design the next run for the values the data now support.

Since those values are still uncertain, the second design should work well across their plausible range, not just at the best estimate: a robust design. Passing param_draws, parameter vectors drawn from the calibration’s posterior, makes optimize_experiment maximize the criterion averaged over them. The script uses ten draws and the default D-criterion.

draws = result.posterior_draws(model, n_draw=10, seed=1)  # (10, n_params)
robust = aquakin.optimize_experiment(
    reactor,
    start,  # the same 8 evenly spaced samples as in step 3
    free_params,
    param_draws=draws,
    free_ic=free_ic,
    time_bounds=(1.0, 1800.0),
    min_spacing=5.0,
    initial_bounds={"O3": (20.0, 150.0)},
)
second = robust.experiments[0]
print(f"sampling times (s): {np.round(np.asarray(second.t_obs), 1).tolist()}")
print(f"ozone dose: {float(second.C0[model.species_index['O3']]):.0f} umol/L")
sampling times (s): [1.0, 6.1, 11.1, 508.5, 513.5, 518.5, 523.5, 528.5]
ozone dose: 150 umol/L

The robust design is almost the same as the one in step 3, as expected when the parameters are already well determined. When the first-round estimates are uncertain, averaging over the posterior keeps the second round from being designed around the wrong values.

Summary#

  • Compute the Fisher information of a planned design before running it. identifiability names the parameter combinations it cannot determine. Equal and opposite loadings in log coordinates point to a product.

  • More samples of the same quantity rarely fix an identifiability problem. Here 30 minutes of ozone samples still leave k₂ and [M]₀ uncertain by about 1000 %, and k₁ undetermined. A different measurement, or samples in a different time window, does.

  • Use rank_experiments to compare discrete options and optimize_experiment for sampling times and doses. D-optimal designs cluster samples, so add a few in between to check the model.

  • After calibrating, compare the estimated uncertainties with the design-stage predictions, and confirm key parameters with a profile likelihood.

  • Design the next experiment from the fitted values, averaged over their uncertainty.