Experiment design#

Before running an experiment you can ask whether it will determine the parameters you care about, and choose the design that determines them best. The tools work on the Fisher information of a design at assumed parameter values; no data are needed. Key ideas explains the Fisher information, the bound it puts on the parameters’ uncertainty and the criteria that score a design, and Worked example: designing an experiment uses them step by step. To choose sensors for a whole plant, see Identifiability of plant parameters (aquakin.plant.plant_rank_sensor_sets).

The experiment-design examples share the setup of Sensitivity analysis: the shipped ozone_bromate model in a batch reactor, with synthetic observations of ozone and bromate made from the default parameters plus 3 % noise. Run this block first; every block below then runs as written, in order.

import aquakin
import jax
import jax.numpy as jnp
import numpy as np

model = aquakin.load_model("ozone_bromate")
reactor = aquakin.BatchReactor(model, model.default_conditions())
C0 = model.default_concentrations()
params = model.default_parameters()
i = model.species_index                          # species name -> column

free_params = ["O3_Br_direct.k1", "O3_decay_OH.k_dec"]
i_free = jnp.array([model.param_index[n] for n in free_params])
observed = ["O3", "BrO3-"]

t_obs = jnp.linspace(30.0, 600.0, 12)            # seconds
truth = reactor.solve(C0, t_span=(0.0, 600.0), t_eval=t_obs, params=params)
clean = jnp.stack([truth.C_named(s) for s in observed], axis=1)   # (12, 2)
sigma = 0.03 * clean.max(axis=0)                 # one noise level per species
rng = np.random.default_rng(0)
observations = clean + sigma * rng.standard_normal(clean.shape)

result = aquakin.calibrate(      # a fit with its Laplace posterior, used below
    reactor, C0, observations, t_obs, free_params, observed_species=observed,
    loss="nll", sigma=sigma, optimizer=aquakin.OptimizerConfig(n_starts=4, seed=0))

Fisher information of a design#

aquakin.fisher_information evaluates the Fisher information of a set of experiments, each an aquakin.Experiment (initial state, sampling times, noise, what is measured, and optionally its own reactor for different operating conditions):

reactor_ph8 = aquakin.BatchReactor(
    model, aquakin.SpatialConditions.uniform(1, pH=8.0, OH_scavenging=5e4))
design = [
    aquakin.Experiment(C0, t_obs=t_obs, sigma=sigma, observed_species=observed),
    aquakin.Experiment(C0.at[i["Br-"]].set(2e-6), t_obs=t_obs, sigma=sigma,
                       observed_species=observed, reactor=reactor_ph8),
]
fim = aquakin.fisher_information(
    reactor, design, free_params, params=params,
    free_ic=aquakin.FreeICConfig(["Br-"]),   # also estimate a pool per experiment
)
fim.names        # ['O3_Br_direct.k1', 'O3_decay_OH.k_dec', 'ic[0].Br-', 'ic[1].Br-']
fim.matrix       # in the coordinates calibrate fits in (log for positive_log, pools)
fim.physical()   # with respect to the physical values
fim.std()        # Cramér-Rao lower bound on each standard deviation, physical units

The information of independent experiments adds, so an experiment that sharpens a poorly determined parameter shows up as a large drop in its std(). When some combination of the quantities cannot be determined from the design at all, the matrix is singular and fim.std() raises numpy.linalg.LinAlgError; aquakin.identifiability(fim) reports the same design without raising, with an infinite standard deviation for each quantity involved and the undetermined combination named (Identifiability report). At a calibration’s optimum, with loss="nll" and no prior, the matrix equals the fit’s Gauss-Newton Laplace Hessian (joint_hessian with include_ic=True).

Fisher information of any forward model#

aquakin.fisher_information_from_fn gives the Fisher information of a forward model that is not an aquakin reactor: any function fn(theta) -> y written in jax.numpy, such as a transport operator or a reactor wrapped in your own code. The Jacobian of the observations comes from AD (mode="auto" picks forward mode when there are more observations than parameters), and the result is a FisherInformation, so identifiability, design_criterion and std() work on it unchanged:

t_toy = jnp.linspace(0.5, 10.0, 12)

def decay(theta):
    k, a0 = theta
    return a0 * jnp.exp(-k * t_toy)

