## ----include = FALSE----------------------------------------------------------
set.seed(20260821)
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
K <- 10^5

## ----setup--------------------------------------------------------------------
library(nhppp)

age_breaks <- c(0, 1, seq(5, 85, by = 5), 100) # M + 1 = 20 bounds
lambda_bands <- c(
  0.5, 0.3, 0.2, 0.3, 0.5, 0.8, 1.2, 2, 3.5, 6,
  11, 20, 35, 60, 95, 140, 190, 235, 270
) / 10^5 # rates per person-year, one per band

w <- stats::rgamma(K, shape = 5, rate = 5)
lambda_matrix <- outer(w, lambda_bands) # K x M

## ----whole-range--------------------------------------------------------------
Z <- vdraw_sc_step(
  lambda_matrix = lambda_matrix,
  time_breaks = age_breaks
)
dim(Z)
mean(!is.na(Z[, 1])) # proportion of people with at least one event

## ----histogram, fig.alt="Histogram of simulated event ages overlaid with the normalized step intensity function. The two agree."----
if (nchar(system.file(package = "ggplot2")) > 0) {
  library(ggplot2)
  t_events <- as.vector(Z)
  t_events <- t_events[!is.na(t_events)]
  dens_bands <- lambda_bands / sum(lambda_bands * diff(age_breaks))
  step_df <- data.frame(
    age = age_breaks,
    density = c(dens_bands, dens_bands[length(dens_bands)])
  )
  ggplot() +
    geom_histogram(
      aes(x = t_events, y = after_stat(density)),
      breaks = 0:100, fill = "gray", color = "white"
    ) +
    geom_step(
      data = step_df, aes(x = age, y = density),
      direction = "hv", color = "red"
    ) +
    labs(
      x = "Age (years)",
      y = "Empirical and theoretical density",
      title = "All simulated event ages"
    )
}

## ----per-row-breaks-----------------------------------------------------------
birth_year <- stats::runif(K, min = 1920, max = 2000)
calendar_breaks <- outer(birth_year, age_breaks, FUN = "+") # K x (M + 1)

Z_cal <- vdraw_sc_step(
  lambda_matrix = lambda_matrix,
  time_breaks = calendar_breaks
)
range(Z_cal, na.rm = TRUE) # calendar years, not ages

## ----qq-per-row, fig.alt="QQ plot comparing event ages sampled on the age scale and on the calendar-time scale. The agreement is excellent."----
age_at_event <- as.vector(Z_cal - birth_year) # birth_year recycles down columns
qqplot(
  as.vector(Z), age_at_event,
  xlab = "Event ages, shared breaks",
  ylab = "Event ages, per-person calendar breaks"
)
abline(0, 1, col = "red")

## ----subinterval--------------------------------------------------------------
T1 <- stats::runif(K, min = 60, max = 100)
t_first <- vdraw_sc_step(
  lambda_matrix = lambda_matrix,
  time_breaks = age_breaks,
  t_min = 40,
  t_max = T1,
  report_first_K = 1
)
summary(as.vector(t_first))

## ----zero-truncated-----------------------------------------------------------
t_dx <- vztdraw_sc_step(
  lambda_matrix = lambda_matrix,
  time_breaks = age_breaks,
  t_min = 40,
  t_max = T1,
  report_first_K = 1, 
  generate_at_least_K = 1
)
sum(is.na(t_dx)) # everyone has an event now

## ----same-seed----------------------------------------------------------------
K2 <- 10^4
lam_bands_2 <- lambda_matrix[1:K2, ]
lam_grid_2 <- lam_bands_2[, rep(seq_along(lambda_bands), times = diff(age_breaks))]
dim(lam_grid_2)

set.seed(2026)
Z_general <- vdraw_sc_step(
  lambda_matrix = lam_grid_2, time_breaks = 0:100
)
set.seed(2026)
Z_regular <- vdraw_sc_step_regular(
  lambda_matrix = lam_grid_2, rate_matrix_t_min = 0, rate_matrix_t_max = 100
)
all.equal(Z_general, Z_regular, tolerance = 10^-12)

## ----timing-------------------------------------------------------------------
median_elapsed <- function(f, R = 10) {
  stats::median(
    vapply(seq_len(R), function(i) system.time(f())[["elapsed"]], numeric(1))
  )
}

breaks_rowwise <- matrix(rep(age_breaks, each = K2), nrow = K2)

timing <- data.frame(
  method = c(
    "vdraw_sc_step, bands, shared breaks",
    "vdraw_sc_step, bands, per-row breaks",
    "vdraw_sc_step, one-year grid",
    "vdraw_sc_step_regular, one-year grid"
  ),
  columns = c(19, 19, 100, 100),
  seconds = c(
    median_elapsed(function() {
      vdraw_sc_step(lambda_matrix = lam_bands_2, time_breaks = age_breaks)
    }),
    median_elapsed(function() {
      vdraw_sc_step(lambda_matrix = lam_bands_2, time_breaks = breaks_rowwise)
    }),
    median_elapsed(function() {
      vdraw_sc_step(lambda_matrix = lam_grid_2, time_breaks = 0:100)
    }),
    median_elapsed(function() {
      vdraw_sc_step_regular(
        lambda_matrix = lam_grid_2,
        rate_matrix_t_min = 0, rate_matrix_t_max = 100
      )
    })
  )
)
knitr::kable(timing, digits = 4)

