Stop Condition
Demonstrates the stopWhen option to halt a simulation when a custom convergence condition is met — useful for Monte Carlo analysis.
What it demonstrates
stopWhencallback — custom stop condition evaluated after each eventlognormaldistribution — right-skewed sampling- Online statistics — checking convergence via coefficient of variation (CV)
stopConditionMetstatus — returned when the condition triggers
Scenario
Each event draws a random value from a lognormal distribution and records it. The simulation stops as soon as enough samples have been collected (count >= 200) and the coefficient of variation drops below a threshold.
Code
import { SimulationEngine } from 'simloop';
type Events = {
sample: Record<string, never>;
};
const CV_THRESHOLD = 0.35; // stop when CV < 35%
const MIN_SAMPLES = 200;
const sim = new SimulationEngine<Events>({
seed: 123,
logLevel: 'silent',
stopWhen: (ctx) => {
const s = ctx.stats.get('value');
if (s.count < MIN_SAMPLES) return false;
const cv = Math.sqrt(s.variance) / Math.abs(s.mean);
return cv < CV_THRESHOLD;
},
});
sim.on('sample', (_event, ctx) => {
const value = ctx.dist.lognormal(2, 0.3)();
ctx.stats.record('value', value);
// Schedule next sample at t + 1
ctx.schedule('sample', ctx.clock + 1, {});
});
sim.init((ctx) => {
ctx.schedule('sample', 0, {});
});
const result = sim.run();
const stats = result.stats['value'];
const cv = Math.sqrt(stats.variance) / Math.abs(stats.mean);
console.log(`Status: ${result.status}`); // 'stopConditionMet'
console.log(`Samples: ${stats.count}`);
console.log(`Mean: ${stats.mean.toFixed(4)}`);
console.log(`Std dev: ${Math.sqrt(stats.variance).toFixed(4)}`);
console.log(`CV: ${(cv * 100).toFixed(2)}%`);
console.log(`Sim time: ${result.finalClock}`);
console.log(`Wall clock: ${result.wallClockMs.toFixed(1)} ms`);Key takeaways
stopWhenis evaluated after each processed event — keep it lightweight- The simulation returns
status: 'stopConditionMet'when the condition triggers - Useful for optimization, steady-state detection, and Monte Carlo convergence
- The theoretical CV for
lognormal(2, 0.3)is ~0.31, so the 0.35 threshold is reachable with ~200+ samples
Last updated on