Skip to content

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.

Advanced ~16 min8 steps

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

01

From a guess to what the data say

Read

A 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.

02

Simulate, compare, keep

Read

Approximate 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:

  1. Draw candidate values of the inputs from their distributions, which act as the prior.
  2. Run the model at each candidate and compute the same statistics that were observed.
  3. 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..

Scenario calibrationRecorded · Python and R agreeRecorded 2026-11-25 · 49 values compared
R

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

base_demand: prior and posteriorHow did the data move belief about the effect, and how much more (or less) plausible is the null value now?
View data
curvedensitybase_demand
prior0.0005509.26
prior0.0006515.84
prior0.0006522.43
prior0.0007529.01
prior0.0007535.60
prior0.0008542.18
prior0.0008548.77
prior0.0008555.35
prior0.0009561.94
prior0.0009568.52
prior0.0009575.11
prior0.0009581.69
prior0.0009588.28
prior0.0010594.86
prior0.0010601.45
prior0.0010608.03
prior0.0010614.62
prior0.0010621.20
prior0.0010627.79
prior0.0010634.37
prior0.0010640.96
prior0.0010647.54
prior0.0010654.13
prior0.0010660.71
prior0.0010667.30
prior0.0010673.88
prior0.0010680.47
prior0.0010687.05
prior0.0011693.64
prior0.0011700.22
prior0.0011706.81
prior0.0011713.39
prior0.0011719.98
prior0.0011726.56
prior0.0011733.15
prior0.0011739.73
prior0.0011746.32
prior0.0010752.90
prior0.0010759.49
prior0.0010766.07
prior0.0010772.66
prior0.0010779.24
prior0.0010785.83
prior0.0010792.41
prior0.0010799.00
prior0.0010805.58
prior0.0010812.17
prior0.0010818.75
prior0.0010825.34
prior0.0010831.92
prior0.0010838.50
prior0.0010845.09
prior0.0010851.67
prior0.0010858.26
prior0.0010864.84
prior0.0010871.43
prior0.0010878.01
prior0.0010884.60
prior0.0010891.18
prior0.0010897.77

First 60 of 300 rows.

volatility: prior and posteriorHow did the data move belief about the effect, and how much more (or less) plausible is the null value now?
View data
curvedensityvolatility
prior0.001548.812
prior0.001751.677
prior0.001954.543
prior0.002157.409
prior0.002360.275
prior0.002463.140
prior0.002566.006
prior0.002668.872
prior0.002771.737
prior0.002874.603
prior0.002877.469
prior0.002980.334
prior0.002983.200
prior0.002986.066
prior0.002988.932
prior0.002991.797
prior0.002994.663
prior0.002997.529
prior0.0029100.39
prior0.0029103.26
prior0.0029106.13
prior0.0029108.99
prior0.0029111.86
prior0.0030114.72
prior0.0030117.59
prior0.0030120.45
prior0.0030123.32
prior0.0030126.19
prior0.0030129.05
prior0.0030131.92
prior0.0030134.78
prior0.0030137.65
prior0.0030140.51
prior0.0030143.38
prior0.0030146.25
prior0.0030149.11
prior0.0030151.98
prior0.0030154.84
prior0.0030157.71
prior0.0029160.57
prior0.0029163.44
prior0.0029166.31
prior0.0029169.17
prior0.0029172.04
prior0.0029174.90
prior0.0029177.77
prior0.0029180.63
prior0.0028183.50
prior0.0028186.37
prior0.0028189.23
prior0.0028192.10
prior0.0028194.96
prior0.0028197.83
prior0.0028200.69
prior0.0028203.56
prior0.0028206.43
prior0.0028209.29
prior0.0029212.16
prior0.0029215.02
prior0.0029217.89

First 60 of 300 rows.

