Tutorial 5: warfarin, a covariate that is another covariate¶
Warfarin in 32 volunteers, one oral dose each, then plasma concentrations over five days (the warfarin data of O'Reilly and colleagues, as distributed with Monolix). Monolix's demo fits it, and with sex on the volume it finds that women have a volume about 30 % smaller. This tutorial fits the same data and asks whether that is about sex:
- the data, and who is in it;
- the PK model, with a lag time, next to Monolix's estimates;
- sex on the volume, as Monolix;
- weight on the volume, and both together.
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/warfarin.csv")
# Monolix's fits of the same data, stored in the repository
REF = "../../validation/warfarin/"
ref_base = pd.read_csv(REF + "reference_monolix_base.csv").set_index("parameter")
ref_sex = pd.read_csv(REF + "reference_monolix_sex_on_V_CL.csv").set_index("parameter")
print(data.head(6))
id time amt dv dvid wt sex age 0 1 0.0 100.0 NaN NaN 66.7 1 50 1 1 0.0 NaN 98.0 2.0 66.7 1 50 2 1 24.0 NaN 9.2 1.0 66.7 1 50 3 1 24.0 NaN 49.0 2.0 66.7 1 50 4 1 36.0 NaN 8.5 1.0 66.7 1 50 5 1 36.0 NaN 32.0 2.0 66.7 1 50
1. The data¶
One row per dose (amt) or measurement (dv); dvid 1 is the warfarin concentration
(mg/L), dvid 2 the clotting response (prothrombin complex activity), which this tutorial
leaves out. Weight wt (kg), sex (1 male, 0 female) and age are columns.
people = data.drop_duplicates("id").set_index("id")
conc = data[data.dvid == 1]
print(f"{len(people)} subjects, {len(conc)} concentrations, one dose each "
f"({people.amt.min():g} to {people.amt.max():g} mg)") # fmt: skip
print(people.groupby("sex").wt.describe()[["count", "mean", "min", "max"]])
early = conc[conc.time < 24].id.nunique()
print(f"subjects sampled in the first 24 h: {early} of {len(people)}")
fig, ax = plt.subplots(1, 2, figsize=(10, 3.5))
for i, d in conc.groupby("id"):
ax[0].plot(d.time, d.dv, "o-", ms=2.5, lw=0.7,
color="#d62728" if people.sex[i] == 0 else "#1f3b73") # fmt: skip
ax[0].set_xlabel("time (h)")
ax[0].set_ylabel("warfarin (mg/L)")
ax[0].set_title("red: women", fontsize=9)
ax[1].hist([people.wt[people.sex == 1], people.wt[people.sex == 0]], bins=10,
color=["#1f3b73", "#d62728"], label=["men", "women"]) # fmt: skip
ax[1].set_xlabel("weight (kg)")
ax[1].legend(fontsize="small")
assert (people.sex == 0).sum() == 5
32 subjects, 247 concentrations, one dose each (60 to 153 mg)
count mean min max
sex
0 5.0 51.340000 40.0 60.0
1 27.0 73.459259 58.0 102.0
subjects sampled in the first 24 h: 13 of 32
Five of the 32 are women, and they are lighter: about 51 kg on average, against 74 kg for the men. Keep that in mind. Most subjects were sampled from 24 hours on; only some in the first hours, when the drug is absorbed.
2. The PK model¶
One compartment, absorption with a lag time: lag depot = tlag delays every dose into
depot (NONMEM's ALAG). The lag time, ka, CL and V vary between subjects, as in Monolix.
model = tq.Model.from_text("""
model warfarin_pk
param ka = 1.5, CL = 0.13, V = 8, tlag = 0.8
d_t(depot) = -ka*depot
d_t(centr) = ka*depot - CL/V*centr
lag depot = tlag
observable conc = centr/V
""")
HEAD = """fit warfarin
data "../examples/warfarin.csv" with ID=id, TIME=time, AMT=amt, DV=dv
unit ID
doses into depot
observe conc = DV where dvid == 1
ignore DV where dvid == 2
estimate tlag ~ lognormal(median=0.8, sdlog=0.5)
estimate ka ~ lognormal(median=1.5, sdlog=0.5)
estimate CL ~ lognormal(median=0.13, sdlog=0.3)
"""
TAIL = """error conc ~ combined(0.3, 0.05)
method laplace
options progress=none
"""
def fit(volume):
"""The fit text: the lines common to every model here, and the volume's own lines."""
return tf.fit(tf.Problem.from_text(HEAD + volume + TAIL, model=model))
base = fit("estimate V ~ lognormal(median=8, sdlog=0.2)\n")
print(base)
warfarin: method laplace (L-BFGS-B, FOCE-I), converged; -2LL 689.5801 (247 measurements, 32 units)
starts: 1; 1 at the best fit (within 0.1); redrawn 0; failed runs during the fit 0; 51 s
quantity estimate SE RSE % 95 % CI also
tlag.median 0.78501 0.1992 25.4 (0.4774, 1.291)
tlag.sdlog 0.6296 0.3001 47.7 (0.2473, 1.603) cv 69.7 %, var 0.3964
ka.median 1.2217 0.3927 32.1 (0.6507, 2.294)
ka.sdlog 0.86235 0.218 25.3 (0.5254, 1.415) cv 105 %, var 0.7436
CL.median 0.13234 0.006917 5.23 (0.1195, 0.1466)
CL.sdlog 0.29124 0.03751 12.9 (0.2263, 0.3749) cv 29.8 %, var 0.08482
V.median 7.9543 0.3277 4.12 (7.337, 8.623)
V.sdlog 0.22118 0.03004 13.6 (0.1695, 0.2886) cv 22.4 %, var 0.04892
conc.additive 0.29238 0.07011 24 (0.1827, 0.4678)
conc.proportional 0.072652 0.01055 14.5 (0.05465, 0.09658)
shrinkage (1 - SD of the units' scores): tlag 70.6 %, ka 40.6 %, CL -0.3 %, V 2.3 %
doctor: 2 warnings, 3 notes
warning shrinkage: shrinkage above 30 %: tlag 71 %, ka 41 %. The units' own values of these are pulled towards the typical value, so plots of them (and of their relation to covariates) are unreliable.
what to do: judge the model by the VPC, not by the units' values.
warning jumps in the model: lag time tlag on the doses into depot: -2LL jumps where a dose's time plus the lag passes a measurement time.
what to do: gradient methods (all three) are safe only if it does not switch near the estimate: check a profile of the quantities involved (result.profile).
note determination: condition number of the curvature 151; 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 0.00022 and the estimates by less than 0.001 SE; rtol 1e-06 is enough.
ignore DV where dvid == 2 leaves the clotting response out of the fit.
The doctor warns about the lag time: −2LL jumps where a dose's time plus the lag passes a
measurement time, so gradient methods are safe only if that does not happen near the
estimate (a profile of tlag would show it). And the lag time and ka have high shrinkage:
with few early samples, each subject's own absorption is poorly determined.
Next to Monolix's fit of the same model:
e = base.estimates
pairs = {"tlag.median": "Tlag_pop", "ka.median": "ka_pop", "CL.median": "Cl_pop",
"V.median": "V_pop", "tlag.sdlog": "omega_Tlag", "ka.sdlog": "omega_ka",
"CL.sdlog": "omega_Cl", "V.sdlog": "omega_V"} # fmt: skip
t = base.table().set_index("quantity")
compare = pd.DataFrame({
"tenqsp-fit": [e[q] for q in pairs], "SE": [t.loc[q, "SE"] for q in pairs],
"Monolix": [ref_base.estimate[m] for m in pairs.values()],
"Monolix SE": [ref_base.se[m] for m in pairs.values()]}, index=list(pairs)) # fmt: skip
# the difference against the uncertainty of both estimates
both_se = np.hypot(compare.SE, compare["Monolix SE"])
compare["difference / SE"] = (compare["tenqsp-fit"] - compare.Monolix) / both_se
print(compare.round(4).to_string())
assert (compare["difference / SE"].abs() < 1).all()
tenqsp-fit SE Monolix Monolix SE difference / SE tlag.median 0.7850 0.1992 0.7643 0.4205 0.0445 ka.median 1.2217 0.3927 1.4562 0.5708 -0.3385 CL.median 0.1323 0.0069 0.1325 0.0069 -0.0146 V.median 7.9543 0.3277 7.9602 0.3297 -0.0127 tlag.sdlog 0.6296 0.3001 0.6051 0.4302 0.0467 ka.sdlog 0.8623 0.2180 1.0821 0.3801 -0.5015 CL.sdlog 0.2912 0.0375 0.2862 0.0369 0.0955 V.sdlog 0.2212 0.0300 0.2225 0.0306 -0.0314
Every estimate agrees with Monolix's within one standard error of the difference (the two
standard errors combined), CL and V to 1 %. They
are not identical, for two reasons: Monolix estimates by SAEM and tenqsp-fit by FOCE-I
(laplace), and Monolix's error model here adds the two parts of the SD (a + b·f),
where tenqsp-fit's combined adds their squares. For the same reason the two −2LL are not
comparable. The absorption, ka and its spread, differs most, and is the least determined.
3. Sex on the volume¶
As Monolix: the volume of women is the volume of men times exp(b_sex).
SEX = "exp(b_sex) if sex == 0 else 1"
by_sex = fit(f"""estimate V_pop = 8
estimate b_sex = 0
estimate V ~ lognormal(median=V_pop*({SEX}), sdlog=0.2)
""")
row = by_sex.table().set_index("quantity").loc["b_sex"]
print(f"-2LL {base.m2ll:.1f} -> {by_sex.m2ll:.1f}; b_sex {row['estimate']:.3f} "
f"(SE {row['SE']:.3f}); Monolix {ref_sex.estimate['beta_V_tSex_F']:.3f} "
f"(SE {ref_sex.se['beta_V_tSex_F']:.3f})") # fmt: skip
print(f"women's volume {np.exp(row['estimate']):.2f} times men's")
assert base.m2ll - by_sex.m2ll > 30
assert abs(row["estimate"] - ref_sex.estimate["beta_V_tSex_F"]) < row["SE"]
-2LL 689.6 -> 633.1; b_sex -0.373 (SE 0.086); Monolix -0.382 (SE 0.085) women's volume 0.69 times men's
A large drop in −2LL, and the same effect as Monolix's (whose model also had sex on CL, where it found nothing): women have a volume about 30 % smaller. But the women here are also 22 kg lighter, and volume follows body size.
4. Weight on the volume, and both¶
The volume in proportion to a power of weight, (wt/70)^b_wt; then weight and sex
together.
by_weight = fit("""estimate V_pop = 8
estimate b_wt = 1
estimate V ~ lognormal(median=V_pop*(wt/70)^b_wt, sdlog=0.2)
""")
both = fit(f"""estimate V_pop = 8
estimate b_wt = 1
estimate b_sex = 0
estimate V ~ lognormal(median=V_pop*(wt/70)^b_wt*({SEX}), sdlog=0.2)
""")
summary = pd.DataFrame({
"-2LL": [r.m2ll for r in (base, by_sex, by_weight, both)],
"V.sdlog": [r.estimates["V.sdlog"] for r in (base, by_sex, by_weight, both)]},
index=["no covariate", "sex", "weight", "weight and sex"]) # fmt: skip
print(summary.round(3).to_string())
print(both)
-2LL V.sdlog
no covariate 689.580 0.221
sex 633.131 0.168
weight 621.260 0.136
weight and sex 620.476 0.134
warfarin: method laplace (L-BFGS-B, FOCE-I), converged; -2LL 620.4761 (247 measurements, 32 units)
starts: 1; 1 at the best fit (within 0.1); redrawn 0; failed runs during the fit 0; 38 s
quantity estimate SE RSE % 95 % CI also
tlag.median 0.78419 0.2111 26.9 (0.4626, 1.329)
tlag.sdlog 0.63226 0.2139 33.8 (0.3258, 1.227) cv 70.1 %, var 0.3998
ka.median 1.2067 0.3639 30.2 (0.6682, 2.179)
ka.sdlog 0.84835 0.2328 27.4 (0.4954, 1.453) cv 103 %, var 0.7197
CL.median 0.13246 0.006897 5.21 (0.1196, 0.1467)
CL.sdlog 0.29028 0.03731 12.9 (0.2256, 0.3735) cv 29.7 %, var 0.08426
V_pop 8.1708 0.2518 3.08 (7.692, 8.679)
b_wt 0.77391 0.1994 25.8 (0.4671, 1.282)
b_sex -0.089756 0.1008 112 (-0.2874, 0.1079)
V.sdlog 0.13387 0.02139 16 (0.09787, 0.1831) cv 13.4 %, var 0.01792
conc.additive 0.29035 0.03683 12.7 (0.2264, 0.3723)
conc.proportional 0.073233 0.006911 9.44 (0.06087, 0.08811)
shrinkage (1 - SD of the units' scores): tlag 57.0 %, ka 48.6 %, CL -0.3 %, V 9.8 %
doctor: 3 warnings, 3 notes
warning weakly determined: b_sex (95 % interval -0.287 to 0.108).
what to do: a written prior, or fix the quantity and say so; or measurements that inform it.
warning shrinkage: shrinkage above 30 %: tlag 57 %, ka 49 %. The units' own values of these are pulled towards the typical value, so plots of them (and of their relation to covariates) are unreliable.
what to do: judge the model by the VPC, not by the units' values.
warning jumps in the model: lag time tlag on the doses into depot: -2LL jumps where a dose's time plus the lag passes a measurement time.
what to do: gradient methods (all three) are safe only if it does not switch near the estimate: check a profile of the quantities involved (result.profile).
note determination: condition number of the curvature 236.
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 0.00026 and the estimates by less than 0.001 SE; rtol 1e-06 is enough.
b = both.table().set_index("quantity")
lo, hi = b.loc["b_sex", "CI 2.5 %"], b.loc["b_sex", "CI 97.5 %"]
print(f"with weight in, b_sex {b.loc['b_sex', 'estimate']:.3f}, 95 % CI ({lo:.3f}, {hi:.3f}); "
f"-2LL lower by {by_weight.m2ll - both.m2ll:.2f} than weight alone") # fmt: skip
assert by_weight.m2ll < by_sex.m2ll - 5
assert by_weight.m2ll - both.m2ll < 3.84 and lo < 0 < hi
with weight in, b_sex -0.090, 95 % CI (-0.287, 0.108); -2LL lower by 0.78 than weight alone
Weight explains the volume better than sex does (−2LL 12 lower, for the same number of quantities), and leaves less unexplained between subjects (the spread of V falls to 0.14). With weight in the model, sex adds nothing: −2LL falls by less than 1, short of the 3.84 a real effect would need, and its interval spans 0. The "sex effect" was the weight difference between these men and women. The exponent of weight is close to 1: volume in proportion to body weight, as expected for warfarin.
Five women are too few to say that sex has no effect of its own: the interval allows a volume up to 25 % smaller or 11 % larger. What the data do say is that weight, not sex, is the covariate to put in the model.
What this shows¶
- The PK model agrees with Monolix's fit within the standard errors; the remaining differences come from the method and the error model, not from the data.
- A covariate that improves the fit may stand in for another: here sex for weight. Test them together before reading the effect as biological.
- A lag time makes −2LL jump; the doctor says so, and a profile of it is the check.