Tutorial 1: theophylline, one subject, then twelve¶
Theophylline, an oral bronchodilator, in 12 subjects (R's Theoph data): one dose each,
then 11 concentrations over 24 hours. It is the textbook example of a population PK fit,
fitted in every pharmacometrics course, so the answers are known. This tutorial fits it in
the order a modeller learns it, and checks each answer against R's own fits (nls for a
subject alone, nlme for the population):
- one subject, by maximum likelihood (
method optimize); - the same subject by Bayesian sampling (
method nuts), next to it; - each subject alone, twelve fits;
- all twelve together, with ka and CL varying between subjects (
method laplace), and what that changes for the subjects the data say least about.
Every section ends with checks against R's numbers.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tenqsp as tq
import tenqsp_fit as tf
data = pd.read_csv("../examples/theoph.csv")
# R's own fits of the same data, stored in the repository (log values and their SEs)
REF = "../../validation/theophylline/"
ref_alone = pd.read_csv(REF + "reference_individual_nls.csv")
ref_pop = pd.read_csv(REF + "reference_population_nlme.csv").set_index("quantity")
print(data.head())
fig, ax = plt.subplots(figsize=(6, 3.5))
for _, d in data.groupby("Subject"):
ax.plot(d.Time, d.conc, "o-", ms=3, lw=0.8)
ax.set_xlabel("time (h)")
ax.set_ylabel("concentration (mg/L)")
ax.set_title("theophylline, 12 subjects")
Subject Wt Dose Time conc 0 1 79.6 4.02 0.00 0.74 1 1 79.6 4.02 0.25 2.84 2 1 79.6 4.02 0.57 6.57 3 1 79.6 4.02 1.12 10.50 4 1 79.6 4.02 2.02 9.66
Text(0.5, 1.0, 'theophylline, 12 subjects')
One row per measurement; the dose (mg/kg) is a column. The model is one compartment with
first-order absorption, written with ka, CL and the elimination rate ke (so the volume is
CL/ke), the parameterisation of R's SSfol:
model = tq.Model.from_text("""
model theoph
param ka=1.6, CL=0.04, ke=0.086
d_t(depot) = -ka*depot
d_t(centr) = ka*depot - ke*centr
observable conc = centr*ke/CL
""")
1. One subject¶
Subject 1 alone. The fit is built in Python here, one call per line of fit text
(p.to_text() prints it): which rows are data, where the dose goes, which observable the
measurements are, what is estimated, and the residual error.
def one_subject(subject):
p = tf.Problem(model, name=f"subject_{subject}")
p.data(data[data.Subject == subject], ID="Subject", TIME="Time", DV="conc")
p.doses(column="Dose", at=0, into="depot")
p.observe("conc", "DV")
p.estimate("ka", 1.5)
p.estimate("CL", 0.04)
p.estimate("ke", 0.08)
p.error("conc", tf.additive(1))
return p
p1 = one_subject(1)
print(p1.to_text())
fit subject_1 # data: a table given in Python (11 rows), not written here doses Dose at t=0 into depot observe conc = DV estimate ka = 1.5 estimate CL = 0.04 estimate ke = 0.08 error conc ~ additive(1)
r1 = tf.fit(p1, method="optimize", progress="none")
print(r1)
subject_1: method optimize (L-BFGS-B), converged; -2LL 20.8487 (11 measurements)
starts: 1; 1 at the best fit (within 0.1); redrawn 0; failed runs during the fit 0; 17 s
quantity estimate SE RSE % 95 % CI also
ka 1.7774 0.23 12.9 (1.379, 2.291)
CL 0.019923 0.002171 10.9 (0.01609, 0.02467)
ke 0.053955 0.007784 14.4 (0.04067, 0.07159)
conc.additive 0.62421 0.1331 21.3 (0.411, 0.948)
doctor: 4 notes
note determination: condition number of the curvature 104; no ridge, every quantity determined within a factor 10.
note optima: one start: other optima were not looked for.
what to do: options starts=8 looks from 8 starts.
note tolerance check: at rtol 1e-08 the -2LL changes by 1.1e-05 and the estimates by less than 0.001 SE; rtol 1e-06 is enough.
note gradient check: exact gradients agree with differences (at rtol 1e-08) to 0.011 % (3 directions).
The printout ends with the doctor: no ridge (every quantity determined within a factor 10), one start (other optima were not looked for), and two numerical checks, that a tighter solver tolerance changes nothing that matters and that the exact gradients agree with finite differences.
R's nls gives the same estimates. The standard errors differ in two known ways:
nlsis least squares and estimates the residual variance as RSS/(n − p); tenqsp-fit maximises the likelihood, RSS/n. That makes tenqsp-fit's SEs smaller by √((n − p)/n) = √(8/11) = 0.85, which is what CL and ke show.nlsapproximates the curvature by the Gauss–Newton product of first derivatives; tenqsp-fit uses the curvature of −2LL itself. They differ most for the parameter the model is most nonlinear in, here ka (0.75).
r1_ref = ref_alone[ref_alone.Subject == 1].set_index("quantity")
se1 = r1.table().set_index("quantity")["SE"]
for q in ["ka", "CL", "ke"]:
ref = np.exp(r1_ref.loc[f"log {q}", "estimate"])
ratio = (se1[q] / r1.estimates[q]) / r1_ref.loc[f"log {q}", "se_log"]
print(f"{q:3s} tenqsp-fit {r1.estimates[q]:.5g} nls {ref:.5g} SE ratio {ratio:.3f}")
assert abs(r1.estimates[q] / ref - 1) < 1e-3
assert 0.7 < ratio < 0.9
ka tenqsp-fit 1.7774 nls 1.7774 SE ratio 0.749 CL tenqsp-fit 0.019923 nls 0.019923 SE ratio 0.856 ke tenqsp-fit 0.053955 nls 0.053954 SE ratio 0.844
2. The same subject, by sampling¶
method nuts draws from the posterior distribution: the likelihood times a prior for each
quantity. None is written here, so each gets the default, a wide lognormal centred on its
start (95 % within a factor 50). The defaults: 4 chains, each of 1000 warmup steps and 1000
draws, each on its own core.
p1n = one_subject(1)
p1n.method("nuts")
p1n.options(seed=1)
r1n = tf.fit(p1n, progress="none")
print(r1n)
/opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html from .autonotebook import tqdm as notebook_tqdm
subject_1: method nuts, sampled; 4 chains x 1000 draws (after 1000 warmup), 0 divergences, R-hat <= 1.002, ESS >= 1989; 74 s started from optimize: -2LL 20.8487 (11 measurements); -2LL at the posterior medians 21.6494 quantity median SD 95 % interval R-hat ESS prior ka 1.7824 0.319 (1.265, 2.519) 1.000 2382 lognormal(median=1.5, sdlog=2) (default) CL 0.019836 0.00295 (0.01427, 0.026) 1.002 1989 lognormal(median=0.04, sdlog=2) (default) ke 0.053628 0.0106 (0.03466, 0.07777) 1.002 2063 lognormal(median=0.08, sdlog=2) (default) conc.additive 0.76512 0.231 (0.4916, 1.396) 1.001 2320 lognormal(median=1, sdlog=2) (default) doctor: 4 notes note convergence: R-hat, effective sample sizes, divergences, BFMI and tree depth: all within their limits. note prior and data: the data narrowed every prior to less than 50 % of its width. note tolerance check: at rtol 1e-08, -2 log posterior changes by at most 1.6e-05 over 20 draws; rtol 1e-06 is enough. note gradient check: exact gradients agree with differences (at rtol 1e-08) to 0.019 % (3 directions).
The data, not the wide priors, decide: the posterior medians of ka, CL and ke sit on the maximum-likelihood estimates. The 95 % intervals are wider, by about a third. Section 1's intervals come from the curvature at the estimates, which assumes many measurements; with 11 measurements and 4 quantities the posterior also carries how uncertain the residual SD is. The maximum-likelihood residual SD (0.62) is the one that is biased low with few measurements, by √((n − p)/n) as in section 1, and the posterior median is higher (0.77).
Sampling earns its cost in exactly such cases: few data, a weakly determined quantity, a skewed or bounded one, or prior knowledge that should count.
ml, post = r1.table().set_index("quantity"), r1n.table().set_index("quantity")
print(pd.DataFrame({"optimize": ml.estimate, "nuts median": post["median"],
"optimize 95 %": ml["CI 2.5 %"].round(4).astype(str) + " to "
+ ml["CI 97.5 %"].round(4).astype(str),
"nuts 95 %": post["CI 2.5 %"].round(4).astype(str) + " to "
+ post["CI 97.5 %"].round(4).astype(str)})) # fmt: skip
for q in ["ka", "CL", "ke"]:
assert abs(np.log(post["median"][q] / ml.estimate[q])) < 0.25 * se1[q] / ml.estimate[q]
for q in ml.index: # wider intervals, every quantity
assert post["CI 97.5 %"][q] - post["CI 2.5 %"][q] > ml["CI 97.5 %"][q] - ml["CI 2.5 %"][q]
assert r1n.doctor().count("warning") == 0
optimize nuts median optimize 95 % nuts 95 % quantity ka 1.777412 1.782377 1.3792 to 2.2905 1.2646 to 2.5193 CL 0.019923 0.019836 0.0161 to 0.0247 0.0143 to 0.026 ke 0.053955 0.053628 0.0407 to 0.0716 0.0347 to 0.0778 conc.additive 0.624210 0.765125 0.411 to 0.948 0.4916 to 1.3958
3. Each subject alone¶
Twelve fits, one per subject, as R's nlsList does.
alone = {}
for subject in sorted(data.Subject.unique()):
r = tf.fit(one_subject(subject), method="optimize", progress="none")
assert r.status == "converged"
alone[subject] = r
table_alone = pd.DataFrame(
{q: [alone[s].estimates[q] for s in alone] for q in ["ka", "CL", "ke"]}, index=list(alone)
)
table_alone["RSE % of ka"] = [
alone[s].table().set_index("quantity").loc["ka", "RSE %"] for s in alone
]
print(table_alone.round(4))
# every subject's estimates are R's
for q in ["ka", "CL", "ke"]:
ref = np.exp(ref_alone[ref_alone.quantity == f"log {q}"].set_index("Subject").estimate)
assert np.max(np.abs(table_alone[q] / ref - 1)) < 1e-3
ka CL ke RSE % of ka 1 1.7774 0.0199 0.0540 12.9398 2 1.9427 0.0448 0.1017 22.1728 3 2.4536 0.0396 0.0814 5.8575 4 1.1715 0.0374 0.0875 17.3777 5 1.4715 0.0436 0.0884 21.6962 6 1.1637 0.0511 0.0995 15.9041 7 0.6797 0.0516 0.1022 10.6752 8 1.3755 0.0465 0.0920 16.8379 9 8.8656 0.0327 0.0866 32.1094 10 0.6955 0.0324 0.0740 8.5772 11 3.8490 0.0572 0.0981 6.4518 12 0.8329 0.0420 0.1056 11.9717
CL and ke are well determined for every subject. ka is not: it is set by the first hour, where each subject has three or four samples, and for subject 9 it is 8.9 per hour with a large uncertainty. A subject alone says nothing about what is typical; the next section lets the subjects inform each other.
4. All twelve together¶
Now ka and CL vary between subjects, lognormally around a typical value (the median), with
a spread (sdlog, about the CV for small values); ke is one value for everyone, as in R's
nlme fit of these data. method laplace is first-order conditional estimation with
interaction (FOCE-I), here written in the fit text:
pop = tf.Problem.from_text(
"""
fit theoph_pop
data "../examples/theoph.csv" with ID=Subject, TIME=Time, DV=conc
unit ID
doses Dose at t=0 into depot
observe conc = DV
estimate ka ~ lognormal(median=1.5, sdlog=0.5)
estimate CL ~ lognormal(median=0.04, sdlog=0.5)
estimate ke = 0.08
error conc ~ additive(1)
method laplace
""",
model=model,
)
rp = tf.fit(pop, progress="none")
print(rp)
theoph_pop: method laplace (L-BFGS-B, FOCE-I), converged; -2LL 353.9837 (132 measurements, 12 units)
starts: 1; 1 at the best fit (within 0.1); redrawn 0; failed runs during the fit 0; 5 s
quantity estimate SE RSE % 95 % CI also
ka.median 1.6195 0.3207 19.8 (1.099, 2.388)
ka.sdlog 0.65643 0.15 22.9 (0.4194, 1.027) cv 73.4 %, var 0.4309
CL.median 0.039544 0.002353 5.95 (0.03519, 0.04444)
CL.sdlog 0.16751 0.03643 21.7 (0.1094, 0.2566) cv 16.9 %, var 0.02806
ke 0.084964 0.004342 5.11 (0.07687, 0.09392)
conc.additive 0.70777 0.04815 6.8 (0.6194, 0.8087)
shrinkage (1 - SD of the units' scores): ka 0.8 %, CL -0.7 %
doctor: 3 notes
note determination: condition number of the curvature 39.1; no ridge, every quantity determined within a factor 10.
note optima: one start: other optima were not looked for.
what to do: options starts=8 looks from 8 starts.
note tolerance check: at rtol 1e-08 the -2LL changes by 2.2e-05 and the estimates by less than 0.001 SE; rtol 1e-06 is enough.
R's nlme reaches −2LL 354.04; tenqsp-fit's 353.98 is a little lower. The two methods
approximate the same likelihood in different ways (nlme by Lindstrom–Bates steps,
tenqsp-fit by the Laplace approximation), so they land close but not on the same point.
Every estimate agrees with nlme's within its standard error:
names = {"ka.median": "log ka.median", "CL.median": "log CL.median", "ke": "log ke",
"ka.sdlog": "ka.sdlog", "CL.sdlog": "CL.sdlog",
"conc.additive": "conc.additive"} # fmt: skip
rows = []
for ours, theirs in names.items():
value = ref_pop.loc[theirs, "estimate"]
value = np.exp(value) if theirs.startswith("log ") else value
rows.append((ours, rp.estimates[ours], value, ref_pop.loc[theirs, "se_log"]))
compare = pd.DataFrame(rows, columns=["quantity", "tenqsp-fit", "nlme", "nlme SE (log)"])
compare["log difference"] = np.log(compare["tenqsp-fit"] / compare["nlme"])
print(compare.round(5))
assert rp.m2ll < 354.0428
assert np.all(np.abs(compare["log difference"]) <= compare["nlme SE (log)"])
quantity tenqsp-fit nlme nlme SE (log) log difference 0 ka.median 1.61952 1.59319 0.19856 0.01639 1 CL.median 0.03954 0.03967 0.06001 -0.00313 2 ke 0.08496 0.08589 0.05249 -0.01082 3 ka.sdlog 0.65643 0.64357 0.23529 0.01977 4 CL.sdlog 0.16751 0.16693 0.21783 0.00348 5 conc.additive 0.70777 0.70925 0.06850 -0.00209
What the population changes for one subject¶
rp.individual() gives each subject's own ka and CL in the population fit (the conditional
modes: NONMEM's empirical Bayes estimates). Two things change from the fits of section 3:
- A subject whose data say little about ka borrows from the others. Subject 9's ka, the least determined (RSE 32 %), moves from 8.9 to 6.6 per hour, toward the typical value; it moves furthest of all.
- ke is now one value for everyone (0.085 per hour), so a subject whose own ke was different refits its ka and CL around it: subject 1's ke alone was 0.054, and its ka moves from 1.78 to 1.42.
ind = rp.individual().set_index("unit")
both = pd.DataFrame({"ka alone": table_alone["ka"], "ka in the population": ind["ka"],
"RSE % alone": table_alone["RSE % of ka"]}) # fmt: skip
print(both.round(3))
fig, ax = plt.subplots(figsize=(5, 3.5))
ax.scatter(both["ka alone"], both["ka in the population"])
for s, row in both.iterrows():
ax.annotate(str(s), (row["ka alone"], row["ka in the population"]), fontsize=8)
lim = [0.5, 10]
ax.plot(lim, lim, "k:", lw=0.8, label="no change")
ax.axhline(rp.estimates["ka.median"], color="grey", lw=0.8, label="typical ka")
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlabel("ka, subject alone (1/h)")
ax.set_ylabel("ka in the population fit (1/h)")
ax.legend(fontsize="small")
typical = rp.estimates["ka.median"]
pull = np.abs(np.log(both["ka alone"] / typical)) - np.abs(
np.log(both["ka in the population"] / typical)
)
assert pull[9] == pull.max() and pull[9] > 0.25 # subject 9 moves most, toward the typical ka
assert both["ka in the population"].idxmax() == 9 # and still has the fastest absorption
ka alone ka in the population RSE % alone 1 1.777 1.424 12.940 2 1.943 2.132 22.173 3 2.454 2.317 5.858 4 1.171 1.214 17.378 5 1.471 1.501 21.696 6 1.164 1.273 15.904 7 0.680 0.787 10.675 8 1.376 1.437 16.838 9 8.866 6.592 32.109 10 0.696 0.653 8.577 11 3.849 3.781 6.452 12 0.833 0.984 11.972
The population fit's shrinkage (rp.shrinkage) is small for both ka and CL, so the
subjects' values still mostly reflect their own data; with sparse sampling it grows, and
the doctor warns above 30 %.
For NONMEM users, rp.tables() gives the sdtab and patab tables:
tables = rp.tables()
sdtab, patab = tables["sdtab"], tables["patab"]
print(sdtab.head())
print(patab.head())
print(rp.shrinkage)
assert all(abs(v) < 0.1 for v in rp.shrinkage.values())
assert set(["ID", "TIME", "DV", "PRED", "IPRED", "IWRES"]) <= set(sdtab.columns)
ID TIME link DV PRED IPRED IWRES CENS LIMIT
0 1 0.00 conc 0.74 0.000000 0.000000 1.045536 0 NaN
1 1 0.25 conc 2.84 2.843414 3.660304 -1.158997 0 NaN
2 1 0.57 conc 6.57 5.063289 6.684126 -0.161247 0 NaN
3 1 1.12 conc 10.50 6.802144 9.281487 1.721621 0 NaN
4 1 2.02 conc 9.66 7.332094 10.327771 -0.943485 0 NaN
ID z(ka) z(CL) ka CL ke
0 1 -0.195647 -2.137349 1.424332 0.027643 0.084964
1 2 0.418644 0.043816 2.131742 0.039835 0.084964
2 3 0.545600 0.141741 2.317008 0.040494 0.084964
3 4 -0.439297 -0.401555 1.213811 0.036971 0.084964
4 5 -0.115435 0.414726 1.501338 0.042388 0.084964
{'ka': 0.007873890306671849, 'CL': -0.006528669037205059}
What this shows¶
- The same model fitted three ways gives R's answers:
optimizereproducesnlsfor every subject, andlaplaceagrees withnlmewithin the standard errors, at a −2LL as low. nutsputs ka, CL and ke whereoptimizedoes, with wider intervals that account for having only 11 measurements; it costs about two minutes for one subject.- A population fit keeps what each subject's data determine and fills in what they do not: subject 9's ka moves from 8.9 toward the typical value.
The population quickstart continues from this fit: goodness of fit, a visual predictive check, a profile of ke, and a prediction for a new regimen.