Posterior predictive: mean of sales (observed 930)Across all simulated scenarios, how likely is each outcome — and of missing the target?
View data
Bin endmean of salesSimulations
845.16840.422
849.90845.160
854.63849.901
859.37854.630
864.10859.370
868.84864.101
873.58868.840
878.31873.581
883.05878.311
887.78883.050
892.52887.781
897.26892.522
901.99897.262
906.73901.993
911.46906.734
916.20911.464
920.94916.204
925.67920.943
930.41925.676
935.14930.414
939.88935.142
944.62939.884
949.35944.622
954.09949.353
958.82954.092
963.56958.823
968.30963.561
973.03968.302
977.77973.031
982.50977.771
Posterior predictive: SD of sales (observed 110)Across all simulated scenarios, how likely is each outcome — and of missing the target?
View data
Bin endSD of salesSimulations
69.87762.7114
77.04469.8773
84.21077.0442
91.37684.2106
98.54291.3763
105.7198.5424
112.87105.714
120.04112.873
127.21120.045
134.37127.213
141.54134.378
148.70141.546
155.87148.701
163.04155.871
170.20163.041
177.37170.200
184.53177.372
191.70184.531
198.87191.700
206.03198.871
213.20206.030
220.36213.201
227.53220.360
234.70227.530
241.86234.700
249.03241.860
256.20249.030
263.36256.200
270.53263.360
277.69270.531
Calibration check: where the true values fell in their posteriors (all inputs)Do the actual values look like draws from the forecast distributions?
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

InputPrior meanPrior SDPosterior meanPosterior SD5%Median95%ShrinkageCalibration p
base_demand1003.93291.541080.4383.522960.111071.881253.5591.8%0.7399
volatility220.88101.49259.3664.352150.95248.19381.6659.8%0.7399

Observed statistics and the posterior predictive check

StatisticObservedPredicted mean5%95%Predictive pDistance scale
mean of sales930924.41866.78968.930.9000139.64
SD of sales110122.6566.156191.430.8333112.23

Posterior draws (60, equally weighted)

Drawbase_demandvolatility
1999.36188.95
21108.76331.85
31072.09237.98
4985.63150.95
51039.59208.36
61063.43246.54
71058.38266.61
81102.92291.22
91001.92238.51
101100.10312.53
11990.76206.97
121094.76295.84
131291.17391.38
141013.07248.19
151134.36288.00
161010.65212.86
171164.26315.51
181016.78262.19
191028.44240.75
201095.42243.83
211179.72319.10
221134.09299.82
231203.35326.00
241145.29296.43
25974.97198.99
261050.68262.91
271212.67317.73
28951.02191.74
291097.59258.20
301055.35264.88
311031.93226.28
321012.32250.19
331053.30206.85
341139.36253.21
351113.71274.23
361043.01203.30
371278.05377.88
381073.66240.87
391182.54370.35
40969.44187.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
))
Python

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

InputPrior meanPrior SDPosterior meanPosterior SD5%Median95%ShrinkageCalibration p
base_demand1003.93291.541080.4383.522960.111071.881253.5591.8%0.7399
volatility220.88101.49259.3664.352150.95248.19381.6659.8%0.7399

Observed statistics and the posterior predictive check

StatisticObservedPredicted mean5%95%Predictive pDistance scale
mean of sales930924.41866.78968.930.9000139.64
SD of sales110122.6566.156191.430.8333112.23

Posterior draws (60, equally weighted)

Drawbase_demandvolatility
1999.36188.95
21108.76331.85
31072.09237.98
4985.63150.95
51039.59208.36
61063.43246.54
71058.38266.61
81102.92291.22
91001.92238.51
101100.10312.53
11990.76206.97
121094.76295.84
131291.17391.38
141013.07248.19
151134.36288.00
161010.65212.86
171164.26315.51
181016.78262.19
191028.44240.75
201095.42243.83
211179.72319.10
221134.09299.82
231203.35326.00
241145.29296.43
25974.97198.99
261050.68262.91
271212.67317.73
28951.02191.74
291097.59258.20
301055.35264.88
311031.93226.28
321012.32250.19
331053.30206.85
341139.36253.21
351113.71274.23
361043.01203.30
371278.05377.88
381073.66240.87
391182.54370.35
40969.44187.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.

