Skip to main content

PK/PD and multiple endpoints

Where you are

So far every model had one endpoint, a drug concentration. Pharmacodynamic (PD) models describe a response. They can be linked to the pharmacokinetics and fitted together with the concentrations, used to compute a predicted effect from a PK fit, or stand on their own as an equation of time or dose. This chapter covers all three with the bundled examples.

WarningMaturity: stable, beta and experimental parts

The error models are stable in ferx-core. ODE models, [scaling] and [derived] are beta. Compartment-free models are documented in the ferx-core structural model page. See feature maturity.

The data

emax_pkpd has 3 subjects with an oral dose, plasma concentrations and effect measurements in one dataset. The CMT column tells the endpoints apart: 2 for the concentration, 3 for the effect:

pkpd <- ferx_example("emax_pkpd")
pkpd_dir <- file.path(tempdir(), "pkpd")
dir.create(pkpd_dir, showWarnings = FALSE)
pkpd_data <- read.csv(pkpd$data, na.strings = ".")
filter(pkpd_data, ID == 1) |> arrange(CMT, TIME)
#>    ID TIME   DV EVID AMT CMT RATE MDV
#> 1   1  0.0   NA    1 100   1    0   1
#> 2   1  0.5  7.8    0  NA   2    0   0
#> 3   1  1.0  9.5    0  NA   2    0   0
#> 4   1  2.0  8.1    0  NA   2    0   0
#> 5   1  4.0  5.2    0  NA   2    0   0
#> 6   1  8.0  2.1    0  NA   2    0   0
#> 7   1  1.0 12.4    0  NA   3    0   0
#> 8   1  2.0 21.7    0  NA   3    0   0
#> 9   1  4.0 28.3    0  NA   3    0   0
#> 10  1  8.0 24.9    0  NA   3    0   0
count(filter(pkpd_data, EVID == 0), CMT)
#>   CMT  n
#> 1   2 15
#> 2   3 12

Minimal runnable call: a joint PK/PD fit

The model has three ODE states: the depot, the central compartment and an effect compartment that follows the plasma concentration with rate KE0. [scaling] gives one readout per observed CMT (Observation scaling with [scaling]), and [error_model] one residual error model per CMT:

invisible(ferx_model_get_section(pkpd$model, "odes"))
#> # [odes]
#>   d/dt(depot)   = -KA * depot
#>   d/dt(central) =  KA * depot - CL/V * central
#>   d/dt(effect)  =  KE0 * (central/V - effect)
invisible(ferx_model_get_section(pkpd$model, "scaling"))
#> # [scaling]
#>   y[CMT=2] = central / V                                  # plasma conc (mg/L)
#>   y[CMT=3] = E0 + EMAX * effect^GAMMA / (EC50^GAMMA + effect^GAMMA)  # Emax PD
invisible(ferx_model_get_section(pkpd$model, "error_model"))
#> # [error_model]
#>   CMT=2: DV ~ proportional(PROP_ERR_PK)   # central compartment (PK)
#>   CMT=3: DV ~ additive(ADD_ERR_PD)        # effect compartment (PD)
invisible(ferx_model_get_section(pkpd$model, "fit_options"))
#> # [fit_options]
#>   method     = focei
#>   maxiter    = 500
#>   covariance = true
fit_pkpd <- ferx_fit(pkpd$model, pkpd$data, verbose = FALSE)

Both endpoints enter one likelihood, so the PK and PD parameters are estimated together. Both readouts are differentiated analytically, so the default gradient = "auto" takes the analytic gradient (fit_pkpd$gradient_used is “analytic”). Finite differences stop short of the optimum on this model, as the simulation–estimation run below shows.

NoteChanged after ferx-r 0.4.0

