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.
A real result
Example “Censored sales rejection”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Calibrated 2 input(s) to 2 observed statistic(s) by rejection ABC (3,000 simulations of 30 scenario(s) each): base_demand 1080 (90% 960.1 to 1254); volatility 259.4 (90% 150.9 to 381.7).
- base_demand (posterior mean)
- 1080.43
- volatility (posterior mean)
- 259.36
Plots
View data
| curve | density | base_demand |
|---|---|---|
| prior | 0.0005 | 509.26 |
| prior | 0.0006 | 515.84 |
| prior | 0.0006 | 522.43 |
| prior | 0.0007 | 529.01 |
| prior | 0.0007 | 535.60 |
| prior | 0.0008 | 542.18 |
| prior | 0.0008 | 548.77 |
| prior | 0.0008 | 555.35 |
| prior | 0.0009 | 561.94 |
| prior | 0.0009 | 568.52 |
| prior | 0.0009 | 575.11 |
| prior | 0.0009 | 581.69 |
| prior | 0.0009 | 588.28 |
| prior | 0.0010 | 594.86 |
| prior | 0.0010 | 601.45 |
| prior | 0.0010 | 608.03 |
| prior | 0.0010 | 614.62 |
| prior | 0.0010 | 621.20 |
| prior | 0.0010 | 627.79 |
| prior | 0.0010 | 634.37 |
| prior | 0.0010 | 640.96 |
| prior | 0.0010 | 647.54 |
| prior | 0.0010 | 654.13 |
| prior | 0.0010 | 660.71 |
| prior | 0.0010 | 667.30 |
| prior | 0.0010 | 673.88 |
| prior | 0.0010 | 680.47 |
| prior | 0.0010 | 687.05 |
| prior | 0.0011 | 693.64 |
| prior | 0.0011 | 700.22 |
| prior | 0.0011 | 706.81 |
| prior | 0.0011 | 713.39 |
| prior | 0.0011 | 719.98 |
| prior | 0.0011 | 726.56 |
| prior | 0.0011 | 733.15 |
| prior | 0.0011 | 739.73 |
| prior | 0.0011 | 746.32 |
| prior | 0.0010 | 752.90 |
| prior | 0.0010 | 759.49 |
| prior | 0.0010 | 766.07 |
| prior | 0.0010 | 772.66 |
| prior | 0.0010 | 779.24 |
| prior | 0.0010 | 785.83 |
| prior | 0.0010 | 792.41 |
| prior | 0.0010 | 799.00 |
| prior | 0.0010 | 805.58 |
| prior | 0.0010 | 812.17 |
| prior | 0.0010 | 818.75 |
| prior | 0.0010 | 825.34 |
| prior | 0.0010 | 831.92 |
| prior | 0.0010 | 838.50 |
| prior | 0.0010 | 845.09 |
| prior | 0.0010 | 851.67 |
| prior | 0.0010 | 858.26 |
| prior | 0.0010 | 864.84 |
| prior | 0.0010 | 871.43 |
| prior | 0.0010 | 878.01 |
| prior | 0.0010 | 884.60 |
| prior | 0.0010 | 891.18 |
| prior | 0.0010 | 897.77 |
First 60 of 300 rows.
View data
| curve | density | volatility |
|---|---|---|
| prior | 0.0015 | 48.812 |
| prior | 0.0017 | 51.677 |
| prior | 0.0019 | 54.543 |
| prior | 0.0021 | 57.409 |
| prior | 0.0023 | 60.275 |
| prior | 0.0024 | 63.140 |
| prior | 0.0025 | 66.006 |
| prior | 0.0026 | 68.872 |
| prior | 0.0027 | 71.737 |
| prior | 0.0028 | 74.603 |
| prior | 0.0028 | 77.469 |
| prior | 0.0029 | 80.334 |
| prior | 0.0029 | 83.200 |
| prior | 0.0029 | 86.066 |
| prior | 0.0029 | 88.932 |
| prior | 0.0029 | 91.797 |
| prior | 0.0029 | 94.663 |
| prior | 0.0029 | 97.529 |
| prior | 0.0029 | 100.39 |
| prior | 0.0029 | 103.26 |
| prior | 0.0029 | 106.13 |
| prior | 0.0029 | 108.99 |
| prior | 0.0029 | 111.86 |
| prior | 0.0030 | 114.72 |
| prior | 0.0030 | 117.59 |
| prior | 0.0030 | 120.45 |
| prior | 0.0030 | 123.32 |
| prior | 0.0030 | 126.19 |
| prior | 0.0030 | 129.05 |
| prior | 0.0030 | 131.92 |
| prior | 0.0030 | 134.78 |
| prior | 0.0030 | 137.65 |
| prior | 0.0030 | 140.51 |
| prior | 0.0030 | 143.38 |
| prior | 0.0030 | 146.25 |
| prior | 0.0030 | 149.11 |
| prior | 0.0030 | 151.98 |
| prior | 0.0030 | 154.84 |
| prior | 0.0030 | 157.71 |
| prior | 0.0029 | 160.57 |
| prior | 0.0029 | 163.44 |
| prior | 0.0029 | 166.31 |
| prior | 0.0029 | 169.17 |
| prior | 0.0029 | 172.04 |
| prior | 0.0029 | 174.90 |
| prior | 0.0029 | 177.77 |
| prior | 0.0029 | 180.63 |
| prior | 0.0028 | 183.50 |
| prior | 0.0028 | 186.37 |
| prior | 0.0028 | 189.23 |
| prior | 0.0028 | 192.10 |
| prior | 0.0028 | 194.96 |
| prior | 0.0028 | 197.83 |
| prior | 0.0028 | 200.69 |
| prior | 0.0028 | 203.56 |
| prior | 0.0028 | 206.43 |
| prior | 0.0028 | 209.29 |
| prior | 0.0029 | 212.16 |
| prior | 0.0029 | 215.02 |
| prior | 0.0029 | 217.89 |
First 60 of 300 rows.
View data
| Bin end | mean of sales | Simulations |
|---|---|---|
| 845.16 | 840.42 | 2 |
| 849.90 | 845.16 | 0 |
| 854.63 | 849.90 | 1 |
| 859.37 | 854.63 | 0 |
| 864.10 | 859.37 | 0 |
| 868.84 | 864.10 | 1 |
| 873.58 | 868.84 | 0 |
| 878.31 | 873.58 | 1 |
| 883.05 | 878.31 | 1 |
| 887.78 | 883.05 | 0 |
| 892.52 | 887.78 | 1 |
| 897.26 | 892.52 | 2 |
| 901.99 | 897.26 | 2 |
| 906.73 | 901.99 | 3 |
| 911.46 | 906.73 | 4 |
| 916.20 | 911.46 | 4 |
| 920.94 | 916.20 | 4 |
| 925.67 | 920.94 | 3 |
| 930.41 | 925.67 | 6 |
| 935.14 | 930.41 | 4 |
| 939.88 | 935.14 | 2 |
| 944.62 | 939.88 | 4 |
| 949.35 | 944.62 | 2 |
| 954.09 | 949.35 | 3 |
| 958.82 | 954.09 | 2 |
| 963.56 | 958.82 | 3 |
| 968.30 | 963.56 | 1 |
| 973.03 | 968.30 | 2 |
| 977.77 | 973.03 | 1 |
| 982.50 | 977.77 | 1 |
View data
| Bin end | SD of sales | Simulations |
|---|---|---|
| 69.877 | 62.711 | 4 |
| 77.044 | 69.877 | 3 |
| 84.210 | 77.044 | 2 |
| 91.376 | 84.210 | 6 |
| 98.542 | 91.376 | 3 |
| 105.71 | 98.542 | 4 |
| 112.87 | 105.71 | 4 |
| 120.04 | 112.87 | 3 |
| 127.21 | 120.04 | 5 |
| 134.37 | 127.21 | 3 |
| 141.54 | 134.37 | 8 |
| 148.70 | 141.54 | 6 |
| 155.87 | 148.70 | 1 |
| 163.04 | 155.87 | 1 |
| 170.20 | 163.04 | 1 |
| 177.37 | 170.20 | 0 |
| 184.53 | 177.37 | 2 |
| 191.70 | 184.53 | 1 |
| 198.87 | 191.70 | 0 |
| 206.03 | 198.87 | 1 |
| 213.20 | 206.03 | 0 |
| 220.36 | 213.20 | 1 |
| 227.53 | 220.36 | 0 |
| 234.70 | 227.53 | 0 |
| 241.86 | 234.70 | 0 |
| 249.03 | 241.86 | 0 |
| 256.20 | 249.03 | 0 |
| 263.36 | 256.20 | 0 |
| 270.53 | 263.36 | 0 |
| 277.69 | 270.53 | 1 |
View data
| share |
|---|
| 0.1250 |
| 0.0750 |
| 0.0750 |
| 0.1125 |
| 0.0625 |
| 0.1250 |
| 0.1625 |
| 0.1000 |
| 0.1000 |
| 0.0625 |
Assumptions
- Priors — Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight.
- Reproduces the observed statistics — Simulations from the posterior bring back every observed statistic (smallest p = 0.83).
- Calibrated algorithm — On 40 simulated data sets the true values spread evenly across the posteriors (smallest rank-test p = 0.74, base_demand).
Calibrated inputs
| Input | Prior mean | Prior SD | Posterior mean | Posterior SD | 5% | Median | 95% | Shrinkage | Calibration p |
|---|---|---|---|---|---|---|---|---|---|
| base_demand | 1003.93 | 291.54 | 1080.43 | 83.522 | 960.11 | 1071.88 | 1253.55 | 91.8% | 0.7399 |
| volatility | 220.88 | 101.49 | 259.36 | 64.352 | 150.95 | 248.19 | 381.66 | 59.8% | 0.7399 |
Observed statistics and the posterior predictive check
| Statistic | Observed | Predicted mean | 5% | 95% | Predictive p | Distance scale |
|---|---|---|---|---|---|---|
| mean of sales | 930 | 924.41 | 866.78 | 968.93 | 0.9000 | 139.64 |
| SD of sales | 110 | 122.65 | 66.156 | 191.43 | 0.8333 | 112.23 |
Posterior draws (60, equally weighted)
| Draw | base_demand | volatility |
|---|---|---|
| 1 | 999.36 | 188.95 |
| 2 | 1108.76 | 331.85 |
| 3 | 1072.09 | 237.98 |
| 4 | 985.63 | 150.95 |
| 5 | 1039.59 | 208.36 |
| 6 | 1063.43 | 246.54 |
| 7 | 1058.38 | 266.61 |
| 8 | 1102.92 | 291.22 |
| 9 | 1001.92 | 238.51 |
| 10 | 1100.10 | 312.53 |
| 11 | 990.76 | 206.97 |
| 12 | 1094.76 | 295.84 |
| 13 | 1291.17 | 391.38 |
| 14 | 1013.07 | 248.19 |
| 15 | 1134.36 | 288.00 |
| 16 | 1010.65 | 212.86 |
| 17 | 1164.26 | 315.51 |
| 18 | 1016.78 | 262.19 |
| 19 | 1028.44 | 240.75 |
| 20 | 1095.42 | 243.83 |
| 21 | 1179.72 | 319.10 |
| 22 | 1134.09 | 299.82 |
| 23 | 1203.35 | 326.00 |
| 24 | 1145.29 | 296.43 |
| 25 | 974.97 | 198.99 |
| 26 | 1050.68 | 262.91 |
| 27 | 1212.67 | 317.73 |
| 28 | 951.02 | 191.74 |
| 29 | 1097.59 | 258.20 |
| 30 | 1055.35 | 264.88 |
| 31 | 1031.93 | 226.28 |
| 32 | 1012.32 | 250.19 |
| 33 | 1053.30 | 206.85 |
| 34 | 1139.36 | 253.21 |
| 35 | 1113.71 | 274.23 |
| 36 | 1043.01 | 203.30 |
| 37 | 1278.05 | 377.88 |
| 38 | 1073.66 | 240.87 |
| 39 | 1182.54 | 370.35 |
| 40 | 969.44 | 187.97 |
First 40 of 60 rows.
- The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation).
- Rejection ABC kept the 60 simulations closest to the observed statistics (tolerance 0.1264).
- The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.
Calibrated 2 input(s) to 2 observed statistic(s) by rejection ABC (3,000 simulations of 30 scenario(s) each): base_demand 1080 (90% 960.1 to 1254); volatility 259.4 (90% 150.9 to 381.7).
- base_demand (posterior mean)
- 1080.43
- volatility (posterior mean)
- 259.36
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Priors — Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight.
- Reproduces the observed statistics — Simulations from the posterior bring back every observed statistic (smallest p = 0.83).
- Calibrated algorithm — On 40 simulated data sets the true values spread evenly across the posteriors (smallest rank-test p = 0.74, base_demand).
Calibrated inputs
| Input | Prior mean | Prior SD | Posterior mean | Posterior SD | 5% | Median | 95% | Shrinkage | Calibration p |
|---|---|---|---|---|---|---|---|---|---|
| base_demand | 1003.93 | 291.54 | 1080.43 | 83.522 | 960.11 | 1071.88 | 1253.55 | 91.8% | 0.7399 |
| volatility | 220.88 | 101.49 | 259.36 | 64.352 | 150.95 | 248.19 | 381.66 | 59.8% | 0.7399 |
Observed statistics and the posterior predictive check
| Statistic | Observed | Predicted mean | 5% | 95% | Predictive p | Distance scale |
|---|---|---|---|---|---|---|
| mean of sales | 930 | 924.41 | 866.78 | 968.93 | 0.9000 | 139.64 |
| SD of sales | 110 | 122.65 | 66.156 | 191.43 | 0.8333 | 112.23 |
Posterior draws (60, equally weighted)
| Draw | base_demand | volatility |
|---|---|---|
| 1 | 999.36 | 188.95 |
| 2 | 1108.76 | 331.85 |
| 3 | 1072.09 | 237.98 |
| 4 | 985.63 | 150.95 |
| 5 | 1039.59 | 208.36 |
| 6 | 1063.43 | 246.54 |
| 7 | 1058.38 | 266.61 |
| 8 | 1102.92 | 291.22 |
| 9 | 1001.92 | 238.51 |
| 10 | 1100.10 | 312.53 |
| 11 | 990.76 | 206.97 |
| 12 | 1094.76 | 295.84 |
| 13 | 1291.17 | 391.38 |
| 14 | 1013.07 | 248.19 |
| 15 | 1134.36 | 288.00 |
| 16 | 1010.65 | 212.86 |
| 17 | 1164.26 | 315.51 |
| 18 | 1016.78 | 262.19 |
| 19 | 1028.44 | 240.75 |
| 20 | 1095.42 | 243.83 |
| 21 | 1179.72 | 319.10 |
| 22 | 1134.09 | 299.82 |
| 23 | 1203.35 | 326.00 |
| 24 | 1145.29 | 296.43 |
| 25 | 974.97 | 198.99 |
| 26 | 1050.68 | 262.91 |
| 27 | 1212.67 | 317.73 |
| 28 | 951.02 | 191.74 |
| 29 | 1097.59 | 258.20 |
| 30 | 1055.35 | 264.88 |
| 31 | 1031.93 | 226.28 |
| 32 | 1012.32 | 250.19 |
| 33 | 1053.30 | 206.85 |
| 34 | 1139.36 | 253.21 |
| 35 | 1113.71 | 274.23 |
| 36 | 1043.01 | 203.30 |
| 37 | 1278.05 | 377.88 |
| 38 | 1073.66 | 240.87 |
| 39 | 1182.54 | 370.35 |
| 40 | 969.44 | 187.97 |
First 40 of 60 rows.
- The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation).
- Rejection ABC kept the 60 simulations closest to the observed statistics (tolerance 0.1264).
- The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.
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).
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,
})
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.