03

Predict: an uninformative statistic

Predict

Predict 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?

Close to 0%About 50%Close to 100%
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.

04

Did it reproduce what was seen?

Read

The 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.

05

Is the posterior honest?

Read

A 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.

06

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.
Scenario calibrationRecorded · Python and R agreeRecorded 2026-11-25 · 47 values compared
R

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

base_demand: prior and posteriorHow did the data move belief about the effect, and how much more (or less) plausible is the null value now?
View data
curvedensitybase_demand
prior0.0005504.58
prior0.0006512.27
prior0.0006519.95
prior0.0006527.64
prior0.0007535.33
prior0.0007543.01
prior0.0007550.70
prior0.0008558.38
prior0.0008566.07
prior0.0008573.76
prior0.0008581.44
prior0.0009589.13
prior0.0009596.81
prior0.0009604.50
prior0.0009612.18
prior0.0009619.87
prior0.0009627.56
prior0.0009635.24
prior0.0009642.93
prior0.0010650.61
prior0.0010658.30
prior0.0010665.99
prior0.0010673.67
prior0.0010681.36
prior0.0010689.04
prior0.0010696.73
prior0.0010704.41
prior0.0009712.10
prior0.0009719.79
prior0.0009727.47
prior0.0009735.16
prior0.0009742.84
prior0.0009750.53
prior0.0009758.22
prior0.0009765.90
prior0.0009773.59
prior0.0009781.27
prior0.0009788.96
prior0.0009796.65
prior0.0009804.33
prior0.0009812.02
prior0.0009819.70
prior0.0009827.39
prior0.0009835.07
prior0.0009842.76
prior0.0009850.45
prior0.0009858.13
prior0.0009865.82
prior0.0009873.50
prior0.0009881.19
prior0.0009888.88
prior0.0009896.56
prior0.0009904.25
prior0.0010911.93
prior0.0010919.62
prior0.0010927.31
prior0.0010934.99
prior0.0010942.68
prior0.0010950.36
prior0.0010958.05

First 60 of 300 rows.

volatility: prior and posteriorHow did the data move belief about the effect, and how much more (or less) plausible is the null value now?
View data
curvedensityvolatility
prior1.161e-5−35.911
prior1.590e-5−32.363
prior2.156e-5−28.815
prior2.892e-5−25.267
prior3.838e-5−21.719
prior5.042e-5−18.171
prior6.554e-5−14.623
prior8.433e-5−11.075
prior0.0001−7.527
prior0.0001−3.979
prior0.0002−0.4314
prior0.00023.117
prior0.00036.664
prior0.000310.212
prior0.000413.760
prior0.000417.308
prior0.000520.856
prior0.000624.404
prior0.000727.952
prior0.000831.500
prior0.000935.048
prior0.001038.596
prior0.001142.144
prior0.001345.692
prior0.001449.240
prior0.001552.788
prior0.001656.336
prior0.001859.884
prior0.001963.432
prior0.002066.979
prior0.002170.527
prior0.002274.075
prior0.002277.623
prior0.002381.171
prior0.002484.719
prior0.002488.267
prior0.002591.815
prior0.002595.363
prior0.002598.911
prior0.0025102.46
prior0.0026106.01
prior0.0026109.55
prior0.0026113.10
prior0.0026116.65
prior0.0026120.20
prior0.0026123.75
prior0.0026127.29
prior0.0026130.84
prior0.0026134.39
prior0.0027137.94
prior0.0027141.49
prior0.0027145.03
prior0.0027148.58
prior0.0027152.13
prior0.0028155.68
prior0.0028159.23
prior0.0028162.77
prior0.0028166.32
prior0.0028169.87
prior0.0028173.42

