Skip to main content

Adaptive dosing and TDM strategies

WarningMaturity: beta

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

Where you are

In a regular simulation (Simulating scenarios) the dosing regimen is fixed in the dataset before the simulation starts. Therapeutic drug monitoring (TDM) and titration protocols do not work that way. The next dose depends on a measured level: if the trough is below 10 mg/L, increase the dose by 25%.

ferx simulates such protocols with a controller that you declare in the model file’s [adaptive_dosing] block. At each decision time the controller reads the simulated state of each virtual patient, applies the first matching rule, and issues the next dose. ferx_simulate_adaptive() runs the simulation and returns what happened: the concentrations, every decision, the doses given, and one summary row per virtual patient. With those outputs you can compare dosing strategies before using them.

This is simulation of a dosing policy under a population model. It does not estimate an individual patient’s parameters from their measured levels.

The data

The bundled adaptive_tdm example titrates a vancomycin-style IV infusion every 12 hours on the measured trough concentration:

ex <- ferx_example("adaptive_tdm")
ferx_model_show(ex$model)
#> # model: adaptive_tdm.ferx 
#> # Adaptive (feedback) dosing -- TDM trough titration (epic #391)
#> #
#> # A vancomycin-style therapeutic-drug-monitoring (TDM) example: the dose is
#> # titrated every 12 h to drive the measured pre-dose trough concentration into a
#> # 10-20 mg/L window. This is a *declarative dosing policy* -- the next dose
#> # depends on the simulated, assay-noised state -- so it is run with
#> # ferx_simulate_adaptive(), not the plain forward ferx_simulate().
#> #
#> # 1-compartment IV model; the observed/predicted endpoint is the concentration
#> # C = central / V (mg/L). The controller titrates on the *measured* trough
#> # (with_assay_error = true), as a clinician would, so the proportional assay
#> # error feeds each decision.
#> 
#> [parameters]
#>   theta TVCL(4.0,  0.5,  20.0)    # clearance (L/h)
#>   theta TVV(50.0,  5.0, 200.0)    # volume of distribution (L)
#> 
#>   omega ETA_CL ~ 0.09             # between-subject variability on CL (log-normal)
#> 
#>   sigma PROP ~ 0.10 (sd)          # proportional assay error (10% CV)
#> 
#> [individual_parameters]
#>   CL = TVCL * exp(ETA_CL)
#>   V  = TVV
#> 
#> [structural_model]
#>   ode(states=[central])
#> 
#> [odes]
#>   # central: drug amount (mg); concentration C = central / V (mg/L)
#>   d/dt(central) = -(CL / V) * central
#> 
#> [scaling]
#>   y = central / V                 # observed/predicted endpoint is concentration
#> 
#> [error_model]
#>   DV ~ proportional(PROP)
#> 
#> [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_TIME_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 PK part is an ordinary one-compartment ODE model. The [adaptive_dosing] block is the dosing policy:

Key in this model What it does
with_assay_error = true, assay_cmt = 1 Titrate on the measured concentration of output 1, including its residual (assay) error
at = every 12 from 0 to 96 Decision times
start_dose = 1000 Starting value of the running dose
route = infuse(cmt=1, over=1) Each dose is a 1-hour infusion into compartment 1
dose_bounds = [250, 2000] Every dose is clamped to this range
target_window = [10, 20] Band used only to report attainment; it does not affect dosing
confirm = 1 Act on the first breach of a rule
when signal < 10 : increase 25% Rules, evaluated top to bottom; the first match wins

The block supports more than this example uses. observe = <expression> titrates on a latent, noise-free quantity instead of a measured one. levels defines a discrete dose ladder. auc_target reports exposure attainment, returned as metrics$AUC_TARGET_ATTAINMENT. The hold and stop actions skip or discontinue dosing. intervals with start_interval gives a ladder of dosing intervals that the lengthen and shorten effects step through, so a rule can change how often a dose is given as well as how much (changing the dosing interval). All are specified on the ferx-core adaptive dosing page.

The dataset supplies only the patients and the observation grid. It contains no doses, because the controller issues all of them:

tdm_data <- read.csv(ex$data, na.strings = ".")
head(tdm_data, 10)
#>    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
#> 4   1   36  0    0  NA   1    0   0
#> 5   1   48  0    0  NA   1    0   0
#> 6   1   60  0    0  NA   1    0   0
#> 7   1   72  0    0  NA   1    0   0
#> 8   1   84  0    0  NA   1    0   0
#> 9   1   96  0    0  NA   1    0   0
#> 10  2    0  0    0  NA   1    0   0

