Calibrating a model to what you observed
Turn a guess about an uncertain input into what the data support. Simulate the model, keep the inputs that reproduce the observed statistics, and check that the answer is honest.
What runs in CodeSplash
You will be able to
- Explain approximate Bayesian computation as simulate, compare and keep
- Choose observed statistics that carry information about each input
- Read posterior intervals, shrinkage and the posterior predictive check
- Use the calibration check to judge whether the posterior is honest
Read first
From a guess to what the data say
ReadA scenario model needs distributions for its uncertain inputs, and often they're guesses: "base demand is somewhere between 500 and 1,500". What you do have is what happened. Last season's sales averaged 930 units, with an SD of 110.
Sales aren't demand. You can't sell more than you ordered, so the observed numbers are a censored view of the input you care about. Calibration asks which values of base demand and its volatility make the model reproduce those two statistics.
Simulate, compare, keep
ReadApproximate Bayesian computationApproximate Bayesian computation (ABC)Bayesian inference by simulation: keep the parameter values whose simulated statistics land close to the observed ones. needs only the ability to run the model:
- Draw candidate values of the inputs from their distributions, which act as the prior.
- Run the model at each candidate and compute the same statistics that were observed.
- Keep the candidates whose statistics land closest to the observed ones.
The kept candidates are the posterior: the values consistent with what happened. The largest distance kept is the toleranceABC toleranceThe largest distance between simulated and observed statistics that still counts as a match; smaller is closer but costlier..
Calibrated 2 input(s) to 2 observed statistic(s) by rejection ABC (3,000 simulations of 30 scenario(s) each): base_demand 1080 (90% 960.1 to 1254); volatility 259.4 (90% 150.9 to 381.7).
- base_demand (posterior mean)
- 1080.43
- volatility (posterior mean)
- 259.36
Plots
View data
| curve | density | base_demand |
|---|---|---|
| prior | 0.0005 | 509.26 |
| prior | 0.0006 | 515.84 |
| prior | 0.0006 | 522.43 |
| prior | 0.0007 | 529.01 |
| prior | 0.0007 | 535.60 |
| prior | 0.0008 | 542.18 |
| prior | 0.0008 | 548.77 |
| prior | 0.0008 | 555.35 |
| prior | 0.0009 | 561.94 |
| prior | 0.0009 | 568.52 |
| prior | 0.0009 | 575.11 |
| prior | 0.0009 | 581.69 |
| prior | 0.0009 | 588.28 |
| prior | 0.0010 | 594.86 |
| prior | 0.0010 | 601.45 |
| prior | 0.0010 | 608.03 |
| prior | 0.0010 | 614.62 |
| prior | 0.0010 | 621.20 |
| prior | 0.0010 | 627.79 |
| prior | 0.0010 | 634.37 |
| prior | 0.0010 | 640.96 |
| prior | 0.0010 | 647.54 |
| prior | 0.0010 | 654.13 |
| prior | 0.0010 | 660.71 |
| prior | 0.0010 | 667.30 |
| prior | 0.0010 | 673.88 |
| prior | 0.0010 | 680.47 |
| prior | 0.0010 | 687.05 |
| prior | 0.0011 | 693.64 |
| prior | 0.0011 | 700.22 |
| prior | 0.0011 | 706.81 |
| prior | 0.0011 | 713.39 |
| prior | 0.0011 | 719.98 |
| prior | 0.0011 | 726.56 |
| prior | 0.0011 | 733.15 |
| prior | 0.0011 | 739.73 |
| prior | 0.0011 | 746.32 |
| prior | 0.0010 | 752.90 |
| prior | 0.0010 | 759.49 |
| prior | 0.0010 | 766.07 |
| prior | 0.0010 | 772.66 |
| prior | 0.0010 | 779.24 |
| prior | 0.0010 | 785.83 |
| prior | 0.0010 | 792.41 |
| prior | 0.0010 | 799.00 |
| prior | 0.0010 | 805.58 |
| prior | 0.0010 | 812.17 |
| prior | 0.0010 | 818.75 |
| prior | 0.0010 | 825.34 |
| prior | 0.0010 | 831.92 |
| prior | 0.0010 | 838.50 |
| prior | 0.0010 | 845.09 |
| prior | 0.0010 | 851.67 |
| prior | 0.0010 | 858.26 |
| prior | 0.0010 | 864.84 |
| prior | 0.0010 | 871.43 |
| prior | 0.0010 | 878.01 |
| prior | 0.0010 | 884.60 |
| prior | 0.0010 | 891.18 |
| prior | 0.0010 | 897.77 |
First 60 of 300 rows.
View data
| curve | density | volatility |
|---|---|---|
| prior | 0.0015 | 48.812 |
| prior | 0.0017 | 51.677 |
| prior | 0.0019 | 54.543 |
| prior | 0.0021 | 57.409 |
| prior | 0.0023 | 60.275 |
| prior | 0.0024 | 63.140 |
| prior | 0.0025 | 66.006 |
| prior | 0.0026 | 68.872 |
| prior | 0.0027 | 71.737 |
| prior | 0.0028 | 74.603 |
| prior | 0.0028 | 77.469 |
| prior | 0.0029 | 80.334 |
| prior | 0.0029 | 83.200 |
| prior | 0.0029 | 86.066 |
| prior | 0.0029 | 88.932 |
| prior | 0.0029 | 91.797 |
| prior | 0.0029 | 94.663 |
| prior | 0.0029 | 97.529 |
| prior | 0.0029 | 100.39 |
| prior | 0.0029 | 103.26 |
| prior | 0.0029 | 106.13 |
| prior | 0.0029 | 108.99 |
| prior | 0.0029 | 111.86 |
| prior | 0.0030 | 114.72 |
| prior | 0.0030 | 117.59 |
| prior | 0.0030 | 120.45 |
| prior | 0.0030 | 123.32 |
| prior | 0.0030 | 126.19 |
| prior | 0.0030 | 129.05 |
| prior | 0.0030 | 131.92 |
| prior | 0.0030 | 134.78 |
| prior | 0.0030 | 137.65 |
| prior | 0.0030 | 140.51 |
| prior | 0.0030 | 143.38 |
| prior | 0.0030 | 146.25 |
| prior | 0.0030 | 149.11 |
| prior | 0.0030 | 151.98 |
| prior | 0.0030 | 154.84 |
| prior | 0.0030 | 157.71 |
| prior | 0.0029 | 160.57 |
| prior | 0.0029 | 163.44 |
| prior | 0.0029 | 166.31 |
| prior | 0.0029 | 169.17 |
| prior | 0.0029 | 172.04 |
| prior | 0.0029 | 174.90 |
| prior | 0.0029 | 177.77 |
| prior | 0.0029 | 180.63 |
| prior | 0.0028 | 183.50 |
| prior | 0.0028 | 186.37 |
| prior | 0.0028 | 189.23 |
| prior | 0.0028 | 192.10 |
| prior | 0.0028 | 194.96 |
| prior | 0.0028 | 197.83 |
| prior | 0.0028 | 200.69 |
| prior | 0.0028 | 203.56 |
| prior | 0.0028 | 206.43 |
| prior | 0.0028 | 209.29 |
| prior | 0.0029 | 212.16 |
| prior | 0.0029 | 215.02 |
| prior | 0.0029 | 217.89 |
First 60 of 300 rows.
View data
| Bin end | mean of sales | Simulations |
|---|---|---|
| 845.16 | 840.42 | 2 |
| 849.90 | 845.16 | 0 |
| 854.63 | 849.90 | 1 |
| 859.37 | 854.63 | 0 |
| 864.10 | 859.37 | 0 |
| 868.84 | 864.10 | 1 |
| 873.58 | 868.84 | 0 |
| 878.31 | 873.58 | 1 |
| 883.05 | 878.31 | 1 |
| 887.78 | 883.05 | 0 |
| 892.52 | 887.78 | 1 |
| 897.26 | 892.52 | 2 |
| 901.99 | 897.26 | 2 |
| 906.73 | 901.99 | 3 |
| 911.46 | 906.73 | 4 |
| 916.20 | 911.46 | 4 |
| 920.94 | 916.20 | 4 |
| 925.67 | 920.94 | 3 |
| 930.41 | 925.67 | 6 |
| 935.14 | 930.41 | 4 |
| 939.88 | 935.14 | 2 |
| 944.62 | 939.88 | 4 |
| 949.35 | 944.62 | 2 |
| 954.09 | 949.35 | 3 |
| 958.82 | 954.09 | 2 |
| 963.56 | 958.82 | 3 |
| 968.30 | 963.56 | 1 |
| 973.03 | 968.30 | 2 |
| 977.77 | 973.03 | 1 |
| 982.50 | 977.77 | 1 |
View data
| Bin end | SD of sales | Simulations |
|---|---|---|
| 69.877 | 62.711 | 4 |
| 77.044 | 69.877 | 3 |
| 84.210 | 77.044 | 2 |
| 91.376 | 84.210 | 6 |
| 98.542 | 91.376 | 3 |
| 105.71 | 98.542 | 4 |
| 112.87 | 105.71 | 4 |
| 120.04 | 112.87 | 3 |
| 127.21 | 120.04 | 5 |
| 134.37 | 127.21 | 3 |
| 141.54 | 134.37 | 8 |
| 148.70 | 141.54 | 6 |
| 155.87 | 148.70 | 1 |
| 163.04 | 155.87 | 1 |
| 170.20 | 163.04 | 1 |
| 177.37 | 170.20 | 0 |
| 184.53 | 177.37 | 2 |
| 191.70 | 184.53 | 1 |
| 198.87 | 191.70 | 0 |
| 206.03 | 198.87 | 1 |
| 213.20 | 206.03 | 0 |
| 220.36 | 213.20 | 1 |
| 227.53 | 220.36 | 0 |
| 234.70 | 227.53 | 0 |
| 241.86 | 234.70 | 0 |
| 249.03 | 241.86 | 0 |
| 256.20 | 249.03 | 0 |
| 263.36 | 256.20 | 0 |
| 270.53 | 263.36 | 0 |
| 277.69 | 270.53 | 1 |
View data
| share |
|---|
| 0.1250 |
| 0.0750 |
| 0.0750 |
| 0.1125 |
| 0.0625 |
| 0.1250 |
| 0.1625 |
| 0.1000 |
| 0.1000 |
| 0.0625 |
Assumptions
- Priors — Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight.
- Reproduces the observed statistics — Simulations from the posterior bring back every observed statistic (smallest p = 0.83).
- Calibrated algorithm — On 40 simulated data sets the true values spread evenly across the posteriors (smallest rank-test p = 0.74, base_demand).
Calibrated inputs
| Input | Prior mean | Prior SD | Posterior mean | Posterior SD | 5% | Median | 95% | Shrinkage | Calibration p |
|---|---|---|---|---|---|---|---|---|---|
| base_demand | 1003.93 | 291.54 | 1080.43 | 83.522 | 960.11 | 1071.88 | 1253.55 | 91.8% | 0.7399 |
| volatility | 220.88 | 101.49 | 259.36 | 64.352 | 150.95 | 248.19 | 381.66 | 59.8% | 0.7399 |
Observed statistics and the posterior predictive check
| Statistic | Observed | Predicted mean | 5% | 95% | Predictive p | Distance scale |
|---|---|---|---|---|---|---|
| mean of sales | 930 | 924.41 | 866.78 | 968.93 | 0.9000 | 139.64 |
| SD of sales | 110 | 122.65 | 66.156 | 191.43 | 0.8333 | 112.23 |
Posterior draws (60, equally weighted)
| Draw | base_demand | volatility |
|---|---|---|
| 1 | 999.36 | 188.95 |
| 2 | 1108.76 | 331.85 |
| 3 | 1072.09 | 237.98 |
| 4 | 985.63 | 150.95 |
| 5 | 1039.59 | 208.36 |
| 6 | 1063.43 | 246.54 |
| 7 | 1058.38 | 266.61 |
| 8 | 1102.92 | 291.22 |
| 9 | 1001.92 | 238.51 |
| 10 | 1100.10 | 312.53 |
| 11 | 990.76 | 206.97 |
| 12 | 1094.76 | 295.84 |
| 13 | 1291.17 | 391.38 |
| 14 | 1013.07 | 248.19 |
| 15 | 1134.36 | 288.00 |
| 16 | 1010.65 | 212.86 |
| 17 | 1164.26 | 315.51 |
| 18 | 1016.78 | 262.19 |
| 19 | 1028.44 | 240.75 |
| 20 | 1095.42 | 243.83 |
| 21 | 1179.72 | 319.10 |
| 22 | 1134.09 | 299.82 |
| 23 | 1203.35 | 326.00 |
| 24 | 1145.29 | 296.43 |
| 25 | 974.97 | 198.99 |
| 26 | 1050.68 | 262.91 |
| 27 | 1212.67 | 317.73 |
| 28 | 951.02 | 191.74 |
| 29 | 1097.59 | 258.20 |
| 30 | 1055.35 | 264.88 |
| 31 | 1031.93 | 226.28 |
| 32 | 1012.32 | 250.19 |
| 33 | 1053.30 | 206.85 |
| 34 | 1139.36 | 253.21 |
| 35 | 1113.71 | 274.23 |
| 36 | 1043.01 | 203.30 |
| 37 | 1278.05 | 377.88 |
| 38 | 1073.66 | 240.87 |
| 39 | 1182.54 | 370.35 |
| 40 | 969.44 | 187.97 |
First 40 of 60 rows.
- The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation).
- Rejection ABC kept the 60 simulations closest to the observed statistics (tolerance 0.1264).
- The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.
The exact R script · R R version 4.5.1 (2025-06-13)
# Calibrate a scenario model to observed statistics (ABC, SMC-ABC, neural posterior)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method simulate.calibrate 1.1.0 · spec acc3c8b6c1925e29
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Model, inputs to calibrate and observed statistics
ALGORITHM <- "rejection"
REPLICATES <- as.integer(30)
SEED <- as.integer(1)
COVERAGE <- TRUE && ALGORITHM %in% c("rejection", "npe")
COVERAGE_N <- as.integer(40)
PRED_DRAWS <- as.integer(60)
warnings <- list()
ctx <- tryCatch(cs_calib_setup("{\"inputs\":[{\"name\":\"base_demand\",\"dist\":\"uniform\",\"params\":{\"min\":500,\"max\":1500}},{\"name\":\"volatility\",\"dist\":\"uniform\",\"params\":{\"min\":50,\"max\":400}},{\"name\":\"shock\",\"dist\":\"normal\",\"params\":{\"mean\":0,\"sd\":1}}],\"decisions\":[{\"name\":\"order\",\"value\":1000,\"min\":0,\"max\":3000}],\"formulas\":[{\"name\":\"demand\",\"expr\":\"max(base_demand + volatility * shock, 0)\"},{\"name\":\"sales\",\"expr\":\"min(demand, order)\"}],\"kpis\":[{\"name\":\"sales\",\"label\":\"Sales\"}],\"correlations\":[]}", "base_demand, volatility", "[{\"name\":\"sales\",\"stat\":\"mean\",\"value\":930},{\"name\":\"sales\",\"stat\":\"sd\",\"value\":110}]", REPLICATES),
error = function(e) cs_error("CS_E_INVALID_OPTION", option = "Calibration setup", allowed = "a valid model, inputs to calibrate and observed statistics",
value = conditionMessage(e)))
params <- ctx$params
targets <- ctx$targets
K <- length(params)
J <- length(targets)
# %% Posterior
# Every algorithm works on normal scores z = qnorm(F(theta)), where any prior is a standard normal, and maps back
# through each input's quantile function (Monte Carlo's twin), so bounds and clipping hold.
values <- list(algorithm = ALGORITHM, n_params = K, n_targets = J, replicates = REPLICATES)
for (key in c("n_accepted", "epsilon", "adjusted", "generations", "stop_reason", "acceptance_rate", "epochs_run", "valid_loss", "coverage_p_min")) values[key] <- list(NULL)
ranks <- NULL
gens <- list()
history <- list()
res <- tryCatch({
if (ALGORITHM == "rejection") {
S <- as.integer(3000)
r <- cs_calib_rejection(ctx, S, 0.02, FALSE, SEED)
r$S <- S
r
} else if (ALGORITHM == "smc") {
cs_calib_smc(ctx, as.integer(500), as.integer(6), 0.5, as.integer(100000), 0.02, SEED)
} else {
cs_calib_npe(ctx, as.integer(2000), as.integer(4), as.integer(32), as.integer(300),
0.005, as.integer(4000), SEED, if (COVERAGE) COVERAGE_N else 0)
}
}, error = function(e) cs_error("CS_E_UNDEFINED", what = "The calibration", reason = conditionMessage(e)))
if (ALGORITHM == "rejection") {
S <- res$S
k_acc <- length(res$accepted)
values$n_simulations <- S
values$n_accepted <- k_acc
values$epsilon <- res$epsilon
values$adjusted <- as.integer(res$adjusted)
values$acceptance_rate <- k_acc / S
if (!is.null(res$note)) warnings[[length(warnings) + 1]] <- res$note
if (res$n_finite < S) warnings[[length(warnings) + 1]] <- sprintf("%s of %s simulations gave no number for some statistic (division by zero or an invalid function argument) and were never kept.",
formatC(S - res$n_finite, big.mark = ",", format = "d"), formatC(S, big.mark = ",", format = "d"))
if (COVERAGE) ranks <- cs_calib_coverage_rejection(ctx, res, COVERAGE_N)
} else if (ALGORITHM == "smc") {
gens <- res$generations
values$n_simulations <- res$n_sims
values$n_accepted <- as.integer(500)
values$epsilon <- res$epsilon
values$generations <- length(gens) - 1L
values$stop_reason <- res$stop
values$acceptance_rate <- gens[[length(gens)]]$rate
if (res$stop == "budget") warnings[[length(warnings) + 1]] <- sprintf("The simulation budget ran out during generation %d; the posterior is generation %d's.", length(gens), length(gens) - 1L)
} else {
history <- res$history
values$n_simulations <- res$n_sims
values$epochs_run <- res$epochs_run
values$valid_loss <- res$valid_loss
ranks <- res$ranks
}
post <- res$post_theta
w <- res$weights / sum(res$weights)
prior <- res$prior_theta
values$ess <- 1 / sum(w * w)
prior_w <- rep(1 / nrow(prior), nrow(prior))
post_rows <- list()
cov_p <- list()
if (!is.null(ranks) && nrow(ranks)) {
for (k in seq_along(params)) cov_p[[params[k]]] <- cs_calib_rank_test(ranks[, k], 100)$p
values$coverage_p_min <- min(unlist(cov_p))
}
for (k in seq_along(params)) {
nm <- params[k]
ps <- cs_calib_summarize(post[, k], w)
pr <- cs_calib_summarize(prior[, k], prior_w)
shrink <- if (pr$sd > 0) 1 - (ps$sd / pr$sd)^2 else NULL
values[sprintf("post_mean[%s]", nm)] <- list(ps$mean)
values[sprintf("post_sd[%s]", nm)] <- list(ps$sd)
values[sprintf("post_lo[%s]", nm)] <- list(ps$lo)
values[sprintf("post_median[%s]", nm)] <- list(ps$median)
values[sprintf("post_hi[%s]", nm)] <- list(ps$hi)
values[sprintf("prior_mean[%s]", nm)] <- list(pr$mean)
values[sprintf("prior_sd[%s]", nm)] <- list(pr$sd)
values[sprintf("shrinkage[%s]", nm)] <- list(shrink)
if (!is.null(cov_p[[nm]])) values[sprintf("coverage_p[%s]", nm)] <- list(cov_p[[nm]])
post_rows[[k]] <- list(input = nm, prior_mean = pr$mean, prior_sd = pr$sd, mean = ps$mean, sd = ps$sd, lo = ps$lo,
median = ps$median, hi = ps$hi, shrinkage = shrink, coverage_p = cov_p[[nm]])
}
values$primary <- params[1]
values$primary_mean <- values[[sprintf("post_mean[%s]", params[1])]]
values$primary_lo <- values[[sprintf("post_lo[%s]", params[1])]]
values$primary_hi <- values[[sprintf("post_hi[%s]", params[1])]]
# %% Posterior predictive check: fresh simulations at posterior draws
pred <- cs_calib_predictive(ctx, post, w, PRED_DRAWS, SEED + 17)
target_rows <- list()
ppc_ps <- list()
for (j in seq_along(targets)) {
t <- targets[[j]]
x <- pred[is.finite(pred[, j]), j]
lab <- t$key
obs <- t$value
values[sprintf("observed[%s]", lab)] <- list(obs)
if (ALGORITHM != "npe") values[sprintf("scale[%s]", lab)] <- list(res$scale[j])
if (length(x)) {
m_ <- sum(x) / length(x)
lo_ <- cs_calib_quantile7(x, 0.05)
hi_ <- cs_calib_quantile7(x, 0.95)
p_ <- min(1, 2 * min(sum(x >= obs) / length(x), sum(x <= obs) / length(x)))
ppc_ps[[t$label]] <- p_
} else {
m_ <- NULL; lo_ <- NULL; hi_ <- NULL; p_ <- NULL
}
values[sprintf("ppc_mean[%s]", lab)] <- list(m_)
values[sprintf("ppc_lo[%s]", lab)] <- list(lo_)
values[sprintf("ppc_hi[%s]", lab)] <- list(hi_)
values[sprintf("ppc_p[%s]", lab)] <- list(p_)
target_rows[[j]] <- list(statistic = t$label, observed = obs, ppc_mean = m_, ppc_lo = lo_, ppc_hi = hi_, ppc_p = p_,
scale = if (ALGORITHM != "npe") res$scale[j] else NULL)
}
# %% Assumptions
assumptions <- list(list(key = "priors", label = "Priors", status = "info",
detail = "Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight."))
bad <- names(ppc_ps)[unlist(ppc_ps) < 0.05]
if (length(ppc_ps) < J) {
assumptions[[2]] <- list(key = "reproduces_targets", label = "Reproduces the observed statistics", status = "warn",
detail = "Some statistics gave no number in the posterior predictive simulations.")
} else if (length(bad)) {
assumptions[[2]] <- list(key = "reproduces_targets", label = "Reproduces the observed statistics", status = "warn",
detail = paste0("Posterior simulations rarely bring back ", paste(bad, collapse = ", "),
" (p < 0.05): the model may be unable to produce what was observed, or the targets conflict."))
} else {
assumptions[[2]] <- list(key = "reproduces_targets", label = "Reproduces the observed statistics", status = "pass",
detail = sprintf("Simulations from the posterior bring back every observed statistic (smallest p = %.2f).", min(unlist(ppc_ps))))
}
if (length(cov_p)) {
cp <- unlist(cov_p)
worst <- names(cp)[which.min(cp)]
if (cp[[worst]] >= 0.01) {
assumptions[[3]] <- list(key = "calibrated", label = "Calibrated algorithm", status = "pass",
detail = sprintf("On %d simulated data sets the true values spread evenly across the posteriors (smallest rank-test p = %.2f, %s).", nrow(ranks), cp[[worst]], worst))
} else {
assumptions[[3]] <- list(key = "calibrated", label = "Calibrated algorithm", status = "warn",
detail = paste0(sprintf("On %d simulated data sets the true values of %s fall unevenly across the posteriors (rank-test p = %.3f): ", nrow(ranks), worst, cp[[worst]]),
"intervals may be too narrow or shifted; keep fewer simulations, add some, or train longer."))
}
} else {
assumptions[[3]] <- list(key = "calibrated", label = "Calibrated algorithm", status = "info",
detail = paste0("Not checked: ", if (ALGORITHM == "smc") "SMC-ABC has no cheap calibration check." else "the calibration check is off."))
}
# %% Charts
charts <- list()
for (k in seq_len(min(K, 6))) {
nm <- params[k]
h <- cs_pf_bandwidth(post[, k], w)
q <- cs_pf_weighted_quantiles(prior[, k], prior_w, c(0.01, 0.99))
lo_g <- min(q[1], min(post[, k]) - 3 * h)
hi_g <- max(q[2], max(post[, k]) + 3 * h)
grid <- seq(lo_g, hi_g, length.out = 150)
charts[[length(charts) + 1]] <- cs_chart(paste0("posterior_", nm), "prior-posterior", sprintf("%s: prior and posterior", nm), list(
x = cs_col(nm, c(grid, grid)),
density = cs_col("density", c(cs_pf_kde(prior[, k], grid, prior_w), cs_pf_kde(post[, k], grid, w))),
curve = cs_col("curve", c(rep("prior", length(grid)), rep("posterior", length(grid))), kind = "categorical")))
}
for (j in seq_along(targets)) {
t <- targets[[j]]
hst <- cs_sim_histogram(pred[, j], 30)
charts[[length(charts) + 1]] <- cs_chart(sprintf("ppc_%d", j), "mc-distribution", sprintf("Posterior predictive: %s (observed %s)", t$label, sprintf("%.4g", t$value)), list(
bin_low = cs_col(t$label, hst$bin_low), bin_high = cs_col("Bin end", hst$bin_high), count = cs_col("Simulations", hst$count)),
controls = list(percentiles = c(5, 50, 95), target = t$value))
}
if (length(gens)) {
charts[[length(charts) + 1]] <- cs_chart("tolerance", "series-line", "SMC-ABC tolerance by generation", list(
x = cs_col("generation", as.numeric(vapply(gens, function(g) g$generation, numeric(1)))),
y = cs_col("tolerance", vapply(gens, function(g) g$epsilon, numeric(1))),
group = cs_col("series", rep("tolerance", length(gens)), kind = "categorical")))
}
if (!is.null(ranks) && nrow(ranks)) {
charts[[length(charts) + 1]] <- cs_chart("coverage", "pit-histogram", "Calibration check: where the true values fell in their posteriors (all inputs)", list(
share = cs_col("share", cs_calib_rank_test(ranks, 100)$shares)))
}
if (length(history)) {
ep <- as.numeric(vapply(history, function(h_) h_$epoch, numeric(1)))
charts[[length(charts) + 1]] <- cs_chart("training", "series-line", "Network training: loss on training and held-out simulations", list(
x = cs_col("epoch", c(ep, ep)),
y = cs_col("negative log-likelihood", c(vapply(history, function(h_) h_$loss, numeric(1)), vapply(history, function(h_) h_$valid_loss, numeric(1)))),
group = cs_col("set", c(rep("training", length(ep)), rep("held out", length(ep))), kind = "categorical")))
}
# %% Tables
tables <- list(
list(key = "posterior", title = "Calibrated inputs",
columns = list(list(key = "input", label = "Input", type = "string"), list(key = "prior_mean", label = "Prior mean", type = "number"),
list(key = "prior_sd", label = "Prior SD", type = "number"), list(key = "mean", label = "Posterior mean", type = "number"),
list(key = "sd", label = "Posterior SD", type = "number"), list(key = "lo", label = "5%", type = "number"),
list(key = "median", label = "Median", type = "number"), list(key = "hi", label = "95%", type = "number"),
list(key = "shrinkage", label = "Shrinkage", type = "percent"), list(key = "coverage_p", label = "Calibration p", type = "number")),
rows = post_rows),
list(key = "targets", title = "Observed statistics and the posterior predictive check",
columns = list(list(key = "statistic", label = "Statistic", type = "string"), list(key = "observed", label = "Observed", type = "number"),
list(key = "ppc_mean", label = "Predicted mean", type = "number"), list(key = "ppc_lo", label = "5%", type = "number"),
list(key = "ppc_hi", label = "95%", type = "number"), list(key = "ppc_p", label = "Predictive p", type = "number"),
list(key = "scale", label = "Distance scale", type = "number")),
rows = target_rows))
if (length(gens)) {
tables[[length(tables) + 1]] <- list(key = "generations", title = "SMC-ABC generations",
columns = list(list(key = "generation", label = "Generation", type = "integer"), list(key = "epsilon", label = "Tolerance", type = "number"),
list(key = "sims", label = "Simulations", type = "integer"), list(key = "rate", label = "Acceptance", type = "percent"),
list(key = "ess", label = "Effective particles", type = "number")),
rows = lapply(gens, function(g) list(generation = g$generation, epsilon = g$epsilon, sims = g$sims, rate = g$rate, ess = g$ess)))
}
n_show <- min(500L, nrow(post))
idx <- cs_calib_resample(nrow(post), w, n_show, cs_runif(cs_rng(SEED + 19), 1))
sample_cols <- c(list(list(key = "draw", label = "Draw", type = "integer")), lapply(seq_along(params), function(k) list(key = sprintf("p%d", k), label = params[k], type = "number")))
tables[[length(tables) + 1]] <- list(key = "sample", title = sprintf("Posterior draws (%d, equally weighted)", n_show), columns = sample_cols,
rows = lapply(seq_len(n_show), function(i) c(list(draw = i), stats::setNames(as.list(post[idx[i], ]), sprintf("p%d", seq_len(K))))))
# %% Posterior draws
artifacts <- list()
if (TRUE) {
out <- cs_ml_out_dir("target/academy-parity/run-8142/simulate.calibrate/censored-sales-rejection/out-r")
path <- file.path(out, "posterior.parquet")
dfp <- as.data.frame(c(list(draw = seq_len(nrow(post))), stats::setNames(lapply(seq_len(K), function(k) post[, k]), params), list(weight = w)), check.names = FALSE)
nanoparquet::write_parquet(dfp, path)
artifacts <- list(list(key = "posterior", path = path, format = "parquet", title = "Posterior draws"))
}
# %% Result
g4 <- function(v) sprintf("%.4g", v)
ALG <- c(rejection = "rejection ABC", smc = "SMC-ABC", npe = "neural posterior estimation")[[ALGORITHM]]
values$algorithm <- ALG
desc <- paste(vapply(params, function(nm) sprintf("%s %s (90%% %s to %s)", nm, g4(values[[sprintf("post_mean[%s]", nm)]]),
g4(values[[sprintf("post_lo[%s]", nm)]]), g4(values[[sprintf("post_hi[%s]", nm)]])), ""), collapse = "; ")
summary <- sprintf("Calibrated %d input(s) to %d observed statistic(s) by %s (%s simulations of %d scenario(s) each): %s.",
K, J, ALG, formatC(values$n_simulations, big.mark = ",", format = "d"), REPLICATES, desc)
notes <- c(paste0("The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. ",
"Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation)."))
if (ALGORITHM == "rejection") {
notes <- c(notes, paste0(sprintf("Rejection ABC kept the %s simulations closest to the observed statistics (tolerance %s)", formatC(values$n_accepted, big.mark = ",", format = "d"), g4(res$epsilon)),
if (res$adjusted) ", then shifted them by a weighted local-linear regression on the statistics (Beaumont et al. 2002)." else "."))
} else if (ALGORITHM == "smc") {
notes <- c(notes, paste0(sprintf("SMC-ABC ran %d generation(s) after the prior one (stop: %s); each tolerance is the 0.5 quantile of the previous distances, ", length(gens) - 1L, res$stop),
"particles move by a Gaussian kernel with twice the weighted covariance, and weights are prior over the kernel mixture (Beaumont et al. 2009)."))
} else {
notes <- c(notes, sprintf("A mixture density network (4 components, two tanh layers of 32) learned the posterior from prior simulations; training stopped at epoch %d (best held-out epoch %d).",
res$epochs_run, res$best_epoch))
}
notes <- c(notes, "The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.")
statistics <- lapply(params, function(nm) list(key = sprintf("post_mean[%s]", nm), label = sprintf("%s (posterior mean)", nm), value = values[[sprintf("post_mean[%s]", nm)]]))
cs_publish(list(
method = "simulate.calibrate",
methodVersion = "1.1.0",
title = "Scenario calibration",
engine = if (ALGORITHM != "npe") cs_engine_info("jsonlite", "nanoparquet") else cs_engine_info("jsonlite", "nanoparquet", "torch"),
n = values$n_simulations,
summary = summary,
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values,
artifacts = artifacts
))
Calibrated 2 input(s) to 2 observed statistic(s) by rejection ABC (3,000 simulations of 30 scenario(s) each): base_demand 1080 (90% 960.1 to 1254); volatility 259.4 (90% 150.9 to 381.7).
- base_demand (posterior mean)
- 1080.43
- volatility (posterior mean)
- 259.36
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Priors — Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight.
- Reproduces the observed statistics — Simulations from the posterior bring back every observed statistic (smallest p = 0.83).
- Calibrated algorithm — On 40 simulated data sets the true values spread evenly across the posteriors (smallest rank-test p = 0.74, base_demand).
Calibrated inputs
| Input | Prior mean | Prior SD | Posterior mean | Posterior SD | 5% | Median | 95% | Shrinkage | Calibration p |
|---|---|---|---|---|---|---|---|---|---|
| base_demand | 1003.93 | 291.54 | 1080.43 | 83.522 | 960.11 | 1071.88 | 1253.55 | 91.8% | 0.7399 |
| volatility | 220.88 | 101.49 | 259.36 | 64.352 | 150.95 | 248.19 | 381.66 | 59.8% | 0.7399 |
Observed statistics and the posterior predictive check
| Statistic | Observed | Predicted mean | 5% | 95% | Predictive p | Distance scale |
|---|---|---|---|---|---|---|
| mean of sales | 930 | 924.41 | 866.78 | 968.93 | 0.9000 | 139.64 |
| SD of sales | 110 | 122.65 | 66.156 | 191.43 | 0.8333 | 112.23 |
Posterior draws (60, equally weighted)
| Draw | base_demand | volatility |
|---|---|---|
| 1 | 999.36 | 188.95 |
| 2 | 1108.76 | 331.85 |
| 3 | 1072.09 | 237.98 |
| 4 | 985.63 | 150.95 |
| 5 | 1039.59 | 208.36 |
| 6 | 1063.43 | 246.54 |
| 7 | 1058.38 | 266.61 |
| 8 | 1102.92 | 291.22 |
| 9 | 1001.92 | 238.51 |
| 10 | 1100.10 | 312.53 |
| 11 | 990.76 | 206.97 |
| 12 | 1094.76 | 295.84 |
| 13 | 1291.17 | 391.38 |
| 14 | 1013.07 | 248.19 |
| 15 | 1134.36 | 288.00 |
| 16 | 1010.65 | 212.86 |
| 17 | 1164.26 | 315.51 |
| 18 | 1016.78 | 262.19 |
| 19 | 1028.44 | 240.75 |
| 20 | 1095.42 | 243.83 |
| 21 | 1179.72 | 319.10 |
| 22 | 1134.09 | 299.82 |
| 23 | 1203.35 | 326.00 |
| 24 | 1145.29 | 296.43 |
| 25 | 974.97 | 198.99 |
| 26 | 1050.68 | 262.91 |
| 27 | 1212.67 | 317.73 |
| 28 | 951.02 | 191.74 |
| 29 | 1097.59 | 258.20 |
| 30 | 1055.35 | 264.88 |
| 31 | 1031.93 | 226.28 |
| 32 | 1012.32 | 250.19 |
| 33 | 1053.30 | 206.85 |
| 34 | 1139.36 | 253.21 |
| 35 | 1113.71 | 274.23 |
| 36 | 1043.01 | 203.30 |
| 37 | 1278.05 | 377.88 |
| 38 | 1073.66 | 240.87 |
| 39 | 1182.54 | 370.35 |
| 40 | 969.44 | 187.97 |
First 40 of 60 rows.
- The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation).
- Rejection ABC kept the 60 simulations closest to the observed statistics (tolerance 0.1264).
- The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Calibrate a scenario model to observed statistics (ABC, SMC-ABC, neural posterior)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method simulate.calibrate 1.1.0 · spec acc3c8b6c1925e29
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.sim import calibrate as cb # ABC, SMC-ABC and NPE on the scenario-model twins (twin of codesplashr cs_calib_*)
from codesplash.sim import mc
from codesplash.stats import particle as pf # weighted quantiles and kernel densities
from codesplash.stats.rng import Rng
# %% Model, inputs to calibrate and observed statistics
ALGORITHM = "rejection"
REPLICATES = int(30)
SEED = int(1)
COVERAGE = True and ALGORITHM in ("rejection", "npe")
COVERAGE_N = int(40)
PRED_DRAWS = int(60)
warnings = []
try:
ctx = cb.setup("{\"inputs\":[{\"name\":\"base_demand\",\"dist\":\"uniform\",\"params\":{\"min\":500,\"max\":1500}},{\"name\":\"volatility\",\"dist\":\"uniform\",\"params\":{\"min\":50,\"max\":400}},{\"name\":\"shock\",\"dist\":\"normal\",\"params\":{\"mean\":0,\"sd\":1}}],\"decisions\":[{\"name\":\"order\",\"value\":1000,\"min\":0,\"max\":3000}],\"formulas\":[{\"name\":\"demand\",\"expr\":\"max(base_demand + volatility * shock, 0)\"},{\"name\":\"sales\",\"expr\":\"min(demand, order)\"}],\"kpis\":[{\"name\":\"sales\",\"label\":\"Sales\"}],\"correlations\":[]}", "base_demand, volatility", "[{\"name\":\"sales\",\"stat\":\"mean\",\"value\":930},{\"name\":\"sales\",\"stat\":\"sd\",\"value\":110}]", REPLICATES)
except ValueError as e:
cs.cs_error("CS_E_INVALID_OPTION", option="Calibration setup", allowed="a valid model, inputs to calibrate and observed statistics", value=str(e))
params = ctx["params"]
targets = ctx["targets"]
K, J = len(params), len(targets)
# %% Posterior
# Every algorithm works on normal scores z = Φ⁻¹(F(θ)), where any prior is a standard normal, and maps back
# through each input's quantile function (Monte Carlo's twin), so bounds and clipping hold.
values = {"algorithm": ALGORITHM, "n_params": K, "n_targets": J, "replicates": REPLICATES}
for key in ("n_accepted", "epsilon", "adjusted", "generations", "stop_reason", "acceptance_rate", "epochs_run", "valid_loss", "coverage_p_min"):
values[key] = None
ranks = None
gens = []
history = []
try:
if ALGORITHM == "rejection":
S = int(3000)
res = cb.rejection(ctx, S, 0.02, False, SEED)
k_acc = len(res["accepted"])
values.update({"n_simulations": S, "n_accepted": k_acc, "epsilon": res["epsilon"], "adjusted": int(res["adjusted"]), "acceptance_rate": k_acc / S})
if res["note"]:
warnings.append(res["note"])
if res["n_finite"] < S:
warnings.append(f"{S - res['n_finite']:,} of {S:,} simulations gave no number for some statistic (division by zero or an invalid function argument) and were never kept.")
if COVERAGE:
ranks = cb.coverage_rejection(ctx, res, COVERAGE_N)
elif ALGORITHM == "smc":
res = cb.smc(ctx, int(500), int(6), 0.5, int(100000), 0.02, SEED)
gens = res["generations"]
values.update({"n_simulations": res["n_sims"], "n_accepted": int(500), "epsilon": res["epsilon"], "generations": len(gens) - 1,
"stop_reason": res["stop"], "acceptance_rate": gens[-1]["rate"]})
if res["stop"] == "budget":
warnings.append(f"The simulation budget ran out during generation {len(gens)}; the posterior is generation {len(gens) - 1}'s.")
else:
res = cb.npe(ctx, int(2000), int(4), int(32), int(300),
0.005, int(4000), SEED, COVERAGE_N if COVERAGE else 0)
history = res["history"]
values.update({"n_simulations": res["n_sims"], "epochs_run": res["epochs_run"], "valid_loss": res["valid_loss"]})
ranks = res["ranks"]
except ValueError as e:
cs.cs_error("CS_E_UNDEFINED", what="The calibration", reason=str(e))
post, w, prior = res["post_theta"], res["weights"], res["prior_theta"]
w = w / float(np.sum(w))
values["ess"] = 1.0 / float(np.sum(w * w))
prior_w = np.full(prior.shape[0], 1.0 / prior.shape[0])
post_rows = []
cov_p = {}
if ranks is not None and len(ranks):
for k, nm in enumerate(params):
cov_p[nm] = cb.rank_test(ranks[:, k], 100.0)[2]
values["coverage_p_min"] = float(min(cov_p.values()))
for k, nm in enumerate(params):
ps = cb.summarize(post[:, k], w)
pr = cb.summarize(prior[:, k], prior_w)
shrink = 1.0 - (ps["sd"] / pr["sd"]) ** 2 if pr["sd"] > 0 else None
values[f"post_mean[{nm}]"], values[f"post_sd[{nm}]"] = ps["mean"], ps["sd"]
values[f"post_lo[{nm}]"], values[f"post_median[{nm}]"], values[f"post_hi[{nm}]"] = ps["lo"], ps["median"], ps["hi"]
values[f"prior_mean[{nm}]"], values[f"prior_sd[{nm}]"], values[f"shrinkage[{nm}]"] = pr["mean"], pr["sd"], shrink
if nm in cov_p:
values[f"coverage_p[{nm}]"] = cov_p[nm]
post_rows.append({"input": nm, "prior_mean": pr["mean"], "prior_sd": pr["sd"], "mean": ps["mean"], "sd": ps["sd"], "lo": ps["lo"],
"median": ps["median"], "hi": ps["hi"], "shrinkage": shrink, "coverage_p": cov_p.get(nm)})
values.update({"primary": params[0], "primary_mean": values[f"post_mean[{params[0]}]"], "primary_lo": values[f"post_lo[{params[0]}]"],
"primary_hi": values[f"post_hi[{params[0]}]"]})
# %% Posterior predictive check: fresh simulations at posterior draws
pred = cb.predictive(ctx, post, w, PRED_DRAWS, SEED + 17)
target_rows = []
ppc_ps = []
for j, t in enumerate(targets):
x = pred[np.isfinite(pred[:, j]), j]
lab = t["key"]
obs = t["value"]
values[f"observed[{lab}]"] = obs
if ALGORITHM != "npe":
values[f"scale[{lab}]"] = float(res["scale"][j])
if len(x):
m_ = float(np.sum(x)) / len(x)
lo_, hi_ = cb.quantile7(x, 0.05), cb.quantile7(x, 0.95)
p_ = min(1.0, 2.0 * min(float(np.sum(x >= obs)) / len(x), float(np.sum(x <= obs)) / len(x)))
else:
m_ = lo_ = hi_ = p_ = None
values[f"ppc_mean[{lab}]"], values[f"ppc_lo[{lab}]"], values[f"ppc_hi[{lab}]"], values[f"ppc_p[{lab}]"] = m_, lo_, hi_, p_
if p_ is not None:
ppc_ps.append((t["label"], p_))
target_rows.append({"statistic": t["label"], "observed": obs, "ppc_mean": m_, "ppc_lo": lo_, "ppc_hi": hi_, "ppc_p": p_,
"scale": float(res["scale"][j]) if ALGORITHM != "npe" else None})
# %% Assumptions
assumptions = [{"key": "priors", "label": "Priors", "status": "info",
"detail": "Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight."}]
bad = [lab for lab, p_ in ppc_ps if p_ < 0.05]
if len(ppc_ps) < J:
assumptions.append({"key": "reproduces_targets", "label": "Reproduces the observed statistics", "status": "warn",
"detail": "Some statistics gave no number in the posterior predictive simulations."})
elif bad:
assumptions.append({"key": "reproduces_targets", "label": "Reproduces the observed statistics", "status": "warn",
"detail": "Posterior simulations rarely bring back " + ", ".join(bad) + " (p < 0.05): the model may be unable to produce what was observed, or the targets conflict."})
else:
assumptions.append({"key": "reproduces_targets", "label": "Reproduces the observed statistics", "status": "pass",
"detail": f"Simulations from the posterior bring back every observed statistic (smallest p = {min(p_ for _, p_ in ppc_ps):.2f})."})
if cov_p:
worst = min(cov_p, key=lambda nm: cov_p[nm])
if cov_p[worst] >= 0.01:
assumptions.append({"key": "calibrated", "label": "Calibrated algorithm", "status": "pass",
"detail": f"On {len(ranks)} simulated data sets the true values spread evenly across the posteriors (smallest rank-test p = {cov_p[worst]:.2f}, {worst})."})
else:
assumptions.append({"key": "calibrated", "label": "Calibrated algorithm", "status": "warn",
"detail": f"On {len(ranks)} simulated data sets the true values of {worst} fall unevenly across the posteriors (rank-test p = {cov_p[worst]:.3f}): "
"intervals may be too narrow or shifted; keep fewer simulations, add some, or train longer."})
else:
assumptions.append({"key": "calibrated", "label": "Calibrated algorithm", "status": "info",
"detail": "Not checked: " + ("SMC-ABC has no cheap calibration check." if ALGORITHM == "smc" else "the calibration check is off.")})
# %% Charts
charts = []
for k, nm in enumerate(params[:6]):
pw = prior_w
h = pf.bandwidth(post[:, k], w)
q01, q99 = pf.weighted_quantiles(prior[:, k], pw, (0.01, 0.99))
lo_g = min(q01, float(np.min(post[:, k])) - 3.0 * h)
hi_g = max(q99, float(np.max(post[:, k])) + 3.0 * h)
grid = np.linspace(lo_g, hi_g, 150)
charts.append(cs.chart(f"posterior_{nm}", "prior-posterior", f"{nm}: prior and posterior", {
"x": cs.col(nm, np.concatenate([grid, grid])),
"density": cs.col("density", np.concatenate([pf.kde(prior[:, k], grid, pw), pf.kde(post[:, k], grid, w)])),
"curve": cs.col("curve", ["prior"] * len(grid) + ["posterior"] * len(grid), kind="categorical")}))
for j, t in enumerate(targets):
hst = mc.histogram(pred[:, j], 30)
charts.append(cs.chart(f"ppc_{j + 1}", "mc-distribution", f"Posterior predictive: {t['label']} (observed {t['value']:.4g})", {
"bin_low": cs.col(t["label"], hst["bin_low"]), "bin_high": cs.col("Bin end", hst["bin_high"]), "count": cs.col("Simulations", hst["count"])},
controls={"percentiles": [5, 50, 95], "target": float(t["value"])}))
if gens:
charts.append(cs.chart("tolerance", "series-line", "SMC-ABC tolerance by generation", {
"x": cs.col("generation", [float(g["generation"]) for g in gens]), "y": cs.col("tolerance", [g["epsilon"] for g in gens]),
"group": cs.col("series", ["tolerance"] * len(gens), kind="categorical")}))
if ranks is not None and len(ranks):
shares = cb.rank_test(ranks, 100.0)[0]
charts.append(cs.chart("coverage", "pit-histogram", "Calibration check: where the true values fell in their posteriors (all inputs)", {
"share": cs.col("share", shares)}))
if history:
ep = [float(h_["epoch"]) for h_ in history]
charts.append(cs.chart("training", "series-line", "Network training: loss on training and held-out simulations", {
"x": cs.col("epoch", ep + ep), "y": cs.col("negative log-likelihood", [h_["loss"] for h_ in history] + [h_["valid_loss"] for h_ in history]),
"group": cs.col("set", ["training"] * len(ep) + ["held out"] * len(ep), kind="categorical")}))
# %% Tables
tables = [{"key": "posterior", "title": "Calibrated inputs",
"columns": [{"key": "input", "label": "Input", "type": "string"}, {"key": "prior_mean", "label": "Prior mean", "type": "number"},
{"key": "prior_sd", "label": "Prior SD", "type": "number"}, {"key": "mean", "label": "Posterior mean", "type": "number"},
{"key": "sd", "label": "Posterior SD", "type": "number"}, {"key": "lo", "label": "5%", "type": "number"},
{"key": "median", "label": "Median", "type": "number"}, {"key": "hi", "label": "95%", "type": "number"},
{"key": "shrinkage", "label": "Shrinkage", "type": "percent"}, {"key": "coverage_p", "label": "Calibration p", "type": "number"}],
"rows": post_rows},
{"key": "targets", "title": "Observed statistics and the posterior predictive check",
"columns": [{"key": "statistic", "label": "Statistic", "type": "string"}, {"key": "observed", "label": "Observed", "type": "number"},
{"key": "ppc_mean", "label": "Predicted mean", "type": "number"}, {"key": "ppc_lo", "label": "5%", "type": "number"},
{"key": "ppc_hi", "label": "95%", "type": "number"}, {"key": "ppc_p", "label": "Predictive p", "type": "number"},
{"key": "scale", "label": "Distance scale", "type": "number"}],
"rows": target_rows}]
if gens:
tables.append({"key": "generations", "title": "SMC-ABC generations",
"columns": [{"key": "generation", "label": "Generation", "type": "integer"}, {"key": "epsilon", "label": "Tolerance", "type": "number"},
{"key": "sims", "label": "Simulations", "type": "integer"}, {"key": "rate", "label": "Acceptance", "type": "percent"},
{"key": "ess", "label": "Effective particles", "type": "number"}],
"rows": [{"generation": g["generation"], "epsilon": g["epsilon"], "sims": g["sims"], "rate": g["rate"], "ess": g["ess"]} for g in gens]})
n_show = min(500, post.shape[0])
idx = cb.resample(post.shape[0], w, n_show, float(Rng(SEED + 19).uniform(1)[0]))
tables.append({"key": "sample", "title": f"Posterior draws ({n_show}, equally weighted)",
"columns": [{"key": "draw", "label": "Draw", "type": "integer"}] + [{"key": f"p{k + 1}", "label": nm, "type": "number"} for k, nm in enumerate(params)],
"rows": [{"draw": i + 1, **{f"p{k + 1}": float(post[idx[i], k]) for k in range(K)}} for i in range(n_show)]})
# %% Posterior draws
artifacts = []
if True:
out = csml.out_dir("target/academy-parity/run-8142/simulate.calibrate/censored-sales-rejection/out-python")
path = os.path.join(out, "posterior.parquet")
pd.DataFrame({"draw": np.arange(1, post.shape[0] + 1), **{nm: post[:, k] for k, nm in enumerate(params)}, "weight": w}).to_parquet(path, index=False)
artifacts.append({"key": "posterior", "path": path, "format": "parquet", "title": "Posterior draws"})
# %% Result
ALG = {"rejection": "rejection ABC", "smc": "SMC-ABC", "npe": "neural posterior estimation"}[ALGORITHM]
values["algorithm"] = ALG
desc = "; ".join(f"{nm} {values[f'post_mean[{nm}]']:.4g} (90% {values[f'post_lo[{nm}]']:.4g} to {values[f'post_hi[{nm}]']:.4g})" for nm in params)
summary = f"Calibrated {K} input(s) to {J} observed statistic(s) by {ALG} ({values['n_simulations']:,} simulations of {REPLICATES} scenario(s) each): {desc}."
notes = ["The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. "
"Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation)."]
if ALGORITHM == "rejection":
notes.append(f"Rejection ABC kept the {values['n_accepted']:,} simulations closest to the observed statistics (tolerance {res['epsilon']:.4g})"
+ (", then shifted them by a weighted local-linear regression on the statistics (Beaumont et al. 2002)." if res["adjusted"] else "."))
elif ALGORITHM == "smc":
notes.append(f"SMC-ABC ran {len(gens) - 1} generation(s) after the prior one (stop: {res['stop']}); each tolerance is the 0.5 quantile of the previous distances, "
"particles move by a Gaussian kernel with twice the weighted covariance, and weights are prior over the kernel mixture (Beaumont et al. 2009).")
else:
notes.append(f"A mixture density network (4 components, two tanh layers of 32) learned the posterior from prior simulations; "
f"training stopped at epoch {res['epochs_run']} (best held-out epoch {res['best_epoch']}).")
notes.append("The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.")
statistics = [{"key": f"post_mean[{nm}]", "label": f"{nm} (posterior mean)", "value": values[f"post_mean[{nm}]"]} for nm in params]
cs.publish({
"method": "simulate.calibrate",
"methodVersion": "1.1.0",
"title": "Scenario calibration",
"engine": cs.engine_info("numpy", "scipy", "pandas") if ALGORITHM != "npe" else cs.engine_info("numpy", "scipy", "pandas", "torch"),
"n": values["n_simulations"],
"summary": summary,
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
"artifacts": artifacts,
})
Base demand is now 1,080 on average. Its 90% interval runs from 960 to 1,254, much narrower than the prior's 500 to 1,500. Shrinkage measures that: 91.8% of the prior's spread is gone.
Predict: an uninformative statistic
PredictPredict first
You calibrate a price elasticity input using only the observed mean of the order quantity, which doesn't depend on the elasticity. What shrinkage do you expect for the elasticity?
Reveal
Close to 0%. A statistic that doesn't depend on an input can't tell you anything about it, so the posterior stays as wide as the prior. Add a statistic the input actually moves.
Did it reproduce what was seen?
ReadThe posterior predictive pPosterior predictive pHow often simulations from the posterior land at least as far out as the observed statistic (two-sided); small means a misfit. re-simulates the model at posterior draws. It then asks how often the statistics land at least as far out as the observed ones. A small p (below 0.05) means the model can't produce what was seen at any input values. The model, or the observed numbers, need another look.
The mean of sales came back with p = 0.90.
Is the posterior honest?
ReadA posterior can be confidently wrong. The intervals can be too narrow because too many simulations were kept, or because a neural network was undertrained. The calibration checkCalibration check (simulation-based calibration)Simulated data sets with known true values: if the algorithm is calibrated, each true value's rank in its posterior is uniform. catches this with simulated data sets whose true values are known. When the algorithm is calibrated, each true value is equally likely to land anywhere within its posterior. The rank histogram should then look flat.
The smallest chi-square p across inputs here is 0.74. Below 0.01 is a warning.
Three ways to get the posterior
Read- Rejection ABC keeps the closest share of prior simulations. It's simple, and its calibration check is cheap, but it wastes simulations when the posterior is narrow.
- SMC-ABCSMC-ABCABC in generations: particles move, are kept only within a shrinking tolerance, and are reweighted against the prior. works in generations. It moves the particles that matched, tightens the tolerance and reweights against the prior, so later simulations concentrate where the posterior is.
Calibrated 2 input(s) to 2 observed statistic(s) by SMC-ABC (2,000 simulations of 30 scenario(s) each): base_demand 1124 (90% 921.2 to 1394); volatility 258.1 (90% 102.6 to 381.5).
- base_demand (posterior mean)
- 1124.27
- volatility (posterior mean)
- 258.08
Plots
View data
| curve | density | base_demand |
|---|---|---|
| prior | 0.0005 | 504.58 |
| prior | 0.0006 | 512.27 |
| prior | 0.0006 | 519.95 |
| prior | 0.0006 | 527.64 |
| prior | 0.0007 | 535.33 |
| prior | 0.0007 | 543.01 |
| prior | 0.0007 | 550.70 |
| prior | 0.0008 | 558.38 |
| prior | 0.0008 | 566.07 |
| prior | 0.0008 | 573.76 |
| prior | 0.0008 | 581.44 |
| prior | 0.0009 | 589.13 |
| prior | 0.0009 | 596.81 |
| prior | 0.0009 | 604.50 |
| prior | 0.0009 | 612.18 |
| prior | 0.0009 | 619.87 |
| prior | 0.0009 | 627.56 |
| prior | 0.0009 | 635.24 |
| prior | 0.0009 | 642.93 |
| prior | 0.0010 | 650.61 |
| prior | 0.0010 | 658.30 |
| prior | 0.0010 | 665.99 |
| prior | 0.0010 | 673.67 |
| prior | 0.0010 | 681.36 |
| prior | 0.0010 | 689.04 |
| prior | 0.0010 | 696.73 |
| prior | 0.0010 | 704.41 |
| prior | 0.0009 | 712.10 |
| prior | 0.0009 | 719.79 |
| prior | 0.0009 | 727.47 |
| prior | 0.0009 | 735.16 |
| prior | 0.0009 | 742.84 |
| prior | 0.0009 | 750.53 |
| prior | 0.0009 | 758.22 |
| prior | 0.0009 | 765.90 |
| prior | 0.0009 | 773.59 |
| prior | 0.0009 | 781.27 |
| prior | 0.0009 | 788.96 |
| prior | 0.0009 | 796.65 |
| prior | 0.0009 | 804.33 |
| prior | 0.0009 | 812.02 |
| prior | 0.0009 | 819.70 |
| prior | 0.0009 | 827.39 |
| prior | 0.0009 | 835.07 |
| prior | 0.0009 | 842.76 |
| prior | 0.0009 | 850.45 |
| prior | 0.0009 | 858.13 |
| prior | 0.0009 | 865.82 |
| prior | 0.0009 | 873.50 |
| prior | 0.0009 | 881.19 |
| prior | 0.0009 | 888.88 |
| prior | 0.0009 | 896.56 |
| prior | 0.0009 | 904.25 |
| prior | 0.0010 | 911.93 |
| prior | 0.0010 | 919.62 |
| prior | 0.0010 | 927.31 |
| prior | 0.0010 | 934.99 |
| prior | 0.0010 | 942.68 |
| prior | 0.0010 | 950.36 |
| prior | 0.0010 | 958.05 |
First 60 of 300 rows.
View data
| curve | density | volatility |
|---|---|---|
| prior | 1.161e-5 | −35.911 |
| prior | 1.590e-5 | −32.363 |
| prior | 2.156e-5 | −28.815 |
| prior | 2.892e-5 | −25.267 |
| prior | 3.838e-5 | −21.719 |
| prior | 5.042e-5 | −18.171 |
| prior | 6.554e-5 | −14.623 |
| prior | 8.433e-5 | −11.075 |
| prior | 0.0001 | −7.527 |
| prior | 0.0001 | −3.979 |
| prior | 0.0002 | −0.4314 |
| prior | 0.0002 | 3.117 |
| prior | 0.0003 | 6.664 |
| prior | 0.0003 | 10.212 |
| prior | 0.0004 | 13.760 |
| prior | 0.0004 | 17.308 |
| prior | 0.0005 | 20.856 |
| prior | 0.0006 | 24.404 |
| prior | 0.0007 | 27.952 |
| prior | 0.0008 | 31.500 |
| prior | 0.0009 | 35.048 |
| prior | 0.0010 | 38.596 |
| prior | 0.0011 | 42.144 |
| prior | 0.0013 | 45.692 |
| prior | 0.0014 | 49.240 |
| prior | 0.0015 | 52.788 |
| prior | 0.0016 | 56.336 |
| prior | 0.0018 | 59.884 |
| prior | 0.0019 | 63.432 |
| prior | 0.0020 | 66.979 |
| prior | 0.0021 | 70.527 |
| prior | 0.0022 | 74.075 |
| prior | 0.0022 | 77.623 |
| prior | 0.0023 | 81.171 |
| prior | 0.0024 | 84.719 |
| prior | 0.0024 | 88.267 |
| prior | 0.0025 | 91.815 |
| prior | 0.0025 | 95.363 |
| prior | 0.0025 | 98.911 |
| prior | 0.0025 | 102.46 |
| prior | 0.0026 | 106.01 |
| prior | 0.0026 | 109.55 |
| prior | 0.0026 | 113.10 |
| prior | 0.0026 | 116.65 |
| prior | 0.0026 | 120.20 |
| prior | 0.0026 | 123.75 |
| prior | 0.0026 | 127.29 |
| prior | 0.0026 | 130.84 |
| prior | 0.0026 | 134.39 |
| prior | 0.0027 | 137.94 |
| prior | 0.0027 | 141.49 |
| prior | 0.0027 | 145.03 |
| prior | 0.0027 | 148.58 |
| prior | 0.0027 | 152.13 |
| prior | 0.0028 | 155.68 |
| prior | 0.0028 | 159.23 |
| prior | 0.0028 | 162.77 |
| prior | 0.0028 | 166.32 |
| prior | 0.0028 | 169.87 |
| prior | 0.0028 | 173.42 |
First 60 of 300 rows.
View data
| Bin end | mean of sales | Simulations |
|---|---|---|
| 811.59 | 805.26 | 1 |
| 817.91 | 811.59 | 0 |
| 824.23 | 817.91 | 0 |
| 830.55 | 824.23 | 0 |
| 836.87 | 830.55 | 1 |
| 843.19 | 836.87 | 0 |
| 849.52 | 843.19 | 0 |
| 855.84 | 849.52 | 0 |
| 862.16 | 855.84 | 2 |
| 868.48 | 862.16 | 0 |
| 874.80 | 868.48 | 5 |
| 881.12 | 874.80 | 0 |
| 887.45 | 881.12 | 0 |
| 893.77 | 887.45 | 1 |
| 900.09 | 893.77 | 2 |
| 906.41 | 900.09 | 1 |
| 912.73 | 906.41 | 4 |
| 919.05 | 912.73 | 4 |
| 925.38 | 919.05 | 4 |
| 931.70 | 925.38 | 1 |
| 938.02 | 931.70 | 2 |
| 944.34 | 938.02 | 4 |
| 950.66 | 944.34 | 4 |
| 956.98 | 950.66 | 1 |
| 963.31 | 956.98 | 4 |
| 969.63 | 963.31 | 5 |
| 975.95 | 969.63 | 5 |
| 982.27 | 975.95 | 2 |
| 988.59 | 982.27 | 4 |
| 994.92 | 988.59 | 3 |
View data
| Bin end | SD of sales | Simulations |
|---|---|---|
| 26.325 | 20.160 | 2 |
| 32.489 | 26.325 | 1 |
| 38.654 | 32.489 | 1 |
| 44.818 | 38.654 | 1 |
| 50.982 | 44.818 | 3 |
| 57.147 | 50.982 | 2 |
| 63.311 | 57.147 | 0 |
| 69.476 | 63.311 | 1 |
| 75.640 | 69.476 | 4 |
| 81.804 | 75.640 | 1 |
| 87.969 | 81.804 | 4 |
| 94.133 | 87.969 | 6 |
| 100.30 | 94.133 | 5 |
| 106.46 | 100.30 | 5 |
| 112.63 | 106.46 | 0 |
| 118.79 | 112.63 | 4 |
| 124.96 | 118.79 | 4 |
| 131.12 | 124.96 | 1 |
| 137.28 | 131.12 | 4 |
| 143.45 | 137.28 | 1 |
| 149.61 | 143.45 | 2 |
| 155.78 | 149.61 | 1 |
| 161.94 | 155.78 | 1 |
| 168.11 | 161.94 | 0 |
| 174.27 | 168.11 | 1 |
| 180.44 | 174.27 | 2 |
| 186.60 | 180.44 | 0 |
| 192.76 | 186.60 | 0 |
| 198.93 | 192.76 | 2 |
| 205.09 | 198.93 | 1 |
View data
| series | generation | tolerance |
|---|---|---|
| tolerance | 0 | 3.850 |
| tolerance | 1 | 1.064 |
| tolerance | 2 | 0.8565 |
| tolerance | 3 | 0.4887 |
Assumptions
- Priors — Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight.
- Reproduces the observed statistics — Simulations from the posterior bring back every observed statistic (smallest p = 0.80).
- Calibrated algorithm — Not checked: SMC-ABC has no cheap calibration check.
Calibrated inputs
| Input | Prior mean | Prior SD | Posterior mean | Posterior SD | 5% | Median | 95% | Shrinkage | Calibration p |
|---|---|---|---|---|---|---|---|---|---|
| base_demand | 1004.05 | 293.89 | 1124.27 | 150.58 | 921.17 | 1121.79 | 1393.56 | 73.7% | — |
| volatility | 231.93 | 104.80 | 258.08 | 93.235 | 102.62 | 278.88 | 381.54 | 20.8% | — |
Observed statistics and the posterior predictive check
| Statistic | Observed | Predicted mean | 5% | 95% | Predictive p | Distance scale |
|---|---|---|---|---|---|---|
| mean of sales | 930 | 933.67 | 860.61 | 988.27 | 0.8667 | 142.14 |
| SD of sales | 110 | 103.48 | 36.636 | 179.52 | 0.8000 | 116.60 |
SMC-ABC generations
| Generation | Tolerance | Simulations | Acceptance | Effective particles |
|---|---|---|---|---|
| 0 | 3.850 | 200 | 100.0% | 200.00 |
| 1 | 1.064 | 400 | 50.0% | 113.85 |
| 2 | 0.8565 | 600 | 33.3% | 139.49 |
| 3 | 0.4887 | 800 | 25.0% | 147.37 |
Posterior draws (200, equally weighted)
| Draw | base_demand | volatility |
|---|---|---|
| 1 | 1210.59 | 288.65 |
| 2 | 1419.42 | 366.79 |
| 3 | 1352.55 | 344.34 |
| 4 | 1058.10 | 227.95 |
| 5 | 921.17 | 112.47 |
| 6 | 921.17 | 112.47 |
| 7 | 978.90 | 110.04 |
| 8 | 948.93 | 56.827 |
| 9 | 999.85 | 208.32 |
| 10 | 999.85 | 208.32 |
| 11 | 1072.34 | 239.14 |
| 12 | 1072.34 | 239.14 |
| 13 | 1207.96 | 381.49 |
| 14 | 937.71 | 217.47 |
| 15 | 937.71 | 217.47 |
| 16 | 968.31 | 79.782 |
| 17 | 915.20 | 162.34 |
| 18 | 915.20 | 162.34 |
| 19 | 1325.17 | 285.38 |
| 20 | 1189.71 | 374.76 |
| 21 | 1238.48 | 301.09 |
| 22 | 1238.48 | 301.09 |
| 23 | 1083.81 | 225.28 |
| 24 | 1138.70 | 360.43 |
| 25 | 1359.43 | 353.48 |
| 26 | 1324.00 | 299.67 |
| 27 | 1455.22 | 358.29 |
| 28 | 1302.89 | 361.52 |
| 29 | 1189.83 | 381.54 |
| 30 | 1148.55 | 281.04 |
| 31 | 1148.55 | 281.04 |
| 32 | 1013.93 | 109.87 |
| 33 | 986.31 | 102.62 |
| 34 | 986.31 | 102.62 |
| 35 | 993.27 | 264.50 |
| 36 | 993.27 | 264.50 |
| 37 | 934.17 | 217.15 |
| 38 | 934.17 | 217.15 |
| 39 | 968.75 | 200.75 |
| 40 | 1231.31 | 272.77 |
First 40 of 200 rows.
- The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation).
- SMC-ABC ran 3 generation(s) after the prior one (stop: generations); each tolerance is the 0.5 quantile of the previous distances, particles move by a Gaussian kernel with twice the weighted covariance, and weights are prior over the kernel mixture (Beaumont et al. 2009).
- The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.
The exact R script · R R version 4.5.1 (2025-06-13)
# Calibrate a scenario model to observed statistics (ABC, SMC-ABC, neural posterior)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method simulate.calibrate 1.1.0 · spec 2fa5316c6a422130
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Model, inputs to calibrate and observed statistics
ALGORITHM <- "smc"
REPLICATES <- as.integer(30)
SEED <- as.integer(3)
COVERAGE <- TRUE && ALGORITHM %in% c("rejection", "npe")
COVERAGE_N <- as.integer(100)
PRED_DRAWS <- as.integer(60)
warnings <- list()
ctx <- tryCatch(cs_calib_setup("{\"inputs\":[{\"name\":\"base_demand\",\"dist\":\"uniform\",\"params\":{\"min\":500,\"max\":1500}},{\"name\":\"volatility\",\"dist\":\"uniform\",\"params\":{\"min\":50,\"max\":400}},{\"name\":\"shock\",\"dist\":\"normal\",\"params\":{\"mean\":0,\"sd\":1}}],\"decisions\":[{\"name\":\"order\",\"value\":1000,\"min\":0,\"max\":3000}],\"formulas\":[{\"name\":\"demand\",\"expr\":\"max(base_demand + volatility * shock, 0)\"},{\"name\":\"sales\",\"expr\":\"min(demand, order)\"}],\"kpis\":[{\"name\":\"sales\",\"label\":\"Sales\"}],\"correlations\":[]}", "base_demand, volatility", "[{\"name\":\"sales\",\"stat\":\"mean\",\"value\":930},{\"name\":\"sales\",\"stat\":\"sd\",\"value\":110}]", REPLICATES),
error = function(e) cs_error("CS_E_INVALID_OPTION", option = "Calibration setup", allowed = "a valid model, inputs to calibrate and observed statistics",
value = conditionMessage(e)))
params <- ctx$params
targets <- ctx$targets
K <- length(params)
J <- length(targets)
# %% Posterior
# Every algorithm works on normal scores z = qnorm(F(theta)), where any prior is a standard normal, and maps back
# through each input's quantile function (Monte Carlo's twin), so bounds and clipping hold.
values <- list(algorithm = ALGORITHM, n_params = K, n_targets = J, replicates = REPLICATES)
for (key in c("n_accepted", "epsilon", "adjusted", "generations", "stop_reason", "acceptance_rate", "epochs_run", "valid_loss", "coverage_p_min")) values[key] <- list(NULL)
ranks <- NULL
gens <- list()
history <- list()
res <- tryCatch({
if (ALGORITHM == "rejection") {
S <- as.integer(10000)
r <- cs_calib_rejection(ctx, S, 0.01, FALSE, SEED)
r$S <- S
r
} else if (ALGORITHM == "smc") {
cs_calib_smc(ctx, as.integer(200), as.integer(3), 0.5, as.integer(100000), 0.02, SEED)
} else {
cs_calib_npe(ctx, as.integer(2000), as.integer(4), as.integer(32), as.integer(300),
0.005, as.integer(4000), SEED, if (COVERAGE) COVERAGE_N else 0)
}
}, error = function(e) cs_error("CS_E_UNDEFINED", what = "The calibration", reason = conditionMessage(e)))
if (ALGORITHM == "rejection") {
S <- res$S
k_acc <- length(res$accepted)
values$n_simulations <- S
values$n_accepted <- k_acc
values$epsilon <- res$epsilon
values$adjusted <- as.integer(res$adjusted)
values$acceptance_rate <- k_acc / S
if (!is.null(res$note)) warnings[[length(warnings) + 1]] <- res$note
if (res$n_finite < S) warnings[[length(warnings) + 1]] <- sprintf("%s of %s simulations gave no number for some statistic (division by zero or an invalid function argument) and were never kept.",
formatC(S - res$n_finite, big.mark = ",", format = "d"), formatC(S, big.mark = ",", format = "d"))
if (COVERAGE) ranks <- cs_calib_coverage_rejection(ctx, res, COVERAGE_N)
} else if (ALGORITHM == "smc") {
gens <- res$generations
values$n_simulations <- res$n_sims
values$n_accepted <- as.integer(200)
values$epsilon <- res$epsilon
values$generations <- length(gens) - 1L
values$stop_reason <- res$stop
values$acceptance_rate <- gens[[length(gens)]]$rate
if (res$stop == "budget") warnings[[length(warnings) + 1]] <- sprintf("The simulation budget ran out during generation %d; the posterior is generation %d's.", length(gens), length(gens) - 1L)
} else {
history <- res$history
values$n_simulations <- res$n_sims
values$epochs_run <- res$epochs_run
values$valid_loss <- res$valid_loss
ranks <- res$ranks
}
post <- res$post_theta
w <- res$weights / sum(res$weights)
prior <- res$prior_theta
values$ess <- 1 / sum(w * w)
prior_w <- rep(1 / nrow(prior), nrow(prior))
post_rows <- list()
cov_p <- list()
if (!is.null(ranks) && nrow(ranks)) {
for (k in seq_along(params)) cov_p[[params[k]]] <- cs_calib_rank_test(ranks[, k], 100)$p
values$coverage_p_min <- min(unlist(cov_p))
}
for (k in seq_along(params)) {
nm <- params[k]
ps <- cs_calib_summarize(post[, k], w)
pr <- cs_calib_summarize(prior[, k], prior_w)
shrink <- if (pr$sd > 0) 1 - (ps$sd / pr$sd)^2 else NULL
values[sprintf("post_mean[%s]", nm)] <- list(ps$mean)
values[sprintf("post_sd[%s]", nm)] <- list(ps$sd)
values[sprintf("post_lo[%s]", nm)] <- list(ps$lo)
values[sprintf("post_median[%s]", nm)] <- list(ps$median)
values[sprintf("post_hi[%s]", nm)] <- list(ps$hi)
values[sprintf("prior_mean[%s]", nm)] <- list(pr$mean)
values[sprintf("prior_sd[%s]", nm)] <- list(pr$sd)
values[sprintf("shrinkage[%s]", nm)] <- list(shrink)
if (!is.null(cov_p[[nm]])) values[sprintf("coverage_p[%s]", nm)] <- list(cov_p[[nm]])
post_rows[[k]] <- list(input = nm, prior_mean = pr$mean, prior_sd = pr$sd, mean = ps$mean, sd = ps$sd, lo = ps$lo,
median = ps$median, hi = ps$hi, shrinkage = shrink, coverage_p = cov_p[[nm]])
}
values$primary <- params[1]
values$primary_mean <- values[[sprintf("post_mean[%s]", params[1])]]
values$primary_lo <- values[[sprintf("post_lo[%s]", params[1])]]
values$primary_hi <- values[[sprintf("post_hi[%s]", params[1])]]
# %% Posterior predictive check: fresh simulations at posterior draws
pred <- cs_calib_predictive(ctx, post, w, PRED_DRAWS, SEED + 17)
target_rows <- list()
ppc_ps <- list()
for (j in seq_along(targets)) {
t <- targets[[j]]
x <- pred[is.finite(pred[, j]), j]
lab <- t$key
obs <- t$value
values[sprintf("observed[%s]", lab)] <- list(obs)
if (ALGORITHM != "npe") values[sprintf("scale[%s]", lab)] <- list(res$scale[j])
if (length(x)) {
m_ <- sum(x) / length(x)
lo_ <- cs_calib_quantile7(x, 0.05)
hi_ <- cs_calib_quantile7(x, 0.95)
p_ <- min(1, 2 * min(sum(x >= obs) / length(x), sum(x <= obs) / length(x)))
ppc_ps[[t$label]] <- p_
} else {
m_ <- NULL; lo_ <- NULL; hi_ <- NULL; p_ <- NULL
}
values[sprintf("ppc_mean[%s]", lab)] <- list(m_)
values[sprintf("ppc_lo[%s]", lab)] <- list(lo_)
values[sprintf("ppc_hi[%s]", lab)] <- list(hi_)
values[sprintf("ppc_p[%s]", lab)] <- list(p_)
target_rows[[j]] <- list(statistic = t$label, observed = obs, ppc_mean = m_, ppc_lo = lo_, ppc_hi = hi_, ppc_p = p_,
scale = if (ALGORITHM != "npe") res$scale[j] else NULL)
}
# %% Assumptions
assumptions <- list(list(key = "priors", label = "Priors", status = "info",
detail = "Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight."))
bad <- names(ppc_ps)[unlist(ppc_ps) < 0.05]
if (length(ppc_ps) < J) {
assumptions[[2]] <- list(key = "reproduces_targets", label = "Reproduces the observed statistics", status = "warn",
detail = "Some statistics gave no number in the posterior predictive simulations.")
} else if (length(bad)) {
assumptions[[2]] <- list(key = "reproduces_targets", label = "Reproduces the observed statistics", status = "warn",
detail = paste0("Posterior simulations rarely bring back ", paste(bad, collapse = ", "),
" (p < 0.05): the model may be unable to produce what was observed, or the targets conflict."))
} else {
assumptions[[2]] <- list(key = "reproduces_targets", label = "Reproduces the observed statistics", status = "pass",
detail = sprintf("Simulations from the posterior bring back every observed statistic (smallest p = %.2f).", min(unlist(ppc_ps))))
}
if (length(cov_p)) {
cp <- unlist(cov_p)
worst <- names(cp)[which.min(cp)]
if (cp[[worst]] >= 0.01) {
assumptions[[3]] <- list(key = "calibrated", label = "Calibrated algorithm", status = "pass",
detail = sprintf("On %d simulated data sets the true values spread evenly across the posteriors (smallest rank-test p = %.2f, %s).", nrow(ranks), cp[[worst]], worst))
} else {
assumptions[[3]] <- list(key = "calibrated", label = "Calibrated algorithm", status = "warn",
detail = paste0(sprintf("On %d simulated data sets the true values of %s fall unevenly across the posteriors (rank-test p = %.3f): ", nrow(ranks), worst, cp[[worst]]),
"intervals may be too narrow or shifted; keep fewer simulations, add some, or train longer."))
}
} else {
assumptions[[3]] <- list(key = "calibrated", label = "Calibrated algorithm", status = "info",
detail = paste0("Not checked: ", if (ALGORITHM == "smc") "SMC-ABC has no cheap calibration check." else "the calibration check is off."))
}
# %% Charts
charts <- list()
for (k in seq_len(min(K, 6))) {
nm <- params[k]
h <- cs_pf_bandwidth(post[, k], w)
q <- cs_pf_weighted_quantiles(prior[, k], prior_w, c(0.01, 0.99))
lo_g <- min(q[1], min(post[, k]) - 3 * h)
hi_g <- max(q[2], max(post[, k]) + 3 * h)
grid <- seq(lo_g, hi_g, length.out = 150)
charts[[length(charts) + 1]] <- cs_chart(paste0("posterior_", nm), "prior-posterior", sprintf("%s: prior and posterior", nm), list(
x = cs_col(nm, c(grid, grid)),
density = cs_col("density", c(cs_pf_kde(prior[, k], grid, prior_w), cs_pf_kde(post[, k], grid, w))),
curve = cs_col("curve", c(rep("prior", length(grid)), rep("posterior", length(grid))), kind = "categorical")))
}
for (j in seq_along(targets)) {
t <- targets[[j]]
hst <- cs_sim_histogram(pred[, j], 30)
charts[[length(charts) + 1]] <- cs_chart(sprintf("ppc_%d", j), "mc-distribution", sprintf("Posterior predictive: %s (observed %s)", t$label, sprintf("%.4g", t$value)), list(
bin_low = cs_col(t$label, hst$bin_low), bin_high = cs_col("Bin end", hst$bin_high), count = cs_col("Simulations", hst$count)),
controls = list(percentiles = c(5, 50, 95), target = t$value))
}
if (length(gens)) {
charts[[length(charts) + 1]] <- cs_chart("tolerance", "series-line", "SMC-ABC tolerance by generation", list(
x = cs_col("generation", as.numeric(vapply(gens, function(g) g$generation, numeric(1)))),
y = cs_col("tolerance", vapply(gens, function(g) g$epsilon, numeric(1))),
group = cs_col("series", rep("tolerance", length(gens)), kind = "categorical")))
}
if (!is.null(ranks) && nrow(ranks)) {
charts[[length(charts) + 1]] <- cs_chart("coverage", "pit-histogram", "Calibration check: where the true values fell in their posteriors (all inputs)", list(
share = cs_col("share", cs_calib_rank_test(ranks, 100)$shares)))
}
if (length(history)) {
ep <- as.numeric(vapply(history, function(h_) h_$epoch, numeric(1)))
charts[[length(charts) + 1]] <- cs_chart("training", "series-line", "Network training: loss on training and held-out simulations", list(
x = cs_col("epoch", c(ep, ep)),
y = cs_col("negative log-likelihood", c(vapply(history, function(h_) h_$loss, numeric(1)), vapply(history, function(h_) h_$valid_loss, numeric(1)))),
group = cs_col("set", c(rep("training", length(ep)), rep("held out", length(ep))), kind = "categorical")))
}
# %% Tables
tables <- list(
list(key = "posterior", title = "Calibrated inputs",
columns = list(list(key = "input", label = "Input", type = "string"), list(key = "prior_mean", label = "Prior mean", type = "number"),
list(key = "prior_sd", label = "Prior SD", type = "number"), list(key = "mean", label = "Posterior mean", type = "number"),
list(key = "sd", label = "Posterior SD", type = "number"), list(key = "lo", label = "5%", type = "number"),
list(key = "median", label = "Median", type = "number"), list(key = "hi", label = "95%", type = "number"),
list(key = "shrinkage", label = "Shrinkage", type = "percent"), list(key = "coverage_p", label = "Calibration p", type = "number")),
rows = post_rows),
list(key = "targets", title = "Observed statistics and the posterior predictive check",
columns = list(list(key = "statistic", label = "Statistic", type = "string"), list(key = "observed", label = "Observed", type = "number"),
list(key = "ppc_mean", label = "Predicted mean", type = "number"), list(key = "ppc_lo", label = "5%", type = "number"),
list(key = "ppc_hi", label = "95%", type = "number"), list(key = "ppc_p", label = "Predictive p", type = "number"),
list(key = "scale", label = "Distance scale", type = "number")),
rows = target_rows))
if (length(gens)) {
tables[[length(tables) + 1]] <- list(key = "generations", title = "SMC-ABC generations",
columns = list(list(key = "generation", label = "Generation", type = "integer"), list(key = "epsilon", label = "Tolerance", type = "number"),
list(key = "sims", label = "Simulations", type = "integer"), list(key = "rate", label = "Acceptance", type = "percent"),
list(key = "ess", label = "Effective particles", type = "number")),
rows = lapply(gens, function(g) list(generation = g$generation, epsilon = g$epsilon, sims = g$sims, rate = g$rate, ess = g$ess)))
}
n_show <- min(500L, nrow(post))
idx <- cs_calib_resample(nrow(post), w, n_show, cs_runif(cs_rng(SEED + 19), 1))
sample_cols <- c(list(list(key = "draw", label = "Draw", type = "integer")), lapply(seq_along(params), function(k) list(key = sprintf("p%d", k), label = params[k], type = "number")))
tables[[length(tables) + 1]] <- list(key = "sample", title = sprintf("Posterior draws (%d, equally weighted)", n_show), columns = sample_cols,
rows = lapply(seq_len(n_show), function(i) c(list(draw = i), stats::setNames(as.list(post[idx[i], ]), sprintf("p%d", seq_len(K))))))
# %% Posterior draws
artifacts <- list()
if (TRUE) {
out <- cs_ml_out_dir("target/academy-parity/run-8142/simulate.calibrate/censored-sales-smc/out-r")
path <- file.path(out, "posterior.parquet")
dfp <- as.data.frame(c(list(draw = seq_len(nrow(post))), stats::setNames(lapply(seq_len(K), function(k) post[, k]), params), list(weight = w)), check.names = FALSE)
nanoparquet::write_parquet(dfp, path)
artifacts <- list(list(key = "posterior", path = path, format = "parquet", title = "Posterior draws"))
}
# %% Result
g4 <- function(v) sprintf("%.4g", v)
ALG <- c(rejection = "rejection ABC", smc = "SMC-ABC", npe = "neural posterior estimation")[[ALGORITHM]]
values$algorithm <- ALG
desc <- paste(vapply(params, function(nm) sprintf("%s %s (90%% %s to %s)", nm, g4(values[[sprintf("post_mean[%s]", nm)]]),
g4(values[[sprintf("post_lo[%s]", nm)]]), g4(values[[sprintf("post_hi[%s]", nm)]])), ""), collapse = "; ")
summary <- sprintf("Calibrated %d input(s) to %d observed statistic(s) by %s (%s simulations of %d scenario(s) each): %s.",
K, J, ALG, formatC(values$n_simulations, big.mark = ",", format = "d"), REPLICATES, desc)
notes <- c(paste0("The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. ",
"Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation)."))
if (ALGORITHM == "rejection") {
notes <- c(notes, paste0(sprintf("Rejection ABC kept the %s simulations closest to the observed statistics (tolerance %s)", formatC(values$n_accepted, big.mark = ",", format = "d"), g4(res$epsilon)),
if (res$adjusted) ", then shifted them by a weighted local-linear regression on the statistics (Beaumont et al. 2002)." else "."))
} else if (ALGORITHM == "smc") {
notes <- c(notes, paste0(sprintf("SMC-ABC ran %d generation(s) after the prior one (stop: %s); each tolerance is the 0.5 quantile of the previous distances, ", length(gens) - 1L, res$stop),
"particles move by a Gaussian kernel with twice the weighted covariance, and weights are prior over the kernel mixture (Beaumont et al. 2009)."))
} else {
notes <- c(notes, sprintf("A mixture density network (4 components, two tanh layers of 32) learned the posterior from prior simulations; training stopped at epoch %d (best held-out epoch %d).",
res$epochs_run, res$best_epoch))
}
notes <- c(notes, "The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.")
statistics <- lapply(params, function(nm) list(key = sprintf("post_mean[%s]", nm), label = sprintf("%s (posterior mean)", nm), value = values[[sprintf("post_mean[%s]", nm)]]))
cs_publish(list(
method = "simulate.calibrate",
methodVersion = "1.1.0",
title = "Scenario calibration",
engine = if (ALGORITHM != "npe") cs_engine_info("jsonlite", "nanoparquet") else cs_engine_info("jsonlite", "nanoparquet", "torch"),
n = values$n_simulations,
summary = summary,
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values,
artifacts = artifacts
))
Calibrated 2 input(s) to 2 observed statistic(s) by SMC-ABC (2,000 simulations of 30 scenario(s) each): base_demand 1124 (90% 921.2 to 1394); volatility 258.1 (90% 102.6 to 381.5).
- base_demand (posterior mean)
- 1124.27
- volatility (posterior mean)
- 258.08
Assumptions
- Priors — Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight.
- Reproduces the observed statistics — Simulations from the posterior bring back every observed statistic (smallest p = 0.80).
- Calibrated algorithm — Not checked: SMC-ABC has no cheap calibration check.
Calibrated inputs
| Input | Prior mean | Prior SD | Posterior mean | Posterior SD | 5% | Median | 95% | Shrinkage | Calibration p |
|---|---|---|---|---|---|---|---|---|---|
| base_demand | 1004.05 | 293.89 | 1124.27 | 150.58 | 921.17 | 1121.79 | 1393.56 | 73.7% | — |
| volatility | 231.93 | 104.80 | 258.08 | 93.235 | 102.62 | 278.88 | 381.54 | 20.8% | — |
Observed statistics and the posterior predictive check
| Statistic | Observed | Predicted mean | 5% | 95% | Predictive p | Distance scale |
|---|---|---|---|---|---|---|
| mean of sales | 930 | 933.67 | 860.61 | 988.27 | 0.8667 | 142.14 |
| SD of sales | 110 | 103.48 | 36.636 | 179.52 | 0.8000 | 116.60 |
SMC-ABC generations
| Generation | Tolerance | Simulations | Acceptance | Effective particles |
|---|---|---|---|---|
| 0 | 3.850 | 200 | 100.0% | 200.00 |
| 1 | 1.064 | 400 | 50.0% | 113.85 |
| 2 | 0.8565 | 600 | 33.3% | 139.49 |
| 3 | 0.4887 | 800 | 25.0% | 147.37 |
Posterior draws (200, equally weighted)
| Draw | base_demand | volatility |
|---|---|---|
| 1 | 1210.59 | 288.65 |
| 2 | 1419.42 | 366.79 |
| 3 | 1352.55 | 344.34 |
| 4 | 1058.10 | 227.95 |
| 5 | 921.17 | 112.47 |
| 6 | 921.17 | 112.47 |
| 7 | 978.90 | 110.04 |
| 8 | 948.93 | 56.827 |
| 9 | 999.85 | 208.32 |
| 10 | 999.85 | 208.32 |
| 11 | 1072.34 | 239.14 |
| 12 | 1072.34 | 239.14 |
| 13 | 1207.96 | 381.49 |
| 14 | 937.71 | 217.47 |
| 15 | 937.71 | 217.47 |
| 16 | 968.31 | 79.782 |
| 17 | 915.20 | 162.34 |
| 18 | 915.20 | 162.34 |
| 19 | 1325.17 | 285.38 |
| 20 | 1189.71 | 374.76 |
| 21 | 1238.48 | 301.09 |
| 22 | 1238.48 | 301.09 |
| 23 | 1083.81 | 225.28 |
| 24 | 1138.70 | 360.43 |
| 25 | 1359.43 | 353.48 |
| 26 | 1324.00 | 299.67 |
| 27 | 1455.22 | 358.29 |
| 28 | 1302.89 | 361.52 |
| 29 | 1189.83 | 381.54 |
| 30 | 1148.55 | 281.04 |
| 31 | 1148.55 | 281.04 |
| 32 | 1013.93 | 109.87 |
| 33 | 986.31 | 102.62 |
| 34 | 986.31 | 102.62 |
| 35 | 993.27 | 264.50 |
| 36 | 993.27 | 264.50 |
| 37 | 934.17 | 217.15 |
| 38 | 934.17 | 217.15 |
| 39 | 968.75 | 200.75 |
| 40 | 1231.31 | 272.77 |
First 40 of 200 rows.
- The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation).
- SMC-ABC ran 3 generation(s) after the prior one (stop: generations); each tolerance is the 0.5 quantile of the previous distances, particles move by a Gaussian kernel with twice the weighted covariance, and weights are prior over the kernel mixture (Beaumont et al. 2009).
- The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Calibrate a scenario model to observed statistics (ABC, SMC-ABC, neural posterior)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method simulate.calibrate 1.1.0 · spec 2fa5316c6a422130
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.sim import calibrate as cb # ABC, SMC-ABC and NPE on the scenario-model twins (twin of codesplashr cs_calib_*)
from codesplash.sim import mc
from codesplash.stats import particle as pf # weighted quantiles and kernel densities
from codesplash.stats.rng import Rng
# %% Model, inputs to calibrate and observed statistics
ALGORITHM = "smc"
REPLICATES = int(30)
SEED = int(3)
COVERAGE = True and ALGORITHM in ("rejection", "npe")
COVERAGE_N = int(100)
PRED_DRAWS = int(60)
warnings = []
try:
ctx = cb.setup("{\"inputs\":[{\"name\":\"base_demand\",\"dist\":\"uniform\",\"params\":{\"min\":500,\"max\":1500}},{\"name\":\"volatility\",\"dist\":\"uniform\",\"params\":{\"min\":50,\"max\":400}},{\"name\":\"shock\",\"dist\":\"normal\",\"params\":{\"mean\":0,\"sd\":1}}],\"decisions\":[{\"name\":\"order\",\"value\":1000,\"min\":0,\"max\":3000}],\"formulas\":[{\"name\":\"demand\",\"expr\":\"max(base_demand + volatility * shock, 0)\"},{\"name\":\"sales\",\"expr\":\"min(demand, order)\"}],\"kpis\":[{\"name\":\"sales\",\"label\":\"Sales\"}],\"correlations\":[]}", "base_demand, volatility", "[{\"name\":\"sales\",\"stat\":\"mean\",\"value\":930},{\"name\":\"sales\",\"stat\":\"sd\",\"value\":110}]", REPLICATES)
except ValueError as e:
cs.cs_error("CS_E_INVALID_OPTION", option="Calibration setup", allowed="a valid model, inputs to calibrate and observed statistics", value=str(e))
params = ctx["params"]
targets = ctx["targets"]
K, J = len(params), len(targets)
# %% Posterior
# Every algorithm works on normal scores z = Φ⁻¹(F(θ)), where any prior is a standard normal, and maps back
# through each input's quantile function (Monte Carlo's twin), so bounds and clipping hold.
values = {"algorithm": ALGORITHM, "n_params": K, "n_targets": J, "replicates": REPLICATES}
for key in ("n_accepted", "epsilon", "adjusted", "generations", "stop_reason", "acceptance_rate", "epochs_run", "valid_loss", "coverage_p_min"):
values[key] = None
ranks = None
gens = []
history = []
try:
if ALGORITHM == "rejection":
S = int(10000)
res = cb.rejection(ctx, S, 0.01, False, SEED)
k_acc = len(res["accepted"])
values.update({"n_simulations": S, "n_accepted": k_acc, "epsilon": res["epsilon"], "adjusted": int(res["adjusted"]), "acceptance_rate": k_acc / S})
if res["note"]:
warnings.append(res["note"])
if res["n_finite"] < S:
warnings.append(f"{S - res['n_finite']:,} of {S:,} simulations gave no number for some statistic (division by zero or an invalid function argument) and were never kept.")
if COVERAGE:
ranks = cb.coverage_rejection(ctx, res, COVERAGE_N)
elif ALGORITHM == "smc":
res = cb.smc(ctx, int(200), int(3), 0.5, int(100000), 0.02, SEED)
gens = res["generations"]
values.update({"n_simulations": res["n_sims"], "n_accepted": int(200), "epsilon": res["epsilon"], "generations": len(gens) - 1,
"stop_reason": res["stop"], "acceptance_rate": gens[-1]["rate"]})
if res["stop"] == "budget":
warnings.append(f"The simulation budget ran out during generation {len(gens)}; the posterior is generation {len(gens) - 1}'s.")
else:
res = cb.npe(ctx, int(2000), int(4), int(32), int(300),
0.005, int(4000), SEED, COVERAGE_N if COVERAGE else 0)
history = res["history"]
values.update({"n_simulations": res["n_sims"], "epochs_run": res["epochs_run"], "valid_loss": res["valid_loss"]})
ranks = res["ranks"]
except ValueError as e:
cs.cs_error("CS_E_UNDEFINED", what="The calibration", reason=str(e))
post, w, prior = res["post_theta"], res["weights"], res["prior_theta"]
w = w / float(np.sum(w))
values["ess"] = 1.0 / float(np.sum(w * w))
prior_w = np.full(prior.shape[0], 1.0 / prior.shape[0])
post_rows = []
cov_p = {}
if ranks is not None and len(ranks):
for k, nm in enumerate(params):
cov_p[nm] = cb.rank_test(ranks[:, k], 100.0)[2]
values["coverage_p_min"] = float(min(cov_p.values()))
for k, nm in enumerate(params):
ps = cb.summarize(post[:, k], w)
pr = cb.summarize(prior[:, k], prior_w)
shrink = 1.0 - (ps["sd"] / pr["sd"]) ** 2 if pr["sd"] > 0 else None
values[f"post_mean[{nm}]"], values[f"post_sd[{nm}]"] = ps["mean"], ps["sd"]
values[f"post_lo[{nm}]"], values[f"post_median[{nm}]"], values[f"post_hi[{nm}]"] = ps["lo"], ps["median"], ps["hi"]
values[f"prior_mean[{nm}]"], values[f"prior_sd[{nm}]"], values[f"shrinkage[{nm}]"] = pr["mean"], pr["sd"], shrink
if nm in cov_p:
values[f"coverage_p[{nm}]"] = cov_p[nm]
post_rows.append({"input": nm, "prior_mean": pr["mean"], "prior_sd": pr["sd"], "mean": ps["mean"], "sd": ps["sd"], "lo": ps["lo"],
"median": ps["median"], "hi": ps["hi"], "shrinkage": shrink, "coverage_p": cov_p.get(nm)})
values.update({"primary": params[0], "primary_mean": values[f"post_mean[{params[0]}]"], "primary_lo": values[f"post_lo[{params[0]}]"],
"primary_hi": values[f"post_hi[{params[0]}]"]})
# %% Posterior predictive check: fresh simulations at posterior draws
pred = cb.predictive(ctx, post, w, PRED_DRAWS, SEED + 17)
target_rows = []
ppc_ps = []
for j, t in enumerate(targets):
x = pred[np.isfinite(pred[:, j]), j]
lab = t["key"]
obs = t["value"]
values[f"observed[{lab}]"] = obs
if ALGORITHM != "npe":
values[f"scale[{lab}]"] = float(res["scale"][j])
if len(x):
m_ = float(np.sum(x)) / len(x)
lo_, hi_ = cb.quantile7(x, 0.05), cb.quantile7(x, 0.95)
p_ = min(1.0, 2.0 * min(float(np.sum(x >= obs)) / len(x), float(np.sum(x <= obs)) / len(x)))
else:
m_ = lo_ = hi_ = p_ = None
values[f"ppc_mean[{lab}]"], values[f"ppc_lo[{lab}]"], values[f"ppc_hi[{lab}]"], values[f"ppc_p[{lab}]"] = m_, lo_, hi_, p_
if p_ is not None:
ppc_ps.append((t["label"], p_))
target_rows.append({"statistic": t["label"], "observed": obs, "ppc_mean": m_, "ppc_lo": lo_, "ppc_hi": hi_, "ppc_p": p_,
"scale": float(res["scale"][j]) if ALGORITHM != "npe" else None})
# %% Assumptions
assumptions = [{"key": "priors", "label": "Priors", "status": "info",
"detail": "Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight."}]
bad = [lab for lab, p_ in ppc_ps if p_ < 0.05]
if len(ppc_ps) < J:
assumptions.append({"key": "reproduces_targets", "label": "Reproduces the observed statistics", "status": "warn",
"detail": "Some statistics gave no number in the posterior predictive simulations."})
elif bad:
assumptions.append({"key": "reproduces_targets", "label": "Reproduces the observed statistics", "status": "warn",
"detail": "Posterior simulations rarely bring back " + ", ".join(bad) + " (p < 0.05): the model may be unable to produce what was observed, or the targets conflict."})
else:
assumptions.append({"key": "reproduces_targets", "label": "Reproduces the observed statistics", "status": "pass",
"detail": f"Simulations from the posterior bring back every observed statistic (smallest p = {min(p_ for _, p_ in ppc_ps):.2f})."})
if cov_p:
worst = min(cov_p, key=lambda nm: cov_p[nm])
if cov_p[worst] >= 0.01:
assumptions.append({"key": "calibrated", "label": "Calibrated algorithm", "status": "pass",
"detail": f"On {len(ranks)} simulated data sets the true values spread evenly across the posteriors (smallest rank-test p = {cov_p[worst]:.2f}, {worst})."})
else:
assumptions.append({"key": "calibrated", "label": "Calibrated algorithm", "status": "warn",
"detail": f"On {len(ranks)} simulated data sets the true values of {worst} fall unevenly across the posteriors (rank-test p = {cov_p[worst]:.3f}): "
"intervals may be too narrow or shifted; keep fewer simulations, add some, or train longer."})
else:
assumptions.append({"key": "calibrated", "label": "Calibrated algorithm", "status": "info",
"detail": "Not checked: " + ("SMC-ABC has no cheap calibration check." if ALGORITHM == "smc" else "the calibration check is off.")})
# %% Charts
charts = []
for k, nm in enumerate(params[:6]):
pw = prior_w
h = pf.bandwidth(post[:, k], w)
q01, q99 = pf.weighted_quantiles(prior[:, k], pw, (0.01, 0.99))
lo_g = min(q01, float(np.min(post[:, k])) - 3.0 * h)
hi_g = max(q99, float(np.max(post[:, k])) + 3.0 * h)
grid = np.linspace(lo_g, hi_g, 150)
charts.append(cs.chart(f"posterior_{nm}", "prior-posterior", f"{nm}: prior and posterior", {
"x": cs.col(nm, np.concatenate([grid, grid])),
"density": cs.col("density", np.concatenate([pf.kde(prior[:, k], grid, pw), pf.kde(post[:, k], grid, w)])),
"curve": cs.col("curve", ["prior"] * len(grid) + ["posterior"] * len(grid), kind="categorical")}))
for j, t in enumerate(targets):
hst = mc.histogram(pred[:, j], 30)
charts.append(cs.chart(f"ppc_{j + 1}", "mc-distribution", f"Posterior predictive: {t['label']} (observed {t['value']:.4g})", {
"bin_low": cs.col(t["label"], hst["bin_low"]), "bin_high": cs.col("Bin end", hst["bin_high"]), "count": cs.col("Simulations", hst["count"])},
controls={"percentiles": [5, 50, 95], "target": float(t["value"])}))
if gens:
charts.append(cs.chart("tolerance", "series-line", "SMC-ABC tolerance by generation", {
"x": cs.col("generation", [float(g["generation"]) for g in gens]), "y": cs.col("tolerance", [g["epsilon"] for g in gens]),
"group": cs.col("series", ["tolerance"] * len(gens), kind="categorical")}))
if ranks is not None and len(ranks):
shares = cb.rank_test(ranks, 100.0)[0]
charts.append(cs.chart("coverage", "pit-histogram", "Calibration check: where the true values fell in their posteriors (all inputs)", {
"share": cs.col("share", shares)}))
if history:
ep = [float(h_["epoch"]) for h_ in history]
charts.append(cs.chart("training", "series-line", "Network training: loss on training and held-out simulations", {
"x": cs.col("epoch", ep + ep), "y": cs.col("negative log-likelihood", [h_["loss"] for h_ in history] + [h_["valid_loss"] for h_ in history]),
"group": cs.col("set", ["training"] * len(ep) + ["held out"] * len(ep), kind="categorical")}))
# %% Tables
tables = [{"key": "posterior", "title": "Calibrated inputs",
"columns": [{"key": "input", "label": "Input", "type": "string"}, {"key": "prior_mean", "label": "Prior mean", "type": "number"},
{"key": "prior_sd", "label": "Prior SD", "type": "number"}, {"key": "mean", "label": "Posterior mean", "type": "number"},
{"key": "sd", "label": "Posterior SD", "type": "number"}, {"key": "lo", "label": "5%", "type": "number"},
{"key": "median", "label": "Median", "type": "number"}, {"key": "hi", "label": "95%", "type": "number"},
{"key": "shrinkage", "label": "Shrinkage", "type": "percent"}, {"key": "coverage_p", "label": "Calibration p", "type": "number"}],
"rows": post_rows},
{"key": "targets", "title": "Observed statistics and the posterior predictive check",
"columns": [{"key": "statistic", "label": "Statistic", "type": "string"}, {"key": "observed", "label": "Observed", "type": "number"},
{"key": "ppc_mean", "label": "Predicted mean", "type": "number"}, {"key": "ppc_lo", "label": "5%", "type": "number"},
{"key": "ppc_hi", "label": "95%", "type": "number"}, {"key": "ppc_p", "label": "Predictive p", "type": "number"},
{"key": "scale", "label": "Distance scale", "type": "number"}],
"rows": target_rows}]
if gens:
tables.append({"key": "generations", "title": "SMC-ABC generations",
"columns": [{"key": "generation", "label": "Generation", "type": "integer"}, {"key": "epsilon", "label": "Tolerance", "type": "number"},
{"key": "sims", "label": "Simulations", "type": "integer"}, {"key": "rate", "label": "Acceptance", "type": "percent"},
{"key": "ess", "label": "Effective particles", "type": "number"}],
"rows": [{"generation": g["generation"], "epsilon": g["epsilon"], "sims": g["sims"], "rate": g["rate"], "ess": g["ess"]} for g in gens]})
n_show = min(500, post.shape[0])
idx = cb.resample(post.shape[0], w, n_show, float(Rng(SEED + 19).uniform(1)[0]))
tables.append({"key": "sample", "title": f"Posterior draws ({n_show}, equally weighted)",
"columns": [{"key": "draw", "label": "Draw", "type": "integer"}] + [{"key": f"p{k + 1}", "label": nm, "type": "number"} for k, nm in enumerate(params)],
"rows": [{"draw": i + 1, **{f"p{k + 1}": float(post[idx[i], k]) for k in range(K)}} for i in range(n_show)]})
# %% Posterior draws
artifacts = []
if True:
out = csml.out_dir("target/academy-parity/run-8142/simulate.calibrate/censored-sales-smc/out-python")
path = os.path.join(out, "posterior.parquet")
pd.DataFrame({"draw": np.arange(1, post.shape[0] + 1), **{nm: post[:, k] for k, nm in enumerate(params)}, "weight": w}).to_parquet(path, index=False)
artifacts.append({"key": "posterior", "path": path, "format": "parquet", "title": "Posterior draws"})
# %% Result
ALG = {"rejection": "rejection ABC", "smc": "SMC-ABC", "npe": "neural posterior estimation"}[ALGORITHM]
values["algorithm"] = ALG
desc = "; ".join(f"{nm} {values[f'post_mean[{nm}]']:.4g} (90% {values[f'post_lo[{nm}]']:.4g} to {values[f'post_hi[{nm}]']:.4g})" for nm in params)
summary = f"Calibrated {K} input(s) to {J} observed statistic(s) by {ALG} ({values['n_simulations']:,} simulations of {REPLICATES} scenario(s) each): {desc}."
notes = ["The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. "
"Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation)."]
if ALGORITHM == "rejection":
notes.append(f"Rejection ABC kept the {values['n_accepted']:,} simulations closest to the observed statistics (tolerance {res['epsilon']:.4g})"
+ (", then shifted them by a weighted local-linear regression on the statistics (Beaumont et al. 2002)." if res["adjusted"] else "."))
elif ALGORITHM == "smc":
notes.append(f"SMC-ABC ran {len(gens) - 1} generation(s) after the prior one (stop: {res['stop']}); each tolerance is the 0.5 quantile of the previous distances, "
"particles move by a Gaussian kernel with twice the weighted covariance, and weights are prior over the kernel mixture (Beaumont et al. 2009).")
else:
notes.append(f"A mixture density network (4 components, two tanh layers of 32) learned the posterior from prior simulations; "
f"training stopped at epoch {res['epochs_run']} (best held-out epoch {res['best_epoch']}).")
notes.append("The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.")
statistics = [{"key": f"post_mean[{nm}]", "label": f"{nm} (posterior mean)", "value": values[f"post_mean[{nm}]"]} for nm in params]
cs.publish({
"method": "simulate.calibrate",
"methodVersion": "1.1.0",
"title": "Scenario calibration",
"engine": cs.engine_info("numpy", "scipy", "pandas") if ALGORITHM != "npe" else cs.engine_info("numpy", "scipy", "pandas", "torch"),
"n": values["n_simulations"],
"summary": summary,
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
"artifacts": artifacts,
})
Shortened for the Academy: 5 chart(s) dropped to stay under 100 KB.
- Neural posterior estimationNeural posterior estimation (NPE)A neural network learns the posterior from simulated pairs of parameters and statistics, then reads it off at the observed data. trains a network on prior simulations to output the posterior for any statistics, then reads it off at the observed ones. It's quick once trained, and the calibration check tells you if training was enough.
Calibrated 2 input(s) to 2 observed statistic(s) by neural posterior estimation (600 simulations of 30 scenario(s) each): base_demand 1110 (90% 954.6 to 1406); volatility 242.2 (90% 118.1 to 379.1).
- base_demand (posterior mean)
- 1109.91
- volatility (posterior mean)
- 242.23
Assumptions
- Priors — Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight.
- Reproduces the observed statistics — Simulations from the posterior bring back every observed statistic (smallest p = 0.70).
- Calibrated algorithm — On 30 simulated data sets the true values spread evenly across the posteriors (smallest rank-test p = 0.15, volatility).
Calibrated inputs
| Input | Prior mean | Prior SD | Posterior mean | Posterior SD | 5% | Median | 95% | Shrinkage | Calibration p |
|---|---|---|---|---|---|---|---|---|---|
| base_demand | 1012.14 | 282.93 | 1109.91 | 137.37 | 954.64 | 1072.23 | 1406.10 | 76.4% | 0.6025 |
| volatility | 220.65 | 98.269 | 242.23 | 83.568 | 118.11 | 235.25 | 379.10 | 27.7% | 0.1481 |
Observed statistics and the posterior predictive check
| Statistic | Observed | Predicted mean | 5% | 95% | Predictive p | Distance scale |
|---|---|---|---|---|---|---|
| mean of sales | 930 | 939.70 | 860.95 | 994.60 | 0.7000 | — |
| SD of sales | 110 | 103.34 | 25.353 | 196.54 | 0.8667 | — |
Posterior draws (500, equally weighted)
| Draw | base_demand | volatility |
|---|---|---|
| 1 | 1050.11 | 123.47 |
| 2 | 1043.50 | 138.80 |
| 3 | 1279.16 | 357.57 |
| 4 | 1009.43 | 151.09 |
| 5 | 1254.07 | 357.72 |
| 6 | 1011.35 | 238.06 |
| 7 | 1052.26 | 131.95 |
| 8 | 1180.40 | 355.57 |
| 9 | 1084.96 | 333.08 |
| 10 | 1142.93 | 130.40 |
| 11 | 1027.84 | 176.95 |
| 12 | 1044.02 | 334.17 |
| 13 | 1326.19 | 396.47 |
| 14 | 1047.59 | 282.71 |
| 15 | 974.38 | 184.37 |
| 16 | 1078.05 | 252.42 |
| 17 | 1036.47 | 192.65 |
| 18 | 1037.36 | 92.367 |
| 19 | 1046.38 | 92.087 |
| 20 | 1071.62 | 227.32 |
| 21 | 1035.73 | 198.07 |
| 22 | 1135.51 | 145.82 |
| 23 | 1010.69 | 184.65 |
| 24 | 1078.16 | 350.52 |
| 25 | 1123.77 | 346.87 |
| 26 | 1047.06 | 302.54 |
| 27 | 1222.11 | 352.06 |
| 28 | 1061.32 | 155.17 |
| 29 | 1398.76 | 347.91 |
| 30 | 1092.70 | 196.06 |
| 31 | 1024.06 | 177.36 |
| 32 | 986.20 | 205.84 |
| 33 | 996.57 | 255.64 |
| 34 | 1153.01 | 308.00 |
| 35 | 979.33 | 147.99 |
| 36 | 1106.87 | 293.43 |
| 37 | 1047.77 | 345.19 |
| 38 | 1414.69 | 352.29 |
| 39 | 1027.37 | 118.14 |
| 40 | 1075.58 | 297.10 |
First 40 of 500 rows.
- The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation).
- A mixture density network (2 components, two tanh layers of 12) learned the posterior from prior simulations; training stopped at epoch 40 (best held-out epoch 40).
- The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.
The exact R script · R R version 4.5.1 (2025-06-13)
# Calibrate a scenario model to observed statistics (ABC, SMC-ABC, neural posterior)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method simulate.calibrate 1.1.0 · spec 82175d8e725ac640
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Model, inputs to calibrate and observed statistics
ALGORITHM <- "npe"
REPLICATES <- as.integer(30)
SEED <- as.integer(7)
COVERAGE <- TRUE && ALGORITHM %in% c("rejection", "npe")
COVERAGE_N <- as.integer(30)
PRED_DRAWS <- as.integer(60)
warnings <- list()
ctx <- tryCatch(cs_calib_setup("{\"inputs\":[{\"name\":\"base_demand\",\"dist\":\"uniform\",\"params\":{\"min\":500,\"max\":1500}},{\"name\":\"volatility\",\"dist\":\"uniform\",\"params\":{\"min\":50,\"max\":400}},{\"name\":\"shock\",\"dist\":\"normal\",\"params\":{\"mean\":0,\"sd\":1}}],\"decisions\":[{\"name\":\"order\",\"value\":1000,\"min\":0,\"max\":3000}],\"formulas\":[{\"name\":\"demand\",\"expr\":\"max(base_demand + volatility * shock, 0)\"},{\"name\":\"sales\",\"expr\":\"min(demand, order)\"}],\"kpis\":[{\"name\":\"sales\",\"label\":\"Sales\"}],\"correlations\":[]}", "base_demand, volatility", "[{\"name\":\"sales\",\"stat\":\"mean\",\"value\":930},{\"name\":\"sales\",\"stat\":\"sd\",\"value\":110}]", REPLICATES),
error = function(e) cs_error("CS_E_INVALID_OPTION", option = "Calibration setup", allowed = "a valid model, inputs to calibrate and observed statistics",
value = conditionMessage(e)))
params <- ctx$params
targets <- ctx$targets
K <- length(params)
J <- length(targets)
# The neural posterior's network trains on the shared trainer: training options, live progress and checkpoints.
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/simulate.calibrate/censored-sales-npe/out-r")
# %% Posterior
# Every algorithm works on normal scores z = qnorm(F(theta)), where any prior is a standard normal, and maps back
# through each input's quantile function (Monte Carlo's twin), so bounds and clipping hold.
values <- list(algorithm = ALGORITHM, n_params = K, n_targets = J, replicates = REPLICATES)
for (key in c("n_accepted", "epsilon", "adjusted", "generations", "stop_reason", "acceptance_rate", "epochs_run", "valid_loss", "coverage_p_min")) values[key] <- list(NULL)
ranks <- NULL
gens <- list()
history <- list()
res <- tryCatch({
if (ALGORITHM == "rejection") {
S <- as.integer(10000)
r <- cs_calib_rejection(ctx, S, 0.01, FALSE, SEED)
r$S <- S
r
} else if (ALGORITHM == "smc") {
cs_calib_smc(ctx, as.integer(500), as.integer(6), 0.5, as.integer(100000), 0.02, SEED)
} else {
cs_calib_npe(ctx, as.integer(600), as.integer(2), as.integer(12), as.integer(40),
0.01, as.integer(800), SEED, if (COVERAGE) COVERAGE_N else 0)
}
}, error = function(e) cs_error("CS_E_UNDEFINED", what = "The calibration", reason = conditionMessage(e)))
if (ALGORITHM == "rejection") {
S <- res$S
k_acc <- length(res$accepted)
values$n_simulations <- S
values$n_accepted <- k_acc
values$epsilon <- res$epsilon
values$adjusted <- as.integer(res$adjusted)
values$acceptance_rate <- k_acc / S
if (!is.null(res$note)) warnings[[length(warnings) + 1]] <- res$note
if (res$n_finite < S) warnings[[length(warnings) + 1]] <- sprintf("%s of %s simulations gave no number for some statistic (division by zero or an invalid function argument) and were never kept.",
formatC(S - res$n_finite, big.mark = ",", format = "d"), formatC(S, big.mark = ",", format = "d"))
if (COVERAGE) ranks <- cs_calib_coverage_rejection(ctx, res, COVERAGE_N)
} else if (ALGORITHM == "smc") {
gens <- res$generations
values$n_simulations <- res$n_sims
values$n_accepted <- as.integer(500)
values$epsilon <- res$epsilon
values$generations <- length(gens) - 1L
values$stop_reason <- res$stop
values$acceptance_rate <- gens[[length(gens)]]$rate
if (res$stop == "budget") warnings[[length(warnings) + 1]] <- sprintf("The simulation budget ran out during generation %d; the posterior is generation %d's.", length(gens), length(gens) - 1L)
} else {
history <- res$history
values$n_simulations <- res$n_sims
values$epochs_run <- res$epochs_run
values$valid_loss <- res$valid_loss
ranks <- res$ranks
}
post <- res$post_theta
w <- res$weights / sum(res$weights)
prior <- res$prior_theta
values$ess <- 1 / sum(w * w)
prior_w <- rep(1 / nrow(prior), nrow(prior))
post_rows <- list()
cov_p <- list()
if (!is.null(ranks) && nrow(ranks)) {
for (k in seq_along(params)) cov_p[[params[k]]] <- cs_calib_rank_test(ranks[, k], 100)$p
values$coverage_p_min <- min(unlist(cov_p))
}
for (k in seq_along(params)) {
nm <- params[k]
ps <- cs_calib_summarize(post[, k], w)
pr <- cs_calib_summarize(prior[, k], prior_w)
shrink <- if (pr$sd > 0) 1 - (ps$sd / pr$sd)^2 else NULL
values[sprintf("post_mean[%s]", nm)] <- list(ps$mean)
values[sprintf("post_sd[%s]", nm)] <- list(ps$sd)
values[sprintf("post_lo[%s]", nm)] <- list(ps$lo)
values[sprintf("post_median[%s]", nm)] <- list(ps$median)
values[sprintf("post_hi[%s]", nm)] <- list(ps$hi)
values[sprintf("prior_mean[%s]", nm)] <- list(pr$mean)
values[sprintf("prior_sd[%s]", nm)] <- list(pr$sd)
values[sprintf("shrinkage[%s]", nm)] <- list(shrink)
if (!is.null(cov_p[[nm]])) values[sprintf("coverage_p[%s]", nm)] <- list(cov_p[[nm]])
post_rows[[k]] <- list(input = nm, prior_mean = pr$mean, prior_sd = pr$sd, mean = ps$mean, sd = ps$sd, lo = ps$lo,
median = ps$median, hi = ps$hi, shrinkage = shrink, coverage_p = cov_p[[nm]])
}
values$primary <- params[1]
values$primary_mean <- values[[sprintf("post_mean[%s]", params[1])]]
values$primary_lo <- values[[sprintf("post_lo[%s]", params[1])]]
values$primary_hi <- values[[sprintf("post_hi[%s]", params[1])]]
# %% Posterior predictive check: fresh simulations at posterior draws
pred <- cs_calib_predictive(ctx, post, w, PRED_DRAWS, SEED + 17)
target_rows <- list()
ppc_ps <- list()
for (j in seq_along(targets)) {
t <- targets[[j]]
x <- pred[is.finite(pred[, j]), j]
lab <- t$key
obs <- t$value
values[sprintf("observed[%s]", lab)] <- list(obs)
if (ALGORITHM != "npe") values[sprintf("scale[%s]", lab)] <- list(res$scale[j])
if (length(x)) {
m_ <- sum(x) / length(x)
lo_ <- cs_calib_quantile7(x, 0.05)
hi_ <- cs_calib_quantile7(x, 0.95)
p_ <- min(1, 2 * min(sum(x >= obs) / length(x), sum(x <= obs) / length(x)))
ppc_ps[[t$label]] <- p_
} else {
m_ <- NULL; lo_ <- NULL; hi_ <- NULL; p_ <- NULL
}
values[sprintf("ppc_mean[%s]", lab)] <- list(m_)
values[sprintf("ppc_lo[%s]", lab)] <- list(lo_)
values[sprintf("ppc_hi[%s]", lab)] <- list(hi_)
values[sprintf("ppc_p[%s]", lab)] <- list(p_)
target_rows[[j]] <- list(statistic = t$label, observed = obs, ppc_mean = m_, ppc_lo = lo_, ppc_hi = hi_, ppc_p = p_,
scale = if (ALGORITHM != "npe") res$scale[j] else NULL)
}
# %% Assumptions
assumptions <- list(list(key = "priors", label = "Priors", status = "info",
detail = "Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight."))
bad <- names(ppc_ps)[unlist(ppc_ps) < 0.05]
if (length(ppc_ps) < J) {
assumptions[[2]] <- list(key = "reproduces_targets", label = "Reproduces the observed statistics", status = "warn",
detail = "Some statistics gave no number in the posterior predictive simulations.")
} else if (length(bad)) {
assumptions[[2]] <- list(key = "reproduces_targets", label = "Reproduces the observed statistics", status = "warn",
detail = paste0("Posterior simulations rarely bring back ", paste(bad, collapse = ", "),
" (p < 0.05): the model may be unable to produce what was observed, or the targets conflict."))
} else {
assumptions[[2]] <- list(key = "reproduces_targets", label = "Reproduces the observed statistics", status = "pass",
detail = sprintf("Simulations from the posterior bring back every observed statistic (smallest p = %.2f).", min(unlist(ppc_ps))))
}
if (length(cov_p)) {
cp <- unlist(cov_p)
worst <- names(cp)[which.min(cp)]
if (cp[[worst]] >= 0.01) {
assumptions[[3]] <- list(key = "calibrated", label = "Calibrated algorithm", status = "pass",
detail = sprintf("On %d simulated data sets the true values spread evenly across the posteriors (smallest rank-test p = %.2f, %s).", nrow(ranks), cp[[worst]], worst))
} else {
assumptions[[3]] <- list(key = "calibrated", label = "Calibrated algorithm", status = "warn",
detail = paste0(sprintf("On %d simulated data sets the true values of %s fall unevenly across the posteriors (rank-test p = %.3f): ", nrow(ranks), worst, cp[[worst]]),
"intervals may be too narrow or shifted; keep fewer simulations, add some, or train longer."))
}
} else {
assumptions[[3]] <- list(key = "calibrated", label = "Calibrated algorithm", status = "info",
detail = paste0("Not checked: ", if (ALGORITHM == "smc") "SMC-ABC has no cheap calibration check." else "the calibration check is off."))
}
# %% Charts
charts <- list()
for (k in seq_len(min(K, 6))) {
nm <- params[k]
h <- cs_pf_bandwidth(post[, k], w)
q <- cs_pf_weighted_quantiles(prior[, k], prior_w, c(0.01, 0.99))
lo_g <- min(q[1], min(post[, k]) - 3 * h)
hi_g <- max(q[2], max(post[, k]) + 3 * h)
grid <- seq(lo_g, hi_g, length.out = 150)
charts[[length(charts) + 1]] <- cs_chart(paste0("posterior_", nm), "prior-posterior", sprintf("%s: prior and posterior", nm), list(
x = cs_col(nm, c(grid, grid)),
density = cs_col("density", c(cs_pf_kde(prior[, k], grid, prior_w), cs_pf_kde(post[, k], grid, w))),
curve = cs_col("curve", c(rep("prior", length(grid)), rep("posterior", length(grid))), kind = "categorical")))
}
for (j in seq_along(targets)) {
t <- targets[[j]]
hst <- cs_sim_histogram(pred[, j], 30)
charts[[length(charts) + 1]] <- cs_chart(sprintf("ppc_%d", j), "mc-distribution", sprintf("Posterior predictive: %s (observed %s)", t$label, sprintf("%.4g", t$value)), list(
bin_low = cs_col(t$label, hst$bin_low), bin_high = cs_col("Bin end", hst$bin_high), count = cs_col("Simulations", hst$count)),
controls = list(percentiles = c(5, 50, 95), target = t$value))
}
if (length(gens)) {
charts[[length(charts) + 1]] <- cs_chart("tolerance", "series-line", "SMC-ABC tolerance by generation", list(
x = cs_col("generation", as.numeric(vapply(gens, function(g) g$generation, numeric(1)))),
y = cs_col("tolerance", vapply(gens, function(g) g$epsilon, numeric(1))),
group = cs_col("series", rep("tolerance", length(gens)), kind = "categorical")))
}
if (!is.null(ranks) && nrow(ranks)) {
charts[[length(charts) + 1]] <- cs_chart("coverage", "pit-histogram", "Calibration check: where the true values fell in their posteriors (all inputs)", list(
share = cs_col("share", cs_calib_rank_test(ranks, 100)$shares)))
}
if (length(history)) {
ep <- as.numeric(vapply(history, function(h_) h_$epoch, numeric(1)))
charts[[length(charts) + 1]] <- cs_chart("training", "series-line", "Network training: loss on training and held-out simulations", list(
x = cs_col("epoch", c(ep, ep)),
y = cs_col("negative log-likelihood", c(vapply(history, function(h_) h_$loss, numeric(1)), vapply(history, function(h_) h_$valid_loss, numeric(1)))),
group = cs_col("set", c(rep("training", length(ep)), rep("held out", length(ep))), kind = "categorical")))
}
# %% Tables
tables <- list(
list(key = "posterior", title = "Calibrated inputs",
columns = list(list(key = "input", label = "Input", type = "string"), list(key = "prior_mean", label = "Prior mean", type = "number"),
list(key = "prior_sd", label = "Prior SD", type = "number"), list(key = "mean", label = "Posterior mean", type = "number"),
list(key = "sd", label = "Posterior SD", type = "number"), list(key = "lo", label = "5%", type = "number"),
list(key = "median", label = "Median", type = "number"), list(key = "hi", label = "95%", type = "number"),
list(key = "shrinkage", label = "Shrinkage", type = "percent"), list(key = "coverage_p", label = "Calibration p", type = "number")),
rows = post_rows),
list(key = "targets", title = "Observed statistics and the posterior predictive check",
columns = list(list(key = "statistic", label = "Statistic", type = "string"), list(key = "observed", label = "Observed", type = "number"),
list(key = "ppc_mean", label = "Predicted mean", type = "number"), list(key = "ppc_lo", label = "5%", type = "number"),
list(key = "ppc_hi", label = "95%", type = "number"), list(key = "ppc_p", label = "Predictive p", type = "number"),
list(key = "scale", label = "Distance scale", type = "number")),
rows = target_rows))
if (length(gens)) {
tables[[length(tables) + 1]] <- list(key = "generations", title = "SMC-ABC generations",
columns = list(list(key = "generation", label = "Generation", type = "integer"), list(key = "epsilon", label = "Tolerance", type = "number"),
list(key = "sims", label = "Simulations", type = "integer"), list(key = "rate", label = "Acceptance", type = "percent"),
list(key = "ess", label = "Effective particles", type = "number")),
rows = lapply(gens, function(g) list(generation = g$generation, epsilon = g$epsilon, sims = g$sims, rate = g$rate, ess = g$ess)))
}
n_show <- min(500L, nrow(post))
idx <- cs_calib_resample(nrow(post), w, n_show, cs_runif(cs_rng(SEED + 19), 1))
sample_cols <- c(list(list(key = "draw", label = "Draw", type = "integer")), lapply(seq_along(params), function(k) list(key = sprintf("p%d", k), label = params[k], type = "number")))
tables[[length(tables) + 1]] <- list(key = "sample", title = sprintf("Posterior draws (%d, equally weighted)", n_show), columns = sample_cols,
rows = lapply(seq_len(n_show), function(i) c(list(draw = i), stats::setNames(as.list(post[idx[i], ]), sprintf("p%d", seq_len(K))))))
# %% Posterior draws
artifacts <- list()
if (TRUE) {
out <- cs_ml_out_dir("target/academy-parity/run-8142/simulate.calibrate/censored-sales-npe/out-r")
path <- file.path(out, "posterior.parquet")
dfp <- as.data.frame(c(list(draw = seq_len(nrow(post))), stats::setNames(lapply(seq_len(K), function(k) post[, k]), params), list(weight = w)), check.names = FALSE)
nanoparquet::write_parquet(dfp, path)
artifacts <- list(list(key = "posterior", path = path, format = "parquet", title = "Posterior draws"))
}
# %% Result
g4 <- function(v) sprintf("%.4g", v)
ALG <- c(rejection = "rejection ABC", smc = "SMC-ABC", npe = "neural posterior estimation")[[ALGORITHM]]
values$algorithm <- ALG
desc <- paste(vapply(params, function(nm) sprintf("%s %s (90%% %s to %s)", nm, g4(values[[sprintf("post_mean[%s]", nm)]]),
g4(values[[sprintf("post_lo[%s]", nm)]]), g4(values[[sprintf("post_hi[%s]", nm)]])), ""), collapse = "; ")
summary <- sprintf("Calibrated %d input(s) to %d observed statistic(s) by %s (%s simulations of %d scenario(s) each): %s.",
K, J, ALG, formatC(values$n_simulations, big.mark = ",", format = "d"), REPLICATES, desc)
notes <- c(paste0("The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. ",
"Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation)."))
if (ALGORITHM == "rejection") {
notes <- c(notes, paste0(sprintf("Rejection ABC kept the %s simulations closest to the observed statistics (tolerance %s)", formatC(values$n_accepted, big.mark = ",", format = "d"), g4(res$epsilon)),
if (res$adjusted) ", then shifted them by a weighted local-linear regression on the statistics (Beaumont et al. 2002)." else "."))
} else if (ALGORITHM == "smc") {
notes <- c(notes, paste0(sprintf("SMC-ABC ran %d generation(s) after the prior one (stop: %s); each tolerance is the 0.5 quantile of the previous distances, ", length(gens) - 1L, res$stop),
"particles move by a Gaussian kernel with twice the weighted covariance, and weights are prior over the kernel mixture (Beaumont et al. 2009)."))
} else {
notes <- c(notes, sprintf("A mixture density network (2 components, two tanh layers of 12) learned the posterior from prior simulations; training stopped at epoch %d (best held-out epoch %d).",
res$epochs_run, res$best_epoch))
}
notes <- c(notes, "The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.")
statistics <- lapply(params, function(nm) list(key = sprintf("post_mean[%s]", nm), label = sprintf("%s (posterior mean)", nm), value = values[[sprintf("post_mean[%s]", nm)]]))
cs_publish(list(
method = "simulate.calibrate",
methodVersion = "1.1.0",
title = "Scenario calibration",
engine = if (ALGORITHM != "npe") cs_engine_info("jsonlite", "nanoparquet") else cs_engine_info("jsonlite", "nanoparquet", "torch"),
n = values$n_simulations,
summary = summary,
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values,
artifacts = artifacts
))
Calibrated 2 input(s) to 2 observed statistic(s) by neural posterior estimation (600 simulations of 30 scenario(s) each): base_demand 1110 (90% 954.6 to 1406); volatility 242.2 (90% 118.1 to 379.1).
- base_demand (posterior mean)
- 1109.91
- volatility (posterior mean)
- 242.23
Assumptions
- Priors — Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight.
- Reproduces the observed statistics — Simulations from the posterior bring back every observed statistic (smallest p = 0.70).
- Calibrated algorithm — On 30 simulated data sets the true values spread evenly across the posteriors (smallest rank-test p = 0.15, volatility).
Calibrated inputs
| Input | Prior mean | Prior SD | Posterior mean | Posterior SD | 5% | Median | 95% | Shrinkage | Calibration p |
|---|---|---|---|---|---|---|---|---|---|
| base_demand | 1012.14 | 282.93 | 1109.91 | 137.37 | 954.64 | 1072.23 | 1406.10 | 76.4% | 0.6025 |
| volatility | 220.65 | 98.269 | 242.23 | 83.568 | 118.11 | 235.25 | 379.10 | 27.7% | 0.1481 |
Observed statistics and the posterior predictive check
| Statistic | Observed | Predicted mean | 5% | 95% | Predictive p | Distance scale |
|---|---|---|---|---|---|---|
| mean of sales | 930 | 939.70 | 860.95 | 994.60 | 0.7000 | — |
| SD of sales | 110 | 103.34 | 25.353 | 196.54 | 0.8667 | — |
Posterior draws (500, equally weighted)
| Draw | base_demand | volatility |
|---|---|---|
| 1 | 1050.11 | 123.47 |
| 2 | 1043.50 | 138.80 |
| 3 | 1279.16 | 357.57 |
| 4 | 1009.43 | 151.09 |
| 5 | 1254.07 | 357.72 |
| 6 | 1011.35 | 238.06 |
| 7 | 1052.26 | 131.95 |
| 8 | 1180.40 | 355.57 |
| 9 | 1084.96 | 333.08 |
| 10 | 1142.93 | 130.40 |
| 11 | 1027.84 | 176.95 |
| 12 | 1044.02 | 334.17 |
| 13 | 1326.19 | 396.47 |
| 14 | 1047.59 | 282.71 |
| 15 | 974.38 | 184.37 |
| 16 | 1078.05 | 252.42 |
| 17 | 1036.47 | 192.65 |
| 18 | 1037.36 | 92.367 |
| 19 | 1046.38 | 92.087 |
| 20 | 1071.62 | 227.32 |
| 21 | 1035.73 | 198.07 |
| 22 | 1135.51 | 145.82 |
| 23 | 1010.69 | 184.65 |
| 24 | 1078.16 | 350.52 |
| 25 | 1123.77 | 346.87 |
| 26 | 1047.06 | 302.54 |
| 27 | 1222.11 | 352.06 |
| 28 | 1061.32 | 155.17 |
| 29 | 1398.76 | 347.91 |
| 30 | 1092.70 | 196.06 |
| 31 | 1024.06 | 177.36 |
| 32 | 986.20 | 205.84 |
| 33 | 996.57 | 255.64 |
| 34 | 1153.01 | 308.00 |
| 35 | 979.33 | 147.99 |
| 36 | 1106.87 | 293.43 |
| 37 | 1047.77 | 345.19 |
| 38 | 1414.69 | 352.29 |
| 39 | 1027.37 | 118.14 |
| 40 | 1075.58 | 297.10 |
First 40 of 500 rows.
- The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation).
- A mixture density network (2 components, two tanh layers of 12) learned the posterior from prior simulations; training stopped at epoch 40 (best held-out epoch 40).
- The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Calibrate a scenario model to observed statistics (ABC, SMC-ABC, neural posterior)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method simulate.calibrate 1.1.0 · spec 82175d8e725ac640
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.sim import calibrate as cb # ABC, SMC-ABC and NPE on the scenario-model twins (twin of codesplashr cs_calib_*)
from codesplash.sim import mc
from codesplash.stats import particle as pf # weighted quantiles and kernel densities
from codesplash.stats.rng import Rng
# %% Model, inputs to calibrate and observed statistics
ALGORITHM = "npe"
REPLICATES = int(30)
SEED = int(7)
COVERAGE = True and ALGORITHM in ("rejection", "npe")
COVERAGE_N = int(30)
PRED_DRAWS = int(60)
warnings = []
try:
ctx = cb.setup("{\"inputs\":[{\"name\":\"base_demand\",\"dist\":\"uniform\",\"params\":{\"min\":500,\"max\":1500}},{\"name\":\"volatility\",\"dist\":\"uniform\",\"params\":{\"min\":50,\"max\":400}},{\"name\":\"shock\",\"dist\":\"normal\",\"params\":{\"mean\":0,\"sd\":1}}],\"decisions\":[{\"name\":\"order\",\"value\":1000,\"min\":0,\"max\":3000}],\"formulas\":[{\"name\":\"demand\",\"expr\":\"max(base_demand + volatility * shock, 0)\"},{\"name\":\"sales\",\"expr\":\"min(demand, order)\"}],\"kpis\":[{\"name\":\"sales\",\"label\":\"Sales\"}],\"correlations\":[]}", "base_demand, volatility", "[{\"name\":\"sales\",\"stat\":\"mean\",\"value\":930},{\"name\":\"sales\",\"stat\":\"sd\",\"value\":110}]", REPLICATES)
except ValueError as e:
cs.cs_error("CS_E_INVALID_OPTION", option="Calibration setup", allowed="a valid model, inputs to calibrate and observed statistics", value=str(e))
params = ctx["params"]
targets = ctx["targets"]
K, J = len(params), len(targets)
# The neural posterior's network trains on the shared trainer: training options, live progress and checkpoints.
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-8142/simulate.calibrate/censored-sales-npe/out-python",
)
# %% Posterior
# Every algorithm works on normal scores z = Φ⁻¹(F(θ)), where any prior is a standard normal, and maps back
# through each input's quantile function (Monte Carlo's twin), so bounds and clipping hold.
values = {"algorithm": ALGORITHM, "n_params": K, "n_targets": J, "replicates": REPLICATES}
for key in ("n_accepted", "epsilon", "adjusted", "generations", "stop_reason", "acceptance_rate", "epochs_run", "valid_loss", "coverage_p_min"):
values[key] = None
ranks = None
gens = []
history = []
try:
if ALGORITHM == "rejection":
S = int(10000)
res = cb.rejection(ctx, S, 0.01, False, SEED)
k_acc = len(res["accepted"])
values.update({"n_simulations": S, "n_accepted": k_acc, "epsilon": res["epsilon"], "adjusted": int(res["adjusted"]), "acceptance_rate": k_acc / S})
if res["note"]:
warnings.append(res["note"])
if res["n_finite"] < S:
warnings.append(f"{S - res['n_finite']:,} of {S:,} simulations gave no number for some statistic (division by zero or an invalid function argument) and were never kept.")
if COVERAGE:
ranks = cb.coverage_rejection(ctx, res, COVERAGE_N)
elif ALGORITHM == "smc":
res = cb.smc(ctx, int(500), int(6), 0.5, int(100000), 0.02, SEED)
gens = res["generations"]
values.update({"n_simulations": res["n_sims"], "n_accepted": int(500), "epsilon": res["epsilon"], "generations": len(gens) - 1,
"stop_reason": res["stop"], "acceptance_rate": gens[-1]["rate"]})
if res["stop"] == "budget":
warnings.append(f"The simulation budget ran out during generation {len(gens)}; the posterior is generation {len(gens) - 1}'s.")
else:
res = cb.npe(ctx, int(600), int(2), int(12), int(40),
0.01, int(800), SEED, COVERAGE_N if COVERAGE else 0)
history = res["history"]
values.update({"n_simulations": res["n_sims"], "epochs_run": res["epochs_run"], "valid_loss": res["valid_loss"]})
ranks = res["ranks"]
except ValueError as e:
cs.cs_error("CS_E_UNDEFINED", what="The calibration", reason=str(e))
post, w, prior = res["post_theta"], res["weights"], res["prior_theta"]
w = w / float(np.sum(w))
values["ess"] = 1.0 / float(np.sum(w * w))
prior_w = np.full(prior.shape[0], 1.0 / prior.shape[0])
post_rows = []
cov_p = {}
if ranks is not None and len(ranks):
for k, nm in enumerate(params):
cov_p[nm] = cb.rank_test(ranks[:, k], 100.0)[2]
values["coverage_p_min"] = float(min(cov_p.values()))
for k, nm in enumerate(params):
ps = cb.summarize(post[:, k], w)
pr = cb.summarize(prior[:, k], prior_w)
shrink = 1.0 - (ps["sd"] / pr["sd"]) ** 2 if pr["sd"] > 0 else None
values[f"post_mean[{nm}]"], values[f"post_sd[{nm}]"] = ps["mean"], ps["sd"]
values[f"post_lo[{nm}]"], values[f"post_median[{nm}]"], values[f"post_hi[{nm}]"] = ps["lo"], ps["median"], ps["hi"]
values[f"prior_mean[{nm}]"], values[f"prior_sd[{nm}]"], values[f"shrinkage[{nm}]"] = pr["mean"], pr["sd"], shrink
if nm in cov_p:
values[f"coverage_p[{nm}]"] = cov_p[nm]
post_rows.append({"input": nm, "prior_mean": pr["mean"], "prior_sd": pr["sd"], "mean": ps["mean"], "sd": ps["sd"], "lo": ps["lo"],
"median": ps["median"], "hi": ps["hi"], "shrinkage": shrink, "coverage_p": cov_p.get(nm)})
values.update({"primary": params[0], "primary_mean": values[f"post_mean[{params[0]}]"], "primary_lo": values[f"post_lo[{params[0]}]"],
"primary_hi": values[f"post_hi[{params[0]}]"]})
# %% Posterior predictive check: fresh simulations at posterior draws
pred = cb.predictive(ctx, post, w, PRED_DRAWS, SEED + 17)
target_rows = []
ppc_ps = []
for j, t in enumerate(targets):
x = pred[np.isfinite(pred[:, j]), j]
lab = t["key"]
obs = t["value"]
values[f"observed[{lab}]"] = obs
if ALGORITHM != "npe":
values[f"scale[{lab}]"] = float(res["scale"][j])
if len(x):
m_ = float(np.sum(x)) / len(x)
lo_, hi_ = cb.quantile7(x, 0.05), cb.quantile7(x, 0.95)
p_ = min(1.0, 2.0 * min(float(np.sum(x >= obs)) / len(x), float(np.sum(x <= obs)) / len(x)))
else:
m_ = lo_ = hi_ = p_ = None
values[f"ppc_mean[{lab}]"], values[f"ppc_lo[{lab}]"], values[f"ppc_hi[{lab}]"], values[f"ppc_p[{lab}]"] = m_, lo_, hi_, p_
if p_ is not None:
ppc_ps.append((t["label"], p_))
target_rows.append({"statistic": t["label"], "observed": obs, "ppc_mean": m_, "ppc_lo": lo_, "ppc_hi": hi_, "ppc_p": p_,
"scale": float(res["scale"][j]) if ALGORITHM != "npe" else None})
# %% Assumptions
assumptions = [{"key": "priors", "label": "Priors", "status": "info",
"detail": "Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight."}]
bad = [lab for lab, p_ in ppc_ps if p_ < 0.05]
if len(ppc_ps) < J:
assumptions.append({"key": "reproduces_targets", "label": "Reproduces the observed statistics", "status": "warn",
"detail": "Some statistics gave no number in the posterior predictive simulations."})
elif bad:
assumptions.append({"key": "reproduces_targets", "label": "Reproduces the observed statistics", "status": "warn",
"detail": "Posterior simulations rarely bring back " + ", ".join(bad) + " (p < 0.05): the model may be unable to produce what was observed, or the targets conflict."})
else:
assumptions.append({"key": "reproduces_targets", "label": "Reproduces the observed statistics", "status": "pass",
"detail": f"Simulations from the posterior bring back every observed statistic (smallest p = {min(p_ for _, p_ in ppc_ps):.2f})."})
if cov_p:
worst = min(cov_p, key=lambda nm: cov_p[nm])
if cov_p[worst] >= 0.01:
assumptions.append({"key": "calibrated", "label": "Calibrated algorithm", "status": "pass",
"detail": f"On {len(ranks)} simulated data sets the true values spread evenly across the posteriors (smallest rank-test p = {cov_p[worst]:.2f}, {worst})."})
else:
assumptions.append({"key": "calibrated", "label": "Calibrated algorithm", "status": "warn",
"detail": f"On {len(ranks)} simulated data sets the true values of {worst} fall unevenly across the posteriors (rank-test p = {cov_p[worst]:.3f}): "
"intervals may be too narrow or shifted; keep fewer simulations, add some, or train longer."})
else:
assumptions.append({"key": "calibrated", "label": "Calibrated algorithm", "status": "info",
"detail": "Not checked: " + ("SMC-ABC has no cheap calibration check." if ALGORITHM == "smc" else "the calibration check is off.")})
# %% Charts
charts = []
for k, nm in enumerate(params[:6]):
pw = prior_w
h = pf.bandwidth(post[:, k], w)
q01, q99 = pf.weighted_quantiles(prior[:, k], pw, (0.01, 0.99))
lo_g = min(q01, float(np.min(post[:, k])) - 3.0 * h)
hi_g = max(q99, float(np.max(post[:, k])) + 3.0 * h)
grid = np.linspace(lo_g, hi_g, 150)
charts.append(cs.chart(f"posterior_{nm}", "prior-posterior", f"{nm}: prior and posterior", {
"x": cs.col(nm, np.concatenate([grid, grid])),
"density": cs.col("density", np.concatenate([pf.kde(prior[:, k], grid, pw), pf.kde(post[:, k], grid, w)])),
"curve": cs.col("curve", ["prior"] * len(grid) + ["posterior"] * len(grid), kind="categorical")}))
for j, t in enumerate(targets):
hst = mc.histogram(pred[:, j], 30)
charts.append(cs.chart(f"ppc_{j + 1}", "mc-distribution", f"Posterior predictive: {t['label']} (observed {t['value']:.4g})", {
"bin_low": cs.col(t["label"], hst["bin_low"]), "bin_high": cs.col("Bin end", hst["bin_high"]), "count": cs.col("Simulations", hst["count"])},
controls={"percentiles": [5, 50, 95], "target": float(t["value"])}))
if gens:
charts.append(cs.chart("tolerance", "series-line", "SMC-ABC tolerance by generation", {
"x": cs.col("generation", [float(g["generation"]) for g in gens]), "y": cs.col("tolerance", [g["epsilon"] for g in gens]),
"group": cs.col("series", ["tolerance"] * len(gens), kind="categorical")}))
if ranks is not None and len(ranks):
shares = cb.rank_test(ranks, 100.0)[0]
charts.append(cs.chart("coverage", "pit-histogram", "Calibration check: where the true values fell in their posteriors (all inputs)", {
"share": cs.col("share", shares)}))
if history:
ep = [float(h_["epoch"]) for h_ in history]
charts.append(cs.chart("training", "series-line", "Network training: loss on training and held-out simulations", {
"x": cs.col("epoch", ep + ep), "y": cs.col("negative log-likelihood", [h_["loss"] for h_ in history] + [h_["valid_loss"] for h_ in history]),
"group": cs.col("set", ["training"] * len(ep) + ["held out"] * len(ep), kind="categorical")}))
# %% Tables
tables = [{"key": "posterior", "title": "Calibrated inputs",
"columns": [{"key": "input", "label": "Input", "type": "string"}, {"key": "prior_mean", "label": "Prior mean", "type": "number"},
{"key": "prior_sd", "label": "Prior SD", "type": "number"}, {"key": "mean", "label": "Posterior mean", "type": "number"},
{"key": "sd", "label": "Posterior SD", "type": "number"}, {"key": "lo", "label": "5%", "type": "number"},
{"key": "median", "label": "Median", "type": "number"}, {"key": "hi", "label": "95%", "type": "number"},
{"key": "shrinkage", "label": "Shrinkage", "type": "percent"}, {"key": "coverage_p", "label": "Calibration p", "type": "number"}],
"rows": post_rows},
{"key": "targets", "title": "Observed statistics and the posterior predictive check",
"columns": [{"key": "statistic", "label": "Statistic", "type": "string"}, {"key": "observed", "label": "Observed", "type": "number"},
{"key": "ppc_mean", "label": "Predicted mean", "type": "number"}, {"key": "ppc_lo", "label": "5%", "type": "number"},
{"key": "ppc_hi", "label": "95%", "type": "number"}, {"key": "ppc_p", "label": "Predictive p", "type": "number"},
{"key": "scale", "label": "Distance scale", "type": "number"}],
"rows": target_rows}]
if gens:
tables.append({"key": "generations", "title": "SMC-ABC generations",
"columns": [{"key": "generation", "label": "Generation", "type": "integer"}, {"key": "epsilon", "label": "Tolerance", "type": "number"},
{"key": "sims", "label": "Simulations", "type": "integer"}, {"key": "rate", "label": "Acceptance", "type": "percent"},
{"key": "ess", "label": "Effective particles", "type": "number"}],
"rows": [{"generation": g["generation"], "epsilon": g["epsilon"], "sims": g["sims"], "rate": g["rate"], "ess": g["ess"]} for g in gens]})
n_show = min(500, post.shape[0])
idx = cb.resample(post.shape[0], w, n_show, float(Rng(SEED + 19).uniform(1)[0]))
tables.append({"key": "sample", "title": f"Posterior draws ({n_show}, equally weighted)",
"columns": [{"key": "draw", "label": "Draw", "type": "integer"}] + [{"key": f"p{k + 1}", "label": nm, "type": "number"} for k, nm in enumerate(params)],
"rows": [{"draw": i + 1, **{f"p{k + 1}": float(post[idx[i], k]) for k in range(K)}} for i in range(n_show)]})
# %% Posterior draws
artifacts = []
if True:
out = csml.out_dir("target/academy-parity/run-8142/simulate.calibrate/censored-sales-npe/out-python")
path = os.path.join(out, "posterior.parquet")
pd.DataFrame({"draw": np.arange(1, post.shape[0] + 1), **{nm: post[:, k] for k, nm in enumerate(params)}, "weight": w}).to_parquet(path, index=False)
artifacts.append({"key": "posterior", "path": path, "format": "parquet", "title": "Posterior draws"})
# %% Result
ALG = {"rejection": "rejection ABC", "smc": "SMC-ABC", "npe": "neural posterior estimation"}[ALGORITHM]
values["algorithm"] = ALG
desc = "; ".join(f"{nm} {values[f'post_mean[{nm}]']:.4g} (90% {values[f'post_lo[{nm}]']:.4g} to {values[f'post_hi[{nm}]']:.4g})" for nm in params)
summary = f"Calibrated {K} input(s) to {J} observed statistic(s) by {ALG} ({values['n_simulations']:,} simulations of {REPLICATES} scenario(s) each): {desc}."
notes = ["The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. "
"Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation)."]
if ALGORITHM == "rejection":
notes.append(f"Rejection ABC kept the {values['n_accepted']:,} simulations closest to the observed statistics (tolerance {res['epsilon']:.4g})"
+ (", then shifted them by a weighted local-linear regression on the statistics (Beaumont et al. 2002)." if res["adjusted"] else "."))
elif ALGORITHM == "smc":
notes.append(f"SMC-ABC ran {len(gens) - 1} generation(s) after the prior one (stop: {res['stop']}); each tolerance is the 0.5 quantile of the previous distances, "
"particles move by a Gaussian kernel with twice the weighted covariance, and weights are prior over the kernel mixture (Beaumont et al. 2009).")
else:
notes.append(f"A mixture density network (2 components, two tanh layers of 12) learned the posterior from prior simulations; "
f"training stopped at epoch {res['epochs_run']} (best held-out epoch {res['best_epoch']}).")
notes.append("The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.")
statistics = [{"key": f"post_mean[{nm}]", "label": f"{nm} (posterior mean)", "value": values[f"post_mean[{nm}]"]} for nm in params]
cs.publish({
"method": "simulate.calibrate",
"methodVersion": "1.1.0",
"title": "Scenario calibration",
"engine": cs.engine_info("numpy", "scipy", "pandas") if ALGORITHM != "npe" else cs.engine_info("numpy", "scipy", "pandas", "torch"),
"n": values["n_simulations"],
"summary": summary,
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
"artifacts": artifacts,
})
Shortened for the Academy: 6 chart(s) dropped to stay under 100 KB; 6 chart(s) dropped to stay under 100 KB.
Use it
ReadIn the Scenario studio, the Calibrate tab can write the posterior back into the model: each calibrated input becomes an empirical input of its posterior draws. From then on, Monte Carlo and sensitivity analysis draw from what the data support, not from the original guess.
Check: calibration
CheckpointCheck yourself
What does rejection ABC keep as the posterior?
Show the answer
Answer: a
Simulate from the prior, compare statistics, keep the closest: no likelihood formula is needed.
Check yourself
The calibration check's rank histogram piles up at both ends (a U shape). What does that mean?
Show the answer
Answer: a
True values landing at the extremes of their posteriors means the intervals are overconfident (too narrow).
Check yourself
After calibration, the posterior predictive p for the observed SD is 0.01. What is the most sensible next step?
Show the answer
Answer: a
A small predictive p says the model can't produce what was seen; fix the model (or recheck the data) before trusting the posterior.
Concepts in this lesson