First 60 of 300 rows.

Posterior predictive: mean of sales (observed 930)Across all simulated scenarios, how likely is each outcome — and of missing the target?
View data
Bin endmean of salesSimulations
811.59805.261
817.91811.590
824.23817.910
830.55824.230
836.87830.551
843.19836.870
849.52843.190
855.84849.520
862.16855.842
868.48862.160
874.80868.485
881.12874.800
887.45881.120
893.77887.451
900.09893.772
906.41900.091
912.73906.414
919.05912.734
925.38919.054
931.70925.381
938.02931.702
944.34938.024
950.66944.344
956.98950.661
963.31956.984
969.63963.315
975.95969.635
982.27975.952
988.59982.274
994.92988.593
Posterior predictive: SD of sales (observed 110)Across all simulated scenarios, how likely is each outcome — and of missing the target?
View data
Bin endSD of salesSimulations
26.32520.1602
32.48926.3251
38.65432.4891
44.81838.6541
50.98244.8183
57.14750.9822
63.31157.1470
69.47663.3111
75.64069.4764
81.80475.6401
87.96981.8044
94.13387.9696
100.3094.1335
106.46100.305
112.63106.460
118.79112.634
124.96118.794
131.12124.961
137.28131.124
143.45137.281
149.61143.452
155.78149.611
161.94155.781
168.11161.940
174.27168.111
180.44174.272
186.60180.440
192.76186.600
198.93192.762
205.09198.931
SMC-ABC tolerance by generationHow does the series move over time, and where is an estimated break?
View data
seriesgenerationtolerance
tolerance03.850
tolerance11.064
tolerance20.8565
tolerance30.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

InputPrior meanPrior SDPosterior meanPosterior SD5%Median95%ShrinkageCalibration p
base_demand1004.05293.891124.27150.58921.171121.791393.5673.7%—
volatility231.93104.80258.0893.235102.62278.88381.5420.8%—

Observed statistics and the posterior predictive check

StatisticObservedPredicted mean5%95%Predictive pDistance scale
mean of sales930933.67860.61988.270.8667142.14
SD of sales110103.4836.636179.520.8000116.60

SMC-ABC generations

GenerationToleranceSimulationsAcceptanceEffective particles
03.850200100.0%200.00
11.06440050.0%113.85
20.856560033.3%139.49
30.488780025.0%147.37

Posterior draws (200, equally weighted)

Drawbase_demandvolatility
11210.59288.65
21419.42366.79
31352.55344.34
41058.10227.95
5921.17112.47
6921.17112.47
7978.90110.04
8948.9356.827
9999.85208.32
10999.85208.32
111072.34239.14
121072.34239.14
131207.96381.49
14937.71217.47
15937.71217.47
16968.3179.782
17915.20162.34
18915.20162.34
191325.17285.38
201189.71374.76
211238.48301.09
221238.48301.09
231083.81225.28
241138.70360.43
251359.43353.48
261324.00299.67
271455.22358.29
281302.89361.52
291189.83381.54
301148.55281.04
311148.55281.04
321013.93109.87
33986.31102.62
34986.31102.62
35993.27264.50
36993.27264.50
37934.17217.15
38934.17217.15
39968.75200.75
401231.31272.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
))
Python

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

InputPrior meanPrior SDPosterior meanPosterior SD5%Median95%ShrinkageCalibration p
base_demand1004.05293.891124.27150.58921.171121.791393.5673.7%—
volatility231.93104.80258.0893.235102.62278.88381.5420.8%—

Observed statistics and the posterior predictive check

StatisticObservedPredicted mean5%95%Predictive pDistance scale
mean of sales930933.67860.61988.270.8667142.14
SD of sales110103.4836.636179.520.8000116.60

SMC-ABC generations

GenerationToleranceSimulationsAcceptanceEffective particles
03.850200100.0%200.00
11.06440050.0%113.85
20.856560033.3%139.49
30.488780025.0%147.37