Minimal runnable call

n_sim <- 200
res <- ferx_simulate_adaptive(ex$model, ex$data, n_sim = n_sim, seed = 1)
names(res)
#> [1] "trajectories" "doses"        "decisions"    "metrics"
sapply(res, nrow)
#> trajectories        doses    decisions      metrics 
#>         9000         9000         9000         1000

Each of the 5 subjects in the dataset is simulated 200 times with fresh random effects, giving 1000 virtual patient runs.

Reading the result

The four data frames describe the same runs at different levels of detail. Follow one virtual patient (subject 1 in replicate 1) through them.

decisions has one row per decision time: the signal the controller read and what it did. The signals are rounded here for display; with assay error the “zero” trough at time 0 is a tiny number, which would otherwise push the column into scientific notation.

res$decisions |> filter(SIM == 1, ID == "1") |> mutate(SIGNAL = round(SIGNAL, 2))
#>   DRAW SIM ID DECISION TIME SIGNAL OUTCOME N_DOSED INTERVAL
#> 1    1   1  1        0    0   0.00   dosed       1       NA
#> 2    1   1  1        1   12   4.78   dosed       1       NA
#> 3    1   1  1        2   24   8.57   dosed       1       NA
#> 4    1   1  1        3   36  12.10   dosed       1       NA
#> 5    1   1  1        4   48  10.19   dosed       1       NA
#> 6    1   1  1        5   60  10.97   dosed       1       NA
#> 7    1   1  1        6   72   9.83   dosed       1       NA
#> 8    1   1  1        7   84  10.56   dosed       1       NA
#> 9    1   1  1        8   96  12.39   dosed       1       NA

doses is the dose ledger. It records the amount given, the signal and the rule that fired. When no rule matches, the running dose is given again and RULE shows the route (here infuse).

res$doses |> filter(SIM == 1, ID == "1") |> select(TIME, AMT, RATE, SIGNAL, RULE) |> mutate(SIGNAL = round(SIGNAL, 2))
#>   TIME      AMT     RATE SIGNAL                       RULE
#> 1    0 1250.000 1250.000   0.00 signal < 10 : increase 25%
#> 2   12 1562.500 1562.500   4.78 signal < 10 : increase 25%
#> 3   24 1953.125 1953.125   8.57 signal < 10 : increase 25%
#> 4   36 1953.125 1953.125  12.10                     infuse
#> 5   48 1953.125 1953.125  10.19                     infuse
#> 6   60 1953.125 1953.125  10.97                     infuse
#> 7   72 2000.000 2000.000   9.83 signal < 10 : increase 25%
#> 8   84 2000.000 2000.000  10.56                     infuse
#> 9   96 2000.000 2000.000  12.39                     infuse

The first dose is already 1250 mg rather than the start_dose of 1000 mg. At the first decision (time 0) no drug has been given, so the trough is zero and the rule signal < 10 : increase 25% fires immediately.

trajectories holds the simulated concentrations on the dataset’s observation grid, in the same layout as ferx_simulate() output:

res$trajectories |> filter(SIM == 1, ID == "1")
#>   DRAW SIM ID TIME CMT     IPRED    DV_SIM OBSERVED
#> 1    1   1  1    0   1  0.000000  0.000000       NA
#> 2    1   1  1   12   1  5.496757  5.496757       NA
#> 3    1   1  1   24   1  8.001636  8.001636       NA
#> 4    1   1  1   36   1 10.234630 10.234630       NA
#> 5    1   1  1   48   1 10.693960 10.693960       NA
#> 6    1   1  1   60   1 10.788444 10.788444       NA
#> 7    1   1  1   72   1 10.807880 10.807880       NA
#> 8    1   1  1   84   1 11.018006 11.018006       NA
#> 9    1   1  1   96   1 11.061230 11.061230       NA

metrics has one row per virtual patient run, summarising the whole course:

