Recap

dvsb estimates disease variability in subpopulations from biomarkers, e.g. estimating the variability between subpopulations in seroprevalence (the proportion of people who are seropositive) with antibody levels estimated using an assay measuring some proxy such as ELISA Optical Density values. We call the biomarker x (e.g. antibody level) and the proxy measurement y (e.g. OD values).

Simulate data

We simulate data. If we were using real data instead of simulated data, we would simply need to create the df_sam and df_cal dataframes ourselves instead of running simulate_data() below. The documentation for wrangle_data() explains what columns these dataframes require.

data <- simulate_data(seed = 12345)
df_sam <- data$df_sam
df_cal <- data$df_cal
df_plate <- data$df_plate
param_true_values_list <- data$params

Plot the simulated calibration data (one facet per plate):

ggplot(df_cal) +
  geom_point(aes(x = x, y = y)) +
  facet_wrap(~plate, ncol = 3) 

Plot the simulated sample data, histogramming the x and y values:

ggplot(df_sam) +
  geom_histogram(aes(x = x), bins = 30) +
  scale_x_log10()

# With default values, y is rarely negative; restrict to positive for visibility
ggplot(df_sam %>% filter(y > 0)) +
  geom_histogram(aes(x = y), bins = 30) +
  scale_x_log10()

Run Stan

Get the default prior distributions.

priors_list <- get_priors()

Wrangle the data and priors into the form needed for stan.

data_wrangled <- wrangle_data(
  df_sam = df_sam, 
  df_cal = df_cal, 
  priors_list = priors_list
)

Update our dataframes for samples, calibrators and plates with the extra columns we just added (which introduce integer indexing); this can be helpful later if we want to combine results and data.

df_sam <- data_wrangled$df_sam
df_cal <- data_wrangled$df_cal
df_plate <- dplyr::left_join(df_plate, data_wrangled$df_plate, by = "plate") 

We run Stan once to sample from the posterior, and again to sample from the prior. (We wrap inside capture.output( ) to suppress Stan’s insistent printing of information.)

capture.output({
df_posterior <- run_stan(data_wrangled = data_wrangled)

df_prior <- run_stan(data_wrangled = data_wrangled, 
                     distribution = "prior")
})

Analyse Stan output

df_posterior and df_prior are the dataframes (in data.table format) of samples, from the posterior and prior respectively, as returned by Stan.

We wrangle the true parameter values - flattening the list of values into a vector and renaming - for plotting convenience:

param_true_values_vector <- wrangle_true_params(
  param_true_values_list = param_true_values_list,
  data_descriptors = data_wrangled$data_descriptors)

For each of the population-level parameters we plot the posterior, prior and true value, demonstrating that the posterior moves away from the prior toward the true value, as it should for a correctly implemented model with informative data. One should always test this. We do this using plot_posterior() from our package mastiff, just for 16 parameters for better visibility within Rmarkdown:

mastiff::plot_posterior(
    posterior_samples = df_posterior,
    prior_samples     = df_prior,
    params_desired = names(df_prior)[1:16],
    true_param_values = param_true_values_vector,
    skip_stanfit_to_dt = TRUE)

df_posterior has columns named xlog_sam[1], xlog_sam[2] etc. which contain the posterior samples for x (on a log scale) for the sample assigned the integer index 1, and 2, etc. Calculate some quantiles of the posterior for each of the samples, and compare these to the true values which we had in df_sam. The smallest values are slightly overestimated and the largest values are slightly underestimated: this is the phenomenon of shrinkage toward the mean, due to these parameters being random effects.

quantiles <- c(0.025, 0.5, 0.975)
df_sam_x <- df_posterior %>%
  select(starts_with("xlog_sam[")) %>%
  pivot_longer(everything(), names_to = "param") %>%
  extract(param,
          into = "id_sam_int", 
          regex = "xlog_sam\\[([0-9]+)\\]") %>%
  mutate(id_sam_int = as.integer(id_sam_int)) %>%
  group_by(id_sam_int) %>%
  reframe(value = quantile(value, probs = quantiles),
          quantile = quantiles) %>%
  pivot_wider(names_from = quantile, names_prefix = "x_quant_") %>%
  left_join(df_sam %>%
              select(id_sam_int, xlog) %>%
              distinct(),
            by = "id_sam_int")
ggplot(df_sam_x) +
  geom_errorbar(aes(xlog, ymin = x_quant_0.025, ymax = x_quant_0.975)) +
  geom_point(aes(xlog, x_quant_0.5)) +
  geom_abline() +
  labs(x = "True log x",
       y = "Estimated log x")

df_posterior has columns named y_sam_sim_unconditional[1], y_sam_sim_unconditional[2] etc. which contain posterior predicted y values for new set of sampled individuals. The integer in square brackets indexes the sample replicate as in df_sam$which_sam_rep. We plot the empirical population-level distribution of y values (in blue), and the posterior predictive distribution of the same thing (in black, one line per sample from the posterior predictive distribution).

df_y_sim <- df_posterior %>%
  select(starts_with("y_sam_sim_unconditional[")) %>%
  mutate(sample = row_number()) %>%
  pivot_longer(-c("sample"), names_to = "param") %>%
  mutate(value = log10(value))
ggplot() +
  geom_density(data = df_y_sim,
               aes(x = value,
                   group = sample),
               color = "black") +
  geom_density(data = df_sam,
            aes(x = log10(y)),
            color="blue") +
  coord_cartesian(expand = F) +
  labs(x = "log10(OD value)",
       y = "probability density")

df_posterior has columns named p_sam_is_pos[1], p_sam_is_pos[2] etc. which contain the probability that sample 1, 2 etc. is positive given its observed y values. Calculate the posterior mean for each of these quantities, and then plot the distribution over individuals of these values, stratified by true serostatus. This gives a sense of the model’s accuracy and confidence in estimating serostatus.

df_prob_pos <- df_posterior %>%
  select(starts_with("p_sam_is_pos["))
df_prob_pos <- df_prob_pos[, lapply(.SD, mean)]
df_prob_pos <- df_prob_pos %>%
  pivot_longer(everything(), names_to = "param", values_to = "p_sam_is_pos") %>%
  tidyr::extract(param, 
                 into = "id_sam_int", 
                 regex = "p_sam_is_pos\\[([0-9]+)\\]") %>%
  mutate(id_sam_int = as.integer(id_sam_int)) %>%
  inner_join(df_sam %>% summarise(.by = id_sam_int, pos = unique(pos)), 
             by = "id_sam_int") %>%
    mutate(status = if_else(pos, "pos", "neg")) 

ggplot(df_prob_pos) +
  geom_histogram(aes(x = p_sam_is_pos, y = after_stat(density), fill = status),
                 position = "identity", alpha = 0.6, bins = 30) +
  labs(y = "Number of samples",
       x = "Probability sample is positive") +
  coord_cartesian(expand = FALSE) +
  scale_x_continuous(limits = c(NA, NA))