Exercise: identifiability and uncertainty of fitted parameters
Goal
By the end of this exercise you should be able to:
- recognise structural non-identifiability (parameters that only appear as a product; the \(k_a/k_e\) flip-flop) from the model equations and from the Jacobian,
- compute standard errors and the correlation matrix of fitted parameters from \(s^2(J^TJ)^{-1}\), and check them against the Hessian of the sum of squares,
- read the badly determined parameter combinations off the SVD of the Jacobian (in log-parameters),
- compute a profile likelihood by re-fitting with one parameter fixed, and spot a flat profile that the standard error hides,
- recognise a sloppy model from the spread of the eigenvalues of \(J^TJ\),
- compare sampling designs before an experiment, and add a prior as an extra residual.
The running example is the pharmacokinetic model and the simulated plasma concentrations of Nonlinear least squares and ODE fitting: one oral dose of 100 mg, true \(k_a = 1\) /h, \(k_e = 0.2\) /h, \(V = 20\) L, noise SD 0.1 mg/L. The code uses that unit’s names: bateman(t, ka, ke, V) with the dose D, the sample times tt and the concentrations y. The by-hand part uses pen, paper and a calculator.
Background
The one-compartment model with first-order absorption from the gut (rate \(k_a\)), first-order elimination (rate \(k_e\)), volume \(V\), dose \(D\) and bioavailability \(F\):
\[C(t) = \frac{F\,D\,k_a}{V\,(k_a - k_e)}\left(e^{-k_e t} - e^{-k_a t}\right)\]
Facts used below:
- Identifiable means: different parameter values give different model outputs. Structural non-identifiability is a property of the model (no data can fix it); practical non-identifiability is a property of the data (too few, too noisy, badly placed samples).
- Jacobian. \(J_{ij} = \partial C(t_i)/\partial\theta_j\) (\(n\) samples × \(p\) parameters). In log-parameters, \(\partial C/\partial\log\theta_j = \theta_j\,\partial C/\partial\theta_j\): multiply column \(j\) by \(\theta_j\). An exact linear dependence between columns (a zero singular value) is structural non-identifiability.
- Hessian. For \(S(\theta) = \sum_i r_i^2\) with \(r_i = y_i - C(t_i)\): \(H = 2J^TJ - 2\sum_i r_i\nabla^2C(t_i) \approx 2J^TJ\) (Gauss–Newton).
- Covariance. With independent noise of variance \(\sigma^2\): \(\operatorname{Cov}(\hat\theta) \approx \sigma^2(J^TJ)^{-1} = 2\sigma^2 H^{-1}\), with \(\sigma^2\) estimated by \(s^2 = S(\hat\theta)/(n-p)\) if not known. Standard errors are the square roots of the diagonal; the correlation is \(r_{jk} = \operatorname{Cov}_{jk}/(\mathrm{SE}_j\,\mathrm{SE}_k)\). The Fisher information is \(\mathcal I = J^TJ/\sigma^2\).
- SVD of \(J\). With \(J = U\Sigma V^T\), the uncertainty along the right singular vector \(v_i\) is \(\sigma/\sigma_i\): small singular values are badly determined directions. The eigenvalues of \(J^TJ\) are \(\sigma_i^2\).
- Profile likelihood. \(\text{PL}(\theta_j) = \min\) of \(S\) over all other parameters, with \(\theta_j\) fixed. A 95 % interval is where \((\text{PL}(\theta_j) - S(\hat\theta))/s^2 \le 3.84\) (\(= 1.96^2\), the 95 % point of \(\chi^2_1\)). For a linear model this equals the Wald interval \(\hat\theta_j \pm 1.96\,\mathrm{SE}_j\).
- Prediction uncertainty (delta method): for any derived quantity \(g(\theta)\), \(\operatorname{Var}g(\hat\theta) \approx \nabla g^T\operatorname{Cov}(\hat\theta)\nabla g\).
- A prior \(\log\theta_j \sim N(\mu, \tau^2)\) adds the residual \((\log\theta_j - \mu)/\tau\) to the data residuals \(r_i/\sigma\). This is ridge regularisation, and the maximum a posteriori estimate.
The data, the fit, standard errors and correlations in each language. The R and Python solutions below continue from this block (run it first); each Rust solution is a complete program with the same helper functions. Python has no nls/vcov: scipy.optimize.least_squares returns the Jacobian res.jac at the solution, and the covariance is \(s^2(J^TJ)^{-1}\). Rust: the Levenberg–Marquardt fit is hand-written on top of nalgebra.
library(numDeriv)
D <- 100 # oral dose, mg
bateman <- function(t, ka, ke, V) D * ka / (V * (ka - ke)) * (exp(-ke * t) - exp(-ka * t))
tt <- c(0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 6, 8, 10, 12) # hours
y <- c(1.02, 1.88, 2.34, 2.98, 3.27, 3.26, 3.17, 2.77, 1.92, 1.23, 1.00, 0.61) # mg/L
late <- tt >= 3 # sparse design
fit <- nls(y ~ bateman(tt, ka, ke, V), start = list(ka = 0.5, ke = 0.1, V = 10))
summary(fit)$coefficients[, 1:2] # estimates and standard errors
# Estimate Std. Error
# ka 1.0150721 0.06243155
# ke 0.1906157 0.01040041
# V 20.2162113 0.71647070
round(cov2cor(vcov(fit)), 2) # correlation matrix of the estimates
# ka ke V
# ka 1.00 -0.82 0.90
# ke -0.82 1.00 -0.91
# V 0.90 -0.91 1.00import numpy as np
from scipy.optimize import least_squares
D = 100.0 # oral dose, mg
tt = np.array([0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 6, 8, 10, 12]) # hours
y = np.array([1.02, 1.88, 2.34, 2.98, 3.27, 3.26, 3.17, 2.77, 1.92, 1.23, 1.00, 0.61]) # mg/L
late = tt >= 3 # sparse design
def bateman(t, ka, ke, V):
return D * ka / (V * (ka - ke)) * (np.exp(-ke * t) - np.exp(-ka * t))
def jacobian(f, p, h=1e-5):
"""Central-difference Jacobian of a vector function f at p (step relative to |p|)."""
p = np.asarray(p, float)
cols = []
for j in range(len(p)):
e = np.zeros_like(p); e[j] = h * max(abs(p[j]), 1.0)
cols.append((f(p + e) - f(p - e)) / (2 * e[j]))
return np.column_stack(cols)
def fit_pk(ts, ys, start):
res = least_squares(lambda p: ys - bateman(ts, *p), start, xtol=1e-12, ftol=1e-12, gtol=1e-12)
return res.x, np.sum(res.fun**2), res
th, S, res = fit_pk(tt, y, [0.5, 0.1, 10])
s2 = S / (len(y) - 3) # residual variance s^2
cov = s2 * np.linalg.inv(res.jac.T @ res.jac)
se = np.sqrt(np.diag(cov))
for name, est, s in zip(["ka", "ke", "V"], th, se):
print(f"{name:2s} {est:10.7f} {s:10.8f}") # estimates and standard errors
# ka 1.0150722 0.06243155
# ke 0.1906157 0.01040041
# V 20.2162105 0.71647068
print(np.round(cov / np.outer(se, se), 2)) # correlation matrix of the estimates
# [[ 1. -0.82 0.9 ]
# [-0.82 1. -0.91]
# [ 0.9 -0.91 1. ]]// rust/examples/identifiability_background.rs — cargo run --example identifiability_background
// Fit the PK model, standard errors and correlations (nalgebra, hand-written LM).
#![allow(dead_code)]
use nalgebra::{DMatrix, DVector};
// One-compartment model with oral absorption, dose D = 100 mg (mg/L)
const D: f64 = 100.0; // oral dose, mg
fn bateman(t: f64, ka: f64, ke: f64, v: f64) -> f64 {
D * ka / (v * (ka - ke)) * ((-ke * t).exp() - (-ka * t).exp())
}
const TT: [f64; 12] = [0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 10.0, 12.0];
const Y: [f64; 12] = [1.02, 1.88, 2.34, 2.98, 3.27, 3.26, 3.17, 2.77, 1.92, 1.23, 1.00, 0.61];
// Central-difference Jacobian of f at p (like numDeriv::jacobian, less refined)
fn jacobian(f: &dyn Fn(&[f64]) -> Vec<f64>, p: &[f64]) -> DMatrix<f64> {
let n = f(p).len();
let mut j = DMatrix::zeros(n, p.len());
for k in 0..p.len() {
let h = 1e-5 * p[k].abs().max(1.0);
let (mut pp, mut pm) = (p.to_vec(), p.to_vec());
pp[k] += h;
pm[k] -= h;
let (fp, fm) = (f(&pp), f(&pm));
for i in 0..n { j[(i, k)] = (fp[i] - fm[i]) / (2.0 * h); }
}
j
}
// Levenberg-Marquardt for min sum r(p)^2, hand-written (R: nls / nls.lm, Python: least_squares)
fn levmar(r: &dyn Fn(&[f64]) -> Vec<f64>, p0: &[f64]) -> Vec<f64> {
let ss = |p: &[f64]| -> f64 { let v = r(p); if v.iter().all(|x| x.is_finite()) { v.iter().map(|x| x * x).sum() } else { f64::INFINITY } };
let (mut p, mut mu) = (p0.to_vec(), 1e-3);
for _ in 0..500 {
let j = jacobian(r, &p); // Jacobian of the residuals
let rv = DVector::from_vec(r(&p));
let jtj = j.transpose() * &j;
let g = j.transpose() * &rv;
loop {
let a = &jtj + DMatrix::from_diagonal(&jtj.diagonal()) * mu;
let step = a.lu().solve(&(-&g)).unwrap();
let pn: Vec<f64> = p.iter().zip(step.iter()).map(|(a, b)| a + b).collect();
if ss(&pn) <= ss(&p) {
let small = step.norm() < 1e-12 * (1.0 + DVector::from_vec(p.clone()).norm());
p = pn;
mu = (mu / 10.0).max(1e-12);
if small { return p; }
break;
}
mu *= 10.0;
if mu > 1e12 { return p; }
}
}
p
}
// Residuals y - C(t) for the one-compartment model at the sample times ts
fn resid(ts: &[f64], ys: &[f64]) -> impl Fn(&[f64]) -> Vec<f64> {
let (ts, ys) = (ts.to_vec(), ys.to_vec());
move |p: &[f64]| ts.iter().zip(&ys).map(|(ti, yi)| yi - bateman(*ti, p[0], p[1], p[2])).collect()
}
fn sse(r: &dyn Fn(&[f64]) -> Vec<f64>, p: &[f64]) -> f64 { r(p).iter().map(|x| x * x).sum() }
fn main() {
let r = resid(&TT, &Y);
let th = levmar(&r, &[0.5, 0.1, 10.0]);
let s2 = sse(&r, &th) / (TT.len() - 3) as f64; // residual variance s^2
let j = jacobian(&r, &th);
let cov = (j.transpose() * &j).try_inverse().unwrap() * s2;
let se: Vec<f64> = (0..3).map(|i| cov[(i, i)].sqrt()).collect();
println!("estimate: {:.5} {:.5} {:.4}", th[0], th[1], th[2]);
println!("SE: {:.5} {:.5} {:.4}", se[0], se[1], se[2]);
println!("correlation:");
for i in 0..3 {
let row: Vec<String> = (0..3).map(|k| format!("{:6.2}", cov[(i, k)] / (se[i] * se[k]))).collect();
println!("{}", row.join(" "));
}
}
// Output:
// estimate: 1.01507 0.19062 20.2162
// SE: 0.06243 0.01040 0.7165
// correlation:
// 1.00 -0.82 0.90
// -0.82 1.00 -0.91
// 0.90 -0.91 1.00R’s vcov gives \(s^2(J^TJ)^{-1}\) for an nls fit, and cov2cor turns it into correlations. numDeriv::jacobian and numDeriv::hessian compute derivatives numerically (Richardson extrapolation); the Python jacobian above and the Rust jacobian are plain central differences, accurate to about 8–10 digits, which is enough here. Rust prints numbers in its own format; the values agree with R and Python to the digits shown unless the text says otherwise.
By hand
B1. Two parameters that only appear as a product. An enzyme assay measures the initial rate \(v(S) = k_\text{cat}E_0\,S/(K_m + S)\) at substrate concentrations \(S = 1, 2, 5\) mM. The enzyme concentration \(E_0\) is not known. Take \(k_\text{cat} = 10\) /s, \(E_0 = 0.1\) µM, \(K_m = 2\) mM. (a) Write down the three columns of the Jacobian, \(\partial v/\partial k_\text{cat}\), \(\partial v/\partial E_0\), \(\partial v/\partial K_m\), and evaluate them at the three values of \(S\). (b) Show that the first two columns are proportional. What is the rank of \(J\)? What happens to \(J^TJ\)? (c) In log-parameters (fact 2), what do the first two columns become? Give the null direction \(v\) in \((\log k_\text{cat}, \log E_0, \log K_m)\). (d) Which combinations of the three parameters are identifiable? What extra measurement would separate \(k_\text{cat}\) from \(E_0\)?
B2. The flip-flop. (a) Show that swapping \(k_a \leftrightarrow k_e\) in the model and replacing \(V\) by \(V' = V k_e/k_a\) leaves \(C(t)\) unchanged for every \(t\). (b) For \(k_a = 1\), \(k_e = 0.2\) /h, \(V = 20\) L, \(F = 1\), \(D = 100\) mg: what is the flip-flop parameter set? Compute \(C(2)\) for both sets (\(e^{-0.4} = 0.6703\), \(e^{-2} = 0.1353\)). (c) An intravenous bolus of the same drug gives \(C(t) = (D/V)e^{-k_e t}\). Why does that experiment break the symmetry? What half-lives would the two parameter sets predict? (d) Is each of the two parameter sets locally identifiable? What does a multistart fit show?
B3. Standard errors for a 2-parameter fit. After an intravenous dose the concentration falls as \(C(t) = A e^{-kt}\). Samples at \(t = 0, 1, 2\) h, \(A = 10\) mg/L, \(k = 0.5\) /h, noise SD \(\sigma = 0.2\) mg/L (\(e^{-0.5} = 0.6065\), \(e^{-1} = 0.3679\)). (a) The columns of \(J\) are \(\partial C/\partial A = e^{-kt}\) and \(\partial C/\partial k = -At\,e^{-kt}\). Write down \(J\) (\(3\times2\)). (b) Compute \(J^TJ\) and its inverse. (c) Compute the standard errors of \(\hat A\) and \(\hat k\) (fact 4, \(\sigma\) known) and their correlation. Explain the sign of the correlation. (d) Move the third sample from \(t = 2\) to \(t = 4\) h (\(e^{-2} = 0.1353\)). Recompute \(\mathrm{SE}(\hat k)\). Did a longer time course help?
B4. Where to sample. In B3, suppose \(A = 10\) is known and only \(k\) is fitted, from a single sample at time \(t\). (a) Show that \(\mathrm{SE}(\hat k) = \sigma/|A t e^{-kt}|\). (b) Evaluate it at \(t = 0.5\), \(2\) and \(8\) h (\(e^{-0.25} = 0.7788\), \(e^{-4} = 0.0183\)). Which time is best? (c) Find the best \(t\) by setting the derivative of \(t e^{-kt}\) to zero. Use the answer to explain B3(d). (d) In the PK model, \(\partial C/\partial k_a\) is large only during the first 2–3 hours (lecture, “Fix 1”). What does that predict for a study whose first sample is at 3 h?
B5. A profile by hand. Same model as B3, data \(y = (10.2, 5.9, 3.8)\) at \(t = 0, 1, 2\), noise SD \(\sigma = 0.2\) known. The best fit is \(\hat A = 10.145\), \(\hat k = 0.5115\) with \(S(\hat\theta) = 0.0598\). (a) With \(k\) fixed, \(C = A e^{-kt}\) is linear in \(A\). Show that the best \(A\) is \(\hat A(k) = \sum_i y_i e^{-kt_i}/\sum_i e^{-2kt_i}\). (b) Compute \(\hat A(k)\) and \(\text{PL}(k) = S(\hat A(k), k)\) for \(k = 0.4\), \(0.5\) and \(0.6\) (\(e^{-0.4} = 0.6703\), \(e^{-0.8} = 0.4493\), \(e^{-0.6} = 0.5488\), \(e^{-1.2} = 0.3012\)). (c) With \(\sigma\) known, the 95 % criterion is \((\text{PL}(k) - S(\hat\theta))/\sigma^2 \le 3.84\). Which of the three \(k\) values lie inside the interval? (d) The Wald interval is \(\hat k \pm 1.96\,\mathrm{SE}\) with \(\mathrm{SE} \approx 0.025\) from B3. Compare.
B6. Reading \(J^TJ\). A model has two positive parameters \(a, b\). At the fit, in log-parameters, \(J^TJ = \begin{pmatrix}4 & 3.9\\ 3.9 & 4\end{pmatrix}\), and \(\sigma = 0.1\). (a) Find the eigenvalues and eigenvectors of \(J^TJ\). (b) What is the standard error along each eigenvector? Which combinations, \(\log a + \log b\) or \(\log a - \log b\), are well and badly determined? What are they in terms of \(a\) and \(b\)? (c) Compute \(\operatorname{Cov} = \sigma^2(J^TJ)^{-1}\), the standard errors of \(\log a\) and \(\log b\), and their correlation. (d) What would you report from this fit?
In code
C1. Standard errors three ways. Continue from the Background block. (a) Compute the Jacobian \(J\) (\(12\times3\)) at the fit (numDeriv::jacobian; Python: the jacobian helper, or res.jac). Compute the standard errors with solve(crossprod(J)) and with the QR route \((J^TJ)^{-1} = R^{-1}R^{-T}\) (qr, chol2inv; Python: np.linalg.qr(J, mode="r")), and compare with vcov. (b) Print the correlation matrix. Which pair of parameters is most strongly correlated, and what does the sign mean? (c) Check your answers to B3(c) in code.
C2. The Hessian. (a) Compute the Hessian \(H\) of \(S(\theta)\) at the fit with numDeriv::hessian (Python: scipy.differentiate.hessian; Rust: central differences). How close is it to \(2J^TJ\)? Compute the standard errors from \(2s^2H^{-1}\). (b) Now take \(\sigma = 0.1\) as known and minimise the negative log-likelihood \(S/(2\sigma^2)\) with optim(..., method = "BFGS", hessian = TRUE) (Python: scipy.optimize.minimize(..., method="BFGS")) from the start \((1, 0.2, 20)\), and from \((0.5, 0.1, 10)\). Invert the Hessian of the negative log-likelihood to get standard errors. What do you get from each start? (c) Python only: BFGS returns an approximation hess_inv of \(H^{-1}\). Compare the standard errors from it with those from the real Hessian.
C3. Structural non-identifiability in code. (a) Let \(F\) be a free parameter: fit \(C(t) = \text{bateman}(t, k_a, k_e, V/F)\) with four parameters. What does nls say? What does least_squares (Python) or the hand-written LM (Rust) return? Compute the singular values of the log-parameter Jacobian (svd; Python: np.linalg.svd) at \((1.0151, 0.1906, 20.22, 1)\) and the right singular vector of the smallest one. (b) Fit the three-parameter model from the starts \((k_a, k_e) = (0.5, 0.1), (2, 0.1), (0.1, 0.5), (2, 0.5)\), all with \(V = 10\). Report the estimates and the SSE. How many different answers, and how do they differ?
C4. The SVD of the Jacobian, two designs. Write a function that fits the model to given samples, computes \(J\), its log-parameter version \(J_\text{log}\) (fact 2), the singular values of \(J_\text{log}\), \(\kappa(J)\) and \(\kappa(J_\text{log})\) (kappa(..., exact = TRUE); Python: np.linalg.cond), the SE along each \(v_i\) (fact 5, with \(s\)), and \(v_3\). (a) Run it on all 12 samples and on the samples from 3 h only (late). (b) Which combination is worst determined in each design? Compare with the slide “Practical non-identifiability”.
C5. Profile likelihood. (a) Write profile_ka(ka, ts, ys): fix \(k_a\), fit \(k_e\) and \(V\) (start \(0.2, 20\)), return the SSE. For \(k_a = 0.3, 0.5, 0.7, 1, 1.5, 2, 5, 10, 30\), print \(\Delta = (\text{PL}(k_a) - S(\hat\theta))/s^2\) for both designs. (b) For all 12 samples, find the profile interval (where \(\Delta = 3.84\)) with uniroot (Python: scipy.optimize.brentq; Rust: bisection). Compare with the Wald interval \(\hat k_a \pm 1.96\,\mathrm{SE}\), and with the Wald interval for \(\log k_a\), \(\hat k_a e^{\pm 1.96\,\mathrm{SE}/\hat k_a}\). (c) For the samples from 3 h: what is the 95 % profile interval? What would you write in a report?
C6. A sloppy model. The two-compartment version of the model has a peripheral compartment exchanging with the central one at rates \(k_{12}\), \(k_{21}\), and elimination rate \(k_{10}\). Its solution is a sum of three exponentials (code below). Take \(k_a = 1\), \(k_{10} = 0.2\), \(k_{12} = 0.3\), \(k_{21} = 0.15\) /h, \(V = 20\) L. (a) Check your implementation: \(C(1), C(6), C(24) = 2.4087, 0.9606, 0.2882\) mg/L. (b) At the 12 sample times, compute the eigenvalues of \(J^TJ\) in log-parameters (eigen; Python: np.linalg.eigh), how many decades they span, and the SE along each eigenvector for \(\sigma = 0.1\). Print the sloppiest eigenvector. (c) Add samples at 24, 36 and 48 h. Which eigenvalues change, and is the model still sloppy?
C7. Fixes: design and prior. (a) Write se_design(tt, p, sigma) that returns the predicted SE of \(\log k_a, \log k_e, \log V\) for sample times tt at a guessed \(\theta\) (no data needed). Compare three 6-sample designs: late \((3, 4, 6, 8, 10, 12)\), early \((0.5, 1, 2, 4, 8, 12)\), peak \((1, 2, 3, 4, 6, 12)\), at \(\theta = (1, 0.2, 20)\), \(\sigma = 0.1\). (b) Fit the samples from 3 h with a prior \(\log k_a \sim N(\log 1.2, \tau^2)\) as an extra residual (fact 8), for \(\tau = 0.1, 0.25, 0.5, 1, 2\). Use minpack.lm::nls.lm with a residual function (Python: least_squares; Rust: the LM helper). Report \(\hat k_a\) and the SE of \(\log k_a\) from the augmented Jacobian. Compare the SE with \(\tau\): when is the answer mostly prior?
Explore
The demo uses the model and data of this exercise. Every sample keeps its own noise value from the course data, so all 12 samples and from 3 h reproduce the fits of the lecture; with noise switched off the data are the true curve and the SEs use \(\sigma = 0.1\), as in se_design (C7). Drag a sample (black dot) along the time axis. Panel (b) shows \(\Delta S/s^2\) over \((k_a, k_e)\) with \(V\) re-fitted (blue, thick at 3.84) and the Wald ellipse from the \((k_a, k_e)\) block of \(s^2(J^TJ)^{-1}\) at the same level (red); (c) the profile of \(k_a\) (\(k_e\) and \(V\) re-fitted for each \(k_a\)) with the Wald parabola (red dotted); (d) the singular values of the log-parameter Jacobian. Grey: the 12-sample design, for comparison.
E1. (the bowl is fine) With all 12 samples, read off the estimates, SEs, correlations and singular values, and compare them with the Background block and C4. Does the red ellipse in (b) match the thick blue contour? Compare the profile and Wald intervals in (c). Where is the second well of the profile, and how deep is it?
\(k_a = 1.015 \pm 0.0624\), \(k_e = 0.1906 \pm 0.0104\), \(V = 20.22 \pm 0.716\); correlations \(-0.82\), \(0.90\), \(-0.91\); singular values \(8.78, 3.48, 1.01\) with \(\kappa = 8.73\), and \(v_3 = (0.69, -0.60, 0.40)\): all as in the Background block and C4. The ellipse lies almost on the 3.84 contour, a tilted valley (corr \(-0.82\)). Profile interval \((0.90, 1.14)\), Wald \((0.89, 1.14)\): the quadratic picture holds. The profile has a second well at \(k_a = 0.19\), the flip-flop solution (\(k_a\) and \(k_e\) swapped), with \(\Delta = 0\): exactly as deep as the first. The hump between them is what keeps a local fit on one side.
E2. (the sparse design) Click from 3 h. Read the SE of \(k_a\), the Wald interval, the profile interval and the level at which the profile levels off on the right. What happens to the 3.84 contour in (b) for large \(k_a\), and what does the ellipse do instead? Which singular value dropped most, and what is \(v_3\)?
\(k_a = 1.122 \pm 0.406\) (36 %), Wald \((0.33, 1.92)\), profile \((0.68, \infty)\): the profile levels off at \(1.07\) on the right, below 3.84, so there is no upper bound (C5). In (b) the 3.84 contour is open to the right: for large \(k_a\) the valley runs horizontally at \(k_e \approx 0.17\)–\(0.23\), every fast absorption fits. The ellipse must close, so it ends at \(k_a = 1.92\), and on the left it reaches \(0.33\), below the true lower bound 0.68: wrong at both ends. \(\sigma_3\) fell from 1.01 to 0.211 (\(\sigma_1\) only from 8.78 to 6.03), \(\kappa = 28.6\), and \(v_3 = (0.98, -0.19, 0.06)\) is almost pure \(\log k_a\) with SE \(0.369\) along it.
E3. (move one sample) Still on from 3 h, drag the 3 h sample to 2 h, then 1 h, then 0.5 h (the times snap to 0.05 h). Each time, note the SE of \(k_a\), \(\sigma_3\) and the profile interval, and watch the ellipse and the profile. How much did moving a single sample buy, at the same cost of six samples?
At 2 h: \(\mathrm{SE}(k_a) = 0.160\) (15 %), \(\sigma_3 = 0.464\), profile \((0.80, 1.49)\): the profile now closes on the right, but it is still clearly asymmetric (Wald \((0.73, 1.36)\)). At 1 h: \(0.093\) (9 %), \(\sigma_3 = 0.682\), profile \((0.87, 1.24)\) against Wald \((0.85, 1.22)\). At 0.5 h: \(0.083\) (8 %), \(\sigma_3 = 0.746\), profile \((0.89, 1.22)\), Wald \((0.88, 1.20)\). The ellipse shrinks from a long cigar to a small, tilted one, and the 3.84 contour closes around it. One sample moved from 3 h to 1 h divides the SE of \(k_a\) by more than 4, and with 6 samples we come close to the 12-sample value 0.062. The profile shows the same as \(\sigma_3\): the weakest direction got stronger, and the quadratic picture became valid again.
E4. (before the experiment) Untick noise: the data are now the true curve and the SEs use \(\sigma = 0.1\). Compare from 3 h with spread: read SE/est. of \(k_a\) (for small values this is the SE of \(\log k_a\)) and compare with the lecture slide “Design in code”. Then click all late, first without and then with noise. What do the SEs, the correlations and (d) say?
From 3 h: SE/est. of \(k_a\) 40 %, of \(k_e\) 11 %, of \(V\) 6.1 %; spread: 10 %, 8.7 %, 5.9 %. These are the lecture’s \(0.398, 0.115, 0.061\) and \(0.101, 0.087, 0.059\): the design can be judged from \(J\) at a guess of \(\theta\), with no data. Without noise the profile of “from 3 h” still levels off (at 0.98), so the problem is the design, not the noise realisation. All late (7–12 h) without noise: \(\mathrm{SE}(k_a) = 10.7\) (1100 %), \(\mathrm{SE}(V) = 41\), \(r(k_e, V) = -1.00\), \(\sigma_3 = 0.0092\), \(\kappa = 496\). With noise the fit wanders off to \(k_a = 2.64\), where \(\sigma_3 \approx 0\): \(J\) is singular and there are no standard errors at all. Only the tail \(A e^{-k_e t}\) is seen, two numbers for three parameters.
E5. (only the rising phase) Click first 3 h (with noise). Which parameters are now badly determined? Look at the correlations and at the profile in (c): what happened to the two flip-flop wells?
Now \(k_e\) (\(0.181 \pm 0.105\), 58 %) and \(V\) (\(20.7 \pm 4.4\), 21 %) are poor, \(k_a\) is at 28 %; the correlations are \(-0.97\), \(0.99\), \(-0.99\), and \(v_3 = (0.40, -0.86, 0.31)\) is mostly \(\log k_e\). Three hours do not show the elimination. In (c) the hump between the two wells is only about 1.7, below 3.84, so the profile interval is \((< 0.05, 1.60)\): it contains the flip-flop branch. With only the rising phase the data cannot even tell which rate is absorption and which is elimination. Early samples fix \(k_a\), late samples fix \(k_e\): a good design has both, as spread does.
Hints
Differentiate the model with respect to one parameter, holding the others fixed. For B1, \(\partial v/\partial k_\text{cat} = E_0 S/(K_m+S)\) and \(\partial v/\partial K_m = -k_\text{cat}E_0S/(K_m+S)^2\). Two columns are proportional if their ratio is the same in every row.
\(\begin{pmatrix}a & b\\ b & d\end{pmatrix}^{-1} = \dfrac{1}{ad - b^2}\begin{pmatrix}d & -b\\ -b & a\end{pmatrix}\). Eigenvalues of \(\begin{pmatrix}a & b\\ b & a\end{pmatrix}\) are \(a \pm b\), with eigenvectors \((1, \pm1)/\sqrt2\).
Write \(C\) as (prefactor) × (bracket). Swapping \(k_a\) and \(k_e\) changes the sign of both \(k_a - k_e\) and the bracket \(e^{-k_et} - e^{-k_at}\). What is left to match is the prefactor \(k_a/V\).
For fixed \(k\), minimising \(\sum_i(y_i - Ae^{-kt_i})^2\) over \(A\) is a one-parameter linear least-squares problem: set the derivative with respect to \(A\) to zero.
R: vcov(fit), cov2cor(vcov(fit)), chol2inv(qr.R(qr(J))) is \((J^TJ)^{-1}\). Python: least_squares minimises half the sum of squares of the residual vector you return; res.jac is the Jacobian of the residuals (\(= -J\)), which gives the same \(J^TJ\). scipy.differentiate.hessian calls your function with an array of shape (3, ...), so loop over the extra axes (as in the solution) or write a vectorised SSE. optim(..., hessian = TRUE) returns the numerical Hessian at the solution in $hessian.
Multiply column \(j\) of \(J\) by \(\theta_j\) (R: J %*% diag(th); Python: J * th; Rust: DMatrix::from_fn). The signs of singular vectors are arbitrary; fix them (e.g. first entry positive) before comparing. nalgebra’s svd does not sort the singular values: sort them yourself.
In R, a parameter that is not in start is taken from the calling environment, so nls(ys ~ bateman(ts, ka, ke, V), start = list(ke = 0.2, V = 20)) inside a function with argument ka fits only ke and V. In Python, write the residual as a function of q = (ke, V) with ka fixed. If a fit fails at an extreme grid point, start it from the solution at the neighbouring point.
Divide the data residuals by \(\sigma\) and append \((\log k_a - \mu)/\tau\). Then the sum of squares is \(-2\log(\text{likelihood} \times \text{prior})\) + constant, and the covariance is \((J_a^TJ_a)^{-1}\) without a factor \(s^2\), where \(J_a\) is the Jacobian of the augmented residual vector. Fit in log-parameters so that the prior is a plain difference.
Solutions
B1. (a) \(S/(K_m+S) = 1/3, 1/2, 5/7 = 0.333, 0.5, 0.714\). \(\partial v/\partial k_\text{cat} = E_0S/(K_m+S) = (0.0333, 0.05, 0.0714)\); \(\partial v/\partial E_0 = k_\text{cat}S/(K_m+S) = (3.33, 5, 7.14)\); \(\partial v/\partial K_m = -k_\text{cat}E_0S/(K_m+S)^2 = -(1/9, 2/16, 5/49) = (-0.111, -0.125, -0.102)\). (b) Column 2 = \((k_\text{cat}/E_0)\,\times\) column 1 = \(100\,\times\) column 1 in every row. So \(J\) has rank 2, not 3, and \(J^TJ\) (\(3\times3\)) is singular: \((J^TJ)^{-1}\) does not exist, and nls stops with “singular gradient”. (c) Both become \(k_\text{cat}\,\partial v/\partial k_\text{cat} = E_0\,\partial v/\partial E_0 = v = (0.333, 0.5, 0.714)\): identical columns. The null direction is \(v = (1, -1, 0)/\sqrt2\): raise \(\log k_\text{cat}\) and lower \(\log E_0\) by the same amount. (d) \(V_\text{max} = k_\text{cat}E_0\) and \(K_m\) are identifiable; \(k_\text{cat}\) and \(E_0\) separately are not. An independent measurement of \(E_0\) (protein concentration, active-site titration) separates them: then \(k_\text{cat} = V_\text{max}/E_0\). This is the same structure as \(F/V\) in the PK model.
B2. (a) Swapped: \(\dfrac{FDk_e}{V'(k_e - k_a)}(e^{-k_at} - e^{-k_et}) = \dfrac{FDk_e}{V'(k_a - k_e)}(e^{-k_et} - e^{-k_at})\). This equals the original for all \(t\) if \(k_e/V' = k_a/V\), i.e. \(V' = Vk_e/k_a\). (b) \((k_a, k_e, V) = (0.2, 1, 4)\). Original: prefactor \(100\cdot1/(20\cdot0.8) = 6.25\), bracket \(0.6703 - 0.1353 = 0.5350\), \(C(2) = 3.344\) mg/L. Flip-flop: prefactor \(100\cdot0.2/(4\cdot(-0.8)) = -6.25\), bracket \(e^{-2} - e^{-0.4} = -0.5350\), \(C(2) = 3.344\) mg/L. Identical. (c) After an IV bolus there is no absorption phase, and \(k_e\) alone sets the decay: half-life \(\ln2/k_e = 3.47\) h for the first set, \(0.69\) h for the second. One IV time course fixes \(k_e\), and then the oral curve fixes \(k_a\). (d) Yes: each minimum is isolated, with a well-defined bowl around it (the profile in the lecture has two separate wells). Globally the data cannot choose. A multistart lands in both minima, with exactly the same SSE: a symmetry, not a convergence failure.
B3. (a) \(J = \begin{pmatrix}1 & 0\\ 0.6065 & -6.065\\ 0.3679 & -7.358\end{pmatrix}\). (b) \(J^TJ = \begin{pmatrix}1.5032 & -6.3855\\ -6.3855 & 90.92\end{pmatrix}\), \(\det = 136.67 - 40.77 = 95.90\), \((J^TJ)^{-1} = \dfrac{1}{95.90}\begin{pmatrix}90.92 & 6.3855\\ 6.3855 & 1.5032\end{pmatrix} = \begin{pmatrix}0.9481 & 0.0666\\ 0.0666 & 0.01567\end{pmatrix}\). (c) \(\mathrm{SE}(\hat A) = 0.2\sqrt{0.9481} = 0.195\) mg/L, \(\mathrm{SE}(\hat k) = 0.2\sqrt{0.01567} = 0.0250\) /h. Correlation \(0.0666/\sqrt{0.9481\cdot0.01567} = 0.546\). Positive: if \(\hat A\) comes out too high, the later points can still be matched by a faster decay, so \(\hat k\) is also too high. (d) Row 3 becomes \((0.1353, -5.413)\): \(J^TJ = \begin{pmatrix}1.3862 & -4.411\\ -4.411 & 66.09\end{pmatrix}\), \(\det = 72.16\), \(\mathrm{SE}(\hat k) = 0.2\sqrt{1.3862/72.16} = 0.0277\) /h. Worse, not better: at 4 h the concentration (and its sensitivity to \(k\)) is smaller than at 2 h. See B4.
B4. (a) One sample, one parameter: \(J = \partial C/\partial k = -Ate^{-kt}\) (\(1\times1\)), so \(\operatorname{Var}\hat k = \sigma^2/(Ate^{-kt})^2\). (b) \(t = 0.5\): \(|At e^{-kt}| = 10\cdot0.5\cdot0.7788 = 3.894\), SE \(= 0.0514\). \(t = 2\): \(10\cdot2\cdot0.3679 = 7.358\), SE \(= 0.0272\). \(t = 8\): \(10\cdot8\cdot0.0183 = 1.465\), SE \(= 0.137\). Best: \(t = 2\). (c) \(\frac{d}{dt}te^{-kt} = (1 - kt)e^{-kt} = 0\) at \(t = 1/k = 2\) h. Samples far beyond \(1/k\) have little signal left; that is why moving the sample from 2 h to 4 h in B3(d) made \(\mathrm{SE}(\hat k)\) larger. (d) With the first sample at 3 h, the columns of \(J\) for \(k_a\) are small (and nearly proportional to those for \(V\)): \(k_a\) will be poorly determined, whatever the number of late samples. C4, C5 and C7 confirm this.
B5. (a) \(\frac{\partial}{\partial A}\sum_i(y_i - Ae^{-kt_i})^2 = -2\sum_i e^{-kt_i}(y_i - Ae^{-kt_i}) = 0\) gives \(\hat A(k) = \sum_iy_ie^{-kt_i}/\sum_ie^{-2kt_i}\). (b)
| \(k\) | \(\sum y_ie^{-kt_i}\) | \(\sum e^{-2kt_i}\) | \(\hat A(k)\) | residuals | \(\text{PL}(k)\) |
|---|---|---|---|---|---|
| 0.4 | \(10.2 + 3.955 + 1.707 = 15.862\) | \(1 + 0.4493 + 0.2019 = 1.6512\) | 9.606 | \(0.594, -0.539, -0.516\) | 0.910 |
| 0.5 | \(10.2 + 3.578 + 1.398 = 15.176\) | \(1 + 0.3679 + 0.1353 = 1.5032\) | 10.096 | \(0.104, -0.223, 0.086\) | 0.068 |
| 0.6 | \(10.2 + 3.238 + 1.145 = 14.582\) | \(1 + 0.3012 + 0.0907 = 1.3919\) | 10.477 | \(-0.277, 0.150, 0.645\) | 0.514 |
- \(\Delta = (\text{PL} - 0.0598)/0.04 = 21.3\), \(0.21\), \(11.4\). Only \(k = 0.5\) is inside the 95 % interval; 0.4 and 0.6 are both outside. (In code: \(\Delta(0.45) = 6.2\) and \(\Delta(0.55) = 2.2\), so the interval is about \((0.46, 0.56)\).)
- Wald: \(0.5115 \pm 1.96\cdot0.025 = (0.462, 0.561)\), essentially the same as the profile: with three good points this model is close to linear near the optimum.
B6. (a) Eigenvalues \(4 \pm 3.9\): \(\lambda_1 = 7.9\) with \((1, 1)/\sqrt2\), \(\lambda_2 = 0.1\) with \((1, -1)/\sqrt2\). (b) SE along \(v_1\): \(0.1/\sqrt{7.9} = 0.036\); along \(v_2\): \(0.1/\sqrt{0.1} = 0.32\), nine times larger. Since \(v_1^T(\log a, \log b) = (\log a + \log b)/\sqrt2\), the product \(ab\) is well determined: \(\mathrm{SE}(\log ab) = \sqrt2\cdot0.036 = 0.05\), about 5 %. The ratio \(a/b\) is not: \(\mathrm{SE}(\log(a/b)) = \sqrt2\cdot0.32 = 0.45\), a factor 1.6. (c) \((J^TJ)^{-1} = \frac{1}{16 - 15.21}\begin{pmatrix}4 & -3.9\\ -3.9 & 4\end{pmatrix} = \begin{pmatrix}5.06 & -4.94\\ -4.94 & 5.06\end{pmatrix}\). \(\mathrm{SE}(\log a) = \mathrm{SE}(\log b) = 0.1\sqrt{5.06} = 0.225\); correlation \(-4.94/5.06 = -0.975\). (d) Report the product \(ab\) (± 5 %) and say that \(a\) and \(b\) separately are only known to a factor of about 1.25 each, and strongly negatively correlated. Quoting \(a\) and \(b\) with their SEs alone hides that their product is known 4.5 times better than either.
C1.
fit <- nls(y ~ bateman(tt, ka, ke, V), start = list(ka = 0.5, ke = 0.1, V = 10))
th <- coef(fit)
print(signif(th, 5))
# ka ke V
# 1.01510 0.19062 20.21600
s2 <- deviance(fit) / (length(y) - 3)
J <- jacobian(function(p) bateman(tt, p[1], p[2], p[3]), th)
se_vcov <- sqrt(diag(vcov(fit)))
se_solve <- sqrt(diag(s2 * solve(crossprod(J))))
se_qr <- sqrt(diag(s2 * chol2inv(qr.R(qr(J)))))
print(signif(rbind(se_vcov, se_solve, se_qr), 5))
# ka ke V
# se_vcov 0.062432 0.0104 0.71647
# se_solve 0.062432 0.0104 0.71647
# se_qr 0.062432 0.0104 0.71647
print(round(cov2cor(vcov(fit)), 3))
# ka ke V
# ka 1.000 -0.818 0.904
# ke -0.818 1.000 -0.913
# V 0.904 -0.913 1.000
# (d) check B3
A <- 10; k <- 0.5; tb <- c(0, 1, 2)
Jb <- cbind(exp(-k * tb), -A * tb * exp(-k * tb))
Cb <- 0.2^2 * solve(crossprod(Jb))
print(round(sqrt(diag(Cb)), 4)); print(round(cov2cor(Cb)[1, 2], 4))
# [1] 0.1947 0.0250
# [1] 0.5462th, S, res = fit_pk(tt, y, [0.5, 0.1, 10])
print(np.round(th, 5))
# [ 1.01507 0.19062 20.21621]
s2 = S / (len(y) - 3)
J = res.jac # Jacobian of the residuals (= -J, same J^T J)
se_jac = np.sqrt(np.diag(s2 * np.linalg.inv(J.T @ J)))
Jc = jacobian(lambda p: bateman(tt, *p), th) # central differences
se_solve = np.sqrt(np.diag(s2 * np.linalg.inv(Jc.T @ Jc)))
R = np.linalg.qr(Jc, mode="r") # (J^T J)^-1 = R^-1 R^-T
Rinv = np.linalg.inv(R)
se_qr = np.sqrt(np.diag(s2 * Rinv @ Rinv.T))
print(np.array2string(np.vstack([se_jac, se_solve, se_qr]), precision=5))
# [[0.06243 0.0104 0.71647]
# [0.06243 0.0104 0.71647]
# [0.06243 0.0104 0.71647]]
C = s2 * Rinv @ Rinv.T
se = np.sqrt(np.diag(C))
print(np.round(C / np.outer(se, se), 3))
# [[ 1. -0.818 0.904]
# [-0.818 1. -0.913]
# [ 0.904 -0.913 1. ]]
# (d) check B3
A, k, tb = 10, 0.5, np.array([0.0, 1, 2])
Jb = np.column_stack([np.exp(-k * tb), -A * tb * np.exp(-k * tb)])
Cb = 0.2**2 * np.linalg.inv(Jb.T @ Jb)
print(np.round(np.sqrt(np.diag(Cb)), 4), round(Cb[0, 1] / np.sqrt(Cb[0, 0] * Cb[1, 1]), 4))
# [0.1947 0.025 ] 0.5462// rust/examples/identifiability_c1.rs — cargo run --example identifiability_c1
// C1: standard errors three ways, and a check of B3.
#![allow(dead_code)]
use nalgebra::{DMatrix, DVector};
// One-compartment model with oral absorption, dose D = 100 mg (mg/L)
const D: f64 = 100.0; // oral dose, mg
fn bateman(t: f64, ka: f64, ke: f64, v: f64) -> f64 {
D * ka / (v * (ka - ke)) * ((-ke * t).exp() - (-ka * t).exp())
}
const TT: [f64; 12] = [0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 10.0, 12.0];
const Y: [f64; 12] = [1.02, 1.88, 2.34, 2.98, 3.27, 3.26, 3.17, 2.77, 1.92, 1.23, 1.00, 0.61];
// Central-difference Jacobian of f at p (like numDeriv::jacobian, less refined)
fn jacobian(f: &dyn Fn(&[f64]) -> Vec<f64>, p: &[f64]) -> DMatrix<f64> {
let n = f(p).len();
let mut j = DMatrix::zeros(n, p.len());
for k in 0..p.len() {
let h = 1e-5 * p[k].abs().max(1.0);
let (mut pp, mut pm) = (p.to_vec(), p.to_vec());
pp[k] += h;
pm[k] -= h;
let (fp, fm) = (f(&pp), f(&pm));
for i in 0..n { j[(i, k)] = (fp[i] - fm[i]) / (2.0 * h); }
}
j
}
// Levenberg-Marquardt for min sum r(p)^2, hand-written (R: nls / nls.lm, Python: least_squares)
fn levmar(r: &dyn Fn(&[f64]) -> Vec<f64>, p0: &[f64]) -> Vec<f64> {
let ss = |p: &[f64]| -> f64 { let v = r(p); if v.iter().all(|x| x.is_finite()) { v.iter().map(|x| x * x).sum() } else { f64::INFINITY } };
let (mut p, mut mu) = (p0.to_vec(), 1e-3);
for _ in 0..500 {
let j = jacobian(r, &p); // Jacobian of the residuals
let rv = DVector::from_vec(r(&p));
let jtj = j.transpose() * &j;
let g = j.transpose() * &rv;
loop {
let a = &jtj + DMatrix::from_diagonal(&jtj.diagonal()) * mu;
let step = a.lu().solve(&(-&g)).unwrap();
let pn: Vec<f64> = p.iter().zip(step.iter()).map(|(a, b)| a + b).collect();
if ss(&pn) <= ss(&p) {
let small = step.norm() < 1e-12 * (1.0 + DVector::from_vec(p.clone()).norm());
p = pn;
mu = (mu / 10.0).max(1e-12);
if small { return p; }
break;
}
mu *= 10.0;
if mu > 1e12 { return p; }
}
}
p
}
// Residuals y - C(t) for the one-compartment model at the sample times ts
fn resid(ts: &[f64], ys: &[f64]) -> impl Fn(&[f64]) -> Vec<f64> {
let (ts, ys) = (ts.to_vec(), ys.to_vec());
move |p: &[f64]| ts.iter().zip(&ys).map(|(ti, yi)| yi - bateman(*ti, p[0], p[1], p[2])).collect()
}
fn sse(r: &dyn Fn(&[f64]) -> Vec<f64>, p: &[f64]) -> f64 { r(p).iter().map(|x| x * x).sum() }
fn main() {
let r = resid(&TT, &Y);
let th = levmar(&r, &[0.5, 0.1, 10.0]);
println!("estimate: {:.5} {:.5} {:.5}", th[0], th[1], th[2]);
let s2 = sse(&r, &th) / (TT.len() - 3) as f64;
let j = jacobian(&r, &th); // = -J; J^T J is the same
let c_solve = (j.transpose() * &j).try_inverse().unwrap() * s2;
let rr = j.clone().qr().r(); // (J^T J)^-1 = R^-1 R^-T
let rinv = rr.try_inverse().unwrap();
let c_qr = &rinv * rinv.transpose() * s2;
for (name, c) in [("se_solve", &c_solve), ("se_qr ", &c_qr)] {
println!("{} {:.5} {:.5} {:.5}", name, c[(0, 0)].sqrt(), c[(1, 1)].sqrt(), c[(2, 2)].sqrt());
}
println!("correlation:");
for i in 0..3 {
let row: Vec<String> = (0..3)
.map(|k| format!("{:7.3}", c_qr[(i, k)] / (c_qr[(i, i)] * c_qr[(k, k)]).sqrt())).collect();
println!("{}", row.join(" "));
}
// (d) check B3: C = A exp(-k t), A = 10, k = 0.5, t = 0, 1, 2, sigma = 0.2
let (a, k) = (10.0_f64, 0.5_f64);
let jb = DMatrix::from_fn(3, 2, |i, c| {
let t = i as f64;
if c == 0 { (-k * t).exp() } else { -a * t * (-k * t).exp() }
});
let cb = (jb.transpose() * &jb).try_inverse().unwrap() * 0.04;
println!("B3: SE {:.4} {:.4}, correlation {:.4}", cb[(0, 0)].sqrt(), cb[(1, 1)].sqrt(),
cb[(0, 1)] / (cb[(0, 0)] * cb[(1, 1)]).sqrt());
}
// Output:
// estimate: 1.01507 0.19062 20.21621
// se_solve 0.06243 0.01040 0.71647
// se_qr 0.06243 0.01040 0.71647
// correlation:
// 1.000 -0.818 0.904
// -0.818 1.000 -0.913
// 0.904 -0.913 1.000
// B3: SE 0.1947 0.0250, correlation 0.5462All three routes agree to the digits shown, as they must for this well-conditioned problem (\(\kappa(J^TJ) \approx 3\times10^4\)); for a sloppy model use the QR route, which never forms \(J^TJ\). The strongest correlation is \(k_e\)–\(V\) (\(-0.91\)), closely followed by \(k_a\)–\(V\) (\(+0.90\)): a larger volume can be compensated by faster absorption (a higher, earlier peak) and slower elimination. The B3 numbers are confirmed.
C2.
fit <- nls(y ~ bateman(tt, ka, ke, V), start = list(ka = 0.5, ke = 0.1, V = 10))
th <- coef(fit); s2 <- deviance(fit) / (length(y) - 3)
J <- jacobian(function(p) bateman(tt, p[1], p[2], p[3]), th)
th <- coef(fit); s2 <- deviance(fit) / (length(y) - 3)
J <- jacobian(function(p) bateman(tt, p[1], p[2], p[3]), th)
sse <- function(p) sum((y - bateman(tt, p[1], p[2], p[3]))^2)
H <- hessian(sse, th)
round(max(abs(H - 2 * crossprod(J)) / abs(H)), 4) # largest relative difference
# [1] 0.0028
signif(sqrt(diag(2 * s2 * solve(H))), 5)
# [1] 0.062164 0.010401 0.715040
# (c) negative log-likelihood with known sigma = 0.1, minimised by BFGS
nll <- function(p) sse(p) / (2 * 0.1^2)
for (start in list(c(1, 0.2, 20), c(0.5, 0.1, 10))) {
o <- optim(start, nll, method = "BFGS", hessian = TRUE)
print(round(c(o$par, sqrt(diag(solve(o$hessian)))), 4))
}
# [1] 1.0150 0.1906 20.2151 0.0723 0.0121 0.8320
# [1] 0.1906 1.0150 3.7967 0.0121 0.0723 0.3422np.set_printoptions(suppress=True)
from scipy.optimize import minimize
from scipy.differentiate import hessian
th, S, res = fit_pk(tt, y, [0.5, 0.1, 10])
s2 = S / (len(y) - 3)
J = jacobian(lambda p: bateman(tt, *p), th)
sse = lambda p: np.sum((y - bateman(tt, *p))**2)
# scipy.differentiate.hessian wants f to accept p with shape (3, ...): loop over extra axes
def sse_vec(p):
p = np.asarray(p)
out = np.empty(p.shape[1:])
for idx in np.ndindex(*p.shape[1:]):
out[idx] = sse(p[(slice(None),) + idx])
return out
H = hessian(sse_vec, th).ddf
print(round(np.max(np.abs(H - 2 * J.T @ J) / np.abs(H)), 4))
# 0.0028
print(np.array2string(np.sqrt(np.diag(2 * s2 * np.linalg.inv(H))), precision=6))
# [0.062164 0.010401 0.715041]
# (c) negative log-likelihood with known sigma = 0.1, BFGS
nll = lambda p: sse(p) / (2 * 0.1**2)
for start in ([1, 0.2, 20], [0.5, 0.1, 10]):
o = minimize(nll, start, method="BFGS")
Hn = hessian(lambda p: sse_vec(p) / (2 * 0.1**2), o.x).ddf
print(np.round(np.concatenate([o.x, np.sqrt(np.diag(np.linalg.inv(Hn)))]), 4))
print(" from BFGS hess_inv:", np.round(np.sqrt(np.diag(o.hess_inv)), 4))
# [ 1.0151 0.1906 20.2162 0.0723 0.0121 0.832 ]
# from BFGS hess_inv: [0.0244 0.0061 0.1416]
# [0.1906 1.0151 3.7963 0.0121 0.0723 0.3422]
# from BFGS hess_inv: [0.0121 0.0726 0.3428]// rust/examples/identifiability_c2.rs — cargo run --example identifiability_c2
// C2: the Hessian of the SSE by central differences; SEs from it.
#![allow(dead_code)]
use nalgebra::{DMatrix, DVector};
// One-compartment model with oral absorption, dose D = 100 mg (mg/L)
const D: f64 = 100.0; // oral dose, mg
fn bateman(t: f64, ka: f64, ke: f64, v: f64) -> f64 {
D * ka / (v * (ka - ke)) * ((-ke * t).exp() - (-ka * t).exp())
}
const TT: [f64; 12] = [0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 10.0, 12.0];
const Y: [f64; 12] = [1.02, 1.88, 2.34, 2.98, 3.27, 3.26, 3.17, 2.77, 1.92, 1.23, 1.00, 0.61];
// Central-difference Jacobian of f at p (like numDeriv::jacobian, less refined)
fn jacobian(f: &dyn Fn(&[f64]) -> Vec<f64>, p: &[f64]) -> DMatrix<f64> {
let n = f(p).len();
let mut j = DMatrix::zeros(n, p.len());
for k in 0..p.len() {
let h = 1e-5 * p[k].abs().max(1.0);
let (mut pp, mut pm) = (p.to_vec(), p.to_vec());
pp[k] += h;
pm[k] -= h;
let (fp, fm) = (f(&pp), f(&pm));
for i in 0..n { j[(i, k)] = (fp[i] - fm[i]) / (2.0 * h); }
}
j
}
// Levenberg-Marquardt for min sum r(p)^2, hand-written (R: nls / nls.lm, Python: least_squares)
fn levmar(r: &dyn Fn(&[f64]) -> Vec<f64>, p0: &[f64]) -> Vec<f64> {
let ss = |p: &[f64]| -> f64 { let v = r(p); if v.iter().all(|x| x.is_finite()) { v.iter().map(|x| x * x).sum() } else { f64::INFINITY } };
let (mut p, mut mu) = (p0.to_vec(), 1e-3);
for _ in 0..500 {
let j = jacobian(r, &p); // Jacobian of the residuals
let rv = DVector::from_vec(r(&p));
let jtj = j.transpose() * &j;
let g = j.transpose() * &rv;
loop {
let a = &jtj + DMatrix::from_diagonal(&jtj.diagonal()) * mu;
let step = a.lu().solve(&(-&g)).unwrap();
let pn: Vec<f64> = p.iter().zip(step.iter()).map(|(a, b)| a + b).collect();
if ss(&pn) <= ss(&p) {
let small = step.norm() < 1e-12 * (1.0 + DVector::from_vec(p.clone()).norm());
p = pn;
mu = (mu / 10.0).max(1e-12);
if small { return p; }
break;
}
mu *= 10.0;
if mu > 1e12 { return p; }
}
}
p
}
// Residuals y - C(t) for the one-compartment model at the sample times ts
fn resid(ts: &[f64], ys: &[f64]) -> impl Fn(&[f64]) -> Vec<f64> {
let (ts, ys) = (ts.to_vec(), ys.to_vec());
move |p: &[f64]| ts.iter().zip(&ys).map(|(ti, yi)| yi - bateman(*ti, p[0], p[1], p[2])).collect()
}
fn sse(r: &dyn Fn(&[f64]) -> Vec<f64>, p: &[f64]) -> f64 { r(p).iter().map(|x| x * x).sum() }
// Central-difference Hessian of a scalar function (R: numDeriv::hessian)
fn hessian(f: &dyn Fn(&[f64]) -> f64, p: &[f64]) -> DMatrix<f64> {
let n = p.len();
let h: Vec<f64> = p.iter().map(|x| 1e-4 * x.abs().max(1.0)).collect();
let fe = |di: usize, si: f64, dk: usize, sk: f64| {
let mut q = p.to_vec();
q[di] += si * h[di];
q[dk] += sk * h[dk];
f(&q)
};
DMatrix::from_fn(n, n, |i, k| {
(fe(i, 1.0, k, 1.0) - fe(i, 1.0, k, -1.0) - fe(i, -1.0, k, 1.0) + fe(i, -1.0, k, -1.0))
/ (4.0 * h[i] * h[k])
})
}
fn main() {
let r = resid(&TT, &Y);
let th = levmar(&r, &[0.5, 0.1, 10.0]);
let s2 = sse(&r, &th) / (TT.len() - 3) as f64;
let j = jacobian(&r, &th);
let f = |p: &[f64]| sse(&r, p);
let h = hessian(&f, &th);
let gn = (j.transpose() * &j) * 2.0;
let rel = (0..9).map(|i| ((h[i] - gn[i]) / h[i]).abs()).fold(0.0, f64::max);
println!("largest relative difference H vs 2 J^T J: {:.4}", rel);
let c = h.try_inverse().unwrap() * (2.0 * s2);
println!("SE from H: {:.6} {:.6} {:.6}", c[(0, 0)].sqrt(), c[(1, 1)].sqrt(), c[(2, 2)].sqrt());
// (c) known sigma = 0.1: minimise nll = SSE / (2 sigma^2) (LM on r / sigma), invert its Hessian
let nll = |p: &[f64]| sse(&r, p) / (2.0 * 0.01);
for start in [[1.0, 0.2, 20.0], [0.5, 0.1, 10.0]] {
let p = levmar(&r, &start);
let ci = hessian(&nll, &p).try_inverse().unwrap();
println!("{:.4} {:.4} {:.4} SE {:.4} {:.4} {:.4}", p[0], p[1], p[2],
ci[(0, 0)].sqrt(), ci[(1, 1)].sqrt(), ci[(2, 2)].sqrt());
}
}
// Output:
// largest relative difference H vs 2 J^T J: 0.0028
// SE from H: 0.062164 0.010401 0.715040
// 1.0151 0.1906 20.2162 SE 0.0723 0.0121 0.8320
// 1.0151 0.1906 20.2162 SE 0.0723 0.0121 0.8320\(H\) and \(2J^TJ\) differ by at most 0.3 % (in the \(k_a\)–\(k_a\) entry): the residual term in fact 3 is small, and the SEs from \(H\) differ from those of vcov in the third digit. With \(\sigma = 0.1\) known the SEs are larger by the factor \(\sigma/s = 0.1/0.0859 = 1.16\). From \((0.5, 0.1, 10)\), BFGS in R and Python lands on the flip-flop minimum \((0.191, 1.015, 3.80)\): same SSE, and SEs that are just as small. The Rust LM fit happens to stay on the first branch from both starts; which minimum you get depends on the algorithm as well as the start. Python’s hess_inv is the BFGS approximation built up from gradients during the run: from the first start it gives SEs 2 to 6 times too small. Never use it for standard errors; compute the Hessian at the solution.
C3.
# (a) F and V both free
f4 <- tryCatch(nls(y ~ bateman(tt, ka, ke, V / F), start = list(ka = 0.5, ke = 0.1, V = 10, F = 0.8)),
error = function(e) conditionMessage(e))
print(f4)
# [1] "singular gradient matrix at initial parameter estimates"
p4 <- c(ka = 1.0151, ke = 0.1906, V = 20.22, F = 1) # near the fit, F = 1
J4 <- jacobian(function(lp) bateman(tt, exp(lp[1]), exp(lp[2]), exp(lp[3] - lp[4])), log(p4))
s4 <- svd(J4)
print(signif(s4$d, 4))
# [1] 1.189e+01 3.483e+00 1.048e+00 1.770e-11
print(round(s4$v[, 4] * sign(s4$v[3, 4]), 3))
# [1] 0.000 0.000 0.707 0.707
# (b) multistart
starts <- rbind(c(0.5, 0.1), c(2, 0.1), c(0.1, 0.5), c(2, 0.5))
for (i in 1:4) {
f <- nls(y ~ bateman(tt, ka, ke, V), start = list(ka = starts[i, 1], ke = starts[i, 2], V = 10))
cat(sprintf("start ka=%.1f ke=%.1f -> ka=%.4f ke=%.4f V=%.3f SSE=%.6f\n",
starts[i, 1], starts[i, 2], coef(f)[1], coef(f)[2], coef(f)[3], deviance(f)))
}
# start ka=0.5 ke=0.1 -> ka=1.0151 ke=0.1906 V=20.216 SSE=0.066467
# start ka=2.0 ke=0.1 -> ka=1.0151 ke=0.1906 V=20.216 SSE=0.066467
# start ka=0.1 ke=0.5 -> ka=0.1906 ke=1.0151 V=3.796 SSE=0.066467
# start ka=2.0 ke=0.5 -> ka=1.0151 ke=0.1906 V=20.216 SSE=0.066467# (a) F and V both free: the Jacobian is singular
p4 = np.array([1.0151, 0.1906, 20.22, 1.0]) # near the fit, F = 1
J4 = jacobian(lambda lp: bateman(tt, np.exp(lp[0]), np.exp(lp[1]), np.exp(lp[2] - lp[3])), np.log(p4))
U, d, Vt = np.linalg.svd(J4)
print(np.array2string(d, precision=3, suppress_small=False))
# [1.189e+01 3.483e+00 1.048e+00 1.100e-11]
v4 = Vt[3] * np.sign(Vt[3, 2])
print(np.round(v4, 3))
# [0. 0. 0.707 0.707]
res = least_squares(lambda p: y - bateman(tt, p[0], p[1], p[2] / p[3]), [0.5, 0.1, 10, 0.8])
print(np.round(res.x, 4), res.status, round(res.x[2] / res.x[3], 4)) # no error; V/F
# [ 1.0151 0.1906 12.5087 0.6187] 2 20.2162
# (b) multistart
for ka0, ke0 in [(0.5, 0.1), (2, 0.1), (0.1, 0.5), (2, 0.5)]:
th, S, _ = fit_pk(tt, y, [ka0, ke0, 10])
print(f"start ka={ka0:.1f} ke={ke0:.1f} -> ka={th[0]:.4f} ke={th[1]:.4f} V={th[2]:.3f} SSE={S:.6f}")
# start ka=0.5 ke=0.1 -> ka=1.0151 ke=0.1906 V=20.216 SSE=0.066467
# start ka=2.0 ke=0.1 -> ka=1.0151 ke=0.1906 V=20.216 SSE=0.066467
# start ka=0.1 ke=0.5 -> ka=0.1906 ke=1.0151 V=3.796 SSE=0.066467
# start ka=2.0 ke=0.5 -> ka=0.1906 ke=1.0151 V=3.796 SSE=0.066467// rust/examples/identifiability_c3.rs — cargo run --example identifiability_c3
// C3: structural non-identifiability: F and V together; the flip-flop in a multistart.
#![allow(dead_code)]
use nalgebra::{DMatrix, DVector};
// One-compartment model with oral absorption, dose D = 100 mg (mg/L)
const D: f64 = 100.0; // oral dose, mg
fn bateman(t: f64, ka: f64, ke: f64, v: f64) -> f64 {
D * ka / (v * (ka - ke)) * ((-ke * t).exp() - (-ka * t).exp())
}
const TT: [f64; 12] = [0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 10.0, 12.0];
const Y: [f64; 12] = [1.02, 1.88, 2.34, 2.98, 3.27, 3.26, 3.17, 2.77, 1.92, 1.23, 1.00, 0.61];
// Central-difference Jacobian of f at p (like numDeriv::jacobian, less refined)
fn jacobian(f: &dyn Fn(&[f64]) -> Vec<f64>, p: &[f64]) -> DMatrix<f64> {
let n = f(p).len();
let mut j = DMatrix::zeros(n, p.len());
for k in 0..p.len() {
let h = 1e-5 * p[k].abs().max(1.0);
let (mut pp, mut pm) = (p.to_vec(), p.to_vec());
pp[k] += h;
pm[k] -= h;
let (fp, fm) = (f(&pp), f(&pm));
for i in 0..n { j[(i, k)] = (fp[i] - fm[i]) / (2.0 * h); }
}
j
}
// Levenberg-Marquardt for min sum r(p)^2, hand-written (R: nls / nls.lm, Python: least_squares)
fn levmar(r: &dyn Fn(&[f64]) -> Vec<f64>, p0: &[f64]) -> Vec<f64> {
let ss = |p: &[f64]| -> f64 { let v = r(p); if v.iter().all(|x| x.is_finite()) { v.iter().map(|x| x * x).sum() } else { f64::INFINITY } };
let (mut p, mut mu) = (p0.to_vec(), 1e-3);
for _ in 0..500 {
let j = jacobian(r, &p); // Jacobian of the residuals
let rv = DVector::from_vec(r(&p));
let jtj = j.transpose() * &j;
let g = j.transpose() * &rv;
loop {
let a = &jtj + DMatrix::from_diagonal(&jtj.diagonal()) * mu;
let step = a.lu().solve(&(-&g)).unwrap();
let pn: Vec<f64> = p.iter().zip(step.iter()).map(|(a, b)| a + b).collect();
if ss(&pn) <= ss(&p) {
let small = step.norm() < 1e-12 * (1.0 + DVector::from_vec(p.clone()).norm());
p = pn;
mu = (mu / 10.0).max(1e-12);
if small { return p; }
break;
}
mu *= 10.0;
if mu > 1e12 { return p; }
}
}
p
}
// Residuals y - C(t) for the one-compartment model at the sample times ts
fn resid(ts: &[f64], ys: &[f64]) -> impl Fn(&[f64]) -> Vec<f64> {
let (ts, ys) = (ts.to_vec(), ys.to_vec());
move |p: &[f64]| ts.iter().zip(&ys).map(|(ti, yi)| yi - bateman(*ti, p[0], p[1], p[2])).collect()
}
fn sse(r: &dyn Fn(&[f64]) -> Vec<f64>, p: &[f64]) -> f64 { r(p).iter().map(|x| x * x).sum() }
fn main() {
// (a) F and V both free: C depends on V / F only
let r4 = |p: &[f64]| -> Vec<f64> { TT.iter().zip(&Y).map(|(t, y)| y - bateman(*t, p[0], p[1], p[2] / p[3])).collect() };
let p4 = [1.0151_f64, 0.1906, 20.22, 1.0];
let lp4: Vec<f64> = p4.iter().map(|x| x.ln()).collect();
let flog = |lp: &[f64]| -> Vec<f64> { TT.iter().map(|t| bateman(*t, lp[0].exp(), lp[1].exp(), (lp[2] - lp[3]).exp())).collect() };
let svd = jacobian(&flog, &lp4).svd(false, true);
let mut idx: Vec<usize> = (0..4).collect(); // nalgebra does not promise an order
idx.sort_by(|a, b| svd.singular_values[*b].partial_cmp(&svd.singular_values[*a]).unwrap());
let d: Vec<String> = idx.iter().map(|&i| format!("{:.3e}", svd.singular_values[i])).collect();
println!("singular values: {}", d.join(" "));
let vt = svd.v_t.unwrap();
let v4 = vt.row(idx[3]) * vt[(idx[3], 2)].signum();
println!("v4: {:.3} {:.3} {:.3} {:.3}", v4[0], v4[1], v4[2], v4[3]);
let p = levmar(&r4, &[0.5, 0.1, 10.0, 0.8]);
println!("LM with F free: ka {:.4} ke {:.4} V {:.4} F {:.4} V/F {:.4}", p[0], p[1], p[2], p[3], p[2] / p[3]);
// (b) multistart
let r = resid(&TT, &Y);
for (ka0, ke0) in [(0.5, 0.1), (2.0, 0.1), (0.1, 0.5), (2.0, 0.5)] {
let th = levmar(&r, &[ka0, ke0, 10.0]);
println!("start ka={:.1} ke={:.1} -> ka={:.4} ke={:.4} V={:.3} SSE={:.6}",
ka0, ke0, th[0], th[1], th[2], sse(&r, &th));
}
}
// Output:
// singular values: 1.189e1 3.483e0 1.048e0 1.101e-11
// v4: 0.000 0.000 0.707 0.707
// LM with F free: ka 1.0151 ke 0.1906 V 11.7700 F 0.5822 V/F 20.2162
// start ka=0.5 ke=0.1 -> ka=1.0151 ke=0.1906 V=20.216 SSE=0.066467
// start ka=2.0 ke=0.1 -> ka=1.0151 ke=0.1906 V=20.216 SSE=0.066467
// start ka=0.1 ke=0.5 -> ka=0.1906 ke=1.0151 V=3.796 SSE=0.066467
// start ka=2.0 ke=0.5 -> ka=1.0151 ke=0.1906 V=20.216 SSE=0.066467nls refuses with “singular gradient”. least_squares and the hand-written LM do not complain: they return some point on the line \(V/F = 20.216\) (here \(V = 12.5\), \(F = 0.62\) in Python, \(V = 11.8\), \(F = 0.58\) in Rust), and which point depends on the start and the algorithm. The SVD shows why: \(\sigma_4 \approx 10^{-11}\) is rounding noise (its exact value differs between languages), and \(v_4 = (0, 0, 0.707, 0.707)\): \(\log V\) and \(\log F\) up together. In the multistart, every fit reaches SSE \(= 0.066467\), in one of two places: the expected \((1.015, 0.191, 20.2)\) or the flip-flop \((0.191, 1.015, 3.80)\). R and Rust find the flip-flop from one start, Python from two.
C4.
svd_report <- function(ts, ys) {
f <- nls(ys ~ bateman(ts, ka, ke, V), start = list(ka = 1, ke = 0.2, V = 20))
th <- coef(f); s <- sqrt(deviance(f) / (length(ys) - 3))
J <- jacobian(function(p) bateman(ts, p[1], p[2], p[3]), th)
Jl <- J %*% diag(th) # d C / d log(theta)
sv <- svd(Jl)
cat("singular values:", signif(sv$d, 4), "\n")
cat("kappa(J) =", signif(kappa(J, exact = TRUE), 4),
" kappa(J_log) =", signif(kappa(Jl, exact = TRUE), 4), "\n")
cat("SE along v_i (log units):", signif(s / sv$d, 3), "\n")
v3 <- sv$v[, 3] * sign(sv$v[1, 3])
cat("v3 (log ka, log ke, log V):", round(v3, 3), "\n")
}
svd_report(tt, y)
# singular values: 8.779 3.478 1.005
# kappa(J) = 169.9 kappa(J_log) = 8.734
# SE along v_i (log units): 0.00979 0.0247 0.0855
# v3 (log ka, log ke, log V): 0.691 -0.601 0.4
svd_report(tt[late], y[late])
# singular values: 6.032 1.527 0.2111
# kappa(J) = 206.5 kappa(J_log) = 28.58
# SE along v_i (log units): 0.0129 0.051 0.369
# v3 (log ka, log ke, log V): 0.98 -0.19 0.056def svd_report(ts, ys):
th, S, _ = fit_pk(ts, ys, [1, 0.2, 20])
s = np.sqrt(S / (len(ys) - 3))
J = jacobian(lambda p: bateman(ts, *p), th)
Jl = J * th # d C / d log(theta): scale the columns
U, d, Vt = np.linalg.svd(Jl)
print("singular values:", np.array2string(d, precision=4))
print(f"kappa(J) = {np.linalg.cond(J):.4g} kappa(J_log) = {np.linalg.cond(Jl):.4g}")
print("SE along v_i (log units):", np.array2string(s / d, precision=3))
v3 = Vt[2] * np.sign(Vt[2, 0])
print("v3 (log ka, log ke, log V):", np.round(v3, 3))
svd_report(tt, y)
# singular values: [8.7791 3.4781 1.0052]
# kappa(J) = 169.9 kappa(J_log) = 8.734
# SE along v_i (log units): [0.01 0.025 0.085]
# v3 (log ka, log ke, log V): [ 0.691 -0.601 0.4 ]
svd_report(tt[late], y[late])
# singular values: [6.0322 1.5269 0.2111]
# kappa(J) = 206.5 kappa(J_log) = 28.58
# SE along v_i (log units): [0.013 0.051 0.369]
# v3 (log ka, log ke, log V): [ 0.98 -0.19 0.056]// rust/examples/identifiability_c4.rs — cargo run --example identifiability_c4
// C4: the SVD of the Jacobian in log-parameters, both designs.
#![allow(dead_code)]
use nalgebra::{DMatrix, DVector};
// One-compartment model with oral absorption, dose D = 100 mg (mg/L)
const D: f64 = 100.0; // oral dose, mg
fn bateman(t: f64, ka: f64, ke: f64, v: f64) -> f64 {
D * ka / (v * (ka - ke)) * ((-ke * t).exp() - (-ka * t).exp())
}
const TT: [f64; 12] = [0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 10.0, 12.0];
const Y: [f64; 12] = [1.02, 1.88, 2.34, 2.98, 3.27, 3.26, 3.17, 2.77, 1.92, 1.23, 1.00, 0.61];
// Central-difference Jacobian of f at p (like numDeriv::jacobian, less refined)
fn jacobian(f: &dyn Fn(&[f64]) -> Vec<f64>, p: &[f64]) -> DMatrix<f64> {
let n = f(p).len();
let mut j = DMatrix::zeros(n, p.len());
for k in 0..p.len() {
let h = 1e-5 * p[k].abs().max(1.0);
let (mut pp, mut pm) = (p.to_vec(), p.to_vec());
pp[k] += h;
pm[k] -= h;
let (fp, fm) = (f(&pp), f(&pm));
for i in 0..n { j[(i, k)] = (fp[i] - fm[i]) / (2.0 * h); }
}
j
}
// Levenberg-Marquardt for min sum r(p)^2, hand-written (R: nls / nls.lm, Python: least_squares)
fn levmar(r: &dyn Fn(&[f64]) -> Vec<f64>, p0: &[f64]) -> Vec<f64> {
let ss = |p: &[f64]| -> f64 { let v = r(p); if v.iter().all(|x| x.is_finite()) { v.iter().map(|x| x * x).sum() } else { f64::INFINITY } };
let (mut p, mut mu) = (p0.to_vec(), 1e-3);
for _ in 0..500 {
let j = jacobian(r, &p); // Jacobian of the residuals
let rv = DVector::from_vec(r(&p));
let jtj = j.transpose() * &j;
let g = j.transpose() * &rv;
loop {
let a = &jtj + DMatrix::from_diagonal(&jtj.diagonal()) * mu;
let step = a.lu().solve(&(-&g)).unwrap();
let pn: Vec<f64> = p.iter().zip(step.iter()).map(|(a, b)| a + b).collect();
if ss(&pn) <= ss(&p) {
let small = step.norm() < 1e-12 * (1.0 + DVector::from_vec(p.clone()).norm());
p = pn;
mu = (mu / 10.0).max(1e-12);
if small { return p; }
break;
}
mu *= 10.0;
if mu > 1e12 { return p; }
}
}
p
}
// Residuals y - C(t) for the one-compartment model at the sample times ts
fn resid(ts: &[f64], ys: &[f64]) -> impl Fn(&[f64]) -> Vec<f64> {
let (ts, ys) = (ts.to_vec(), ys.to_vec());
move |p: &[f64]| ts.iter().zip(&ys).map(|(ti, yi)| yi - bateman(*ti, p[0], p[1], p[2])).collect()
}
fn sse(r: &dyn Fn(&[f64]) -> Vec<f64>, p: &[f64]) -> f64 { r(p).iter().map(|x| x * x).sum() }
fn svd_report(ts: &[f64], ys: &[f64]) {
let r = resid(ts, ys);
let th = levmar(&r, &[1.0, 0.2, 20.0]);
let s = (sse(&r, &th) / (ts.len() - 3) as f64).sqrt();
let model = |p: &[f64]| -> Vec<f64> { ts.iter().map(|t| bateman(*t, p[0], p[1], p[2])).collect() };
let j = jacobian(&model, &th);
let jl = DMatrix::from_fn(ts.len(), 3, |i, k| j[(i, k)] * th[k]); // d C / d log(theta)
let kappa = |m: &DMatrix<f64>| { let d = m.singular_values(); d.max() / d.min() };
let svd = jl.clone().svd(false, true);
let mut idx: Vec<usize> = (0..3).collect();
idx.sort_by(|a, b| svd.singular_values[*b].partial_cmp(&svd.singular_values[*a]).unwrap());
let d: Vec<f64> = idx.iter().map(|&i| svd.singular_values[i]).collect();
println!("singular values: {:.4} {:.4} {:.4}", d[0], d[1], d[2]);
println!("kappa(J) = {:.1} kappa(J_log) = {:.3}", kappa(&j), kappa(&jl));
println!("SE along v_i (log units): {:.3} {:.3} {:.3}", s / d[0], s / d[1], s / d[2]);
let vt = svd.v_t.unwrap();
let v3 = vt.row(idx[2]) * vt[(idx[2], 0)].signum();
println!("v3 (log ka, log ke, log V): {:.3} {:.3} {:.3}", v3[0], v3[1], v3[2]);
}
fn main() {
svd_report(&TT, &Y);
svd_report(&TT[6..], &Y[6..]); // samples from 3 h
}
// Output:
// singular values: 8.7791 3.4781 1.0052
// kappa(J) = 169.9 kappa(J_log) = 8.734
// SE along v_i (log units): 0.010 0.025 0.085
// v3 (log ka, log ke, log V): 0.691 -0.601 0.400
// singular values: 6.0322 1.5269 0.2111
// kappa(J) = 206.5 kappa(J_log) = 28.576
// SE along v_i (log units): 0.013 0.051 0.369
// v3 (log ka, log ke, log V): 0.980 -0.190 0.056All 12 samples: the worst direction \(v_3 \approx (0.69, -0.60, 0.40)\) mixes all three parameters, with SE 0.085 (9 %). From 3 h: \(\sigma_3\) drops from 1.0 to 0.21, the SE along \(v_3\) rises from 0.085 to 0.37 (a factor \(e^{0.37} = 1.45\) either way), and \(v_3 \approx (0.98, -0.19, 0.06)\) is almost pure \(\log k_a\). That matches the slide: the late data determine \(k_e\) and the amplitude, and \(k_a\) is what is left. Note that \(\kappa(J)\) hardly changes (170 → 207) because it is dominated by units, while \(\kappa(J_\text{log})\) triples (8.7 → 28.6): only the log version measures the real problem.
C5.
profile_ka <- function(ka, ts, ys) { # fix ka, re-fit ke and V
f <- nls(ys ~ bateman(ts, ka, ke, V), start = list(ke = 0.2, V = 20))
deviance(f)
}
grid <- c(0.3, 0.5, 0.7, 1, 1.5, 2, 5, 10, 30)
for (d in list(rep(TRUE, 11), late)) {
ts <- tt[d]; ys <- y[d]
f <- nls(ys ~ bateman(ts, ka, ke, V), start = list(ka = 1, ke = 0.2, V = 20))
s2 <- deviance(f) / (length(ys) - 3)
delta <- sapply(grid, function(k) (profile_ka(k, ts, ys) - deviance(f)) / s2)
print(round(rbind(ka = grid, delta = delta), 2))
}
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
# ka 0.30 0.50 0.70 1.00 1.50 2.00 5.00 10.00 30.00
# delta 46.69 69.34 29.19 0.06 44.39 133.61 576.84 840.25 940.49
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
# ka 0.3 0.50 0.70 1.00 1.50 2.00 5.00 10.00 30.00
# delta 12.4 10.19 3.35 0.14 0.42 0.88 1.07 1.07 1.07
# (b) profile interval vs Wald intervals, all samples
fit <- nls(y ~ bateman(tt, ka, ke, V), start = list(ka = 1, ke = 0.2, V = 20))
s2 <- deviance(fit) / (length(y) - 3); ka_hat <- coef(fit)[["ka"]]
crit <- function(k) (profile_ka(k, tt, y) - deviance(fit)) / s2 - 3.84
s2 <- deviance(fit) / (length(y) - 3); ka_hat <- coef(fit)[["ka"]]
crit <- function(k) (profile_ka(k, tt, y) - deviance(fit)) / s2 - 3.84
prof_ci <- c(uniroot(crit, c(0.3, ka_hat))$root, uniroot(crit, c(ka_hat, 30))$root)
se <- sqrt(vcov(fit)["ka", "ka"])
wald <- ka_hat + c(-1.96, 1.96) * se
waldlog <- ka_hat * exp(c(-1.96, 1.96) * se / ka_hat) # Wald in log ka
print(round(rbind(profile = prof_ci, wald = wald, wald_log = waldlog), 4))
# [,1] [,2]
# profile 0.8971 1.1418
# wald 0.8927 1.1374
# wald_log 0.8998 1.1451np.set_printoptions(suppress=True)
from scipy.optimize import brentq
def profile_ka(ka, ts, ys): # fix ka, re-fit ke and V
r = least_squares(lambda q: ys - bateman(ts, ka, q[0], q[1]), [0.2, 20], xtol=1e-12, ftol=1e-12)
return np.sum(r.fun**2)
grid = np.array([0.3, 0.5, 0.7, 1, 1.5, 2, 5, 10, 30])
for d in (np.ones(len(tt), bool), late):
ts, ys = tt[d], y[d]
th, S, _ = fit_pk(ts, ys, [1, 0.2, 20])
s2 = S / (len(ys) - 3)
delta = [(profile_ka(k, ts, ys) - S) / s2 for k in grid]
print(np.round(np.vstack([grid, delta]), 2))
# [[ 0.3 0.5 0.7 1. 1.5 2. 5. 10. 30. ]
# [ 46.69 69.34 29.19 0.06 44.39 133.61 576.84 840.25 940.49]]
# [[ 0.3 0.5 0.7 1. 1.5 2. 5. 10. 30. ]
# [12.4 10.19 3.35 0.14 0.42 0.88 1.07 1.07 1.07]]
# (b) profile interval vs Wald intervals, all samples
th, S, res = fit_pk(tt, y, [1, 0.2, 20])
s2 = S / (len(y) - 3)
crit = lambda k: (profile_ka(k, tt, y) - S) / s2 - 3.84
prof_ci = [brentq(crit, 0.3, th[0]), brentq(crit, th[0], 30)]
J = jacobian(lambda p: bateman(tt, *p), th)
se = np.sqrt(s2 * np.linalg.inv(J.T @ J)[0, 0])
wald = th[0] + np.array([-1.96, 1.96]) * se
wald_log = th[0] * np.exp(np.array([-1.96, 1.96]) * se / th[0])
print(np.round(np.vstack([prof_ci, wald, wald_log]), 4))
# [[0.8971 1.1418]
# [0.8927 1.1374]
# [0.8998 1.1451]]// rust/examples/identifiability_c5.rs — cargo run --example identifiability_c5
// C5: profile likelihood of ka (others re-fitted), and profile vs Wald intervals.
#![allow(dead_code)]
use nalgebra::{DMatrix, DVector};
// One-compartment model with oral absorption, dose D = 100 mg (mg/L)
const D: f64 = 100.0; // oral dose, mg
fn bateman(t: f64, ka: f64, ke: f64, v: f64) -> f64 {
D * ka / (v * (ka - ke)) * ((-ke * t).exp() - (-ka * t).exp())
}
const TT: [f64; 12] = [0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 10.0, 12.0];
const Y: [f64; 12] = [1.02, 1.88, 2.34, 2.98, 3.27, 3.26, 3.17, 2.77, 1.92, 1.23, 1.00, 0.61];
// Central-difference Jacobian of f at p (like numDeriv::jacobian, less refined)
fn jacobian(f: &dyn Fn(&[f64]) -> Vec<f64>, p: &[f64]) -> DMatrix<f64> {
let n = f(p).len();
let mut j = DMatrix::zeros(n, p.len());
for k in 0..p.len() {
let h = 1e-5 * p[k].abs().max(1.0);
let (mut pp, mut pm) = (p.to_vec(), p.to_vec());
pp[k] += h;
pm[k] -= h;
let (fp, fm) = (f(&pp), f(&pm));
for i in 0..n { j[(i, k)] = (fp[i] - fm[i]) / (2.0 * h); }
}
j
}
// Levenberg-Marquardt for min sum r(p)^2, hand-written (R: nls / nls.lm, Python: least_squares)
fn levmar(r: &dyn Fn(&[f64]) -> Vec<f64>, p0: &[f64]) -> Vec<f64> {
let ss = |p: &[f64]| -> f64 { let v = r(p); if v.iter().all(|x| x.is_finite()) { v.iter().map(|x| x * x).sum() } else { f64::INFINITY } };
let (mut p, mut mu) = (p0.to_vec(), 1e-3);
for _ in 0..500 {
let j = jacobian(r, &p); // Jacobian of the residuals
let rv = DVector::from_vec(r(&p));
let jtj = j.transpose() * &j;
let g = j.transpose() * &rv;
loop {
let a = &jtj + DMatrix::from_diagonal(&jtj.diagonal()) * mu;
let step = a.lu().solve(&(-&g)).unwrap();
let pn: Vec<f64> = p.iter().zip(step.iter()).map(|(a, b)| a + b).collect();
if ss(&pn) <= ss(&p) {
let small = step.norm() < 1e-12 * (1.0 + DVector::from_vec(p.clone()).norm());
p = pn;
mu = (mu / 10.0).max(1e-12);
if small { return p; }
break;
}
mu *= 10.0;
if mu > 1e12 { return p; }
}
}
p
}
// Residuals y - C(t) for the one-compartment model at the sample times ts
fn resid(ts: &[f64], ys: &[f64]) -> impl Fn(&[f64]) -> Vec<f64> {
let (ts, ys) = (ts.to_vec(), ys.to_vec());
move |p: &[f64]| ts.iter().zip(&ys).map(|(ti, yi)| yi - bateman(*ti, p[0], p[1], p[2])).collect()
}
fn sse(r: &dyn Fn(&[f64]) -> Vec<f64>, p: &[f64]) -> f64 { r(p).iter().map(|x| x * x).sum() }
// fix ka, re-fit ke and V; return the minimal SSE
fn profile_ka(ka: f64, ts: &[f64], ys: &[f64]) -> f64 {
let r = |q: &[f64]| -> Vec<f64> { ts.iter().zip(ys).map(|(t, y)| y - bateman(*t, ka, q[0], q[1])).collect() };
let q = levmar(&r, &[0.2, 20.0]);
sse(&r, &q)
}
// bisection for a sign change of f on [a, b] (R: uniroot, Python: brentq)
fn bisect(f: &dyn Fn(f64) -> f64, mut a: f64, mut b: f64) -> f64 {
let fa = f(a);
for _ in 0..60 {
let m = 0.5 * (a + b);
if (f(m) > 0.0) == (fa > 0.0) { a = m } else { b = m }
}
0.5 * (a + b)
}
fn main() {
let grid = [0.3, 0.5, 0.7, 1.0, 1.5, 2.0, 5.0, 10.0, 30.0];
for start in [0, 6] { // all samples; samples from 3 h
let (ts, ys) = (&TT[start..], &Y[start..]);
let r = resid(ts, ys);
let th = levmar(&r, &[1.0, 0.2, 20.0]);
let (smin, s2) = (sse(&r, &th), sse(&r, &th) / (ts.len() - 3) as f64);
let row: Vec<String> = grid.iter().map(|&k| format!("{:.2}", (profile_ka(k, ts, ys) - smin) / s2)).collect();
println!("delta: {}", row.join(" "));
}
// (b) profile interval vs Wald intervals, all samples
let r = resid(&TT, &Y);
let th = levmar(&r, &[1.0, 0.2, 20.0]);
let (smin, s2) = (sse(&r, &th), sse(&r, &th) / 9.0);
let crit = |k: f64| (profile_ka(k, &TT, &Y) - smin) / s2 - 3.84;
let (lo, hi) = (bisect(&crit, 0.3, th[0]), bisect(&crit, th[0], 30.0));
let j = jacobian(&r, &th);
let se = ((j.transpose() * &j).try_inverse().unwrap()[(0, 0)] * s2).sqrt();
println!("profile {:.4} {:.4}", lo, hi);
println!("wald {:.4} {:.4}", th[0] - 1.96 * se, th[0] + 1.96 * se);
println!("wald_log {:.4} {:.4}", th[0] * (-1.96 * se / th[0]).exp(), th[0] * (1.96 * se / th[0]).exp());
}
// Output:
// delta: 46.69 69.34 29.19 0.06 44.39 133.61 576.84 840.25 940.49
// delta: 12.40 10.19 3.35 0.14 0.42 0.88 1.07 1.07 1.07
// profile 0.8971 1.1418
// wald 0.8927 1.1374
// wald_log 0.8998 1.1451With all samples the profile rises steeply on both sides (\(\Delta = 29\) at 0.7 and 44 at 1.5). The profile interval \((0.897, 1.142)\) is slightly asymmetric; the Wald interval in \(\log k_a\) is a little closer to it than the plain Wald interval on both sides; all three agree to within 0.01. From 3 h, \(\Delta\) crosses 3.84 just below 0.7 on the left but never on the right: it stays at 1.07 from \(k_a = 5\) to 30 (and to infinity, where absorption is instantaneous). The 95 % profile interval is \((0.68, \infty)\). A report should say “\(k_a > 0.68\) /h; the data do not bound it from above”, not “\(k_a = 1.12 \pm 0.41\)”. The large values at \(k_a = 0.3\) and 0.5 come from the hump between the true minimum and the flip-flop branch.
C6.
pk2 <- function(t, ka, k10, k12, k21, V, D = 100) {
s <- k10 + k12 + k21; q <- sqrt(s^2 - 4 * k21 * k10)
al <- (s + q) / 2; be <- (s - q) / 2 # the two disposition rates
ka * D / V * ((k21 - al) / ((ka - al) * (be - al)) * exp(-al * t) +
(k21 - be) / ((ka - be) * (al - be)) * exp(-be * t) +
(k21 - ka) / ((al - ka) * (be - ka)) * exp(-ka * t))
}
p2 <- c(ka = 1, k10 = 0.2, k12 = 0.3, k21 = 0.15, V = 20)
sloppy <- function(ts) {
J <- jacobian(function(lp) do.call(pk2, c(list(ts), as.list(exp(lp)))), log(p2))
e <- eigen(crossprod(J))
cat("eigenvalues:", signif(e$values, 3), "\n")
cat("decades:", round(log10(e$values[1] / e$values), 2), "\n")
cat("SE along eigenvectors (sigma = 0.1):", signif(0.1 / sqrt(e$values), 3), "\n")
v5 <- e$vectors[, 5] * sign(e$vectors[1, 5])
cat("sloppiest (ka, k10, k12, k21, V):", round(v5, 2), "\n")
}
round(pk2(c(1, 6, 24), 1, 0.2, 0.3, 0.15, 20), 4)
# [1] 2.4087 0.9606 0.2882
sloppy(tt)
# eigenvalues: 43 5.5 0.482 0.0205 0.00134
# decades: 0 0.89 1.95 3.32 4.51
# SE along eigenvectors (sigma = 0.1): 0.0153 0.0426 0.144 0.699 2.73
# sloppiest (ka, k10, k12, k21, V): 0.26 -0.59 -0.28 -0.66 0.25
sloppy(c(tt, 24, 36, 48))
# eigenvalues: 43.1 5.56 0.593 0.144 0.00821
# decades: 0 0.89 1.86 2.48 3.72
# SE along eigenvectors (sigma = 0.1): 0.0152 0.0424 0.13 0.263 1.1
# sloppiest (ka, k10, k12, k21, V): 0.41 -0.41 -0.67 -0.29 0.37def pk2(t, ka, k10, k12, k21, V, D=100):
s = k10 + k12 + k21; q = np.sqrt(s**2 - 4 * k21 * k10)
al, be = (s + q) / 2, (s - q) / 2 # the two disposition rates
return ka * D / V * ((k21 - al) / ((ka - al) * (be - al)) * np.exp(-al * t) +
(k21 - be) / ((ka - be) * (al - be)) * np.exp(-be * t) +
(k21 - ka) / ((al - ka) * (be - ka)) * np.exp(-ka * t))
p2 = np.array([1, 0.2, 0.3, 0.15, 20])
def sloppy(ts):
J = jacobian(lambda lp: pk2(ts, *np.exp(lp)), np.log(p2))
lam, vec = np.linalg.eigh(J.T @ J)
lam, vec = lam[::-1], vec[:, ::-1] # largest first, as in R
print("eigenvalues:", np.array2string(lam, precision=3, suppress_small=False))
print("decades:", np.round(np.log10(lam[0] / lam), 2))
print("SE along eigenvectors (sigma = 0.1):", np.array2string(0.1 / np.sqrt(lam), precision=3))
v5 = vec[:, 4] * np.sign(vec[0, 4])
print("sloppiest (ka, k10, k12, k21, V):", np.round(v5, 2))
print(np.round(pk2(np.array([1, 6, 24]), 1, 0.2, 0.3, 0.15, 20), 4))
# [2.4087 0.9606 0.2882]
sloppy(tt)
# eigenvalues: [4.300e+01 5.503e+00 4.815e-01 2.046e-02 1.343e-03]
# decades: [0. 0.89 1.95 3.32 4.51]
# SE along eigenvectors (sigma = 0.1): [0.015 0.043 0.144 0.699 2.728]
# sloppiest (ka, k10, k12, k21, V): [ 0.26 -0.59 -0.28 -0.66 0.25]
sloppy(np.concatenate([tt, [24, 36, 48]]))
# eigenvalues: [4.314e+01 5.561e+00 5.929e-01 1.441e-01 8.212e-03]
# decades: [0. 0.89 1.86 2.48 3.72]
# SE along eigenvectors (sigma = 0.1): [0.015 0.042 0.13 0.263 1.104]
# sloppiest (ka, k10, k12, k21, V): [ 0.41 -0.41 -0.67 -0.29 0.37]// rust/examples/identifiability_c6.rs — cargo run --example identifiability_c6
// C6: a sloppy model: eigenvalues of J^T J for the two-compartment PK model.
#![allow(dead_code)]
use nalgebra::{DMatrix, DVector};
// One-compartment model with oral absorption, dose D = 100 mg (mg/L)
const D: f64 = 100.0; // oral dose, mg
fn bateman(t: f64, ka: f64, ke: f64, v: f64) -> f64 {
D * ka / (v * (ka - ke)) * ((-ke * t).exp() - (-ka * t).exp())
}
const TT: [f64; 12] = [0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 10.0, 12.0];
const Y: [f64; 12] = [1.02, 1.88, 2.34, 2.98, 3.27, 3.26, 3.17, 2.77, 1.92, 1.23, 1.00, 0.61];
// Central-difference Jacobian of f at p (like numDeriv::jacobian, less refined)
fn jacobian(f: &dyn Fn(&[f64]) -> Vec<f64>, p: &[f64]) -> DMatrix<f64> {
let n = f(p).len();
let mut j = DMatrix::zeros(n, p.len());
for k in 0..p.len() {
let h = 1e-5 * p[k].abs().max(1.0);
let (mut pp, mut pm) = (p.to_vec(), p.to_vec());
pp[k] += h;
pm[k] -= h;
let (fp, fm) = (f(&pp), f(&pm));
for i in 0..n { j[(i, k)] = (fp[i] - fm[i]) / (2.0 * h); }
}
j
}
// Levenberg-Marquardt for min sum r(p)^2, hand-written (R: nls / nls.lm, Python: least_squares)
fn levmar(r: &dyn Fn(&[f64]) -> Vec<f64>, p0: &[f64]) -> Vec<f64> {
let ss = |p: &[f64]| -> f64 { let v = r(p); if v.iter().all(|x| x.is_finite()) { v.iter().map(|x| x * x).sum() } else { f64::INFINITY } };
let (mut p, mut mu) = (p0.to_vec(), 1e-3);
for _ in 0..500 {
let j = jacobian(r, &p); // Jacobian of the residuals
let rv = DVector::from_vec(r(&p));
let jtj = j.transpose() * &j;
let g = j.transpose() * &rv;
loop {
let a = &jtj + DMatrix::from_diagonal(&jtj.diagonal()) * mu;
let step = a.lu().solve(&(-&g)).unwrap();
let pn: Vec<f64> = p.iter().zip(step.iter()).map(|(a, b)| a + b).collect();
if ss(&pn) <= ss(&p) {
let small = step.norm() < 1e-12 * (1.0 + DVector::from_vec(p.clone()).norm());
p = pn;
mu = (mu / 10.0).max(1e-12);
if small { return p; }
break;
}
mu *= 10.0;
if mu > 1e12 { return p; }
}
}
p
}
// Residuals y - C(t) for the one-compartment model at the sample times ts
fn resid(ts: &[f64], ys: &[f64]) -> impl Fn(&[f64]) -> Vec<f64> {
let (ts, ys) = (ts.to_vec(), ys.to_vec());
move |p: &[f64]| ts.iter().zip(&ys).map(|(ti, yi)| yi - bateman(*ti, p[0], p[1], p[2])).collect()
}
fn sse(r: &dyn Fn(&[f64]) -> Vec<f64>, p: &[f64]) -> f64 { r(p).iter().map(|x| x * x).sum() }
// Two-compartment model with oral absorption: closed-form tri-exponential solution
fn pk2(t: f64, p: &[f64]) -> f64 {
let (ka, k10, k12, k21, v) = (p[0], p[1], p[2], p[3], p[4]);
let s = k10 + k12 + k21;
let q = (s * s - 4.0 * k21 * k10).sqrt();
let (al, be) = ((s + q) / 2.0, (s - q) / 2.0); // the two disposition rates
ka * 100.0 / v * ((k21 - al) / ((ka - al) * (be - al)) * (-al * t).exp()
+ (k21 - be) / ((ka - be) * (al - be)) * (-be * t).exp()
+ (k21 - ka) / ((al - ka) * (be - ka)) * (-ka * t).exp())
}
fn sloppy(ts: &[f64]) {
let lp2: Vec<f64> = [1.0_f64, 0.2, 0.3, 0.15, 20.0].iter().map(|x| x.ln()).collect();
let f = |lp: &[f64]| -> Vec<f64> {
let p: Vec<f64> = lp.iter().map(|x| x.exp()).collect();
ts.iter().map(|t| pk2(*t, &p)).collect()
};
let j = jacobian(&f, &lp2);
let eig = (j.transpose() * &j).symmetric_eigen();
let mut idx: Vec<usize> = (0..5).collect(); // sort largest first
idx.sort_by(|a, b| eig.eigenvalues[*b].partial_cmp(&eig.eigenvalues[*a]).unwrap());
let lam: Vec<f64> = idx.iter().map(|&i| eig.eigenvalues[i]).collect();
let fmt = |v: Vec<String>| v.join(" ");
println!("eigenvalues: {}", fmt(lam.iter().map(|x| format!("{:.3e}", x)).collect()));
println!("decades: {}", fmt(lam.iter().map(|x| format!("{:.2}", (lam[0] / x).log10())).collect()));
println!("SE along eigenvectors (sigma = 0.1): {}", fmt(lam.iter().map(|x| format!("{:.3}", 0.1 / x.sqrt())).collect()));
let v5 = eig.eigenvectors.column(idx[4]) * eig.eigenvectors[(0, idx[4])].signum();
println!("sloppiest (ka, k10, k12, k21, V): {}", fmt(v5.iter().map(|x| format!("{:.2}", x)).collect()));
}
fn main() {
let p = [1.0, 0.2, 0.3, 0.15, 20.0];
println!("{:.4} {:.4} {:.4}", pk2(1.0, &p), pk2(6.0, &p), pk2(24.0, &p));
sloppy(&TT);
let mut longer = TT.to_vec();
longer.extend([24.0, 36.0, 48.0]);
sloppy(&longer);
}
// Output:
// 2.4087 0.9606 0.2882
// eigenvalues: 4.300e1 5.503e0 4.815e-1 2.046e-2 1.343e-3
// decades: 0.00 0.89 1.95 3.32 4.51
// SE along eigenvectors (sigma = 0.1): 0.015 0.043 0.144 0.699 2.728
// sloppiest (ka, k10, k12, k21, V): 0.26 -0.59 -0.28 -0.66 0.25
// eigenvalues: 4.314e1 5.561e0 5.929e-1 1.441e-1 8.212e-3
// decades: 0.00 0.89 1.86 2.48 3.72
// SE along eigenvectors (sigma = 0.1): 0.015 0.042 0.130 0.263 1.104
// sloppiest (ka, k10, k12, k21, V): 0.41 -0.41 -0.67 -0.29 0.37The eigenvalues are spread over 4.5 decades, roughly one decade each, with no gap: a sloppy spectrum. The stiffest combination has SE 0.015 (1.5 %), the sloppiest 2.7 in log units: a factor \(e^{2.7} \approx 15\) either way. The sloppiest direction mixes all five parameters, mostly \(k_{10}\) and \(k_{21}\) moving together, against \(k_a\) and \(V\): data up to 12 h barely separate elimination from the slow return from the periphery. Adding samples at 24–48 h raises the two smallest eigenvalues (the sloppiest SE drops from 2.7 to 1.1) and leaves the large ones unchanged; the spectrum still spans 3.7 decades. Longer sampling helps the combinations that act late; it does not make the model stiff.
C7.
se_design <- function(ts, p = c(1, 0.2, 20), sigma = 0.1) {
J <- jacobian(function(lp) bateman(ts, exp(lp[1]), exp(lp[2]), exp(lp[3])), log(p))
sigma * sqrt(diag(solve(crossprod(J)))) # SE of log ka, log ke, log V
}
designs <- list(late = c(3, 4, 6, 8, 10, 12), early = c(0.5, 1, 2, 4, 8, 12),
peak = c(1, 2, 3, 4, 6, 12))
print(round(t(sapply(designs, se_design)), 3))
# [,1] [,2] [,3]
# late 0.398 0.115 0.061
# early 0.101 0.087 0.059
# peak 0.116 0.101 0.059
# (b) prior on log ka, sparse data
fit_prior <- function(tau, mu = log(1.2), sigma = 0.1) {
res <- function(lp) c((y[late] - bateman(tt[late], exp(lp[1]), exp(lp[2]), exp(lp[3]))) / sigma,
(lp[1] - mu) / tau)
fp <- minpack.lm::nls.lm(par = log(c(1, 0.2, 20)), fn = res)
Ja <- jacobian(res, fp$par)
c(tau = tau, ka = exp(fp$par[1]), se_logka = sqrt(solve(crossprod(Ja))[1, 1]))
}
print(round(t(sapply(c(0.1, 0.25, 0.5, 1, 2), fit_prior)), 3))
# tau ka se_logka
# [1,] 0.10 1.197 0.098
# [2,] 0.25 1.182 0.225
# [3,] 0.50 1.156 0.350
# [4,] 1.00 1.134 0.428
# [5,] 2.00 1.125 0.455def se_design(ts, p=(1, 0.2, 20), sigma=0.1):
J = jacobian(lambda lp: bateman(ts, *np.exp(lp)), np.log(p))
return sigma * np.sqrt(np.diag(np.linalg.inv(J.T @ J))) # SE of log ka, log ke, log V
designs = {"late": [3, 4, 6, 8, 10, 12], "early": [0.5, 1, 2, 4, 8, 12], "peak": [1, 2, 3, 4, 6, 12]}
for name, ts in designs.items():
print(f"{name:6s}", np.round(se_design(np.array(ts, float)), 3))
# late [0.398 0.115 0.061]
# early [0.101 0.087 0.059]
# peak [0.116 0.101 0.059]
# (b) prior on log ka, sparse data
def fit_prior(tau, mu=np.log(1.2), sigma=0.1):
res = lambda lp: np.append((y[late] - bateman(tt[late], *np.exp(lp))) / sigma, (lp[0] - mu) / tau)
r = least_squares(res, np.log([1, 0.2, 20]), xtol=1e-12, ftol=1e-12)
Ja = jacobian(res, r.x)
return tau, np.exp(r.x[0]), np.sqrt(np.linalg.inv(Ja.T @ Ja)[0, 0])
for tau in (0.1, 0.25, 0.5, 1, 2):
print(np.round(fit_prior(tau), 3))
# [0.1 1.197 0.098]
# [0.25 1.182 0.225]
# [0.5 1.156 0.35 ]
# [1. 1.134 0.428]
# [2. 1.125 0.455]// rust/examples/identifiability_c7.rs — cargo run --example identifiability_c7
// C7: fixes: compare sampling designs; a prior on log ka as an extra residual.
#![allow(dead_code)]
use nalgebra::{DMatrix, DVector};
// One-compartment model with oral absorption, dose D = 100 mg (mg/L)
const D: f64 = 100.0; // oral dose, mg
fn bateman(t: f64, ka: f64, ke: f64, v: f64) -> f64 {
D * ka / (v * (ka - ke)) * ((-ke * t).exp() - (-ka * t).exp())
}
const TT: [f64; 12] = [0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 10.0, 12.0];
const Y: [f64; 12] = [1.02, 1.88, 2.34, 2.98, 3.27, 3.26, 3.17, 2.77, 1.92, 1.23, 1.00, 0.61];
// Central-difference Jacobian of f at p (like numDeriv::jacobian, less refined)
fn jacobian(f: &dyn Fn(&[f64]) -> Vec<f64>, p: &[f64]) -> DMatrix<f64> {
let n = f(p).len();
let mut j = DMatrix::zeros(n, p.len());
for k in 0..p.len() {
let h = 1e-5 * p[k].abs().max(1.0);
let (mut pp, mut pm) = (p.to_vec(), p.to_vec());
pp[k] += h;
pm[k] -= h;
let (fp, fm) = (f(&pp), f(&pm));
for i in 0..n { j[(i, k)] = (fp[i] - fm[i]) / (2.0 * h); }
}
j
}
// Levenberg-Marquardt for min sum r(p)^2, hand-written (R: nls / nls.lm, Python: least_squares)
fn levmar(r: &dyn Fn(&[f64]) -> Vec<f64>, p0: &[f64]) -> Vec<f64> {
let ss = |p: &[f64]| -> f64 { let v = r(p); if v.iter().all(|x| x.is_finite()) { v.iter().map(|x| x * x).sum() } else { f64::INFINITY } };
let (mut p, mut mu) = (p0.to_vec(), 1e-3);
for _ in 0..500 {
let j = jacobian(r, &p); // Jacobian of the residuals
let rv = DVector::from_vec(r(&p));
let jtj = j.transpose() * &j;
let g = j.transpose() * &rv;
loop {
let a = &jtj + DMatrix::from_diagonal(&jtj.diagonal()) * mu;
let step = a.lu().solve(&(-&g)).unwrap();
let pn: Vec<f64> = p.iter().zip(step.iter()).map(|(a, b)| a + b).collect();
if ss(&pn) <= ss(&p) {
let small = step.norm() < 1e-12 * (1.0 + DVector::from_vec(p.clone()).norm());
p = pn;
mu = (mu / 10.0).max(1e-12);
if small { return p; }
break;
}
mu *= 10.0;
if mu > 1e12 { return p; }
}
}
p
}
// Residuals y - C(t) for the one-compartment model at the sample times ts
fn resid(ts: &[f64], ys: &[f64]) -> impl Fn(&[f64]) -> Vec<f64> {
let (ts, ys) = (ts.to_vec(), ys.to_vec());
move |p: &[f64]| ts.iter().zip(&ys).map(|(ti, yi)| yi - bateman(*ti, p[0], p[1], p[2])).collect()
}
fn sse(r: &dyn Fn(&[f64]) -> Vec<f64>, p: &[f64]) -> f64 { r(p).iter().map(|x| x * x).sum() }
// predicted SE of log ka, log ke, log V for sample times ts, at a guessed theta
fn se_design(ts: &[f64], p: [f64; 3], sigma: f64) -> Vec<f64> {
let f = |lp: &[f64]| -> Vec<f64> { ts.iter().map(|t| bateman(*t, lp[0].exp(), lp[1].exp(), lp[2].exp())).collect() };
let lp: Vec<f64> = p.iter().map(|x| x.ln()).collect();
let j = jacobian(&f, &lp);
let c = (j.transpose() * &j).try_inverse().unwrap();
(0..3).map(|i| sigma * c[(i, i)].sqrt()).collect()
}
fn main() {
let designs: [(&str, [f64; 6]); 3] = [("late", [3.0, 4.0, 6.0, 8.0, 10.0, 12.0]),
("early", [0.5, 1.0, 2.0, 4.0, 8.0, 12.0]), ("peak", [1.0, 2.0, 3.0, 4.0, 6.0, 12.0])];
for (name, ts) in designs.iter() {
let se = se_design(ts, [1.0, 0.2, 20.0], 0.1);
println!("{:6} {:.3} {:.3} {:.3}", name, se[0], se[1], se[2]);
}
// (b) prior on log ka (centre log 1.2, SD tau), sparse data, noise SD 0.1
for tau in [0.1, 0.25, 0.5, 1.0, 2.0] {
let res = |lp: &[f64]| -> Vec<f64> {
let mut r: Vec<f64> = TT[6..].iter().zip(&Y[6..])
.map(|(t, y)| (y - bateman(*t, lp[0].exp(), lp[1].exp(), lp[2].exp())) / 0.1).collect();
r.push((lp[0] - 1.2_f64.ln()) / tau);
r
};
let lp = levmar(&res, &[0.0, 0.2_f64.ln(), 20.0_f64.ln()]);
let ja = jacobian(&res, &lp);
let c = (ja.transpose() * &ja).try_inverse().unwrap();
println!("tau {:.2} ka {:.3} se_logka {:.3}", tau, lp[0].exp(), c[(0, 0)].sqrt());
}
}
// Output:
// late 0.398 0.115 0.061
// early 0.101 0.087 0.059
// peak 0.116 0.101 0.059
// tau 0.10 ka 1.197 se_logka 0.098
// tau 0.25 ka 1.182 se_logka 0.225
// tau 0.50 ka 1.156 se_logka 0.350
// tau 1.00 ka 1.134 se_logka 0.428
// tau 2.00 ka 1.125 se_logka 0.455Before any experiment, the late design predicts an SE of 0.40 for \(\log k_a\) (a factor 1.5 either way, and the profile in C5 shows it is really unbounded), while the early design gives 0.10 with the same six samples, and even improves \(k_e\). The peak design is nearly as good: samples at 1 and 2 h already carry most of the absorption information. With a prior, the SE of \(\log k_a\) is always a little below \(\tau\) when \(\tau \le 0.5\): the estimate is mostly prior, and \(\hat k_a\) stays near the prior centre 1.2. For large \(\tau\) the SE approaches 0.46, the linearised SE of the data alone (with \(\sigma = 0.1\)), which the profile showed to be meaningless on the upper side. A prior is only informative about the data when the posterior SE is clearly smaller than \(\tau\).
Where this leads
- Part 10, Constraints and linear programming: bounds such as \(k_a > k_e\) or \(F \le 1\) as constraints in the optimiser, and what the Lagrange multipliers of active bounds say.
- The capstone (if used): fit an ODE model to a real time course and report what is determined, using the checklist of the lecture (multistart, SVD of \(J\), profiles, prediction uncertainty).
- We linearised (Wald SEs) and profiled with a \(\chi^2_1\) threshold, both large-sample approximations. Bootstrap and Bayesian sampling (MCMC) give uncertainty without them; they need many model fits, which is where fast and robust fitting (Nonlinear least squares and ODE fitting) pays off.
- Structural identifiability can also be decided symbolically, before any data, for ODE models of moderate size (differential algebra, as in the tools DAISY or StructuralIdentifiability.jl). We did it by hand and from the rank of \(J\).