Skip to main content

Example: Adaptive dosing, parameter uncertainty and the controller’s effect

ferx_simulate_adaptive() simulates a dosing policy: the model file’s [adaptive_dosing] block reads each virtual patient’s simulated state at every decision time and picks the next dose. This page covers two questions about such a policy:

  1. How sure are we of its performance? uncertainty = runs the policy under parameter sets drawn from a fit’s uncertainty, not only at the point estimates.
  2. What do the rules themselves buy? reference = "fixed" runs the same patients a second time under the fixed start dose, so the difference between the two arms is the controller’s effect.
WarningMaturity: beta

ferx-core labels adaptive dosing beta: it is usable, but its syntax and outputs may still change. See feature maturity.

Tip

For the full walkthrough (reading every result table, loading doses, simulating fitted patients at their own EBEs), see Chapter 23 (Adaptive dosing and TDM strategies) in the FeRx book. The block’s syntax is on the ferx-core adaptive dosing page, and every argument is in the ferx_simulate_adaptive() reference.

Model and design

The bundled adaptive_tdm example is a one-compartment IV model with between-subject variability on clearance and a proportional assay error. Its [adaptive_dosing] block titrates a 1-hour infusion every 12 hours on the measured trough:

library(ferx)
ex <- ferx_example("adaptive_tdm")
ferx_model_get_section(ex$model, "adaptive_dosing")
# [adaptive_dosing]
  with_assay_error = true                 # titrate on the *measured* trough (assay-noised)
  assay_cmt        = 1                     # output #1 -- the concentration (y = central/V) + its proportional error
  at               = every 12 from 0 to 96 # a TDM decision before each q12h dose
  start_dose       = 1000                  # initial dose (mg)
  route            = infuse(cmt=1, over=1) # 1-hour IV infusion
  dose_bounds      = [250, 2000]           # never below 250 or above 2000 mg
  target_window    = [10, 20]              # reported attainment band (mg/L); feeds the PCT_READINGS_IN_WINDOW metric only, never dosing
  confirm          = 1                     # act on the first breach
  when signal < 10 : increase 25%          # sub-therapeutic trough -> escalate
  when signal > 20 : decrease 25%          # supra-therapeutic trough -> de-escalate

The first matching when rule changes the running dose by 25%; when no rule matches, the running dose is given again. target_window does not steer dosing: it only scores the attainment metric PCT_READINGS_IN_WINDOW, the fraction of a run’s decisions whose noise-free trough is inside 10 to 20 mg/L.

The dataset holds five subjects and their observation grid (0 to 96 h, every 12 h) and no dose rows: the controller issues every dose.

design <- read.csv(ex$data, na.strings = ".")
head(design, 3)
  ID TIME DV EVID AMT CMT RATE MDV
1  1    0  0    0  NA   1    0   0
2  1   12  0    0  NA   1    0   0
3  1   24  0    0  NA   1    0   0
table(design$ID)

1 2 3 4 5 
9 9 9 9 9 

The controller’s effect

The controller has no variance of its own: given the same patients and the same noise it always doses the same way. Its effect is a contrast: the same patients run once under the rules and once under a reference regimen. reference = "fixed" does both in one call. The reference arm is the [adaptive_dosing] block with its rules cleared, which gives each subject the start dose (here 1000 mg) at every due point. Both arms run on one seed and share every random number (parameter draws, etas, IOV kappas and assay noise), so their difference is the controller’s effect, not simulation noise.

arm_labels names each arm; the reference is never implicit.

con <- ferx_simulate_adaptive(ex$model, ex$data, n_sim = 50L, seed = 1L,
                              reference = "fixed",
                              arm_labels = c(adaptive = "trough TDM rule",
                                             reference = "start dose every due point"))
con$arm_labels
                    adaptive                    reference 
           "trough TDM rule" "start dose every due point" 
names(con$metrics)[1:4]
[1] "ARM"  "DRAW" "SIM"  "REP" 
table(con$metrics$ARM)

 adaptive reference 
      250       250 