fim_toy = aquakin.fisher_information_from_fn(
    decay, jnp.array([0.25, 1.5]),
    names=["k", "A0"],
    sigma=0.05, noise="lognormal",           # observe log y; sigma ~ relative error
    transforms=["positive_log", "positive_log"],
)

sigma broadcasts to the shape of y, and inf marks an entry as unmeasured. With groups=, a label per observation (or per row), the information of each group is returned too. Each group is one candidate measurement, for example one sampling site, and the groups’ information sums to the total:

def decay_sites(theta):               # the same decay seen at three dilutions
    return jnp.stack([decay(theta) * d for d in (1.0, 0.5, 0.2)])   # (3, 12)

total, per_site = aquakin.fisher_information_from_fn(
    decay_sites, jnp.array([0.25, 1.5]), names=["k", "A0"], sigma=0.1,
    groups=["inlet", "zone A", "zone B"],
)
per_site["zone A"].matrix     # what sampling zone A alone contributes

If fn calls reactor.solve, pass mode="reverse": a reactor solve is differentiated in reverse mode.

Scoring and optimizing a design#

A design is scored by a criterion of its Fisher information: criterion="D" (the default), "A", "E" or "modified_E", the criteria of Scoring a design. D and E are better larger, A and modified E smaller. Pass subset=[...] to score only the information about some quantities, treating the others (for example nuisance initial pools) as unknown.

aquakin.design_criterion(fim, "D", subset=["O3_Br_direct.k1"])

# Choose the most useful next experiment from a list of candidates.
candidates = [
    aquakin.Experiment(C0, t_obs=t_obs, sigma=sigma[1], observed_species=["BrO3-"]),
    aquakin.Experiment(C0.at[i["O3"]].set(2e-4), t_obs=t_obs, sigma=sigma,
                       observed_species=observed),
]
ranked = aquakin.rank_experiments(reactor, candidates, free_params, base=design[:1])
ranked[0].index, ranked[0].improvement

# Or optimize the sampling times and initial concentrations directly.
res = aquakin.optimize_experiment(
    reactor,
    aquakin.Experiment(C0, t_obs=jnp.linspace(60.0, 360.0, 6), sigma=sigma,
                       observed_species=observed),
    free_params,
    time_bounds=(30.0, 600.0), min_spacing=20.0,   # in the experiment's time unit
    initial_bounds={"O3": (5e-5, 2e-4)},           # dose range to search, mol/L
)
res.experiments[0].t_obs, res.experiments[0].C0

optimize_experiment keeps the number of samples fixed and moves them within the bounds by gradient, keeping consecutive samples at least min_spacing apart.

To plan the next run given the runs already made, pass them as base=: their information is counted but their samples are not moved, so the new run is designed to add what they lack. Here the first run of design has been made and fitted (result), and the next one is planned at the fitted values:

next_run = aquakin.optimize_experiment(
    reactor,
    aquakin.Experiment(C0.at[i["O3"]].set(2e-4), t_obs=jnp.linspace(60.0, 360.0, 6),
                       sigma=sigma, observed_species=observed),
    free_params,
    base=design[:1],                 # the run already made
    params=result.params,            # its fitted values
    time_bounds=(30.0, 600.0), min_spacing=20.0,
)
next_run.experiments[0].t_obs        # the new run's samples only

To keep a design with the project, and rerun it when the model changes, make it a design study of the reactor (Designing a batch experiment).

The optimal design depends on the parameter values you assume, which are uncertain before the experiment. To make it a robust design, pass param_draws, an array of parameter vectors drawn from a prior or a previous calibration’s posterior, and the criterion is averaged over them. A calibration with its Laplace posterior (the default) provides the draws directly:

draws = result.posterior_draws(model, n_draw=20, seed=0)   # (20, 7)
robust = aquakin.optimize_experiment(reactor, design[0], free_params,
                                     param_draws=draws, time_bounds=(30.0, 600.0),
                                     min_spacing=20.0)

Draws from aquakin.sample_posterior (its draws) serve the same purpose when the Laplace posterior is a poor description (Sampling the posterior).

Choosing measurements from a candidate pool#

rank_experiments scores one candidate at a time. When you can afford several measurements from a fixed list (sampling sites, sampling times, species to analyze, experiments to run), aquakin.design_from_candidates chooses the best set under a budget. Each candidate carries its own Fisher information F_c, and the information of a design that takes candidate c n_c times is base + sum_c n_c F_c.