Posterior draws (200, equally weighted)

Drawbase_demandvolatility
11210.59288.65
21419.42366.79
31352.55344.34
41058.10227.95
5921.17112.47
6921.17112.47
7978.90110.04
8948.9356.827
9999.85208.32
10999.85208.32
111072.34239.14
121072.34239.14
131207.96381.49
14937.71217.47
15937.71217.47
16968.3179.782
17915.20162.34
18915.20162.34
191325.17285.38
201189.71374.76
211238.48301.09
221238.48301.09
231083.81225.28
241138.70360.43
251359.43353.48
261324.00299.67
271455.22358.29
281302.89361.52
291189.83381.54
301148.55281.04
311148.55281.04
321013.93109.87
33986.31102.62
34986.31102.62
35993.27264.50
36993.27264.50
37934.17217.15
38934.17217.15
39968.75200.75
401231.31272.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.
Scenario calibrationRecorded · Python and R agreeRecorded 2026-11-25 · 47 values compared
R

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

InputPrior meanPrior SDPosterior meanPosterior SD5%Median95%ShrinkageCalibration p
base_demand1012.14282.931109.91137.37954.641072.231406.1076.4%0.6025
volatility220.6598.269242.2383.568118.11235.25379.1027.7%0.1481

Observed statistics and the posterior predictive check

StatisticObservedPredicted mean5%95%Predictive pDistance scale
mean of sales930939.70860.95994.600.7000—
SD of sales110103.3425.353196.540.8667—

Posterior draws (500, equally weighted)

Drawbase_demandvolatility
11050.11123.47
21043.50138.80
31279.16357.57
41009.43151.09
51254.07357.72
61011.35238.06
71052.26131.95
81180.40355.57
91084.96333.08
101142.93130.40
111027.84176.95
121044.02334.17
131326.19396.47
141047.59282.71
15974.38184.37
161078.05252.42
171036.47192.65
181037.3692.367
191046.3892.087
201071.62227.32
211035.73198.07
221135.51145.82
231010.69184.65
241078.16350.52
251123.77346.87
261047.06302.54
271222.11352.06
281061.32155.17
291398.76347.91
301092.70196.06
311024.06177.36
32986.20205.84
33996.57255.64
341153.01308.00
35979.33147.99
361106.87293.43
371047.77345.19
381414.69352.29
391027.37118.14
401075.58297.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
))
Python

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

InputPrior meanPrior SDPosterior meanPosterior SD5%Median95%ShrinkageCalibration p
base_demand1012.14282.931109.91137.37954.641072.231406.1076.4%0.6025
volatility220.6598.269242.2383.568118.11235.25379.1027.7%0.1481

Observed statistics and the posterior predictive check

StatisticObservedPredicted mean5%95%Predictive pDistance scale
mean of sales930939.70860.95994.600.7000—
SD of sales110103.3425.353196.540.8667—

Posterior draws (500, equally weighted)

Drawbase_demandvolatility
11050.11123.47
21043.50138.80
31279.16357.57
41009.43151.09
51254.07357.72
61011.35238.06
71052.26131.95
81180.40355.57
91084.96333.08
101142.93130.40
111027.84176.95
121044.02334.17
131326.19396.47
141047.59282.71
15974.38184.37
161078.05252.42
171036.47192.65
181037.3692.367
191046.3892.087
201071.62227.32
211035.73198.07
221135.51145.82
231010.69184.65
241078.16350.52
251123.77346.87
261047.06302.54
271222.11352.06
281061.32155.17
291398.76347.91
301092.70196.06
311024.06177.36
32986.20205.84
33996.57255.64
341153.01308.00
35979.33147.99
361106.87293.43
371047.77345.19
381414.69352.29
391027.37118.14
401075.58297.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.

07

Use it

Read

In 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.

08

Check: calibration

Checkpoint

Check 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