Every table gains a leading ARM column. The run tables (trajectories, doses, decisions, metrics) hold an "adaptive" and a "reference" arm, each exactly what that arm alone gives. The summary tables add "difference" rows, adaptive minus reference:

key <- c("CUM_DOSE", "PCT_READINGS_IN_WINDOW")
subset(con$summary_rows, STATISTIC == "mean" & METRIC %in% key,
       c(ARM, METRIC, VALUE, MC_SE, N_RUNS, N_MISSING))
           ARM                 METRIC      VALUE     MC_SE N_RUNS N_MISSING
1     adaptive               CUM_DOSE 11528.7510 167.14131    250         0
21    adaptive PCT_READINGS_IN_WINDOW     0.7204   0.01047    250         0
43   reference               CUM_DOSE  9000.0000   0.00000    250         0
63   reference PCT_READINGS_IN_WINDOW     0.4542   0.01707    250         0
85  difference               CUM_DOSE  2528.7510 167.14131    250         0
105 difference PCT_READINGS_IN_WINDOW     0.2662   0.01843    250         0

The rule raises the mean fraction of decisions in the window by 0.266 (Monte Carlo SE 0.018) and gives 2529 mg more drug per patient over the course (SE 167 mg).

Reading the difference rows

The difference is paired: summary_rows summarises the per-run differences (adaptive minus reference for the same patient, sim and noise), not the two arms’ summaries.

  • The "mean" row is the mean effect. Its MC_SE leaves one sim out of both arms at once, so it accounts for the correlation between the arms, which combining the arms’ own SEs as sqrt(se_A^2 + se_R^2) ignores.
  • A "fraction_at_least" difference row (from summary_thresholds) is P(A − R ≥ threshold). The change in attainment is the adaptive row minus the reference row, not the difference row.
  • A run whose metric is missing in either arm is missing in the difference. Where the arms’ N_MISSING differ (a rule that stops some runs, say), the difference row is over the runs present in both and is not the adaptive row minus the reference row. Here no run is missing in either arm.

In the reference arm every subject gets the same 1000 mg nine times, so its CUM_DOSE mean is exactly 9000 mg with an MC_SE of 0.

Monte Carlo standard errors

MC_SE is the delete-one jackknife over the sims that carry the metric. A sim is the independent replicate, since the runs within it share each subject’s eta. Read it with a t distribution on S − 1 degrees of freedom for S such sims. It is NA on "median" rows, where the jackknife is inconsistent, and with fewer than two sims:

subset(con$summary_rows, ARM == "adaptive" & METRIC == "CUM_DOSE",
       c(STATISTIC, VALUE, MC_SE))
  STATISTIC VALUE MC_SE
1      mean 11529 167.1
2    median 11250    NA
one <- ferx_simulate_adaptive(ex$model, ex$data, n_sim = 1L, seed = 1L)
subset(one$summary_rows, METRIC == "CUM_DOSE", c(STATISTIC, VALUE, MC_SE))
  STATISTIC VALUE MC_SE
1      mean 11532    NA
2    median  9941    NA

Which variability does the controller remove?

decompose = TRUE splits the variance of each metric into a parameter-uncertainty layer ("parameter", drawn only with uncertainty), between-subject variability ("bsv") and within-subject variability ("within": IOV and assay noise). Separating the within layer needs repeated runs of the same patient, n_reps >= 2, and n_sim >= 2. With reference = "fixed", the decomposition gets difference rows too:

dec <- ferx_simulate_adaptive(ex$model, ex$data, n_sim = 50L, seed = 1L,
                              n_reps = 3L, decompose = TRUE,
                              reference = "fixed",
                              arm_labels = c(adaptive = "trough TDM rule",
                                             reference = "start dose every due point"))