head(res$metrics) |> mutate(across(starts_with("SIGNAL"), \(x) round(x, 2)))
#>   DRAW SIM ID  CUM_DOSE N_DOSES N_INCREASES N_DECREASES N_HOLDS N_NOT_DUE
#> 1    1   1  1 16625.000       9           3           0       0         0
#> 2    1   1  2 13750.000       9           1           0       0         0
#> 3    1   1  3  9941.406       9           1           2       0         0
#> 4    1   1  4  9687.500       9           0           1       0         0
#> 5    1   1  5  7656.250       9           0           2       0         0
#> 6    1   2  1 16765.625       9           3           0       0         0
#>   DISCONTINUED TIME_TO_DISCONT SIGNAL_MIN SIGNAL_MAX SIGNAL_MEAN
#> 1        FALSE              NA          0      12.39        8.82
#> 2        FALSE              NA          0      14.60       11.21
#> 3        FALSE              NA          0      20.61       12.97
#> 4        FALSE              NA          0      23.54       15.97
#> 5        FALSE              NA          0      22.88       13.33
#> 6        FALSE              NA          0      11.04        7.75
#>   PCT_TIME_IN_WINDOW AUC_TARGET_ATTAINMENT ETA_SUPPLIED DOSE_ORACLE
#> 1          0.5555556                    NA        FALSE       FALSE
#> 2          0.7777778                    NA        FALSE       FALSE
#> 3          0.5555556                    NA        FALSE       FALSE
#> 4          0.7777778                    NA        FALSE       FALSE
#> 5          0.6666667                    NA        FALSE       FALSE
#> 6          0.2222222                    NA        FALSE       FALSE

PCT_TIME_IN_WINDOW is the fraction (between 0 and 1) of that patient’s decisions at which the signal was inside target_window. CUM_DOSE and N_DOSES count the controller’s doses.

Summaries across all runs show how the policy performs in the population. The trough at each decision time:

res$decisions |>
  group_by(TIME) |>
  summarise(p10 = quantile(SIGNAL, 0.1), p50 = median(SIGNAL), p90 = quantile(SIGNAL, 0.9)) |>
  ggplot(aes(TIME, p50)) +
  geom_ribbon(aes(ymin = p10, ymax = p90), alpha = 0.25) +
  geom_line() +
  geom_hline(yintercept = c(10, 20), linetype = "dashed") +
  labs(x = "Time (h)", y = "Measured trough (mg/L)")
Figure 23.1: Measured trough at each decision time across 1000 virtual patient runs: median (line), 10th–90th percentile (band), target window (dashed).

And the dose each patient ended up on:

res$doses |>
  filter(SIM <= 3) |>
  ggplot(aes(TIME, AMT, group = interaction(SIM, ID))) +
  geom_step(alpha = 0.6) +
  geom_hline(yintercept = c(250, 2000), linetype = "dotted") +
  labs(x = "Time (h)", y = "Dose (mg)")
Figure 23.2: Dose issued at each decision for the five subjects in the first three replicates.

Over all runs, the mean fraction of decisions in the target window is 0.692, and the mean cumulative dose is 11610 mg.

Options that matter

Argument Default Meaning
model — Model file; it must contain an [adaptive_dosing] block
data NULL Dataset with subjects, observation grid, covariates and optionally base doses. When NULL, the model’s [data] block is used
n_sim 1 Replicates per subject
seed 42 Random seed
verify TRUE After each run, replay the realized doses through the standard simulation engine and stop with an error if the result diverges
max_decisions 0 Upper limit on decision points per run (a runaway guard); 0 keeps the engine default

max_decisions is a safety limit, not a way to shorten the schedule. A schedule with more decision points than the limit stops with an error:

try(ferx_simulate_adaptive(ex$model, ex$data, n_sim = 1, seed = 1, max_decisions = 3))
#> Error in ferx_rust_simulate_adaptive(model_path = normalizePath(model),  : 
#>   ferx_simulate_adaptive: decision schedule has 9 points, exceeding max_decisions = 3 (runaway guard); raise `max_decisions` in the simulate options if the schedule is intentional [E_ADAPTIVE_OPTIONS]

A model without an [adaptive_dosing] block is rejected with an error as well. Use ferx_simulate() for fixed regimens.

Variants

Comparing two dosing strategies

The main use of adaptive simulation is comparing policies. Here is a more aggressive version of the same protocol, which changes the dose in 50% steps instead of 25%. Edit a copy of the model: ferx_model_set_section() edits a file path in place, and the example model lives inside the installed package.