In ferx-r 0.4.0 the bundled model file sets gradient = fd, with a comment calling it required (ferx-core #1625, fixed after that release). With 0.4.0, pass gradient = "auto" to ferx_fit() for this model.

Reading the result

sdtab keeps the CMT column, so each endpoint can be plotted separately:

fit_pkpd$sdtab |>
  mutate(endpoint = ifelse(CMT == 2, "Concentration (CMT 2)", "Effect (CMT 3)")) |>
  ggplot(aes(TIME, colour = factor(ID))) +
  geom_point(aes(y = DV)) +
  geom_line(aes(y = IPRED)) +
  facet_wrap(~ endpoint, scales = "free_y") +
  labs(x = "Time (h)", y = NULL, colour = "ID")
Figure 20.1: Joint PK/PD fit: observations (points) and individual predictions (lines) by endpoint.

The predictions follow the data, but three subjects do not determine the PD parameters:

fit_pkpd$estimates[, c("estimate", "rse_pct")]
#>                 estimate    rse_pct
#> TVCL         1.973333887   2.070162
#> TVV          8.640699137   2.473635
#> TVKA         2.371622757   3.851734
#> TVKE0        0.251557163   3.204320
#> TVE0         3.208106164 123.490320
#> TVEMAX      45.243462927  30.558207
#> TVEC50       3.992943951  21.518778
#> TVGAMMA      1.418900856  31.694421
#> ETA_CL       0.001097516  95.714970
#> ETA_V        0.001255828  97.799178
#> PROP_ERR_PK  0.026041252  23.513484
#> ADD_ERR_PD   0.416648308  23.453727
pd <- c("TVE0", "TVEMAX", "TVEC50", "TVGAMMA")
round(fit_pkpd$cor_matrix[pd, pd], 2)
#>          TVE0 TVEMAX TVEC50 TVGAMMA
#> TVE0     1.00  -0.96  -0.80    0.97
#> TVEMAX  -0.96   1.00   0.94   -0.99
#> TVEC50  -0.80   0.94   1.00   -0.90
#> TVGAMMA  0.97  -0.99  -0.90    1.00
pkpd_warnings <- ferx_get_warnings(fit_pkpd, as_df = TRUE)
pkpd_warnings[, c("severity", "category")]
#>   severity         category
#> 1  warning     inflated_rse
#> 2  warning high_correlation
#> 3 critical condition_number

The typical PK parameters are well determined, with relative standard errors of at most 4%; with three subjects their between-subject variances are poorly determined (96% and more). The typical PD parameters are not well determined either: the baseline TVE0 has a relative standard error of 123%, and the PD parameters are almost perfectly correlated with each other (|r| up to 0.99). The model structure is fine; the question is what data would determine the PD parameters, which the simulation–estimation runs below answer.

Options that matter

Where Syntax Meaning
Data CMT on observation rows Which endpoint the row is
[structural_model] ode(states=[depot, central, effect]) No single obs_cmt; [scaling] defines each readout
[scaling] y[CMT=2] = central / V, y[CMT=3] = <expr> One readout per observed CMT
[error_model] CMT=2: DV ~ proportional(...), CMT=3: DV ~ additive(...) One residual error model per CMT (ODE models only)
[structural_model] y = <expr> with no pk or ode line A compartment-free model
[derived] EFF = EMAX * IPRED / (EC50 + IPRED) An effect computed from a PK fit

Every observed CMT needs a readout and an error model. The two forms cannot be mixed in one block (error model).

Variants

Simulation and estimation: can a design support the model?

To see whether the joint model can be estimated with a realistic design, simulate a study from the model’s initial values and fit it again. simulate_study() below writes a design, simulates it once with ferx_simulate() (without fit, so with the model file’s parameters, Simulating scenarios) and returns the simulated study as a data file. The first design is the bundled one, scaled up: 30 subjects on 100, with six concentration and six effect samples each. recovery() puts each estimate beside the value it was simulated with:

simulate_study <- function(doses, file, seed = 42) {
  ids <- seq_along(doses)
  design <- bind_rows(
    data.frame(ID = ids, TIME = 0, DV = NA, EVID = 1, AMT = doses, CMT = 1, RATE = 0, MDV = 1),
    expand.grid(ID = ids, TIME = c(0.5, 1, 2, 4, 8, 12)) |>
      mutate(DV = NA, EVID = 0, AMT = NA, CMT = 2, RATE = 0, MDV = 0),
    expand.grid(ID = ids, TIME = c(1, 2, 4, 8, 12, 24)) |>
      mutate(DV = NA, EVID = 0, AMT = NA, CMT = 3, RATE = 0, MDV = 0)
  ) |> arrange(ID, TIME, desc(EVID), CMT)
  design_file <- sub("\\.csv$", "_design.csv", file)
  write.csv(design, design_file, row.names = FALSE, na = ".")
  # the empty DV cells are the points to simulate, which ferx notes as W_DESIGN_DV
  simulated <- suppressWarnings(ferx_simulate(pkpd$model, design_file, n_sim = 1, seed = seed))
  rows <- design$EVID == 0
  design$DV[rows] <- simulated$DV_SIM[match(paste(design$ID, design$TIME, design$CMT)[rows],
                                            paste(simulated$ID, simulated$TIME, simulated$CMT))]
  write.csv(design, file, row.names = FALSE, na = ".")
  file
}
recovery <- function(f) {
  data.frame(parameter = c(names(f$theta), f$eta_names, f$sigma_names),
             simulated_with = c(f$theta_init, f$omega_init[c(1, 4)], f$sigma_init),
             estimate = c(f$theta, diag(f$omega), f$sigma),
             rse_pct = f$estimates$rse_pct)
}
one_dose <- simulate_study(rep(100, 30), file.path(pkpd_dir, "pkpd_100.csv"))
fit_one_dose <- ferx_fit(pkpd$model, one_dose, verbose = FALSE)
recovery(fit_one_dose)
#>               parameter simulated_with   estimate   rse_pct
#> TVCL               TVCL           5.00  5.1338081  6.466668
#> TVV                 TVV          50.00 46.7909951  5.825120
#> TVKA               TVKA           1.00  0.9322938  3.739269
#> TVKE0             TVKE0           0.30  0.2885711  5.516660
#> TVE0               TVE0           2.00  3.1317211 11.365332
#> TVEMAX           TVEMAX          40.00 10.8230576 18.372539
#> TVEC50           TVEC50           5.00  0.9003789 16.113025
#> TVGAMMA         TVGAMMA           1.00  1.8742908 21.027653
#> ETA_CL           ETA_CL           0.09  0.1168019 26.960125
#> ETA_V             ETA_V           0.09  0.0867357 26.709415
#> PROP_ERR_PK PROP_ERR_PK           0.10  0.1017429  6.426023
#> ADD_ERR_PD   ADD_ERR_PD           1.00  0.9723118  5.567341

The PK parameters are recovered and the PD parameters are not: TVEMAX ends at 10.8 and TVEC50 at 0.9, where the simulation used 40 and 5, and their relative standard errors of 18% and 16% do not flag it. This is where the data put the optimum, not a fit that went wrong. maxiter = 0 evaluates the objective at the starting values without moving, which here are the simulation values themselves:

# suppress the R warning that reports overriding the model file's covariance setting
at_simulation_values <- suppressWarnings(ferx_fit(pkpd$model, one_dose, covariance = FALSE,
                                                  settings = list(maxiter = 0), verbose = FALSE))
data.frame(fit = fit_one_dose$ofv, simulation_values = at_simulation_values$ofv)
#>         fit simulation_values
#> 1 -256.8763         -233.1005
one_dose_data <- read.csv(one_dose, na.strings = ".")
max(one_dose_data$DV[one_dose_data$CMT == 2])
#> [1] 2.915333

The true parameters score 23.8 OFV points worse than the fit. The cause is the design: with 100 for every subject, the concentration never rises above 2.9, below the EC50 of 5, so the data see only the lower part of the Emax curve, and a smaller EMAX with a smaller EC50 traces nearly the same part. More subjects on the same dose do not help. Doses that reach past EC50 do – the same number of subjects, ten each on 100, 300 and 1000:

dose_range <- simulate_study(rep(c(100, 300, 1000), each = 10), file.path(pkpd_dir, "pkpd_dose_range.csv"))
fit_dose_range <- ferx_fit(pkpd$model, dose_range, verbose = FALSE)
recovery(fit_dose_range)
#>               parameter simulated_with    estimate   rse_pct
#> TVCL               TVCL           5.00  5.06373398  6.361780
#> TVV                 TVV          50.00 47.55294487  5.717354
#> TVKA               TVKA           1.00  0.95822156  3.145032
#> TVKE0             TVKE0           0.30  0.29369562  3.169814
#> TVE0               TVE0           2.00  2.50093777 15.172120
#> TVEMAX           TVEMAX          40.00 36.69990092  4.425980
#> TVEC50           TVEC50           5.00  4.24526684  7.010147
#> TVGAMMA         TVGAMMA           1.00  1.06964157  5.301892
#> ETA_CL           ETA_CL           0.09  0.11452809 26.578097
#> ETA_V             ETA_V           0.09  0.08791938 26.469347
#> PROP_ERR_PK PROP_ERR_PK           0.10  0.10349949  6.311739
#> ADD_ERR_PD   ADD_ERR_PD           1.00  0.98207341  5.966799

With concentrations up to 29, TVEMAX and TVEC50 come out at 36.7 and 4.2, within 16% of 40 and 5 instead of several-fold off, and the largest relative standard error of any parameter is 27%. One simulated study is one draw: repeat it with other seeds before settling a design. A simulation–estimation run answers the design question before the study is run.

Finite differences on this model

The fits above take the analytic gradient. With gradient = "fd", the default optimizer reaches the same optimum on both designs. A gradient-based optimizer on finite differences, which Estimation methods and controlling the fit suggests when bobyqa stops on a slope, does not:

gradient_runs <- function(data, fit_auto) {
  list(`gradient = "fd"` = ferx_fit(pkpd$model, data, gradient = "fd", verbose = FALSE),
       # suppress the R warning that reports overriding the model file's optimizer
       `gradient = "fd", optimizer = slsqp` = suppressWarnings(
         ferx_fit(pkpd$model, data, gradient = "fd", settings = list(optimizer = "slsqp"), verbose = FALSE)),
       `gradient = "auto"` = fit_auto)
}
fd_runs <- list(`100 for all` = gradient_runs(one_dose, fit_one_dose),
                `100, 300, 1000` = gradient_runs(dose_range, fit_dose_range))
do.call(rbind, lapply(names(fd_runs), function(design) {
  do.call(rbind, lapply(names(fd_runs[[design]]), function(run) {
    f <- fd_runs[[design]][[run]]
    data.frame(design = design, fit = run, ofv = f$ofv, TVEMAX = f$theta[["TVEMAX"]],
               TVEC50 = f$theta[["TVEC50"]], max_rse_pct = max(f$estimates$rse_pct))
  }))
}))
#>           design                                fit       ofv   TVEMAX
#> 1    100 for all                    gradient = "fd" -256.8763 10.81705
#> 2    100 for all gradient = "fd", optimizer = slsqp -253.7087 12.67404
#> 3    100 for all                  gradient = "auto" -256.8763 10.82306
#> 4 100, 300, 1000                    gradient = "fd"  177.7509 36.69815
#> 5 100, 300, 1000 gradient = "fd", optimizer = slsqp  181.2158 38.47807
#> 6 100, 300, 1000                  gradient = "auto"  177.7508 36.69990
#>      TVEC50 max_rse_pct
#> 1 0.8999972    26.94976
#> 2 1.0338286    39.25998
#> 3 0.9003789    26.96012
#> 4 4.2441650    26.56573
#> 5 4.4862046    27.01920
#> 6 4.2452668    26.57810

The default-optimizer finite-difference fits land within 1e-04 of the analytic optimum. The slsqp fits stop between 3.2 and 3.5 OFV points above it. The objective is the same on both paths (the analytic optimum scores the same OFV on the finite-difference path), so it is the optimizer on a finite-difference gradient that loses the optimum. On the 100 design this is the trap of a simulation–estimation run: the slsqp fit stops at a TVEMAX of 12.7, between the analytic optimum at 10.8 and the simulation value 40, so the design looks better able to support the model than it is. Fit a simulated study with the most reliable settings you have, and compare its OFV with the objective at the simulation values. For this model, leave the gradient to ferx.

NoteChanged after ferx-r 0.4.0

In ferx-r 0.4.0, the default-optimizer finite-difference fits also stop above the optimum on this model.

Effects computed from a PK fit

When the PD parameters are known, an effect can be computed from the PK predictions without PD data. warfarin_derived_pkpd fixes EMAX, EC50 and a minimum effective concentration MEC as thetas and uses them in [derived]:

derived_pkpd <- ferx_example("warfarin_derived_pkpd")
invisible(ferx_model_get_section(derived_pkpd$model, "derived"))
#> # [derived]
#>   KE     = CL / V
#>   T_HALF = 0.6931472 / KE
#> 
#>   # Emax PD effect at current concentration
#>   EFF    = EMAX * IPRED / (EC50 + IPRED)
#> 
#>   # TAD-gated Cmax: peak within the current dosing interval
#>   CMAX_INTERVAL = max(IPRED, TAD < 24)
#> 
#>   # Time above MEC per dosing interval (hours)
#>   TAM_TAU = integral(1.0, IPRED > MEC, window=24, anchor=0, step=0.1)
#> 
#>   # Time above MEC on day 1 specifically
#>   TAM_D1  = integral(1.0, IPRED > MEC, from=0, to=24, step=0.1)
fit_derived <- ferx_fit(derived_pkpd$model, derived_pkpd$data, verbose = FALSE)
filter(fit_derived$sdtab, ID == 1) |> select(TIME, IPRED, EFF, CMAX_INTERVAL, TAM_D1)
#>     TIME     IPRED      EFF CMAX_INTERVAL TAM_D1
#> 1    0.5  5.354089 51.27155      11.38196     24
#> 2    1.0  8.285651 58.73406      11.38196     24
#> 3    2.0 10.708975 62.49322      11.38196     24
#> 4    4.0 11.381964 63.31243      11.38196     24
#> 5    8.0 10.756208 62.55333      11.38196     24
#> 6   12.0 10.067873 61.63435      11.38196     24
#> 7   24.0  8.253757 58.67379      11.38196     24
#> 8   48.0  5.547264 51.92084      11.38196     24
#> 9   72.0  3.728258 44.32955      11.38196     24
#> 10  96.0  2.505723 36.40899      11.38196     24
#> 11 120.0  1.684070 28.76251      11.38196     24

The fixed thetas are used only in [derived], so the fit warns that they do not affect the predictions. That is intended here. With MEC = 0.5 every concentration in these data is above the MEC, so the time above it is the whole day. A copy with MEC = 8 shows a threshold within the concentration range, per 24-hour window:

mec8_model <- file.path(pkpd_dir, "warfarin_derived_pkpd_mec8.ferx")
writeLines(sub("theta MEC(0.5)", "theta MEC(8.0)", readLines(derived_pkpd$model), fixed = TRUE), mec8_model)
fit_mec8 <- ferx_fit(mec8_model, derived_pkpd$data, verbose = FALSE)
filter(fit_mec8$sdtab, ID == 1) |> select(TIME, IPRED, TAM_TAU, TAM_D1)
#>     TIME     IPRED TAM_TAU TAM_D1
#> 1    0.5  5.354089    23.2   23.2
#> 2    1.0  8.285651    23.2   23.2
#> 3    2.0 10.708975    23.2   23.2
#> 4    4.0 11.381964    23.2   23.2
#> 5    8.0 10.756208    23.2   23.2
#> 6   12.0 10.067873    23.2   23.2
#> 7   24.0  8.253757    12.0   23.2
#> 8   48.0  5.547264     NaN   23.2
#> 9   72.0  3.728258     NaN   23.2
#> 10  96.0  2.505723     NaN   23.2
#> 11 120.0  1.684070     NaN   23.2

TAM_TAU evaluates IPRED on its step grid by the nearest observation, so where samples are sparse it is a coarse count. Subject 1’s second window has samples only at 24 and 48 hours: the half of the window nearer 24 hours takes that sample’s 8.25, above 8, and the other half the 48-hour 5.55, so the window counts 12 hours above the MEC, half the window, whatever the concentration does between the two samples. The ferx-core derived quantities page describes the approximation. Sample densely where the time above a threshold matters. From day 3 on its concentration stays below 8, and the time above the MEC in those windows is reported as NaN, not 0. Treat NaN as “never above” when you summarise it.

Models without compartments

A response that is a plain equation of time, dose or other data needs no compartments. emax_timecourse writes the prediction directly in [structural_model]: EFF is an intermediate and y is the prediction. The dataset has no doses:

timecourse <- ferx_example("emax_timecourse")
invisible(ferx_model_get_section(timecourse$model, "structural_model"))
#> # [structural_model]
#>   # No `pk ...` and no `ode(...)` line: this block declares the prediction
#>   # directly. `EFF` is a named intermediate; `y` is the prediction.
#>   EFF = EMAX * TIME / (ET50 + TIME)
#>   y   = E0 - EFF
head(read.csv(timecourse$data, na.strings = "."), 3)
#>   ID TIME      DV MDV
#> 1  1  0.0 19.7922   0
#> 2  1  0.5 17.3779   0
#> 3  1  1.0 17.0081   0
fit_timecourse <- ferx_fit(timecourse$model, timecourse$data, verbose = FALSE)
fit_timecourse$estimates[, c("estimate", "rse_pct")]
#>           estimate   rse_pct
#> TVE0   10.20388022  5.609338
#> TVEMAX  5.91765035  1.708776
#> TVET50  2.09943823  6.894185
#> ETA_E0  0.09235703 25.925786
#> ADD     0.48045173  4.878357

Such a model works with prediction, simulation and the diagnostics like any other. TAD and TAFD are NaN in sdtab, since there are no doses:

head(fit_timecourse$sdtab, 3)
#>   ID TIME      DV      PRED    IPRED       CWRES      IWRES EBE_OFV N_OBS TAFD
#> 1  1  0.0 19.7922 10.203880 19.28424  1.77661869  1.0572592 9.32809     8  NaN
#> 2  1  0.5 17.3779  9.065625 18.14598 -0.87930760 -1.5986671 9.32809     8  NaN
#> 3  1  1.0 17.0081  8.294615 17.37497 -0.04423966 -0.7635992 9.32809     8  NaN
#>   TAD
#> 1 NaN
#> 2 NaN
#> 3 NaN
ggplot(fit_timecourse$sdtab, aes(TIME)) +
  geom_line(aes(y = DV, group = ID), alpha = 0.2) +
  geom_line(data = ferx_predict(timecourse$model, timecourse$data, fit = fit_timecourse) |> distinct(TIME, PRED),
            aes(y = PRED), linewidth = 1) +
  labs(x = "Time", y = "Response")
Figure 20.2: Compartment-free Emax time-course: observations (points) and the typical prediction (line).

A compartment-free model cannot have [odes], [scaling] or references to central and depot. y[CMT=N] gives it several endpoints (structural model).

Pitfalls

  • Joint PK/PD models need data for every parameter. Check relative standard errors and correlations before interpreting PD parameters; a simulation–estimation run tells whether a design can support the model.
  • An Emax design has to reach the EC50. With concentrations that stay below it, EMAX and EC50 cannot be told apart, whatever the number of subjects, and their standard errors need not say so. Compare the fit’s OFV with the objective at the simulation values: a fit that stops near its starting values looks like a recovery.
  • Per-CMT error models need an ODE model. An analytical pk model with CMT=N: lines is rejected. Use ode_template to write the PK part as ODEs.
  • Every observed CMT needs a readout and an error model. A missing entry stops the fit and names the compartment.
  • Thresholds that are never crossed give NaN in [derived] filters and conditional integrals.

Warnings you may see here

  • general (warning): parameters declared but not used by the predictions, such as the fixed PD thetas of warfarin_derived_pkpd that only [derived] reads.

Other warnings above (inflated_rse, high_correlation, condition_number) are covered in Parameter uncertainty.

Summary

  • Put all endpoints in one dataset and tell them apart with CMT.
  • Write the PK and PD states as ODEs, one [scaling] readout and one error model per CMT, and fit them jointly.
  • Check with simulation and estimation whether a design can support the PD parameters.
  • Compute effects from a PK fit with [derived] when the PD parameters are known.
  • Write responses that are plain equations as compartment-free models.

Next: Binary endpoints covers binary endpoints.