subset(dec$variance_components,
       SCOPE == "population" & METRIC == "PCT_READINGS_IN_WINDOW",
       c(ARM, LAYER, STATUS, VALUE, MC_SE))
            ARM           LAYER    STATUS      VALUE     MC_SE
271    adaptive       parameter not_drawn         NA        NA
272    adaptive             bsv estimated  0.0251160 0.0053029
273    adaptive          within estimated  0.0050041 0.0006256
274    adaptive between_subject estimated  0.0002578 0.0003243
275    adaptive           total estimated  0.0303779 0.0052457
771   reference       parameter not_drawn         NA        NA
772   reference             bsv estimated  0.1167911 0.0039602
773   reference          within estimated  0.0000000 0.0000000
774   reference between_subject estimated  0.0016960 0.0019498
775   reference           total estimated  0.1184871 0.0034484
1271 difference       parameter not_drawn         NA        NA
1272 difference             bsv estimated -0.0916751 0.0074180
1273 difference          within estimated  0.0050041 0.0006256
1274 difference between_subject estimated -0.0014382 0.0019445
1275 difference           total estimated -0.0881093 0.0067309

A negative "bsv" difference at population scope is between-patient variance the controller removed: -0.0917 here. The "within" layer of the reference arm is 0: a fixed dose ignores the assay readings and this model has no IOV, so a patient’s repeated runs have the same noise-free troughs. Under the rule, assay noise changes the doses and so the troughs: that is within-subject variance the feedback adds.

Part of the effect is the first decision. At t = 0 no drug has been given, so the trough is 0 and signal < 10 : increase 25% fires: the adaptive arm’s first dose is 1250 mg in every run, against the reference’s 1000 mg. The t = 0 reading is never in the window either, so in both arms a run has at most 8 of its 9 readings in it.

ImportantChoose a fair reference

The fixed reference is the start dose at every due point. That is not a fair reference for a controller with a loading dose (in the block or in the data’s base regimen): the comparison then credits the rules with what the loading dose does. Whatever the reference is, say so in arm_labels.

Parameter uncertainty

The runs above use the model file’s values. With fit =, the policy runs at a fit’s estimates instead; with uncertainty = as well, it runs under parameter sets drawn from the fit’s uncertainty.

A fit to collected TDM data

adaptive_tdm is a simulation design (every DV is 0), so a fit to it has no information. To have a fit, run the protocol on 20 virtual patients (4 sims of the 5 subjects), keep the doses it chose, and measure each trough with assay error. The troughs come from ferx_simulate() on those dose records, which adds the residual error. The empty DV cells mark the times to simulate at, and ferx_simulate() says so with the W_DESIGN_DV warning printed below:

protocol <- ferx_simulate_adaptive(ex$model, ex$data, n_sim = 4L, seed = 2L)
patient <- function(d) (as.integer(d$SIM) - 1L) * 5L + as.integer(d$ID)
obs <- protocol$trajectories[protocol$trajectories$TIME > 0, ]
records <- rbind(
  data.frame(ID = patient(protocol$doses), TIME = protocol$doses$TIME, DV = NA,
             EVID = 1, AMT = protocol$doses$AMT, CMT = protocol$doses$CMT,
             RATE = protocol$doses$RATE, MDV = 1),
  data.frame(ID = patient(obs), TIME = obs$TIME, DV = NA,
             EVID = 0, AMT = NA, CMT = 1, RATE = 0, MDV = 0)
)
records <- records[order(records$ID, records$TIME, records$EVID), ]
tdm_file <- file.path(tempdir(), "tdm_collected.csv")
write.csv(records, tdm_file, row.names = FALSE, na = ".")

measured <- ferx_simulate(ex$model, tdm_file, n_sim = 1L, seed = 3L)
Warning: ferx_simulate produced 1 diagnostic:
  W_DESIGN_DV: 160 observation row(s) (EVID=0) had a missing DV (`.`/`NA`/blank) and were kept as design points to simulate at. A fit of the same dataset would skip these rows (W_MISSING_DV), so the simulated dataset has more rows than the fitted one. Set MDV=1 on rows that are not sampling times.