strategy_dir <- file.path(tempdir(), "adaptive-strategies")
dir.create(strategy_dir, showWarnings = FALSE)
aggressive <- file.path(strategy_dir, "adaptive_tdm_aggressive.ferx")
invisible(file.copy(ex$model, aggressive, overwrite = TRUE))

rules <- 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_TIME_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
rules <- sub("increase 25%", "increase 50%", rules, fixed = TRUE)
rules <- sub("decrease 25%", "decrease 50%", rules, fixed = TRUE)
ferx_model_set_section(aggressive, "adaptive_dosing", rules)

Simulate both strategies with the same seed and compare the per-patient metrics:

res_aggressive <- ferx_simulate_adaptive(aggressive, ex$data, n_sim = n_sim, seed = 1)

strategies <- bind_rows(
  `25% steps` = res$metrics,
  `50% steps` = res_aggressive$metrics,
  .id = "strategy"
) |>
  group_by(strategy) |>
  summarise(
    `mean fraction in window` = mean(PCT_TIME_IN_WINDOW),
    `mean cumulative dose (mg)` = mean(CUM_DOSE),
    `mean increases` = mean(N_INCREASES),
    `mean decreases` = mean(N_DECREASES)
  )
strategies |>
  gt::gt() |>
  gt::fmt_number(columns = -strategy, decimals = 2)
Table 23.1: Two titration strategies, 1000 virtual patient runs each.
strategy mean fraction in window mean cumulative dose (mg) mean increases mean decreases
25% steps 0.69 11,609.68 0.72 0.91
50% steps 0.71 11,504.47 0.56 0.83

The larger steps put slightly more decisions in the target window (0.71 against 0.69) with fewer dose changes per patient (1.39 against 1.62), for about the same cumulative dose. On this population the two policies perform almost alike. A policy is judged by such a comparison, run with the same seed, rather than by either column on its own.

A loading dose followed by titration

A dataset can also carry a base regimen: ordinary dose rows that the controller adds its own doses to. adaptive_vanco_loading gives one typical patient a 1500 mg loading dose at time 0 and titrates daily maintenance boluses from 24 h. It titrates on the latent concentration, using observe rather than an assay-noised measurement:

ex_load <- ferx_example("adaptive_vanco_loading")
ferx_model_get_section(ex_load$model, "adaptive_dosing")
#> # [adaptive_dosing]
#>   observe       = CENT / V                # titrate on the latent trough concentration
#>   at            = every 24 from 24 to 144 # daily MAINTENANCE decisions, after the load
#>   start_dose    = 750                     # empiric maintenance start (mg): subtherapeutic
#>   route         = bolus(cmt=1)            # maintenance boluses into the drug compartment
#>   dose_bounds   = [250, 4000]             # mg
#>   target_window = [10, 15]                # report % of days with trough in [10, 15] mg/L
#>   when signal < 10 : increase 25%         # subtherapeutic trough -> raise the dose
#>   when signal > 15 : decrease 25%         # supratherapeutic trough -> lower the dose
read.csv(ex_load$data, na.strings = ".")
#>   ID TIME DV  AMT EVID CMT MDV
#> 1  1    0  0 1500    1   1   1
#> 2  1   24  0    0    0   1   0
#> 3  1   48  0    0    0   1   0
#> 4  1   72  0    0    0   1   0
#> 5  1   96  0    0    0   1   0
#> 6  1  120  0    0    0   1   0
#> 7  1  144  0    0    0   1   0
res_load <- ferx_simulate_adaptive(ex_load$model, ex_load$data, n_sim = 1, seed = 1)
res_load$doses |> select(TIME, AMT, SIGNAL, RULE)
#>   TIME      AMT    SIGNAL                       RULE
#> 1   24  937.500  5.647391 signal < 10 : increase 25%
#> 2   48 1171.875  5.230581 signal < 10 : increase 25%
#> 3   72 1464.844  5.987445 signal < 10 : increase 25%
#> 4   96 1831.055  7.318415 signal < 10 : increase 25%
#> 5  120 2288.818  9.098053 signal < 10 : increase 25%
#> 6  144 2288.818 11.357516                      bolus
res_load$metrics |> select(CUM_DOSE, N_DOSES, N_INCREASES, PCT_TIME_IN_WINDOW)
#>   CUM_DOSE N_DOSES N_INCREASES PCT_TIME_IN_WINDOW
#> 1  9982.91       6           4          0.1666667