The per-candidate information comes most easily from fisher_information_from_fn with groups=. Here each candidate is one (time, species) sample of the ozonation batch, 30 in all, for three rate constants, and we can afford six:

names = ["O3_Br_direct.k1", "O3_decay_OH.k_dec", "O3_OBr_oxidation.k2"]
idx = jnp.array([model.param_index[n] for n in names])
t_cand = jnp.linspace(60.0, 600.0, 10)
species = ["O3", "HOBr", "BrO3-"]
cols = jnp.array([i[s] for s in species])

def samples_of(theta):
    sol = reactor.solve(C0, params=params.at[idx].set(theta),
                        t_span=(0.0, 600.0), t_eval=t_cand)
    return sol.C[:, cols]                    # (10 times, 3 species)

labels = [[f"{s} @ {float(t):.0f} s" for s in species] for t in t_cand]
_, pool = aquakin.fisher_information_from_fn(
    samples_of, params[idx], names=names,
    sigma=0.03 * samples_of(params[idx]).max(axis=0),
    transforms=["positive_log"] * 3, groups=labels, mode="reverse",
)
choice = aquakin.design_from_candidates(pool, budget=6)
choice.selected      # the six samples to take
choice.efficiency    # 0.9997 of the bound from the relaxed problem

The candidates can also be a stack of (p, p) matrices or a list of FisherInformation objects. The main options are:

  • budget= is the number of candidates to take or, with costs= (one per candidate), the total cost.

  • required=[...] lists candidates that must be in the design.

  • max_repeats= allows replicates (default 1; None for no cap).

  • base= is information already in hand, such as a prior or experiments already run.

  • criterion= and subset= work as for design_criterion. D on a subset (Ds-optimality) chooses for some parameters while treating the rest as nuisance.

  • param_draws_axis= names an axis of parameter draws in a stack of candidates, for a design robust to the assumed values; the criterion is averaged over the draws.

method= selects the search:

Method

What it does

"relaxed"

Solves the continuous problem (real weights that spend the budget), then rounds it. D and A only.

"greedy"

Adds the best affordable candidate one at a time.

"exchange"

Improves the greedy design by single swaps until none helps.

"auto" (default)

Scores every design when there are few enough (exhaustive_limit), otherwise runs the rounded relaxed and greedy designs through exchange and keeps the better.

For D and A the relaxed problem is concave, so its optimum is a bound that no integer design can beat. The result reports it as bound and the chosen design’s efficiency against it. For D with no base, no required candidates and no binding cap, equivalence is the pair (largest standardized variance, number of scored parameters), which are equal at the relaxed optimum (the equivalence check). gains shows how much one more of each candidate would add, which is useful when the budget grows.

A design with fewer informative candidates than parameters has singular information, so without a positive-definite base the search compares candidates with a tiny ridge added (regularized is then True; the reported criterion has no ridge). If the whole pool cannot determine the parameters, the function raises an error and asks for a base or a subset.

The forward model does not have to be an aquakin reactor. In this toy source localization problem, three sources on a line spread a tracer to 41 candidate sensor nodes, and we choose four sensors to estimate the third source’s strength, treating the other two as nuisance. Node 0 is always sampled:

nodes = jnp.linspace(0.0, 10.0, 41)
sources = jnp.array([2.0, 5.0, 8.0])

def conc(q):
    return jnp.exp(-jnp.abs(nodes[:, None] - sources[None, :]) / 1.5) @ q

_, sensors = aquakin.fisher_information_from_fn(
    conc, jnp.array([1.0, 2.0, 0.5]), names=["q1", "q2", "q3"], sigma=0.1,
    groups=[f"node {n}" for n in range(41)],
)
placement = aquakin.design_from_candidates(
    sensors, budget=4, subset=["q3"], required=["node 0"],
)

Telling two models apart#

The designs above sharpen the parameters of one model. When two model structures both fit the data in hand, such as two rate laws or a mechanism with and without an extra pathway (see Comparing model structures), the next experiment should rather be the one whose outcome tells them apart: it samples where the two models’ predictions differ by more than the measurement noise and the uncertainty of their fitted parameters can explain.