trough <- records$EVID == 0
records$DV[trough] <- measured$DV_SIM[match(paste(records$ID, records$TIME)[trough],
                                            paste(measured$ID, measured$TIME))]
write.csv(records, tdm_file, row.names = FALSE, na = ".")

tdm_fit <- ferx_fit(ex$model, tdm_file, method = "focei", verbose = FALSE)
tdm_fit$converged
[1] TRUE
rbind(estimate = tdm_fit$theta, se = tdm_fit$se_theta)
          TVCL    TVV
estimate 4.470 52.914
se       0.267  2.448

Each trough is recorded before the dose given at the same time. The fit’s covariance step ran, so tdm_fit$cov_matrix is available.

Asymptotic draws

uncertainty = list(method = "asymptotic", n_draws = ) draws parameter sets from a multivariate normal on fit$cov_matrix, so it needs fit and a fit whose covariance step succeeded. Every subject and each of the n_sim replicates is simulated under every draw, so the run has n_draws * n_sim replicates per subject. "asymptotic" is the default method; "sir" is below.

res_u <- ferx_simulate_adaptive(ex$model, ex$data, n_sim = 20L, seed = 1L,
                                fit = tdm_fit,
                                uncertainty = list(method = "asymptotic", n_draws = 20L))
table(res_u$metrics$ID)  # 20 draws x 20 sims per subject

  1   2   3   4   5 
400 400 400 400 400 
sapply(res_u[c("trajectories", "doses", "decisions", "metrics", "summary_rows")],
       function(x) range(x$DRAW))
     trajectories doses decisions metrics summary_rows
[1,]            1     1         1       1            1
[2,]           20    20        20      20           20

DRAW on every table is the parameter set a row was simulated under: 1 throughout without uncertainty, 1 to n_draws with it. res_u$parameters has one row per draw, named as the rows of fit$cov_matrix and on the scale fit$theta, fit$omega and fit$sigma report them. Join it to the other tables by DRAW:

head(res_u$parameters, 3)
  DRAW  TVCL   TVV  ETA_CL    PROP
1    1 4.871 53.44 0.09292 0.09543
2    2 4.753 51.63 0.05891 0.09302
3    3 4.630 49.60 0.08193 0.08658
nrow(res_u$parameters)
[1] 20
head(merge(res_u$metrics, res_u$parameters, by = "DRAW")[, c("DRAW", "ID", "CUM_DOSE", "TVCL")], 3)
  DRAW ID CUM_DOSE  TVCL
1    1  1    16766 4.871
2    1  2    16484 4.871
3    1  3    13750 4.871

Without uncertainty, parameters has its columns and no rows. con, the contrast run above, shows it (with the leading ARM column every table gets under reference):

nrow(con$parameters)
[1] 0
names(con$parameters)
[1] "ARM"    "DRAW"   "TVCL"   "TVV"    "ETA_CL" "PROP"  

How the draws behave, per ?ferx_simulate_adaptive:

  • The draws come from a random stream of their own. Draw 1 uses the random effects the same seed gives without uncertainty (under draw 1’s omega), so draw 1 does not depend on n_draws; each further draw simulates new virtual patients.
  • A FIX or held-at-bound parameter stays at its estimate in every draw (adaptive_tdm has none).
  • A dose expression that reads only theta is evaluated at the fit’s estimate in every draw, while a dose_knowledge = oracle subject is dosed from its own draw’s parameters.
  • Warnings and refusals name the replicate as "(draw d, sim s)" only in a run with uncertainty.

summary_rows then has one row per metric, statistic and draw, and summary_bands the quantiles of each per-draw statistic across the draws, at summary_probs (5%, 50% and 95% by default):

subset(res_u$summary_bands, STATISTIC == "mean" & METRIC %in% key,
       c(METRIC, STATUS, N_DRAWS_PRESENT, LO, MED, HI))
                   METRIC    STATUS N_DRAWS_PRESENT         LO        MED
