suppressMessages(pkgload::load_all(".", quiet=TRUE))
set.seed(2026)
reps <- 200L; n <- 400L; B <- 100L; z <- qnorm(0.975)
truth <- c("comp1:(Intercept)"=10, "comp1:x"=-10, "comp2:(Intercept)"=-10, "comp2:x"=10, "pi1"=0.5)
P <- length(truth)
est <- matrix(NA_real_, reps, P); se_s <- se_m <- matrix(NA_real_, reps, P)
for (r in seq_len(reps)) {
  d <- sim_mixqr2(n=n)
  fs <- tryCatch(suppressWarnings(mixqr(y~x, d, m=2, engine="ald", nstart=8, variance="sparsity")), error=function(e) NULL)
  fm <- tryCatch(suppressWarnings(mixqr(y~x, d, m=2, engine="ald", nstart=8, variance="stochEM",
                  vcontrol=mixqr_vcontrol(B=B, burnin=15))), error=function(e) NULL)
  if (is.null(fs) || is.null(fm)) next
  est[r,] <- c(as.numeric(fm$beta), fm$pi[1])
  se_s[r,] <- fs$se[names(truth)]
  se_m[r,] <- fm$se[names(truth)]
}
ok <- complete.cases(est)
est <- est[ok,]; se_s <- se_s[ok,]; se_m <- se_m[ok,]
emp_sd <- apply(est, 2, sd)
cov_s <- colMeans(abs(sweep(est,2,truth)) <= z*se_s)
cov_m <- colMeans(abs(sweep(est,2,truth)) <= z*se_m)
tab <- data.frame(param=names(truth), truth=truth, est_mean=round(colMeans(est),3),
                  emp_sd=round(emp_sd,3),
                  sparsity_se=round(colMeans(se_s),3), sparsity_cov=round(cov_s,3),
                  stochEM_se=round(colMeans(se_m),3), stochEM_cov=round(cov_m,3), row.names=NULL)
cat(sprintf("SE-coverage benchmark: 2-component DGP, n=%d, reps=%d (used %d), B=%d, nominal 95%%\n\n", n, reps, sum(ok), B))
print(tab, row.names=FALSE)
cat(sprintf("\nMean coverage  -- sparsity: %.1f%%   stochEM: %.1f%%  (target 95%%)\n",
            100*mean(cov_s), 100*mean(cov_m)))
cat(sprintf("Mean SE/emp_sd -- sparsity: %.2f      stochEM: %.2f   (target 1.00)\n",
            mean(colMeans(se_s)/emp_sd), mean(colMeans(se_m)/emp_sd)))