aquakin.optimize_discrimination designs that experiment, and aquakin.rank_discrimination scores candidate experiments for it. Each model is passed as a reactor with its calibration. For a design with predictions y1 and y2 of the observed quantities, each model at its fitted parameters, the default criterion, Buzzi-Ferraris (also called Box-Hill), is

\[T = (y_1 - y_2)^\top \left(2\Sigma + V_1 + V_2\right)^{-1} (y_1 - y_2)\]

where Σ is the diagonal measurement-noise covariance and Vi is the covariance of model i’s predictions under its Laplace posterior (its sensitivities to the fitted parameters times the fit’s posterior_cov). A gap where a model’s prediction is itself uncertain counts for less. criterion="hunter_reiner" leaves out V1 and V2 and weighs the gap by the noise alone, (y1 - y2)ᵀ (2Σ)⁻¹ (y1 - y2); it needs no posterior. Larger is better for both. A T-optimal criterion, which judges a design by how badly the wrong model would fit the data it produces, is planned as a further option.

Σ comes from the fits: each fit’s sigma_estimate, or the sigma it was fitted with, averaged as variances over the two fits. Pass sigma= to set it yourself, for example for a new measurement method. The two models must have the same species and their fits must observe the same quantities; each experiment measures what the fits observed, so its sigma is not used.

Here first-order and second-order decay of A are both fitted to early measurements of a first-order decay. Over the measured window the two curves agree to within the noise, so the data cannot choose between them:

# first_order.yaml
model: {name: first_order, version: "1.0", description: "A -> B, first order", references: []}
species:
  - {name: A, units: mol/L, default_concentration: 1.0}
  - {name: B, units: mol/L, default_concentration: 0.0}
conditions:
  - {name: T, default: 293.15}
reactions:
  - name: decay
    rate: "k * [A]"
    parameters: {k: {value: 0.1, units: "s-1"}}
    stoichiometry: {A: -1, B: +1}
# second_order.yaml
model: {name: second_order, version: "1.0", description: "A -> B, second order", references: []}
species:
  - {name: A, units: mol/L, default_concentration: 1.0}
  - {name: B, units: mol/L, default_concentration: 0.0}
conditions:
  - {name: T, default: 293.15}
reactions:
  - name: decay
    rate: "k * [A] * [A]"
    parameters: {k: {value: 0.1, units: "L/mol/s"}}
    stoichiometry: {A: -1, B: +1}
first = aquakin.load_model_from_file("first_order.yaml")
second = aquakin.load_model_from_file("second_order.yaml")
reactor1 = aquakin.BatchReactor(first, first.default_conditions())
reactor2 = aquakin.BatchReactor(second, second.default_conditions())

C0_ab = jnp.array([1.0, 0.0])
t_early = jnp.linspace(0.2, 2.0, 8)                   # seconds
a_obs = jnp.exp(-0.3 * t_early) + 0.01 * np.random.default_rng(1).standard_normal(8)
fit_kw = dict(observed_species=["A"], loss="nll", sigma=0.01)
fit1 = aquakin.calibrate(reactor1, C0_ab, a_obs, t_early, ["decay.k"], **fit_kw)
fit2 = aquakin.calibrate(reactor2, C0_ab, a_obs, t_early, ["decay.k"], **fit_kw)

discriminating = aquakin.optimize_discrimination(
    (reactor1, fit1), (reactor2, fit2),
    aquakin.Experiment(C0_ab, t_obs=jnp.array([1.0, 1.5, 2.0]), sigma=0.01),
    design=aquakin.DesignConfig(time_bounds=(0.1, 30.0), min_spacing=0.5),
)
discriminating.experiments[0].t_obs    # all three samples move past 5 s

The samples move to late times, where first-order decay has run further than second-order decay. DesignConfig holds the controls optimize_experiment takes as keywords: optimize_times, time_bounds, min_spacing, initial_bounds (to search the initial concentrations too), max_iter and tol. To choose between experiments you could run, rank them instead:

choices = [aquakin.Experiment(C0_ab, t_obs=t, sigma=0.01)
           for t in (jnp.array([0.5, 1.0, 1.5]), jnp.array([6.0, 9.0, 12.0]))]
ranked = aquakin.rank_discrimination((reactor1, fit1), (reactor2, fit2), choices)
ranked[0].index      # 1: the late samples