The dose ledger and CUM_DOSE (9982.9 mg) contain only the controller’s maintenance doses. The 1500 mg loading dose from the dataset is not counted, so the total given is 11482.9 mg.

Simulating at fitted estimates

So far every simulation ran at the model file’s values. Once TDM data from the protocol are collected, the protocol can be re-evaluated at the estimates fitted to them: ferx_simulate_adaptive() takes the fit as fit =, as ferx_simulate() does (Simulating scenarios). To have data to fit, run the protocol on 20 patients whose typical clearance is 6 L/h rather than the model file’s 4, and measure their troughs with assay error. The doses are the ones the protocol chose; ferx_simulate() on those records adds the assay error the measurements carry:

fast_lines <- sub("theta TVCL(4.0,  0.5,  20.0)", "theta TVCL(6.0,  0.5,  20.0)", readLines(ex$model), fixed = TRUE)
stopifnot(any(grepl("theta TVCL(6.0,  0.5,  20.0)", fast_lines, fixed = TRUE)))
fast_model <- file.path(strategy_dir, "adaptive_tdm_fast_clearance.ferx")
writeLines(fast_lines, fast_model)
protocol <- ferx_simulate_adaptive(fast_model, ex$data, n_sim = 4, seed = 2)
patient <- function(d) (as.integer(d$SIM) - 1L) * 5L + as.integer(d$ID)  # 4 runs x 5 subjects -> 20 patients
tdm_records <- bind_rows(
  transmute(protocol$doses, ID = patient(protocol$doses), TIME, DV = NA, EVID = 1, AMT, CMT, RATE, MDV = 1),
  protocol$trajectories |> filter(TIME > 0) |>
    transmute(ID = patient(filter(protocol$trajectories, TIME > 0)), TIME, DV = NA, EVID = 0, AMT = NA,
              CMT = 1, RATE = 0, MDV = 0)
) |> arrange(ID, TIME, EVID)
records_file <- file.path(strategy_dir, "tdm_records.csv")
write.csv(tdm_records, records_file, row.names = FALSE, na = ".")
# the empty DV cells raise the W_DESIGN_DV warning that every design file gets (@sec-simulation)
measured <- suppressWarnings(ferx_simulate(fast_model, records_file, n_sim = 1, seed = 3))
troughs <- tdm_records$EVID == 0
tdm_records$DV[troughs] <- measured$DV_SIM[match(paste(tdm_records$ID, tdm_records$TIME)[troughs],
                                                 paste(measured$ID, measured$TIME))]
stopifnot(!anyNA(tdm_records$DV[troughs]))
tdm_file <- file.path(strategy_dir, "tdm_collected.csv")
write.csv(tdm_records, tdm_file, row.names = FALSE, na = ".")
tdm_fit <- ferx_fit(ex$model, tdm_file, verbose = FALSE)
rbind(model_file = tdm_fit$theta_init, estimate = tdm_fit$theta, se = tdm_fit$se_theta)
#>                 TVCL      TVV
#> model_file 4.0000000 50.00000
#> estimate   6.9498879 56.19010
#> se         0.4742187  4.31254

Each trough is recorded before the dose given at the same time, as the protocol measured it. The fit puts the typical clearance well above the model file’s value. Simulating the protocol at the fit shows what that does to it:

Table 23.2: The 25% titration protocol simulated at the model file’s values and at the estimates fitted to the collected TDM data.
res_at_fit <- ferx_simulate_adaptive(ex$model, ex$data, n_sim = n_sim, seed = 1, fit = tdm_fit)
at_fit <- bind_rows(`model file` = res$metrics, `fitted estimates` = res_at_fit$metrics, .id = "parameters") |>
  group_by(parameters = factor(parameters, c("model file", "fitted estimates"))) |>
  summarise(`mean fraction in window` = mean(PCT_TIME_IN_WINDOW),
            `mean cumulative dose (mg)` = mean(CUM_DOSE),
            `mean increases` = mean(N_INCREASES))
at_fit
#> # A tibble: 2 × 4
#>   parameters      mean fraction in win…¹ mean cumulative dose…² `mean increases`
#>   <fct>                            <dbl>                  <dbl>            <dbl>
#> 1 model file                       0.692                 11610.            0.717
#> 2 fitted estimat…                  0.409                 15739.            2.25 
#> # ℹ abbreviated names: ¹​`mean fraction in window`, ²​`mean cumulative dose (mg)`

