Time-to-event models
Where you are
Time-to-event (TTE) endpoints record when an event happens, such as dropout, a clinical event or death, or that it had not happened by the end of follow-up. ferx models them with an [event_model] block: a parametric hazard, with random effects and covariates in its parameters, fitted with a survival likelihood. This chapter fits the bundled examples: exponential, Weibull and Gompertz hazards, competing risks, and a hazard driven by the drug concentration. It then predicts survival curves and checks the models by simulation, with a Kaplan–Meier VPC.
ferx-core labels time-to-event endpoints beta. See feature maturity.
The data
A TTE row is an observation (EVID = 0) on the event model’s CMT. TIME is the event or censoring time and DV says which: 1 for an event, 0 for right censoring. tte_weibull has one row for each of 30 subjects, with follow-up to 60 hours:
weibull <- ferx_example("tte_weibull")
tte_dir <- file.path(tempdir(), "tte")
dir.create(tte_dir, showWarnings = FALSE)
weibull_data <- read.csv(weibull$data, na.strings = ".")
head(weibull_data, 4)
#> ID TIME DV EVID AMT CMT RATE MDV
#> 1 1 23.04 1 0 0 2 0 0
#> 2 2 25.31 1 0 0 2 0 0
#> 3 3 4.59 1 0 0 2 0 0
#> 4 4 26.89 1 0 0 2 0 0
count(weibull_data, DV)
#> DV n
#> 1 0 1
#> 2 1 29Minimal runnable call
A TTE-only model needs [parameters], [event_model] and [fit_options]. The block names the endpoint’s cmt, the hazard family, and the family’s parameters as expressions of thetas, etas and covariates:
invisible(ferx_model_get_section(weibull$model, "parameters"))
#> # [parameters]
#> theta TVSCALE(20.0, 0.1, 500.0)
#> theta TVSHAPE(1.5, 0.1, 10.0)
#>
#> omega ETA_SCALE ~ 0.04
invisible(ferx_model_get_section(weibull$model, "event_model"))
#> # [event_model]
#> cmt = 2
#> family = weibull
#> scale = TVSCALE * exp(ETA_SCALE)
#> shape = TVSHAPE
fit_weibull <- ferx_fit(weibull$model, weibull$data, verbose = FALSE)
fit_weibull$estimates[, c("estimate", "rse_pct")]
#> estimate rse_pct
#> TVSCALE 22.4977122 12.17866
#> TVSHAPE 2.7023104 34.46758
#> ETA_SCALE 0.1691596 72.78672According to the model file, the data were simulated with TVSCALE 20, TVSHAPE 1.5 and a variance of 0.04. With 30 subjects the shape is poorly determined.
Reading the result: survival curves
ferx_predict_survival() evaluates the survival function S(t), the cumulative hazard H(t) and the hazard h(t) at the requested times, for each subject and TTE compartment. With fit, it uses the fitted thetas (random effects at 0); without, the model file’s initial values. type = "individual" evaluates each subject at its own fitted random effects instead (Individual survival curves). Each subject also gets a median and mean survival time:
survival_curve <- ferx_predict_survival(weibull$model, weibull$data, times = seq(0, 60, by = 1), fit = fit_weibull)
filter(survival_curve, ID == 1, TIME %in% c(0, 10, 20, 30, 40)) |>
select(TIME, survival, cum_hazard, hazard, median_survival, mean_survival)
#> TIME survival cum_hazard hazard median_survival mean_survival
#> 1 0 1.000000000 0.0000000 0.00000000 19.64424 20.00742
#> 2 10 0.894229750 0.1117925 0.03020982 19.64424 20.00742
#> 3 20 0.483069671 0.7275944 0.09830930 19.64424 20.00742
#> 4 30 0.113447013 2.1764194 0.19604536 19.64424 20.00742
#> 5 40 0.008778059 4.7355000 0.31991977 19.64424 20.00742The Kaplan–Meier estimate of the observed data, from the survival package, is the natural comparison:
library(survival)
km <- survfit(Surv(TIME, DV) ~ 1, data = weibull_data)
km_data <- data.frame(TIME = c(0, km$time), survival = c(1, km$surv))
ggplot() +
geom_step(data = km_data, aes(TIME, survival)) +
geom_line(data = filter(survival_curve, ID == 1), aes(TIME, survival), colour = "steelblue") +
labs(x = "Time (h)", y = "Survival")
The model curve is for a subject with random effect 0. With between-subject variability, the population survival curve is flatter than that, which is why a simulation-based check (below) is the better comparison.
sdtab has one row per TTE record. There is no concentration-type prediction, so PRED, IPRED and the weighted residuals are NaN, and DV is the event indicator. Four residuals take their place, computed at each subject’s EBE: COXSNELL (the cumulative hazard over the record’s interval), MARTINGALE (the event indicator minus that hazard), DEVIANCE and PIT (the probability-integral transform, the survival over the interval). See time-to-event residuals in ferx-core for their definitions:
nrow(fit_weibull$sdtab)
#> [1] 30
head(fit_weibull$sdtab[, c("ID", "TIME", "DV", "IPRED", "COXSNELL", "MARTINGALE", "DEVIANCE", "PIT")], 4)
#> ID TIME DV IPRED COXSNELL MARTINGALE DEVIANCE PIT
#> 1 1 23.04 1 NaN 1.02897697 -0.02897697 -0.02870172 0.3573724
#> 2 2 25.31 1 NaN 1.14679077 -0.14679077 -0.14016678 0.3176546
#> 3 3 4.59 1 NaN 0.04438064 0.95561936 2.07813982 0.9565898
#> 4 4 26.89 1 NaN 1.22551299 -0.22551299 -0.21049212 0.2936070In ferx-r 0.4.0, sdtab has no rows for a TTE-only model and no COXSNELL, MARTINGALE, DEVIANCE or PIT columns.
Options that matter
Key in [event_model]
|
Meaning |
|---|---|
cmt |
The CMT value of the event rows |
family |
exponential, weibull or gompertz
|
scale (alias rate for exponential) |
Rate (exponential) or characteristic time (Weibull) |
shape |
Weibull shape |
alpha, gamma
|
Gompertz baseline hazard and growth rate |
loghr |
A proportional-hazards term that multiplies the hazard by exp(loghr)
|
hazard |
A hazard expression of ODE states and individual parameters (instead of family), for a drug-driven hazard |
type, clock
|
tte (default) or repeated events (rtte), with a forward or reset clock |
| Data | Meaning |
|---|---|
DV = 1 / DV = 0
|
Event / right-censored at TIME
|
DV = 2 |
Right bound of an interval-censored event (after a DV = 0 row with the left bound) |
TENTRY |
Entry time for left truncation (delayed entry) |
| Function | Argument | Meaning |
|---|---|---|
ferx_predict_survival() |
model, data
|
Model with at least one [event_model], and its dataset |
times |
Times at which to evaluate S(t), H(t) and h(t) | |
fit |
Use the fitted thetas instead of the model file’s | |
type |
"population" (default): every subject at random effect 0; "individual": each subject at its etas in fit$ebe_etas (needs fit) |
|
ferx_simulate() |
horizon |
End of follow-up (administrative censoring) for simulated event times |
ferx_vpc_tte() |
model, data, fit
|
Model, observed TTE data (a path or a data frame; by default the data fit was fitted to, else the model file’s [data]), and optionally the fit to simulate at |
n_sim, seed
|
Number of replicates (at least 20 for the default band) and the random seed | |
censoring |
"observed" (default): replicates censored like the data; "horizon": at the horizon only |
|
strata, by_dose
|
Stratify by a covariate, or by each subject’s first dose | |
cmt |
The endpoint to check, required when the model has several | |
horizon |
The time the replicates are simulated to; by default the latest time recorded on the endpoint | |
probs |
The band’s lower bound, middle line and upper bound | |
grid |
The times the band is evaluated at: "auto", "all_steps" or a numeric vector |
Named blocks, [event_model NAME], declare several endpoints. The ferx-core event model and TTE estimation pages document the families, interval censoring and repeated events.
Variants
Exponential and Gompertz hazards
tte_exponential has a constant hazard. It still carries the placeholder PK, error and individual-parameter blocks that older TTE models needed. tte_gompertz has a hazard that grows exponentially with time:
exponential <- ferx_example("tte_exponential")
gompertz <- ferx_example("tte_gompertz")
invisible(ferx_model_get_section(exponential$model, "event_model"))
#> # [event_model]
#> cmt = 2
#> family = exponential
#> # Note: [event_model] expressions are evaluated in the theta/eta/covariate
#> # namespace — not in the [individual_parameters] namespace. Write the full
#> # theta/eta expression here rather than referencing LAMBDA directly.
#> scale = TVLAMBDA * exp(ETA_LAMBDA)
invisible(ferx_model_get_section(gompertz$model, "event_model"))
#> # [event_model]
#> cmt = 2
#> family = gompertz
#> alpha = TVALPHA
#> gamma = TVGAMMA * exp(ETA_GAMMA)
fit_exponential <- ferx_fit(exponential$model, exponential$data, verbose = FALSE)
fit_gompertz <- ferx_fit(gompertz$model, gompertz$data, verbose = FALSE)
fit_exponential$estimates[c("TVLAMBDA", "ETA_LAMBDA"), c("estimate", "rse_pct")]
#> estimate rse_pct
#> TVLAMBDA 0.03318021 26.5991
#> ETA_LAMBDA 0.29343592 263.8840
fit_gompertz$estimates[, c("estimate", "rse_pct")]
#> estimate rse_pct
#> TVALPHA 0.00187306 54.86375
#> TVGAMMA 0.05339556 22.98570
#> ETA_GAMMA 0.10659813 51.34886The exponential fit’s placeholder parameters (DUMMY_CL, DUMMY_V, SIGMA_DV) are fixed, so fit_exponential$estimates marks them fixed and gives them no standard error (se is NA; ferx-r 0.4.0 differs, see Variability: random effects, residual error and IOV). The model files give the simulation values: an exponential rate of 0.05 with variance 0.09, and Gompertz TVALPHA 0.002, TVGAMMA 0.05 with variance 0.04. The typical parameters are in range, but the between-subject variances of these single-event datasets are poorly determined. With one event per subject, frailty is hard to separate from the hazard’s shape.
A simulation-based check
ferx_simulate() draws an event time for each subject from the fitted model. OBSERVED is 1 for an event and 0 for censoring at horizon. The Kaplan–Meier curves of 200 simulated datasets give an interval to compare with the observed curve:
simulated <- ferx_simulate(weibull$model, weibull$data, n_sim = 200, seed = 1, fit = fit_weibull, horizon = 60)
head(simulated, 3)
#> DRAW SIM ID TIME CMT IPRED DV_SIM OBSERVED
#> 1 1 1 1 30.84560 2 NA NA 1
#> 2 1 1 2 26.20654 2 NA NA 1
#> 3 1 1 3 4.61846 2 NA NA 1
grid <- seq(0, 60, by = 1)
km_on_grid <- function(time, status) {
summary(survfit(Surv(time, status) ~ 1), times = grid, extend = TRUE)$surv
}
simulated_km <- simulated |>
group_by(SIM) |>
group_modify(~ data.frame(TIME = grid, survival = km_on_grid(.x$TIME, .x$OBSERVED))) |>
group_by(TIME) |>
summarise(lo = quantile(survival, 0.05), mid = median(survival), hi = quantile(survival, 0.95))
ggplot(simulated_km, aes(TIME)) +
geom_ribbon(aes(ymin = lo, ymax = hi), alpha = 0.3) +
geom_line(aes(y = mid), linetype = "dashed") +
geom_step(data = km_data, aes(TIME, survival)) +
labs(x = "Time (h)", y = "Survival")
Without horizon, simulated event times are not censored at the end of follow-up, and some lie far beyond it. ferx_simulate() also reports that tte_exponential computes LAMBDA in [individual_parameters] without using it: its [event_model] writes the scale out again as TVLAMBDA * exp(ETA_LAMBDA), so the placeholder block has no effect.
fit_exp_sim <- ferx_simulate(exponential$model, exponential$data, n_sim = 1, seed = 1, fit = fit_exponential)
#> Warning: ferx_simulate produced 1 diagnostic:
#> [individual_parameters] `LAMBDA` is computed but never used — not mapped into the `pk(...)` model and not referenced in any other block, so it has no effect. Map it in [structural_model] (e.g. `f=F`) or remove it.
range(fit_exp_sim$TIME)
#> [1] 1.154544 162.657215
range(ferx_simulate(exponential$model, exponential$data, n_sim = 1, seed = 1, fit = fit_exponential,
horizon = 30)$TIME)
#> Warning: ferx_simulate produced 1 diagnostic:
#> [individual_parameters] `LAMBDA` is computed but never used — not mapped into the `pk(...)` model and not referenced in any other block, so it has no effect. Map it in [structural_model] (e.g. `f=F`) or remove it.
#> [1] 1.154544 30.000000The check above censors every replicate at the horizon only. That is right for tte_weibull, but not for data with dropouts before the end of follow-up, which the next section handles.
The Kaplan–Meier VPC: ferx_vpc_tte()
ferx_vpc_tte() and its print() and plot() methods are not in ferx-r 0.4.0.
ferx_vpc_tte() builds the same check in the engine, for one single-event TTE endpoint. It simulates the observed design n_sim times (at the fitted parameters when fit is given, otherwise at the model file’s initial values), censors the replicates like the data, and returns the observed Kaplan–Meier curve beside the pointwise band of the replicate curves. It never refits. On the exponential fit:
vpc_exponential <- ferx_vpc_tte(exponential$model, exponential$data, n_sim = 200, seed = 1,
fit = fit_exponential)
#> Warning: ferx_vpc_tte produced 1 diagnostic:
#> [individual_parameters] `LAMBDA` is computed but never used — not mapped into the `pk(...)` model and not referenced in any other block, so it has no effect. Map it in [structural_model] (e.g. `f=F`) or remove it.
vpc_exponential
#> Kaplan-Meier VPC (ferx_vpc_tte)
#> endpoint cmt 2, horizon 30, 200 replicates, observed censoring
#> band 5%-95% with the 50% line
#> all: 30 subjects, 19 events
#> 1 warning (see `$warnings`)
head(vpc_exponential$observed, 3)
#> STRATUM time n_risk n_event n_censor surv cumhaz
#> 1 all 1.83 30 1 0 0.9666667 0.03333333
#> 2 all 2.67 29 1 0 0.9333333 0.06781609
#> 3 all 3.61 28 1 0 0.9000000 0.10353038
head(vpc_exponential$band, 3)
#> STRATUM time obs lo med hi n_used
#> 1 all 0.0 1 1.0000000 1.0000000 1 200
#> 2 all 0.3 1 0.9333333 1.0000000 1 200
#> 3 all 0.6 1 0.9316667 0.9666667 1 200The warning is the unused-LAMBDA diagnostic of the simulator, shown above for ferx_simulate(); it is also kept in vpc_exponential$warnings. observed has one row per distinct time, with the numbers at risk, events and censorings, the Kaplan–Meier survival surv and the Nelson–Aalen cumulative hazard cumhaz. It follows the survival package’s conventions, so it matches survfit() row for row:
band has one row per grid time: obs, the observed curve read there, and lo, med and hi, the replicate curves’ quantiles at probs (5%, 50% and 95% by default). n_used counts the replicates still under follow-up at that time; where too few are left, the band is NA. plot() draws the band and the observed curve, with the vpc package’s plot_vpc() when it is installed and base graphics otherwise; engine = "base" asks for base graphics regardless:
plot(vpc_exponential, engine = "base")
Censoring the replicates
The observed curve is censored where subjects left the study, and the band is only comparable with it if the replicates are censored the same way. With the default censoring = "observed", a subject observed censored keeps its own censoring time in every replicate, and a subject observed with an event draws a censoring time after that event from the censorings seen in the data. censoring = "horizon" censors the replicates at the horizon only.
In tte_exponential every censoring is at the end of follow-up, 30 hours, so the two give the same band:
vpc_exponential_horizon <- ferx_vpc_tte(exponential$model, exponential$data, n_sim = 200, seed = 1,
fit = fit_exponential, censoring = "horizon")
#> Warning: ferx_vpc_tte produced 1 diagnostic:
#> [individual_parameters] `LAMBDA` is computed but never used — not mapped into the `pk(...)` model and not referenced in any other block, so it has no effect. Map it in [structural_model] (e.g. `f=F`) or remove it.
all.equal(vpc_exponential$band, vpc_exponential_horizon$band)
#> [1] TRUEA copy of the data with dropouts shows the difference. Each subject gets a dropout time drawn uniformly between 0 and 40 hours, independently of its event time; a subject that drops out before its event or the end of follow-up is censored then. The replicates still use the parameters of fit_exponential, and ferx_vpc_tte() takes the data frame directly:
set.seed(2)
dropout_time <- runif(nrow(exponential_data), 0, 40)
dropout_data <- mutate(exponential_data,
DV = if_else(dropout_time < TIME, 0L, DV),
TIME = pmin(TIME, round(dropout_time, 2)))
count(dropout_data, DV, before_end = TIME < 30)
#> DV before_end n
#> 1 0 FALSE 5
#> 2 0 TRUE 13
#> 3 1 TRUE 12
vpc_observed <- ferx_vpc_tte(exponential$model, dropout_data, n_sim = 200, seed = 1,
fit = fit_exponential)
#> Warning: ferx_vpc_tte produced 1 diagnostic:
#> [individual_parameters] `LAMBDA` is computed but never used — not mapped into the `pk(...)` model and not referenced in any other block, so it has no effect. Map it in [structural_model] (e.g. `f=F`) or remove it.
vpc_horizon <- ferx_vpc_tte(exponential$model, dropout_data, n_sim = 200, seed = 1,
fit = fit_exponential, censoring = "horizon")
#> Warning: ferx_vpc_tte produced 1 diagnostic:
#> [individual_parameters] `LAMBDA` is computed but never used — not mapped into the `pk(...)` model and not referenced in any other block, so it has no effect. Map it in [structural_model] (e.g. `f=F`) or remove it.
dropout_bands <- bind_rows(observed = vpc_observed$band, horizon = vpc_horizon$band, .id = "censoring")
dropout_summary <- dropout_bands |>
group_by(censoring) |>
summarise(width_after_15h = mean((hi - lo)[time >= 15], na.rm = TRUE),
na_band = sum(is.na(lo)), grid_times = n())
dropout_summary
#> # A tibble: 2 × 4
#> censoring width_after_15h na_band grid_times
#> <chr> <dbl> <int> <int>
#> 1 horizon 0.300 0 124
#> 2 observed 0.368 0 124ggplot(dropout_bands, aes(time)) +
geom_ribbon(aes(ymin = lo, ymax = hi), alpha = 0.3) +
geom_line(aes(y = med), linetype = "dashed") +
geom_step(aes(y = obs)) +
facet_wrap(~censoring) +
labs(x = "Time (h)", y = "Survival")
Late in follow-up, few subjects of the data with dropouts are still at risk, so its Kaplan–Meier curve is uncertain there. Replicates censored like the data carry that uncertainty, and their band is wider. Censored at the horizon only, the replicates keep every subject at risk to the end, so their band is too narrow for this curve: after 15 hours it is 0.30 wide on average, against 0.37 with censoring = "observed". A band that is too narrow flags misfit where there is none.
Stratifying
strata names a covariate: subjects are grouped by its value at their first record, and each group gets its own curve and band. tte_exponential has no covariates, so a copy of the data gives the subjects an ARM column. The hazard does not depend on it, so both arms are simulated alike:
arm_data <- mutate(exponential_data, ARM = if_else(ID %% 2 == 0, 1, 2))
vpc_arm <- ferx_vpc_tte(exponential$model, arm_data, n_sim = 200, seed = 1, fit = fit_exponential,
strata = "ARM")
#> Warning: ferx_vpc_tte produced 1 diagnostic:
#> [individual_parameters] `LAMBDA` is computed but never used — not mapped into the `pk(...)` model and not referenced in any other block, so it has no effect. Map it in [structural_model] (e.g. `f=F`) or remove it.
vpc_arm$strata
#> STRATUM value n_subjects
#> 1 ARM=1 1 15
#> 2 ARM=2 2 15
plot(vpc_arm, engine = "base")
ARM column.
A covariate with more than 10 values is refused; bin it into a categorical column first. by_dose = TRUE stratifies by the amount of each subject’s first dose instead (0 for a subject without a dose), and cannot be combined with strata. Here a copy gives each subject a dose of 100 or 200 at time 0, in compartment 1 of the placeholder PK model:
dose_rows <- data.frame(ID = exponential_data$ID, TIME = 0, EVID = 1, CMT = 1, RATE = 0, MDV = 1,
AMT = if_else(exponential_data$ID %% 2 == 0, 100, 200))
dosed_data <- bind_rows(dose_rows, exponential_data) |>
arrange(ID, TIME, desc(EVID))
vpc_dose <- ferx_vpc_tte(exponential$model, dosed_data, n_sim = 200, seed = 1, fit = fit_exponential,
by_dose = TRUE)
#> Warning: ferx_vpc_tte produced 1 diagnostic:
#> [individual_parameters] `LAMBDA` is computed but never used — not mapped into the `pk(...)` model and not referenced in any other block, so it has no effect. Map it in [structural_model] (e.g. `f=F`) or remove it.
vpc_dose$strata
#> STRATUM value n_subjects
#> 1 dose=100 100 15
#> 2 dose=200 200 15Competing risks: choose the endpoint
tte_competing_risks has two TTE endpoints, and without cmt it is refused with a ferx_engine_error whose code is E_VPC_TTE_INPUT:
competing_risks <- ferx_example("tte_competing_risks")
vpc_refusal <- tryCatch(ferx_vpc_tte(competing_risks$model, competing_risks$data, n_sim = 50),
ferx_engine_error = function(e) e)
vpc_refusal$code
#> [1] "E_VPC_TTE_INPUT"One minus the Kaplan–Meier curve of one cause is not that cause’s cumulative incidence, so ferx does not pick one for you. With cmt, the observed curve is that cause’s survival, with the other cause’s events counted as censorings, and it matches survfit() on the endpoint’s rows. The replicates keep each subject’s observed censoring time, the other cause’s event time included, as for any censoring:
vpc_cause <- ferx_vpc_tte(competing_risks$model, competing_risks$data, n_sim = 200, seed = 1, cmt = 2)
vpc_cause
#> Kaplan-Meier VPC (ferx_vpc_tte)
#> endpoint cmt 2, horizon 14, 200 replicates, observed censoring
#> band 5%-95% with the 50% line
#> all: 40 subjects, 23 events
cause_rows <- filter(read.csv(competing_risks$data, na.strings = "."), CMT == 2)
all.equal(vpc_cause$observed$surv, survfit(Surv(TIME, DV) ~ 1, data = cause_rows)$surv)
#> [1] TRUE
plot(vpc_cause, engine = "base")
tte_competing_risks (cmt = 2), with the other cause as censoring, simulated at the model file’s values.
Without fit, as here, the replicates use the model file’s initial values; the competing-risks fit follows below.
With the same code, ferx_vpc_tte() refuses the inputs ?ferx_vpc_tte lists, among them repeated events, delayed entry (TENTRY), interval-censored records and more than one record per subject on the endpoint.
Individual survival curves
The type argument of ferx_predict_survival() is not in ferx-r 0.4.0.
The curves so far are for a subject with random effects 0. With type = "individual", ferx_predict_survival() evaluates each subject at its own etas from fit$ebe_etas, so each subject gets its own S(t), H(t), h(t), median and mean survival. It needs fit, and every subject in data needs a row in fit$ebe_etas. When data is omitted, the fitted data is used if it can still be found. The exponential fit gives both kinds of curve, each with the unused-LAMBDA diagnostic shown above:
times <- seq(0, 30, by = 1)
typical_curve <- ferx_predict_survival(exponential$model, times = times, fit = fit_exponential)
#> Warning: ferx_predict_survival produced 1 diagnostic:
#> [individual_parameters] `LAMBDA` is computed but never used — not mapped into the `pk(...)` model and not referenced in any other block, so it has no effect. Map it in [structural_model] (e.g. `f=F`) or remove it.
individual_curve <- ferx_predict_survival(exponential$model, times = times, fit = fit_exponential,
type = "individual")
#> Warning: ferx_predict_survival produced 1 diagnostic:
#> [individual_parameters] `LAMBDA` is computed but never used — not mapped into the `pk(...)` model and not referenced in any other block, so it has no effect. Map it in [structural_model] (e.g. `f=F`) or remove it.
head(fit_exponential$ebe_etas, 3)
#> ID ETA_LAMBDA
#> 1 1 0.2068651
#> 2 2 -0.2316834
#> 3 3 0.2483782
filter(individual_curve, TIME == 10) |>
select(ID, survival, cum_hazard, median_survival) |>
head(3)
#> ID survival cum_hazard median_survival
#> 1 1 0.6649418 0.4080558 16.98658
#> 2 2 0.7686001 0.2631845 26.33693
#> 3 3 0.6535397 0.4253520 16.29585
The hazard is TVLAMBDA * exp(ETA_LAMBDA), so a subject’s cumulative hazard is the typical one multiplied by exp(η̂), and its median survival is the typical one multiplied by exp(−η̂). Matched on ID with fit$ebe_etas, the two outputs agree with that to rounding:
eta_hat <- fit_exponential$ebe_etas
ratios <- inner_join(individual_curve, typical_curve, by = c("ID", "CMT", "TIME"),
suffix = c("_ind", "_typ")) |>
filter(TIME > 0) |>
inner_join(eta_hat, by = "ID") |>
mutate(hazard_ratio = cum_hazard_ind / cum_hazard_typ,
median_ratio = median_survival_ind / median_survival_typ)
summarise(ratios,
max_error_hazard = max(abs(hazard_ratio - exp(ETA_LAMBDA))),
max_error_median = max(abs(median_ratio - exp(-ETA_LAMBDA))))
#> max_error_hazard max_error_median
#> 1 2.220446e-16 3.330669e-16The etas are point estimates (EBEs, or posterior means for a VI fit), and with one record per subject they shrink towards 0: their standard deviation is 0.2, against 0.54 for the fitted between-subject standard deviation. A subject with little information gets a curve close to the typical one. The subjects censored at the end of follow-up have the same data, no event by then, so they get the same eta, the lowest one:
exponential_data <- read.csv(exponential$data, na.strings = ".")
censored_ids <- as.character(exponential_data$ID[exponential_data$DV == 0])
censored_eta <- filter(eta_hat, ID %in% censored_ids)$ETA_LAMBDA
c(n_censored = length(censored_ids), censored_at = max(exponential_data$TIME))
#> n_censored censored_at
#> 11 30
range(censored_eta)
#> [1] -0.2316834 -0.2316834
range(eta_hat$ETA_LAMBDA)
#> [1] -0.2316834 0.2700936These 11 subjects share one curve, the highest in the figure. Individual curves describe the fitted subjects; they are not a prediction for new ones.
A subject the fit never saw has no eta, and is refused with a ferx_engine_error whose code is E_SUPPLIED_ETAS:
new_subjects <- mutate(read.csv(exponential$data, na.strings = "."), ID = ID + 1000)
new_file <- file.path(tte_dir, "tte_exponential_new_ids.csv")
write.csv(new_subjects, new_file, row.names = FALSE)
refusal <- tryCatch(suppressWarnings(
ferx_predict_survival(exponential$model, new_file, times = times, fit = fit_exponential,
type = "individual")),
ferx_engine_error = function(e) e)
refusal$code
#> [1] "E_SUPPLIED_ETAS"?ferx_predict_survival adds that a [mixture] model is refused the same way, and that IOV kappas are taken as 0, which is exact because no hazard can read a kappa. A fit without random effects has no etas, so its individual curves are the population ones:
no_eta_model <- file.path(tte_dir, "tte_weibull_no_eta.ferx")
no_eta_lines <- sub("scale = TVSCALE * exp(ETA_SCALE)", "scale = TVSCALE", readLines(weibull$model), fixed = TRUE)
no_eta_lines <- no_eta_lines[!grepl("omega ETA_SCALE", no_eta_lines, fixed = TRUE)]
stopifnot(!any(grepl("ETA_SCALE", sub("#.*", "", no_eta_lines))))
writeLines(no_eta_lines, no_eta_model)
fit_no_eta <- ferx_fit(no_eta_model, weibull$data, verbose = FALSE)
all.equal(ferx_predict_survival(no_eta_model, times = times, fit = fit_no_eta),
ferx_predict_survival(no_eta_model, times = times, fit = fit_no_eta, type = "individual"))
#> [1] TRUECompeting risks
tte_competing_risks has two causes, each with its own named event block and compartment, and a shared frailty ETA_F. Each subject has one row per cause at the same time: DV = 1 for the cause that happened, DV = 0 for the other:
competing <- ferx_example("tte_competing_risks")
head(read.csv(competing$data, na.strings = "."), 4)
#> ID TIME DV EVID AMT CMT RATE MDV
#> 1 1 12.2538 1 0 0 2 0 0
#> 2 1 12.2538 0 0 0 3 0 0
#> 3 10 9.3770 1 0 0 2 0 0
#> 4 10 9.3770 0 0 0 3 0 0
invisible(ferx_model_get_section(competing$model, "parameters"))
#> # [parameters]
#> theta TVLAMBDA_A(0.10, 0.001, 10.0)
#> theta TVLAMBDA_B(0.06, 0.001, 10.0)
#>
#> omega ETA_F ~ 0.25
fit_competing <- ferx_fit(competing$model, competing$data, verbose = FALSE)
fit_competing$estimates[, c("estimate", "rse_pct")]
#> estimate rse_pct
#> TVLAMBDA_A 1.140563e-01 20.85150
#> TVLAMBDA_B 7.438451e-02 25.81994
#> ETA_F 6.144212e-06 NAThe two rates recover the simulation values of the model file (0.10 and 0.06), while the frailty variance collapses. The model file notes that it is weakly identified with FOCEI. For several causes, ferx_predict_survival() adds the cumulative incidence of each cause (cif) and the all-cause survival (survival_all); the incidences and the all-cause survival add up to 1:
competing_curve <- ferx_predict_survival(competing$model, competing$data, times = seq(0, 14, by = 0.5), fit = fit_competing)
subject <- filter(competing_curve, ID == first(ID))
subject |>
group_by(TIME) |>
summarise(total = sum(cif) + first(survival_all)) |>
summarise(min_total = min(total), max_total = max(total))
#> # A tibble: 1 × 2
#> min_total max_total
#> <dbl> <dbl>
#> 1 1 1
bind_rows(mutate(subject, curve = paste("incidence, CMT", CMT), value = cif),
distinct(subject, TIME, survival_all) |> mutate(curve = "all-cause survival", value = survival_all)) |>
ggplot(aes(TIME, value, colour = curve)) +
geom_line() +
labs(x = "Time (h)", y = NULL, colour = NULL)
A drug-driven hazard: joint PK and TTE
In pktte_joint the hazard depends on the drug concentration. hazard = is written with ODE states and individual parameters; ferx adds the cumulative hazard as an ODE state and fits it together with the concentrations:
joint <- ferx_example("pktte_joint")
invisible(ferx_model_get_section(joint$model, "individual_parameters"))
#> # [individual_parameters]
#> CL = TVCL * exp(ETA_CL)
#> V = TVV
#> KA = TVKA
#> H0 = TVH0
#> BETA = TVBETA
invisible(ferx_model_get_section(joint$model, "event_model"))
#> # [event_model]
#> cmt = 3
#> hazard = H0 * exp(BETA * (central / V))
filter(read.csv(joint$data, na.strings = "."), ID == 1)
#> ID TIME DV EVID AMT CMT RATE MDV
#> 1 1 0.0 NA 1 100 1 0 1
#> 2 1 2.0 75 0 NA 2 0 0
#> 3 1 8.0 49 0 NA 2 0 0
#> 4 1 9.5 1 0 0 3 0 0
fit_joint <- ferx_fit(joint$model, joint$data, verbose = FALSE)
fit_joint$estimates[, c("estimate", "rse_pct")]
#> estimate rse_pct
#> TVCL 1.110878509 82729.13922
#> TVV 10.431458334 82729.13919
#> TVKA 0.929912331 3.80720
#> TVH0 0.112830671 95.17506
#> TVBETA -0.277624964 82729.08492
#> ETA_CL 0.004987848 80.71205
#> PROP_ERR 0.030861739 29.22488With 6 subjects, clearance, volume and the concentration effect TVBETA are not determined: their relative standard errors are 83000% and more, and their estimates are correlated with |r| of at least 1. The example shows the syntax; a real analysis needs more data. sdtab holds the concentration rows, followed by one row per event record with the residuals shown for tte_weibull; COXSNELL and the other three are NaN on the concentration rows. Simulating a drug-driven hazard needs horizon:
try(ferx_simulate(joint$model, joint$data, n_sim = 1, seed = 1, fit = fit_joint))
#> Error in ferx_rust_simulate_from_fit(model_path = normalizePath(model), :
#> Error simulating: ODE-accumulated TTE (joint PK-TTE) simulation requires a finite, positive administrative horizon: set `[simulation] horizon` (or `SimulateOptions.horizon`). A drug-driven hazard can vanish, so there is no implicit observation window. [E_SIMULATE_HORIZON]
joint_sim <- ferx_simulate(joint$model, joint$data, n_sim = 1, seed = 1, fit = fit_joint, horizon = 24)
filter(joint_sim, ID == 1)
#> DRAW SIM ID TIME CMT IPRED DV_SIM OBSERVED
#> 1 1 1 1 2 2 72.46126 74.11760 NA
#> 2 1 1 1 8 2 43.96335 43.79085 NA
#> 3 1 1 1 24 3 NA NA 0The simulation returns the concentration rows and, per subject, one event row on CMT 3 with the event or censoring time.
Delayed entry
When subjects are known to be event-free until they enter the study, the likelihood should condition on that. A TENTRY column gives the entry time. In a copy of the Weibull data every subject enters at 4 hours (before the first event, at 4.59 hours):
entry_data <- mutate(weibull_data, TENTRY = 4)
entry_file <- file.path(tte_dir, "tte_weibull_entry.csv")
write.csv(entry_data, entry_file, row.names = FALSE)
fit_entry <- ferx_fit(weibull$model, entry_file, verbose = FALSE)
rbind(from_time_0 = fit_weibull$theta, entry_at_4 = fit_entry$theta)
#> TVSCALE TVSHAPE
#> from_time_0 22.49771 2.702310
#> entry_at_4 22.54085 2.178544The shape estimate changes, because the time from 0 to 4 hours no longer counts as survival evidence.
Repeated events
type = rtte models events that can happen more than once per subject, with the clock key choosing total time or time since the last event. Fits from R work, but no bundled ferx-r example uses repeated events. See the ferx-core repeated events section, which also recommends SAEM or IMP for their frailty variance.
Pitfalls
-
Validate a compact TTE model like any other.
ferx_model_validate()accepts a model without[structural_model],[error_model]and[individual_parameters], such astte_weibull:weibull_check <- ferx_model_validate(weibull$model, weibull$data) #> Validating: tte_weibull.ferx #> data: tte_weibull.csv #> #> Sections present: #> parameters [ok] #> event_model [ok] #> fit_options [ok] #> #> Result: VALID weibull_check$ok #> [1] TRUENoteChanged after ferx-r 0.4.0In ferx-r 0.4.0,
ferx_model_validate()reports such compact TTE models as invalid, although they fit (ferx-r #306). Only models that keep the placeholder blocks, such astte_exponential, validate there. Set
horizonwhen simulating. Without it, analytical hazards are not censored at the end of follow-up, and a drug-driven hazard cannot be simulated.A typical-subject curve is not the population curve. Compare observed Kaplan–Meier curves with simulations (
ferx_vpc_tte()), not withferx_predict_survival()at random effect 0.Censor the replicates like the data. When subjects drop out before the end of follow-up, a band censored at the horizon only is too narrow; keep
ferx_vpc_tte()’s defaultcensoring = "observed".Covariates in a hazard must be constant within a subject. A time-varying covariate in the hazard stops the fit.
Frailty variances are weakly identified with one event per subject. Check their standard errors, and consider SAEM or IMP.
Warnings you may see here
-
simulation(warning): a problem in individual simulated subjects, such as a non-positive hazard, which ferx turns into censoring at the horizon. The messages are attached to the result asattr(sim, "simulation_warnings"). Here a copy of the Weibull model subtracts 25 from the scale, which makes it negative for most subjects:degenerate_model <- file.path(tte_dir, "tte_weibull_negative_scale.ferx") writeLines(sub("scale = TVSCALE * exp(ETA_SCALE)", "scale = TVSCALE * exp(ETA_SCALE) - 25", readLines(weibull$model), fixed = TRUE), degenerate_model) degenerate <- suppressWarnings(ferx_simulate(degenerate_model, weibull$data, n_sim = 1, seed = 1, horizon = 60)) length(attr(degenerate, "simulation_warnings")) #> [1] 27 substr(attr(degenerate, "simulation_warnings")[1], 1, 120) #> [1] "W_TTE_DEGENERATE_HAZARD: subject '2' (CMT=2) drew a non-positive / non-finite effective hazard rate; no event was genera" count(degenerate, OBSERVED) #> OBSERVED n #> 1 0 27 #> 2 1 3The same diagnostics are raised as one R warning unless suppressed.
Summary
- Event rows carry
TIMEandDV(1 event, 0 censored) on the[event_model]’scmt. - Choose a hazard
family(exponential, Weibull, Gompertz), or write a drug-drivenhazardin an ODE model. -
ferx_predict_survival()gives S(t), H(t), h(t) and, for competing risks, cumulative incidences;type = "individual"gives each fitted subject’s curves at its fitted etas. - Check TTE models with a Kaplan–Meier VPC,
ferx_vpc_tte(): replicates censored like the data, stratified withstrataorby_dose, one endpoint at a time (cmt) under competing risks. -
TENTRYhandles delayed entry,DV = 2interval censoring, andtype = rtterepeated events.
Next: Adaptive dosing and TDM strategies simulates dosing that responds to measurements.
- R help:
?ferx_predict_survival,?ferx_vpc_tte,?plot.ferx_vpc_tte,?ferx_simulate(horizon),?ferx_fit - ferx-core: event model, TTE estimation