Skip to content

DOptimization · simulate.calibrate

Calibrate a scenario model to observed statistics (ABC, SMC-ABC, neural posterior)

Which values of a scenario model's uncertain inputs make it reproduce what was actually observed, and how sure can we be?

Calibrates a scenario model: the uncertain inputs you choose are treated as unknowns whose distributions are the prior, and the model is run many times to find the values that reproduce observed statistics — a mean, an SD, a percentile or the share above a threshold of any input or formula. Three algorithms: rejection ABC (keep the closest simulations, optional regression adjustment), SMC-ABC (populations that tighten the tolerance generation by generation) and neural posterior estimation (a mixture density network learns the posterior from simulations). Reports each input's posterior with 90% intervals and shrinkage, a posterior predictive check of every statistic, and a calibration check of the algorithm itself. Every draw comes from the shared random stream, so Python and R calibrate the same way.

Experimental Python and R agree to 6 decimals Seeded Also called approximate Bayesian computation, ABC, ABC rejection…

A real result

Example “Censored sales rejection”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Censored sales rejectionNo data needed
  • Censored sales adjustedNo data needed
  • Censored sales smcNo data needed
  • Censored sales npeNo data needed
  • Growth deterministic quantileNo data needed
  • Wait times sharesNo data needed
  • Invalid target nameNo data needed
  • Invalid correlated parameterNo data needed

In the guides

Where it sits in the decision guides

  • Prescriptive analytics (simulation, OR, causal RL) · DS & ML Decision Guide · Optimize / decide

Choices you make

hypothesis

Scenario model (JSON)default {"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":[]}

Inputs with distributions, decisions and formulas, as built in the Scenario studio. The calibrated inputs' distributions are their priors.

Inputs to calibratedefault base_demand, volatility

Comma-separated names of the uncertain inputs to calibrate (at most 10). Other inputs keep varying as in Monte Carlo.

Observed statistics (JSON)default [{"name":"sales","stat":"mean","value":930},{"name":"sales","stat":"sd","value":110}]

What was observed: a list of {name, stat, value}; stat is mean, sd, median, quantile (with p) or share_above (with threshold).

model

Algorithmdefault rejection

How the posterior is approximated.

  • Rejection ABC(default) — Simulate from the prior and keep the simulations closest to the observed statistics. Simple and checkable.
  • SMC-ABC — Populations of particles that move and tighten the tolerance each generation; fewer wasted simulations when the posterior is narrow.
  • Neural posterior estimation — A mixture density network learns the posterior from prior simulations, then reads it off at the observed statistics.
Scenarios per simulationdefault 50

Scenarios run at each candidate value to compute the statistics; 1 suits a model with no other uncertain inputs.

Mixture componentsdefault 4

Gaussian components in the network's posterior; more can fit skewed or multi-peaked posteriors.

Hidden unitsdefault 32

Units in each of the network's two hidden layers (tanh).

statistics

Simulationsdefault 10000

Prior draws simulated; more gives a closer tolerance for the same number kept.

Share keptdefault 0.01

Share of simulations kept as the posterior, the closest first (the tolerance is the largest kept distance).

Regression adjustmentdefault off

Shift the kept values by a weighted linear regression on the statistics (Beaumont et al. 2002), which corrects for the tolerance.

Particlesdefault 500

Particles in each SMC-ABC generation.

Generationsdefault 6

Most generations after the prior one; it stops earlier when acceptance drops below the floor.

Training simulationsdefault 2000

Prior simulations the network learns from (10% held out for early stopping).

Posterior drawsdefault 4000

Draws taken from the learned posterior at the observed statistics.

Calibration checkdefault on

Check that the algorithm's posteriors are calibrated, using simulations as stand-ins for the data (rank histogram and chi-square test).

Predictive drawsdefault 200

Posterior draws re-simulated for the posterior predictive check of each statistic.

Advanced

Tolerance quantiledefault 0.5

Each generation's tolerance is this quantile of the previous generation's distances.

Simulation budgetdefault 100000

SMC-ABC stops when it has run this many simulations in total.

Acceptance floordefault 0.02