At the fitted clearance the protocol starts too low for these patients, so it escalates more often and gives more drug in total, and fewer of its trough readings fall in the 10 to 20 mg/L window: 0.41 against 0.69. That is the case for a higher starting dose, which the loading-dose example above shows how to write. The random effects are still drawn from the fitted omega, so each run is a new virtual patient from the fitted population.

Simulating the fitted patients themselves

The 20 patients in the fit are known patients now: the fit estimated each one’s clearance deviation, and tdm_fit$ebe_etas holds those estimates as a data frame with ID and one column per eta in the model’s order. Passed as etas =, they replace the omega draw for each subject whose ID has a row, so the protocol is re-run on these patients rather than on new ones. The design gives the 20 patients the dataset’s observation grid and no doses, as adaptive_tdm does:

grid <- read.csv(ex$data, na.strings = ".") |> filter(ID == 1)
known_design <- bind_rows(lapply(as.integer(tdm_fit$ebe_etas$ID), \(id) mutate(grid, ID = id)))
known_file <- file.path(strategy_dir, "tdm_known_patients.csv")
write.csv(known_design, known_file, row.names = FALSE, na = ".")
res_known <- ferx_simulate_adaptive(ex$model, known_file, n_sim = 20, seed = 1,
                                    fit = tdm_fit, etas = tdm_fit$ebe_etas)
per_patient <- res_known$metrics |>
  group_by(ID) |>
  summarise(in_window = mean(PCT_TIME_IN_WINDOW), cum_dose = mean(CUM_DOSE), sd_cum_dose = sd(CUM_DOSE)) |>
  left_join(tdm_fit$ebe_etas, by = "ID") |>
  relocate(ETA_CL, .after = ID) |>
  arrange(ETA_CL)
per_patient |> mutate(across(where(is.numeric), \(x) round(x, 2))) |> print(n = Inf)
#> # A tibble: 20 × 5
#>    ID    ETA_CL in_window cum_dose sd_cum_dose
#>    <chr>  <dbl>     <dbl>    <dbl>       <dbl>
#>  1 12     -0.43      0.75   13535.       410. 
#>  2 20     -0.43      0.77   13043.      1046. 
#>  3 10     -0.41      0.77   13566.       578. 
#>  4 1      -0.25      0.77   13887.       611. 
#>  5 9      -0.22      0.75   14258.      1023. 
#>  6 8      -0.18      0.72   15059.      1367. 
#>  7 15     -0.13      0.67   16348.       317. 
#>  8 13     -0.13      0.67   16250        626. 
#>  9 14     -0.1       0.66   16234.       762. 
#> 10 4      -0.01      0.53   16639.       123. 
#> 11 19      0.04      0.34   16738.        44.1
#> 12 11      0.07      0.22   16763.        10.5
#> 13 5       0.11      0.05   16766.         0  
#> 14 3       0.12      0.05   16766.         0  
#> 15 2       0.22      0      16766.         0  
#> 16 16      0.29      0      16766.         0  
#> 17 18      0.33      0      16766.         0  
#> 18 6       0.35      0      16766.         0  
#> 19 17      0.35      0      16766.         0  
#> 20 7       0.4       0      16766.         0

The population summary of the previous section hides who the protocol fails. Here the answer has names: 6 of the 20 patients, the ones with the highest estimated clearance, never have a trough in the window. The protocol has them at the 2000 mg cap from the fourth dose on, and their troughs stay below 10 mg/L there. Every ETA_SUPPLIED in res_known$metrics is TRUE.

A patient’s replicates share their etas, so what still varies between them is what is drawn per run: the kappas (this model has none) and the assay error the controller titrates on. That is why most patients’ cumulative dose has a nonzero SD (sd_cum_dose). The patients with an SD of 0 reach the cap in every replicate: noise in the trough does not change a dose that is already at its bound.

Known and virtual patients can run in one population. A design subject without a row in etas is refused by default (unmatched = "refuse"); unmatched = "draw" draws its etas from the fitted omega instead. Add five new patients, IDs 101 to 105, to the 20 known ones:

