LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
ldes_stats.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 */
5#ifndef LINE_SOLVERS_LDES_LDES_STATS_H
6#define LINE_SOLVERS_LDES_LDES_STATS_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * The estimators of the native LDES engine: running integrals, the MSER-5
12 * warmup filter, and the batch-means confidence intervals.
13 *
14 * THE INTEGRALS ARE LAZY. `tot_qlen(i,r)` is the time integral of the class-r
15 * queue length at station i, advanced only when that pair CHANGES. Advancing
16 * every pair on every event would be O(M*K) per event on a hot loop where the
17 * event touches one pair; the reference does the same thing with
18 * `lastQueueUpdateTime`, and the invariant is that `update_qlen` is called
19 * BEFORE any write to `qlen`, never after.
20 *
21 * THE WARMUP FILTER IS MSER-5 over EVENT-SPACED observations, not time-spaced
22 * ones. That matters for what the estimators may then do with the series: an
23 * unweighted mean of per-interval averages overweights congested epochs,
24 * because a congested epoch contains more events and therefore more intervals
25 * per unit time. So the means below are integral DIFFERENCES over elapsed
26 * time, and only the CI -- which needs a sequence of comparable observations,
27 * not a mean -- reads the per-interval series directly.
28 */
29
30#include <algorithm>
31#include <cmath>
32#include <cstddef>
33#include <cstdint>
34#include <limits>
35#include <string>
36#include <vector>
37
40#include "line/util/matrix.h"
41
42namespace line {
43namespace ldes {
44namespace engine {
45
46/** The running per-(station, class) integrals and tallies. */
47struct Accum {
48 Accum(std::size_t M, std::size_t K)
49 : qlen(M, std::vector<double>(K, 0.0)),
50 held(M, std::vector<double>(K, 0.0)),
51 busy(M, std::vector<double>(K, 0.0)),
52 tot_qlen(M, std::vector<double>(K, 0.0)),
53 tot_busy(M, std::vector<double>(K, 0.0)),
54 last_qlen(M, std::vector<double>(K, 0.0)),
55 last_busy(M, std::vector<double>(K, 0.0)),
56 busy_scale(M, 1.0),
57 util_peak(M, 1.0),
58 resp_sum(M, std::vector<double>(K, 0.0)),
59 resp_cnt(M, std::vector<double>(K, 0.0)),
60 resp_avg(M, std::vector<double>(K, 0.0)),
61 resp_m2(M, std::vector<double>(K, 0.0)),
62 completed(M, std::vector<double>(K, 0.0)),
63 arrived(M, std::vector<double>(K, 0.0)),
64 join_dropped(M, std::vector<double>(K, 0.0)) {}
65
66 /** Advance the queue-length integral of (i,r) to `now`. Call BEFORE writing qlen. */
67 void update_qlen(std::size_t i, std::size_t r, double now) {
68 const double dt = now - last_qlen[i][r];
69 if (dt > 0.0) tot_qlen[i][r] += (qlen[i][r] + held[i][r]) * dt;
70 last_qlen[i][r] = now;
71 }
72 /**
73 * Advance the busy-server integral of (i,r) to `now`. Call BEFORE writing busy.
74 *
75 * The integrand is the WORK being delivered, `busy * busy_scale`, not the
76 * head count: a load-dependent server running alpha(n) times faster does the
77 * same work in less time, so plain busy TIME reads it as no busier than one
78 * at its nominal rate. `busy_scale` is 1 unless the station is load
79 * dependent, so this is the identity everywhere else.
80 */
81 void update_busy(std::size_t i, std::size_t r, double now) {
82 const double dt = now - last_busy[i][r];
83 if (dt > 0.0) tot_busy[i][r] += busy[i][r] * busy_scale[i] * dt;
84 last_busy[i][r] = now;
85 }
86 /**
87 * Install the load-dependent speed station `i` runs at from `now` on.
88 *
89 * Flushes every class FIRST, so the interval that just ended is credited at
90 * the scale that was actually in force over it. The engine calls this after
91 * the population is written, from the same chokepoint that re-times the
92 * departures.
93 */
94 void set_busy_scale(std::size_t i, double v, double now) {
95 if (v == busy_scale[i]) return;
96 for (std::size_t r = 0; r < busy[i].size(); ++r) update_busy(i, r, now);
97 busy_scale[i] = v;
98 }
99
100 std::vector<std::vector<double>> qlen;
101 /**
102 * Callers parked on their server awaiting a synchronous REPLY (sn.syncreply), per (station, class).
103 *
104 * They are counted in the QLen INTEGRAL, as the reference counts currentBlockedServers in
105 * Solver_ssj.updateQueueStats, but kept OUT of `qlen`, which every decision reads: capacity,
106 * load-dependent rates, JSQ and setup all use currentQueueLength there, which excludes them.
107 * Written only after update_qlen, like qlen.
108 */
109 std::vector<std::vector<double>> held;
110 std::vector<std::vector<double>> busy;
111 std::vector<std::vector<double>> tot_qlen, tot_busy;
112 std::vector<std::vector<double>> last_qlen, last_busy;
113 /**
114 * The speed each station is running at right now (load dependence only),
115 * and the peak capacity that normalizes its utilization,
116 * max(c, max(alpha)).
117 *
118 * `util_peak` is CTMC's own `ceff`, which is what makes LDES report the same
119 * utilization as the analytic solvers on a load-dependent station. Both are
120 * 1 and c respectively when the station is not load dependent, leaving every
121 * other model's numbers untouched.
122 */
123 std::vector<double> busy_scale, util_peak;
124 std::vector<std::vector<double>> resp_sum, resp_cnt, completed;
125 /**
126 * Running mean and sum of squared deviations of the response times, for the
127 * iid interval the reference takes off its response-time Tally. Updated as
128 * SSJ's `Tally.add` updates `curAverage`/`curSum2` (Welford), so the variance
129 * is the reference's to the last bit rather than the sum-of-squares form,
130 * which differed by ~2.5e-10 relative and cancels badly on long runs
131 * (closed 2026-11-14).
132 */
133 std::vector<std::vector<double>> resp_avg, resp_m2;
134 /** Tally one response time `x` at (i,r): the sum, the running moments and the count move together. */
135 void tally_resp(std::size_t i, std::size_t r, double x) {
136 resp_sum[i][r] += x;
137 resp_cnt[i][r] += 1.0;
138 const double y = x - resp_avg[i][r];
139 resp_avg[i][r] += y / resp_cnt[i][r];
140 resp_m2[i][r] += y * (x - resp_avg[i][r]);
141 }
142 /**
143 * Jobs that ARRIVED at each (station, class), which is not what `completed`
144 * counts: the reference reports AN as the arrivals after the truncation point
145 * over the truncated window (cumulative, differenced like `completed`), and the
146 * two differ by whatever is still in the station at the end and by anything
147 * dropped, balked or reneged. Reporting completions as the arrival rate
148 * would hide exactly the loss those features exist to measure.
149 */
150 std::vector<std::vector<double>> arrived;
151 /**
152 * Siblings a QUORUM Join discarded, per (station, class): a sibling that
153 * reaches the Join after its parent already fired lost the race and is
154 * thrown away. It is a completion of nothing, so it belongs neither in
155 * `completed` nor in `arrived`, and it is what a Join row's loss rate is.
156 * Cumulative, and differenced against the truncation point like `completed`.
157 */
158 std::vector<std::vector<double>> join_dropped;
159};
160
161/**
162 * MSER-5 truncation point over a series of observations, in BATCHES.
163 *
164 * Returns the batch index d minimising var(Z_{d..N-1}) / (N-d)^2 over the
165 * batch means Z, and 0 when there are fewer than four batches -- below that
166 * the criterion is estimated from too few terms to be a truncation rule.
167 * Transcribes `computeMSER5TruncationPoint`.
168 */
169inline int mser5_truncation(const std::vector<double>& obs, int batch_size) {
170 const std::size_t n = obs.size();
171 if (batch_size <= 0 || n < static_cast<std::size_t>(batch_size) * 4) return 0;
172 const int num_batches = static_cast<int>(n / static_cast<std::size_t>(batch_size));
173 std::vector<double> means(static_cast<std::size_t>(num_batches), 0.0);
174 for (int j = 0; j < num_batches; ++j) {
175 double sum = 0.0;
176 for (int i = 0; i < batch_size; ++i)
177 sum += obs[static_cast<std::size_t>(j * batch_size + i)];
178 means[static_cast<std::size_t>(j)] = sum / batch_size;
179 }
180 double min_mser = std::numeric_limits<double>::max();
181 int optimal_d = 0;
182 const int max_d = num_batches / 2;
183 for (int d = 0; d < max_d; ++d) {
184 const int remaining = num_batches - d;
185 if (remaining < 2) break;
186 double sum = 0.0;
187 for (int j = d; j < num_batches; ++j) sum += means[static_cast<std::size_t>(j)];
188 const double mean = sum / remaining;
189 double variance = 0.0;
190 for (int j = d; j < num_batches; ++j) {
191 const double diff = means[static_cast<std::size_t>(j)] - mean;
192 variance += diff * diff;
193 }
194 variance /= (remaining - 1);
195 const double mser = variance / (static_cast<double>(remaining) * remaining);
196 if (mser < min_mser) {
197 min_mser = mser;
198 optimal_d = d;
199 }
200 }
201 return optimal_d;
202}
203
204/** Where the warmup ended, and whether a truncation was applied at all. */
206 std::size_t index = 0; ///< observation index of the truncation point
207 double warmup_end = 0.0; ///< the instant of that observation
208 bool applied = false;
209};
210
211/** The event-spaced observation series MSER-5 and the CI both read. */
213 Observations(std::size_t M, std::size_t K, bool mser_on, int batch)
214 : enabled(mser_on),
215 batch_size(batch),
216 qlen(M, std::vector<std::vector<double>>(K)),
217 qt(M, std::vector<std::vector<double>>(K)),
218 bt(M, std::vector<std::vector<double>>(K)),
219 cmp(M, std::vector<std::vector<double>>(K)),
220 drp(M, std::vector<std::vector<double>>(K)),
221 arv(M, std::vector<std::vector<double>>(K)),
222 last_qt(M, std::vector<double>(K, 0.0)),
223 in_mser(M, static_cast<char>(1)),
224 sys(K),
225 nstations(M),
226 nclasses(K) {}
227
228 /**
229 * Record one observation.
230 *
231 * The queue-length entry is the INTERVAL TIME-AVERAGE, not the instantaneous
232 * count: it is the integral delivered since the previous observation over
233 * the interval length, which is what makes a sequence of them comparable
234 * even though the intervals differ in duration. The other three are
235 * CUMULATIVE, because the estimators difference them against the truncation
236 * point rather than averaging them.
237 */
238 void collect(const Accum& acc, double now) { collect(acc, now, acc.arrived); }
239
240 /**
241 * Record one observation, reading the arrival counters from `arrived`.
242 *
243 * The reference takes its observation INSIDE the completion that triggers
244 * it (`checkEventCountStop` in `departureActions`): after the completion is
245 * counted and before the departing job is routed, so the arrival it causes
246 * downstream belongs to the NEXT observation. This loop observes after the
247 * whole event, so it passes the arrival counters as they stood when the
248 * event began; every other series is a time integral or a completion count
249 * and reads the same at either point (closed 2026-11-14).
250 */
251 void collect(const Accum& acc, double now, const std::vector<std::vector<double>>& arrived) {
252 const double dt = now - last_time;
253 time.push_back(now);
254 for (std::size_t i = 0; i < nstations; ++i)
255 for (std::size_t r = 0; r < nclasses; ++r) {
256 if (dt > 0.0) {
257 qlen[i][r].push_back((acc.tot_qlen[i][r] - last_qt[i][r]) / dt);
258 last_qt[i][r] = acc.tot_qlen[i][r];
259 } else {
260 qlen[i][r].push_back(acc.qlen[i][r]);
261 }
262 qt[i][r].push_back(acc.tot_qlen[i][r]);
263 bt[i][r].push_back(acc.tot_busy[i][r]);
264 cmp[i][r].push_back(acc.completed[i][r]);
265 drp[i][r].push_back(acc.join_dropped[i][r]);
266 arv[i][r].push_back(arrived[i][r]);
267 }
268 last_time = now;
269 }
270
271 /**
272 * Record the cumulative SYSTEM completions per class beside the observation
273 * just taken, so an open class's system XN can difference them against the
274 * truncation point over the same window its denominator spans, as the
275 * per-station completions are (Java `systemCompletionObservations`).
276 */
277 void collect_system(const std::vector<double>& completed) {
278 for (std::size_t r = 0; r < nclasses && r < completed.size(); ++r)
279 sys[r].push_back(completed[r]);
280 }
281
282 /**
283 * The truncation point, on the AGGREGATE queue length first.
284 *
285 * The per-series fallback is not a refinement, it is the closed-network
286 * case: a closed model holds a constant total population, so the aggregate
287 * series is flat and carries no transient signal at all, however long the
288 * warmup actually was. The most conservative per-series point is taken then.
289 *
290 * BOTH RUN OVER THE SERVICE STATIONS ONLY, which is the range
291 * `applyMSER5Truncation` walks. A Join is measured like a station but is
292 * not one of them, and folding its series in would move the truncation
293 * point of every fork-join model away from the reference's.
294 */
296 Truncation t;
297 if (!enabled || time.empty()) return t;
298 std::vector<double> aggregate(time.size(), 0.0);
299 for (std::size_t k = 0; k < time.size(); ++k) {
300 double tot = 0.0;
301 for (std::size_t i = 0; i < nstations; ++i) {
302 if (!in_mser[i]) continue;
303 for (std::size_t r = 0; r < nclasses; ++r)
304 if (k < qlen[i][r].size()) tot += qlen[i][r][k];
305 }
306 aggregate[k] = tot;
307 }
308 int batch = mser5_truncation(aggregate, batch_size);
309 if (batch == 0) {
310 for (std::size_t i = 0; i < nstations; ++i) {
311 if (!in_mser[i]) continue;
312 for (std::size_t r = 0; r < nclasses; ++r) {
313 const int b = mser5_truncation(qlen[i][r], batch_size);
314 if (b > batch) batch = b;
315 }
316 }
317 }
318 const std::size_t idx =
319 static_cast<std::size_t>(batch) * static_cast<std::size_t>(batch_size);
320 // warmup_end is the instant the WHOLE-RUN counters (system XN, region
321 // and orbit integrals, reneging rate) are divided from, and the
322 // reference's applyMSER5Truncation moves warmupEndTime only for a
323 // POSITIVE truncation index, leaving it at 0 otherwise. The per-station
324 // window still opens at time[index] (time[0] included), since
325 // mserWindowRate differences against that observation. Reading time[0]
326 // here put system XN 0.09% above the reference on every open model that
327 // MSER did not truncate (closed 2026-11-14).
328 if (idx < time.size()) {
329 t.index = idx;
330 t.warmup_end = (idx > 0) ? time[idx] : 0.0;
331 t.applied = true;
332 }
333 return t;
334 }
335
336 bool enabled = true;
337 int batch_size = 5;
338 std::vector<double> time;
339 std::vector<std::vector<std::vector<double>>> qlen, qt, bt, cmp, drp, arv;
340 std::vector<std::vector<double>> last_qt;
341 /// Whether station i feeds the truncation criterion; every one is still recorded.
342 std::vector<char> in_mser;
343 /// Cumulative system completions per class, one entry per observation.
344 std::vector<std::vector<double>> sys;
345 double last_time = 0.0;
346 std::size_t nstations = 0, nclasses = 0;
347};
348
349/** Grand mean, standard error and degrees of freedom of a batch-means estimate. */
351 double mean = 0.0;
352 double stderr_ = 0.0;
353 int df = 0;
354 bool ok = false;
355};
356
357/**
358 * The variance inflation of OVERLAPPING batch means.
359 *
360 * Overlapping batches are positively correlated, so the naive sample variance
361 * of their means underestimates the true one; 4/3 is the standard asymptotic
362 * correction at 50% overlap, interpolated linearly below it and reducing to 1
363 * at zero overlap, where the batches are disjoint and no correction is due.
364 * Transcribes `computeOverlapAdjustmentFactor`.
365 */
366inline double overlap_adjustment(double overlap) {
367 if (overlap <= 0.0) return 1.0;
368 if (overlap >= 0.5) return 4.0 / 3.0;
369 return 1.0 + (overlap / 0.5) * (4.0 / 3.0 - 1.0);
370}
371
372/** Non-overlapping batch means. Transcribes `computeBMStatisticsInternal`. */
373inline StatTriple bm_statistics(const std::vector<double>& obs, int batch_size) {
374 StatTriple s;
375 const std::size_t n = obs.size();
376 const int nb = (batch_size > 0) ? static_cast<int>(n / static_cast<std::size_t>(batch_size)) : 0;
377 if (nb < 2) return s;
378 std::vector<double> means(static_cast<std::size_t>(nb), 0.0);
379 for (int i = 0; i < nb; ++i) {
380 double sum = 0.0;
381 for (int j = 0; j < batch_size; ++j)
382 sum += obs[static_cast<std::size_t>(i * batch_size + j)];
383 means[static_cast<std::size_t>(i)] = sum / batch_size;
384 }
385 double grand = 0.0;
386 for (int i = 0; i < nb; ++i) grand += means[static_cast<std::size_t>(i)];
387 grand /= nb;
388 double ss = 0.0;
389 for (int i = 0; i < nb; ++i) {
390 const double d = means[static_cast<std::size_t>(i)] - grand;
391 ss += d * d;
392 }
393 s.mean = grand;
394 s.stderr_ = std::sqrt((ss / (nb - 1)) / nb);
395 s.df = nb - 1;
396 s.ok = true;
397 return s;
398}
399
400/** Overlapping batch means. Transcribes `computeOBMStatisticsInternal`. */
401inline StatTriple obm_statistics(const std::vector<double>& obs, int batch_size, double overlap) {
402 StatTriple s;
403 const std::size_t n = obs.size();
404 if (batch_size <= 0 || n < static_cast<std::size_t>(batch_size) * 2) return s;
405 int step = static_cast<int>(batch_size * (1.0 - overlap));
406 if (step < 1) step = 1;
407 const int nb = static_cast<int>((n - static_cast<std::size_t>(batch_size)) /
408 static_cast<std::size_t>(step)) + 1;
409 if (nb < 2) return s;
410 std::vector<double> means(static_cast<std::size_t>(nb), 0.0);
411 for (int i = 0; i < nb; ++i) {
412 const std::size_t start = static_cast<std::size_t>(i) * static_cast<std::size_t>(step);
413 double sum = 0.0;
414 for (int j = 0; j < batch_size; ++j)
415 if (start + static_cast<std::size_t>(j) < n) sum += obs[start + static_cast<std::size_t>(j)];
416 means[static_cast<std::size_t>(i)] = sum / batch_size;
417 }
418 double grand = 0.0;
419 for (int i = 0; i < nb; ++i) grand += means[static_cast<std::size_t>(i)];
420 grand /= nb;
421 double ss = 0.0;
422 for (int i = 0; i < nb; ++i) {
423 const double d = means[static_cast<std::size_t>(i)] - grand;
424 ss += d * d;
425 }
426 const double adj = overlap_adjustment(overlap);
427 s.mean = grand;
428 s.stderr_ = std::sqrt((adj * ss / (nb - 1)) / nb);
429 s.df = static_cast<int>((nb - 1) / adj);
430 if (s.df < 1) s.df = 1;
431 s.ok = true;
432 return s;
433}
434
435/**
436 * The two-sided t critical value at confidence `level` with `df` degrees of freedom: the EXACT Student-t
437 * quantile t_{(1+level)/2, df}, as the Java engine's `Solver_ssj.getTCriticalValue` computes it.
438 *
439 * Both engines used a three-decimal table, bucketed to the 90/95/99% levels and saturating at df = 30, until
440 * 2026-10-28; that moved every half-width by parts in a thousand and kept df > 30 from tending to the normal
441 * quantile. Below one degree of freedom there is no t law, and the normal quantile at the same level stands in.
442 */
443inline double t_critical(double level, int df) {
444 const double p = 0.5 + 0.5 * level;
445 if (df < 1) return sim::sim_norminv(p);
446 return sim::sim_tinv(p, static_cast<double>(df));
447}
448
449
450/**
451 * Heidelberger-Welch spectral estimate of the variance of the sample mean.
452 *
453 * The variance of a mean over a correlated series is 2*pi*S(0)/m, with S(0)
454 * the spectral density at frequency zero. S(0) cannot be read off the
455 * periodogram directly -- the ordinate at f=0 is exactly the quantity being
456 * estimated and carries all the bias -- so the LOG-periodogram over the lowest
457 * frequencies is fitted with a quadratic and the intercept extrapolated back
458 * to zero. That is what makes this estimator different from batch means rather
459 * than a re-spelling of it: it models the correlation instead of trying to
460 * batch it away.
461 *
462 * FALLS BACK TO PLAIN BATCH MEANS, not to an error, whenever the fit cannot be
463 * trusted: too few batches, too few regression points, a zero periodogram
464 * ordinate (log undefined) or a non-positive intercept. A spectral estimate
465 * from a singular fit is not conservative, it is arbitrary. Transcribes
466 * `computeSpectralStatisticsInternal`.
467 */
468inline StatTriple spectral_statistics(const std::vector<double>& obs, int batch_size,
469 double low_freq_frac) {
470 const std::size_t n = obs.size();
471 const int m = (batch_size > 0) ? static_cast<int>(n / static_cast<std::size_t>(batch_size)) : 0;
472 if (m < 4) return bm_statistics(obs, batch_size);
473
474 std::vector<double> means(static_cast<std::size_t>(m), 0.0);
475 for (int i = 0; i < m; ++i) {
476 double sum = 0.0;
477 for (int j = 0; j < batch_size; ++j)
478 sum += obs[static_cast<std::size_t>(i * batch_size + j)];
479 means[static_cast<std::size_t>(i)] = sum / batch_size;
480 }
481 double grand = 0.0;
482 for (int i = 0; i < m; ++i) grand += means[static_cast<std::size_t>(i)];
483 grand /= m;
484
485 const int nf = m / 2;
486 if (nf < 2) return bm_statistics(obs, batch_size);
487 std::vector<double> per(static_cast<std::size_t>(nf), 0.0);
488 for (int k = 1; k <= nf; ++k) {
489 double re = 0.0, im = 0.0;
490 const double f = 2.0 * 3.14159265358979323846 * k / m;
491 for (int t = 0; t < m; ++t) {
492 const double c = means[static_cast<std::size_t>(t)] - grand;
493 re += c * std::cos(f * t);
494 im += c * std::sin(f * t);
495 }
496 per[static_cast<std::size_t>(k - 1)] = (re * re + im * im) / m;
497 }
498
499 int npts = static_cast<int>(nf * low_freq_frac);
500 if (npts < 3) npts = 3;
501 if (npts > nf) return bm_statistics(obs, batch_size);
502 for (int k = 0; k < npts; ++k)
503 if (!(per[static_cast<std::size_t>(k)] > 0.0)) return bm_statistics(obs, batch_size);
504
505 // Ordinary least squares for log I(f) = b0 + b1 f + b2 f^2, solved through
506 // the 3x3 normal equations by Gaussian elimination: the design is tiny and
507 // pulling in a general solver here would only add a failure mode.
508 double A[3][4];
509 for (int r = 0; r < 3; ++r)
510 for (int c = 0; c < 4; ++c) A[r][c] = 0.0;
511 for (int k = 0; k < npts; ++k) {
512 const double f = 2.0 * 3.14159265358979323846 * (k + 1) / m;
513 const double x[3] = {1.0, f, f * f};
514 const double y = std::log(per[static_cast<std::size_t>(k)]);
515 for (int r = 0; r < 3; ++r) {
516 for (int c = 0; c < 3; ++c) A[r][c] += x[r] * x[c];
517 A[r][3] += x[r] * y;
518 }
519 }
520 for (int i = 0; i < 3; ++i) {
521 int piv = i;
522 for (int r = i + 1; r < 3; ++r)
523 if (std::fabs(A[r][i]) > std::fabs(A[piv][i])) piv = r;
524 if (!(std::fabs(A[piv][i]) > 1e-300)) return bm_statistics(obs, batch_size);
525 if (piv != i)
526 for (int c = 0; c < 4; ++c) std::swap(A[i][c], A[piv][c]);
527 for (int r = 0; r < 3; ++r) {
528 if (r == i) continue;
529 const double fct = A[r][i] / A[i][i];
530 for (int c = i; c < 4; ++c) A[r][c] -= fct * A[i][c];
531 }
532 }
533 const double b0 = A[0][3] / A[0][0];
534 const double s0 = std::exp(b0);
535 if (!(s0 > 0.0) || !std::isfinite(s0)) return bm_statistics(obs, batch_size);
536
537 StatTriple st;
538 st.mean = grand;
539 st.stderr_ = std::sqrt(2.0 * 3.14159265358979323846 * s0 / m);
540 st.df = npts - 3;
541 if (st.df < 1) st.df = 1;
542 st.ok = true;
543 return st;
544}
545
546/** Dispatch on `cimethod`. */
547inline StatTriple ci_statistics(const std::vector<double>& obs, int batch_size,
548 const LdesOptions& o) {
549 if (o.cimethod == "bm") return bm_statistics(obs, batch_size);
550 if (o.cimethod == "spectral")
551 return spectral_statistics(obs, batch_size, o.spectral_low_freq_frac);
552 return obm_statistics(obs, batch_size, o.obmoverlap);
553}
554
555
556/**
557 * Convergence-based stopping: batch the four metrics and stop once EVERY
558 * active (station, class) pair has reached the requested relative precision.
559 *
560 * THE CONJUNCTION IS THE POINT. A run stops when the WORST metric at the WORST
561 * pair is precise enough, not when the aggregate is: stopping on an average
562 * relative precision leaves the lightly loaded stations, whose estimates
563 * converge slowest, arbitrarily wrong while the report looks converged.
564 *
565 * A pair whose mean is effectively zero counts as converged: a relative
566 * precision against zero is not a bound, it is a division. Transcribes
567 * `checkConvergence` and `isMetricConverged`.
568 */
570public:
571 void init(std::size_t M, std::size_t K, const LdesOptions& o, std::uint64_t max_events) {
572 enabled_ = o.cnvgon;
573 if (!enabled_) return;
574 tol_ = o.cnvgtol;
575 min_batches_ = o.cnvgbatch;
576 interval_ = (o.cnvgchk > 0) ? static_cast<std::uint64_t>(o.cnvgchk)
577 : std::max<std::uint64_t>(1, max_events / 50);
578 level_ = (o.confint > 0.0) ? o.confint : 0.95;
579 batch_obs_ = std::max(1, o.mserbatch);
580 nobs_ = 0;
581 q_.assign(M, std::vector<std::vector<double>>(K));
582 u_.assign(M, std::vector<std::vector<double>>(K));
583 r_.assign(M, std::vector<std::vector<double>>(K));
584 t_.assign(M, std::vector<std::vector<double>>(K));
585 start_qt_.assign(M, std::vector<double>(K, 0.0));
586 start_bt_.assign(M, std::vector<double>(K, 0.0));
587 start_cmp_.assign(M, std::vector<double>(K, 0.0));
588 nstations_ = M;
589 nclasses_ = K;
590 }
591
592 bool enabled() const { return enabled_; }
593 std::uint64_t interval() const { return interval_; }
594
595 /**
596 * One convergence check's observation, `collectConvergenceSample`: a batch
597 * CLOSES only every `mserbatch` checks (the reference batches its checks
598 * with the MSER batch size), so the first `cnvgbatch` batches need
599 * `cnvgbatch * mserbatch` checks, not `cnvgbatch`. Closing one per check
600 * stopped he_tandem at 80000 of 200000 events where the JAR, with 10
601 * batches, never stops (closed 2026-11-14).
602 *
603 * `is_delay[i]` makes a delay's utilization its queue length, and
604 * `lost_unserved[i][k]` (a class that has lost a job unserved since the
605 * statistics were last reset) replaces the batch response time by
606 * Q*dur/done, both as `finalizeBatch` does.
607 */
608 void observe(const Accum& acc, const std::vector<std::size_t>& nservers,
609 const std::vector<bool>& is_delay,
610 const std::vector<std::vector<bool>>& lost_unserved, double now) {
611 if (!enabled_) return;
612 if (++nobs_ >= batch_obs_) finalize_batch(acc, nservers, is_delay, lost_unserved, now);
613 }
614
615 /**
616 * Close the current batch at `now` and record one batch mean per metric.
617 *
618 * THE RESPONSE-TIME BATCH MEAN IS THE CUMULATIVE TALLY AVERAGE, not the mean
619 * over the batch: the reference's per-batch sum is fed by
620 * `recordResponseTimeForBatch`, which nothing calls, so every batch falls
621 * through to `responseTimeTally.average()`. Transcribed as such, since the
622 * stopping decision is part of the sample path.
623 */
624 void finalize_batch(const Accum& acc, const std::vector<std::size_t>& nservers,
625 const std::vector<bool>& is_delay,
626 const std::vector<std::vector<bool>>& lost_unserved, double now) {
627 if (!enabled_) return;
628 const double dur = now - batch_start_;
629 if (!(dur > 0.0)) {
630 reset_batch(acc, now);
631 return;
632 }
633 for (std::size_t i = 0; i < nstations_; ++i)
634 for (std::size_t k = 0; k < nclasses_; ++k) {
635 const double ql = (acc.tot_qlen[i][k] - start_qt_[i][k]) / dur;
636 q_[i][k].push_back(ql);
637 const double c = static_cast<double>(nservers[i] > 0 ? nservers[i] : 1);
638 u_[i][k].push_back(is_delay[i] ? ql
639 : (acc.tot_busy[i][k] - start_bt_[i][k]) / (dur * c));
640 const double done = acc.completed[i][k] - start_cmp_[i][k];
641 double rt = 0.0;
642 if (lost_unserved[i][k])
643 rt = (done > 0.0) ? ql * dur / done : 0.0;
644 else if (acc.resp_cnt[i][k] > 0.0)
645 rt = acc.resp_avg[i][k];
646 r_[i][k].push_back(rt);
647 t_[i][k].push_back(done / dur);
648 }
649 reset_batch(acc, now);
650 }
651
652 /** True once every active pair has reached the tolerance on all four metrics. */
653 bool converged(const std::vector<std::vector<bool>>& off) const {
654 if (!enabled_) return false;
655 if (nstations_ == 0 || nclasses_ == 0) return false;
656 if (static_cast<int>(q_[0][0].size()) < min_batches_) return false;
657 for (std::size_t i = 0; i < nstations_; ++i)
658 for (std::size_t k = 0; k < nclasses_; ++k) {
659 if (off[i][k]) continue;
660 if (!metric_ok(q_[i][k])) return false;
661 if (!metric_ok(u_[i][k])) return false;
662 if (!metric_ok(t_[i][k])) return false;
663 bool any_positive = false;
664 for (double v : r_[i][k])
665 if (v > 0.0) {
666 any_positive = true;
667 break;
668 }
669 if (any_positive && !metric_ok(r_[i][k])) return false;
670 }
671 return true;
672 }
673
674 int batches() const { return (nstations_ && nclasses_) ? static_cast<int>(q_[0][0].size()) : 0; }
675
676private:
677 void reset_batch(const Accum& acc, double now) {
678 batch_start_ = now;
679 nobs_ = 0;
680 for (std::size_t i = 0; i < nstations_; ++i)
681 for (std::size_t k = 0; k < nclasses_; ++k) {
682 start_qt_[i][k] = acc.tot_qlen[i][k];
683 start_bt_[i][k] = acc.tot_busy[i][k];
684 start_cmp_[i][k] = acc.completed[i][k];
685 }
686 }
687
688 bool metric_ok(const std::vector<double>& b) const {
689 const std::size_t n = b.size();
690 if (n < 2) return false;
691 double sum = 0.0;
692 for (double x : b) sum += x;
693 const double mean = sum / n;
694 // A relative precision against a zero mean is a division, not a bound.
695 if (std::fabs(mean) < 1e-12) return true;
696 double var = 0.0;
697 for (double x : b) var += (x - mean) * (x - mean);
698 var /= (n - 1);
699 const double se = std::sqrt(var / n);
700 const double half = t_critical(level_, static_cast<int>(n) - 1) * se;
701 return half / std::fabs(mean) <= tol_;
702 }
703
704 bool enabled_ = false;
705 double tol_ = 0.05, level_ = 0.95, batch_start_ = 0.0;
706 int min_batches_ = 20, batch_obs_ = 1, nobs_ = 0;
707 std::uint64_t interval_ = 1;
708 std::size_t nstations_ = 0, nclasses_ = 0;
709 std::vector<std::vector<std::vector<double>>> q_, u_, r_, t_;
710 std::vector<std::vector<double>> start_qt_, start_bt_, start_cmp_;
711};
712
713/**
714 * Fill the half-width matrices of `res` from the post-warmup observation
715 * series. Transcribes `computeOBMConfidenceIntervals`.
716 *
717 * The three series are not treated alike, and that is the reference's design:
718 *
719 * - QUEUE LENGTH has one observation per interval already, so it batches
720 * directly;
721 * - THROUGHPUT is stored CUMULATIVE, so it is differenced into per-interval
722 * rates first -- batching the cumulative counts would estimate the variance
723 * of a random walk;
724 * - UTILIZATION is not measured separately at all. Its interval is the
725 * throughput's, carried through the utilization law U = T*S/c (`u_law`, the
726 * S/c of each row, with c the peak capacity and 1 at a delay), as MATLAB's
727 * law and the JAR's TNCI/(mu*c) read it, not through the measured UN/TN;
728 * - RESPONSE TIME is not batched: as the reference's `responseTimeTally`, it is
729 * the iid interval t(n-1) * sd / sqrt(n) over the tallied response times,
730 * reported only above 30 of them, over the same tally `RN` is the mean of.
731 *
732 * A series shorter than `ciminobs` yields NO interval rather than a wide one:
733 * a half-width computed from a handful of batches is not conservative, it is
734 * arbitrary.
735 */
736inline void batch_means_ci(const Observations& obs, const Truncation& tr, const Accum& acc,
737 const LdesOptions& o, LdesResult& res, const Matrix<double>& u_law,
738 const std::vector<std::vector<bool>>* lost_unserved = nullptr) {
739 if (o.cimethod == "none" || !(o.confint > 0.0) || obs.time.empty()) return;
740 const std::size_t M = obs.nstations, K = obs.nclasses;
741 res.QNCI = Matrix<double>(M, K, 0.0);
742 res.UNCI = Matrix<double>(M, K, 0.0);
743 res.RNCI = Matrix<double>(M, K, 0.0);
744 res.TNCI = Matrix<double>(M, K, 0.0);
745 const std::size_t t0 = tr.applied ? tr.index : 0;
746
747 for (std::size_t i = 0; i < M; ++i) {
748 for (std::size_t r = 0; r < K; ++r) {
749 if (t0 >= obs.qlen[i][r].size()) continue;
750 const std::vector<double> q(obs.qlen[i][r].begin() + static_cast<std::ptrdiff_t>(t0),
751 obs.qlen[i][r].end());
752 if (q.size() >= static_cast<std::size_t>(o.ciminobs)) {
753 const int b = std::max(o.ciminbatch, static_cast<int>(std::sqrt(
754 static_cast<double>(q.size()))));
755 const StatTriple s = ci_statistics(q, b, o);
756 if (s.ok) res.QNCI(i, r) = t_critical(o.confint, s.df) * s.stderr_;
757 }
758
759 const bool little = lost_unserved != nullptr && (*lost_unserved)[i][r];
760 const double n = acc.resp_cnt[i][r];
761 if (!little && n > 30.0) {
762 const double var = acc.resp_m2[i][r] / (n - 1.0);
763 if (var > 0.0)
764 res.RNCI(i, r) = t_critical(o.confint, static_cast<int>(n) - 1) * std::sqrt(var / n);
765 }
766
767 std::vector<double> rates;
768 for (std::size_t k = t0 + 1; k < obs.cmp[i][r].size(); ++k) {
769 const double dt = obs.time[k] - obs.time[k - 1];
770 if (dt > 0.0) rates.push_back((obs.cmp[i][r][k] - obs.cmp[i][r][k - 1]) / dt);
771 }
772 if (rates.size() >= static_cast<std::size_t>(o.ciminobs)) {
773 const int b = std::max(o.ciminbatch, static_cast<int>(std::sqrt(
774 static_cast<double>(rates.size()))));
775 const StatTriple s = ci_statistics(rates, b, o);
776 if (s.ok) {
777 const double half = t_critical(o.confint, s.df) * s.stderr_;
778 res.TNCI(i, r) = half;
779 if (u_law.rows() > i && u_law(i, r) > 0.0) res.UNCI(i, r) = half * u_law(i, r);
780 }
781 }
782 // RN = QN/TN where jobs left unserved, so its half-width is the delta-method one from QNCI and TNCI, as
783 // the JAR propagates it, not the served-job tally's.
784 if (little && res.QN(i, r) > 0.0 && res.TN(i, r) > 0.0) {
785 const double rq = res.QNCI(i, r) / res.QN(i, r), rt = res.TNCI(i, r) / res.TN(i, r);
786 res.RNCI(i, r) = (res.QN(i, r) / res.TN(i, r)) * std::sqrt(rq * rq + rt * rt);
787 }
788 }
789 }
790
791 // HOW LONG THE RUN SHOULD HAVE BEEN, when the caller asked for it. The
792 // half-widths just computed pin the ASYMPTOTIC variance of each estimator,
793 // which is the quantity a run length is planned from -- not the stationary
794 // variance, which on M/M/1 differs from it by a factor blowing up like
795 // (1-rho)^-2.
796 if (o.run_length_plan_precision > 0.0) {
797 // The ACTUAL number of events simulated where the result carries it,
798 // not the budget: LDES stops early on convergence, and planning from a
799 // budget it never spent would overstate N and so overstate sigma^2.
800 const double used = res.total_simulated_events > 0
801 ? static_cast<double>(res.total_simulated_events)
802 : static_cast<double>(o.events > 0 ? o.events : o.samples);
803 if (used > 0.0) {
805 res.QN, res.QNCI, used, o.run_length_plan_precision, o.confint);
806 res.has_run_length_plan = true;
807 }
808 }
809}
810
811} // namespace engine
812} // namespace ldes
813} // namespace line
814
815#endif // LINE_SOLVERS_LDES_LDES_STATS_H
std::size_t rows() const
Definition matrix.h:89
Convergence-based stopping: batch the four metrics and stop once EVERY active (station,...
Definition ldes_stats.h:569
bool converged(const std::vector< std::vector< bool > > &off) const
True once every active pair has reached the tolerance on all four metrics.
Definition ldes_stats.h:653
void observe(const Accum &acc, const std::vector< std::size_t > &nservers, const std::vector< bool > &is_delay, const std::vector< std::vector< bool > > &lost_unserved, double now)
One convergence check's observation, collectConvergenceSample: a batch CLOSES only every mserbatch ch...
Definition ldes_stats.h:608
std::uint64_t interval() const
Definition ldes_stats.h:593
void finalize_batch(const Accum &acc, const std::vector< std::size_t > &nservers, const std::vector< bool > &is_delay, const std::vector< std::vector< bool > > &lost_unserved, double now)
Close the current batch at now and record one batch mean per metric.
Definition ldes_stats.h:624
void init(std::size_t M, std::size_t K, const LdesOptions &o, std::uint64_t max_events)
Definition ldes_stats.h:571
The option and result records of SolverLDES, the discrete-event simulator.
Dense matrix and non-owning view.
StatTriple bm_statistics(const std::vector< double > &obs, int batch_size)
Non-overlapping batch means.
Definition ldes_stats.h:373
StatTriple spectral_statistics(const std::vector< double > &obs, int batch_size, double low_freq_frac)
Heidelberger-Welch spectral estimate of the variance of the sample mean.
Definition ldes_stats.h:468
StatTriple ci_statistics(const std::vector< double > &obs, int batch_size, const LdesOptions &o)
Dispatch on cimethod.
Definition ldes_stats.h:547
void batch_means_ci(const Observations &obs, const Truncation &tr, const Accum &acc, const LdesOptions &o, LdesResult &res, const Matrix< double > &u_law, const std::vector< std::vector< bool > > *lost_unserved=nullptr)
Fill the half-width matrices of res from the post-warmup observation series.
Definition ldes_stats.h:736
StatTriple obm_statistics(const std::vector< double > &obs, int batch_size, double overlap)
Overlapping batch means.
Definition ldes_stats.h:401
double t_critical(double level, int df)
The two-sided t critical value at confidence level with df degrees of freedom: the EXACT Student-t qu...
Definition ldes_stats.h:443
double overlap_adjustment(double overlap)
The variance inflation of OVERLAPPING batch means.
Definition ldes_stats.h:366
int mser5_truncation(const std::vector< double > &obs, int batch_size)
MSER-5 truncation point over a series of observations, in BATCHES.
Definition ldes_stats.h:169
RunLengthPlan< T > sim_runlength_plan(const Matrix< T > &means, const Matrix< T > &ciHalfWidth, const T &samplesUsed, const T &relPrecision=num_traits< T >::from_rational(1, 20), const T &confidence=num_traits< T >::from_rational(19, 20))
How long a simulation run should have been, from the one it already did.
double sim_norminv(double p)
Standard normal quantile function.
Definition sim_dist.h:62
double sim_tinv(double p, double nu)
Quantile function of Student's t distribution.
Definition sim_dist.h:77
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
Normal and Student t quantiles used by the output-analysis routines.
The knobs of one LDES run.
int ciminbatch
–ciminbatch
double spectral_low_freq_frac
–spectrallowfreqfrac
double cnvgtol
–cnvgtol
double confint
Confidence level of the reported half-widths.
double obmoverlap
–obmoverlap; 0 reduces OBM to plain batch means
double run_length_plan_precision
options.config.runLengthPlan: ask for the run length this run SHOULD have had, for a target relative ...
int mserbatch
–mserbatch, MSER batch size
std::string cimethod
–cimethod: obm | bm | spectral | none
int cnvgchk
–cnvgchk, events between checks; 0 = samples/50
int ciminobs
–ciminobs, below which no CI is reported
std::size_t events
0 = not given; overrides samples when set
int cnvgbatch
–cnvgbatch, batches before the first check
std::size_t samples
-s, service-completion budget
One ldes-result document, parsed.
sim::RunLengthPlan< double > run_length_plan
Matrix< double > TNCI
bool has_run_length_plan
options.config.runLengthPlan: the run length the caller would need for the precision they asked for,...
Matrix< double > TN
Matrix< double > UNCI
Matrix< double > QNCI
long long total_simulated_events
Matrix< double > RNCI
Matrix< double > QN
The running per-(station, class) integrals and tallies.
Definition ldes_stats.h:47
void tally_resp(std::size_t i, std::size_t r, double x)
Tally one response time x at (i,r): the sum, the running moments and the count move together.
Definition ldes_stats.h:135
std::vector< std::vector< double > > held
Callers parked on their server awaiting a synchronous REPLY (sn.syncreply), per (station,...
Definition ldes_stats.h:109
Accum(std::size_t M, std::size_t K)
Definition ldes_stats.h:48
void update_busy(std::size_t i, std::size_t r, double now)
Advance the busy-server integral of (i,r) to now.
Definition ldes_stats.h:81
std::vector< std::vector< double > > busy
Definition ldes_stats.h:110
std::vector< double > busy_scale
The speed each station is running at right now (load dependence only), and the peak capacity that nor...
Definition ldes_stats.h:123
std::vector< std::vector< double > > last_qlen
Definition ldes_stats.h:112
std::vector< std::vector< double > > resp_cnt
Definition ldes_stats.h:124
std::vector< std::vector< double > > qlen
Definition ldes_stats.h:100
std::vector< std::vector< double > > tot_qlen
Definition ldes_stats.h:111
std::vector< std::vector< double > > completed
Definition ldes_stats.h:124
std::vector< std::vector< double > > resp_sum
Definition ldes_stats.h:124
std::vector< std::vector< double > > join_dropped
Siblings a QUORUM Join discarded, per (station, class): a sibling that reaches the Join after its par...
Definition ldes_stats.h:158
void update_qlen(std::size_t i, std::size_t r, double now)
Advance the queue-length integral of (i,r) to now.
Definition ldes_stats.h:67
void set_busy_scale(std::size_t i, double v, double now)
Install the load-dependent speed station i runs at from now on.
Definition ldes_stats.h:94
std::vector< std::vector< double > > resp_m2
Definition ldes_stats.h:133
std::vector< std::vector< double > > tot_busy
Definition ldes_stats.h:111
std::vector< std::vector< double > > arrived
Jobs that ARRIVED at each (station, class), which is not what completed counts: the reference reports...
Definition ldes_stats.h:150
std::vector< std::vector< double > > last_busy
Definition ldes_stats.h:112
std::vector< double > util_peak
Definition ldes_stats.h:123
std::vector< std::vector< double > > resp_avg
Running mean and sum of squared deviations of the response times, for the iid interval the reference ...
Definition ldes_stats.h:133
The event-spaced observation series MSER-5 and the CI both read.
Definition ldes_stats.h:212
Truncation truncate() const
The truncation point, on the AGGREGATE queue length first.
Definition ldes_stats.h:295
void collect(const Accum &acc, double now, const std::vector< std::vector< double > > &arrived)
Record one observation, reading the arrival counters from arrived.
Definition ldes_stats.h:251
std::vector< std::vector< double > > last_qt
Definition ldes_stats.h:340
std::vector< std::vector< std::vector< double > > > bt
Definition ldes_stats.h:339
std::vector< std::vector< std::vector< double > > > qlen
Definition ldes_stats.h:339
std::vector< std::vector< std::vector< double > > > cmp
Definition ldes_stats.h:339
std::vector< std::vector< double > > sys
Cumulative system completions per class, one entry per observation.
Definition ldes_stats.h:344
std::vector< char > in_mser
Whether station i feeds the truncation criterion; every one is still recorded.
Definition ldes_stats.h:342
std::vector< double > time
Definition ldes_stats.h:338
void collect(const Accum &acc, double now)
Record one observation.
Definition ldes_stats.h:238
std::vector< std::vector< std::vector< double > > > drp
Definition ldes_stats.h:339
void collect_system(const std::vector< double > &completed)
Record the cumulative SYSTEM completions per class beside the observation just taken,...
Definition ldes_stats.h:277
std::vector< std::vector< std::vector< double > > > qt
Definition ldes_stats.h:339
Observations(std::size_t M, std::size_t K, bool mser_on, int batch)
Definition ldes_stats.h:213
std::vector< std::vector< std::vector< double > > > arv
Definition ldes_stats.h:339
Grand mean, standard error and degrees of freedom of a batch-means estimate.
Definition ldes_stats.h:350
Where the warmup ended, and whether a truncation was applied at all.
Definition ldes_stats.h:205
double warmup_end
the instant of that observation
Definition ldes_stats.h:207
std::size_t index
observation index of the truncation point
Definition ldes_stats.h:206