1                CUM_DOSE quantiles              20 12015.4021 12860.7812
21 PCT_READINGS_IN_WINDOW quantiles              20     0.6596     0.7183
           HI
1  13678.7031
21     0.7657

The band of the mean window fraction, 0.66 to 0.77, is how far the fit to 20 patients leaves the protocol’s expected performance open, together with the Monte Carlo error of 20 sims per draw. A band needs enough draws to resolve its quantiles (19 for a 5% quantile); with too few, LO and HI are NA.

SIR draws

method = "sir" takes each parameter set from the fit’s sampling importance resampling instead of the normal approximation. It draws from the resampled vectors SIR keeps on the fit, and SIR keeps them only when asked. tdm_fit has run no SIR, so the call is refused:

refused <- tryCatch(
  ferx_simulate_adaptive(ex$model, ex$data, n_sim = 20L, seed = 1L, fit = tdm_fit,
                         uncertainty = list(method = "sir", n_draws = 20L)),
  error = conditionMessage)
cat(strwrap(refused, 80), sep = "\n")
ferx_simulate_adaptive: `fit$sir_resamples` is empty: SIR did not keep its
draws. Run `fit <- ferx_sir(fit, sir_keep_samples = TRUE)`, or fit with
`ferx_fit(..., sir = TRUE, settings = list(sir_keep_samples = TRUE))`.

Run ferx_sir(fit, sir_keep_samples = TRUE) first:

tdm_fit_sir <- ferx_sir(tdm_fit, sir_samples = 1000, sir_resamples = 250,
                        sir_keep_samples = TRUE)
res_sir <- ferx_simulate_adaptive(ex$model, ex$data, n_sim = 20L, seed = 1L,
                                  fit = tdm_fit_sir,
                                  uncertainty = list(method = "sir", n_draws = 20L))
subset(res_sir$summary_bands, STATISTIC == "mean" & METRIC %in% key,
       c(METRIC, STATUS, LO, MED, HI))
                   METRIC    STATUS         LO        MED         HI
1                CUM_DOSE quantiles 11254.6664 12614.5898 13650.4238
21 PCT_READINGS_IN_WINDOW quantiles     0.6011     0.7311     0.7673

Not with supplied etas

etas = fit$ebe_etas simulates each fitted subject at its own estimated random effects. That cannot be combined with uncertainty: each supplied eta was estimated at the fit’s theta, so pairing it with a drawn theta would not describe the same patient. The call is refused, coded E_SUPPLIED_ETAS:

refused <- tryCatch(
  ferx_simulate_adaptive(ex$model, tdm_file, n_sim = 2L, seed = 1L, fit = tdm_fit,
                         etas = tdm_fit$ebe_etas,
                         uncertainty = list(method = "asymptotic", n_draws = 2L)),
  error = conditionMessage)
regmatches(refused, regexpr("\\[E_[A-Z_]+\\]", refused))
[1] "[E_SUPPLIED_ETAS]"

Uncertainty and contrast together

uncertainty and reference combine: each draw runs both arms on the same random numbers, so the difference rows carry the parameter uncertainty of the controller’s effect in summary_bands:

both <- ferx_simulate_adaptive(ex$model, ex$data, n_sim = 20L, seed = 1L,
                               fit = tdm_fit,
                               uncertainty = list(method = "asymptotic", n_draws = 20L),
                               reference = "fixed",
                               arm_labels = c(adaptive = "trough TDM rule",
                                              reference = "start dose every due point"))
subset(both$summary_bands,
       ARM == "difference" & STATISTIC == "mean" & METRIC %in% key,
       c(ARM, METRIC, LO, MED, HI))
           ARM                 METRIC        LO       MED        HI
85  difference               CUM_DOSE 3015.4021 3860.7812 4678.7031
105 difference PCT_READINGS_IN_WINDOW    0.2452    0.3156    0.3654

See also