mixed_design <- bind_rows(known_design, filter(known_design, ID <= 5) |> mutate(ID = ID + 100L))
mixed_file <- file.path(strategy_dir, "tdm_mixed.csv")
write.csv(mixed_design, mixed_file, row.names = FALSE, na = ".")
res_mixed <- ferx_simulate_adaptive(ex$model, mixed_file, n_sim = 20, seed = 1,
                                    fit = tdm_fit, etas = tdm_fit$ebe_etas, unmatched = "draw")
res_mixed$metrics |> count(new_patient = as.integer(ID) > 100, ETA_SUPPLIED)
#>   new_patient ETA_SUPPLIED   n
#> 1       FALSE         TRUE 400
#> 2        TRUE        FALSE 100

$metrics$ETA_SUPPLIED tells the two apart: TRUE for a run at a patient’s supplied etas, FALSE for a drawn one.

Two cautions. First, a supplied eta is a point estimate, and the simulation treats it as exact. Each patient here has 8 troughs and the eta shrinkage is 0.3%, so the estimates are informative. With sparse TDM and high shrinkage the EBEs sit near zero and the spread between patients is understated, which makes the protocol look better than it is. Second, the EBEs are only as good as the fit they come from. adaptive_tdm is a simulation design: every DV in it is 0. A fit to it warns W_ZERO_DV_MAGNITUDE_ONLY and never leaves its initial estimates. Its objective is flat, so the restart that checks an unmoved start comes back to the same value, and the fit reports converged = TRUE with stationary_start = TRUE rather than a stall (Estimation methods and controlling the fit); the failed covariance step, which names every parameter as a flat objective, is what gives it away. The ETA shrinkage is 100% and every patient’s EBE is 0. Supplying those etas would simulate every patient as the typical patient.

NoteChanged after ferx-r 0.4.0

In ferx-r 0.4.0 this fit is also reported converged and stays at its initial estimates, but it warns W_STALLED_AT_INIT (ferx-core #2506), raises no W_ZERO_DV_MAGNITUDE_ONLY, and has no fit$stationary_start. The failed covariance step, the 100% shrinkage and the zero EBEs are the same.

ImportantNeeds ferx-r newer than 0.4.0

The fit, etas and unmatched arguments of ferx_simulate_adaptive() and the ETA_SUPPLIED column of its metrics are not in ferx-r 0.4.0, and neither are the dosing-interval ladder (intervals, start_interval, lengthen, shorten), the "not_due" decision outcome and the INTERVAL and N_NOT_DUE columns it adds, or the AUC_TARGET_ATTAINMENT column of metrics.

Pitfalls

  • The dose ledger excludes base doses. doses, CUM_DOSE and N_DOSES count controller doses only. Add the dose rows of your dataset to get the full regimen.

  • Signals are read before the dose; trajectories at the same time include a bolus. The controller reads the level before the dose given at that decision time. A trajectories row at the same time already includes a bolus given then. In the loading-dose run the first signal is 5.65 mg/L, while the trajectory at 24 h is 17.37 mg/L. The difference is the 937.5 mg bolus divided by the volume of 80 L. Use decisions$SIGNAL for trough-based attainment.

  • PCT_TIME_IN_WINDOW is a fraction of decisions. Despite its name, it is a proportion between 0 and 1 of the signal-bearing decisions, not a percentage of time.

  • target_window does not steer dosing. Only the when rules change doses. The window only feeds the attainment metric.

  • Scope. The controller runs on ODE models, titrates on one signal per block, and rejects stochastic ([diffusion]) models. A steady-state, lag-timed or modelled-rate (RATE) base dose under a time-varying covariate or IOV is rejected with an error; base doses with system resets (EVID = 3/4) run on every path. ?ferx_simulate_adaptive and the ferx-core page list the rest.

    NoteChanged after ferx-r 0.4.0

    ferx-r 0.4.0 also rejects a base regimen with system resets under a time-varying covariate or IOV, and an auc_target metric combined with a time-varying covariate, a TIME-dependent PK parameter, IOV or a reset.

Summary

  • Declare the dosing policy in [adaptive_dosing] and simulate it with ferx_simulate_adaptive().
  • Read decisions and doses to see how individual patients were titrated. Use metrics to compare strategies across the population.
  • Compare strategies by editing a copy of the model and simulating each version with the same seed.
  • Re-run a protocol on fitted patients with fit = fit, etas = fit$ebe_etas, and mix in new patients with unmatched = "draw".

Reference

TipReference