--- title: "Probabilistic Outlier Detection in Sparse Hierarchical Count Data" subtitle: "A Case Study in Hospital-Acquired Infection Surveillance" author: "Bayesian Statistics Technical Co-Writer" format: html: toc: true toc-location: left code-fold: true code-tools: true execute: cache: true warning: false message: false --- ## Introduction This tutorial details the implementation of a hierarchical probabilistic model for identifying outliers in sparse count data. The case study focuses on hospital-acquired infection (HAI) surveillance. The methodology relies on generating and recovering structural parameters using Monte Carlo simulation via the `SimDesign` package, and approximating posterior distributions using Integrated Nested Laplace Approximations (`INLA`). ## Structural Model Definition The statistical framework models event counts generated from disparate locations possessing variable exposure windows. Directed Acyclic Graphs are excluded from this methodology; the model architecture is defined strictly via structural equations and distributional notation. Let $y_{i}$ represent the observed number of infections in facility $i$, situated within health district $j[i]$. The data generating mechanism (DGM) assumes $y_i$ follows a Poisson distribution conditional on an expected rate $\lambda_i$: $$ y_i \sim \text{Poisson}(\lambda_i) $$ $$ \log(\lambda_i) = \log(\text{patient\_days}_i) + \beta_0 + \beta_1(\text{ward}_i) + \gamma_{j[i]} + \theta_i $$ $$ \gamma_j \sim \mathcal{N}(0, \sigma^2_\gamma) $$ $$ \theta_i \sim \mathcal{N}(0, \sigma^2_\theta) $$ Where: - $\text{patient\_days}_i$ defines the exposure baseline, incorporated via a logarithmic transformation. - $\text{ward}_i$ is a fixed covariate indicating the unit classification (e.g., intensive care unit). - $\gamma_j$ isolates the district-level spatial hierarchy. - $\theta_i$ represents the facility-specific frailty term. **Methodological Pitfall: Offset Misinterpretation** A recurring error in applied modeling is treating the exposure variable as an estimated predictor rather than a fixed scalar. As established in the generalized linear modeling literature, an offset is a known structural component included directly in the linear predictor. It enforces the assumption that the event rate scales proportionally with exposure. Fitting the exposure variable with a free coefficient distorts the fundamental structural constraint of the incidence density rate. ## Simulation Architecture: Data Generation The `SimDesign` framework isolates the data generation, analysis, and summarization steps. The `Generate` function maps the structural equations above into a synthetic cohort. ```{r generate} library(SimDesign) Generate <- function(condition, fixed_objects = NULL) { N_districts <- condition$N_districts N_facilities <- condition$N_facilities sigma_gamma <- condition$sigma_gamma sigma_theta <- condition$sigma_theta N <- N_districts * N_facilities # Exposure scalar patient_days <- sample(100:2000, N, replace = TRUE) # Fixed covariates ward_type <- rbinom(N, 1, prob = 0.3) # Hierarchical random effects health_district <- rep(1:N_districts, each = N_facilities) gamma_j <- rnorm(N_districts, mean = 0, sd = sigma_gamma) # Facility frailty (target for outlier detection) theta_i <- rnorm(N, mean = 0, sd = sigma_theta) # Deterministic anomaly thresholding for TPR/FDR calculation true_anomaly <- theta_i > quantile(theta_i, 0.95) # Structural equation mapping log_lambda <- log(patient_days) + (-2.0) + (0.5 * ward_type) + gamma_j[health_district] + theta_i infections <- rpois(N, exp(log_lambda)) data.frame( facility_id = 1:N, health_district = health_district, ward_type = ward_type, patient_days = patient_days, infections = infections, true_theta = theta_i, true_anomaly = true_anomaly ) } ``` ## Bayesian Estimation and Exceedance ### MCMC vs. Deterministic Approximations Probabilistic evaluation of $\theta_i$ requires approximating the posterior distribution $P(\theta \mid y)$. While Markov Chain Monte Carlo (MCMC) algorithms, implemented in frameworks like `brms` and Stan, provide exact posterior sampling asymptotically, they introduce a distinct procedural pitfall in simulation regimes: recompiling Stan models unnecessarily within iterative loops, resulting in prohibitive computational overhead. To circumvent this, inference is executed via the `INLA` package. INLA calculates deterministic analytical approximations of posterior marginals. As defined by Rue et al. (2009), INLA evaluates approximate Bayesian inference in latent Gaussian models without reliance on iterative simulation, rendering it uniquely suited for high-dimensional factorial simulations requiring rapid convergence. ### Implementation: The Analyse Function The `Analyse` function fits the Poisson configuration and extracts the exceedance probability: $P(\theta_i > c \mid y)$. **Methodological Pitfall: Conflating Significance with Severity** Identifying a facility where $P(\theta_i > 0 \mid y)$ approaches 1.0 demonstrates statistical confidence that the relative risk is greater than zero. It does not prove the magnitude of the deviation requires operational intervention. Consequently, exceedance thresholds ($c$) must be calibrated to a domain-specific tolerance bound, rather than a null bound of zero. ```{r analyse} library(INLA) Analyse <- function(condition, dat, fixed_objects = NULL) { # Structural formula formulation formula <- infections ~ ward_type + offset(log(patient_days)) + f(health_district, model = "iid") + f(facility_id, model = "iid") # Model inference fit <- inla(formula, family = "poisson", data = dat, control.compute = list(dic = TRUE, waic = TRUE), control.predictor = list(compute = TRUE)) # Operational threshold for severity (c) # Represents a target escalation threshold (e.g., log(1.25) = 25% increase) c_threshold <- log(1.25) # Extract posterior marginals for facility effects marginals_theta <- fit$marginals.random$facility_id exceedance_probs <- sapply(marginals_theta, function(m) { 1 - inla.pmarginal(c_threshold, m) }) data.frame( facility_id = dat$facility_id, exceedance_prob = exceedance_probs, true_anomaly = dat$true_anomaly, dic = fit$dic$dic, waic = fit$waic$waic ) } ``` ### Advanced Evidence Metrics When replicating findings across independent surveillance audits, standard posterior probabilities lack constraints for epistemic rigor. Robust inference requires the utilization of advanced evidence synthesis metrics: 1. **Held's Sceptical p-value:** Quantifies the conflict between a prior reflecting strict scepticism and the observed data. I do not know the exact mathematical derivation applied by Held (2020) without referencing the primary literature, and thus will not hallucinate the proof parameters. Algorithmically, it identifies the boundary limit at which the resulting posterior interval precisely intersects the null hypothesis when subjected to a sceptical prior distribution. 2. **Sceptical Bayes Factors:** Represents the ratio of marginal likelihoods conditional on a specific sceptical prior variance matrix. 3. **Jeffreys-Zellner-Siow (JZS) Bayes Factor:** Imposes a Cauchy prior on standardized effect sizes to evaluate replication viability. ## Simulation Evaluation: Power and FDR The `Summarise` function aggregates the exceedance probability arrays across Monte Carlo replications to compute the true positive rate (Power) and the false discovery rate (FDR). ```{r summarise} Summarise <- function(condition, results, fixed_objects = NULL) { # Flag threshold for categorical decision-making decision_threshold <- 0.90 metrics <- do.call(rbind, lapply(results, function(res) { flagged <- res$exceedance_prob >= decision_threshold tpr <- sum(flagged & res$true_anomaly) / max(sum(res$true_anomaly), 1) fdr <- sum(flagged & !res$true_anomaly) / max(sum(flagged), 1) c(TPR = tpr, FDR = fdr, DIC = mean(res$dic)) })) colMeans(metrics) } ``` ## Visualization of Posterior Marginals To communicate probabilistic exceedance boundaries to non-technical stakeholders, the posterior marginal density $P(\theta_i \mid y)$ must be projected effectively. The following `ggplot2` architecture isolates and shades the probability mass strictly exceeding the operational threshold $c$. ```{r visualization} library(ggplot2) plot_exceedance <- function(inla_marginal, facility_name, c_threshold) { density_df <- as.data.frame(inla_marginal) colnames(density_df) <- c("x", "y") ggplot(density_df, aes(x = x, y = y)) + geom_line(color = "black", linewidth = 0.8) + # Region shading validating the exceedance probability geom_ribbon(data = subset(density_df, x > c_threshold), aes(ymin = 0, ymax = y), fill = "red", alpha = 0.4) + geom_vline(xintercept = c_threshold, linetype = "dashed", color = "darkred") + labs( title = paste("Posterior Marginal Density:", facility_name), subtitle = paste("Shaded Area = P(\u03b8 >", round(c_threshold, 2), "| y)"), x = expression(theta[i] ~ (Log ~ Relative ~ Risk)), y = "Density" ) + theme_minimal() } ```