SMC-ABC stops after a generation that accepts less than this share of its proposals.

Learning ratedefault 0.005

Adam's step size.

Check simulationsdefault 100

Simulated data sets used by the calibration check.

Optimizerdefault default

How the weights are updated. The method's own choice is the usual one.

  • Method's own(default) — Adam or AdamW, as the method describes; the usual choice.
  • Adam — Adam without decoupled weight decay (an AdamW method's weight decay is then not applied).
  • AdamW — Adam with decoupled weight decay; on an Adam method it adds decay 0.01 on weight matrices.
  • SGD with momentum — Plain gradient steps with momentum 0.9; often needs a larger learning rate and a schedule.
Learning-rate scheduledefault none

How the learning rate changes over training.

  • Constant(default) — The same learning rate every epoch (the method's default).
  • Cosine — Falls smoothly from the learning rate toward 0 over the epochs.
  • Step — Divides the learning rate by 10 after each third of the epochs.
  • One cycle — Rises from a 25th of the learning rate to the full rate over the first 30% of steps, then falls far below it.
  • Reduce on plateau — Divides the learning rate by 10 after 10 epochs without improvement in the validation loss.
Warm-up epochsdefault 0

Epochs at the start that ramp the learning rate up linearly; 0 = no warm-up.

Gradient clippingdefault 0

Largest gradient size (L2 norm over all weights) before a step; larger gradients are scaled down. 0 = off.

Weight average (EMA)default 0

Keeps a moving average of the weights (for example 0.99) and uses it for validation and the result. 0 = off.

Weight average from epoch (SWA)default 0

Averages the weights at the end of every epoch from this one on and returns the average. 0 = off; not with EMA.

Record every stepdefault off

Saves the loss, learning rate and gradient size after every batch in the training history, not only per epoch.

Compute profiledefault parity

Where and how precisely the network trains. Parity matches the other engine; the faster profiles can give slightly different numbers.

  • Parity(default) — Double precision on one CPU thread: the same numbers in Python and R, run after run (the default).
  • Faster CPU — Single precision on all performance cores; repeatable on this Mac, results differ slightly from Parity.
  • Apple GPU — Single precision on the Apple GPU (macOS 15 or later); results can differ slightly. Falls back to Faster CPU without a GPU.
Checkpoint every (epochs)default —

Saves the training state this often and when training ends, so a stopped run can resume where it was. Automatic saves about every 30 seconds; 0 = off. Each save holds the weights and the optimizer's state, so a large text encoder tuned on every layer can take 1–2 GB per fold.

options

Training epochsdefault 300

Most passes over the training simulations; training stops after 30 epochs without improvement on the held-out set.

Random seeddefault 1

Fixes the random numbers so reruns give identical results, in Python and in R.

Save posterior drawsdefault on

Write every posterior draw and its weight to posterior.parquet next to the run.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • PriorsNot checked from data: state why it holds

    The calibrated inputs' distributions are the priors: the posterior can't put weight where the prior has none.

  • Reproduces the observed statistics

    Simulations from the posterior should bring back every observed statistic (posterior predictive p of at least 0.05).

  • Calibrated algorithm

    On simulated data the true values should be spread evenly across the algorithm's posteriors (rank histogram chi-square p of at least 0.01).

What it reports

algorithm
Bayesian inference by simulation: keep the parameter values whose simulated statistics land close to the observed ones.
n_params
Bayesian inference by simulation: keep the parameter values whose simulated statistics land close to the observed ones.
n_targets
What was actually seen — a mean, SD, percentile or share above a threshold — that the calibrated model must reproduce.
replicates
What was actually seen — a mean, SD, percentile or share above a threshold — that the calibrated model must reproduce.
n_simulations
The largest distance between simulated and observed statistics that still counts as a match; smaller is closer but costlier.
n_accepted
The largest distance between simulated and observed statistics that still counts as a match; smaller is closer but costlier.
epsilon
The largest distance between simulated and observed statistics that still counts as a match; smaller is closer but costlier.
adjusted
Shifts each kept value by a weighted regression on how far its statistics missed, correcting for a nonzero tolerance.
generations
ABC in generations: particles move, are kept only within a shrinking tolerance, and are reweighted against the prior.
ess
ABC in generations: particles move, are kept only within a shrinking tolerance, and are reweighted against the prior.
stop_reason
ABC in generations: particles move, are kept only within a shrinking tolerance, and are reweighted against the prior.
acceptance_rate
The largest distance between simulated and observed statistics that still counts as a match; smaller is closer but costlier.
epochs_run
A neural network learns the posterior from simulated pairs of parameters and statistics, then reads it off at the observed data.
valid_loss
A neural network learns the posterior from simulated pairs of parameters and statistics, then reads it off at the observed data.
coverage_p_min
Simulated data sets with known true values: if the algorithm is calibrated, each true value's rank in its posterior is uniform.
primary
Bayesian inference by simulation: keep the parameter values whose simulated statistics land close to the observed ones.
primary_mean
Bayesian inference by simulation: keep the parameter values whose simulated statistics land close to the observed ones.
primary_lo
Bayesian inference by simulation: keep the parameter values whose simulated statistics land close to the observed ones.
primary_hi
Bayesian inference by simulation: keep the parameter values whose simulated statistics land close to the observed ones.

Per group, level or term: post_mean[<input>], post_sd[<input>], post_lo[<input>], post_median[<input>], post_hi[<input>], prior_mean[<input>], prior_sd[<input>], shrinkage[<input>], coverage_p[<input>], observed[<statistic>], ppc_mean[<statistic>], ppc_lo[<statistic>], ppc_hi[<statistic>], ppc_p[<statistic>], scale[<statistic>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses numpy, scipy, pandas, pyarrow, torch, codesplash; R uses jsonlite, nanoparquet, torch, codesplashr.

Default traps between the two languages

  • Both engines run the same twins (codesplash.sim.calibrate ↔ codesplashr R/sim_calibrate.R) on the scenario-model twins: prior draws, simulations, SMC picks and perturbations come from the same Wichmann–Hill stream in the same layout; normal scores use ndtri/qnorm and ndtr/pnorm, which agree to ~1e-15, so a keep-or-reject decision could only change if a distance fell within that of the tolerance — not seen in practice.
  • Neural posterior estimation trains the same mixture density network on LibTorch in double precision on one thread in both engines (initial weights from the shared stream, Adam written out with torch's arithmetic, full-batch steps). Python's and R's torch ship different LibTorch builds, so single kernels can differ by an ulp; on the fixtures every value agrees to about 1e-12 relative (measured).
Python

The exact script CodeSplash ran for example “Censored sales rejection” · 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,
})
R

The exact script CodeSplash ran for example “Censored sales rejection” · 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
))

Sources

  • Pritchard, J. K., Seielstad, M. T., Perez-Lezaun, A., & Feldman, M. W. (1999). Population growth of human Y chromosomes: a study of Y chromosome microsatellites. Molecular Biology and Evolution, 16(12), 1791–1798.
  • Beaumont, M. A., Zhang, W., & Balding, D. J. (2002). Approximate Bayesian computation in population genetics. Genetics, 162(4), 2025–2035.
  • Beaumont, M. A., Cornuet, J.-M., Marin, J.-M., & Robert, C. P. (2009). Adaptive approximate Bayesian computation. Biometrika, 96(4), 983–990.
  • Papamakarios, G., & Murray, I. (2016). Fast ε-free inference of simulation models with Bayesian conditional density estimation. Advances in Neural Information Processing Systems 29.
  • Bishop, C. M. (1994). Mixture density networks. Technical report NCRG/94/004, Aston University.
  • Talts, S., Betancourt, M., Simpson, D., Vehtari, A., & Gelman, A. (2018). Validating Bayesian inference algorithms with simulation-based calibration. arXiv:1804.06788.
  • Sisson, S. A., Fan, Y., & Beaumont, M. A. (Eds.) (2018). Handbook of Approximate Bayesian Computation. CRC Press.

From the CodeSplash method registry · simulate.calibrate v1.1.0.