LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
ldes_engine.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_ENGINE_H
6#define LINE_SOLVERS_LDES_LDES_ENGINE_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * The NATIVE LDES discrete-event engine.
12 *
13 * WHAT THIS IS. `solvers/wrappers/ldes/solver_ldes.h` is a CLIENT: it writes a
14 * model.json, runs the Java engine as a subprocess and parses the result back.
15 * This header is the engine itself, in process, and is the C++ twin of
16 * `jline/solvers/ldes/handlers/Solver_ssj.java`. Do not confuse the two
17 * directories -- `wrappers/ldes/` shells out, `ldes/` simulates.
18 *
19 * WHAT IT COVERS TODAY. Networks over Source, Queue, Delay, Router,
20 * ClassSwitch, Logger and Sink; every renewal, Markovian and trace-driven
21 * service law the language carries (see `ldes_sampler.h`); the buffered
22 * disciplines FCFS, LCFS, SIRO, HOL, the LCFS priority variants, SJF, LJF,
23 * SEPT, LEPT, EDD, EDF, INF; the preemptive disciplines FCFSPR/PI,
24 * LCFSPR/PI, their PRIO variants, SRPT, SRPTPRIO, PSJF, FB, LRPT, SETF and
25 * FSP, in both resume and restart; the sharing disciplines PS, DPS, GPS,
26 * their priority variants and LPS; multi-server stations; class priorities;
27 * finite station and per-class capacity with DROP; balking (all three
28 * strategies, one job-count table, as the Java engine) and reneging;
29 * load dependence (`sn.lldscaling`) and class dependence (`sn.cdscaling`);
30 * open and closed classes; class switching; G-network NEGATIVE and CATASTROPHE
31 * signals, with their batch-size law and removal policy; and confidence
32 * intervals by overlapping or non-overlapping batch means.
33 *
34 * WHAT IT REFUSES, by name, in `ldes_engine_reject` (this list was rewritten on
35 * 2026-08-01 against the code; the tranche that followed the first draft added
36 * most of what the old text said was missing): the EXT discipline; a REPLY
37 * signal, whose synchronous call holds a server this engine does not model; a
38 * blocking rule that is neither DROP, BAS nor BBS; a continuously shared server
39 * or an NHPP or NNPP under SLOTTED mode, none of which lands on the slot lattice; an
40 * NNPP anywhere but at a Source (it is an arrival process only); and any
41 * node kind outside Source, Sink, Queue, Delay, Router, ClassSwitch, Logger,
42 * Cache, Place and Transition. POLLING, PAS, FSP, SETF, EDD, EDF and RR
43 * (round robin, a quantum clock per busy slot) ARE simulated, as are caches, Petri nets, fork-join, finite capacity regions,
44 * retrial orbits, setup/delay-off, MAPt/PHt, slotted time, transient runs, busy
45 * periods and replications. SERVER BREAKDOWNS are simulated as of 2026-08-15:
46 * `NetworkStruct::breakdownparam` carries the two clocks and the degraded
47 * `downServiceRates`, and the engine runs the outage as a state-dependent rate
48 * change -- a zero multiplier stalls the job in service with its residual
49 * intact, a positive one is the degraded server -- so a job is interrupted and
50 * never evicted. They are refused under SLOTTED mode, where the failure and
51 * repair epochs would have to land on the lattice too. Each refusal is a
52 * definite feature with a definite semantics, and serving one as though it were
53 * something else produces a run that finishes and reports numbers no downstream
54 * test can distinguish from correct ones.
55 *
56 * WHAT IS TRANSCRIBED FROM THE JAVA ENGINE, because these choices decide the
57 * numbers and not just the speed:
58 *
59 * - THE BUDGET IS SERVICE COMPLETIONS, not simulated time and not arrivals.
60 * - WARMUP IS MSER-5 over EVENT-SPACED observations, interval
61 * `maxEvents / 1000` completions, truncation chosen on the AGGREGATE queue
62 * length with a per-series fallback (the closed-network case, whose
63 * constant total carries no transient signal).
64 * - THE ESTIMATORS ARE TIME-WEIGHTED AND TRUNCATION-DIFFERENCED: QLen and
65 * Util are (integral at the end - integral at the truncation) / elapsed,
66 * never an unweighted mean of the per-interval averages, which overweights
67 * congested epochs because they contain more events per unit time.
68 * - RESPONSE TIME IS THE FULL TALLY. `getAvgResponseTime` averages every
69 * observation including the warmup ones, so Little's law holds only up to
70 * the warmup mass. That is the reference's behaviour, mirrored rather than
71 * corrected, or the two engines would disagree on a short run.
72 * - THE SOURCE ROW OF TN IS THE NOMINAL ARRIVAL RATE, not a measured one.
73 *
74 * RANDOMNESS, AND HOW FAR IT NOW AGREES WITH THE JAVA ENGINE. The generators
75 * are no longer Mersenne Twisters: `ldes_sampler.h` draws every renewal family
76 * from `rng::Mrg32k3a`, a bit-exact reproduction of SSJ's MRG32k3a, through the
77 * inverse-CDF quantiles of `ldes_ssj_variates.h`, and every Markovian family
78 * from `rng::JavaRandom` through the transcribed `Map_sample.MapSampler` walk,
79 * because the reference sends those two families to those two generators. What
80 * is NOT yet aligned is stream OWNERSHIP: `Solver_ssj` seeds one stream per
81 * (node, class) from `seed + offset`, while this engine still carries three
82 * streams for the whole run (arrivals, services, routing). Until that is
83 * matched a fixed seed does not reproduce the Java sample path, so a
84 * cross-engine test must still compare means against a tolerance derived from
85 * the standard error rather than element by element. The seed bands are kept separate
86 * per role (arrivals, services, routing) for the reason the Java engine
87 * separates them: one shared stream makes the routing draw the very uniform
88 * that generated the interarrival time, which correlates a probabilistic split
89 * with the gap length and biases the destinations in opposite directions.
90 */
91
92#include <algorithm>
93#include <array>
94#include <chrono>
95#include <cmath>
96#include <cstddef>
97#include <cstdint>
98#include <cstdio>
99#include <cstdlib>
100#include <ctime>
101#include <deque>
102#include <exception>
103#include <fstream>
104#include <functional>
105#include <limits>
106#include <map>
107#include <memory>
108#include <numeric>
109#include <queue>
110#include <random>
111#include <string>
112#include <thread>
113#include <vector>
114
117#include "line/lang/qn/state.h"
128#include "line/util/error.h"
130#include "line/util/matrix.h"
131
132namespace line {
133namespace ldes {
134namespace engine {
135
136/**
137 * Station roles this engine simulates.
138 *
139 * A Fork and a Join appear in `sn.stations` because the refresh registers
140 * them, but they SERVE NOTHING: they are handled by the routing layer, which
141 * replicates at one and synchronizes at the other. Giving them a role of their
142 * own keeps them out of the service-station setup, which would otherwise
143 * demand a service law they do not have.
144 */
146
147/**
148 * Event tags, ordered so that a service completion precedes an arrival
149 * scheduled for the same instant.
150 *
151 * The order matters on any model whose rates produce exact ties (a Det
152 * service, a closed class placed at t=0), and it is the completions-then-
153 * arrivals phase order of the Java engine's `slotPhase`. Ties inside one tag
154 * break on the insertion sequence, so the event list is a total order and the
155 * path is reproducible from the seed.
156 */
166 /**
167 * A service completion in the EMBEDDED QUEUE of a queueing place: the token
168 * leaves the place's servers for its depository, where the output arcs can
169 * finally see it. `station` is the place SLOT and `cls` the token colour.
170 *
171 * It sorts AFTER a firing at the same instant, which matters only for the
172 * degenerate Immediate service law: a token whose service ends exactly when
173 * a transition fires reaches the depository after that firing read it, which
174 * is the reference's own order (`placeDepartureActions` re-checks enabling
175 * once it has deposited, so the firing simply happens next).
176 */
178 /** A job abandons the retrial orbit (`sn.orbitImpatience`); `tag` is its id. */
180 /**
181 * Round robin: the quantum of the job in `slot` expires; `tag` is the slot's
182 * `rr_qtag` when it was armed. It sorts after a departure at the same
183 * instant, so a service that ends exactly when its quantum does completes,
184 * as `Solver_ssj` arms the expiry only for a quantum strictly shorter.
185 */
187 /** A polling visit timer expires; `station` is the station and `tag` the timer id. */
189};
190
191/**
192 * The power state of one server of a setup/delay-off station, the reference's
193 * `Solver_ssj.ServerState`. An EV_SETUP event ends whichever timer the slot is
194 * running (SETUP -> ACTIVE, DELAYOFF -> OFF) and is discarded when its tag no
195 * longer matches the slot's `power_tag`, which is how a cancelled delay-off is
196 * neutralised.
197 */
198enum PowerState { PW_ACTIVE = 0, PW_OFF = 1, PW_SETUP = 2, PW_DELAYOFF = 3 };
199
200/** One scheduled event. */
201struct Event {
202 double t = 0.0;
204 std::size_t station = 0;
205 std::size_t cls = 0;
206 std::size_t slot = 0; ///< server slot at a buffered station
207 /**
208 * Identifies the job the event was scheduled for.
209 *
210 * A preempted or resharing job leaves a departure event behind that the
211 * event list gives no way to cancel, so every completion carries the tag
212 * its job held when it was scheduled and is DISCARDED if the two no longer
213 * agree. Without it a preempted job would depart twice: once on its stale
214 * event and once on the one its resumption schedules.
215 */
216 std::uint64_t tag = 0;
217 Job job; ///< Delay and PS carry the job in the event
218 std::uint64_t seq = 0;
219};
220
221/** Later-is-greater, so the priority queue pops the earliest event. */
223 bool operator()(const Event& a, const Event& b) const {
224 if (a.t != b.t) return a.t > b.t;
225 if (a.kind != b.kind) return a.kind > b.kind;
226 return a.seq > b.seq;
227 }
228};
229
230/** One routing alternative out of a (node, class) pair. */
232 std::size_t node = 0; ///< 1-based destination NODE
233 std::size_t station = 0; ///< its station index, or M when it is not one
234 std::size_t cls = 0;
235 bool sink = false;
236 double cum = 0.0;
237};
238
239/**
240 * One destination NODE of a (node, class) pair, with the class it switches to.
241 *
242 * THE STRATEGY CHOOSES THE NODE AND THE SWITCH ROW CHOOSES THE CLASS, in that
243 * order, which is `selectDestinationWithClassSwitch` and the reason the two are
244 * separated at all. A strategy applied to (node, class) PAIRS would resample
245 * the class as well -- uniformly under RAND, in turn under RROBIN -- and
246 * destroy the class-switch probabilities the pair was carrying.
247 *
248 * The list is built in ASCENDING NODE INDEX because a round-robin pointer walks
249 * it in order: any other order is a different, and equally arbitrary, cycle.
250 */
251struct RouteDest {
252 std::size_t node = 0; ///< 1-based destination NODE
253 std::size_t station = 0; ///< its station index, or M when it is not one
254 bool sink = false;
255 double mass = 0.0; ///< total probability into this node, over classes
256 std::vector<std::pair<std::size_t, double>> cls; ///< (class, probability)
257};
258
259/**
260 * A double as Java's `Double.toString` spells it, which is how the reference's
261 * Logger writes its time columns: the shortest digit string that reads back to
262 * the same value, plain between 1e-3 and 1e7 and `d.dddE<n>` outside, always
263 * with one digit after the point (`1.0`, `2.5E-4`).
264 */
265inline std::string java_double_str(double v) {
266 if (std::isnan(v)) return "NaN";
267 if (std::isinf(v)) return v > 0 ? "Infinity" : "-Infinity";
268 if (v == 0.0) return std::signbit(v) ? "-0.0" : "0.0";
269 char buf[40];
270 int p = 1;
271 for (; p < 17; ++p) {
272 std::snprintf(buf, sizeof buf, "%.*e", p - 1, v);
273 if (std::strtod(buf, nullptr) == v) break;
274 }
275 std::snprintf(buf, sizeof buf, "%.*e", p - 1, v);
276 const std::string e(buf);
277 const bool neg = e[0] == '-';
278 const std::size_t epos = e.find('e');
279 std::string digits;
280 for (std::size_t i = neg ? 1 : 0; i < epos; ++i)
281 if (e[i] != '.') digits += e[i];
282 const int ex = std::atoi(e.c_str() + epos + 1);
283 while (digits.size() > 1 && digits[digits.size() - 1] == '0') digits.erase(digits.size() - 1);
284 std::string out = neg ? "-" : "";
285 const double a = std::fabs(v);
286 if (a >= 1e-3 && a < 1e7) {
287 if (ex >= 0) {
288 const std::size_t ip = static_cast<std::size_t>(ex) + 1;
289 std::string ipart = digits.substr(0, std::min(ip, digits.size()));
290 while (ipart.size() < ip) ipart += '0';
291 const std::string fpart = digits.size() > ip ? digits.substr(ip) : "0";
292 out += ipart + "." + fpart;
293 } else {
294 out += "0." + std::string(static_cast<std::size_t>(-ex - 1), '0') + digits;
295 }
296 } else {
297 out += digits.substr(0, 1) + "." + (digits.size() > 1 ? digits.substr(1) : "0") + "E" +
298 std::to_string(ex);
299 }
300 return out;
301}
302
303/**
304 * Refuse, by name, every model outside this engine's scope.
305 *
306 * The refusal is the point. A PS station served FCFS, a preemptive-resume
307 * station served non-preemptively, or a blocking model run without blocking
308 * all finish and report plausible numbers; nothing downstream can tell them
309 * from correct ones, so the check has to happen here, before the run.
310 */
311template <class T>
313 using lang::NodeType;
315
316 // A USER-DEFINED ACCESS-COST MATRIX (Cache.setAccessProb / setAccessGraph) is not read by this engine, which
317 // always promotes one list per hit and inserts misses into the first list -- the default matrix. Anything else
318 // would be simulated as the default, so it is refused and the subprocess client falls back to the JAR engine,
319 // which samples the target list from the matrix as MATLAB afterEventCache does.
320 for (const auto& kv : sn.nodeparam) {
321 const qn::CacheParam<T>& cp = kv.second;
322 if (cp.accost.empty()) continue;
323 for (const auto& row : cp.accost)
324 for (const Matrix<T>& A : row) {
325 const std::size_t H = A.rows();
326 if (H == 0) continue;
327 for (std::size_t r = 0; r < H; ++r)
328 for (std::size_t c = 0; c < A.cols(); ++c) {
329 const std::size_t want = (r == 0) ? 1 : std::min(r + 1, H - 1);
330 const double v = num_traits<T>::to_double(A(r, c));
331 const double expect = (c == want) ? 1.0 : 0.0;
332 // rows only matter up to normalization: compare the support, not the scale
333 if ((v > 0.0) != (expect > 0.0))
334 throw UnsupportedError(ErrorKind{"CacheAccessProb"},
335 "SolverLDES (native engine): a user-defined cache access-cost matrix "
336 "(setAccessProb/setAccessGraph) is not read by this engine; use the subprocess client");
337 }
338 }
339 }
340
341 for (const auto& nd : sn.nodes) {
342 switch (nd.nodetype) {
343 case NodeType::Source:
344 case NodeType::Sink:
345 case NodeType::Queue:
346 case NodeType::Delay:
347 case NodeType::Router:
348 case NodeType::ClassSwitch:
349 case NodeType::Logger:
350 case NodeType::Fork:
351 case NodeType::Join:
352 case NodeType::Cache:
353 case NodeType::Place:
354 case NodeType::Transition:
355 break;
356 default:
357 throw UnsupportedError(ErrorKind{"NodeType"},
358 std::string("SolverLDES (native engine): node kind ") +
359 lang::node_type_to_text(nd.nodetype) +
360 " is not ported yet; use the subprocess client");
361 }
362 }
363 // HETEROGENEOUS SERVER POOLS are simulated here as of 2026-09-04: each job
364 // occupies one server of one compatible pool and is served at that pool's
365 // own law, which is what makes a pooled model a different system from the
366 // multiserver it would otherwise look like. What is NOT ported is the pools
367 // under a SHARING discipline, where the reference has no per-pool treatment
368 // either -- `calculatePSRates` never consults the server types, so the JAR
369 // silently flattens them. Rather than reproduce that, the sharing case is
370 // refused by name; the max-min fair allocation it would need is the layered
371 // engine's `SnCompatShare`, and neither engine carries it for a flat model.
372 //
373 // A FIFO depository is still understood by no engine at all.
374 for (std::size_t si = 0; si < sn.stations.size(); ++si) {
375 const auto& st = sn.stations[si];
376 if (!st.server_types.empty()) {
377 const SchedStrategy sc = st.sched;
378 const bool sharing = (sc == SchedStrategy::PS || sc == SchedStrategy::DPS ||
379 sc == SchedStrategy::GPS || sc == SchedStrategy::LPS ||
380 sc == SchedStrategy::PSPRIO || sc == SchedStrategy::DPSPRIO ||
381 sc == SchedStrategy::GPSPRIO);
382 if (sharing)
383 throw UnsupportedError(ErrorKind{"HeteroServers"},
384 std::string("SolverLDES (native engine): station '") + st.name +
385 "' declares heterogeneous server pools under a sharing discipline, which "
386 "no engine allocates per pool; use a queueing discipline");
387 // POLLING with pools is simulated as of 2026-11-14: the server still
388 // serves one job at a time, on the slot of the pool the station's
389 // policy picks and at that pool's law (Java `pollingStartService`).
390 if (sc == SchedStrategy::PAS)
391 throw UnsupportedError(ErrorKind{"HeteroServers"},
392 std::string("SolverLDES (native engine): station '") + st.name +
393 "' declares heterogeneous server pools under " +
394 std::string(lang::sched_to_text(sc)) +
395 ", whose controller picks the server itself and has no pool to pick from");
396 }
397 for (lang::DepartureDiscipline d : st.departure_discipline)
399 throw UnsupportedError(ErrorKind{"DepartureDiscipline"},
400 std::string("SolverLDES (native engine): station '") + st.name +
401 "' sets a non-NORMAL depository departure discipline, which no "
402 "engine implements");
403 // A TIME-INHOMOGENEOUS MATRIX-SCHEDULE SERVICE (PHt or MAPt) is sampled
404 // by walking a phase process forward from the SERVICE START instant,
405 // which is exact only while service is then delivered continuously at
406 // unit rate. Sharing hands the job a varying fraction of the server,
407 // preemption interrupts the walk, a load- or class-dependent rate
408 // rescales it, and a pool serves it under a law of its own; none of
409 // those is recoverable from a start instant alone, and unlike an NHPP
410 // rate there is no operational-time transform to fall back on, because
411 // tau = int mu du presumes a SCALAR rate while these vary their matrix
412 // entries independently. Refusing mirrors the reference engine's
413 // `assertMatrixScheduleServiceSupported`; the alternative is a silently
414 // wrong sample path.
415 for (std::size_t r = 0; r < sn.service[si].size(); ++r) {
416 const lang::ProcessType pt = sn.service[si][r].type;
417 if (pt != lang::ProcessType::PHT && pt != lang::ProcessType::MAPT) continue;
418 const SchedStrategy sc = st.sched;
419 const std::string family = (pt == lang::ProcessType::MAPT) ? "MAPt" : "PHt";
420 const std::string where = std::string(" service is not supported at station '") +
421 st.name + "' for class '" + sn.classes[r].name + "'";
422 if (is_ps_family(sc) || is_preemptive(sc))
423 throw UnsupportedError(ErrorKind{"MAPt"}, "SolverLDES (native engine): " + family + where +
424 " under " + std::string(lang::sched_to_text(sc)) +
425 ". A time-inhomogeneous matrix schedule is walked from"
426 " the service start instant, which is exact only while"
427 " service runs continuously at unit rate; use INF or a"
428 " non-preemptive FCFS/LCFS-family discipline");
429 if (!st.lldscaling.empty())
430 throw UnsupportedError(ErrorKind{"LoadDependence"}, "SolverLDES (native engine): " + family + where +
431 " with load dependence: the rate rescaling cannot be"
432 " applied to a phase walk taken from the service start"
433 " instant");
434 if (sn.gdscaling)
435 throw UnsupportedError(ErrorKind{"GlobalDependence"}, "SolverLDES (native engine): " + family + where +
436 " with a global dependence: phi(n) rescales the rate at"
437 " every population change anywhere in the network, which"
438 " a phase walk taken from the service start instant"
439 " cannot be asked for");
440 if (!st.server_types.empty())
441 throw UnsupportedError(ErrorKind{"HeteroServers"}, "SolverLDES (native engine): " + family + where +
442 " with heterogeneous server types: the pool draws its"
443 " own duration, which the walk cannot be asked for");
444 }
445 }
446 for (std::size_t i = 0; i < sn.nstations; ++i) {
447 const auto& st = sn.stations[i];
448 if (st.nodetype == NodeType::Source) continue;
449 switch (st.sched) {
450 case SchedStrategy::INF:
451 case SchedStrategy::FCFS:
452 case SchedStrategy::LCFS:
453 case SchedStrategy::SIRO:
454 case SchedStrategy::HOL:
455 case SchedStrategy::LCFSPRIO:
456 case SchedStrategy::SJF:
457 case SchedStrategy::LJF:
458 case SchedStrategy::SEPT:
459 case SchedStrategy::LEPT:
460 case SchedStrategy::PS:
461 case SchedStrategy::DPS:
462 case SchedStrategy::GPS:
463 case SchedStrategy::PSPRIO:
464 case SchedStrategy::DPSPRIO:
465 case SchedStrategy::GPSPRIO:
466 case SchedStrategy::LPS:
467 case SchedStrategy::LCFSPR:
468 case SchedStrategy::LCFSPI:
469 case SchedStrategy::LCFSPRPRIO:
470 case SchedStrategy::LCFSPIPRIO:
471 case SchedStrategy::FCFSPR:
472 case SchedStrategy::FCFSPI:
473 case SchedStrategy::FCFSPRPRIO:
474 case SchedStrategy::FCFSPIPRIO:
475 case SchedStrategy::SRPT:
476 case SchedStrategy::SRPTPRIO:
477 case SchedStrategy::PSJF:
478 case SchedStrategy::FB:
479 case SchedStrategy::LRPT:
480 case SchedStrategy::SETF:
481 case SchedStrategy::FSP:
482 case SchedStrategy::EDD:
483 case SchedStrategy::EDF:
484 case SchedStrategy::POLLING:
485 case SchedStrategy::PAS:
486 case SchedStrategy::OI:
487 break;
488 case SchedStrategy::RR:
489 // Round robin with a finite quantum (Haverkort 1998, Sect. 6.4),
490 // simulated as `Solver_ssj` does (RRQuantumExpiry): a quantum
491 // clock per busy slot, EV_QUANTUM. Any law the sampler can draw
492 // is accepted, a Det quantum included.
493 for (std::size_t r = 0; r < sn.nclasses; ++r)
494 if (r >= st.quantum.size() || st.quantum[r].disabled)
495 throw InputError(ErrorKind{"Model"},
496 "LDES: round-robin station '" + st.name + "' has no quantum for class '" +
497 sn.classes[r].name + "'.");
498 break;
499 default:
500 // EXT IS NOT A SERVICE DISCIPLINE AND IS REFUSED ON PURPOSE.
501 // `Source.m` and `Sink.m` set it as their own marker, so it
502 // never reaches a served station by any supported route; a
503 // Queue explicitly built with it is refused by the reference
504 // too, at its model layer -- `Queue.<init>` throws "Routing
505 // Strategy is not supported in JLINE" before the Java engine
506 // sees the model. Serving it as INF, which is how `npfqn_sqd`
507 // and `sn_has_product_form` group it, would be a guess at a
508 // semantics neither reference implements.
509 throw UnsupportedError(ErrorKind{"SchedStrategy_EXT"},
510 "SolverLDES (native engine): station '" + st.name +
511 "' uses a scheduling this engine does not simulate (EXT is the "
512 "Source and Sink marker, not a queueing discipline)");
513 }
514 }
515 // BAS and BBS are simulated, and so is RETRIAL on a class that declares a
516 // retrial process (the capacity then bounds service plus orbit, setOrbit's
517 // finite orbit); RSRD is not. Only a rule on a CAPPED station can ever fire,
518 // and the refresh gives every station a default rule including the Source,
519 // so an uncapped station is not consulted -- rejecting on the default would
520 // refuse every model.
521 for (std::size_t i = 0; i < sn.nstations; ++i) {
522 if (sn.stations[i].nodetype == NodeType::Source) continue;
523 if (!std::isfinite(sn.stations[i].cap)) continue;
524 const auto rpit = sn.retrialparam.find(i + 1);
525 for (std::size_t r = 0; r < sn.nclasses; ++r) {
526 if (i >= sn.droprule.size() || r >= sn.droprule[i].size()) continue;
527 const lang::DropStrategy d = sn.droprule[i][r];
528 const bool simulated_retrial =
530 rpit != sn.retrialparam.end() && r < rpit->second.retrial_proc.size() &&
531 !rpit->second.retrial_proc[r].disabled;
532 if (simulated_retrial) continue;
535 throw UnsupportedError(ErrorKind{"FiniteCapacity"},
536 "SolverLDES (native engine): station '" + sn.stations[i].name +
537 "' declares a blocking rule that is not DROP, BAS or BBS");
538 }
539 }
540 // AN ARRIVAL BATCH IS DRAWN AND RELEASED (see the EV_ARRIVAL arm). It used to be
541 // stored and ignored -- `Station::arrival_batch` crossed the wire and BatchArrival
542 // was declared, but every epoch released one job, so an M[3]/M/2 queue came back
543 // as the M/M/2 queue at a third of the task rate -- and was then refused by name
544 // rather than answered wrongly. Both are now gone.
545 //
546 // `Source.setArrivalBatch` and a process that carries its OWN batch sizes are
547 // MUTUALLY EXCLUSIVE: a BMAP or a BMMAPt already says how many jobs an epoch
548 // releases, so a second law bolted on top would multiply the two.
549 for (std::size_t i = 0; i < sn.nstations; ++i) {
550 const auto& stb = sn.stations[i];
551 for (std::size_t r = 0; r < stb.arrival_batch.size(); ++r) {
552 if (stb.arrival_batch[r].disabled) continue;
553 if (r < sn.service[i].size() && lang::process_is_batch(sn.service[i][r].type))
554 throw InputError(
555 "SolverLDES (native engine): station '" + stb.name + "' class '" +
556 sn.classes[r].name + "' declares BOTH an arrival batch and a " +
557 lang::process_to_text(sn.service[i][r].type) +
558 " arrival process, which carries its own batch sizes; the two are "
559 "mutually exclusive");
560 }
561 }
562 // A BULK SERVER (BMSP) is refused with immediate feedback and with a blocking
563 // destination, the two model-level features its per-firing release cannot honour.
564 // Feedback would have to hand a completed job back into a server the firing clock
565 // owns rather than a slot, and blocking has no answer to "which of the b jobs
566 // just released is the one that blocks". The per-station guards -- single server,
567 // single class, FCFS, no preemption/polling/PAS/setup/load dependence/pools --
568 // are applied where the stations are built.
569 for (std::size_t i = 0; i < sn.nstations; ++i) {
570 if (sn.stations[i].nodetype == NodeType::Source) continue;
571 bool bulk = false;
572 for (std::size_t r = 0; r < sn.nclasses && r < sn.service[i].size(); ++r)
573 if (!sn.disabled[i][r] && lang::process_is_batch(sn.service[i][r].type)) bulk = true;
574 if (!bulk) continue;
575 for (std::size_t r = 0; r < sn.nclasses; ++r)
576 if (i < sn.immfeed.size() && r < sn.immfeed[i].size() && sn.immfeed[i][r])
577 throw UnsupportedError(ErrorKind{"BMAP"},
578 "SolverLDES (native engine): batch (BMSP) service at station '" +
579 sn.stations[i].name + "' is incompatible with immediate feedback");
580 for (std::size_t d = 0; d < sn.nstations && d < sn.droprule.size(); ++d)
581 for (std::size_t r = 0; r < sn.droprule[d].size(); ++r)
582 if (sn.droprule[d][r] == lang::DropStrategy::BAS ||
583 sn.droprule[d][r] == lang::DropStrategy::BBS)
584 throw UnsupportedError(ErrorKind{"BMAP"},
585 "SolverLDES (native engine): batch (BMSP) service at station '" +
586 sn.stations[i].name + "' is incompatible with the blocking rule at "
587 "station '" + sn.stations[d].name +
588 "'; a firing releases several jobs at once and none of them can hold "
589 "the server on the destination's behalf");
590 }
591 // A REPLY SIGNAL completes a SYNCHRONOUS CALL: the caller keeps its server
592 // while the callee runs and gets it back only when the reply arrives. That
593 // is simulated -- see the `pending_reply` map below -- but only where a
594 // server EXISTS to hold. A sharing station divides one server continuously
595 // among everyone present and has no slot to park, so a caller there would
596 // be served as though its call were asynchronous.
597 for (std::size_t r = 0; r < sn.nclasses; ++r) {
598 if (r >= sn.syncreply.size() || sn.syncreply[r] == 0) continue;
599 for (std::size_t i = 0; i < sn.nstations; ++i) {
600 if (sn.stations[i].nodetype == NodeType::Source) continue;
601 if (i < sn.disabled.size() && r < sn.disabled[i].size() && sn.disabled[i][r]) continue;
602 // A SERVICE DECLARED FOR A CLASS THE ROUTING NEVER SENDS HERE IS NOT
603 // A VISIT: only a station some (node, class) pair routes class r
604 // into can see the caller. Same rule as the reference.
605 {
606 const std::size_t ind = sn.station_to_node[i];
607 bool routed = false;
608 for (std::size_t from = 1; from <= sn.nof_nodes() && !routed; ++from)
609 for (std::size_t s2 = 0; s2 < sn.nclasses && !routed; ++s2)
610 routed = num_traits<T>::to_double(sn.route_eff(s2 + 1, r + 1, from, ind)) > 0.0;
611 if (!routed) continue;
612 }
613 if (is_ps_family(sn.stations[i].sched) || sn.stations[i].sched == SchedStrategy::INF)
614 throw UnsupportedError(ErrorKind{"SyncCall"},
615 "SolverLDES (native engine): class '" + sn.classes[r].name +
616 "' makes a synchronous call at station '" + sn.stations[i].name +
617 "', which has no server slot to hold across it");
618 }
619 }
620 // AN NNPP IS AN ARRIVAL PROCESS ONLY. Its thinning-plus-SCIATA construction
621 // generates a point process on absolute time; it defines no service-time
622 // law, so it is refused anywhere but at a Source.
623 for (std::size_t i = 0; i < sn.nstations; ++i) {
624 if (sn.stations[i].nodetype == NodeType::Source) continue;
625 for (std::size_t r = 0; r < sn.nclasses; ++r)
626 if (!sn.disabled[i][r] && sn.procid(i + 1, r + 1) == lang::ProcessType::NNPP)
627 throw UnsupportedError(ErrorKind{"NNPP"},
628 "SolverLDES (native engine): station '" + sn.stations[i].name + "' uses an NNPP as the "
629 "service process of class '" + sn.classes[r].name + "'; an NNPP is an arrival process "
630 "and is supported only at a Source");
631 }
632 // SLOTTED TIME EXCLUDES TWO FAMILIES, and refuses rather than approximates.
633 // NHPP integrates a cumulative intensity over CONTINUOUS time, so its
634 // inverse transform does not land on the lattice; the PS family divides the
635 // server continuously among the jobs in service, which has no discrete-time
636 // counterpart at all. Serving either on a lattice would answer a different
637 // model.
638 if (o.slotted) {
639 // A rate SCHEDULE (NHPP, MAPt, PHt) is refused at EVERY station, the Source
640 // included, as the reference's assertSlottedModelIsSupported does: before
641 // 2026-11-14 this loop skipped the Source and let MAPt/PHt through, so an
642 // NHPP or MAPt arrival failed later, at its first off-lattice draw, with an
643 // InputError where the reference refuses up front with LINE:unsupported:Slotted.
644 for (std::size_t i = 0; i < sn.nstations; ++i) {
645 if (sn.stations[i].nodetype != NodeType::Source && is_ps_family(sn.stations[i].sched))
646 throw UnsupportedError(ErrorKind{"Slotted"},
647 "SolverLDES (native engine): station '" + sn.stations[i].name +
648 "' shares its server continuously, which slotted mode has no "
649 "counterpart for");
650 for (std::size_t r = 0; r < sn.nclasses; ++r) {
651 if (sn.disabled[i][r]) continue;
652 const lang::ProcessType pt = sn.procid(i + 1, r + 1);
655 throw UnsupportedError(ErrorKind{"Slotted"},
656 "SolverLDES (native engine): station '" + sn.stations[i].name +
657 "' carries a " +
658 std::string(pt == lang::ProcessType::NHPP ? "NHPP" :
659 pt == lang::ProcessType::MAPT ? "MAPt" : "PHt") +
660 ", whose rate schedule is integrated over continuous "
661 "time and does not land on the slot lattice");
662 }
663 }
664 // An NNPP thins a continuous-time renewal stream, so its epochs do not land
665 // on the slot lattice either. It sits at a Source, which the loop above skips.
666 for (std::size_t i = 0; i < sn.nstations; ++i)
667 for (std::size_t r = 0; r < sn.nclasses; ++r)
668 if (!sn.disabled[i][r] && sn.procid(i + 1, r + 1) == lang::ProcessType::NNPP)
669 throw UnsupportedError(ErrorKind{"Slotted"},
670 "SolverLDES (native engine): station '" + sn.stations[i].name +
671 "' carries an NNPP, whose arrival epochs are generated in continuous "
672 "time and do not land on the slot lattice");
673 for (std::size_t i = 0; i < sn.nstations; ++i)
674 if (sn.breakdownparam.find(i + 1) != sn.breakdownparam.end())
675 throw UnsupportedError(ErrorKind{"Slotted"},
676 "SolverLDES (native engine): station '" + sn.stations[i].name +
677 "' declares a server breakdown, whose failure and repair epochs are drawn on "
678 "a continuous clock and do not land on the slot lattice");
679 }
680}
681
682/** One station's mutable state. */
686 bool ps = false;
687 bool preemptive = false;
688 bool resume = false; ///< PR (continue the residual) as against PI (redraw)
689 /**
690 * The waiting room is ranked by the job's SAMPLED size, so the size has to
691 * exist before the job enters service. A time-inhomogeneous law is drawn at
692 * the service start instant everywhere else (see `draw_at_arrival`); here it
693 * cannot be, and is drawn on arrival as the reference does.
694 */
695 bool size_ordered = false;
696 std::size_t nservers = 1;
697 std::size_t lps_limit = 0; ///< LPS admission cap; 0 = none
698 double cap = std::numeric_limits<double>::infinity();
699 std::vector<double> classcap;
700 /**
701 * `sn.droprule`, per class, declared on the DESTINATION station.
702 *
703 * JMT's convention and the reference's: the policy belongs to the station
704 * whose capacity is limited, not to the upstream one whose server ends up
705 * blocked. A model that declared it on the source would be read as having
706 * no policy at all.
707 */
708 std::vector<lang::DropStrategy> droprule;
709 /**
710 * Jobs held OUTSIDE this station's buffer but counted in its queue length:
711 * a BAS or BBS job whose destination is full occupies the upstream server
712 * and is charged to the destination, which is where it is queueing for.
713 * Charging it upstream would let a full station report a queue below its
714 * own capacity while jobs pile up in front of it.
715 */
716 std::vector<double> blocked_at;
717 std::vector<double> weight; ///< schedparam, the DPS/GPS weights
718 std::vector<double> class_mean; ///< mean service per class, for SEPT/LEPT
719 /**
720 * `sn.lldscaling`: the RATE multiplier when n jobs are present, indexed
721 * n-1. It divides the sampled service time at an ordinary station and IS
722 * the effective server count at a sharing one -- the same table read two
723 * ways, because a share of c servers and a c-fold rate are the same thing
724 * only for PS.
725 */
726 std::vector<double> lld;
727 /** `sn.cdscaling`: beta_r(n), a per-class RATE at the station's population. */
729 bool has_cd = false;
730 /**
731 * A PASS-AND-SWAP station serves an ORDERED LIST whose total rate is a
732 * function of the whole class sequence (Dorsman and Gardner 2024).
733 *
734 * The rate of the token at position p is the INCREMENT
735 * mu(c1..cp) - mu(c1..c_{p-1}), which is what makes the station
736 * order-independent. On a completion at position p the departing job is not
737 * the one at p: the SWAP GRAPH chains forward from p to the last position
738 * reachable through it, and that job departs while the chain shifts into
739 * the hole. An empty swap graph is the plain OI station, where p itself
740 * departs.
741 */
742 bool pas = false;
743 std::function<double(const std::vector<std::size_t>&)> pas_rate;
744 std::vector<std::vector<bool>> pas_swap;
745 std::vector<Job> pas_list;
746 std::uint64_t pas_tag = 0;
747
748 /**
749 * A POLLING SERVER visits the per-class buffers in a fixed cyclic order,
750 * paying a SWITCHOVER on each leg.
751 *
752 * It advances ONE STEP AT A TIME and pays that step's switchover whether or
753 * not the buffer it reaches holds work. Skipping ahead to the next
754 * non-empty buffer for a single switchover is a different and much faster
755 * discipline: it shortens the cycle and understates the waiting time by
756 * tens of percent against Takagi's exact formulas, which assume the walking
757 * server. The one exception is a lap made entirely of zero-time legs, which
758 * would spin forever at the same instant: there the server PARKS and the
759 * next arrival restarts it.
760 *
761 * The switchover charged to a leg is the one stored against the buffer
762 * being LEFT -- that is Takagi's r_i and what `Queue.setSwitchover` means --
763 * not the one against the buffer being entered.
764 */
765 bool polling = false;
766 std::size_t poll_at = 0; ///< the buffer the server is serving or heading to
767 bool poll_switching = false;
768 bool poll_parked = false;
769 std::size_t poll_budget = 0; ///< remaining visit budget; 0 = exhausted
770 std::size_t poll_gate = 0; ///< DECREMENTING: jobs found at the polling instant
772 std::size_t poll_k = 1;
773 std::vector<Sampler> switchover;
774 std::vector<bool> has_switchover;
775
776 /**
777 * ROUND ROBIN (`SchedStrategy::RR`): the per-class quantum law, and per slot
778 * the identity of the quantum clock armed for the job it serves, 0 when
779 * none. The clock has its OWN identity rather than the slot's `server_tag`
780 * because a rate change retags the departure (`sd_reschedule_one`) without
781 * restarting the quantum, which is wall-clock time.
782 */
783 bool rr = false;
784 std::vector<Sampler> rr_quantum;
785 std::vector<std::uint64_t> rr_qtag;
786
787 /**
788 * POLLING EXTENSIONS (`set_polling_table`, `set_polling_order`,
789 * `set_polling_timer`), the event-driven counterpart of
790 * `State.pollingInfo`/`pollingAdvance` and of the Java engine's
791 * `pollingExtAdvance`. A station with none of them leaves `poll_ext` false
792 * and keeps the cyclic walk above untouched.
793 *
794 * The server walks a RING of positions: the table entries, or the polled
795 * classes in cyclic order, or (under a load-dependent order) the classes
796 * themselves. `poll_leg[p]` is the walk OUT of position p (under a
797 * load-dependent order, out of class p), absent when immediate. Under a
798 * visit timer the visit ends when the timer fires: after the job in
799 * service (non-preemptive), or at once with that job put back at the head
800 * of its buffer to restart (preemptive). A GLOBAL timer is a timed token:
801 * `poll_trt[r]` is the absolute expiry of class r's token rotation timer,
802 * restarted at every arrival of the token at r, and the visit may hold the
803 * server only for what was left of the previous rotation.
804 */
805 bool poll_ext = false;
806 std::vector<std::size_t> poll_ring; ///< class (0-based) at each position
807 std::size_t poll_pos = 0; ///< current position in the ring
808 std::vector<Sampler> poll_leg;
809 std::vector<bool> poll_has_leg;
811 std::size_t poll_thr_class = 0; ///< THRESHOLD priority class, 0-based
812 long poll_thr_l = 0;
814 bool poll_preempt = false;
815 std::vector<Sampler> poll_tlaw; ///< visit timer law per class
816 std::vector<bool> poll_has_tlaw;
817 std::vector<bool> poll_polled;
818 std::vector<double> poll_trt; ///< GLOBAL: token rotation timer expiry per class
819 bool poll_trt_ready = false;
820 std::uint64_t poll_timer_tag = 0; ///< the live visit timer, 0 = none
821 bool poll_expired = false; ///< non-preemptive: end the visit at the next completion
822
823 /**
824 * SETUP AND DELAY-OFF: servers that power down when they fall idle.
825 *
826 * EACH SERVER runs its own four-state machine, as the reference's
827 * `Solver_ssj.ServerState` does: ACTIVE, OFF, SETUP, DELAYOFF, all servers
828 * starting ACTIVE. An arrival takes the first ACTIVE idle server; failing
829 * that the first DELAYOFF one, whose timer is cancelled so the job pays
830 * nothing; failing that the first OFF one, which starts a setup under the
831 * ARRIVING class's law while the job waits; failing all three it waits.
832 * A server freed with nobody waiting enters DELAYOFF under the DEPARTING
833 * class's law, and only when that class declares both laws; a completed
834 * setup serves the head of the queue or idles ACTIVE with no timer.
835 *
836 * Keeping ONE machine per station, as this engine did before 2026-11-24,
837 * let one setup power every server and started the delay-off only when the
838 * whole station emptied: at c = 2 that read 1.822 against CTMC 1.789.
839 *
840 * The laws are PER CLASS (`sn.setupparam`). A declared delay-off of zero
841 * mean shuts the server down the instant it empties; see `doff_zero`.
842 */
843 bool has_setup = false;
844 std::vector<Sampler> setup_law; ///< [class], valid where has_setup_law
845 std::vector<bool> has_setup_law; ///< a setup of positive mean is declared
846 std::vector<Sampler> doff_law; ///< [class], valid where has_doff_law
847 std::vector<bool> has_doff_law; ///< a delay-off of positive mean is declared
848 std::vector<bool> doff_zero; ///< a delay-off is declared with zero mean
849 std::vector<int> power; ///< [slot] PowerState
850 std::vector<std::uint64_t> power_tag; ///< [slot] generation of the live power timer
851 /** Does a server freed by class `r` enter DELAYOFF (or power down at once)? */
852 bool powers_down_after(std::size_t r) const {
853 return has_setup && r < has_setup_law.size() && has_setup_law[r] &&
854 (has_doff_law[r] || doff_zero[r]);
855 }
856
857 /**
858 * RETRIAL: a retrial station has NO WAITING ROOM. A job of a retrial class
859 * that finds every server busy joins an ORBIT and re-offers itself later;
860 * a freed server is never filled from the orbit, only by a retry.
861 *
862 * The orbit is not a waiting line, but it IS part of the station
863 * population, as in the reference (MATLAB SSA holds it in the station, MAM
864 * and CTMC count it in QLen, manual Section 5.3.5): QLen counts orbiting
865 * jobs, the response time runs from the first arrival, and the capacity
866 * bounds service plus orbit, so setOrbit's cap = nservers + maxOrbit is
867 * what loses a job arriving to a full orbit.
868 */
869 std::vector<Sampler> retrial;
870 std::vector<bool> has_retrial;
871 std::vector<int> max_attempts;
872 std::vector<int> retrial_policy; ///< 1 = LINEAR (a clock per job), 2 = CONSTANT (one per orbit)
873 std::vector<bool> const_pending; ///< CONSTANT: the shared clock is armed
874 std::vector<std::deque<Job> > orbit; ///< per class, oldest first
875 std::vector<Sampler> orbit_abandon;
876 std::vector<bool> has_orbit_abandon;
877 std::vector<double> orbit_size; ///< live, per class
878 std::vector<double> tot_orbit; ///< time integral of the orbit size
879 double orbit_last = 0.0;
880 std::vector<double> retried, retrial_lost;
881
882 /** Reneging: the abandonment timer of a WAITING job, per class. */
883 std::vector<Sampler> patience;
884 std::vector<bool> has_patience;
885 /** Balking: the (min, max, probability) triples an arrival consults. */
886 struct BalkRule {
887 double min_jobs = 0.0;
888 double max_jobs = -1.0; ///< -1 = unbounded above, the wire's spelling
889 double probability = 0.0;
890 };
891 std::vector<std::vector<BalkRule>> balk;
892 std::vector<Sampler> svc;
893 std::vector<bool> off;
894
895 /**
896 * BULK SERVICE (BMSP): a THIRD station kind, beside the buffered one and the
897 * sharing one.
898 *
899 * A BMAP or BMMAPt assigned as a SERVICE process is a batch Markovian service
900 * process: the station has no per-job service time at all, only a station-level
901 * FIRING CLOCK, and one firing completes min(b, present) jobs at once. Neither
902 * existing path can express that -- `draw_at_arrival` gives every job a
903 * `Job::service`, and a sharing station divides one server among everyone -- so
904 * this is its own arm in the admit path and in the departure arm.
905 *
906 * The clock is armed when the station goes from EMPTY to non-empty and re-armed
907 * at every firing, so the server fires continuously while it holds work. That is
908 * what makes a wall-clock schedule walk exact for a BMMAPt clock: the firing
909 * interval is drawn from the instant the clock is armed, never from a job's
910 * arrival.
911 *
912 * Restricted BY NAME to a single-server, single-class FCFS queue with no
913 * preemption, polling, PAS, setup, load dependence, server pools, immediate
914 * feedback or blocking destination, exactly as the Java engine restricts it: a
915 * bulk server is a single server by construction, and "which of the b jobs it
916 * just released is the one blocking" has no answer.
917 */
918 bool bmsp = false;
919 std::size_t bmsp_cls = 0; ///< the one enabled class
920 std::size_t bmsp_pending = 1; ///< jobs the armed firing will complete
921 std::uint64_t bmsp_tag = 0; ///< neutralises a superseded firing
922
923 /**
924 * HETEROGENEOUS SERVER POOLS, empty on a station whose servers are alike.
925 *
926 * A pool is `count` servers that accept only `compatible` classes and serve
927 * them at a law of their own, so a model that declares them is a DIFFERENT
928 * system from the multiserver it would otherwise look like: flattening the
929 * pools into `nservers` answers that other system, plausibly and silently.
930 *
931 * The slots are laid out POOL BY POOL in declaration order, so slot
932 * `type_first[t] .. type_first[t] + type_count[t] - 1` belongs to pool `t`
933 * and `server_type[slot]` is the inverse. Every other part of the engine
934 * addresses a server by its slot and needs to know nothing about this.
935 */
936 bool has_pools = false;
937 std::vector<std::size_t> server_type; ///< per slot, its pool
938 std::vector<std::size_t> type_first; ///< per pool, its first slot
939 std::vector<std::size_t> type_count; ///< per pool, its server count
940 std::vector<std::vector<bool>> type_compat; ///< [pool][class]
941 std::vector<std::vector<Sampler>> type_svc; ///< [pool][class]
942 std::vector<std::vector<bool>> type_has_svc; ///< [pool][class], a law of its own
943 std::vector<std::vector<double>> type_rate; ///< [pool][class], 1/mean, for FSF
945 /** ALIS/FAIRNESS rotate this order; a used pool goes to the back. */
946 std::vector<std::size_t> type_order;
947 /** ALFS walks the pools least-flexible first: fewest compatible classes. */
948 std::vector<std::size_t> alfs_order;
949
950 /**
951 * The waiting room, as an EXPLICIT HEAP rather than a `std::priority_queue`.
952 *
953 * FSP is why. Its order is the virtual finish time of a processor-sharing
954 * schedule over the residual work PRESENT AT THE STATION, so it changes
955 * whenever the station's composition does and cannot be stamped on a job
956 * when it arrives. A container that hides its storage cannot be reordered
957 * or rescanned; this one is scanned linearly for FSP and kept as a heap
958 * for every other discipline, whose keys are per-job constants.
959 */
960 std::vector<Job> buffer;
962 std::vector<Job> server;
963 std::vector<bool> server_busy;
964 std::vector<double> server_start; ///< instant the held job entered service
965 std::vector<std::uint64_t> server_tag;
966 /**
967 * A server holding a completed job it cannot hand on, because its
968 * destination is full. It is NOT free: refusing to start a new service is
969 * the whole content of blocking, and a blocked slot treated as idle turns
970 * a blocking network into a lossless one with the same topology.
971 */
972 std::vector<bool> server_blocked;
973 /**
974 * A server HELD ACROSS A SYNCHRONOUS CALL. Its job has left for the callee
975 * and the slot is NOT free: releasing it would let the caller serve someone
976 * else while its own call is outstanding, which is the asynchronous model
977 * under the synchronous one's name. Separate from `server_blocked`, which
978 * holds a COMPLETED job whose destination is full.
979 */
980 std::vector<bool> server_held;
981 std::vector<std::size_t> held_cls;
982 std::vector<Job> blocked_job;
983 std::vector<std::size_t> blocked_dest;
984 std::vector<std::size_t> blocked_dest_cls;
985
986 // sharing disciplines
987 std::vector<PsJob> ps_jobs;
988 double ps_last_update = 0.0;
989
990 /**
991 * True when the station's service RATE depends on its own population, i.e.
992 * it declares a load- or class-dependence table.
993 *
994 * Such a station cannot schedule a departure once and forget it: the rate
995 * in force changes every time the population does, so the residual work
996 * must be integrated forward and the completion re-timed at each change --
997 * the same discipline a sharing station needs, for a different reason.
998 * Applying the scaling only at service start would time every completion
999 * at the rate that happened to hold when it began.
1000 */
1001 bool state_dependent = false;
1002 /**
1003 * True when the service requirement is drawn when a server TAKES the job,
1004 * not when it joins the station: every non-preemptive, non-sharing queue
1005 * outside polling, round robin, PAS, bulk service and the size-ranked
1006 * disciplines. That is where the reference draws it (`serviceTimeOnServer`),
1007 * and the instant matters to the sample path whenever the service order
1008 * differs from the arrival order on one (station, class) stream: LCFS,
1009 * SIRO, an immediate feedback that keeps the server. Under
1010 * FCFS the two instants consume the stream in the same order.
1011 */
1012 bool draw_at_start = false;
1013 /** max(c, max(alpha)): the peak capacity the utilization is reported against. */
1014 double util_peak = 1.0;
1015 /**
1016 * Class or joint dependence: the declared peak per class, the product over the declared families of the
1017 * largest entry within the class's CHAIN, as solver_nc_conv normalizes. A single station-wide maximum halved
1018 * the utilization of a class whose own peak is 1 (setClassDependence(beta, [2 1]) gave B 0.22 for 0.44).
1019 */
1020 std::vector<double> cd_peak_class;
1021 /**
1022 * `Queue.setServerParallelism(class, n)`: the servers a class-r job seizes
1023 * for the whole of its service, one entry per class.
1024 *
1025 * The job holds the WHOLE SET or it waits, so the station serves at most
1026 * floor(c/n) of them at once and the utilization one contributes is n/c
1027 * rather than 1/c. That is JMT's `Server.serverNumRequired`, and it is not
1028 * the same model as an n-fold slower server, which would leave the other
1029 * slots free for someone else.
1030 */
1031 std::vector<std::size_t> parallelism;
1032 bool has_parallelism = false;
1033 /**
1034 * The further slots held beside each primary one, so that releasing the
1035 * primary releases the whole set. Empty at a station that declares none.
1036 */
1037 std::vector<std::vector<std::size_t> > held_extra;
1038 /**
1039 * The declared peak of the GLOBAL (Whittle) dependence at this station, one
1040 * entry per class, 1 when the model declares none.
1041 *
1042 * It MULTIPLIES whatever peak the station already reports against, because
1043 * phi multiplies the rate the class-, joint- and load-dependent scalings
1044 * have already set; `getPeakScaling` folds the same product.
1045 */
1046 std::vector<double> gd_peak;
1047 /**
1048 * The class-dependent speed a SHARING station is running at right now, one
1049 * entry per class.
1050 *
1051 * It is cached rather than recomputed because `ps_advance` integrates the
1052 * interval that just ENDED while the caller has already written the new
1053 * population: reading the handle there would credit that interval at the
1054 * speed that only starts now. `ps_reschedule` refreshes it in the same
1055 * breath as it re-times the departures, which is the moment the new speed
1056 * actually takes effect -- the same flush-then-install order
1057 * `Accum::set_busy_scale` uses for load dependence.
1058 */
1059 std::vector<double> ps_cd;
1060 /**
1061 * Server breakdown: the server alternates up and down on two clocks.
1062 *
1063 * `down_scale[r]` is the RATE MULTIPLIER while down, `down_rate(r) *
1064 * E[S(i,r)]`, so the whole outage is expressed as a state-dependent rate
1065 * change and needs no separate machinery: a zero multiplier stalls the job
1066 * with its residual intact (nothing is rescheduled, so nothing departs
1067 * until repair) and a positive one is the degraded server. That is exactly
1068 * the reference's semantics -- a breakdown does not evict the job in
1069 * service, and `downServiceRates` degrades rather than stops.
1070 */
1071 bool has_breakdown = false;
1072 bool up = true;
1073 std::vector<double> down_scale;
1074 /** The declared absolute rate, kept so the scale can be formed once E[S] is known. */
1075 std::vector<double> down_rate_raw;
1077 double sd_last_update = 0.0;
1078};
1079
1080/**
1081 * The job placement the model's DECLARED initial state stands for, station-major
1082 * like `init_sol`, or empty when there is none to take.
1083 *
1084 * Port of the JAR's `Solver_ldes_analyzer.deriveInitSolFromState`, so both engines
1085 * start from the same placement and inject it in the same order. A station's
1086 * declared state is its (statespace, stateprior) pair, which
1087 * `Network::set_state_prior` and the reader of `initialState` write and which
1088 * CTMC, SSA, FLD and JMT start from; the weighed row gives the per-class COUNT
1089 * at each Queue and Delay. The engine draws every service afresh, so buffer
1090 * order and phase are not carried, exactly as for `init_sol`. Empty, and so the
1091 * reference-station default, when a Queue or Delay declares nothing or the
1092 * counts do not conserve every closed population; a prior over rows with
1093 * different counts is refused, since one run starts from one placement.
1094 */
1095template <class T>
1097 using lang::NodeType;
1098 const std::size_t M = sn.stations.size(), K = sn.nclasses;
1099 std::vector<double> placed(M * K, 0.0), totals(K, 0.0);
1100 for (std::size_t ist = 1; ist <= M; ++ist) {
1101 const NodeType nt = sn.stations[ist - 1].nodetype;
1102 if (nt != NodeType::Queue && nt != NodeType::Delay) continue;
1103 const std::size_t ind = sn.node_of_station(ist);
1104 typename std::map<std::size_t, std::vector<T> >::const_iterator sp = sn.stateprior.find(ind);
1105 typename std::map<std::size_t, Matrix<T> >::const_iterator ss = sn.statespace.find(ind);
1106 if (sp == sn.stateprior.end() || ss == sn.statespace.end() || ss->second.rows() == 0)
1107 return std::vector<double>();
1108 std::vector<std::size_t> ph(K, 1), shift(K, 0);
1109 std::size_t w = 0;
1110 for (std::size_t k = 0; k < K; ++k) {
1111 ph[k] = sn.phasessz_of(ist, k + 1);
1112 shift[k] = w;
1113 w += ph[k];
1114 }
1115 const std::size_t nvar = sn.nvars_of(ind);
1116 const Matrix<T>& space = ss->second;
1117 const std::size_t base = (ist - 1) * K;
1118 bool first = true;
1119 for (std::size_t row = 0; row < space.rows(); ++row) {
1120 if (row >= sp->second.size() || !(num_traits<T>::to_double(sp->second[row]) > 0.0)) continue;
1121 std::vector<T> v(space.cols());
1122 for (std::size_t c = 0; c < space.cols(); ++c) v[c] = space(row, c);
1123 const qn::Marginal<T> m = qn::to_marginal(sn, ist, v, ph, shift, nvar);
1124 for (std::size_t r = 0; r < K; ++r) {
1125 const double n = num_traits<T>::to_double(m.nir[r]);
1126 if (first) {
1127 placed[base + r] = n;
1128 } else if (n != placed[base + r]) {
1129 throw UnsupportedError(ErrorKind{"StatePrior"},
1130 "SolverLDES (native engine): the initial state of station '" +
1131 sn.stations[ist - 1].name + "' is a distribution over different "
1132 "job counts; LDES starts every run from one placement");
1133 }
1134 }
1135 first = false;
1136 }
1137 if (first) return std::vector<double>();
1138 for (std::size_t r = 0; r < K; ++r) totals[r] += placed[base + r];
1139 }
1140 for (std::size_t r = 0; r < K; ++r) {
1141 if (sn.classes[r].type == lang::JobClassType::OPEN) continue;
1142 if (std::fabs(totals[r] - sn.classes[r].population) > 1e-6) return std::vector<double>();
1143 }
1144 return placed;
1145}
1146
1147} // namespace engine
1148
1149/**
1150 * Simulate `sn` in process and return the same record the subprocess client
1151 * parses out of an `ldes-result` document.
1152 *
1153 * A metric the run did not measure stays EMPTY rather than becoming a matrix
1154 * of zeros: zero is a measurement and absence is not.
1155 */
1156template <class T>
1158 using namespace engine;
1159 using lang::NodeType;
1160 using lang::SchedStrategy;
1161
1162 /**
1163 * --sample-path: ONE UNAVERAGED RUN FROM TIME 0, stopped by its row count,
1164 * as the reference runs it: no warmup removal, no convergence stop and no
1165 * completion cap. With the export off `o` IS the caller's options and
1166 * nothing below takes a different branch.
1167 */
1168 const bool sp_on = o_in.sample_path_events > 0;
1169 LdesOptions o_sp;
1170 if (sp_on) {
1171 o_sp = o_in;
1172 o_sp.tranfilter = "none";
1173 o_sp.cnvgon = false;
1174 }
1175 const LdesOptions& o = sp_on ? o_sp : o_in;
1176
1177 ldes_engine_reject(sn, o);
1178
1179 const std::size_t M = sn.nstations, K = sn.nclasses;
1180 if (M == 0 || K == 0) throw InputError("SolverLDES (native engine): empty model");
1181
1182 // --maxtime / options.timeout: the COOPERATIVE wall-clock budget, capped by
1183 // any budget armed around this call. The event loop polls it on a stride
1184 // and stops with stoppingReason "max_time", the JAR's label, keeping what
1185 // it measured so far as the interim result.
1187 bool time_stopped = false;
1188 std::uint64_t wall_tick = 0;
1189
1190 const std::uint64_t max_events =
1191 sp_on ? std::numeric_limits<std::uint64_t>::max()
1192 : static_cast<std::uint64_t>(o.events > 0 ? o.events : o.samples);
1193 if (max_events == 0)
1194 throw InputError("SolverLDES (native engine): the completion budget is zero");
1195
1196 // ---- random streams, one band per role ---------------------------------
1197 const std::uint64_t base =
1198 (o.seed >= 0) ? static_cast<std::uint64_t>(o.seed) : std::random_device{}();
1199 /**
1200 * Snap a sampled duration onto the slot lattice, or REFUSE it.
1201 *
1202 * A non-lattice sample is an ERROR, not something to round: rounding
1203 * silently changes the distribution, and a model whose service law is not
1204 * lattice-valued is not a discrete-time model. The reference refuses for
1205 * the same reason. Only Geometric, Det with an integral slot count, and
1206 * DMAP produce lattice values.
1207 */
1208 const bool slotted = o.slotted;
1209 const double slot_len = o.slot_length;
1210 auto slot_snap = [&](double v, const char* what) -> double {
1211 if (!slotted || v == 0.0) return v;
1212 const double slots = v / slot_len;
1213 const double rounded = std::floor(slots + 0.5);
1214 if (rounded < 1.0 || std::fabs(slots - rounded) > 1e-9 * std::max(1.0, slots))
1215 throw InputError(std::string("SolverLDES (native engine): slotted mode sampled a ") +
1216 what + " of " + std::to_string(v) +
1217 ", which is not a positive multiple of the slot length " +
1218 std::to_string(slot_len) +
1219 "; a discrete-time model needs lattice-valued interarrival and "
1220 "service times, e.g. Geometric or Det on an integral slot count");
1221 return rounded * slot_len;
1222 };
1223
1224 /**
1225 * SAMPLE-PATH CAPTURE AROUND A DRAW. With the export off these are the bare
1226 * draw, so the run is the one it always was; with it on, a walked family is
1227 * handed the recorder's trace for this one draw and the value is captured
1228 * AFTER the slot snap, as the reference captures it. Nothing here touches a
1229 * simulation stream: the trace reads the walk the draw takes anyway.
1230 */
1231 sp::Tracker spt;
1232 // An NHPP SERVICE draws its Exp(1) operational-time budget instead of a wall
1233 // duration (`Sampler::op_time`); the engine times it with `svc_delay`.
1234 auto svc_variate = [](Sampler& smp, Rng& g, double at) -> double {
1235 return smp.op_time() ? smp.op_budget(g) : smp.next_at(g, at);
1236 };
1237 auto sp_draw_svc = [&](std::size_t i, std::size_t k, Sampler& smp, Rng& g, double at) -> double {
1238 if (!sp_on) return slot_snap(svc_variate(smp, g, at), "service time");
1239 if (sp::walked(smp, false)) smp.set_trace(spt.trace_fill());
1240 const double v = slot_snap(svc_variate(smp, g, at), "service time");
1241 smp.set_trace(nullptr);
1242 spt.capture_service(i, k, v, smp.erlang_k());
1243 return v;
1244 };
1245 auto sp_draw_arr = [&](std::size_t st, std::size_t k, Sampler& smp, Rng& g, double at) -> double {
1246 if (!sp_on) return slot_snap(smp.next_at(g, at), "interarrival time");
1247 if (sp::walked(smp, true)) smp.set_trace(spt.trace_fill());
1248 const double v = slot_snap(smp.next_at(g, at), "interarrival time");
1249 smp.set_trace(nullptr);
1250 spt.capture_arrival(st, k, v, smp.erlang_k(), at);
1251 return v;
1252 };
1253
1254 /**
1255 * ONE STREAM PER (node, class), with the reference's own offsets.
1256 *
1257 * `Solver_ssj` never shares a stream between two generators: it builds one
1258 * MRG32k3a and one java.util.Random per (node, class) and seeds them from
1259 * (seed, offset), the MRG stream through the `rng::SeedHash` of the pair and
1260 * the Random from `seed + offset`, with
1261 *
1262 * arrival (source s, class k) stream (s*K + k)*10, random the same + 2000
1263 * service (svc j, class k) both ((numSources + j)*K + k)*10 + 1000
1264 * routing ROUTING_SEED_BASE = 900000
1265 *
1266 * where `numSources` counts SOURCE nodes and `j` indexes the SERVICE nodes
1267 * in order, neither of which is the station index. Sharing three run-wide
1268 * streams instead, as this engine did, changes the interleaving of every
1269 * draw: two stations that each consume their own stream in the reference
1270 * would take turns from one here, so the paths diverge from the first event
1271 * even with identical generators and identical quantiles.
1272 *
1273 * The station-level draws that are not per-class -- a polling switchover,
1274 * a setup or delay-off, an SPN transition -- sit on `g_aux[station]` in a
1275 * band of their own, mirroring the reference's own
1276 * `(numSources + numServiceNodes + j)` family without claiming to match it
1277 * draw for draw.
1278 */
1279 const long long seed_ll = static_cast<long long>(base);
1280 const long long Kll = static_cast<long long>(K);
1281 std::size_t num_sources = 0, num_service_nodes = 0;
1282 std::vector<std::size_t> svc_index(M, 0);
1283 for (std::size_t i = 0; i < M; ++i) {
1284 if (sn.stations[i].nodetype == NodeType::Source) {
1285 ++num_sources;
1286 } else {
1287 svc_index[i] = num_service_nodes++;
1288 }
1289 }
1290 const long long nsrc = static_cast<long long>(num_sources);
1291 const long long nsvc = static_cast<long long>(num_service_nodes);
1292
1293 std::vector<Rng> g_arr; ///< [class], at the (single) source
1294 g_arr.reserve(K);
1295 for (std::size_t k = 0; k < K; ++k) {
1296 const long long off = (static_cast<long long>(k)) * 10; // srcIdx == 0
1297 g_arr.push_back(Rng(seed_ll, off, off + 2000));
1298 }
1299 std::vector<std::vector<Rng>> g_svc; ///< [station][class]
1300 g_svc.reserve(M);
1301 for (std::size_t i = 0; i < M; ++i) {
1302 std::vector<Rng> row;
1303 row.reserve(K);
1304 for (std::size_t k = 0; k < K; ++k) {
1305 const long long off =
1306 ((nsrc + static_cast<long long>(svc_index[i])) * Kll + static_cast<long long>(k)) *
1307 10 + 1000;
1308 row.push_back(Rng(seed_ll, off));
1309 }
1310 g_svc.push_back(row);
1311 }
1312 // [station][pool][class]: a heterogeneous pool's own service stream, on the
1313 // reference's own bands (`createHeteroServiceGenerator` and the
1314 // `heteroServiceRng` loop of Solver_ssj): base svcIdx*1000 + pool*100 + k,
1315 // with svcIdx WITHOUT the source offset, plus 7000 for the MRG stream and
1316 // 8000 for the java.util.Random the Markovian samplers read (aligned
1317 // 2026-11-14; the old private band 600000 + 137*pool drew a different path).
1318 std::vector<std::vector<std::vector<Rng>>> g_hsvc(M);
1319 for (std::size_t i = 0; i < M; ++i) {
1320 const std::size_t nT = sn.stations[i].server_types.size();
1321 g_hsvc[i].resize(nT);
1322 for (std::size_t t = 0; t < nT; ++t) {
1323 g_hsvc[i][t].reserve(K);
1324 for (std::size_t k = 0; k < K; ++k) {
1325 const long long base = static_cast<long long>(svc_index[i]) * 1000 +
1326 static_cast<long long>(t) * 100 +
1327 static_cast<long long>(k);
1328 g_hsvc[i][t].push_back(Rng(seed_ll, base + 7000, base + 8000));
1329 }
1330 }
1331 }
1332 // [station][class]: the PATIENCE and RETRIAL clocks, on the reference's own
1333 // bands. `Solver_ssj` seeds each from (svcIdx*K + k)*10 + 50000 (patience)
1334 // and + 60000 (retrial), with svcIdx WITHOUT the source offset the service
1335 // band carries, and the java.util.Random that `createImpatienceGenerator`
1336 // gives the Markovian families from + 70000 for both. Drawing them off the
1337 // SERVICE stream instead, as before 2026-11-14, interleaved every reneging
1338 // or retrial clock with the service draws of the same (station, class).
1339 std::vector<std::vector<Rng>> g_pat(M), g_retr(M);
1340 for (std::size_t i = 0; i < M; ++i)
1341 for (std::size_t k = 0; k < K; ++k) {
1342 const long long b = (static_cast<long long>(svc_index[i]) * Kll +
1343 static_cast<long long>(k)) * 10;
1344 g_pat[i].push_back(Rng(seed_ll, b + 50000, b + 70000));
1345 g_retr[i].push_back(Rng(seed_ll, b + 60000, b + 70000));
1346 }
1347 std::vector<Rng> g_aux; ///< [station], the draws that carry no class
1348 g_aux.reserve(M);
1349 for (std::size_t i = 0; i < M; ++i) {
1350 const long long off = ((nsrc + nsvc + static_cast<long long>(svc_index[i])) * Kll) * 10;
1351 g_aux.push_back(Rng(seed_ll, off));
1352 }
1353 // [station][class]: the SETUP and DELAY-OFF clocks, on the reference's own
1354 // bands. `Solver_ssj` seeds one MRG32k3a per (service node, class) from
1355 // ((numSources + numServiceNodes + svcIdx)*K + k)*10 + 3000 (setup) and
1356 // + 4000 (delay-off). Its Markovian samplers there read a java.util.Random
1357 // seeded from the stream's identity hash, which no other process can
1358 // reproduce, so only the renewal families (Exp, Erlang, HyperExp, Det, ...)
1359 // can share a sample path with it; the Random here takes the same offset.
1360 std::vector<std::vector<Rng>> g_setup(M), g_doff(M);
1361 for (std::size_t i = 0; i < M; ++i) {
1362 if (sn.setupparam.find(i + 1) == sn.setupparam.end()) continue;
1363 for (std::size_t k = 0; k < K; ++k) {
1364 const long long b = ((nsrc + nsvc + static_cast<long long>(svc_index[i])) * Kll +
1365 static_cast<long long>(k)) * 10;
1366 g_setup[i].push_back(Rng(seed_ll, b + 3000));
1367 g_doff[i].push_back(Rng(seed_ll, b + 4000));
1368 }
1369 }
1370 // The round-robin quantum of [station][class], on the band `Solver_ssj`
1371 // gives `rrQuantumGens` (4400000 + svcIdx*K + k). Only an RR station has a
1372 // row, so no other model's streams are touched.
1373 std::vector<std::vector<Rng>> g_rr(M);
1374 for (std::size_t i = 0; i < M; ++i) {
1375 if (sn.stations[i].sched != SchedStrategy::RR) continue;
1376 g_rr[i].reserve(K);
1377 for (std::size_t k = 0; k < K; ++k)
1378 g_rr[i].push_back(Rng(seed_ll, 4400000LL + static_cast<long long>(svc_index[i]) * Kll +
1379 static_cast<long long>(k)));
1380 }
1381 Rng g_routing(seed_ll, 900000); // ROUTING_SEED_BASE
1382 // The SPN transition clocks are a model-level draw, not a station's.
1383 // The reference bands the place generators at +5000; this is that band.
1384 Rng g_spn(seed_ll, 5000);
1385 // The SIRO pick of a queueing place's embedded queue, on a band of its own:
1386 // a place that serves FCFS or INF never reaches it, so adding the discipline
1387 // to the engine moves no other model's draws.
1388 Rng g_qplace(seed_ll, 5001);
1389 // The fork degree and branch activation draws, on the reference's own
1390 // `new Random(seed + 88888)` band. DRAWN FROM ONLY BY A FORK THAT DECLARES
1391 // AN OVERRIDE: a plain fork must consume nothing here, or every seeded
1392 // golden and the bit-exact agreement with the Java engine would move.
1393 Rng g_fork(seed_ll, 88888);
1394 // THE SIRO KEY of an admitted job, on the reference's `new Random(seed + 99999)` band (`siroRng`). It used to
1395 // come off g_routing, which made every admission consume a ROUTING draw the Java engine never takes, so any
1396 // model whose routing stream is read at all (a probabilistic split, a balk) parted company with the reference
1397 // path. Only SIRO reads the key; the routing stream now carries only the draws Java's routingRng carries.
1398 Rng g_siro(seed_ll, 99999);
1399
1400 /**
1401 * True when a fork's parameters actually vary: some branch is uncertain,
1402 * some link carries a count other than the scalar, or some link draws its
1403 * count. A fork that declares the matrices but leaves them uniform stays on
1404 * the fixed path, so it keeps drawing nothing.
1405 */
1406 auto fork_is_variable = [&](std::size_t node) -> bool {
1407 const auto* fp = sn.fork_param_of(node);
1408 if (fp == 0) return false;
1409 const double tpl = sn.nodes[node - 1].tasks_per_link;
1410 for (std::size_t k = 0; k < fp->fan_out_link.rows(); ++k)
1411 for (std::size_t r = 0; r < fp->fan_out_link.cols(); ++r) {
1412 const double p = static_cast<double>(fp->fan_out_prob(k, r));
1413 if (p == 0.0) continue; // link not taken
1414 if (p != 1.0) return true;
1415 if (static_cast<double>(fp->fan_out_link(k, r)) != tpl) return true;
1416 if (!fp->fan_out_dist[k][r].disabled) return true;
1417 }
1418 return false;
1419 };
1420
1421 /** One draw from a jobs-per-link distribution, by inverse CDF on its pmf. */
1422 auto sample_fork_degree = [&](const auto& d) -> int {
1423 double tot = 0.0;
1424 for (std::size_t e = 0; e < d.params.size(); ++e) tot += static_cast<double>(d.params[e]);
1425 const double u = g_fork.aux.next_double() * tot;
1426 double accp = 0.0;
1427 for (std::size_t e = 0; e < d.params.size(); ++e) {
1428 accp += static_cast<double>(d.params[e]);
1429 if (u <= accp)
1430 return static_cast<int>((d.trace.empty() ? static_cast<double>(e + 1) : static_cast<double>(d.trace[e])) +
1431 0.5);
1432 }
1433 return static_cast<int>(
1434 (d.trace.empty() ? static_cast<double>(d.params.size()) : static_cast<double>(d.trace.back())) + 0.5);
1435 };
1436
1437 // ---- stations ----------------------------------------------------------
1438 std::vector<StationState> S(M);
1439 std::size_t source_st = M;
1440 std::vector<int> classprio(K, 0);
1441 std::vector<double> classdeadline(K, std::numeric_limits<double>::infinity());
1442 for (std::size_t r = 0; r < K; ++r) {
1443 classprio[r] = sn.classes[r].prio;
1444 classdeadline[r] = sn.classes[r].deadline;
1445 }
1446
1447 for (std::size_t i = 0; i < M; ++i) {
1448 const auto& st = sn.stations[i];
1449 StationState& s = S[i];
1450 s.sched = st.sched;
1451 s.off.assign(K, true);
1452 s.class_mean.assign(K, 0.0);
1453 s.weight.assign(K, 1.0);
1454 for (std::size_t r = 0; r < K; ++r)
1455 if (r < st.schedparam.size()) s.weight[r] = num_traits<T>::to_double(st.schedparam[r]);
1456
1457 if (st.nodetype == NodeType::Source) {
1458 s.role = Role::Source;
1459 source_st = i;
1460 } else if (st.nodetype == NodeType::Fork || st.nodetype == NodeType::Join ||
1461 st.nodetype == NodeType::Place || st.nodetype == NodeType::Transition) {
1462 // A Place holds tokens and a Transition moves them; neither serves,
1463 // so neither belongs in the service-station setup.
1464 s.role = Role::Synchronization;
1465 // A JOIN STILL REPORTS. It serves nothing, so it stays out of the
1466 // setup below, but it holds siblings and releases parents and the
1467 // result assembly must read those rows; leaving every class OFF is
1468 // what emitted it as an all-zero station. `off` gates the report
1469 // here, not admission: `admit` is never reached through a Join.
1470 if (st.nodetype == NodeType::Join) s.off.assign(K, false);
1471 // A PLACE STILL REPORTS, for the same reason a Join does: it holds
1472 // tokens and the result assembly has to read its rows. The marking
1473 // is carried in `acc.qlen` by the SPN section below, which is what
1474 // QN, TN and (for a queueing place) UN are read off.
1475 //
1476 // THE SERVER COUNT IS THE EMBEDDED QUEUE'S, and it doubles as the
1477 // utilization denominator: a c-server place reports busy/(t*c),
1478 // while an INF one leaves `nservers` at 1 so that busy/t is the mean
1479 // number in service, which is the convention LINE uses for every
1480 // infinite server (U == Q).
1481 if (st.nodetype == NodeType::Place) {
1482 s.off.assign(K, false);
1483 if (std::isfinite(st.nservers))
1484 s.nservers = static_cast<std::size_t>(st.nservers + 0.5);
1485 }
1486 } else if (st.nodetype == NodeType::Delay || st.sched == SchedStrategy::INF) {
1487 s.role = Role::Delay;
1488 } else {
1489 s.role = Role::Queue;
1490 s.ps = is_ps_family(st.sched);
1491 s.preemptive = is_preemptive(st.sched);
1492 s.resume = is_preemptive_resume(st.sched);
1493 // The disciplines whose WaitCmp reads job.service or job.remaining.
1494 s.size_ordered = (st.sched == SchedStrategy::SJF ||
1495 st.sched == SchedStrategy::LJF ||
1496 st.sched == SchedStrategy::SRPT ||
1497 st.sched == SchedStrategy::SRPTPRIO ||
1498 st.sched == SchedStrategy::PSJF ||
1499 st.sched == SchedStrategy::LRPT ||
1500 st.sched == SchedStrategy::FSP);
1501 const double c = st.nservers;
1502 if (!(c >= 1.0) || !std::isfinite(c))
1503 throw InputError("SolverLDES (native engine): station '" + st.name +
1504 "' has a server count that is neither finite nor at least one");
1505 s.nservers = static_cast<std::size_t>(c + 0.5);
1506 s.cap = st.cap;
1507 s.classcap.assign(K, std::numeric_limits<double>::infinity());
1508 s.blocked_at.assign(K, 0.0);
1509 s.droprule.assign(K, lang::DropStrategy::DROP);
1510 for (std::size_t r = 0; r < K; ++r)
1511 if (i < sn.droprule.size() && r < sn.droprule[i].size())
1512 s.droprule[r] = sn.droprule[i][r];
1513 for (std::size_t r = 0; r < K; ++r)
1514 if (i < sn.classcap.size() && r < sn.classcap[i].size())
1515 s.classcap[r] = sn.classcap[i][r];
1516 if (st.sched == SchedStrategy::LPS) s.lps_limit = s.nservers;
1517 // SERVER PARALLELISM. Read unconditionally so that a station
1518 // declaring only ones keeps every path it had: `has_parallelism`
1519 // is what the seize, the release and the admission gate consult.
1520 s.parallelism.assign(K, 1);
1521 for (std::size_t r = 0; r < K && r < st.server_parallelism.size(); ++r)
1522 if (st.server_parallelism[r] > 1) {
1523 s.parallelism[r] = st.server_parallelism[r];
1524 s.has_parallelism = true;
1525 }
1526 }
1527
1528 // One entry per class, neutral until a sharing station with a class
1529 // dependence refreshes it in `ps_reschedule`.
1530 s.ps_cd.assign(K, 1.0);
1531 s.gd_peak.assign(K, 1.0);
1532 for (const T& v : st.lldscaling) s.lld.push_back(num_traits<T>::to_double(v));
1533 // The peak capacity that normalizes this station's utilization is
1534 // max(c, max(alpha)) -- CTMC's own ceff, which is what makes the two
1535 // report the same number on a load-dependent station. Without load
1536 // dependence it is just c, so nothing else moves.
1537 s.util_peak = static_cast<double>(s.nservers);
1538 for (double a : s.lld) s.util_peak = std::max(s.util_peak, a);
1539 // CLASS DEPENDENCE beta_r(n) AND JOINT DEPENDENCE eta_i(n) ENTER THE
1540 // SAMPLE-PATH RATE THE SAME WAY, and a station declaring both is scaled
1541 // by their PRODUCT -- `initializeClassDependence` and `State.java` both
1542 // fold them that way. They stay separate on the struct because they
1543 // carry different modelling claims (beta keeps the product form, eta
1544 // does not), but a simulator has no use for that distinction: it needs
1545 // the rate in force, which is the product.
1546 if (st.cdscaling || st.jdscaling) {
1547 s.has_cd = true;
1548 // THE DECLARED PEAK IS THE NORMALIZER, not a peak swept out of the
1549 // handle. `solver_ssa_serial` and `solver_ssa_nrm_space` take the
1550 // PRODUCT of whichever declared peaks are present, and drop the
1551 // server count while doing so, because the rate in force is that
1552 // same product; this engine must answer with their number. A handle
1553 // with no declared peak is a model defect here exactly as it is
1554 // there -- an open class has no lattice to sweep, so a swept peak
1555 // would be an invented bound.
1556 double dep_peak = 1.0;
1557 const std::vector<T>* pks[2] = {&st.cdscalingpeak, &st.jdscalingpeak};
1558 const bool on[2] = {static_cast<bool>(st.cdscaling), static_cast<bool>(st.jdscaling)};
1559 const char* names[2] = {"setClassDependence", "setJointDependence"};
1560 for (std::size_t h = 0; h < 2; ++h) {
1561 if (!on[h]) continue;
1562 if (pks[h]->empty())
1563 throw InputError(
1564 std::string("SolverLDES: station '") + st.name +
1565 "' declares a dependent scaling with no declared peak rate. Utilization "
1566 "there is T*E[S]/peak, so pass the peak to " + names[h]);
1567 double m = 0.0;
1568 for (const T& v : *pks[h]) m = std::max(m, num_traits<T>::to_double(v));
1569 if (!(m > 0.0))
1570 throw InputError(std::string("SolverLDES: station '") + st.name +
1571 "' declares a non-positive peak rate for " + names[h]);
1572 dep_peak *= m;
1573 }
1574 s.util_peak = dep_peak;
1575 s.cd_peak_class.assign(sn.nclasses, 1.0);
1576 for (std::size_t r = 0; r < sn.nclasses; ++r) {
1577 std::size_t cr = sn.chains.size();
1578 for (std::size_t c = 0; c < sn.chains.size(); ++c)
1579 if (r < sn.chains[c].size() && sn.chains[c][r]) { cr = c; break; }
1580 for (std::size_t h = 0; h < 2; ++h) {
1581 if (!on[h]) continue;
1582 double m = 0.0;
1583 for (std::size_t k = 0; k < sn.nclasses; ++k) {
1584 const bool same = (cr < sn.chains.size()) ? (k < sn.chains[cr].size() && sn.chains[cr][k])
1585 : (k == r);
1586 if (!same) continue;
1587 const std::size_t e = pks[h]->size() > 1 ? k : 0;
1588 if (e < pks[h]->size()) m = std::max(m, num_traits<T>::to_double((*pks[h])[e]));
1589 }
1590 s.cd_peak_class[r] *= (m > 0.0) ? m : 1.0;
1591 }
1592 }
1593 const auto& beta = st.cdscaling;
1594 const auto& eta = st.jdscaling;
1595 s.cd = [beta, eta](const std::vector<double>& n) {
1596 std::vector<T> nt(n.size());
1597 for (std::size_t k = 0; k < n.size(); ++k) nt[k] = num_traits<T>::from_double(n[k]);
1598 std::vector<double> bd, ed;
1599 if (beta) {
1600 const std::vector<T> b = beta(nt);
1601 bd.resize(b.size());
1602 for (std::size_t k = 0; k < b.size(); ++k) bd[k] = num_traits<T>::to_double(b[k]);
1603 }
1604 if (eta) {
1605 const std::vector<T> e = eta(nt);
1606 ed.resize(e.size());
1607 for (std::size_t k = 0; k < e.size(); ++k) ed[k] = num_traits<T>::to_double(e[k]);
1608 }
1609 if (bd.empty()) return ed;
1610 if (ed.empty()) return bd;
1611 // Elementwise, with scalar broadcasting: either factor may be a
1612 // single value shared across the classes.
1613 const std::size_t n2 = std::max(bd.size(), ed.size());
1614 std::vector<double> out(n2, 1.0);
1615 for (std::size_t k = 0; k < n2; ++k)
1616 out[k] = bd[bd.size() > 1 ? k : 0] * ed[ed.size() > 1 ? k : 0];
1617 return out;
1618 };
1619 }
1620 if (st.sched == SchedStrategy::PAS || st.sched == SchedStrategy::OI) {
1621 s.pas = true;
1622 auto pp = sn.pasparam.find(i + 1);
1623 if (pp != sn.pasparam.end()) {
1624 if (pp->second.svc_rate_fun) {
1625 const auto f = pp->second.svc_rate_fun;
1626 // mu(c) TAKES 1-BASED CLASS TAGS -- it is the state
1627 // encoding's own convention, the one `state.h` and
1628 // `after_event_station_pas` hand it and the one
1629 // `oi_rate_from_json` decodes (it drops any entry below 1).
1630 // This engine's `Job::cls` is 0-based, so shift on the way
1631 // in: unshifted, class 0 is invisible to mu, contributes no
1632 // rate increment at any position, and its jobs pile up at
1633 // the station and never complete.
1634 s.pas_rate = [f](const std::vector<std::size_t>& seq) {
1635 std::vector<std::size_t> tags(seq.size());
1636 for (std::size_t k = 0; k < seq.size(); ++k) tags[k] = seq[k] + 1;
1637 return num_traits<T>::to_double(f(tags));
1638 };
1639 }
1640 s.pas_swap = pp->second.swap_graph;
1641 }
1642 if (!s.pas_rate)
1643 throw InputError("SolverLDES (native engine): station '" + st.name +
1644 "' is a pass-and-swap station with no service rate function");
1645 }
1646 if (st.sched == SchedStrategy::POLLING) {
1647 s.polling = true;
1648 const auto pp = sn.effective_polling(i + 1);
1649 s.poll_type = pp.ptype;
1650 s.poll_k = (pp.pk >= 1) ? pp.pk : 1;
1651 s.poll_budget = (s.poll_type == lang::PollingType::EXHAUSTIVE)
1652 ? std::numeric_limits<std::size_t>::max()
1653 : ((s.poll_type == lang::PollingType::KLIMITED) ? s.poll_k : 1);
1654 s.poll_parked = true;
1655 s.switchover.resize(K);
1656 s.has_switchover.assign(K, false);
1657 for (std::size_t r = 0; r < K && r < pp.switchover.size(); ++r)
1658 if (!pp.switchover[r].disabled &&
1659 num_traits<T>::to_double(pp.switchover[r].mean) > 0.0) {
1660 s.switchover[r] = Sampler(pp.switchover[r],
1661 "the switchover of station '" + st.name +
1662 "', class '" + sn.classes[r].name + "'");
1663 s.has_switchover[r] = true;
1664 }
1665 // ---- the polling extensions (Solver_ssj.initializePollingExtensions)
1666 const bool ptab = !pp.table.empty();
1667 const bool pld = pp.order != lang::PollingOrder::CYCLIC;
1668 if (ptab || pld || pp.timer_scope != lang::PollingTimer::NONE) {
1669 const std::string at = "SolverLDES (native engine): polling station '" + st.name + "'";
1670 s.poll_ext = true;
1671 s.poll_order = pp.order;
1672 s.poll_timer = pp.timer_scope;
1673 s.poll_preempt = pp.timer_preempt;
1674 s.poll_polled = sn.polling_polled(i + 1);
1675 s.poll_polled.resize(K, false);
1676 if (ptab && pld)
1677 throw InputError(ErrorKind{"Model"}, at + ": a polling table cannot be combined with a "
1678 "load-dependent polling order.");
1679 std::vector<const lang::Distrib<T>*> legd;
1680 if (ptab) {
1681 std::vector<bool> listed(K, false);
1682 for (std::size_t p = 0; p < pp.table.size(); ++p) {
1683 const std::size_t c = pp.table[p] - 1;
1684 if (pp.table[p] < 1 || c >= K || !s.poll_polled[c])
1685 throw InputError(ErrorKind{"Model"},
1686 at + ": the polling table lists a class that is not served there.");
1687 listed[c] = true;
1688 s.poll_ring.push_back(c);
1689 const lang::Distrib<T>* d = nullptr;
1690 if (p < pp.table_sw.size() && !pp.table_sw[p].disabled)
1691 d = &pp.table_sw[p];
1692 else if (c < pp.switchover.size())
1693 d = &pp.switchover[c];
1694 legd.push_back(d);
1695 }
1696 for (std::size_t c = 0; c < K; ++c)
1697 if (s.poll_polled[c] && !listed[c])
1698 throw InputError(ErrorKind{"Model"}, at + ": the polling table must list every class "
1699 "served there at least once.");
1700 } else if (pld) {
1701 // positions are the classes; the leg out of buffer c is
1702 // class c's switchover, paid only when the server moves away
1703 for (std::size_t c = 0; c < K; ++c) {
1704 s.poll_ring.push_back(c);
1705 legd.push_back((s.poll_polled[c] && c < pp.switchover.size()) ? &pp.switchover[c]
1706 : nullptr);
1707 }
1708 } else {
1709 for (std::size_t c = 0; c < K; ++c)
1710 if (s.poll_polled[c]) {
1711 s.poll_ring.push_back(c);
1712 legd.push_back(c < pp.switchover.size() ? &pp.switchover[c] : nullptr);
1713 }
1714 }
1715 if (s.poll_ring.empty())
1716 throw InputError(ErrorKind{"Model"}, at + " serves no class.");
1717 s.poll_leg.resize(s.poll_ring.size());
1718 s.poll_has_leg.assign(s.poll_ring.size(), false);
1719 bool any_timed_leg = false;
1720 for (std::size_t p = 0; p < legd.size(); ++p) {
1721 const lang::Distrib<T>* d = legd[p];
1722 if (d == nullptr || d->disabled || d->type == lang::ProcessType::IMMEDIATE ||
1724 continue;
1725 const double mean = num_traits<T>::to_double(d->mean);
1726 if (!(mean > 0.0) || !std::isfinite(mean)) continue;
1727 s.poll_leg[p] = Sampler(*d, "the switchover out of polling position " +
1728 std::to_string(p + 1) + " of station '" + st.name + "'");
1729 s.poll_has_leg[p] = true;
1730 any_timed_leg = true;
1731 }
1732 s.poll_pos = 0;
1733 if (pld) {
1734 for (std::size_t c = 0; c < K; ++c)
1735 if (s.poll_polled[c]) {
1736 s.poll_pos = c;
1737 break;
1738 }
1739 }
1740 s.poll_at = s.poll_ring[s.poll_pos];
1741 if (pp.order == lang::PollingOrder::THRESHOLD) {
1742 const std::size_t c = pp.order_class; // 1-based
1743 if (c < 1 || c > K || !s.poll_polled[c - 1])
1744 throw InputError(ErrorKind{"Model"}, at + ": the THRESHOLD polling order names a class "
1745 "that is not served there.");
1746 s.poll_thr_class = c - 1;
1747 s.poll_thr_l = pp.order_threshold;
1748 }
1749 s.poll_tlaw.resize(K);
1750 s.poll_has_tlaw.assign(K, false);
1751 s.poll_trt.assign(K, 0.0);
1752 if (pp.timer_scope != lang::PollingTimer::NONE) {
1753 for (std::size_t c = 0; c < K; ++c) {
1754 if (!s.poll_polled[c]) continue;
1755 if (c >= pp.timer.size() || pp.timer[c].disabled ||
1756 pp.timer[c].type == lang::ProcessType::DISABLED)
1757 throw InputError(ErrorKind{"Model"}, at + " declares a visit timer without a law for "
1758 "class '" + sn.classes[c].name + "'.");
1759 const lang::Distrib<T>& td = pp.timer[c];
1760 const double mean = num_traits<T>::to_double(td.mean);
1761 // Det and every other positive law are sampled as they are
1762 if (td.type != lang::ProcessType::IMMEDIATE && mean > 0.0 && std::isfinite(mean)) {
1763 s.poll_tlaw[c] = Sampler(td, "the polling timer of station '" + st.name +
1764 "', class '" + sn.classes[c].name + "'");
1765 s.poll_has_tlaw[c] = true;
1766 }
1767 }
1768 if (pp.timer_scope == lang::PollingTimer::GLOBAL) {
1769 if (pld)
1770 throw InputError(ErrorKind{"Model"},
1771 at + ": a GLOBAL (timed-token) polling timer needs a fixed visit "
1772 "order; it cannot be combined with a load-dependent polling order.");
1773 if (!any_timed_leg)
1774 throw InputError(ErrorKind{"Model"},
1775 at + ": a GLOBAL (timed-token) polling timer needs at least one timed "
1776 "switchover: with zero walk times the token would rotate in zero "
1777 "time.");
1778 // the rotation timers run from t = 0; they are drawn at the
1779 // first arrival of the token (poll_trt_ready), when the
1780 // station's stream exists, and that draw is from t = 0
1781 }
1782 }
1783 }
1784 }
1785 if (st.sched == SchedStrategy::RR) {
1786 s.rr = true;
1787 s.rr_quantum.resize(K);
1788 for (std::size_t r = 0; r < K && r < st.quantum.size(); ++r)
1789 s.rr_quantum[r] = Sampler(st.quantum[r], "the quantum of station '" + st.name +
1790 "', class '" + sn.classes[r].name + "'");
1791 }
1792 s.retrial.resize(K);
1793 s.has_retrial.assign(K, false);
1794 s.max_attempts.assign(K, 0);
1795 s.retrial_policy.assign(K, 1);
1796 s.const_pending.assign(K, false);
1797 s.orbit.assign(K, std::deque<Job>());
1798 s.orbit_abandon.resize(K);
1799 s.has_orbit_abandon.assign(K, false);
1800 s.orbit_size.assign(K, 0.0);
1801 s.tot_orbit.assign(K, 0.0);
1802 s.retried.assign(K, 0.0);
1803 s.retrial_lost.assign(K, 0.0);
1804 {
1805 auto rp = sn.retrialparam.find(i + 1);
1806 if (rp != sn.retrialparam.end())
1807 for (std::size_t r = 0; r < K && r < rp->second.retrial_proc.size(); ++r)
1808 if (!rp->second.retrial_proc[r].disabled) {
1809 s.retrial[r] = Sampler(rp->second.retrial_proc[r],
1810 "the retrial process of station '" + st.name +
1811 "', class '" + sn.classes[r].name + "'");
1812 s.has_retrial[r] = true;
1813 if (r < rp->second.max_attempts.size())
1814 s.max_attempts[r] = rp->second.max_attempts[r];
1815 if (r < rp->second.policy.size())
1816 s.retrial_policy[r] = rp->second.policy[r];
1817 if (r < st.orbit_impatience.size() && !st.orbit_impatience[r].disabled) {
1818 s.orbit_abandon[r] = Sampler(st.orbit_impatience[r],
1819 "the orbit impatience of station '" + st.name +
1820 "', class '" + sn.classes[r].name + "'");
1821 s.has_orbit_abandon[r] = true;
1822 }
1823 }
1824 }
1825 s.patience.resize(K);
1826 s.has_patience.assign(K, false);
1827 s.balk.assign(K, std::vector<StationState::BalkRule>());
1828 for (std::size_t r = 0; r < K; ++r) {
1829 if (r < st.impatience.size() && st.impatience[r] == lang::ImpatienceType::RENEGING &&
1830 r < st.patience.size() && !st.patience[r].disabled) {
1831 s.patience[r] = Sampler(st.patience[r], "the patience of station '" + st.name +
1832 "', class '" + sn.classes[r].name + "'");
1833 s.has_patience[r] = true;
1834 }
1835 // ALL THREE STRATEGIES READ THE SAME TABLE, as in the Java engine
1836 // (Solver_ssj.shouldBalk), which never consults the strategy: the
1837 // model layer stores EXPECTED_WAIT and COMBINED thresholds in JOBS,
1838 // {minJobs, maxJobs, probability}, and carries no wait parameter.
1839 if (r < st.balking.size() &&
1840 st.balking[r].strategy != lang::BalkingStrategy::NONE) {
1841 for (const auto& th : st.balking[r].thresholds) {
1842 StationState::BalkRule br;
1843 br.min_jobs = th.min_jobs;
1844 br.max_jobs = th.max_jobs;
1845 br.probability = num_traits<T>::to_double(th.probability);
1846 s.balk[r].push_back(br);
1847 }
1848 }
1849 }
1850
1851 {
1852 auto sp = sn.setupparam.find(i + 1);
1853 if (sp != sn.setupparam.end()) {
1854 // A law of ZERO mean (Det(0), Immediate) gets no sampler, as the
1855 // reference builds no generator for one. A zero SETUP is a cold
1856 // start that costs nothing, so the class never powers a server
1857 // down; a zero DELAY-OFF is not the absence of the window but a
1858 // window of length zero: the server shuts down the instant it
1859 // empties, so every busy period starts cold.
1860 auto zero_mean = [](const lang::Distrib<T>& d) -> bool {
1861 if (d.type == lang::ProcessType::IMMEDIATE) return true;
1862 if (d.type == lang::ProcessType::DET || d.type == lang::ProcessType::EXP)
1863 return !(num_traits<T>::to_double(d.mean) > 0.0);
1864 return false;
1865 };
1866 const qn::SetupDelayOffParam<T>& P = sp->second;
1867 s.setup_law.assign(K, Sampler());
1868 s.has_setup_law.assign(K, false);
1869 s.doff_law.assign(K, Sampler());
1870 s.has_doff_law.assign(K, false);
1871 s.doff_zero.assign(K, false);
1872 for (std::size_t r = 0; r < K; ++r) {
1873 const std::string at = "class '" + sn.classes[r].name + "' at station '" + st.name + "'";
1874 if (r < P.setup.size() && !P.setup[r].disabled) {
1875 s.has_setup = true;
1876 if (!zero_mean(P.setup[r])) {
1877 s.setup_law[r] = Sampler(P.setup[r], "the setup time of " + at);
1878 s.has_setup_law[r] = true;
1879 }
1880 }
1881 if (r < P.delayoff.size() && !P.delayoff[r].disabled) {
1882 if (zero_mean(P.delayoff[r])) {
1883 s.doff_zero[r] = true;
1884 } else {
1885 s.doff_law[r] = Sampler(P.delayoff[r], "the delay-off time of " + at);
1886 s.has_doff_law[r] = true;
1887 }
1888 }
1889 }
1890 }
1891 }
1892 {
1893 typename std::map<std::size_t, qn::BreakdownParam<T> >::const_iterator bp =
1894 sn.breakdownparam.find(i + 1);
1895 if (bp != sn.breakdownparam.end()) {
1896 s.has_breakdown = true;
1897 s.up = true;
1898 s.failure_time =
1899 Sampler(bp->second.failure, "the failure time of station '" + st.name + "'");
1900 s.repair_time =
1901 Sampler(bp->second.repair, "the repair time of station '" + st.name + "'");
1902 s.down_scale.assign(K, 0.0);
1903 s.down_rate_raw.assign(K, 0.0);
1904 for (std::size_t r = 0; r < K && r < bp->second.down_service_rates.size(); ++r)
1905 s.down_rate_raw[r] = num_traits<T>::to_double(bp->second.down_service_rates[r]);
1906 }
1907 }
1908 // A BREAKDOWN IS A STATE-DEPENDENT RATE, so it reuses sd_advance /
1909 // sd_reschedule rather than growing a second freeze-and-retime path.
1910 s.state_dependent = (!s.lld.empty() || s.has_cd || s.has_breakdown);
1911
1912 s.svc.resize(K);
1913 if (s.role == Role::Synchronization) continue;
1914 for (std::size_t r = 0; r < K; ++r) {
1915 s.off[r] = sn.disabled[i][r];
1916 if (s.off[r]) continue;
1917 const std::string where = "station '" + st.name + "', class '" + sn.classes[r].name + "'";
1918 s.svc[r] = Sampler(sn.service[i][r], where);
1919 s.class_mean[r] = s.svc[r].mean();
1920 if (!(s.class_mean[r] > 0.0))
1921 throw InputError("SolverLDES (native engine): " + where +
1922 " has a non-positive mean service time");
1923 }
1924
1925 // ---- bulk service (BMSP) ----------------------------------------------
1926 //
1927 // Detected from the PROCESS, not from a flag: a BMAP or BMMAPt assigned as a
1928 // service process IS a batch Markovian service process. Every guard below is
1929 // the Java engine's, refused by name rather than answered wrongly -- before
1930 // this arm existed the batch blocks were read and never consulted, so a bulk
1931 // server was simulated as an ordinary one completing one job per firing.
1932 // A SOURCE's `service` column holds its ARRIVAL processes, so a batch family
1933 // there is a batch ARRIVAL and has nothing to do with bulk service.
1934 if (s.role != Role::Source) {
1935 std::size_t nbatch = 0, enabled = 0, bcls = K;
1936 for (std::size_t r = 0; r < K; ++r) {
1937 if (s.off[r]) continue;
1938 ++enabled;
1939 if (lang::process_is_batch(sn.service[i][r].type)) {
1940 ++nbatch;
1941 bcls = r;
1942 }
1943 }
1944 if (nbatch > 0) {
1945 const std::string fam = lang::process_to_text(sn.service[i][bcls].type);
1946 const std::string at = fam + " service (BMSP) at station '" + st.name + "'";
1947 if (s.role == Role::Delay)
1948 throw UnsupportedError(ErrorKind{"BMAP"}, "SolverLDES (native engine): " + at +
1949 " is not supported at an infinite-server station; "
1950 "batch service requires a single-server FCFS queue");
1951 if (s.nservers != 1)
1952 throw UnsupportedError(ErrorKind{"BMAP"}, "SolverLDES (native engine): " + at +
1953 " requires a single server; multiserver bulk service "
1954 "is not supported");
1955 if (s.sched != lang::SchedStrategy::FCFS)
1956 throw UnsupportedError(ErrorKind{"BMAP"}, "SolverLDES (native engine): " + at +
1957 " requires FCFS scheduling");
1958 if (enabled != 1)
1959 throw UnsupportedError(ErrorKind{"BMAP"}, "SolverLDES (native engine): " + at +
1960 " requires exactly one job class; multiclass bulk "
1961 "service is not supported");
1962 if (s.pas || s.preemptive || s.polling)
1963 throw UnsupportedError(ErrorKind{"BMAP"}, "SolverLDES (native engine): " + at +
1964 " is incompatible with PAS/preemptive/polling "
1965 "scheduling");
1966 if (s.has_setup)
1967 throw UnsupportedError(ErrorKind{"BMAP"}, "SolverLDES (native engine): " + at +
1968 " is incompatible with server setup/delayoff");
1969 if (s.state_dependent)
1970 throw UnsupportedError(ErrorKind{"BMAP"}, "SolverLDES (native engine): " + at +
1971 " is not supported with load or class dependence or "
1972 "breakdowns: the rate rescaling cannot be applied to "
1973 "a firing clock armed at the instant the station "
1974 "became busy");
1975 if (!st.server_types.empty())
1976 throw UnsupportedError(ErrorKind{"BMAP"}, "SolverLDES (native engine): " + at +
1977 " is not supported with heterogeneous server types; a "
1978 "bulk server is a single server by construction");
1979 s.bmsp = true;
1980 s.bmsp_cls = bcls;
1981 s.bmsp_pending = 1;
1982 }
1983 }
1984
1985 // ---- heterogeneous server pools ---------------------------------------
1986 //
1987 // The pools REPLACE the flat server bank rather than sitting beside it:
1988 // `nservers` becomes their total, so every slot loop below is already
1989 // over the right range and only the CHOICE of slot has to learn about
1990 // compatibility. A pool that declares no law of its own for a class
1991 // serves it at the station's class-level default, which is what the
1992 // reference's `generateHeteroServiceTime` falls back to.
1993 if (!st.server_types.empty()) {
1994 // A per-pool law has no operational-time branch, so an NHPP service
1995 // here would be drawn as a wall duration and silently mistimed. The
1996 // reference refuses the same pairing (`assertScheduleServiceSupported`).
1997 for (std::size_t k = 0; k < K; ++k)
1998 if (!s.off[k] && s.svc[k].type() == lang::ProcessType::NHPP)
1999 throw UnsupportedError(ErrorKind{"NHPP"},
2000 "SolverLDES (native engine): NHPP service is not supported at station '" +
2001 sn.stations[i].name + "' for class '" + sn.classes[k].name +
2002 "' with heterogeneous server types; use homogeneous servers, for "
2003 "which mu(t) is supported under any scheduling discipline");
2004 const std::size_t nT = st.server_types.size();
2005 s.has_pools = true;
2006 s.hetero_policy = st.hetero_policy;
2007 s.type_count.assign(nT, 0);
2008 s.type_first.assign(nT, 0);
2009 s.type_compat.assign(nT, std::vector<bool>(K, true));
2010 s.type_svc.assign(nT, std::vector<Sampler>(K));
2011 s.type_has_svc.assign(nT, std::vector<bool>(K, false));
2012 s.type_rate.assign(nT, std::vector<double>(K, 0.0));
2013 std::size_t total = 0;
2014 for (std::size_t t = 0; t < nT; ++t) {
2015 const typename qn::Station<T>::ServerType& pt = st.server_types[t];
2016 const double c = pt.count;
2017 if (!(c >= 1.0))
2018 throw InputError("SolverLDES (native engine): station '" + st.name +
2019 "' declares server pool '" + pt.name +
2020 "' with fewer than one server");
2021 s.type_first[t] = total;
2022 s.type_count[t] = static_cast<std::size_t>(c + 0.5);
2023 total += s.type_count[t];
2024 for (std::size_t r = 0; r < K; ++r) {
2025 // An empty compatibility row means every class, as the
2026 // struct documents; a short one is padded the same way.
2027 s.type_compat[t][r] = pt.compatible.empty() || r >= pt.compatible.size()
2028 ? true
2029 : pt.compatible[r];
2030 if (s.off[r]) s.type_compat[t][r] = false;
2031 if (r < pt.service.size() && !pt.service[r].disabled) {
2032 const std::string where = "station '" + st.name + "', pool '" + pt.name +
2033 "', class '" + sn.classes[r].name + "'";
2034 s.type_svc[t][r] = Sampler(pt.service[r], where);
2035 s.type_has_svc[t][r] = true;
2036 const double mu = s.type_svc[t][r].mean();
2037 if (!(mu > 0.0))
2038 throw InputError("SolverLDES (native engine): " + where +
2039 " has a non-positive mean service time");
2040 s.type_rate[t][r] = 1.0 / mu;
2041 } else if (!s.off[r]) {
2042 s.type_rate[t][r] =
2043 (s.class_mean[r] > 0.0) ? 1.0 / s.class_mean[r] : 0.0;
2044 }
2045 }
2046 }
2047 for (std::size_t r = 0; r < K; ++r) {
2048 if (s.off[r]) continue;
2049 bool served = false;
2050 for (std::size_t t = 0; t < nT && !served; ++t) served = s.type_compat[t][r];
2051 if (!served)
2052 throw InputError("SolverLDES (native engine): station '" + st.name +
2053 "' declares no server pool compatible with class '" +
2054 sn.classes[r].name +
2055 "', so a job of that class would wait forever");
2056 }
2057 // The pools ARE the server bank. A declared `nservers` that
2058 // disagrees is the flattened view of the same pools, and taking it
2059 // instead would serve more or fewer jobs at once than declared.
2060 s.nservers = total;
2061 s.util_peak = static_cast<double>(total);
2062 if (s.sched == lang::SchedStrategy::LPS) s.lps_limit = total;
2063 s.server_type.assign(total, 0);
2064 for (std::size_t t = 0; t < nT; ++t)
2065 for (std::size_t j = 0; j < s.type_count[t]; ++j)
2066 s.server_type[s.type_first[t] + j] = t;
2067 s.type_order.resize(nT);
2068 for (std::size_t t = 0; t < nT; ++t) s.type_order[t] = t;
2069 // ALFS: fewest compatible classes first, ties by declaration order,
2070 // so the least flexible pool is spent before the more flexible one.
2071 s.alfs_order = s.type_order;
2072 std::stable_sort(s.alfs_order.begin(), s.alfs_order.end(),
2073 [&](std::size_t a, std::size_t b) {
2074 std::size_t ca = 0, cb = 0;
2075 for (std::size_t r = 0; r < K; ++r) {
2076 if (s.type_compat[a][r]) ++ca;
2077 if (s.type_compat[b][r]) ++cb;
2078 }
2079 return ca < cb;
2080 });
2081 }
2082 // THE DEGRADED RATE BECOMES A MULTIPLIER, and it can only be formed
2083 // here, once the mean service time of each class is known: the wire
2084 // carries an ABSOLUTE rate while the engine's state-dependent path
2085 // takes a factor on the nominal one.
2086 if (s.has_breakdown) {
2087 s.down_scale.assign(K, 0.0);
2088 for (std::size_t r = 0; r < K; ++r) {
2089 if (s.off[r] || !(s.class_mean[r] > 0.0)) continue;
2090 if (r < s.down_rate_raw.size() && s.down_rate_raw[r] > 0.0)
2091 s.down_scale[r] = s.down_rate_raw[r] * s.class_mean[r];
2092 }
2093 }
2094 if (!s.ps) {
2095 s.cmp.sched = s.sched;
2096 s.cmp.class_mean = &s.class_mean;
2097 if (s.role == Role::Queue) {
2098 s.server.assign(s.nservers, Job());
2099 s.server_busy.assign(s.nservers, false);
2100 s.server_start.assign(s.nservers, 0.0);
2101 s.server_tag.assign(s.nservers, 0);
2102 s.server_blocked.assign(s.nservers, false);
2103 s.server_held.assign(s.nservers, false);
2104 s.held_cls.assign(s.nservers, 0);
2105 s.blocked_job.assign(s.nservers, Job());
2106 s.blocked_dest.assign(s.nservers, 0);
2107 s.blocked_dest_cls.assign(s.nservers, 0);
2108 if (s.has_parallelism) s.held_extra.assign(s.nservers, std::vector<std::size_t>());
2109 if (s.rr) s.rr_qtag.assign(s.nservers, 0);
2110 // Every server starts ACTIVE, as the reference's do: the first
2111 // busy period of a run pays no setup.
2112 if (s.has_setup) {
2113 s.power.assign(s.nservers, PW_ACTIVE);
2114 s.power_tag.assign(s.nservers, 0);
2115 }
2116 }
2117 }
2118 }
2119
2120 // ---- setup / delay-off: a station of interchangeable FCFS-family servers ----
2121 //
2122 // The power states live on the SERVER SLOTS, as the reference's do, so a
2123 // station with no bank of slots to power up and down -- a sharing
2124 // discipline, a pass-and-swap or polling controller -- has nothing for a
2125 // setup to act on. The reference takes the setup path only in its
2126 // non-preemptive slot arrival and would silently ignore the declaration
2127 // under a preemptive discipline too; all of these are refused by name.
2128 for (std::size_t i = 0; i < M; ++i) {
2129 const StationState& s = S[i];
2130 if (!s.has_setup) continue;
2131 if (s.role != Role::Queue || s.ps || s.pas || s.polling || s.preemptive)
2132 throw UnsupportedError(ErrorKind{"SetupDelayOff"},
2133 "SolverLDES (native engine): station '" + sn.stations[i].name +
2134 "' declares a setup/delay-off but serves under " +
2135 lang::sched_to_text(s.sched) +
2136 "; setup is simulated per server at a queue with a bank of "
2137 "FCFS-family server slots");
2138 }
2139
2140 // ---- server parallelism: what a station must be for a job to seize n ----
2141 //
2142 // Every refusal below is the reference engine's `initializeServerParallelism`,
2143 // named rather than answered wrongly. What they have in common is that the
2144 // station has no BANK OF INTERCHANGEABLE SLOTS to take n of: an infinite
2145 // server never makes a job wait for one, a sharing discipline hands out
2146 // fractions of its whole capacity instead of slots, a polling or
2147 // pass-and-swap controller picks the server itself, a bulk server has only a
2148 // station-level firing clock, a heterogeneous pool binds a job to the one
2149 // type whose law serves it, and a setup station powers its slots up one at a
2150 // time so "n free at once" is not a state it passes through.
2151 for (std::size_t i = 0; i < M; ++i) {
2152 const auto& st = sn.stations[i];
2153 std::size_t maxpar = 1;
2154 for (std::size_t r = 0; r < st.server_parallelism.size(); ++r)
2155 maxpar = std::max(maxpar, st.server_parallelism[r]);
2156 if (maxpar <= 1) continue;
2157 StationState& s = S[i];
2158 const std::string where = std::string("SolverLDES (native engine): station '") +
2159 st.name + "' declares server parallelism";
2160 if (s.role != Role::Queue)
2161 throw UnsupportedError(ErrorKind{"ServerParallelism"}, where + " at an infinite server, which never makes a job "
2162 "wait for a slot; drop the declaration or give the "
2163 "station a finite server count");
2164 if (s.ps)
2165 throw UnsupportedError(ErrorKind{"ServerParallelism"}, where + " under " + std::string(lang::sched_to_text(s.sched)) +
2166 ", which shares its whole capacity rather than handing out "
2167 "slots, so a job cannot hold n of them; use a queueing "
2168 "discipline, or a class weight to slow the class down");
2169 if (s.polling || s.pas)
2170 throw UnsupportedError(ErrorKind{"ServerParallelism"}, where + " under " + std::string(lang::sched_to_text(s.sched)) +
2171 ", whose controller picks the server itself and has no pool "
2172 "to seize n slots from");
2173 if (s.bmsp)
2174 throw UnsupportedError(ErrorKind{"ServerParallelism"}, where + " at a bulk (BMSP) server, which has only a "
2175 "station-level firing clock and no per-job server "
2176 "to seize");
2177 if (s.has_pools)
2178 throw UnsupportedError(ErrorKind{"ServerParallelism"}, where + " together with heterogeneous server pools: a job is "
2179 "served at the law of the one pool it occupies, which "
2180 "n servers of mixed types cannot express");
2181 if (s.has_setup)
2182 throw UnsupportedError(ErrorKind{"ServerParallelism"}, where + " together with setup/delayoff: the slots of such a "
2183 "station power up one at a time, so 'n free at once' "
2184 "is not a state it passes through");
2185 if (maxpar > s.nservers)
2186 throw InputError(where + " of " + std::to_string(maxpar) + " above its " +
2187 std::to_string(s.nservers) + " servers, so the job could never "
2188 "enter service");
2189 }
2190
2191 // ---- global (Whittle) dependence ----------------------------------------
2192 /**
2193 * `sn.gdscaling`: ONE handle phi(n), read at the FULL (nstations x nclasses)
2194 * population, that multiplies every station's service rate at once.
2195 *
2196 * It is not a station's own state dependence under another name. A job
2197 * moving ANYWHERE changes the rate EVERYWHERE, so the four advance and
2198 * reschedule calls fan out over the whole network instead of touching the
2199 * station that moved. That fan-out is cheap here precisely because this
2200 * engine rescales RESIDUAL WORK rather than resampling: repeating a
2201 * reschedule burns no variate and lands on the same completion instant, so
2202 * it is idempotent in a way the reference engine's cancel-and-redraw is not.
2203 */
2204 const bool has_gd = static_cast<bool>(sn.gdscaling);
2205 std::vector<std::vector<double> > gd_cache(M, std::vector<double>(K, 1.0));
2206 if (has_gd) {
2207 if (sn.gdscalingpeak.size() < M * K)
2208 throw InputError(
2209 "SolverLDES (native engine): a global dependence requires an explicit peak rate, "
2210 "because utilization under it is reported as T*E[S]/peak; pass one to "
2211 "setGlobalDependence");
2212 for (std::size_t i = 0; i < M; ++i) {
2213 StationState& s = S[i];
2214 const std::string& nm = sn.stations[i].name;
2215 if (s.bmsp)
2216 throw UnsupportedError(ErrorKind{"GlobalDependence"},
2217 "SolverLDES (native engine): station '" + nm +
2218 "' is a bulk (BMSP) server under a global dependence, which holds only a "
2219 "station-level firing clock and no per-job residual work to rescale");
2220 if (s.pas)
2221 throw UnsupportedError(ErrorKind{"GlobalDependence"},
2222 "SolverLDES (native engine): station '" + nm +
2223 "' is a pass-and-swap station under a global dependence, whose single "
2224 "aggregate clock is armed from its own list and carries no residual work "
2225 "to rescale");
2226 for (std::size_t r = 0; r < K; ++r) {
2227 const double pk = num_traits<T>::to_double(sn.gdscalingpeak[i * K + r]);
2228 if (!(pk > 0.0) || !std::isfinite(pk))
2229 throw InputError("SolverLDES (native engine): the global dependence declares "
2230 "a peak rate that is not finite and positive at station '" +
2231 nm + "'");
2232 s.gd_peak[r] = pk;
2233 }
2234 // Its rate is now a function of the whole population, so it has to
2235 // be re-timed at every change -- which is what `state_dependent`
2236 // means and is why a global dependence needs no flag of its own on
2237 // the buffered path.
2238 if (s.role == Role::Queue) s.state_dependent = true;
2239 }
2240 }
2241
2242 /**
2243 * RE-TIMING UNDER A STATE-DEPENDENT RATE RESCALES THE RESIDUAL WORK, at the
2244 * station whose rate changed and nowhere else (decided 2026-11-14, for
2245 * load, class, joint and global dependence alike). Each in-service job keeps
2246 * its remaining work and its completion is re-timed by old_rate/new_rate.
2247 * That is the time change CTMC and MATLAB apply when they scale the phase
2248 * rates of a PH service by phi(n), so it is the reference law for any
2249 * phase-type service, and for exponential service it equals the former
2250 * cancel-and-resample in law. The Java engine is being moved to the same
2251 * mechanism in `Solver_ssj.java`.
2252 *
2253 * The service requirement is drawn when a server TAKES the job wherever
2254 * the reference draws it there (`serviceTimeOnServer`).
2255 */
2256 for (std::size_t i = 0; i < M; ++i) {
2257 StationState& s = S[i];
2258 s.draw_at_start = s.role == Role::Queue && !s.ps && !s.pas && !s.preemptive &&
2259 !s.polling && !s.rr && !s.bmsp && !s.size_ordered;
2260 }
2261
2262 // ---- routing, resolved once per (station, class) -----------------------
2263 // A Router, a ClassSwitch and a Logger are not stations. `Peff` is a
2264 // NODE-level matrix and keeps them, so they appear as destinations here and
2265 // `deliver` walks through them in one instant; a destination that is none of
2266 // those and none of Source/Queue/Delay/Sink/Fork/Join/Cache/Place/Transition
2267 // is a node this engine must not guess at.
2268 const std::size_t nnodes = sn.nof_nodes();
2269 std::vector<std::size_t> node_to_station(nnodes + 1, M);
2270 for (std::size_t i = 0; i < M; ++i) node_to_station[sn.station_to_node[i]] = i;
2271
2272 /**
2273 * ROUTING IS RESOLVED OVER NODES, not over stations.
2274 *
2275 * A Router, a ClassSwitch and a Logger appear here as destinations: the
2276 * stochastic complement that removes them lives in `rt`, not in the
2277 * NODE-level `Peff` this table is read off. They hold nothing, so `deliver`
2278 * walks straight through them. A FORK and a JOIN are different again: they
2279 * are stateful, they change the NUMBER of jobs in flight, and no stochastic
2280 * complement can express that, so `deliver` replicates at a Fork and
2281 * synchronizes at a Join.
2282 */
2283 std::vector<std::vector<std::vector<RouteDest>>> nroute(
2284 nnodes + 1, std::vector<std::vector<RouteDest>>(K));
2285 /**
2286 * The dispatcher each (node, class) declares, and its round-robin pointer.
2287 *
2288 * The pointer is per (node, class) and NOT per destination: a round-robin
2289 * dispatcher hands out its outgoing links in turn, and one counter per link
2290 * would let two classes at the same node walk the cycle independently and
2291 * both start at the head.
2292 */
2293 std::vector<std::vector<lang::RoutingStrategy>> node_routing(
2294 nnodes + 1, std::vector<lang::RoutingStrategy>(K, lang::RoutingStrategy::PROB));
2295 std::vector<std::vector<std::size_t>> rr_counter(nnodes + 1, std::vector<std::size_t>(K, 0));
2296 for (std::size_t inode = 1; inode <= nnodes; ++inode)
2297 for (std::size_t r = 0; r < K; ++r)
2298 if (sn.nodes[inode - 1].routing.size() > r)
2299 node_routing[inode][r] = sn.nodes[inode - 1].routing[r];
2300 for (std::size_t inode = 1; inode <= nnodes; ++inode) {
2301 // THE SINK HAS NO OUTGOING PATH. The refresh writes a Sink -> Source
2302 // closure into the effective routing so the visit ratios of an open
2303 // model have a cycle to solve on; it is bookkeeping, not a route a job
2304 // takes. Reading it as one sends every departing job back to the
2305 // Source. The station-level table never saw it because the Sink is not
2306 // a station.
2307 if (sn.nodes[inode - 1].nodetype == NodeType::Sink) continue;
2308 // A PETRI NET DOES NOT ROUTE. Its arcs declare the structure, but the
2309 // tokens move by the enabling and firing matrices of the transitions,
2310 // so walking the routing here would move them twice.
2311 if (sn.nodes[inode - 1].nodetype == NodeType::Place ||
2312 sn.nodes[inode - 1].nodetype == NodeType::Transition)
2313 continue;
2314 for (std::size_t r = 0; r < K; ++r) {
2315 // ASCENDING NODE INDEX in the outer loop: this is the order the
2316 // round-robin pointer walks, and it is the reference's order.
2317 for (std::size_t j = 1; j <= nnodes; ++j) {
2318 RouteDest d;
2319 d.node = j;
2320 d.sink = (sn.nodes[j - 1].nodetype == NodeType::Sink);
2321 d.station = node_to_station[j];
2322 for (std::size_t s2 = 0; s2 < K; ++s2) {
2323 const double p = num_traits<T>::to_double(sn.route_eff(r + 1, s2 + 1, inode, j));
2324 if (!(p > 0.0)) continue;
2325 d.mass += p;
2326 d.cls.push_back(std::make_pair(s2, p));
2327 }
2328 if (d.cls.empty()) continue;
2329 // A Fork, a Join and a Cache are STATEFUL and hold jobs; a
2330 // ClassSwitch, a Router and a Logger do not and are walked
2331 // through in one step by `deliver`. Neither kind is folded away
2332 // by the refresh -- `Peff` is a NODE-level matrix and keeps
2333 // every intermediate hop -- so both must be reachable here.
2334 // Anything else is a node this engine would have to guess at.
2335 if (!d.sink && d.station >= M && sn.nodes[j - 1].nodetype != NodeType::Fork &&
2336 sn.nodes[j - 1].nodetype != NodeType::Join &&
2337 sn.nodes[j - 1].nodetype != NodeType::Cache &&
2338 sn.nodes[j - 1].nodetype != NodeType::ClassSwitch &&
2339 sn.nodes[j - 1].nodetype != NodeType::Router &&
2340 sn.nodes[j - 1].nodetype != NodeType::Logger &&
2341 sn.nodes[j - 1].nodetype != NodeType::Place &&
2342 sn.nodes[j - 1].nodetype != NodeType::Transition)
2343 throw UnsupportedError(ErrorKind{"RoutingStrategy"},
2344 "SolverLDES (native engine): the routing crosses node '" +
2345 sn.nodes[j - 1].name +
2346 "', which the refresh did not fold into the station-to-station "
2347 "routing");
2348 if (d.station < M && S[d.station].role == Role::Source)
2349 throw InputError("SolverLDES (native engine): the routing sends a "
2350 "job back into the Source");
2351 nroute[inode][r].push_back(d);
2352 }
2353 }
2354 }
2355
2356 // ---- fork and join --------------------------------------------------------
2357 // A Fork replicates the arriving job onto every outgoing edge; a Join holds
2358 // the siblings until the strategy is satisfied and releases ONE job. The
2359 // pair is matched by `sn.fj`, so a Fork with no Join is a model whose
2360 // siblings never recombine and is refused rather than run.
2361 std::vector<int> join_of_fork(nnodes + 1, -1);
2362 std::vector<bool> is_fork(nnodes + 1, false), is_join(nnodes + 1, false);
2363 for (const auto& fjp : sn.fj) {
2364 if (fjp.first > nnodes || fjp.second > nnodes) continue;
2365 is_fork[fjp.first] = true;
2366 is_join[fjp.second] = true;
2367 join_of_fork[fjp.first] = static_cast<int>(fjp.second);
2368 }
2369 // Whether a class routes into a Join ANYWHERE: it decides whether a phase-2
2370 // continuation of that class inherits the trigger's fork identity.
2371 std::vector<bool> spawn_joins_at(K, false);
2372 for (std::size_t inode = 1; inode <= nnodes; ++inode)
2373 for (std::size_t r = 0; r < K; ++r)
2374 for (const RouteDest& d : nroute[inode][r])
2375 if (d.node >= 1 && d.node <= nnodes &&
2376 sn.nodes[d.node - 1].nodetype == NodeType::Join)
2377 for (std::size_t c = 0; c < d.cls.size(); ++c)
2378 spawn_joins_at[d.cls[c].first] = true;
2379 for (std::size_t nd = 1; nd <= nnodes; ++nd) {
2380 if (sn.nodes[nd - 1].nodetype == NodeType::Fork && !is_fork[nd])
2381 throw InputError("SolverLDES (native engine): Fork node '" + sn.nodes[nd - 1].name +
2382 "' has no matching Join");
2383 if (sn.nodes[nd - 1].nodetype == NodeType::Join && !is_join[nd])
2384 throw InputError("SolverLDES (native engine): Join node '" + sn.nodes[nd - 1].name +
2385 "' closes no Fork");
2386 }
2387
2388 /**
2389 * One forked parent awaiting its siblings.
2390 *
2391 * `required` is fixed at FORK time, not at join time: the quorum is a
2392 * fraction of the siblings THIS fork produced, and a Join shared by two
2393 * forks of different fan-out would otherwise apply one fork's count to the
2394 * other's siblings.
2395 */
2396 struct ForkSync {
2397 std::size_t cls = 0;
2398 double t_sys = 0.0;
2399 int sys_cls = -1; ///< Job::sys_cls of the parent
2400 int total = 0;
2401 int required = 0;
2402 /**
2403 * (class, instant) of every sibling this parent has parked at the Join.
2404 *
2405 * Held PER PARENT, not per Join: the Join's queue length must fall by
2406 * the siblings THIS synchronization releases, and a node-wide tally
2407 * would clear the siblings of every other parent still waiting. It also
2408 * dates each sibling's own wait, which is `forkedJobJoinArrivalTimes`.
2409 */
2410 std::vector<std::pair<std::size_t, double>> siblings;
2411 /** The parent's own fork identity, restored on release so a NESTED section rejoins its outer one. */
2412 std::uint64_t outer = 0;
2413 double t_fork = 0.0; ///< when the parent arrived at the Fork, the start of its FJRespT sample
2414 int pair = -1; ///< index of the (Fork, Join) pair in fj_pairs, -1 when unpaired
2415 };
2416 std::map<std::uint64_t, ForkSync> fork_sync;
2417 std::uint64_t next_parent = 0;
2418 // FORK-JOIN SECTION METRICS (getAvgFJ). One sojourn sample per parent, from its arrival at the Fork to its
2419 // release by the Join, under the (pair, class it arrived in). Release epochs are kept so FJTput is
2420 // differenced at the truncation point exactly as TN is; the sojourn is the full tally, as RN is.
2421 const std::vector<std::pair<std::size_t, std::size_t>> fj_pairs = solvers::fj_sorted_pairs(sn);
2422 std::vector<int> fj_pair_of_fork(nnodes + 1, -1);
2423 for (std::size_t p = 0; p < fj_pairs.size(); ++p)
2424 if (fj_pairs[p].first <= nnodes &&
2425 join_of_fork[fj_pairs[p].first] == static_cast<int>(fj_pairs[p].second))
2426 fj_pair_of_fork[fj_pairs[p].first] = static_cast<int>(p);
2427 std::vector<std::vector<double>> fj_resp_sum(fj_pairs.size(), std::vector<double>(K, 0.0));
2428 std::vector<std::vector<double>> fj_resp_cnt(fj_pairs.size(), std::vector<double>(K, 0.0));
2429 std::vector<std::vector<std::vector<double>>> fj_release(fj_pairs.size(),
2430 std::vector<std::vector<double>>(K));
2431
2432
2433 // ---- cache nodes ----------------------------------------------------------
2434 // A Cache is a ROUTING node with state: it reads an item, decides hit or
2435 // miss on its real list contents, and switches the job onto the hit or the
2436 // miss class. That makes the hit an exact sample-path event rather than a
2437 // rate, which is the reason to ask a simulator about a cache at all.
2438 std::map<std::size_t, CacheState> caches;
2439 for (const auto& np : sn.nodeparam) {
2440 const std::size_t nd = np.first;
2441 if (nd == 0 || nd > nnodes) continue;
2442 if (sn.nodes[nd - 1].nodetype != NodeType::Cache) continue;
2443 const auto& cp = np.second;
2444 CacheState cs;
2445 cs.node = nd;
2446 cs.nitems = cp.nitems;
2447 cs.policy = cp.replacestrat;
2448 for (int c : cp.itemcap)
2449 if (c > 0) cs.capacity.push_back(static_cast<std::size_t>(c));
2450 if (cs.capacity.empty()) cs.capacity.push_back(1);
2451 cs.lists.assign(cs.capacity.size(), std::list<std::size_t>());
2452 for (int v : cp.itemsize) cs.item_size.push_back(v);
2453 for (int v : cp.costcap) cs.cost_cap.push_back(v);
2454 cs.hits.assign(K, 0.0);
2455 cs.misses.assign(K, 0.0);
2456 cs.hits_per_list.assign(K, std::vector<double>(cs.lists.size(), 0.0));
2457 cs.item_level_time.assign(cs.nitems, std::vector<double>(cs.lists.size(), 0.0));
2458 cs.hit_class.assign(K, -1);
2459 cs.miss_class.assign(K, -1);
2460 for (std::size_t r = 0; r < K && r < cp.hitclass.size(); ++r)
2461 if (cp.hitclass[r] > 0) cs.hit_class[r] = static_cast<int>(cp.hitclass[r] - 1);
2462 for (std::size_t r = 0; r < K && r < cp.missclass.size(); ++r)
2463 if (cp.missclass[r] > 0) cs.miss_class[r] = static_cast<int>(cp.missclass[r] - 1);
2464 // The popularity is stored as a pmf per class and used as a CUMULATIVE
2465 // law here, so one uniform draw picks an item.
2466 cs.popularity.assign(K, std::vector<double>());
2467 for (std::size_t r = 0; r < K && r < cp.pread.size(); ++r) {
2468 double acc = 0.0;
2469 for (const T& v : cp.pread[r]) {
2470 acc += num_traits<T>::to_double(v);
2471 cs.popularity[r].push_back(acc);
2472 }
2473 if (!cs.popularity[r].empty()) cs.popularity[r].back() = 1.0;
2474 }
2475 // Delayed-hit retrieval: one class per (item, read class) carries the
2476 // fetch through the retrieval stations and back here.
2477 if (cp.retrieval_capacity > 0 && !cp.retrieval_classes.empty()) {
2478 cs.has_retrieval = true;
2479 cs.retrieval_class = cp.retrieval_classes;
2480 cs.retrieval_class_to_item.assign(K, -1);
2481 for (std::size_t it = 0; it < cs.retrieval_class.size(); ++it)
2482 for (std::size_t r = 0; r < cs.retrieval_class[it].size(); ++r) {
2483 const std::size_t rc = cs.retrieval_class[it][r];
2484 if (rc > 0 && rc <= K) cs.retrieval_class_to_item[rc - 1] = static_cast<int>(it);
2485 }
2486 cs.in_flight.assign(cs.nitems, 0);
2487 cs.fetch_start.assign(cs.nitems, 0.0);
2488 cs.held.assign(cs.nitems, std::vector<CacheState::HeldRequest>());
2489 cs.delayed.assign(K, 0.0);
2490 }
2491 caches[nd] = cs;
2492 }
2493
2494
2495 // ---- Petri net: places and transitions --------------------------------------
2496 // A Place is a STATION holding tokens per class; a Transition is a node that
2497 // moves them. The marking is the places' token counts, and it is the only
2498 // state the net has.
2499 std::vector<std::size_t> place_of(nnodes + 1, M);
2500 std::vector<std::size_t> place_nodes;
2501 for (std::size_t nd = 1; nd <= nnodes; ++nd)
2502 if (sn.nodes[nd - 1].nodetype == NodeType::Place) {
2503 place_of[nd] = place_nodes.size();
2504 place_nodes.push_back(nd);
2505 }
2506 std::vector<std::size_t> place_station(place_nodes.size(), M);
2507 for (std::size_t p = 0; p < place_nodes.size(); ++p)
2508 place_station[p] = node_to_station[place_nodes[p]];
2509 /**
2510 * The initial marking: what the model DECLARED, widened by the closed
2511 * populations whose reference station is this place.
2512 *
2513 * The widening is not a convenience. A closed class in a Petri net has its
2514 * jobs in the marking and nowhere else, and `Network.initDefault` is what
2515 * puts them there -- which the JSON document only records once someone has
2516 * called `setState`, so a net that never did would start EMPTY and never
2517 * fire. `default_init_state` takes the same maximum for the CTMC, and
2518 * `initClosedClassPopulations` skips its own injection on a Place for the
2519 * same reason, so all three agree on the state the model starts in.
2520 */
2521 std::vector<std::vector<double>> marking(place_nodes.size(), std::vector<double>(K, 0.0));
2522 for (std::size_t p = 0; p < place_nodes.size(); ++p) {
2523 auto im = sn.initmarking.find(place_nodes[p]);
2524 if (im != sn.initmarking.end())
2525 for (std::size_t r = 0; r < K && r < im->second.size(); ++r)
2526 marking[p][r] = num_traits<T>::to_double(im->second[r]);
2527 for (std::size_t r = 0; r < K; ++r) {
2528 if (sn.classes[r].type == lang::JobClassType::OPEN) continue;
2529 const double n = sn.classes[r].population;
2530 if (!std::isfinite(n) || !(n > 0.0)) continue;
2531 if (sn.classes[r].refstat != place_station[p] + 1) continue;
2532 marking[p][r] = std::max(marking[p][r], n);
2533 }
2534 }
2535
2536 // ---- queueing places -----------------------------------------------------
2537 /**
2538 * A QUEUEING PLACE holds its tokens in three compartments, and only the last
2539 * of them is what a Petri net normally calls the marking.
2540 *
2541 * waiting tokens queued for one of the place's own servers
2542 * in service tokens a server is working on
2543 * depository tokens whose service is finished
2544 *
2545 * THE OUTPUT ARCS SEE THE DEPOSITORY ALONE. That is the entire construct: a
2546 * token deposited by an input transition has to be SERVED before it can
2547 * enable an output one, which is how a queueing Petri net puts a scheduling
2548 * station inside a place. `marking` stays the sum of the three, because that
2549 * is what the place's token count means and what QN reports.
2550 *
2551 * An ORDINARY place keeps `avail == marking` and never touches the rest, so
2552 * every existing net is unmoved.
2553 */
2554 std::vector<std::vector<double>> avail(place_nodes.size(), std::vector<double>(K, 0.0));
2555 std::vector<bool> qplace(place_nodes.size(), false);
2556 std::vector<std::size_t> place_servers(place_nodes.size(), 1);
2557 std::vector<std::deque<std::size_t>> place_wait(place_nodes.size());
2558 std::vector<std::size_t> place_busy(place_nodes.size(), 0);
2559 std::vector<std::vector<double>> place_insvc(place_nodes.size(), std::vector<double>(K, 0.0));
2560 std::vector<std::vector<Sampler>> place_svc(place_nodes.size(), std::vector<Sampler>(K));
2561 /**
2562 * One stream per (place, class), on the reference's own band.
2563 *
2564 * `Solver_ssj` seeds a queueing place's generators at
2565 * `((numSources + numServiceNodes + placeIdx) * K + k) * 10 + 5000`, and
2566 * this is that expression: `svc_index` already numbers the non-Source
2567 * stations the way `numServiceNodes` counts them, and a place IS one of
2568 * them here. The transition clocks sit at the bare +5000 of `g_spn`, which
2569 * the expression never reaches because an SPN has at least one place and so
2570 * at least one full stride of K*10 above it.
2571 */
2572 std::vector<std::vector<Rng>> g_place(place_nodes.size());
2573 for (std::size_t p = 0; p < place_nodes.size(); ++p) {
2574 const std::size_t ist = place_station[p];
2575 g_place[p].reserve(K);
2576 for (std::size_t k = 0; k < K; ++k) {
2577 const long long off =
2578 ((nsrc + nsvc + static_cast<long long>(p)) * Kll + static_cast<long long>(k)) *
2579 10 + 5000;
2580 g_place[p].push_back(Rng(seed_ll, off));
2581 }
2582 if (ist >= M) continue;
2583 qplace[p] = sn.is_queueing_place(ist);
2584 if (!qplace[p]) {
2585 for (std::size_t r = 0; r < K; ++r) avail[p][r] = marking[p][r];
2586 continue;
2587 }
2588 const auto& pst = sn.stations[ist];
2589 // The embedded queue's discipline. FCFS, LCFS and SIRO differ only in
2590 // WHICH waiting token is taken next; INF takes every one of them at
2591 // once and so has no order to choose. Anything else is refused by name:
2592 // sharing a place's server among its tokens, or ordering them by a size
2593 // the place never sampled, is a queue this construct does not describe.
2594 if (pst.sched != SchedStrategy::FCFS && pst.sched != SchedStrategy::LCFS &&
2595 pst.sched != SchedStrategy::SIRO && pst.sched != SchedStrategy::INF)
2596 throw UnsupportedError(ErrorKind{"QueueingPlace"},
2597 "SolverLDES (native engine): queueing place '" + pst.name +
2598 "' is scheduled " + lang::sched_to_text(pst.sched) +
2599 ", which the embedded-queue algorithm does not support "
2600 "(supported: FCFS, LCFS, SIRO, INF)");
2601 place_servers[p] = (pst.sched == SchedStrategy::INF || !std::isfinite(pst.nservers))
2602 ? std::numeric_limits<std::size_t>::max()
2603 : static_cast<std::size_t>(pst.nservers + 0.5);
2604 for (std::size_t r = 0; r < K; ++r) {
2605 if (sn.service[ist][r].disabled) continue;
2606 place_svc[p][r] =
2607 Sampler(sn.service[ist][r],
2608 "queueing place '" + pst.name + "', class '" + sn.classes[r].name + "'");
2609 }
2610 // The initial tokens are QUEUED, not deposited: a token the model puts
2611 // in a queueing place has not been served yet, so it must pass through
2612 // the embedded queue before an output arc may take it. ASCENDING class
2613 // order, which is the order `Solver_ssj` enqueues them in.
2614 for (std::size_t k = 0; k < K; ++k)
2615 for (double t = 0.0; t + 0.5 < marking[p][k]; t += 1.0) place_wait[p].push_back(k);
2616 }
2617
2618 std::vector<SpnTransition> transitions;
2619 // The firing LAW of each timed mode, [transition][mode]; `SpnMode::rate` keeps only its mean.
2620 std::vector<std::vector<Sampler>> spn_law;
2621 for (const auto& tp : sn.transparam) {
2622 const std::size_t nd = tp.first;
2623 if (nd == 0 || nd > nnodes) continue;
2624 SpnTransition tr;
2625 tr.node = nd;
2626 tr.places = place_nodes;
2627 for (std::size_t m = 0; m < tp.second.nmodes; ++m) {
2628 SpnMode mode;
2629 // (place slot, class), flattened p*K + r, the layout `flat_marking`
2630 // produces and `spn_enabled`/`spn_fire` read.
2631 for (std::size_t p = 0; p < place_nodes.size(); ++p) {
2632 const std::size_t pn = place_nodes[p];
2633 for (std::size_t r = 0; r < K; ++r) {
2634 mode.enabling.push_back(
2635 (m < tp.second.enabling.size() && pn - 1 < tp.second.enabling[m].rows() &&
2636 r < tp.second.enabling[m].cols())
2637 ? num_traits<T>::to_double(tp.second.enabling[m](pn - 1, r))
2638 : 0.0);
2639 mode.inhibiting.push_back(
2640 (m < tp.second.inhibiting.size() &&
2641 pn - 1 < tp.second.inhibiting[m].rows() &&
2642 r < tp.second.inhibiting[m].cols())
2643 ? num_traits<T>::to_double(tp.second.inhibiting[m](pn - 1, r))
2644 : std::numeric_limits<double>::infinity());
2645 mode.firing.push_back(
2646 (m < tp.second.firing.size() && pn - 1 < tp.second.firing[m].rows() &&
2647 r < tp.second.firing[m].cols())
2648 ? num_traits<T>::to_double(tp.second.firing[m](pn - 1, r))
2649 : 0.0);
2650 }
2651 }
2652 if (m < tp.second.firing.size())
2653 for (std::size_t nd2 = 1; nd2 <= nnodes && nd2 - 1 < tp.second.firing[m].rows(); ++nd2) {
2654 if (sn.nodes[nd2 - 1].nodetype == NodeType::Place) continue;
2655 for (std::size_t r = 0; r < K && r < tp.second.firing[m].cols(); ++r) {
2656 const double f = num_traits<T>::to_double(tp.second.firing[m](nd2 - 1, r));
2657 if (f > 0.0) mode.exits.emplace_back(nd2, r, f);
2658 }
2659 }
2660 if (m < tp.second.nmodeservers.size()) mode.servers = tp.second.nmodeservers[m];
2661 if (m < tp.second.firingprio.size()) mode.priority = tp.second.firingprio[m];
2662 if (m < tp.second.fireweight.size())
2663 mode.weight = num_traits<T>::to_double(tp.second.fireweight[m]);
2664 mode.immediate = (m < tp.second.timing.size() &&
2665 tp.second.timing[m] == lang::TimingStrategy::IMMEDIATE);
2666 if (m < tp.second.firingproc.size() && !tp.second.firingproc[m].disabled) {
2667 const double mean = num_traits<T>::to_double(tp.second.firingproc[m].mean);
2668 if (mean > 0.0) mode.rate = 1.0 / mean;
2669 }
2670 if (m < tp.second.firingdep.size() && tp.second.firingdep[m]) {
2671 const auto f = tp.second.firingdep[m];
2672 const std::vector<std::size_t> pl = place_nodes;
2673 const std::size_t nn = nnodes, KK = K;
2674 // g(marking) reads the NODE-indexed (node, class) marking flattened node-major, the vector
2675 // `state_events.h` builds; the engine's own (place, class) vector is re-laid onto it by node.
2676 mode.dep = [f, pl, nn, KK](const std::vector<double>& tok) {
2677 std::vector<T> mk(nn * KK, num_traits<T>::from_int(0));
2678 for (std::size_t p = 0; p < pl.size(); ++p) {
2679 if (pl[p] < 1 || pl[p] - 1 >= nn) continue;
2680 for (std::size_t r = 0; r < KK; ++r)
2681 if (p * KK + r < tok.size())
2682 mk[(pl[p] - 1) * KK + r] = num_traits<T>::from_double(tok[p * KK + r]);
2683 }
2684 return num_traits<T>::to_double(f(mk));
2685 };
2686 }
2687 tr.modes.push_back(mode);
2688 }
2689 tr.fired.assign(tr.modes.size(), 0.0);
2690 std::vector<Sampler> law(tr.modes.size());
2691 const std::string tname = sn.nodes[nd - 1].name;
2692 for (std::size_t m = 0; m < tr.modes.size(); ++m)
2693 if (!tr.modes[m].immediate && m < tp.second.firingproc.size() &&
2694 !tp.second.firingproc[m].disabled)
2695 law[m] = Sampler(tp.second.firingproc[m], "the firing time of mode " +
2696 std::to_string(m + 1) + " of transition '" + tname + "'");
2697 spn_law.push_back(law);
2698 transitions.push_back(tr);
2699 }
2700
2701 // ---- statistics --------------------------------------------------------
2702 Accum acc(M, K);
2703 for (std::size_t i = 0; i < M; ++i) acc.util_peak[i] = S[i].util_peak;
2704 // A PLACE'S QUEUE LENGTH IS ITS MARKING, and it starts at the initial one.
2705 // The integral is lazy, so the value has to be in `acc.qlen` from t = 0 and
2706 // every later write has to go through `update_qlen` first, exactly as a
2707 // station's does.
2708 for (std::size_t p = 0; p < place_nodes.size(); ++p) {
2709 if (place_station[p] >= M) continue;
2710 for (std::size_t r = 0; r < K; ++r) acc.qlen[place_station[p]][r] = marking[p][r];
2711 }
2712 // Declared here and populated below: the admission lambda tracks into it,
2713 // and a lambda cannot capture a name introduced after it.
2714 BusyPeriods bp;
2715 std::vector<double> sys_resp_sum(K, 0.0), sys_resp_cnt(K, 0.0), sys_completed(K, 0.0);
2716 // Per (station, class): a model can drop at one station and balk at
2717 // another, and a per-class total would not say which.
2718 std::vector<std::vector<double>> dropped(M, std::vector<double>(K, 0.0));
2719 std::vector<std::vector<double>> balked(M, std::vector<double>(K, 0.0));
2720 std::vector<std::vector<double>> reneged(M, std::vector<double>(K, 0.0));
2721 // Epoch of the LAST job lost unserved (reneged, or removed by a NEGATIVE/CATASTROPHE signal) per (station, class),
2722 // -1 when none: compared with the truncation epoch it says whether any loss falls in the measured window.
2723 std::vector<std::vector<double>> last_lost(M, std::vector<double>(K, -1.0));
2724 std::vector<std::vector<double>> blocked_count(M, std::vector<double>(K, 0.0));
2725 /**
2726 * Every per-visit response time, when either flag asked for them.
2727 *
2728 * --trajectory counts as asking: the reference NESTS the same samples inside
2729 * its `transient` block, and MATLAB's `sample()` and `sampleSys()` read them
2730 * from there. Recording only under --respt-samples left those two returning
2731 * nothing on the transient path.
2732 */
2733 const bool want_respt = o.export_respt || o.export_trajectory;
2734 std::vector<std::vector<std::vector<double>>> resp_samples(
2735 want_respt ? M : 0, std::vector<std::vector<double>>(K));
2736 std::uint64_t job_id = 0;
2737 double now = 0.0;
2738
2739 /**
2740 * THE TWO OPERATIONAL-TIME PRIMITIVES (`Sampler::op_time`), and the identity
2741 * off an NHPP service. `svc_work` is the work delivered at full share over a
2742 * wall interval and `svc_delay` the wall delay until `work` units are
2743 * delivered from now, computed as the reference does (`t1 - now`, then
2744 * scheduled at `now + delay`). Every residual this engine carries is in
2745 * operational time, so these are the only two places the schedule enters.
2746 */
2747 auto svc_nhpp = [&](std::size_t i, std::size_t c) -> const Sampler* {
2748 if (i >= M || c >= S[i].svc.size()) return nullptr;
2749 const Sampler& sm = S[i].svc[c];
2750 return sm.op_time() ? &sm : nullptr;
2751 };
2752 auto svc_work = [&](std::size_t i, std::size_t c, double t0, double t1) -> double {
2753 const Sampler* sm = svc_nhpp(i, c);
2754 if (!sm) return t1 - t0;
2755 return sm->op_work_between(t0, t1);
2756 };
2757 auto svc_delay = [&](std::size_t i, std::size_t c, double work) -> double {
2758 const Sampler* sm = svc_nhpp(i, c);
2759 if (!sm) return work;
2760 return sm->op_wall_after(now, work) - now;
2761 };
2762
2763 /**
2764 * LOGGER TRACES, the reference's `initializeLoggers` and `logJobPassage`.
2765 *
2766 * Every Logger writes one CSV row per job crossing it, into `filePath` (or
2767 * the model's log path when the node names none) joined with `fileName`
2768 * (`logger_<name>.csv` when unnamed). The header always carries all seven
2769 * columns and a column whose flag is off is left EMPTY, delimiters kept,
2770 * so a trace has the same shape whatever it records. The interarrival
2771 * columns measure from time 0 for the first crossing, as the reference's
2772 * zero-initialized last-crossing times do. JOB_ID is a counter taken
2773 * once per routing walk through pass-through nodes, which is what the
2774 * reference's `nextJobId++` in `selectDestination` numbers.
2775 */
2776 struct LoggerTrace {
2777 std::unique_ptr<std::ofstream> out;
2778 qn::NodeDef::LoggerParam par;
2779 std::string name;
2780 double last_any = 0.0;
2781 std::vector<double> last_cls;
2782 };
2783 std::map<std::size_t, LoggerTrace> logger_traces;
2784 std::string log_start_time;
2785 std::uint64_t log_walk_id = 0;
2786 for (std::size_t nd = 1; nd <= sn.nof_nodes(); ++nd) {
2787 if (sn.nodes[nd - 1].nodetype != NodeType::Logger) continue;
2788 if (log_start_time.empty()) {
2789 const std::time_t tt = std::time(nullptr);
2790 char buf[32];
2791 std::strftime(buf, sizeof buf, "%Y-%m-%d %H:%M:%S", std::localtime(&tt));
2792 log_start_time = buf;
2793 }
2794 LoggerTrace lt;
2795 lt.par = sn.nodes[nd - 1].logger;
2796 lt.name = sn.nodes[nd - 1].name;
2797 lt.last_cls.assign(K, 0.0);
2798 const std::string file =
2799 lt.par.file_name.empty() ? "logger_" + lt.name + ".csv" : lt.par.file_name;
2800 std::string dir = lt.par.file_path.empty() ? sn.log_path : lt.par.file_path;
2801 if (!dir.empty() && dir[dir.size() - 1] != '/') dir += '/';
2802 const std::string path = dir + file;
2803 lt.out.reset(new std::ofstream(path.c_str(), std::ios::out | std::ios::trunc));
2804 // A trace is a side output: a path that cannot be opened is reported and the run goes on.
2805 if (!*lt.out) {
2806 std::fprintf(stderr, "Warning: solver_ldes: failed to create logger file for %s: %s\n",
2807 lt.name.c_str(), path.c_str());
2808 continue;
2809 }
2810 *lt.out << "LOGGERNAME,TIMESTAMP,JOB_ID,CLASS_ID,INTERARRIVAL_SAMECLASS,"
2811 "INTERARRIVAL_ANYCLASS,SIMUL_START_TIME\n";
2812 logger_traces[nd] = std::move(lt);
2813 }
2814 auto log_passage = [&](std::size_t nd, std::size_t r, std::uint64_t id) {
2815 typename std::map<std::size_t, LoggerTrace>::iterator it = logger_traces.find(nd);
2816 if (it == logger_traces.end()) return;
2817 LoggerTrace& lt = it->second;
2818 const double same = now - lt.last_cls[r], any = now - lt.last_any;
2819 lt.last_cls[r] = now;
2820 lt.last_any = now;
2821 std::ostream& w = *lt.out;
2822 if (lt.par.logger_name) w << lt.name;
2823 w << ',';
2824 if (lt.par.timestamp) w << java_double_str(now);
2825 w << ',';
2826 if (lt.par.job_id) w << id;
2827 w << ',';
2828 if (lt.par.job_class) w << sn.classes[r].name;
2829 w << ',';
2830 if (lt.par.time_same_class) w << java_double_str(same);
2831 w << ',';
2832 if (lt.par.time_any_class) w << java_double_str(any);
2833 w << ',';
2834 if (lt.par.start_time) w << log_start_time;
2835 w << '\n';
2836 };
2837
2838 /**
2839 * G-NETWORK REMOVAL SIGNALS, resolved once per class.
2840 *
2841 * A removal signal is a class like any other while it is in transit and
2842 * stops being one the instant it reaches a station: it never joins, it
2843 * removes jobs already there and it is annihilated. `is_removal_signal`
2844 * is the whole gate, and everything the removal costs -- the registry of
2845 * jobs held at a Delay station, the extra draws -- is paid only where it
2846 * is true, so a model without signals runs exactly as before.
2847 */
2848 std::vector<bool> is_removal_signal(K, false);
2849 bool has_removal_signal = false;
2850 for (std::size_t r = 0; r < K; ++r) {
2851 if (r >= sn.issignal.size() || !sn.issignal[r]) continue;
2852 const lang::SignalType kind =
2853 (r < sn.signaltype.size()) ? sn.signaltype[r] : lang::SignalType::NEGATIVE;
2855 is_removal_signal[r] = true;
2856 has_removal_signal = true;
2857 }
2858 }
2859 /**
2860 * The Delay job registry is kept for a GLOBAL DEPENDENCE as well as for a
2861 * removal signal: phi re-times the think times with everything else, and
2862 * the registry is the only handle on them (an infinite server has no slot
2863 * to hang a generation off).
2864 */
2865 // `options.init_jobs` and `options.track_jobs`: see the injection below and
2866 // the export at the end of the run.
2867 const bool init_jobs_on = o.init_jobs.rows() > 0;
2868 const bool track_jobs = o.track_jobs || init_jobs_on;
2869 // The sample-path export reads a Delay's occupants from this registry too.
2870 const bool track_delay_jobs = has_removal_signal || has_gd || track_jobs || sp_on;
2871 /** [id, station, class, time] of each departure of a tagged init_jobs job. */
2872 std::vector<std::array<double, 4>> job_departure_log;
2873 /**
2874 * The jobs a Delay station currently holds, in arrival order.
2875 *
2876 * A Delay keeps no buffer and no server: its occupants live only in the
2877 * departure events already scheduled for them, and the event list has no
2878 * handle to cancel one. The registry is that handle -- a job removed by a
2879 * signal is erased from it, and the departure that arrives later finds no
2880 * entry and is discarded, which is the same tag trick the buffered
2881 * stations use against a preempted departure.
2882 */
2883 std::vector<std::vector<Job>> delay_live(track_delay_jobs ? M : 0);
2884
2885 /**
2886 * SYNCHRONOUS CALLS, `sn.syncreply`: the class a caller expects its reply in.
2887 *
2888 * A caller that expects one KEEPS ITS SERVER when it leaves for the callee
2889 * and gets it back only when the matching REPLY class returns, which is the
2890 * whole difference between a synchronous call and an ordinary hop. The
2891 * pending calls are keyed by an identity that rides on the job, because the
2892 * reply comes back from a station the caller never names.
2893 */
2894 std::vector<std::size_t> sync_reply(K, K);
2895 std::vector<bool> is_reply_signal(K, false);
2896 bool has_sync_call = false;
2897 for (std::size_t r = 0; r < K; ++r) {
2898 if (r < sn.syncreply.size() && sn.syncreply[r] >= 1 && sn.syncreply[r] <= K) {
2899 sync_reply[r] = sn.syncreply[r] - 1;
2900 has_sync_call = true;
2901 }
2902 if (r < sn.issignal.size() && sn.issignal[r] && r < sn.signaltype.size() &&
2903 sn.signaltype[r] == lang::SignalType::REPLY)
2904 is_reply_signal[r] = true;
2905 }
2906 /** One outstanding call: the slot it holds and the class that holds it. */
2907 struct PendingCall {
2908 std::size_t station = 0;
2909 std::size_t slot = 0;
2910 std::size_t cls = 0;
2911 double since = 0.0;
2912 };
2913 std::map<std::uint64_t, PendingCall> pending_reply;
2914 std::uint64_t next_call = 0;
2915 /**
2916 * REPLIES THAT ANSWERED A CALL, per (station, class): the completions a
2917 * reply makes at the caller WHILE THE CALLEE'S DEPARTURE IS ROUTED. They
2918 * are downstream of the completion that triggers a fixed-warmup reset, and
2919 * the reference resets before routing, so the reset keeps the ones that
2920 * event made instead of zeroing them with the station's own completions.
2921 */
2922 std::vector<std::vector<double>> reply_passed(M, std::vector<double>(K, 0.0));
2923
2924 /** Whether any (station, class) declares immediate feedback at all. */
2925 bool has_immfeed = false;
2926 for (std::size_t i = 0; i < M && i < sn.immfeed.size(); ++i)
2927 for (std::size_t r = 0; r < sn.immfeed[i].size(); ++r)
2928 if (sn.immfeed[i][r]) has_immfeed = true;
2929
2930 /**
2931 * SPAWN ON COMPLETION, `sn.classspawn`: completing a job of class r injects
2932 * a FRESH job of the mapped class at the same station.
2933 *
2934 * It is an LQN phase-2 continuation: the work the server owes after the
2935 * reply has gone back. The continuation is a new passage, so it starts its
2936 * own response-time clock and is not the completing job under another name.
2937 */
2938 std::vector<std::size_t> spawn_of(K, K);
2939 bool has_spawn = false;
2940 for (std::size_t r = 0; r < K; ++r)
2941 if (sn.classes[r].spawn >= 1 && sn.classes[r].spawn <= K) {
2942 spawn_of[r] = sn.classes[r].spawn - 1;
2943 has_spawn = true;
2944 }
2945
2946 // ---- event list --------------------------------------------------------
2947 std::priority_queue<Event, std::vector<Event>, EventLater> evq;
2948 std::uint64_t seq = 0, ps_tag = 0;
2949
2950 auto push = [&](Event e) {
2951 e.seq = seq++;
2952 evq.push(e);
2953 };
2954
2955 // ---- the embedded queue of a queueing place ------------------------------
2956 /**
2957 * Take the next waiting token into service, as often as a server is free.
2958 *
2959 * THE DISCIPLINE CHOOSES WHICH TOKEN, and nothing else about the place:
2960 * FCFS takes the token that has waited longest, LCFS the one that has waited
2961 * least, SIRO one at random, and INF takes all of them because it never runs
2962 * out of servers. The reference's engine accepts the same four names but
2963 * polls the head of one deque for all of them, so LCFS and SIRO are served
2964 * FIFO there; the mean token count is the same under any work-conserving
2965 * order at exponential service, and the two engines part company only in the
2966 * sojourn-time DISTRIBUTION they report.
2967 */
2968 std::function<void(std::size_t)> place_try_start = [&](std::size_t p) {
2969 const std::size_t ist = place_station[p];
2970 if (ist >= M) return;
2971 while (place_busy[p] < place_servers[p] && !place_wait[p].empty()) {
2972 std::size_t r = 0;
2973 if (S[ist].sched == SchedStrategy::LCFS) {
2974 r = place_wait[p].back();
2975 place_wait[p].pop_back();
2976 } else if (S[ist].sched == SchedStrategy::SIRO) {
2977 const std::size_t at = std::min(
2978 place_wait[p].size() - 1,
2979 static_cast<std::size_t>(uniform01(g_qplace) *
2980 static_cast<double>(place_wait[p].size())));
2981 r = place_wait[p][at];
2982 place_wait[p].erase(place_wait[p].begin() + static_cast<std::ptrdiff_t>(at));
2983 } else {
2984 r = place_wait[p].front();
2985 place_wait[p].pop_front();
2986 }
2987 // A COLOUR THE PLACE CANNOT SERVE IS A MODEL DEFECT, not a token to
2988 // pass through: a queueing place is queueing for every colour at
2989 // once, so a token arriving in a colour `setService` never named has
2990 // no service time to draw and would otherwise sit in the queue
2991 // forever, silently draining the net.
2992 if (place_svc[p][r].disabled())
2993 throw InputError("SolverLDES (native engine): a token of class '" +
2994 sn.classes[r].name + "' entered queueing place '" +
2995 sn.stations[ist].name +
2996 "', which has no service process for that class; call "
2997 "setService for every token colour of a queueing place");
2998 acc.update_busy(ist, r, now);
2999 ++place_busy[p];
3000 place_insvc[p][r] += 1.0;
3001 acc.busy[ist][r] = place_insvc[p][r];
3002 Event e;
3003 e.t = now + place_svc[p][r].next(g_place[p][r]);
3004 e.kind = EV_PLACE_SVC;
3005 e.station = p;
3006 e.cls = r;
3007 push(e);
3008 }
3009 };
3010
3011 /** Tokens an input arc puts at place `p`: into the queue, or straight to the arcs. */
3012 auto place_deposit = [&](std::size_t p, std::size_t r, double n) {
3013 const std::size_t ist = place_station[p];
3014 if (ist < M) {
3015 acc.update_qlen(ist, r, now);
3016 marking[p][r] += n;
3017 acc.qlen[ist][r] = marking[p][r];
3018 acc.arrived[ist][r] += n;
3019 } else {
3020 marking[p][r] += n;
3021 }
3022 if (!qplace[p]) {
3023 avail[p][r] += n;
3024 return;
3025 }
3026 for (double t = 0.0; t + 0.5 < n; t += 1.0) place_wait[p].push_back(r);
3027 place_try_start(p);
3028 };
3029
3030 /**
3031 * Tokens an output arc takes from place `p`, which are its COMPLETIONS.
3032 *
3033 * TN at a place is the rate at which tokens leave it, which is
3034 * `placeCompletions` in the reference and what Little's law turns back into
3035 * the mean token sojourn reported as RespT. A queueing place takes them from
3036 * the depository, the only compartment an arc can see.
3037 */
3038 auto place_take = [&](std::size_t p, std::size_t r, double n) {
3039 const std::size_t ist = place_station[p];
3040 marking[p][r] -= n;
3041 avail[p][r] -= n;
3042 if (ist < M) {
3043 acc.update_qlen(ist, r, now);
3044 acc.qlen[ist][r] = marking[p][r];
3045 acc.completed[ist][r] += n;
3046 }
3047 };
3048
3049
3050 /**
3051 * Push onto, and pop from, a station's waiting room.
3052 *
3053 * FSP takes the linear branch: its key is recomputed against the residual
3054 * work present at the station RIGHT NOW, over the waiting jobs and the
3055 * ones in service alike, so no stamped ordering can stand in for it. Every
3056 * other discipline has a per-job constant key and rides the heap.
3057 */
3058 auto buffer_push = [&](std::size_t i, const Job& job) {
3059 StationState& s = S[i];
3060 if (s.sched != SchedStrategy::FSP)
3061 jpq_offer(s.buffer, job, s.cmp);
3062 else
3063 s.buffer.push_back(job);
3064 };
3065 auto buffer_pop = [&](std::size_t i) -> Job {
3066 StationState& s = S[i];
3067 if (s.sched != SchedStrategy::FSP) {
3068 return jpq_poll(s.buffer, s.cmp);
3069 }
3070 std::vector<double> works;
3071 for (const Job& j : s.buffer) works.push_back(j.remaining);
3072 for (std::size_t sl = 0; sl < s.nservers; ++sl)
3073 if (s.server_busy[sl])
3074 works.push_back(std::max(0.0, s.server[sl].remaining -
3075 svc_work(i, s.server[sl].cls,
3076 s.server_start[sl], now)));
3077 std::size_t best = 0;
3078 double best_vft = std::numeric_limits<double>::infinity();
3079 for (std::size_t j = 0; j < s.buffer.size(); ++j) {
3080 const double v = fsp_virtual_finish(works, s.buffer[j].remaining,
3081 static_cast<double>(s.nservers), now);
3082 if (v < best_vft) {
3083 best_vft = v;
3084 best = j;
3085 }
3086 }
3087 Job job = s.buffer[best];
3088 s.buffer.erase(s.buffer.begin() + static_cast<std::ptrdiff_t>(best));
3089 return job;
3090 };
3091
3092 // ---- heterogeneous server pools: slot choice and buffer matching ---------
3093 //
3094 // Two questions the flat server bank never had to ask. WHICH SLOT can take
3095 // this job, and WHICH WAITING JOB can this slot take. Everything else in the
3096 // engine addresses a server by its slot and is untouched.
3097 //
3098 // On a station with no pools both reduce to what was there before -- the
3099 // first free slot, and the head of the waiting room -- so the pool-free path
3100 // keeps its exact draw sequence and a seeded homogeneous run is unchanged.
3101
3102 /**
3103 * Set only while the setup arrival path asks `free_slot_for` which POOL a
3104 * job goes to: the reference counts every non-busy server of a pool there,
3105 * powered or not (`getCompatibleServerTypes`), and only then looks inside
3106 * the pool for an ACTIVE, a DELAYOFF or an OFF server.
3107 */
3108 bool power_blind = false;
3109 /** Free, unblocked, unheld, POWERED (ACTIVE), and its pool accepts `cls`. */
3110 auto slot_ok_for = [&](const StationState& s, std::size_t sl, std::size_t cls) -> bool {
3111 if (s.server_busy[sl] || s.server_blocked[sl] || s.server_held[sl]) return false;
3112 if (s.has_setup && !power_blind && !s.power.empty() && s.power[sl] != PW_ACTIVE) return false;
3113 if (!s.has_pools) return true;
3114 return s.type_compat[s.server_type[sl]][cls];
3115 };
3116
3117 /** Idle, unblocked, unheld slots: the pool a job seizing n of them draws from. */
3118 auto free_slot_count = [&](std::size_t i) -> std::size_t {
3119 const StationState& s = S[i];
3120 std::size_t n = 0;
3121 for (std::size_t sl = 0; sl < s.server_busy.size(); ++sl)
3122 if (!s.server_busy[sl] && !s.server_blocked[sl] && !s.server_held[sl]) ++n;
3123 return n;
3124 };
3125
3126 /**
3127 * The free slot a job of class `cls` may enter, or `s.nservers` for none.
3128 *
3129 * The POOL is chosen first, by the station's heterogeneous scheduling
3130 * policy, and the slot is then the first free one inside it. That is the
3131 * reference's order and it matters: picking the globally-first free slot
3132 * would make every policy behave as ORDER.
3133 */
3134 auto free_slot_for = [&](std::size_t i, std::size_t cls) -> std::size_t {
3135 StationState& s = S[i];
3136 // A JOB DECLARING SERVER PARALLELISM NEEDS ITS WHOLE SET AT ONCE: a
3137 // station with fewer than n idle slots cannot start it even though one
3138 // of them is free, which is the entire content of the feature.
3139 if (s.has_parallelism && free_slot_count(i) < s.parallelism[cls]) return s.nservers;
3140 if (!s.has_pools) {
3141 for (std::size_t sl = 0; sl < s.nservers; ++sl)
3142 if (slot_ok_for(s, sl, cls)) return sl;
3143 return s.nservers;
3144 }
3145 // The pools that accept the class AND still hold a free slot.
3146 std::vector<std::size_t> cand;
3147 for (std::size_t t = 0; t < s.type_count.size(); ++t) {
3148 if (!s.type_compat[t][cls]) continue;
3149 for (std::size_t j = 0; j < s.type_count[t]; ++j)
3150 if (slot_ok_for(s, s.type_first[t] + j, cls)) {
3151 cand.push_back(t);
3152 break;
3153 }
3154 }
3155 if (cand.empty()) return s.nservers;
3156 std::size_t chosen = cand[0];
3157 if (cand.size() > 1) {
3158 switch (s.hetero_policy) {
3161 // Round robin over the pools: the one just used goes to the
3162 // back, so a steady stream spreads over the compatible
3163 // pools instead of filling the first one.
3164 for (std::size_t k = 0; k < s.type_order.size(); ++k) {
3165 const std::size_t t = s.type_order[k];
3166 if (std::find(cand.begin(), cand.end(), t) == cand.end()) continue;
3167 chosen = t;
3168 s.type_order.erase(s.type_order.begin() +
3169 static_cast<std::ptrdiff_t>(k));
3170 s.type_order.push_back(t);
3171 break;
3172 }
3173 break;
3174 }
3176 // Least flexible first: spend the pool that fewest classes
3177 // can use before the one that many can.
3178 for (std::size_t k = 0; k < s.alfs_order.size(); ++k)
3179 if (std::find(cand.begin(), cand.end(), s.alfs_order[k]) != cand.end()) {
3180 chosen = s.alfs_order[k];
3181 break;
3182 }
3183 break;
3184 }
3186 // Fastest server first, by this class's rate at the pool.
3187 double best = -1.0;
3188 for (std::size_t k = 0; k < cand.size(); ++k) {
3189 const double rt = s.type_rate[cand[k]][cls];
3190 if (rt > best) {
3191 best = rt;
3192 chosen = cand[k];
3193 }
3194 }
3195 break;
3196 }
3198 // A uniform draw over the candidate pools, off the ROUTING
3199 // stream as the reference draws it.
3200 std::size_t at = static_cast<std::size_t>(
3201 uniform01(g_routing) * static_cast<double>(cand.size()));
3202 if (at >= cand.size()) at = cand.size() - 1;
3203 chosen = cand[at];
3204 break;
3205 }
3207 default: {
3208 // Declaration order, which `cand` is already built in.
3209 chosen = cand[0];
3210 break;
3211 }
3212 }
3213 }
3214 for (std::size_t j = 0; j < s.type_count[chosen]; ++j) {
3215 const std::size_t sl = s.type_first[chosen] + j;
3216 if (slot_ok_for(s, sl, cls)) return sl;
3217 }
3218 return s.nservers;
3219 };
3220
3221 /** Is any waiting job servable by slot `sl`? */
3222 auto buffer_has_for_slot = [&](std::size_t i, std::size_t sl) -> bool {
3223 StationState& s = S[i];
3224 if (s.buffer.empty()) return false;
3225 // A server that is OFF, in SETUP or in DELAYOFF takes no job from here:
3226 // a setup completion and an arrival are the only ways it starts one.
3227 if (s.has_setup && !s.power.empty() && s.power[sl] != PW_ACTIVE) return false;
3228 if (!s.has_pools) return true;
3229 const std::vector<bool>& ok = s.type_compat[s.server_type[sl]];
3230 for (std::size_t j = 0; j < s.buffer.size(); ++j)
3231 if (ok[s.buffer[j].cls]) return true;
3232 return false;
3233 };
3234
3235 /**
3236 * Pop the job slot `sl` should serve next.
3237 *
3238 * Off a pooled station this IS `buffer_pop`. On one it is the job the
3239 * station's own order would have taken FIRST AMONG THOSE THE SLOT CAN
3240 * SERVE, which is what a pool means: a server does not skip the queue, it
3241 * skips the jobs it is not compatible with. The heap is drained and rebuilt
3242 * because the discipline's order lives in the comparator, not in the
3243 * sequence, so scanning the vector would answer in heap order rather than
3244 * in service order.
3245 */
3246 auto buffer_pop_for_slot = [&](std::size_t i, std::size_t sl) -> Job {
3247 StationState& s = S[i];
3248 if (!s.has_pools) return buffer_pop(i);
3249 const std::vector<bool>& ok = s.type_compat[s.server_type[sl]];
3250 std::vector<Job> skipped;
3251 Job job;
3252 bool got = false;
3253 while (!s.buffer.empty()) {
3254 Job cand = buffer_pop(i);
3255 if (ok[cand.cls]) {
3256 job = cand;
3257 got = true;
3258 break;
3259 }
3260 skipped.push_back(cand);
3261 }
3262 for (std::size_t j = 0; j < skipped.size(); ++j) buffer_push(i, skipped[j]);
3263 if (!got)
3264 throw InputError("SolverLDES (native engine): buffer_pop_for_slot was asked for a "
3265 "job no pool of this slot can serve; guard with buffer_has_for_slot");
3266 return job;
3267 };
3268
3269
3270 /**
3271 * The RATE multiplier a station applies to a class at its current
3272 * population: load dependence times class dependence.
3273 *
3274 * A sampled requirement is DIVIDED by this, so a multiplier above one is a
3275 * faster station. `lldscaling` is indexed by the total population minus
3276 * one, saturating at the table's end, which is the reference's convention
3277 * and not a guard: the table is declared up to the station's capacity and a
3278 * closed model can hold exactly that many.
3279 *
3280 * A SHARING station does NOT take the load-dependent factor here. Its
3281 * `lldscaling` is read instead as the effective SERVER COUNT in
3282 * `ps_shares`, because c servers and a c-fold rate are the same thing only
3283 * when the capacity is shared -- applying both would scale it twice.
3284 */
3285 // The load-dependent speed alone, which is both a factor of the service
3286 // rate below and the scale the busy integral is measured in. Sharing one
3287 // definition is what keeps `U = T*E[S]/peak` exact on the sample path.
3288 auto lld_factor = [&](std::size_t i) -> double {
3289 StationState& s = S[i];
3290 if (s.lld.empty() || s.ps) return 1.0;
3291 double total = 0.0;
3292 for (std::size_t k = 0; k < K; ++k) total += acc.qlen[i][k];
3293 if (!(total > 0.0)) return 1.0;
3294 const std::size_t idx = std::min(static_cast<std::size_t>(total) - 1, s.lld.size() - 1);
3295 return s.lld[idx] > 0.0 ? s.lld[idx] : 1.0;
3296 };
3297 // The class-dependent speed alone. It is a factor of the RATE, so every
3298 // path that turns a population into a departure time has to apply it -- the
3299 // sharing disciplines included, which is what `ps_advance`/`ps_reschedule`
3300 // below missed: they built their shares from `ps_shares` and the breakdown
3301 // clock and never read the handle, so a PS station carrying a `cdscaling`
3302 // ran its whole sample path at the UNSCALED rates. On a closed
3303 // Delay+Queue(PS), N=3, beta(n)=min(n,2), that was Tput 0.935 against the
3304 // exact 1.412, and utilization inherited the error through T*E[S]/peak.
3305 auto cd_factor = [&](std::size_t i, std::size_t r) -> double {
3306 StationState& s = S[i];
3307 if (!s.has_cd) return 1.0;
3308 std::vector<double> nvec(K, 0.0);
3309 for (std::size_t k = 0; k < K; ++k) nvec[k] = acc.qlen[i][k];
3310 const std::vector<double> beta = s.cd(nvec);
3311 const double b = (beta.size() > 1) ? beta[r] : (beta.empty() ? 1.0 : beta[0]);
3312 return (b > 1e-10) ? b : 1.0;
3313 };
3314 /**
3315 * Read phi at the LIVE population and install it in the cache.
3316 *
3317 * It is called from the RESCHEDULE fan-out and from nowhere else, because
3318 * that is the instant the new speed takes effect: an advance has to credit
3319 * the interval that just ended at the speed which held THROUGH it, and the
3320 * cache still holds that one. Same flush-then-install order as `ps_cd` and
3321 * `Accum::set_busy_scale`.
3322 */
3323 auto gd_refresh = [&]() {
3324 std::vector<T> nvec(M * K);
3325 for (std::size_t i = 0; i < M; ++i)
3326 for (std::size_t r = 0; r < K; ++r)
3327 nvec[i * K + r] = num_traits<T>::from_double(acc.qlen[i][r]);
3328 const std::vector<T> v = sn.gdscaling(nvec);
3329 if (v.empty())
3330 throw InputError("SolverLDES (native engine): the global dependence handle returned "
3331 "no scaling");
3332 for (std::size_t i = 0; i < M; ++i)
3333 for (std::size_t r = 0; r < K; ++r) {
3334 // Scalar, one per station, or one per (station, class): the same
3335 // broadcast `set_global_dependence` validates at declaration.
3336 const double f = num_traits<T>::to_double(
3337 (v.size() == 1) ? v[0] : ((v.size() == M) ? v[i] : v[i * K + r]));
3338 if (!std::isfinite(f) || f < 0.0)
3339 throw InputError("SolverLDES (native engine): the global dependence handle "
3340 "returned a scaling that is not finite and nonnegative at "
3341 "station '" + sn.stations[i].name + "'");
3342 if (!(f > 0.0) && acc.qlen[i][r] > 0.0)
3343 throw InputError(
3344 "SolverLDES (native engine): the global dependence handle returned a "
3345 "zero scaling at station '" + sn.stations[i].name +
3346 "', which holds jobs of class '" + sn.classes[r].name +
3347 "'. A station that stops while it holds work has no completion left to "
3348 "schedule; use Queue.setBreakdown for a server that genuinely stops");
3349 gd_cache[i][r] = f;
3350 }
3351 };
3352
3353 auto rate_scaling = [&](std::size_t i, std::size_t r) -> double {
3354 StationState& s = S[i];
3355 double factor = lld_factor(i) * cd_factor(i, r);
3356 // A GLOBAL DEPENDENCE IS A FACTOR OF THE SAME RATE, read out of the
3357 // cache rather than the handle for the reason `gd_refresh` gives.
3358 if (has_gd) factor *= gd_cache[i][r];
3359 // A DOWN SERVER IS A ZERO FACTOR, not a skipped station: the job in
3360 // service keeps its residual and simply stops accruing, which is what
3361 // makes the outage an interruption rather than an eviction. A positive
3362 // `down_scale` is the degraded server of `downServiceRates`.
3363 if (s.has_breakdown && !s.up)
3364 factor *= (r < s.down_scale.size() ? s.down_scale[r] : 0.0);
3365 return factor;
3366 };
3367
3368 /**
3369 * The effective server count of a SHARING station, which is where its
3370 * load-dependence table is read. Transcribes `getEffectivePSServerCount`:
3371 * with no jobs present the count is 1, not the table's first entry, so the
3372 * very first arrival gets a whole server.
3373 */
3374 auto ps_servers = [&](std::size_t i) -> double {
3375 StationState& s = S[i];
3376 if (s.lld.empty()) return static_cast<double>(s.nservers);
3377 double total = 0.0;
3378 for (std::size_t k = 0; k < K; ++k) total += acc.qlen[i][k];
3379 if (!(total > 0.0)) return 1.0;
3380 const std::size_t idx = std::min(static_cast<std::size_t>(total) - 1, s.lld.size() - 1);
3381 return s.lld[idx];
3382 };
3383
3384 // ---- the sharing disciplines -------------------------------------------
3385 // Every population change at a PS station invalidates every departure it
3386 // has scheduled, so the pair below is always called together: integrate the
3387 // work delivered since the last change, then reschedule everything. A
3388 // stale event is not cancelled (the event list has no handle); it is
3389 // ignored on arrival by comparing its tag against the job's current one.
3390 auto ps_advance_one = [&](std::size_t i) {
3391 StationState& s = S[i];
3392 const double ps_t0 = s.ps_last_update;
3393 const double dt = now - ps_t0;
3394 s.ps_last_update = now;
3395 // THE BUSY TIME OF A SHARING STATION IS THE INTEGRAL OF THE SHARES, not
3396 // of the head count. Every job at a PS station is "in service", so
3397 // counting heads makes the busy time n*dt and reports a utilization of
3398 // n/c -- above one as soon as the station queues at all. The reference
3399 // accumulates `rate * elapsed` per job for exactly this reason, which
3400 // also makes U = T*E[S] hold automatically, since the shares sum to the
3401 // work actually delivered.
3402 for (std::size_t r = 0; r < K; ++r) acc.last_busy[i][r] = now;
3403 if (!(dt > 0.0) || s.ps_jobs.empty()) return;
3404 std::vector<double> rates = ps_shares(s.sched, s.ps_jobs, ps_servers(i), s.weight, K);
3405 if (s.has_cd)
3406 for (std::size_t j = 0; j < rates.size() && j < s.ps_jobs.size(); ++j)
3407 rates[j] *= s.ps_cd[s.ps_jobs[j].cls];
3408 if (has_gd)
3409 for (std::size_t j = 0; j < rates.size() && j < s.ps_jobs.size(); ++j)
3410 rates[j] *= gd_cache[i][s.ps_jobs[j].cls];
3411 if (s.has_breakdown && !s.up)
3412 for (std::size_t j = 0; j < rates.size() && j < s.ps_jobs.size(); ++j)
3413 rates[j] *= (s.ps_jobs[j].cls < s.down_scale.size() ? s.down_scale[s.ps_jobs[j].cls]
3414 : 0.0);
3415 for (std::size_t j = 0; j < s.ps_jobs.size(); ++j)
3416 if (rates[j] > 0.0) {
3417 acc.tot_busy[i][s.ps_jobs[j].cls] += rates[j] * dt;
3418 // The WORK delivered is in operational time (`svc_work`), the
3419 // busy share above in wall time; the two agree off an NHPP.
3420 s.ps_jobs[j].remaining = std::max(
3421 0.0, s.ps_jobs[j].remaining -
3422 rates[j] * svc_work(i, s.ps_jobs[j].cls, ps_t0, now));
3423 }
3424 };
3425 auto ps_reschedule_one = [&](std::size_t i) {
3426 StationState& s = S[i];
3427 // The new speed takes effect HERE, on the population the caller has just
3428 // written, and the departures re-timed below are what it applies to.
3429 if (s.has_cd)
3430 for (std::size_t r = 0; r < K; ++r) s.ps_cd[r] = cd_factor(i, r);
3431 if (s.ps_jobs.empty()) return;
3432 std::vector<double> rates = ps_shares(s.sched, s.ps_jobs, ps_servers(i), s.weight, K);
3433 if (s.has_cd)
3434 for (std::size_t j = 0; j < rates.size() && j < s.ps_jobs.size(); ++j)
3435 rates[j] *= s.ps_cd[s.ps_jobs[j].cls];
3436 if (has_gd)
3437 for (std::size_t j = 0; j < rates.size() && j < s.ps_jobs.size(); ++j)
3438 rates[j] *= gd_cache[i][s.ps_jobs[j].cls];
3439 if (s.has_breakdown && !s.up)
3440 for (std::size_t j = 0; j < rates.size() && j < s.ps_jobs.size(); ++j)
3441 rates[j] *= (s.ps_jobs[j].cls < s.down_scale.size() ? s.down_scale[s.ps_jobs[j].cls]
3442 : 0.0);
3443 for (std::size_t j = 0; j < s.ps_jobs.size(); ++j) {
3444 PsJob& pj = s.ps_jobs[j];
3445 // Retag the STARVED jobs too: the tag is what invalidates a departure already in the list.
3446 pj.tag = ++ps_tag;
3447 const double rate = rates[j];
3448 if (!(rate > 0.0)) continue;
3449 Event e;
3450 e.t = now + ((pj.remaining <= 1e-12) ? 1e-12 : svc_delay(i, pj.cls, pj.remaining / rate));
3451 if (!std::isfinite(e.t)) continue; // a non-cyclic rate ran out: never fires
3452 e.kind = EV_DEPARTURE;
3453 e.station = i;
3454 e.cls = pj.cls;
3455 e.tag = pj.tag;
3456 push(e);
3457 }
3458 };
3459
3460
3461 /**
3462 * Integrate the work delivered at a state-dependent station since its last
3463 * change, then re-time every completion it holds.
3464 *
3465 * `sd_advance` must run BEFORE the population is written and `sd_reschedule`
3466 * after, because the rate in force over the elapsed interval is the one the
3467 * OLD population implied. The stale departures are neutralised by the tag,
3468 * exactly as a preemption's are.
3469 */
3470 auto sd_advance_one = [&](std::size_t i) {
3471 StationState& s = S[i];
3472 if (!s.state_dependent || s.ps) return;
3473 const double sd_t0 = s.sd_last_update;
3474 const double dt = now - sd_t0;
3475 s.sd_last_update = now;
3476 if (!(dt > 0.0)) return;
3477 for (std::size_t sl = 0; sl < s.nservers; ++sl)
3478 if (s.server_busy[sl]) {
3479 const double scale = rate_scaling(i, s.server[sl].cls);
3480 const double w = svc_work(i, s.server[sl].cls, sd_t0, now) * scale;
3481 s.server[sl].remaining = std::max(0.0, s.server[sl].remaining - w);
3482 s.server[sl].elapsed += w;
3483 s.server_start[sl] = now;
3484 }
3485 };
3486 auto sd_reschedule_one = [&](std::size_t i) {
3487 StationState& s = S[i];
3488 if (!s.state_dependent || s.ps) return;
3489 // The population has just been written, so this is where the new speed
3490 // takes effect -- for the busy integral exactly as for the departures
3491 // re-timed below. `set_busy_scale` credits the interval that just ended
3492 // at the OLD speed before installing the new one.
3493 acc.set_busy_scale(i, lld_factor(i), now);
3494 for (std::size_t sl = 0; sl < s.nservers; ++sl)
3495 if (s.server_busy[sl]) {
3496 const double scale = rate_scaling(i, s.server[sl].cls);
3497 // RETAG BEFORE THE ZERO TEST, as ps_reschedule does. The tag is
3498 // the only thing that invalidates a departure already in the
3499 // list, so a slot whose rate has fallen to zero must be retagged
3500 // too -- otherwise the departure scheduled at the OLD rate stays
3501 // valid and the job leaves in the middle of the outage that was
3502 // supposed to stop it. Measured on M/M/1/8 with a failing
3503 // server: mean queue 1.486 against the exact chain's 1.922, with
3504 // throughput 1.6% HIGH, because the stalled work was delivered
3505 // anyway.
3506 s.server_tag[sl] = ++ps_tag;
3507 if (!(scale > 0.0)) continue;
3508 Event e;
3509 e.t = now + svc_delay(i, s.server[sl].cls, s.server[sl].remaining / scale);
3510 if (!std::isfinite(e.t)) continue;
3511 e.kind = EV_DEPARTURE;
3512 e.station = i;
3513 e.cls = s.server[sl].cls;
3514 e.slot = sl;
3515 e.tag = s.server_tag[sl];
3516 push(e);
3517 }
3518 };
3519
3520
3521 /**
3522 * A GLOBAL DEPENDENCE REACHES THE INFINITE SERVERS TOO.
3523 *
3524 * phi multiplies every station's rate, an INF station's included, so its
3525 * think times are integrated forward and re-timed along with everything
3526 * else. They are reached through the job registry because a Delay has no
3527 * slot to hang a residual or a generation off, which is why
3528 * `track_delay_jobs` keeps the registry for a global dependence as well.
3529 */
3530 auto gd_delay_advance = [&](std::size_t i) {
3531 StationState& s = S[i];
3532 const double gd_t0 = s.sd_last_update;
3533 const double dt = now - gd_t0;
3534 s.sd_last_update = now;
3535 if (!(dt > 0.0)) return;
3536 for (std::size_t j = 0; j < delay_live[i].size(); ++j) {
3537 Job& d = delay_live[i][j];
3538 const double scale = gd_cache[i][d.cls];
3539 const double w = svc_work(i, d.cls, gd_t0, now) * scale;
3540 d.remaining = std::max(0.0, d.remaining - w);
3541 d.elapsed += w;
3542 }
3543 };
3544 auto gd_delay_reschedule = [&](std::size_t i) {
3545 for (std::size_t j = 0; j < delay_live[i].size(); ++j) {
3546 Job& d = delay_live[i][j];
3547 // Retag before the zero test, as `sd_reschedule_one` does: the tag
3548 // is the only thing that invalidates the departure already listed.
3549 d.tag = ++ps_tag;
3550 const double scale = gd_cache[i][d.cls];
3551 if (!(scale > 0.0)) continue;
3552 Event e;
3553 e.t = now + ((d.remaining <= 1e-12) ? 1e-12 : svc_delay(i, d.cls, d.remaining / scale));
3554 if (!std::isfinite(e.t)) continue;
3555 e.kind = EV_DEPARTURE;
3556 e.station = i;
3557 e.cls = d.cls;
3558 e.slot = std::numeric_limits<std::size_t>::max();
3559 e.tag = d.tag;
3560 e.job = d;
3561 push(e);
3562 }
3563 };
3564
3565 /**
3566 * The four calls above, fanned out over the whole network when a global
3567 * dependence couples the stations.
3568 *
3569 * A job moving anywhere changes every station's rate at once, so an advance
3570 * has to book the work EVERY station delivered over the interval that just
3571 * ended, and a reschedule has to re-time every completion in flight against
3572 * the refreshed phi. Repeating either is free: an advance over a zero
3573 * interval books nothing, and a reschedule rescales residual work rather
3574 * than resampling, so it consumes no variate and lands on the instant one
3575 * call would have produced. Without a global dependence each call touches
3576 * exactly the station it names, as before.
3577 */
3578 auto gd_advance_all = [&]() {
3579 for (std::size_t a = 0; a < M; ++a) {
3580 if (S[a].role == Role::Delay)
3581 gd_delay_advance(a);
3582 else if (S[a].role != Role::Queue)
3583 continue;
3584 else if (S[a].ps)
3585 ps_advance_one(a);
3586 else
3587 sd_advance_one(a);
3588 }
3589 };
3590 auto gd_reschedule_all = [&]() {
3591 gd_refresh();
3592 for (std::size_t a = 0; a < M; ++a) {
3593 if (S[a].role == Role::Delay)
3594 gd_delay_reschedule(a);
3595 else if (S[a].role != Role::Queue)
3596 continue;
3597 else if (S[a].ps)
3598 ps_reschedule_one(a);
3599 else
3600 sd_reschedule_one(a);
3601 }
3602 };
3603 auto ps_advance = [&](std::size_t i) {
3604 if (has_gd) gd_advance_all(); else ps_advance_one(i);
3605 };
3606 auto ps_reschedule = [&](std::size_t i) {
3607 if (has_gd) gd_reschedule_all(); else ps_reschedule_one(i);
3608 };
3609 auto sd_advance = [&](std::size_t i) {
3610 if (has_gd) gd_advance_all(); else sd_advance_one(i);
3611 };
3612 auto sd_reschedule = [&](std::size_t i) {
3613 if (has_gd) gd_reschedule_all(); else sd_reschedule_one(i);
3614 };
3615
3616 /**
3617 * Whether station `j` can admit one more job of class `r` RIGHT NOW,
3618 * counting the jobs already blocked in front of it.
3619 *
3620 * THE CAPACITY TEST EXCLUDES THE BLOCKED JOBS, and reporting includes
3621 * them. `acc.qlen` carries both, because the reference's
3622 * effectiveQueueLength adds basBlockedAtDest/bbsBlockedAtDest for the
3623 * statistics, while `destinationHasCapacity` reads
3624 * getTotalCustomersAtStation -- the jobs actually AT the station. Testing
3625 * against the inclusive count DEADLOCKS a station of capacity one: the job
3626 * blocked in front of it occupies the very slot it is waiting for, so the
3627 * station can never make room and the upstream server is never released.
3628 */
3629 auto dest_has_room = [&](std::size_t j, std::size_t r) -> bool {
3630 StationState& d = S[j];
3631 if (d.role != Role::Queue) return true;
3632 double total = 0.0;
3633 for (std::size_t k = 0; k < K; ++k) total += acc.qlen[j][k] - d.blocked_at[k];
3634 return (total + 1.0 <= d.cap) &&
3635 (acc.qlen[j][r] - d.blocked_at[r] + 1.0 <= d.classcap[r]);
3636 };
3637
3638 /** The blocking policy the DESTINATION declares for an arriving class. */
3639 auto dest_policy = [&](std::size_t j, std::size_t r) -> lang::DropStrategy {
3640 return (S[j].role == Role::Queue && r < S[j].droprule.size()) ? S[j].droprule[r]
3642 };
3643
3644 // ---- finite capacity regions --------------------------------------------
3645 // At most ONE region per station, which is the reference's own restriction:
3646 // `fcRegionIndices` is a single index per station, and overlapping regions
3647 // would need a join over their constraints that no codebase implements.
3648 std::vector<Region> regions;
3649 std::vector<int> region_of(M, -1);
3650 for (const auto& rg : sn.regions) {
3651 Region R;
3652 R.name = rg.name;
3653 R.members.assign(M, false);
3654 R.class_cap.assign(K, -1.0);
3655 R.class_size.assign(K, 1.0);
3656 R.class_weight.assign(K, 1.0);
3657 R.rule.assign(K, lang::DropStrategy::DROP);
3658 R.jobs.assign(K, 0.0);
3659 R.blocked.assign(K, 0.0);
3660 R.dropped.assign(K, 0.0);
3661 R.tot_jobs.assign(K, 0.0);
3662 R.tot_weight.assign(K, 0.0);
3663 R.tot_mem.assign(K, 0.0);
3664 R.completed.assign(K, 0.0);
3665 R.resp_sum.assign(K, 0.0);
3666 R.resp_cnt.assign(K, 0.0);
3667 for (std::size_t i = 0; i < M && i < rg.members.size(); ++i)
3668 if (rg.members[i]) {
3669 R.members[i] = true;
3670 if (region_of[i] >= 0)
3671 throw UnsupportedError(ErrorKind{"Region"},
3672 "SolverLDES (native engine): station '" + sn.stations[i].name +
3673 "' belongs to more than one finite capacity region");
3674 region_of[i] = static_cast<int>(regions.size());
3675 }
3676 // `cap(i,r)` is the class-r bound at member i and `cap(i,K)` the global
3677 // one; -1 is the reference's unbounded sentinel and is kept, because it
3678 // is compared with != -1 to test MEMBERSHIP as well as boundedness.
3679 for (std::size_t i = 0; i < rg.cap.size(); ++i) {
3680 if (i >= M || !R.members[i]) continue;
3681 for (std::size_t r = 0; r < K && r < rg.cap[i].size(); ++r)
3682 if (rg.cap[i][r] >= 0.0)
3683 R.class_cap[r] = (R.class_cap[r] < 0.0) ? rg.cap[i][r]
3684 : std::min(R.class_cap[r], rg.cap[i][r]);
3685 if (rg.cap[i].size() > K && rg.cap[i][K] >= 0.0)
3686 R.global_cap = (R.global_cap < 0.0) ? rg.cap[i][K]
3687 : std::min(R.global_cap, rg.cap[i][K]);
3688 }
3689 for (double mm : rg.maxmem)
3690 if (mm >= 0.0) R.max_mem = (R.max_mem < 0.0) ? mm : std::min(R.max_mem, mm);
3691 for (std::size_t r = 0; r < K && r < rg.rule.size(); ++r) R.rule[r] = rg.rule[r];
3692 for (std::size_t r = 0; r < K && r < rg.size.size(); ++r)
3693 R.class_size[r] = num_traits<T>::to_double(rg.size[r]);
3694 for (std::size_t r = 0; r < K && r < rg.weight.size(); ++r)
3695 R.class_weight[r] = num_traits<T>::to_double(rg.weight[r]);
3696 for (std::size_t c = 0; c < rg.lincon_A.rows(); ++c) {
3697 std::vector<double> row;
3698 for (std::size_t r = 0; r < rg.lincon_A.cols(); ++r)
3699 row.push_back(num_traits<T>::to_double(rg.lincon_A(c, r)));
3700 R.lincon_A.push_back(row);
3701 R.lincon_b.push_back(c < rg.lincon_b.size() ? num_traits<T>::to_double(rg.lincon_b[c])
3702 : 0.0);
3703 }
3704 regions.push_back(R);
3705 }
3706
3707 /**
3708 * Jobs parked by a WAITQ region: they have NOT entered the region, so they
3709 * are outside every station's buffer, but they are still in the system and
3710 * are charged to the station they were trying to enter.
3711 */
3712 struct RegionWaiter {
3713 std::size_t station = 0;
3714 Job job;
3715 };
3716 std::vector<std::vector<RegionWaiter>> region_wait(regions.size());
3717
3718 /**
3719 * Whether the service requirement of (station, class) is drawn when the job
3720 * ARRIVES rather than when it reaches a server.
3721 *
3722 * Every time-invariant law is: the two instants give the same distribution,
3723 * and drawing once on arrival is what the reference engine does. A
3724 * TIME-INHOMOGENEOUS law is not, because its rate is a function of absolute
3725 * time and a job that queues is served under a later part of the schedule
3726 * than the one in force when it joined -- so it waits for `start_service`.
3727 * Three station kinds cannot wait: a Delay, where the two instants coincide
3728 * anyway; a processor-sharing station, which never calls `start_service` and
3729 * holds the requirement itself; and one whose waiting room is RANKED by the
3730 * sampled size, which must have a size to rank by. All three draw on arrival.
3731 */
3732 auto draw_at_arrival = [&](std::size_t i, std::size_t r) -> bool {
3733 const StationState& s = S[i];
3734 // A BULK SERVER has no per-job service time at all, only a station-level
3735 // firing clock, so nothing may be drawn from its process on arrival: one
3736 // draw per arrival would advance the batch sampler once per JOB instead of
3737 // once per FIRING and consume the stream the clock reads from.
3738 if (s.bmsp) return false;
3739 // Drawn at service start where the reference draws it there; see
3740 // `StationState::draw_at_start` (closed 2026-11-14).
3741 if (s.draw_at_start) return false;
3742 if (s.role != Role::Queue || s.ps || s.size_ordered) return true;
3743 // An NHPP budget is an Exp(1) in operational time, independent of the
3744 // instant it is drawn at, so it follows the ordinary rule; drawing it at
3745 // every entry into service would redraw a preempted job on resume.
3746 return !s.svc[r].time_varying() || s.svc[r].op_time();
3747 };
3748
3749 /**
3750 * Arm a BULK SERVER's firing clock and record how many jobs the firing will
3751 * complete.
3752 *
3753 * The interval comes from the station's own process, drawn at `now` because a
3754 * BMMAPt clock is a wall-clock SCHEDULE and a BMAP one simply ignores the
3755 * instant. The size is whatever block fired, read off the sampler beside the
3756 * interval and at no extra draw; a MARK the walk may also have returned is
3757 * DISCARDED, because a completion drives no class switch.
3758 *
3759 * A non-cyclic schedule past its horizon yields no interval: the clock is left
3760 * UNARMED rather than re-armed at zero delay, which would spin at one instant.
3761 * The jobs present stay present, which is what "the process has stopped" means
3762 * for a bulk server.
3763 */
3764 auto bmsp_arm = [&](std::size_t i) {
3765 StationState& s = S[i];
3766 const std::size_t r = s.bmsp_cls;
3767 const double gap = slot_snap(s.svc[r].next_at(g_svc[i][r], now), "firing interval");
3768 const int b = s.svc[r].last_batch();
3769 s.bmsp_pending = (b > 0) ? static_cast<std::size_t>(b) : 1;
3770 if (!(gap > 0.0) && s.svc[r].time_varying()) return;
3771 Event e;
3772 e.t = now + gap;
3773 e.kind = EV_DEPARTURE;
3774 e.station = i;
3775 e.cls = r;
3776 e.slot = 0;
3777 e.tag = ++ps_tag;
3778 s.bmsp_tag = e.tag;
3779 push(e);
3780 };
3781
3782 auto start_service = [&](std::size_t i, std::size_t slot, const Job& job_in) {
3783 StationState& s = S[i];
3784 Job job = job_in;
3785 // A TIME-INHOMOGENEOUS law is drawn HERE, at the instant service begins,
3786 // because its rate is a function of absolute time: a duration drawn when
3787 // the job ARRIVED would be governed by the schedule in force while the
3788 // job was still waiting, which is not the schedule that serves it. The
3789 // arrival path leaves the draw to this one (see `draw_at_arrival`), so
3790 // there is exactly one draw per service and the modulating phase a MAPt
3791 // carries is never advanced by a discarded sample.
3792 bool drew = false;
3793 // A ROUND-ROBIN job back from a quantum expiry RESUMES: it owes its
3794 // residual and is never redrawn, by a time-inhomogeneous law or a pool.
3795 const bool rr_resumed = s.rr && job.elapsed > 0.0;
3796 if (s.rr) job.order_time = -1.0;
3797 // A pool declaring its own law for the class draws below and nowhere
3798 // else, so the station-level law is not sampled as well: one service,
3799 // one variate, as `generateHeteroServiceTime` takes it.
3800 // An init_jobs residual is the work still owed and is never redrawn.
3801 const bool pool_law = s.has_pools && s.type_has_svc[s.server_type[slot]][job.cls];
3802 if (!draw_at_arrival(i, job.cls) && !rr_resumed && !pool_law && !job.preset) {
3803 job.service = sp_draw_svc(i, job.cls, s.svc[job.cls], g_svc[i][job.cls], now);
3804 job.remaining = job.service;
3805 job.elapsed = 0.0;
3806 drew = true;
3807 }
3808 // A RESUMED job owes its residual; a RESTARTED one draws afresh and
3809 // discards what it had done, which is the whole of the PR/PI split.
3810 if (!drew && s.preemptive && !s.resume && job.elapsed > 0.0) {
3811 job.service = sp_draw_svc(i, job.cls, s.svc[job.cls], g_svc[i][job.cls], now);
3812 job.remaining = job.service;
3813 job.elapsed = 0.0;
3814 }
3815 // A POOLED STATION DRAWS THE SERVICE FROM THE POOL, and it can only be
3816 // drawn here: the law depends on which server takes the job, and that
3817 // is not known until the slot is assigned. The draw made on arrival is
3818 // the station's class-level default and stands as the NOMINAL size the
3819 // size-based disciplines order the waiting room by; the duration
3820 // actually served is this one. A pool that declares no law of its own
3821 // for the class keeps that nominal draw, so it costs no extra variate.
3822 if (s.has_pools && !(s.preemptive && s.resume && job.elapsed > 0.0) && !rr_resumed &&
3823 !job.preset) {
3824 const std::size_t ty = s.server_type[slot];
3825 if (s.type_has_svc[ty][job.cls]) {
3826 job.service = slot_snap(
3827 s.type_svc[ty][job.cls].next_at(g_hsvc[i][ty][job.cls], now),
3828 "service time");
3829 job.remaining = job.service;
3830 job.elapsed = 0.0;
3831 }
3832 }
3833 s.server[slot] = job;
3834 s.server_busy[slot] = true;
3835 s.server_start[slot] = now;
3836 s.server_tag[slot] = ++ps_tag;
3837 // A JOB DECLARING SERVER PARALLELISM SEIZES ITS WHOLE SET HERE, and the
3838 // extras are recorded against the primary so that releasing that one
3839 // releases them together. `free_slot_for` has already refused a station
3840 // with fewer than n idle slots, so coming up short is an inconsistency
3841 // in this engine rather than a busy station, and is reported as one.
3842 double occupied = 1.0;
3843 if (s.has_parallelism && s.parallelism[job.cls] > 1) {
3844 const std::size_t need = s.parallelism[job.cls];
3845 std::vector<std::size_t> extras;
3846 for (std::size_t sl = 0; sl < s.nservers && extras.size() + 1 < need; ++sl) {
3847 if (sl == slot || s.server_busy[sl] || s.server_blocked[sl] || s.server_held[sl])
3848 continue;
3849 s.server_busy[sl] = true;
3850 extras.push_back(sl);
3851 }
3852 if (extras.size() + 1 < need)
3853 throw InputError("SolverLDES (native engine): station '" + sn.stations[i].name +
3854 "' started a job holding " + std::to_string(need) +
3855 " servers with only " + std::to_string(extras.size() + 1) +
3856 " free");
3857 s.held_extra[slot] = extras;
3858 occupied = static_cast<double>(need);
3859 }
3860 acc.update_busy(i, job.cls, now);
3861 // SERVERS OCCUPIED, not jobs in service: a job holding n slots for the
3862 // whole of its service contributes n/c to the utilization, not 1/c.
3863 acc.busy[i][job.cls] += occupied;
3864 // ROUND ROBIN: a FRESH QUANTUM at every entry into service, armed in
3865 // wall-clock time and before the zero-rate test below, because the
3866 // slice runs out whether or not the server is up. Departure and expiry
3867 // are both in the list; whichever comes first invalidates the other
3868 // (the departure clears `rr_qtag`, the expiry retires `server_tag`).
3869 if (s.rr) {
3870 s.rr_qtag[slot] = ++ps_tag;
3871 Event qe;
3872 qe.t = now + slot_snap(s.rr_quantum[job.cls].next(g_rr[i][job.cls]), "quantum");
3873 qe.kind = EV_QUANTUM;
3874 qe.station = i;
3875 qe.cls = job.cls;
3876 qe.slot = slot;
3877 qe.tag = s.rr_qtag[slot];
3878 push(qe);
3879 }
3880 // A ZERO RATE SCHEDULES NOTHING, it does not schedule a departure at
3881 // t = infinity. A job that enters service while the server is down
3882 // holds the slot with its residual intact and gets its departure back
3883 // from the repair's reschedule; pushing `now + remaining/0` instead
3884 // puts an infinite timestamp in the event list, which the run then
3885 // pops and processes with now = inf.
3886 const double scale0 = rate_scaling(i, job.cls);
3887 if (!(scale0 > 0.0)) return;
3888 Event e;
3889 e.t = now + svc_delay(i, job.cls, job.remaining / scale0);
3890 if (!std::isfinite(e.t)) return; // a non-cyclic rate ran out: the job holds the server
3891 e.kind = EV_DEPARTURE;
3892 e.station = i;
3893 e.cls = job.cls;
3894 e.slot = slot;
3895 e.tag = s.server_tag[slot];
3896 push(e);
3897 };
3898
3899 /**
3900 * Free the slots a job held BESIDE its primary one, and answer how many
3901 * servers it occupied in all.
3902 *
3903 * One at a station that declares no parallelism, which is every caller's
3904 * previous behaviour; calling it twice on the same slot is harmless, which
3905 * matters because a blocked slot is released once at the completion that
3906 * blocked it and again when the handoff finally goes through.
3907 */
3908 auto release_slots = [&](std::size_t i, std::size_t slot) -> double {
3909 StationState& s = S[i];
3910 if (!s.has_parallelism || slot >= s.held_extra.size()) return 1.0;
3911 std::vector<std::size_t>& extras = s.held_extra[slot];
3912 if (extras.empty()) return 1.0;
3913 for (std::size_t j = 0; j < extras.size(); ++j) s.server_busy[extras[j]] = false;
3914 const double n = static_cast<double>(extras.size() + 1);
3915 extras.clear();
3916 return n;
3917 };
3918
3919 /**
3920 * Start the next waiting job on the slot just freed, or leave the slot idle.
3921 *
3922 * SERVER PARALLELISM IS HEAD-OF-LINE: the job the station's own order takes
3923 * next needs n slots free at once, and when the station cannot offer them it
3924 * WAITS rather than serving whoever behind it would fit. Skipping ahead to a
3925 * job that fits is a different discipline, not the same one under load.
3926 */
3927 auto serve_next_on_slot = [&](std::size_t i, std::size_t sl) {
3928 if (!buffer_has_for_slot(i, sl)) return;
3929 Job nextjob = buffer_pop_for_slot(i, sl);
3930 if (S[i].has_parallelism && free_slot_count(i) < S[i].parallelism[nextjob.cls]) {
3931 buffer_push(i, nextjob);
3932 return;
3933 }
3934 start_service(i, sl, nextjob);
3935 };
3936
3937 // ---- setup / delay-off, per server (see StationState::has_setup) ----------
3938
3939 /** OFF -> SETUP under class `cls`'s law (`Solver_ssj.startServerSetup`). */
3940 auto power_setup = [&](std::size_t i, std::size_t sl, std::size_t cls) {
3941 StationState& s = S[i];
3942 s.power[sl] = PW_SETUP;
3943 Event e;
3944 // A class with no setup law of its own powers the server up in no time,
3945 // which is the reference's zero from `generateSetupTime`.
3946 e.t = now + (s.has_setup_law[cls] ? s.setup_law[cls].next(g_setup[i][cls]) : 0.0);
3947 e.kind = EV_SETUP;
3948 e.station = i;
3949 e.cls = cls;
3950 e.slot = sl;
3951 e.tag = ++s.power_tag[sl];
3952 push(e);
3953 };
3954 /** DELAYOFF -> ACTIVE: the pending power-down is dropped (`cancelDelayoff`). */
3955 auto power_cancel = [&](std::size_t i, std::size_t sl) {
3956 StationState& s = S[i];
3957 ++s.power_tag[sl];
3958 s.power[sl] = PW_ACTIVE;
3959 };
3960 /**
3961 * A server freed by class `cls` with nobody waiting: DELAYOFF under that
3962 * class's law (`startServerDelayoff`), or OFF at once under a zero one.
3963 */
3964 auto power_down = [&](std::size_t i, std::size_t sl, std::size_t cls) {
3965 StationState& s = S[i];
3966 if (!s.powers_down_after(cls)) return;
3967 ++s.power_tag[sl];
3968 if (!s.has_doff_law[cls]) {
3969 s.power[sl] = PW_OFF;
3970 return;
3971 }
3972 s.power[sl] = PW_DELAYOFF;
3973 Event e;
3974 e.t = now + s.doff_law[cls].next(g_doff[i][cls]);
3975 e.kind = EV_SETUP;
3976 e.station = i;
3977 e.cls = cls;
3978 e.slot = sl;
3979 e.tag = s.power_tag[sl];
3980 push(e);
3981 };
3982 /**
3983 * The server an arriving job of class `cls` claims at a setup station, or
3984 * `s.nservers` for none (`findFreeServerImpl` / `findFreeServerOfType`):
3985 * the first ACTIVE idle server, else the first DELAYOFF one, else the first
3986 * OFF one, inside the pool the station's policy picks over the pools that
3987 * hold any non-busy server.
3988 */
3989 auto setup_pick = [&](std::size_t i, std::size_t cls) -> std::size_t {
3990 StationState& s = S[i];
3991 std::size_t lo = 0, hi = s.nservers;
3992 if (s.has_pools) {
3993 power_blind = true;
3994 const std::size_t any = free_slot_for(i, cls);
3995 power_blind = false;
3996 if (any >= s.nservers) return s.nservers;
3997 const std::size_t t = s.server_type[any];
3998 lo = s.type_first[t];
3999 hi = lo + s.type_count[t];
4000 }
4001 for (std::size_t sl = lo; sl < hi; ++sl)
4002 if (slot_ok_for(s, sl, cls)) return sl;
4003 for (std::size_t sl = lo; sl < hi; ++sl)
4004 if (s.power[sl] == PW_DELAYOFF) return sl;
4005 for (std::size_t sl = lo; sl < hi; ++sl)
4006 if (s.power[sl] == PW_OFF) return sl;
4007 return s.nservers;
4008 };
4009
4010 /**
4011 * Interrupt the job in `slot` and return it to the waiting room.
4012 *
4013 * Its residual work and attained service are carried on the job, so a
4014 * resume needs no side table; the tag is left stale, which is how the
4015 * departure event already in the list is neutralised.
4016 */
4017 auto preempt = [&](std::size_t i, std::size_t slot) {
4018 StationState& s = S[i];
4019 Job job = s.server[slot];
4020 const double served = svc_work(i, job.cls, s.server_start[slot], now);
4021 job.remaining = std::max(0.0, job.remaining - served);
4022 job.elapsed += served;
4023 s.server_busy[slot] = false;
4024 s.server_tag[slot] = 0;
4025 const double freed = release_slots(i, slot);
4026 acc.update_busy(i, job.cls, now);
4027 acc.busy[i][job.cls] -= freed;
4028 // The job stays in the system: its queue length is unchanged, and it
4029 // re-enters the waiting room under the station's own order.
4030 buffer_push(i, job);
4031 };
4032
4033 /**
4034 * Advance a polling server one leg, or park it.
4035 *
4036 * `poll_serve` starts the next job at the buffer the server stands at;
4037 * `poll_advance` walks it to the next buffer, paying that leg's switchover.
4038 * The walk stops after a full lap of zero-time legs that found no work, or
4039 * the server would spin forever at the same simulated instant.
4040 */
4041 std::function<void(std::size_t)> poll_serve;
4042 std::function<void(std::size_t)> poll_advance;
4043 /** Next move of an extended polling server (`poll_ext`); see below. */
4044 std::function<void(std::size_t, bool)> poll_ext_advance;
4045
4046 /**
4047 * The slot holding the polling server's one job, or `s.nservers` when it
4048 * holds none. A polling server serves ONE job at a time (Java
4049 * `customersInService == 0` gates every start), but at a station with
4050 * HETEROGENEOUS SERVER POOLS that job sits on the slot of the pool the
4051 * station's policy picked (`pollingStartService` ->
4052 * `findFreeServerForClass`), not necessarily on slot 0.
4053 */
4054 auto poll_slot = [&](const StationState& s) -> std::size_t {
4055 for (std::size_t sl = 0; sl < s.nservers; ++sl)
4056 if (s.server_busy[sl] || s.server_blocked[sl] || s.server_held[sl]) return sl;
4057 return s.nservers;
4058 };
4059
4060 /**
4061 * Open a visit at the buffer the server has just polled.
4062 *
4063 * The budget is fixed AT THE POLLING INSTANT: EXHAUSTIVE serves until the
4064 * buffer empties, K-LIMITED at most K, GATED exactly the jobs found there
4065 * (later arrivals wait for the next visit), G-LIMITED at most K of the jobs
4066 * found there, and DECREMENTING until the
4067 * buffer is one shorter than it was found. GATED and DECREMENTING are NOT
4068 * one-job visits; serving one job per visit is 1-limited, a different and
4069 * slower discipline.
4070 */
4071 auto poll_open_visit = [&](StationState& s) {
4072 std::size_t found = 0;
4073 for (const Job& j : s.buffer)
4074 if (j.cls == s.poll_at) ++found;
4075 switch (s.poll_type) {
4076 case lang::PollingType::KLIMITED: s.poll_budget = s.poll_k; break;
4077 case lang::PollingType::GATED: s.poll_budget = found; break;
4078 case lang::PollingType::GLIMITED: s.poll_budget = std::min(s.poll_k, found); break;
4080 s.poll_budget = std::numeric_limits<std::size_t>::max();
4081 s.poll_gate = found;
4082 break;
4084 default: s.poll_budget = std::numeric_limits<std::size_t>::max(); break;
4085 }
4086 };
4087
4088 poll_serve = [&](std::size_t i) {
4089 StationState& s = S[i];
4090 if (poll_slot(s) < s.nservers) return;
4091 // Only the class the server currently stands at may be served.
4092 std::size_t at = s.buffer.size();
4093 std::size_t waiting = 0;
4094 for (std::size_t j = 0; j < s.buffer.size(); ++j)
4095 if (s.buffer[j].cls == s.poll_at) {
4096 ++waiting;
4097 if (at == s.buffer.size() || s.buffer[j].t_arr < s.buffer[at].t_arr) at = j;
4098 }
4099 // DECREMENTING ends the visit once the buffer has fallen to one below
4100 // the count found at the polling instant.
4101 const bool decremented =
4102 s.poll_type == lang::PollingType::DECREMENTING && waiting < s.poll_gate;
4103 // A non-preemptive visit timer that expired during the last service
4104 // ends the visit at that completion, whatever the discipline.
4105 const bool timed_out = s.poll_ext && s.poll_expired;
4106 if (at == s.buffer.size() || s.poll_budget == 0 || decremented || timed_out) {
4107 poll_advance(i);
4108 return;
4109 }
4110 Job job = s.buffer[at];
4111 jpq_remove_at(s.buffer, at, s.cmp);
4112 if (s.poll_type == lang::PollingType::GATED || s.poll_type == lang::PollingType::KLIMITED
4113 || s.poll_type == lang::PollingType::GLIMITED)
4114 --s.poll_budget;
4115 // A pooled station hands the job to the pool its policy picks and serves
4116 // it at that pool's law, as the reference's `pollingStartService` does;
4117 // `ldes_engine_reject` has refused a class no pool accepts.
4118 std::size_t slot = 0;
4119 if (s.has_pools) {
4120 slot = free_slot_for(i, job.cls);
4121 if (slot >= s.nservers)
4122 throw InputError("SolverLDES (native engine): polling station '" + sn.stations[i].name +
4123 "' found no free pool for class '" + sn.classes[job.cls].name +
4124 "' with its server idle");
4125 }
4126 start_service(i, slot, job);
4127 };
4128
4129 poll_advance = [&](std::size_t i) {
4130 StationState& s = S[i];
4131 if (s.poll_ext) {
4132 // end of a visit under a table, an LD order or a visit timer
4133 s.poll_timer_tag = 0;
4134 s.poll_expired = false;
4135 poll_ext_advance(i, false);
4136 return;
4137 }
4138 for (std::size_t step = 0; step < K; ++step) {
4139 const std::size_t from = s.poll_at;
4140 const std::size_t next = (from + 1) % K;
4141 // Takagi's r_i: the leg OUT of `from` is charged the switchover
4142 // stored against `from`, not against the buffer being entered.
4143 if (s.has_switchover[from]) {
4144 s.poll_switching = true;
4145 Event e;
4146 e.t = now + s.switchover[from].next(g_aux[i]);
4147 e.kind = EV_SWITCHOVER;
4148 e.station = i;
4149 e.cls = next;
4150 push(e);
4151 return;
4152 }
4153 s.poll_at = next;
4154 poll_open_visit(s);
4155 bool has_work = false;
4156 for (const Job& j : s.buffer)
4157 if (j.cls == next) {
4158 has_work = true;
4159 break;
4160 }
4161 if (has_work) {
4162 poll_serve(i);
4163 return;
4164 }
4165 }
4166 // A whole lap of zero-time legs found nothing. Parking is the only
4167 // alternative to spinning at this instant, and it is unobservable: the
4168 // next arrival restarts the server.
4169 s.poll_parked = true;
4170 };
4171
4172 // ---- polling extensions: tables, load-dependent orders, visit timers ----
4173
4174 auto poll_has_work = [&](const StationState& s, std::size_t r) -> bool {
4175 for (const Job& j : s.buffer)
4176 if (j.cls == r) return true;
4177 return false;
4178 };
4179 auto poll_count = [&](const StationState& s, std::size_t r) -> long {
4180 long n = 0;
4181 for (const Job& j : s.buffer)
4182 if (j.cls == r) ++n;
4183 return n;
4184 };
4185 /** A draw of class c's visit timer law (0 for an Immediate law). */
4186 auto poll_sample_timer = [&](std::size_t i, std::size_t c) -> double {
4187 StationState& s = S[i];
4188 if (!s.poll_has_tlaw[c]) return 0.0;
4189 return std::max(0.0, s.poll_tlaw[c].next(g_aux[i]));
4190 };
4191 auto poll_park_at = [&](StationState& s, std::size_t pos) {
4192 s.poll_pos = pos;
4193 s.poll_at = s.poll_ring[pos];
4194 s.poll_parked = true;
4195 };
4196
4197 /**
4198 * Open a visit at position p, whose buffer holds work. The visit timer is
4199 * `holding` under GLOBAL, a fresh draw of the class law under LOCAL, and
4200 * absent otherwise. The first service of a visit always starts: a zero
4201 * holding time lets the visit serve exactly one job.
4202 */
4203 auto poll_start_visit = [&](std::size_t i, std::size_t p, double holding) {
4204 StationState& s = S[i];
4205 const std::size_t r = s.poll_ring[p];
4206 s.poll_pos = p;
4207 s.poll_at = r;
4208 s.poll_parked = false;
4209 s.poll_timer_tag = 0;
4210 s.poll_expired = false;
4211 poll_open_visit(s);
4212 bool zero_hold = false;
4213 if (s.poll_timer != lang::PollingTimer::NONE) {
4214 if (s.poll_timer == lang::PollingTimer::LOCAL) holding = poll_sample_timer(i, r);
4215 if (holding > 0.0) {
4216 s.poll_timer_tag = ++ps_tag;
4217 Event e;
4218 e.t = now + holding;
4219 e.kind = EV_POLL_TIMER;
4220 e.station = i;
4221 e.cls = r;
4222 e.tag = s.poll_timer_tag;
4223 push(e);
4224 } else {
4225 zero_hold = true;
4226 }
4227 }
4228 poll_serve(i);
4229 if (zero_hold) s.poll_expired = true;
4230 };
4231
4232 /**
4233 * The server (or token) reaches position p: opens a visit there, answering
4234 * true, or passes. Under GLOBAL the token rotation timer of the class
4235 * restarts at every arrival, and the visit holds the server only for what
4236 * was left of the previous rotation (timed token).
4237 */
4238 auto poll_arrive_at = [&](std::size_t i, std::size_t p) -> bool {
4239 StationState& s = S[i];
4240 const std::size_t r = s.poll_ring[p];
4241 const bool non_empty = poll_has_work(s, r);
4242 if (s.poll_timer == lang::PollingTimer::GLOBAL) {
4243 if (!s.poll_trt_ready) {
4244 // every rotation timer runs from t = 0
4245 for (std::size_t c = 0; c < K; ++c)
4246 if (s.poll_polled[c]) s.poll_trt[c] = poll_sample_timer(i, c);
4247 s.poll_trt_ready = true;
4248 }
4249 const double remaining = s.poll_trt[r] - now;
4250 s.poll_trt[r] = now + poll_sample_timer(i, r);
4251 if (remaining > 0.0 && non_empty) {
4252 poll_start_visit(i, p, remaining);
4253 return true;
4254 }
4255 return false;
4256 }
4257 if (non_empty) {
4258 poll_start_visit(i, p, -1.0);
4259 return true;
4260 }
4261 return false;
4262 };
4263
4264 /**
4265 * Load-dependent choice at the end of a visit at buffer i
4266 * (`State.pollingChoose`): the buffer to visit next, or K to park at i.
4267 */
4268 auto poll_ld_choose = [&](const StationState& s, std::size_t i0) -> std::size_t {
4269 if (s.poll_order == lang::PollingOrder::THRESHOLD &&
4270 poll_count(s, s.poll_thr_class) > s.poll_thr_l)
4271 return s.poll_thr_class;
4272 if (s.poll_order == lang::PollingOrder::LQF) {
4273 long best = 0;
4274 std::size_t j = K, p = i0;
4275 for (std::size_t step = 0; step < K; ++step) {
4276 p = (p + 1) % K;
4277 if (!s.poll_polled[p]) continue;
4278 const long n = poll_count(s, p);
4279 if (n > best) {
4280 best = n;
4281 j = p;
4282 }
4283 }
4284 return j;
4285 }
4286 // SKIPEMPTY, and THRESHOLD below the threshold
4287 std::size_t p = i0;
4288 for (std::size_t step = 0; step < K; ++step) {
4289 p = (p + 1) % K;
4290 if (s.poll_polled[p] && poll_has_work(s, p)) return p;
4291 }
4292 return K;
4293 };
4294
4295 auto poll_schedule_leg = [&](std::size_t i, std::size_t dest, double t) {
4296 StationState& s = S[i];
4297 s.poll_switching = true;
4298 s.poll_parked = false;
4299 Event e;
4300 e.t = now + t;
4301 e.kind = EV_SWITCHOVER;
4302 e.station = i;
4303 e.cls = dest; // the POSITION the server reaches
4304 push(e);
4305 };
4306
4307 /**
4308 * Next move of an extended polling server (`State.pollingAdvance`). With
4309 * `arrived` the server stands at its current position (it has just
4310 * completed a leg into it, or it is parked there and a job arrived);
4311 * otherwise it has just ended a visit there.
4312 */
4313 poll_ext_advance = [&](std::size_t i, bool arrived) {
4314 StationState& s = S[i];
4315 if (s.poll_order != lang::PollingOrder::CYCLIC) {
4316 const std::size_t i0 = s.poll_pos;
4317 if (arrived && poll_has_work(s, i0)) {
4318 poll_start_visit(i, i0, -1.0);
4319 return;
4320 }
4321 const std::size_t j = poll_ld_choose(s, i0);
4322 if (j >= K) {
4323 poll_park_at(s, i0); // wait at the buffer just left
4324 return;
4325 }
4326 // j == i0 is a new visit with no switchover; otherwise pay i0's leg
4327 const double t = (j == i0 || !s.poll_has_leg[i0]) ? 0.0 : s.poll_leg[i0].next(g_aux[i]);
4328 if (t > 0.0) {
4329 s.poll_at = i0;
4330 poll_schedule_leg(i, j, t);
4331 } else {
4332 poll_start_visit(i, j, -1.0);
4333 }
4334 return;
4335 }
4336 // Fixed order (table or cyclic ring): walk the positions
4337 const std::size_t m = s.poll_ring.size();
4338 const std::size_t start = s.poll_pos;
4339 std::size_t p = start;
4340 if (arrived && poll_arrive_at(i, p)) return;
4341 for (std::size_t step = 0; step < m; ++step) {
4342 const std::size_t p2 = (p + 1) % m;
4343 const double t = s.poll_has_leg[p] ? s.poll_leg[p].next(g_aux[i]) : 0.0;
4344 if (t > 0.0) {
4345 s.poll_pos = p;
4346 s.poll_at = s.poll_ring[p];
4347 poll_schedule_leg(i, p2, t);
4348 return;
4349 }
4350 p = p2;
4351 if (poll_arrive_at(i, p)) return;
4352 }
4353 // a full lap of zero-time legs found no work: park where the walk began
4354 poll_park_at(s, start);
4355 };
4356
4357 /**
4358 * Expiry of a visit timer. Non-preemptive: the job in service completes
4359 * and the visit ends with it. Preemptive: the job returns to the head of
4360 * its buffer (its arrival stamp is unchanged, so the visit order serves it
4361 * first), to restart with a fresh service draw at a later visit, and the
4362 * server leaves at once.
4363 */
4364 auto poll_timer_expired = [&](std::size_t i, std::uint64_t tag) {
4365 StationState& s = S[i];
4366 if (!s.poll_ext || s.poll_timer_tag != tag || tag == 0) return; // a cancelled timer
4367 s.poll_timer_tag = 0;
4368 const std::size_t ps0 = poll_slot(s);
4369 if (!s.poll_preempt || ps0 >= s.nservers || !s.server_busy[ps0] || s.server_blocked[ps0]) {
4370 s.poll_expired = true;
4371 return;
4372 }
4373 Job job = s.server[ps0];
4374 acc.update_busy(i, job.cls, now);
4375 acc.busy[i][job.cls] -= 1.0;
4376 // freeing the slot and clearing its tag neutralises the departure
4377 // already in the event list
4378 s.server_busy[ps0] = false;
4379 s.server_tag[ps0] = 0;
4380 if (draw_at_arrival(i, job.cls)) {
4381 job.service = sp_draw_svc(i, job.cls, s.svc[job.cls], g_svc[i][job.cls], now);
4382 job.remaining = job.service;
4383 }
4384 job.elapsed = 0.0;
4385 buffer_push(i, job);
4386 s.poll_expired = false;
4387 poll_ext_advance(i, false);
4388 };
4389
4390 // ---- admission ---------------------------------------------------------
4391
4392 /**
4393 * Reschedule the aggregate completion of a pass-and-swap station.
4394 *
4395 * ONE CLOCK FOR THE WHOLE STATION, at the total rate mu(c) of its ordered
4396 * list, and the position that completes is drawn from the per-position
4397 * INCREMENTS. Scheduling one clock per job instead would need each job's
4398 * marginal rate to be constant, which is exactly what an order-independent
4399 * station does not have: every arrival and departure changes every other
4400 * job's rate.
4401 */
4402 std::function<void(std::size_t)> pas_reschedule = [&](std::size_t i) {
4403 StationState& s = S[i];
4404 if (s.pas_list.empty()) return;
4405 std::vector<std::size_t> seq;
4406 for (const Job& j : s.pas_list) seq.push_back(j.cls);
4407 const double total = s.pas_rate(seq);
4408 if (!(total > 0.0)) return;
4409 s.pas_tag = ++ps_tag;
4410 Event e;
4411 e.t = now + (-std::log(uniform01(g_aux[i])) / total);
4412 e.kind = EV_DEPARTURE;
4413 e.station = i;
4414 e.cls = 0;
4415 e.tag = s.pas_tag;
4416 e.slot = std::numeric_limits<std::size_t>::max();
4417 push(e);
4418 };
4419
4420 /**
4421 * The position that completes, drawn from the per-position rate increments,
4422 * and the job that actually departs after the swap chain.
4423 */
4424 auto pas_complete = [&](std::size_t i) -> Job {
4425 StationState& s = S[i];
4426 std::vector<std::size_t> seq;
4427 for (const Job& j : s.pas_list) seq.push_back(j.cls);
4428 std::vector<double> inc(seq.size(), 0.0);
4429 double prev = 0.0, total = 0.0;
4430 for (std::size_t p = 0; p < seq.size(); ++p) {
4431 std::vector<std::size_t> pre(seq.begin(),
4432 seq.begin() + static_cast<std::ptrdiff_t>(p + 1));
4433 const double cur = s.pas_rate(pre);
4434 inc[p] = std::max(0.0, cur - prev);
4435 prev = cur;
4436 total += inc[p];
4437 }
4438 std::size_t pos = 0;
4439 if (total > 0.0) {
4440 const double u = uniform01(g_routing) * total;
4441 double acc2 = 0.0;
4442 for (std::size_t p = 0; p < inc.size(); ++p) {
4443 acc2 += inc[p];
4444 if (u < acc2) {
4445 pos = p;
4446 break;
4447 }
4448 }
4449 }
4450 // The swap chain: from `pos`, walk forward to the last position the swap
4451 // graph can reach. That job departs and the chain shifts back into the
4452 // hole at `pos`. An empty graph makes the chain trivial, which is the
4453 // plain order-independent station.
4454 std::vector<std::size_t> chain(1, pos);
4455 std::size_t moving = seq[pos], cur = pos;
4456 while (true) {
4457 std::size_t nxt = seq.size();
4458 for (std::size_t j = cur + 1; j < seq.size(); ++j) {
4459 const bool swappable =
4460 s.pas_swap.empty() ||
4461 (moving < s.pas_swap.size() && seq[j] < s.pas_swap[moving].size() &&
4462 s.pas_swap[moving][seq[j]]);
4463 if (swappable) {
4464 nxt = j;
4465 break;
4466 }
4467 }
4468 if (nxt >= seq.size()) break;
4469 chain.push_back(nxt);
4470 moving = seq[nxt];
4471 cur = nxt;
4472 }
4473 Job departing = s.pas_list[chain.back()];
4474 std::vector<Job> arr = s.pas_list;
4475 for (std::size_t k = 0; k + 1 < chain.size(); ++k)
4476 arr[chain[k + 1]] = s.pas_list[chain[k]];
4477 std::vector<Job> survivors;
4478 for (std::size_t k = 0; k < arr.size(); ++k)
4479 if (k != chain.front()) survivors.push_back(arr[k]);
4480 s.pas_list = survivors;
4481 return departing;
4482 };
4483 /**
4484 * Admit a job at station `i`, or drop it when the station is full.
4485 *
4486 * `from` is the station the job comes from, or M for an arrival that enters
4487 * from outside the network. IT IS NOT BOOKKEEPING: a hop BETWEEN TWO
4488 * MEMBERS of the same finite capacity region does not cross the region
4489 * boundary, so the job must neither be re-tested against the region's caps
4490 * nor counted into it again. Without that test an intra-region hop adds one
4491 * to the region on arrival and removes nothing on departure, so occupancy
4492 * grows by one per hop until every arrival is refused and the run never
4493 * completes another job.
4494 */
4495 // The main departure site leaves the region BEFORE routing and sets `hop_old_cls` to the departing class. A hop
4496 // into the same region is then re-gated like an arrival; one that also SWITCHES class crosses the border, as in
4497 // JMT and the Java engine (the ClassSwitch node sits outside the region), so it first completes and releases the
4498 // waiters, and a freed per-class or linear slot is never left idle.
4499 std::size_t hop_old_cls = K;
4500 std::function<void(std::size_t)> release_region; ///< defined below, called by admit on a class-switching hop
4501 /// Region wait of the waiter release_region is re-admitting; admit takes it onto the job and clears it.
4502 double pending_region_wait = 0.0;
4503 // Set by the region release only: the parked job keeps the SIRO key it was given when it first tried
4504 // to enter, as `tryReleaseBlockedCustomers` re-admits the very Customer it parked.
4505 bool pending_keep_rank = false;
4506 bool hop_internal = false; ///< set by admit when the hop stayed inside a region, read by the departure site
4507 /// Set by the retrial site for the next admit only: a job re-offering itself from the orbit decided to join
4508 /// already, so it is not asked to balk again (Java `arriveAtQueueFromRetrial` skips the test likewise).
4509 bool pending_retry = false;
4510 /// Set by the retrial site when an orbiting job takes a free server: it is already counted in the station
4511 /// population and keeps its first arrival time, so admit must neither count it again nor re-test its admission.
4512 bool pending_orbit_exit = false;
4513 /// Set by the init_jobs injection for the next admit only: the job is already present, so it keeps the arrival
4514 /// instants it was given and is not asked to balk.
4515 bool pending_preset = false;
4516
4517 // ---- the retrial orbit (see StationState::retrial) ------------------------------------------------------
4518 auto retrial_server_free = [&](std::size_t i, std::size_t cls) -> bool {
4519 StationState& s = S[i];
4520 if (s.ps) return s.ps_jobs.size() < s.nservers;
4521 return free_slot_for(i, cls) < s.nservers;
4522 };
4523 auto orbit_tick = [&](std::size_t i) {
4524 StationState& s = S[i];
4525 const double dt = now - s.orbit_last;
4526 if (dt > 0.0)
4527 for (std::size_t r = 0; r < K; ++r) s.tot_orbit[r] += s.orbit_size[r] * dt;
4528 s.orbit_last = now;
4529 };
4530 // LINEAR: every orbiting job carries its own clock, tagged with its id. CONSTANT: one clock serves the whole
4531 // (station, class) orbit, tagged 0, and is given to the oldest member when it fires.
4532 auto arm_retrial = [&](std::size_t i, std::size_t c, std::uint64_t id) {
4533 StationState& s = S[i];
4534 if (s.retrial_policy[c] == 2) {
4535 if (s.const_pending[c] || s.orbit[c].empty()) return;
4536 s.const_pending[c] = true;
4537 id = 0;
4538 }
4539 Event e;
4540 e.t = now + s.retrial[c].next(g_retr[i][c]);
4541 e.kind = EV_RETRIAL;
4542 e.station = i;
4543 e.cls = c;
4544 e.tag = id;
4545 push(e);
4546 };
4547 auto orbit_join = [&](std::size_t i, Job job) {
4548 StationState& s = S[i];
4549 const std::size_t c = job.cls;
4550 orbit_tick(i);
4551 s.orbit_size[c] += 1.0;
4552 job.t_arr = now;
4553 job.id = ++job_id;
4554 job.attempts = 0;
4555 job.deadline = now + classdeadline[c];
4556 sd_advance(i);
4557 acc.update_qlen(i, c, now);
4558 acc.qlen[i][c] += 1.0;
4559 acc.arrived[i][c] += 1.0;
4560 bp.track(i, c, +1, now);
4561 s.orbit[c].push_back(job);
4562 if (s.has_orbit_abandon[c]) {
4563 Event e;
4564 e.t = now + s.orbit_abandon[c].next(g_svc[i][c]);
4565 e.kind = EV_ORBIT_ABANDON;
4566 e.station = i;
4567 e.cls = c;
4568 e.tag = job.id;
4569 push(e);
4570 }
4571 arm_retrial(i, c, job.id);
4572 sd_reschedule(i);
4573 };
4574 // Takes the orbit job at position `at` out of the orbit; `leaves` also takes it out of the station.
4575 auto orbit_leave = [&](std::size_t i, std::size_t c, std::size_t at, bool leaves) {
4576 StationState& s = S[i];
4577 orbit_tick(i);
4578 s.orbit_size[c] -= 1.0;
4579 s.orbit[c].erase(s.orbit[c].begin() + static_cast<std::ptrdiff_t>(at));
4580 if (leaves) {
4581 sd_advance(i);
4582 acc.update_qlen(i, c, now);
4583 acc.qlen[i][c] -= 1.0;
4584 bp.track(i, c, -1, now);
4585 sd_reschedule(i);
4586 }
4587 };
4588
4589 std::function<bool(std::size_t, Job, std::size_t)> admit =
4590 [&](std::size_t i, Job job, std::size_t from) -> bool {
4591 StationState& s = S[i];
4592 const double rwait = pending_region_wait;
4593 pending_region_wait = 0.0;
4594 const bool is_retry = pending_retry;
4595 pending_retry = false;
4596 const bool from_orbit = pending_orbit_exit;
4597 pending_orbit_exit = false;
4598 const bool preset = pending_preset;
4599 pending_preset = false;
4600 const bool keep_rank = pending_keep_rank;
4601 pending_keep_rank = false;
4602 // THE SIRO KEY IS DRAWN HERE, BEFORE ANY TEST THAT CAN REFUSE THE JOB. The reference draws it in the
4603 // Customer constructor, which runs before `arriveAtQueue` decides anything, so a job dropped by a full
4604 // buffer, refused or parked by a region, balked or sent to the orbit has already consumed one. Drawing it
4605 // only on admission (as before 2026-11-14) left the siroRng band one draw behind per refusal.
4606 if (!keep_rank) job.rank = g_siro.aux.next_double();
4607 if (s.off[job.cls])
4608 throw InputError("SolverLDES (native engine): a job of class '" +
4609 sn.classes[job.cls].name + "' reached station '" +
4610 sn.stations[i].name + "', which does not serve it");
4611 // THE REGION IS CONSULTED FIRST. Its cap spans stations, so a job may
4612 // be refused entry to a station that has room of its own; testing the
4613 // station first and the region second would admit into the buffer and
4614 // then have to unwind it. The test is on MEMBERSHIP ALONE, exactly as
4615 // on the departure side: a Delay is capped by the region like any other
4616 // member, and gating entry on Role::Queue while the exit is ungated
4617 // drains the occupancy below zero, after which nothing is ever refused.
4618 int rgi = region_of[i];
4619 if (rgi >= 0 && from < M && region_of[from] == rgi) {
4620 const std::size_t oc = hop_old_cls;
4621 hop_old_cls = K;
4622 if (oc < K) {
4623 // The main departure site has already left the region: the job is gated like an arrival, and a
4624 // class-switching hop first completes and releases the waiters, the ClassSwitch being outside
4625 hop_internal = true;
4626 if (oc != job.cls) {
4627 const std::size_t rg = static_cast<std::size_t>(rgi);
4628 regions[rg].completed[oc] += 1.0;
4629 release_region(rg);
4630 }
4631 } else {
4632 rgi = -1; // any other departure site keeps the job counted inside: it stays inside
4633 }
4634 }
4635 if (rgi >= 0) {
4636 Region& R = regions[static_cast<std::size_t>(rgi)];
4637 if (R.would_exceed(job.cls)) {
4638 R.update(now);
4639 if (R.drops(job.cls)) {
4640 R.dropped[job.cls] += 1.0;
4641 dropped[i][job.cls] += 1.0;
4642 return false;
4643 }
4644 // WAITQ: parked outside the region, still in the system.
4645 RegionWaiter w;
4646 w.station = i;
4647 w.job = job;
4648 w.job.t_arr = now;
4649 w.job.id = ++job_id;
4650 region_wait[static_cast<std::size_t>(rgi)].push_back(w);
4651 R.blocked[job.cls] += 1.0;
4652 return true;
4653 }
4654 }
4655
4656 // Kendall's K counts the jobs HELD by the station, waiting and in
4657 // service alike; a per-class buffer caps its own class on top of that.
4658 // At a retrial station the orbit is held too (see StationState::retrial),
4659 // so a full station there is a full orbit and the job is lost.
4660 if (s.role == Role::Queue && !from_orbit) {
4661 double total = 0.0;
4662 for (std::size_t r = 0; r < K; ++r) total += acc.qlen[i][r] - s.blocked_at[r];
4663 if (total + 1.0 > s.cap ||
4664 acc.qlen[i][job.cls] - s.blocked_at[job.cls] + 1.0 > s.classcap[job.cls]) {
4665 if (s.has_retrial[job.cls]) s.retrial_lost[job.cls] += 1.0;
4666 dropped[i][job.cls] += 1.0;
4667 if (sp_on) spt.drop(i, job.cls);
4668 // A job lost to a full STATION buffer did arrive there: CTMC and JMT report the
4669 // offered rate as ArvR (M/M/1/2 at lambda 0.8: ArvR 0.8, Tput 0.59), as does the JAR
4670 // engine. A REGION drop above is not counted: the job never reaches the member.
4671 acc.arrived[i][job.cls] += 1.0;
4672 return false;
4673 }
4674 // A RETRIAL STATION HAS NO WAITING ROOM: a job of a retrial class
4675 // that finds every server busy joins the orbit at once.
4676 if (s.has_retrial[job.cls] && !retrial_server_free(i, job.cls)) {
4677 orbit_join(i, job);
4678 return true;
4679 }
4680 }
4681 // BALKING is a refusal to JOIN, decided on what the arrival sees.
4682 // It is not a drop for want of room: the station may have plenty,
4683 // and the job declines anyway. Counted separately for that reason.
4684 // The FIRST range holding the pre-arrival population decides, as in
4685 // MATLAB afterEventStation and Java Solver_ssj.shouldBalk, and a match
4686 // costs one routing draw even at probability 0, because Java's
4687 // `routingRng.nextDouble() < p` does. A Delay balks too: both
4688 // references apply the rule at any station that declares it.
4689 if (!is_retry && !preset && !s.balk[job.cls].empty()) {
4690 double total = 0.0;
4691 for (std::size_t r = 0; r < K; ++r)
4692 total += acc.qlen[i][r] - (s.blocked_at.empty() ? 0.0 : s.blocked_at[r]);
4693 for (const StationState::BalkRule& br : s.balk[job.cls])
4694 if (total >= br.min_jobs && (br.max_jobs < 0.0 || total <= br.max_jobs)) {
4695 if (uniform01(g_routing) < br.probability) {
4696 balked[i][job.cls] += 1.0;
4697 acc.arrived[i][job.cls] += 1.0; // offered, as CTMC and the JAR engine count it
4698 if (sp_on) spt.drop(i, job.cls);
4699 return false;
4700 }
4701 break;
4702 }
4703 }
4704 if (!from_orbit && !preset) job.t_arr = now;
4705 job.region_wait = rwait;
4706 job.priority = classprio[job.cls];
4707 // A TIME-INHOMOGENEOUS service is NOT drawn here: it is drawn when the
4708 // job reaches a server, because its rate depends on absolute time and
4709 // the job may wait first. The exception is a station that ranks its
4710 // waiting room by the sampled size, which has to have one now. Every
4711 // other family is time-invariant and is drawn once, here, as before.
4712 if (draw_at_arrival(i, job.cls) && !job.preset) {
4713 job.service = sp_draw_svc(i, job.cls, S[i].svc[job.cls], g_svc[i][job.cls], now);
4714 job.remaining = job.service;
4715 job.elapsed = 0.0;
4716 }
4717 if (!from_orbit) job.deadline = (preset ? job.t_sys : now) + classdeadline[job.cls];
4718 job.id = ++job_id;
4719 if (rgi >= 0) {
4720 Region& R = regions[static_cast<std::size_t>(rgi)];
4721 R.update(now);
4722 R.enter(job.cls);
4723 }
4724 sd_advance(i);
4725 if (!from_orbit) {
4726 // an orbiting job has been in the station population since it arrived
4727 acc.update_qlen(i, job.cls, now);
4728 acc.qlen[i][job.cls] += 1.0;
4729 // Counted where the job JOINS the station; a buffer drop and a balk are
4730 // counted where they are refused, above, so a drop, a balk or a reneging
4731 // leaves AN above TN, which is the difference AN exists to show.
4732 acc.arrived[i][job.cls] += 1.0;
4733 bp.track(i, job.cls, +1, now);
4734 }
4735
4736 if (s.role == Role::Delay) {
4737 job.due = now + svc_delay(i, job.cls, job.service);
4738 if (track_delay_jobs) {
4739 job.tag = ++ps_tag;
4740 delay_live[i].push_back(job);
4741 }
4742 Event e;
4743 e.t = job.due;
4744 e.kind = EV_DEPARTURE;
4745 e.station = i;
4746 e.cls = job.cls;
4747 e.slot = std::numeric_limits<std::size_t>::max();
4748 e.tag = job.tag;
4749 e.job = job;
4750 push(e);
4751 // The scaling this think time actually runs at is installed by the
4752 // flush, which re-times the event just pushed along with every other
4753 // completion in flight. A model with no global dependence never gets
4754 // here, and the departure stands as scheduled.
4755 if (has_gd) sd_reschedule(i);
4756 return true;
4757 }
4758 if (s.ps) {
4759 ps_advance(i);
4760 // LPS admits at most `limit` jobs into the shared server; the rest
4761 // wait in the buffer under the same order a PS station would use.
4762 if (s.lps_limit > 0 && s.ps_jobs.size() >= s.lps_limit) {
4763 buffer_push(i, job);
4764 return true;
4765 }
4766 PsJob pj;
4767 pj.cls = job.cls;
4768 pj.priority = job.priority;
4769 pj.t_arr = job.t_arr;
4770 pj.region_wait = job.region_wait;
4771 pj.t_sys = job.t_sys;
4772 pj.sys_cls = job.sys_cls;
4773 pj.total = job.preset ? job.elapsed + job.service : job.service;
4774 pj.remaining = job.service;
4775 pj.parent = job.parent;
4776 pj.ext = job.ext;
4777 pj.id = job.id;
4778 s.ps_jobs.push_back(pj);
4779 ps_reschedule(i);
4780 return true;
4781 }
4782 // SERVERS THAT POWER DOWN. The arrival claims an ACTIVE idle server, or
4783 // one inside its delay-off window (which pays nothing, the server never
4784 // having shut down), or a cold one, which starts its setup under THIS
4785 // job's class while the job waits; with none of the three it waits.
4786 // Either way it waits through the ordinary tail below, reneging clock
4787 // included, as the reference's `waitQueues.add` + `scheduleRenegingEvent`.
4788 bool setup_wait = false;
4789 if (s.has_setup) {
4790 const std::size_t sl = setup_pick(i, job.cls);
4791 if (sl < s.nservers && s.power[sl] != PW_OFF) {
4792 if (s.power[sl] == PW_DELAYOFF) power_cancel(i, sl);
4793 start_service(i, sl, job);
4794 sd_reschedule(i);
4795 return true;
4796 }
4797 if (sl < s.nservers) power_setup(i, sl, job.cls);
4798 setup_wait = true;
4799 }
4800 if (s.pas) {
4801 s.pas_list.push_back(job);
4802 acc.update_busy(i, job.cls, now);
4803 acc.busy[i][job.cls] += 1.0;
4804 pas_reschedule(i);
4805 return true;
4806 }
4807 if (s.polling && s.poll_ext) {
4808 buffer_push(i, job);
4809 // An idle server that is not walking is parked: it advances as
4810 // State.pollingAdvance does with arrived = true.
4811 if (poll_slot(s) >= s.nservers && !s.poll_switching) {
4812 s.poll_parked = false;
4813 poll_ext_advance(i, true);
4814 }
4815 return true;
4816 }
4817 if (s.polling) {
4818 buffer_push(i, job);
4819 if (s.poll_parked && !s.poll_switching) {
4820 s.poll_parked = false;
4821 // A parked server stands at a polling instant: the arrival
4822 // opens a fresh visit if it joins the buffer the server is at.
4823 if (job.cls == s.poll_at) {
4824 poll_open_visit(s);
4825 poll_serve(i);
4826 } else {
4827 poll_advance(i);
4828 }
4829 } else if (poll_slot(s) >= s.nservers && !s.poll_switching) {
4830 poll_serve(i);
4831 }
4832 return true;
4833 }
4834 // A BULK SERVER holds no per-job service time: the arrival joins the queue
4835 // and, if the station was EMPTY, arms the station-level firing clock. It is
4836 // never given a slot, so the ordinary free-slot path below must not see it.
4837 if (s.bmsp) {
4838 buffer_push(i, job);
4839 if (!s.server_busy[0]) {
4840 s.server_busy[0] = true;
4841 s.server_start[0] = now;
4842 acc.update_busy(i, job.cls, now);
4843 acc.busy[i][job.cls] += 1.0;
4844 bmsp_arm(i);
4845 }
4846 return true;
4847 }
4848 if (!setup_wait) {
4849 const std::size_t sl = free_slot_for(i, job.cls);
4850 if (sl < s.nservers) {
4851 start_service(i, sl, job);
4852 sd_reschedule(i);
4853 return true;
4854 }
4855 }
4856 // Every server is busy, or on a pooled station every server THIS CLASS
4857 // MAY USE is. A preemptive station now asks whether this arrival
4858 // displaces one of them; the freed slot is taken by the arrival itself,
4859 // not by the head of the queue, because the victim has just been pushed
4860 // there and could otherwise be picked straight back.
4861 // A job seizing n slots displaces ONE job and still needs n-1 idle, so
4862 // a station that cannot offer them gains nothing by preempting: the
4863 // victim would be sent back to the waiting room for a service that
4864 // still could not start.
4865 if (s.preemptive &&
4866 (!s.has_parallelism || free_slot_count(i) + 1 >= s.parallelism[job.cls])) {
4867 std::vector<Job> held;
4868 std::vector<std::size_t> slot_of;
4869 std::vector<double> started;
4870 for (std::size_t sl = 0; sl < s.nservers; ++sl)
4871 if (s.server_busy[sl] && !s.server_blocked[sl]) {
4872 // ONLY A SLOT THE ARRIVAL COULD THEN OCCUPY is a candidate
4873 // victim: preempting a job on a pool that does not accept
4874 // this class frees a server the arrival cannot use, so the
4875 // victim would be displaced for nothing.
4876 if (s.has_pools && !s.type_compat[s.server_type[sl]][job.cls]) continue;
4877 Job h = s.server[sl];
4878 // The residual as of NOW, which is what every size-based
4879 // rule compares against; the stored value is as of the
4880 // instant service started.
4881 const double hw = svc_work(i, h.cls, s.server_start[sl], now);
4882 h.remaining = std::max(0.0, h.remaining - hw);
4883 h.elapsed += hw;
4884 held.push_back(h);
4885 slot_of.push_back(sl);
4886 started.push_back(s.server_start[sl]);
4887 }
4888 const std::size_t v = preemption_victim(s.sched, held, started, job,
4889 static_cast<double>(s.nservers), now);
4890 if (v < held.size()) {
4891 const std::size_t sl = slot_of[v];
4892 preempt(i, sl);
4893 start_service(i, sl, job);
4894 sd_reschedule(i);
4895 return true;
4896 }
4897 }
4898 buffer_push(i, job);
4899 // RENEGING times out a job that is WAITING, not one in service: a job
4900 // that reached a server has been served and no longer abandons. The
4901 // timer is therefore armed here and nowhere else, and it is re-armed
4902 // if a preemption sends the job back to the waiting room.
4903 if (s.has_patience[job.cls]) {
4904 Event e;
4905 e.t = now + s.patience[job.cls].next(g_pat[i][job.cls]);
4906 e.kind = EV_RENEGE;
4907 e.station = i;
4908 e.cls = job.cls;
4909 e.tag = job.id;
4910 push(e);
4911 }
4912 sd_reschedule(i);
4913 return true;
4914 };
4915
4916 const std::map<std::size_t, double> kNoWeights;
4917 /** Every index of `tab`, so JSQ can be told to consider all of them. */
4918 std::vector<std::size_t> tab_all;
4919
4920 /**
4921 * PROB: one draw against the static row.
4922 *
4923 * The mass is NOT renormalized before the draw. The reference scales the
4924 * uniform by the row total instead, so a row summing to one only up to
4925 * rounding still lands, and the two engines consume the routing stream
4926 * identically.
4927 */
4928 auto draw_prob = [&](const std::vector<RouteDest>& tab) -> std::size_t {
4929 double total = 0.0;
4930 for (std::size_t k = 0; k < tab.size(); ++k) total += tab[k].mass;
4931 const double u = uniform01(g_routing) * total;
4932 double cum = 0.0;
4933 std::size_t pick = 0;
4934 for (pick = 0; pick + 1 < tab.size(); ++pick) {
4935 cum += tab[pick].mass;
4936 if (u <= cum) break;
4937 }
4938 return pick;
4939 };
4940
4941 // ---- state-dependent routing (Krzesinski 1987) ----------------------------
4942 // The coefficients are derived ONCE: `pfqn_sdrcoeff` validates the
4943 // declaration and its population bounds, and repeating that at every
4944 // departure would make the validation the cost of the run.
4945 //
4946 // INDEX SPACE. The probabilities are read off the STATION-indexed structure
4947 // against station populations, and the destination split is mapped back
4948 // through the NODE-indexed twin, exactly as `state.h`'s `rt_state` does. The
4949 // two spaces must not be mixed: `pfqn_sdrprob` uses `sdr.branch[b][k]` as
4950 // indices into the population vector, so the structure and the vector have
4951 // to agree, while `entryOf`/`departure` are compared against node indices.
4952 const bool has_sdr = !sn.sdr.empty() && !sn.sdr_nodes.empty();
4953 pfqn::SdrCoeff sdr_coeff;
4954 if (has_sdr) sdr_coeff = pfqn::pfqn_sdrcoeff(sn.sdr);
4955 std::vector<double> sdr_pop, sdr_mass;
4956
4957 /**
4958 * Eq. (10) of Krzesinski (1987) at the CURRENT marking: the split out of the
4959 * entry centre into the branch entries, plus the residual that returns the
4960 * customer to the departure centre.
4961 *
4962 * A Source is reported as zero rather than as the infinite reservoir its
4963 * encoding carries, which is the `station_populations` rule and the one the
4964 * enumerating solvers use, so the sample path here has an exact counterpart
4965 * in SolverNC rather than merely a similar one.
4966 */
4967 auto draw_sdr = [&](const std::vector<RouteDest>& tab) -> std::size_t {
4968 sdr_pop.assign(M, 0.0);
4969 for (std::size_t i = 0; i < M; ++i) {
4970 if (S[i].role == Role::Source) continue;
4971 double held = 0.0;
4972 for (std::size_t q = 0; q < K; ++q) held += acc.qlen[i][q];
4973 sdr_pop[i] = held;
4974 }
4975 const std::vector<double> Pb = pfqn::pfqn_sdrprob(sdr_coeff, sdr_pop);
4976 const double Ped = pfqn::pfqn_sdrped(Pb);
4977
4978 sdr_mass.assign(tab.size(), 0.0);
4979 double total = 0.0;
4980 for (std::size_t i = 0; i < tab.size(); ++i) {
4981 const std::size_t dnode = tab[i].node - 1; // 0-based, as sdr_nodes is
4982 double p = 0.0;
4983 for (std::size_t b = 1; b < sn.sdr_nodes.branch.size(); ++b)
4984 if (sn.sdr_nodes.entryOf[b] == dnode) p += Pb[b];
4985 if (sn.sdr_nodes.departure == dnode) p += Ped;
4986 // Eq. (10) returns zero at a branch closed to new arrivals; the
4987 // clamp only guards the residual against round-off.
4988 if (p < 0.0) p = 0.0;
4989 sdr_mass[i] = p;
4990 total += p;
4991 }
4992 // The branch probabilities and the residual sum to one over the branch
4993 // entries and the departure centre, so this normalization is an identity
4994 // whenever the declaration and the links agree. It is kept so the draw
4995 // stays a distribution if they do not, and the fallback below keeps a
4996 // model whose links reach neither from dividing by zero.
4997 if (!(total > 0.0)) return draw_prob(tab);
4998 const double u = uniform01(g_routing) * total;
4999 double cum = 0.0;
5000 std::size_t pick = 0;
5001 for (pick = 0; pick + 1 < tab.size(); ++pick) {
5002 cum += sdr_mass[pick];
5003 if (u <= cum) break;
5004 }
5005 return pick;
5006 };
5007
5008 /**
5009 * The candidate holding the FEWEST jobs, ties broken uniformly.
5010 *
5011 * A destination that is not a service station holds nothing to compare, so
5012 * it is skipped rather than counted as empty -- a Sink would otherwise win
5013 * every comparison and absorb the whole stream. When no candidate is a
5014 * station the first one is taken, which is the reference's fallback.
5015 */
5016 auto shortest_queue = [&](const std::vector<RouteDest>& tab,
5017 const std::vector<std::size_t>& cand) -> std::size_t {
5018 double best = std::numeric_limits<double>::infinity();
5019 std::vector<std::size_t> tied;
5020 for (std::size_t c = 0; c < cand.size(); ++c) {
5021 const std::size_t k = cand[c];
5022 if (tab[k].station >= M || S[tab[k].station].role == Role::Source) continue;
5023 double held = 0.0;
5024 for (std::size_t q = 0; q < K; ++q) held += acc.qlen[tab[k].station][q];
5025 if (held < best) {
5026 best = held;
5027 tied.clear();
5028 tied.push_back(k);
5029 } else if (held == best) {
5030 tied.push_back(k);
5031 }
5032 }
5033 if (tied.empty()) return cand.empty() ? 0 : cand[0];
5034 if (tied.size() == 1) return tied[0];
5035 std::size_t at = static_cast<std::size_t>(uniform01(g_routing) *
5036 static_cast<double>(tied.size()));
5037 if (at >= tied.size()) at = tied.size() - 1;
5038 return tied[at];
5039 };
5040
5041 /**
5042 * One hop out of node `inode` in class `r`: the DISPATCHER picks the node,
5043 * the class-switch row picks the class.
5044 *
5045 * NEITHER STAGE DRAWS WHEN ITS OUTCOME IS DETERMINED. A single destination
5046 * and a single arriving class each cost nothing, which is the reference's
5047 * rule and not an optimization: a routing stream that advanced on a forced
5048 * hop would put every subsequent draw out of step with the Java engine and
5049 * make a seeded run of a tandem irreproducible across the two.
5050 */
5051 auto draw_node_route = [&](std::size_t inode, std::size_t r) -> RouteEntry {
5052 const std::vector<RouteDest>& tab = nroute[inode][r];
5053 if (tab.empty())
5054 throw InputError("SolverLDES (native engine): node '" + sn.nodes[inode - 1].name +
5055 "' has no routing for class '" + sn.classes[r].name + "'");
5056 std::size_t pick = 0;
5057 if (tab.size() > 1) {
5058 if (tab_all.size() != tab.size()) {
5059 tab_all.resize(tab.size());
5060 for (std::size_t k = 0; k < tab.size(); ++k) tab_all[k] = k;
5061 }
5062 switch (node_routing[inode][r]) {
5064 pick = static_cast<std::size_t>(uniform01(g_routing) *
5065 static_cast<double>(tab.size()));
5066 if (pick >= tab.size()) pick = tab.size() - 1;
5067 break;
5068 }
5070 pick = rr_counter[inode][r] % tab.size();
5071 ++rr_counter[inode][r];
5072 break;
5073 }
5075 // The weights become an INTEGER schedule and the counter
5076 // walks it, so a 3:1 split really is three then one and not
5077 // a 0.75 coin. A fractional weight is scaled by 1000 and a
5078 // positive weight never rounds to zero, or a link declared
5079 // open would never be offered a job.
5080 const std::map<std::size_t, double>& w =
5081 (sn.nodes[inode - 1].routing_weights.size() > r)
5082 ? sn.nodes[inode - 1].routing_weights[r]
5083 : kNoWeights;
5084 std::vector<double> raw(tab.size(), 0.0);
5085 bool integral = true;
5086 for (std::size_t k = 0; k < tab.size(); ++k) {
5087 const std::map<std::size_t, double>::const_iterator it = w.find(tab[k].node);
5088 raw[k] = (it == w.end()) ? 0.0 : it->second;
5089 if (raw[k] < 0.0 || raw[k] != std::floor(raw[k])) integral = false;
5090 }
5091 std::vector<std::size_t> quota(tab.size(), 0);
5092 std::size_t total = 0;
5093 for (std::size_t k = 0; k < tab.size(); ++k) {
5094 double v = integral ? raw[k] : raw[k] * 1000.0;
5095 std::size_t q = (v > 0.0) ? static_cast<std::size_t>(v) : 0;
5096 if (raw[k] > 0.0 && q < 1) q = 1;
5097 quota[k] = q;
5098 total += q;
5099 }
5100 if (total == 0) {
5101 // No usable weights: the dispatcher degenerates to plain
5102 // round robin, which is the reference's fallback.
5103 pick = rr_counter[inode][r] % tab.size();
5104 ++rr_counter[inode][r];
5105 break;
5106 }
5107 std::size_t counter = rr_counter[inode][r] % total;
5108 ++rr_counter[inode][r];
5109 std::size_t cum = 0;
5110 for (pick = 0; pick + 1 < tab.size(); ++pick) {
5111 cum += quota[pick];
5112 if (counter < cum) break;
5113 }
5114 break;
5115 }
5117 // Unlike JSQ and SQ(d) this routing keeps a product form of
5118 // its own, so this sample path has an exact counterpart in
5119 // solver_nc_sdr. The two agree only if both read the same
5120 // populations; see draw_sdr. A routing named SDR with no
5121 // declaration behind it is a malformed model every reader
5122 // refuses, and draw_prob is what it falls back to rather
5123 // than dividing by an absent structure.
5124 pick = has_sdr ? draw_sdr(tab) : draw_prob(tab);
5125 break;
5126 }
5128 pick = shortest_queue(tab, tab_all);
5129 break;
5130 }
5132 // POWER OF d: sample d candidates WITH replacement (manual
5133 // 3.2, SSA's NRM), then take the shortest among them. Two
5134 // draws can hit the same queue, so it is not JSQ even when d
5135 // covers every destination; sampling without replacement and
5136 // short-cutting to JSQ made SQ bit-identical to JSQ there.
5137 std::size_t d = (sn.nodes[inode - 1].routing_param.size() > r &&
5138 sn.nodes[inode - 1].routing_param[r] > 0)
5139 ? static_cast<std::size_t>(
5140 sn.nodes[inode - 1].routing_param[r])
5141 : 2;
5142 std::vector<std::size_t> cand;
5143 for (std::size_t k = 0; k < d; ++k) {
5144 std::size_t at = static_cast<std::size_t>(
5145 uniform01(g_routing) * static_cast<double>(tab.size()));
5146 if (at >= tab.size()) at = tab.size() - 1;
5147 cand.push_back(at);
5148 }
5149 pick = shortest_queue(tab, cand);
5150 break;
5151 }
5152 default: {
5153 pick = draw_prob(tab);
5154 break;
5155 }
5156 }
5157 }
5158 const RouteDest& d = tab[pick];
5159 RouteEntry e;
5160 e.node = d.node;
5161 e.station = d.station;
5162 e.sink = d.sink;
5163 e.cls = d.cls[0].first;
5164 if (d.cls.size() > 1) {
5165 double total = 0.0;
5166 for (std::size_t k = 0; k < d.cls.size(); ++k) total += d.cls[k].second;
5167 const double u = uniform01(g_routing) * total;
5168 double cum = 0.0;
5169 for (std::size_t k = 0; k < d.cls.size(); ++k) {
5170 cum += d.cls[k].second;
5171 if (u <= cum || k + 1 == d.cls.size()) {
5172 e.cls = d.cls[k].first;
5173 break;
5174 }
5175 }
5176 }
5177 return e;
5178 };
5179
5180 /**
5181 * The class a job routed out of `node` under `cls` will ARRIVE the true
5182 * destination station under, resolving through any ClassSwitch/Router/
5183 * Logger chain `draw_node_route` itself stops one hop short of.
5184 *
5185 * `draw_node_route(i, r).cls` names the class on the FIRST edge out of a
5186 * station, and when `link()` synthesized a ClassSwitch node for that edge
5187 * (any route whose class differs from station to station), that first
5188 * edge's class is the PRE-switch one -- the switch happens INSIDE the
5189 * synthesized node, one hop later. The synchronous-call park check below
5190 * needs the class the job actually lands under, or a callee's own reply
5191 * (its edge into the synthesized node still reads as the CALL class) is
5192 * misread as a brand-new call: the reply's `job.call` is then overwritten
5193 * with a fresh id, the caller's real call is never answered, and its
5194 * server stays held while the buffer behind it grows without bound.
5195 *
5196 * Consumes no extra draw when every hop is forced, which a link()-
5197 * synthesized pass-through node always is (`draw_node_route` never spends
5198 * a draw on a single-destination table), so the routing stream stays in
5199 * step with a caller that already resolved through this same node.
5200 */
5201 auto resolve_final_cls = [&](std::size_t node, std::size_t cls) -> std::size_t {
5202 std::size_t at_node = node, at_cls = cls;
5203 for (std::size_t hop = 0; hop <= nnodes && at_node != 0; ++hop) {
5204 const NodeType dt = sn.nodes[at_node - 1].nodetype;
5205 if (dt != NodeType::ClassSwitch && dt != NodeType::Router && dt != NodeType::Logger)
5206 break;
5207 const RouteEntry e = draw_node_route(at_node, at_cls);
5208 at_cls = e.cls;
5209 at_node = e.node;
5210 }
5211 return at_cls;
5212 };
5213
5214 /**
5215 * The station and class a job routed onto `re` ACTUALLY lands at, walking
5216 * the ClassSwitch/Router/Logger chain `draw_node_route` stops one hop short
5217 * of, and only while every hop is FORCED.
5218 *
5219 * WHY IT EXISTS: `link()` synthesizes `CS_<i>_to_<j>` for any route whose
5220 * class changes, so a CLASS-SWITCHING SELF-LOOP leaves the station as an
5221 * edge into that synthesized node. `re.station` is then not the station at
5222 * all and `re.cls` is still the PRE-switch class, so an immediate-feedback
5223 * test written on the raw entry reads the self-loop as a departure to
5224 * elsewhere and the feature goes silently inert on exactly the models that
5225 * need it -- measured against the Java engine and SolverSSA, which both
5226 * move the held job between classes.
5227 *
5228 * WHY FORCED HOPS ONLY: this is a LOOK-AHEAD. A job that turns out not to
5229 * be fed back is handed to `deliver`, which makes the same hops again, so
5230 * the walk must not spend a routing draw or every ordinary departure would
5231 * consume the stream twice and put the run out of step with the Java
5232 * engine. A hop with one destination and one arriving class costs nothing
5233 * (`draw_node_route` draws only where the outcome is undetermined), and a
5234 * link()-synthesized pass-through is always of that shape. Anything else
5235 * stops the walk and leaves the entry as it was, which reads as "not a
5236 * self-loop". A Logger is walked with the other two; the Loggers crossed are
5237 * kept in `fb_loggers`, and a job that IS fed back writes its trace rows from
5238 * there, since it never reaches the `deliver` that would otherwise write them.
5239 */
5240 std::vector<std::pair<std::size_t, std::size_t>> fb_loggers; // Loggers the last look-ahead crossed
5241 auto resolve_forced_dest = [&](const RouteEntry& re) -> RouteEntry {
5242 RouteEntry at = re;
5243 fb_loggers.clear();
5244 for (std::size_t hop = 0; hop <= nnodes; ++hop) {
5245 if (at.node == 0 || at.sink) break;
5246 const NodeType dt = sn.nodes[at.node - 1].nodetype;
5247 if (dt != NodeType::ClassSwitch && dt != NodeType::Router && dt != NodeType::Logger)
5248 break;
5249 if (dt == NodeType::Logger) fb_loggers.push_back(std::make_pair(at.node, at.cls));
5250 const std::vector<RouteDest>& tab = nroute[at.node][at.cls];
5251 if (tab.size() != 1 || tab[0].cls.size() != 1) break;
5252 RouteEntry nxt;
5253 nxt.node = tab[0].node;
5254 nxt.station = tab[0].station;
5255 nxt.sink = tab[0].sink;
5256 nxt.cls = tab[0].cls[0].first;
5257 at = nxt;
5258 }
5259 return at;
5260 };
5261
5262 // ---- busy periods -------------------------------------------------------
5263 // Every station is a target set of its own, every declared subnetwork is a
5264 // set, and each is measured aggregated and then per class, which is the
5265 // order `initializeBusyPeriods` builds them in and the order the result
5266 // rows carry.
5267 if (o.busy_period_orders > 0) {
5268 std::vector<std::vector<std::size_t>> sets;
5269 std::vector<std::string> set_names;
5270 for (std::size_t i = 0; i < M; ++i) {
5271 if (S[i].role == Role::Source || S[i].role == Role::Synchronization) continue;
5272 sets.push_back(std::vector<std::size_t>(1, i));
5273 set_names.push_back(sn.stations[i].name);
5274 }
5275 for (const std::vector<std::size_t>& sub : o.busy_period_subnets) {
5276 std::string nm;
5277 for (std::size_t s2 : sub) {
5278 if (s2 >= M || S[s2].role == Role::Source)
5279 throw InputError("SolverLDES (native engine): station " +
5280 std::to_string(s2) +
5281 " of a busy period subnetwork is not a service station");
5282 nm += (nm.empty() ? "" : "+") + sn.stations[s2].name;
5283 }
5284 sets.push_back(sub);
5285 set_names.push_back(nm);
5286 }
5287 std::vector<BpTarget> targets;
5288 for (std::size_t si = 0; si < sets.size(); ++si) {
5289 BpTarget t;
5290 t.stations = sets[si];
5291 t.job_class = -1;
5292 t.name = set_names[si];
5293 targets.push_back(t);
5294 for (std::size_t r = 0; r < K; ++r) {
5295 BpTarget tc;
5296 tc.stations = sets[si];
5297 tc.job_class = static_cast<int>(r);
5298 tc.name = set_names[si] + ":" + sn.classes[r].name;
5299 targets.push_back(tc);
5300 }
5301 }
5302 bp.init(targets, o.busy_period_orders, M);
5303 }
5304
5305
5306 /**
5307 * Hand on the jobs blocked in front of `j`, oldest first, now that it has
5308 * room.
5309 *
5310 * OLDEST FIRST is the reference's rule and it matters: releasing the newest
5311 * would starve a server that has been blocked longest, which no blocking
5312 * discipline does and which shows up as an unbounded blocked time at one
5313 * station while another cycles freely.
5314 */
5315 std::function<void(std::size_t)> release_blocked = [&](std::size_t j) {
5316 bool progress = true;
5317 while (progress) {
5318 progress = false;
5319 std::size_t best_i = M, best_sl = 0;
5320 double oldest = std::numeric_limits<double>::infinity();
5321 for (std::size_t a = 0; a < M; ++a) {
5322 // A SHARING station has no per-server slots at all, so it has
5323 // no slot to block and none of these vectors is allocated for
5324 // it. Indexing them by `nservers` reads off the end.
5325 if (S[a].role != Role::Queue || S[a].ps || S[a].server_blocked.empty()) continue;
5326 for (std::size_t sl = 0; sl < S[a].nservers; ++sl)
5327 if (S[a].server_blocked[sl] && S[a].blocked_dest[sl] == j &&
5328 S[a].blocked_job[sl].t_arr < oldest) {
5329 oldest = S[a].blocked_job[sl].t_arr;
5330 best_i = a;
5331 best_sl = sl;
5332 }
5333 }
5334 if (best_i >= M) break;
5335 const std::size_t dcls = S[best_i].blocked_dest_cls[best_sl];
5336 if (!dest_has_room(j, dcls)) break;
5337
5338 StationState& src = S[best_i];
5339 Job moved = src.blocked_job[best_sl];
5340 src.server_blocked[best_sl] = false;
5341 src.server_busy[best_sl] = false;
5342 src.server_tag[best_sl] = 0;
5343 acc.update_qlen(j, dcls, now);
5344 acc.qlen[j][dcls] -= 1.0;
5345 S[j].blocked_at[dcls] -= 1.0;
5346
5347 // The job now leaves the upstream station for good.
5348 acc.update_busy(best_i, moved.cls, now);
5349 if (acc.busy[best_i][moved.cls] > 0.0) acc.busy[best_i][moved.cls] -= 1.0;
5350
5351 Job fresh;
5352 fresh.cls = dcls;
5353 fresh.t_sys = moved.t_sys;
5354 fresh.sys_cls = moved.sys_cls;
5355 fresh.parent = moved.parent;
5356 admit(j, fresh, best_i);
5357
5358 // The freed server takes its own next waiting job -- on a pooled
5359 // station, the first one in service order that its pool accepts.
5360 serve_next_on_slot(best_i, best_sl);
5361 progress = true;
5362 }
5363 };
5364
5365
5366 /**
5367 * Let the jobs parked by region `rg` in, oldest first, now that it has
5368 * room.
5369 *
5370 * THE WAIT QUEUE IS STRICT FIFO: a head that still does not fit stops the release, and no younger waiter
5371 * overtakes it, as in JMT and the Java engine (`tryReleaseBlockedCustomers`). Letting a waiter of another class
5372 * jump the head starves the head whenever a per-class or linear cap keeps binding for it.
5373 *
5374 * A waiter re-enters through `admit`, which re-tests every constraint: the
5375 * region may have freed one slot while the waiter's own class cap or the
5376 * linear constraints still bind, and admitting on the global count alone
5377 * would breach them.
5378 */
5379 release_region = [&](std::size_t rg) {
5380 std::vector<RegionWaiter>& q = region_wait[rg];
5381 while (!q.empty()) {
5382 {
5383 const std::size_t w = 0;
5384 Region& R = regions[rg];
5385 if (R.would_exceed(q[w].job.cls)) break;
5386 RegionWaiter taken = q[w];
5387 R.update(now);
5388 R.blocked[taken.job.cls] -= 1.0;
5389 q.erase(q.begin() + static_cast<std::ptrdiff_t>(w));
5390 Job fresh;
5391 fresh.cls = taken.job.cls;
5392 fresh.t_sys = taken.job.t_sys;
5393 fresh.sys_cls = taken.job.sys_cls;
5394 // A parked job keeps its fork and call identities: without them a Join discards it as an orphan and
5395 // the reply to a parked call finds no pending call, so the caller's server is held forever
5396 fresh.parent = taken.job.parent;
5397 fresh.call = taken.job.call;
5398 fresh.rank = taken.job.rank;
5399 pending_keep_rank = true;
5400 // The wait outside the region is charged to the visit's response time, as JMT and
5401 // Solver_ssj charge it (the released customer keeps its queueArrivalTime); QLen
5402 // still counts the waiter nowhere, which is the JMT convention the reference keeps.
5403 pending_region_wait = now - taken.job.t_arr;
5404 admit(taken.station, fresh, M);
5405 }
5406 }
5407 };
5408
5409 // ---- G-network signals --------------------------------------------------
5410
5411 /** The jobs station `i` actually HOLDS, waiting and in service alike. */
5412 auto signal_held = [&](std::size_t i) -> std::size_t {
5413 const StationState& s = S[i];
5414 if (s.role == Role::Delay) return delay_live[i].size();
5415 if (s.pas) return s.pas_list.size();
5416 std::size_t n = s.buffer.size();
5417 if (s.ps) return n + s.ps_jobs.size();
5418 for (std::size_t sl = 0; sl < s.nservers; ++sl)
5419 if (s.server_busy[sl]) ++n;
5420 return n;
5421 };
5422
5423 /**
5424 * Remove ONE job from station `i` under `policy`, returning its class or
5425 * `K` when the station holds nothing.
5426 *
5427 * THE POLICY IS TWO-TIER, as in the reference: FCFS and LCFS rank the
5428 * WAITING line by age and only reach into the servers once nobody waits,
5429 * while RANDOM draws uniformly over waiting and in-service jobs together.
5430 * A station whose occupants are all in service -- Delay, PS, PAS -- has no
5431 * waiting line for the age tiers to rank, so there the three policies
5432 * differ only in which of the equally-served jobs is taken.
5433 *
5434 * The victim is drawn WITHOUT REGARD TO CLASS. That is Gelenbe's negative
5435 * customer and what the Java engine and SolverMAM both do; `sn.signaltarget`
5436 * narrows the eligible class only in the state-space solvers, whose state
5437 * carries the per-class composition this one draws over directly.
5438 */
5439 auto signal_remove_one = [&](std::size_t i, lang::RemovalPolicy policy) -> std::size_t {
5440 StationState& s = S[i];
5441
5442 // A DELAY holds every occupant in service, in the registry.
5443 if (s.role == Role::Delay) {
5444 std::vector<Job>& live = delay_live[i];
5445 if (live.empty()) return K;
5446 std::size_t at = 0;
5447 if (policy == lang::RemovalPolicy::FCFS) {
5448 for (std::size_t j = 1; j < live.size(); ++j)
5449 if (live[j].t_arr < live[at].t_arr) at = j;
5450 } else if (policy == lang::RemovalPolicy::LCFS) {
5451 for (std::size_t j = 1; j < live.size(); ++j)
5452 if (live[j].t_arr > live[at].t_arr) at = j;
5453 } else {
5454 at = static_cast<std::size_t>(uniform01(g_routing) *
5455 static_cast<double>(live.size()));
5456 if (at >= live.size()) at = live.size() - 1;
5457 }
5458 const std::size_t rc = live[at].cls;
5459 live.erase(live.begin() + static_cast<std::ptrdiff_t>(at));
5460 return rc;
5461 }
5462
5463 // A PASS-AND-SWAP list: one aggregate clock covers the whole station,
5464 // so the survivors must be re-timed rather than left on a rate the
5465 // list no longer has.
5466 if (s.pas) {
5467 if (s.pas_list.empty()) return K;
5468 std::size_t at = 0;
5469 if (policy == lang::RemovalPolicy::FCFS) {
5470 for (std::size_t j = 1; j < s.pas_list.size(); ++j)
5471 if (s.pas_list[j].t_arr < s.pas_list[at].t_arr) at = j;
5472 } else if (policy == lang::RemovalPolicy::LCFS) {
5473 for (std::size_t j = 1; j < s.pas_list.size(); ++j)
5474 if (s.pas_list[j].t_arr > s.pas_list[at].t_arr) at = j;
5475 } else {
5476 at = static_cast<std::size_t>(uniform01(g_routing) *
5477 static_cast<double>(s.pas_list.size()));
5478 if (at >= s.pas_list.size()) at = s.pas_list.size() - 1;
5479 }
5480 const std::size_t rc = s.pas_list[at].cls;
5481 s.pas_list.erase(s.pas_list.begin() + static_cast<std::ptrdiff_t>(at));
5482 acc.update_busy(i, rc, now);
5483 if (acc.busy[i][rc] > 0.0) acc.busy[i][rc] -= 1.0;
5484 pas_reschedule(i);
5485 return rc;
5486 }
5487
5488 const std::size_t waiting = s.buffer.size();
5489
5490 // A SHARING station: `ps_jobs` are in service, `buffer` holds only the
5491 // jobs an LPS admission cap has left outside.
5492 if (s.ps) {
5493 const std::size_t inservice = s.ps_jobs.size();
5494 if (waiting + inservice == 0) return K;
5495 bool from_wait;
5496 if (policy == lang::RemovalPolicy::RANDOM) {
5497 const std::size_t pick = static_cast<std::size_t>(
5498 uniform01(g_routing) * static_cast<double>(waiting + inservice));
5499 from_wait = pick < waiting;
5500 } else {
5501 from_wait = waiting > 0;
5502 }
5503 if (from_wait) {
5504 std::size_t at = 0;
5505 if (policy == lang::RemovalPolicy::FCFS) {
5506 for (std::size_t j = 1; j < s.buffer.size(); ++j)
5507 if (s.buffer[j].t_arr < s.buffer[at].t_arr) at = j;
5508 } else if (policy == lang::RemovalPolicy::LCFS) {
5509 for (std::size_t j = 1; j < s.buffer.size(); ++j)
5510 if (s.buffer[j].t_arr > s.buffer[at].t_arr) at = j;
5511 } else {
5512 at = std::min(waiting - 1,
5513 static_cast<std::size_t>(uniform01(g_routing) *
5514 static_cast<double>(waiting)));
5515 }
5516 const std::size_t rc = s.buffer[at].cls;
5517 if (s.sched != SchedStrategy::FSP)
5518 jpq_remove_at(s.buffer, at, s.cmp);
5519 else
5520 s.buffer.erase(s.buffer.begin() + static_cast<std::ptrdiff_t>(at));
5521 return rc;
5522 }
5523 ps_advance(i);
5524 std::size_t at = 0;
5525 if (policy == lang::RemovalPolicy::FCFS) {
5526 for (std::size_t j = 1; j < s.ps_jobs.size(); ++j)
5527 if (s.ps_jobs[j].t_arr < s.ps_jobs[at].t_arr) at = j;
5528 } else if (policy == lang::RemovalPolicy::LCFS) {
5529 for (std::size_t j = 1; j < s.ps_jobs.size(); ++j)
5530 if (s.ps_jobs[j].t_arr > s.ps_jobs[at].t_arr) at = j;
5531 } else {
5532 at = std::min(inservice - 1,
5533 static_cast<std::size_t>(uniform01(g_routing) *
5534 static_cast<double>(inservice)));
5535 }
5536 const std::size_t rc = s.ps_jobs[at].cls;
5537 s.ps_jobs.erase(s.ps_jobs.begin() + static_cast<std::ptrdiff_t>(at));
5538 // The freed share is taken by whatever an LPS cap was holding out.
5539 if (s.lps_limit > 0 && !s.buffer.empty() && s.ps_jobs.size() < s.lps_limit) {
5540 Job nextjob = buffer_pop(i);
5541 PsJob pj;
5542 pj.cls = nextjob.cls;
5543 pj.priority = nextjob.priority;
5544 pj.t_arr = nextjob.t_arr;
5545 pj.region_wait = nextjob.region_wait;
5546 pj.t_sys = nextjob.t_sys;
5547 pj.sys_cls = nextjob.sys_cls;
5548 pj.total = nextjob.preset ? nextjob.elapsed + nextjob.service : nextjob.service;
5549 pj.remaining = nextjob.service;
5550 pj.parent = nextjob.parent;
5551 pj.ext = nextjob.ext;
5552 pj.id = nextjob.id;
5553 s.ps_jobs.push_back(pj);
5554 }
5555 ps_reschedule(i);
5556 return rc;
5557 }
5558
5559 // A BUFFERED station. A blocked slot is NOT a candidate: the job it
5560 // holds has already completed here and is charged to the destination
5561 // it is queueing for, so removing it would decrement the wrong station.
5562 std::size_t inservice = 0;
5563 for (std::size_t sl = 0; sl < s.nservers; ++sl)
5564 if (s.server_busy[sl]) ++inservice;
5565 if (waiting + inservice == 0) return K;
5566 bool from_wait;
5567 if (policy == lang::RemovalPolicy::RANDOM) {
5568 const std::size_t pick = static_cast<std::size_t>(
5569 uniform01(g_routing) * static_cast<double>(waiting + inservice));
5570 from_wait = pick < waiting;
5571 } else {
5572 from_wait = waiting > 0;
5573 }
5574
5575 if (from_wait) {
5576 std::size_t at = 0;
5577 if (policy == lang::RemovalPolicy::FCFS) {
5578 for (std::size_t j = 1; j < s.buffer.size(); ++j)
5579 if (s.buffer[j].t_arr < s.buffer[at].t_arr) at = j;
5580 } else if (policy == lang::RemovalPolicy::LCFS) {
5581 for (std::size_t j = 1; j < s.buffer.size(); ++j)
5582 if (s.buffer[j].t_arr > s.buffer[at].t_arr) at = j;
5583 } else {
5584 at = std::min(waiting - 1,
5585 static_cast<std::size_t>(uniform01(g_routing) *
5586 static_cast<double>(waiting)));
5587 }
5588 const std::size_t rc = s.buffer[at].cls;
5589 if (s.sched != SchedStrategy::FSP)
5590 jpq_remove_at(s.buffer, at, s.cmp);
5591 else
5592 s.buffer.erase(s.buffer.begin() + static_cast<std::ptrdiff_t>(at));
5593 return rc;
5594 }
5595
5596 std::size_t slot = s.nservers;
5597 for (std::size_t sl = 0; sl < s.nservers; ++sl) {
5598 if (!s.server_busy[sl]) continue;
5599 if (slot == s.nservers) {
5600 slot = sl;
5601 continue;
5602 }
5603 if (policy == lang::RemovalPolicy::FCFS) {
5604 if (s.server[sl].t_arr < s.server[slot].t_arr) slot = sl;
5605 } else if (policy == lang::RemovalPolicy::LCFS) {
5606 if (s.server[sl].t_arr > s.server[slot].t_arr) slot = sl;
5607 }
5608 }
5609 if (policy == lang::RemovalPolicy::RANDOM) {
5610 std::size_t pick = std::min(inservice - 1,
5611 static_cast<std::size_t>(uniform01(g_routing) *
5612 static_cast<double>(inservice)));
5613 for (std::size_t sl = 0; sl < s.nservers; ++sl)
5614 if (s.server_busy[sl]) {
5615 if (pick == 0) {
5616 slot = sl;
5617 break;
5618 }
5619 --pick;
5620 }
5621 }
5622 if (slot == s.nservers) return K;
5623 sd_advance(i);
5624 const std::size_t rc = s.server[slot].cls;
5625 // Freeing the slot and clearing its tag is what neutralises the
5626 // departure already in the list; there is no handle to cancel it with.
5627 s.server_busy[slot] = false;
5628 s.server_tag[slot] = 0;
5629 if (s.rr) s.rr_qtag[slot] = 0;
5630 const double freed = release_slots(i, slot);
5631 acc.update_busy(i, rc, now);
5632 acc.busy[i][rc] -= freed;
5633 // The vacated server takes the next job, under the station's own order:
5634 // the polling controller decides for itself, everyone else pops.
5635 if (s.polling) {
5636 poll_serve(i);
5637 } else if (!s.server_blocked[slot] && !s.server_held[slot]) {
5638 serve_next_on_slot(i, slot);
5639 }
5640 sd_reschedule(i);
5641 return rc;
5642 };
5643
5644 /**
5645 * A G-NETWORK REMOVAL SIGNAL arriving at station `i`, and annihilated there.
5646 *
5647 * The signal NEVER JOINS the station and never continues along its routing
5648 * chain: it removes a batch of the jobs it finds, and one that finds the
5649 * station empty is simply lost. That is Gelenbe's semantics and the one
5650 * `State.afterEventStationSignal` and the Java engine both implement;
5651 * routing the signal onward instead would make a single signal fire once
5652 * per downstream station, which is what the tandem regression measures.
5653 *
5654 * A CATASTROPHE removes EVERY job held, in-service ones included, and
5655 * ignores the batch-size law entirely -- removing all of them is what the
5656 * word means. A NEGATIVE signal draws its batch size from `signalremdist`
5657 * (absent: exactly one) and CLIPS it at what the station holds, so an
5658 * oversized batch drains the station instead of driving it negative.
5659 */
5660 // The class a system completion is credited to: the one the passage started
5661 // in, falling back to the current class for a job whose entry was not recorded.
5662 auto entry_class = [&](const Job& jb) -> std::size_t {
5663 return (jb.sys_cls >= 0 && static_cast<std::size_t>(jb.sys_cls) < K)
5664 ? static_cast<std::size_t>(jb.sys_cls) : jb.cls;
5665 };
5666 auto apply_signal = [&](std::size_t i, const Job& sig) {
5667 StationState& s = S[i];
5668 const std::size_t held = signal_held(i);
5669 if (held > 0) {
5670 std::size_t to_remove = 1;
5671 if (sig.cls < sn.signaltype.size() &&
5672 sn.signaltype[sig.cls] == lang::SignalType::CATASTROPHE) {
5673 to_remove = held;
5674 } else if (sig.cls < sn.signalremdist.size() && !sn.signalremdist[sig.cls].empty()) {
5675 const std::vector<T>& pmf = sn.signalremdist[sig.cls];
5676 const double u = uniform01(g_routing);
5677 double cum = 0.0;
5678 std::size_t b = 0;
5679 for (; b + 1 < pmf.size(); ++b) {
5680 cum += static_cast<double>(pmf[b]);
5681 if (u < cum) break;
5682 }
5683 to_remove = std::min(b, held);
5684 } else {
5685 to_remove = std::min<std::size_t>(1, held);
5686 }
5688 if (sig.cls < sn.signalrempolicy.size()) policy = sn.signalrempolicy[sig.cls];
5689 for (std::size_t rep = 0; rep < to_remove; ++rep) {
5690 if (signal_held(i) == 0) break;
5691 const std::size_t rc = signal_remove_one(i, policy);
5692 if (rc >= K) break;
5693 last_lost[i][rc] = now;
5694 sd_advance(i);
5695 acc.update_qlen(i, rc, now);
5696 acc.qlen[i][rc] -= 1.0;
5697 bp.track(i, rc, -1, now);
5698 // A job destroyed inside a finite capacity region frees the
5699 // slot it occupied; leaving it charged would shrink the region
5700 // by one for the rest of the run.
5701 if (region_of[i] >= 0) {
5702 const std::size_t rg = static_cast<std::size_t>(region_of[i]);
5703 regions[rg].update(now);
5704 regions[rg].leave(rc);
5705 release_region(rg);
5706 }
5707 }
5708 release_blocked(i);
5709 }
5710 // The signal is annihilated here: it leaves the system without ever
5711 // having been at a station, so it is a system completion and nothing
5712 // else -- no arrival, no queue length and no station throughput.
5713 const std::size_t sc = entry_class(sig);
5714 sys_resp_sum[sc] += now - sig.t_sys;
5715 sys_resp_cnt[sc] += 1.0;
5716 sys_completed[sc] += 1.0;
5717 };
5718
5719
5720 /**
5721 * The completion budget, spent by anything the model actually DOES.
5722 *
5723 * Declared ahead of `deliver` because a service completion is not the only
5724 * thing that spends it: a Petri net has no services of its own and counts a
5725 * FIRING, and a cache-only model (Source -> Cache -> Sink) has none either
5726 * and counts the cache's delivery to the Sink. Without the latter the loop
5727 * at the bottom of this function never terminates on such a model, since
5728 * the Source keeps the event queue non-empty forever. `Solver_ssj` spends
5729 * the budget at the same point (`deliverCacheCompletion` calls
5730 * `checkEventCountStop` on the sink branch), so this is the reference's
5731 * rule and not a local convention.
5732 */
5733 std::uint64_t total_completions = 0;
5734
5735 /**
5736 * Free every request parked while `item` was being fetched.
5737 *
5738 * Declared ahead of `deliver` and assigned after it because the two are
5739 * mutually recursive: a release routes each freed request onward, and a
5740 * delivery to a cache is what triggers a release. Each freed request reads
5741 * the now-cached item and completes at once, counted as a DELAYED HIT and
5742 * leaving under its own hit class; its original `t_sys` is preserved so the
5743 * response time still spans the wait it actually served.
5744 */
5745 std::function<void(CacheState&, std::size_t, std::size_t)> release_delayed_hits;
5746
5747 /**
5748 * Hand a job to a NODE, replicating at a Fork and synchronizing at a Join.
5749 *
5750 * A FORK sends a sibling down EVERY outgoing edge, not one drawn from the
5751 * routing probabilities: the edges of a fork are branches taken together,
5752 * and drawing among them would turn a fork into a probabilistic split with
5753 * the same picture and a completely different response time. `tasksPerLink`
5754 * multiplies each branch.
5755 *
5756 * A JOIN releases ONE job once its strategy is satisfied and DISCARDS the
5757 * siblings that arrive afterwards -- under a quorum they are the losers of
5758 * the race, and counting them as completions would inflate the throughput
5759 * of everything downstream.
5760 */
5761 std::function<void()> spn_settle; // defined with the net below; a token reaching a Place settles it
5762 std::function<void(std::size_t, Job, std::size_t)> deliver =
5763 [&](std::size_t node, Job job, std::size_t from) {
5764 const NodeType nt = sn.nodes[node - 1].nodetype;
5765
5766 /**
5767 * A JOB REACHING A PLACE BECOMES A TOKEN of its own class, which is the
5768 * reference's `handlePlaceArrival`; one reaching a Transition is absorbed
5769 * and only re-evaluates the net. Before 2026-10-11 both fell through to
5770 * the station admission and drew a service time from the place's empty
5771 * process, so every open net died in `map_sample`.
5772 */
5773 if (nt == NodeType::Place) {
5774 place_deposit(place_of[node], job.cls, 1.0);
5775 spn_settle();
5776 return;
5777 }
5778 if (nt == NodeType::Transition) {
5779 spn_settle();
5780 return;
5781 }
5782
5783 if (nt == NodeType::Sink) {
5784 // Credited to the class the passage STARTED in (Job::sys_cls), not the
5785 // class the job leaves in, so a chain switching A -> B reports XN/CN
5786 // under A and nothing under B, as MATLAB's XN at the reference
5787 // station (the Source) does.
5788 const std::size_t sc = entry_class(job);
5789 sys_resp_sum[sc] += now - job.t_sys;
5790 sys_resp_cnt[sc] += 1.0;
5791 sys_completed[sc] += 1.0;
5792 return;
5793 }
5794
5795 if (nt == NodeType::Cache) {
5796 auto ci = caches.find(node);
5797 if (ci == caches.end())
5798 throw InputError("SolverLDES (native engine): Cache node '" +
5799 sn.nodes[node - 1].name + "' carries no parameters");
5800 CacheState& cs = ci->second;
5801 Job out = job;
5802
5803 // A RETURNING FETCH, not a read. The job wearing a retrieval class
5804 // is the fetch this cache sent out on an earlier miss: it inserts
5805 // the item, clears the in-flight flag and frees everyone parked
5806 // behind it. The miss was counted when the fetch was TRIGGERED, so
5807 // counting it again here would double every miss.
5808 if (cs.has_retrieval) {
5809 const int fetched = cs.fetches_item(job.cls);
5810 if (fetched >= 0) {
5811 const std::size_t fi = static_cast<std::size_t>(fetched);
5812 cs.accumulate(now);
5813 cache_miss(cs, fi, uniform01(g_routing), uniform01(g_routing));
5814 cs.in_flight[fi] = 0;
5815 cs.total_fetch_time += now - cs.fetch_start[fi];
5816 cs.completed_fetches += 1.0;
5817 release_delayed_hits(cs, fi, node);
5818 if (cs.miss_class[job.cls] >= 0)
5819 out.cls = static_cast<std::size_t>(cs.miss_class[job.cls]);
5820 const RouteEntry re = draw_node_route(node, out.cls);
5821 out.cls = re.cls;
5822 if (re.node != 0 && sn.nodes[re.node - 1].nodetype == NodeType::Sink)
5823 ++total_completions;
5824 deliver(re.node, out, M);
5825 return;
5826 }
5827 }
5828
5829 const std::vector<double>& pop = cs.popularity[job.cls];
5830 if (pop.empty())
5831 throw InputError("SolverLDES (native engine): class '" +
5832 sn.classes[job.cls].name + "' reads cache '" +
5833 sn.nodes[node - 1].name + "' with no item popularity");
5834 const double u = uniform01(g_routing);
5835 std::size_t item = 0;
5836 while (item + 1 < pop.size() && u >= pop[item]) ++item;
5837
5838 const int at = cs.find(item);
5839 if (at >= 0) {
5840 cs.hits[job.cls] += 1.0;
5841 cs.hits_per_list[job.cls][static_cast<std::size_t>(at)] += 1.0;
5842 cs.accumulate(now);
5843 cache_hit(cs, item, static_cast<std::size_t>(at), uniform01(g_routing));
5844 if (cs.hit_class[job.cls] >= 0)
5845 out.cls = static_cast<std::size_t>(cs.hit_class[job.cls]);
5846 } else if (cs.has_retrieval && cs.retrieval_of(item, job.cls) > 0) {
5847 if (cs.in_flight[item]) {
5848 // A fetch for this item is already out: PARK the request. It
5849 // leaves the event stream entirely and is released when the
5850 // fetch returns, so it is neither a hit nor a miss yet.
5851 CacheState::HeldRequest hr;
5852 hr.cls = job.cls;
5853 hr.hold_time = now;
5854 hr.t_sys = job.t_sys;
5855 hr.sys_cls = job.sys_cls;
5856 cs.held[item].push_back(hr);
5857 return;
5858 }
5859 // Trigger the fetch: count the miss now and leave wearing the
5860 // per-item retrieval class, which the routing carries through
5861 // the retrieval stations and back to this cache.
5862 cs.misses[job.cls] += 1.0;
5863 cs.in_flight[item] = 1;
5864 cs.fetch_start[item] = now;
5865 out.cls = cs.retrieval_of(item, job.cls) - 1;
5866 } else {
5867 cs.misses[job.cls] += 1.0;
5868 cs.accumulate(now);
5869 cache_miss(cs, item, uniform01(g_routing), uniform01(g_routing));
5870 if (cs.miss_class[job.cls] >= 0)
5871 out.cls = static_cast<std::size_t>(cs.miss_class[job.cls]);
5872 }
5873 // The hit and miss classes are what the POST_CACHE branch routes on,
5874 // so the job leaves the cache under its new class.
5875 const RouteEntry e = draw_node_route(node, out.cls);
5876 out.cls = e.cls;
5877 // A cache delivering to a Sink is this model's only completion when
5878 // it has no service station, so it spends the budget (see above).
5879 if (e.node != 0 && sn.nodes[e.node - 1].nodetype == NodeType::Sink)
5880 ++total_completions;
5881 deliver(e.node, out, M);
5882 return;
5883 }
5884
5885 if (nt == NodeType::ClassSwitch || nt == NodeType::Router || nt == NodeType::Logger) {
5886 // A PASS-THROUGH NODE HOLDS NOTHING. It changes the class (a
5887 // ClassSwitch), picks a destination (a Router) or records the
5888 // crossing (a Logger) and the job continues in the SAME instant, so
5889 // there is no queue, no service and no row to fill.
5890 //
5891 // `link()` synthesizes `CS_<i>_to_<j>` for every link that switches
5892 // class, so this branch carries every class switch the routing
5893 // matrix used to hold as an edge attribute. Such a node has ONE
5894 // outgoing destination, so `draw_node_route` spends no draw on it
5895 // and the sample path stays in step with the Java engine.
5896 //
5897 // The walk is iterative, not recursive, and bounded: a routing that
5898 // sends a job round a cycle of pass-through nodes never reaches a
5899 // station and would otherwise hang the run.
5900 Job out = job;
5901 std::size_t at = node;
5902 const std::uint64_t walk = logger_traces.empty() ? 0 : log_walk_id++;
5903 if (nt == NodeType::Logger) log_passage(node, out.cls, walk);
5904 for (std::size_t hop = 0; hop <= nnodes; ++hop) {
5905 const RouteEntry e = draw_node_route(at, out.cls);
5906 out.cls = e.cls;
5907 if (e.node == 0) return;
5908 const NodeType dt = sn.nodes[e.node - 1].nodetype;
5909 if (dt == NodeType::ClassSwitch || dt == NodeType::Router ||
5910 dt == NodeType::Logger) {
5911 if (dt == NodeType::Logger) log_passage(e.node, out.cls, walk);
5912 at = e.node;
5913 continue;
5914 }
5915 deliver(e.node, out, from);
5916 return;
5917 }
5918 throw InputError("SolverLDES (native engine): the routing out of node '" +
5919 sn.nodes[node - 1].name +
5920 "' cycles through pass-through nodes without reaching a station");
5921 }
5922
5923 if (nt == NodeType::Fork) {
5924 // A FORK TAKES EVERY EDGE, so it flattens the two-stage table back
5925 // into one sibling per (destination, arriving class): there is no
5926 // dispatcher decision to make and no draw to spend.
5927 const std::vector<RouteDest>& tab = nroute[node][job.cls];
5928 if (tab.empty()) return;
5929 std::vector<RouteEntry> links;
5930 for (std::size_t di = 0; di < tab.size(); ++di)
5931 for (std::size_t ci = 0; ci < tab[di].cls.size(); ++ci) {
5932 RouteEntry e;
5933 e.node = tab[di].node;
5934 e.station = tab[di].station;
5935 e.sink = tab[di].sink;
5936 e.cls = tab[di].cls[ci].first;
5937 links.push_back(e);
5938 }
5939 const qn::NodeDef& fk = sn.nodes[node - 1];
5940 const auto* fp = sn.fork_param_of(node);
5941 const int per_link = std::max(1, static_cast<int>(fk.tasks_per_link + 0.5));
5942
5943 // How many tasks each branch emits on THIS firing. A plain fork
5944 // takes `per_link` on every link and draws NOTHING -- which is what
5945 // keeps every seeded golden and the bit-exact agreement with the
5946 // Java engine intact. A variable one draws the branch activation
5947 // and the degree per link, so the count the Join waits for is known
5948 // only after the draws.
5949 std::vector<int> per_branch(links.size(), per_link);
5950 int total = 0;
5951 const bool variable = fork_is_variable(node);
5952 for (std::size_t li = 0; li < links.size(); ++li) {
5953 if (variable) {
5954 const std::size_t k0 = links[li].node - 1, r0 = job.cls;
5955 const double p = static_cast<double>(fp->fan_out_prob(k0, r0));
5956 if (p < 1.0 && g_fork.aux.next_double() >= p) {
5957 per_branch[li] = 0;
5958 } else if (!fp->fan_out_dist[k0][r0].disabled) {
5959 per_branch[li] = sample_fork_degree(fp->fan_out_dist[k0][r0]);
5960 } else {
5961 per_branch[li] = static_cast<int>(static_cast<double>(fp->fan_out_link(k0, r0)) + 0.5);
5962 }
5963 }
5964 total += per_branch[li];
5965 }
5966 if (total <= 0)
5967 throw InputError("SolverLDES (native engine): Fork '" + fk.name +
5968 "' emitted no sibling; at least one branch must be certain "
5969 "to emit at least one task");
5970
5971 ForkSync fs;
5972 fs.cls = job.cls;
5973 fs.t_sys = job.t_sys;
5974 fs.sys_cls = job.sys_cls;
5975 fs.outer = job.parent;
5976 fs.t_fork = now;
5977 fs.pair = fj_pair_of_fork[node];
5978 fs.total = total;
5979 fs.required = fs.total;
5980 const int jn = join_of_fork[node];
5981 if (jn > 0) {
5982 auto jd = sn.joindecl.find(static_cast<std::size_t>(jn));
5983 if (jd != sn.joindecl.end() &&
5984 jd->second.strategy != lang::JoinStrategy::STD && jd->second.quorum > 0.0) {
5985 // The quorum is a count of THIS fork's siblings, fixed here
5986 // rather than at the Join: a Join shared by two forks of
5987 // different fan-out would otherwise apply one fork's count
5988 // to the other's siblings.
5989 fs.required = std::min(fs.total,
5990 std::max(1, static_cast<int>(jd->second.quorum + 0.5)));
5991 }
5992 }
5993 const std::uint64_t pid = ++next_parent;
5994 fork_sync[pid] = fs;
5995 for (std::size_t li = 0; li < links.size(); ++li)
5996 for (int t = 0; t < per_branch[li]; ++t) {
5997 Job sib;
5998 sib.cls = links[li].cls;
5999 sib.t_sys = job.t_sys;
6000 sib.sys_cls = job.sys_cls;
6001 sib.parent = pid;
6002 deliver(links[li].node, sib, M);
6003 }
6004 return;
6005 }
6006
6007 if (nt == NodeType::Join) {
6008 auto it = fork_sync.find(job.parent);
6009 if (it == fork_sync.end()) {
6010 // Its parent already synchronized: this sibling lost the quorum
6011 // race and is discarded rather than released a second time. It
6012 // goes into the SAME accumulators every other station uses, so
6013 // it is warmup-truncated with them; see Accum::join_dropped.
6014 //
6015 // IT STILL ARRIVED. `arrived` is the OFFERED rate, and the whole
6016 // point of a quorum is that N siblings are offered and only K
6017 // consumed, so leaving the straggler out reports AN = K*TN and
6018 // hides the very loss the measurement exists for. The reference
6019 // counts it the same way: its AN at the join is exactly N times
6020 // the fork rate under a quorum, not K times.
6021 const std::size_t jd = node_to_station[node];
6022 if (jd < M) {
6023 acc.arrived[jd][job.cls] += 1.0;
6024 acc.join_dropped[jd][job.cls] += 1.0;
6025 }
6026 return;
6027 }
6028 ForkSync& fs = it->second;
6029 // A JOIN IS A STATION LIKE ANY OTHER. Its siblings are its queue
6030 // length and its synchronizations are its completions, so they go
6031 // into the same accumulators every other station uses and are
6032 // warmup-truncated with them rather than measured on a private
6033 // tally the result assembly never reads.
6034 // `js == M` is a Join the refresh registered as a node and not as a
6035 // station, which has no row to fill; `handleJoinArrival` gates on
6036 // the same bound. The synchronization itself runs either way.
6037 const std::size_t js = node_to_station[node];
6038 if (js < M) {
6039 acc.update_qlen(js, job.cls, now);
6040 acc.qlen[js][job.cls] += 1.0;
6041 acc.arrived[js][job.cls] += 1.0;
6042 }
6043 fs.siblings.push_back(std::make_pair(job.cls, now));
6044 if (static_cast<int>(fs.siblings.size()) < fs.required) return;
6045
6046 // Satisfied: the siblings leave the Join together and one job goes on.
6047 if (js < M) {
6048 for (std::size_t si = 0; si < fs.siblings.size(); ++si) {
6049 const std::size_t sc = fs.siblings[si].first;
6050 acc.update_qlen(js, sc, now);
6051 acc.qlen[js][sc] -= 1.0;
6052 // Each sibling waited from ITS OWN arrival, not the first:
6053 // the Join charges the delay it imposed on each.
6054 acc.tally_resp(js, sc, now - fs.siblings[si].second);
6055 }
6056 acc.completed[js][fs.cls] += 1.0;
6057 }
6058 Job merged;
6059 merged.cls = fs.cls;
6060 merged.t_sys = fs.t_sys;
6061 merged.sys_cls = fs.sys_cls;
6062 merged.parent = fs.outer;
6063 if (fs.pair >= 0 && fs.cls < K) {
6064 const std::size_t p = static_cast<std::size_t>(fs.pair);
6065 fj_resp_sum[p][fs.cls] += now - fs.t_fork;
6066 fj_resp_cnt[p][fs.cls] += 1.0;
6067 fj_release[p][fs.cls].push_back(now);
6068 }
6069 fork_sync.erase(it);
6070 const RouteEntry e = draw_node_route(node, merged.cls);
6071 merged.cls = e.cls;
6072 deliver(e.node, merged, M);
6073 return;
6074 }
6075
6076 // An ordinary station.
6077 const std::size_t j = node_to_station[node];
6078 // A REMOVAL SIGNAL acts on the station and is annihilated: it is
6079 // intercepted here, before any of the accounting an arrival gets,
6080 // because it never becomes one.
6081 if (has_removal_signal && j < M && is_removal_signal[job.cls]) {
6082 apply_signal(j, job);
6083 return;
6084 }
6085 /**
6086 * A REPLY ANSWERS ITS CALL AND TRAVELS ON. It releases the server the
6087 * caller has been holding, lets that station take its next waiting job,
6088 * and then CONTINUES along its own routing -- which is what separates it
6089 * from a removal signal, annihilated where it lands. It arrives and
6090 * leaves in the same instant, taking the released server for zero time
6091 * (MATLAB `afterEventStationReply` with the reply's service Immediate),
6092 * so it counts as an ARRIVAL and a COMPLETION here, as the reference
6093 * counts it.
6094 *
6095 * A reply with NO MATCHING CALL is an ORDINARY JOB of its class: it is
6096 * admitted, queued and served with the service this station declares
6097 * for it, as MATLAB `State.afterEventStation` treats a REPLY at a station
6098 * holding no block for it. It used to route straight on from every
6099 * station, so a Delay giving the reply a think time reported QLen 0
6100 * (closed 2026-11-17).
6101 */
6102 typename std::map<std::uint64_t, PendingCall>::iterator pc = pending_reply.end();
6103 if (has_sync_call && j < M && is_reply_signal[job.cls]) pc = pending_reply.find(job.call);
6104 if (pc != pending_reply.end()) {
6105 acc.completed[j][job.cls] += 1.0;
6106 acc.arrived[j][job.cls] += 1.0;
6107 reply_passed[j][job.cls] += 1.0;
6108 {
6109 const std::size_t bi = pc->second.station, bs = pc->second.slot;
6110 const std::size_t bc = pc->second.cls;
6111 pending_reply.erase(pc);
6112 StationState& bst = S[bi];
6113 bst.server_held[bs] = false;
6114 acc.update_busy(bi, bc, now);
6115 if (acc.busy[bi][bc] > 0.0) acc.busy[bi][bc] -= 1.0;
6116 acc.update_qlen(bi, bc, now);
6117 acc.held[bi][bc] -= 1.0;
6118 if (!bst.server_blocked[bs]) {
6119 serve_next_on_slot(bi, bs);
6120 sd_reschedule(bi);
6121 }
6122 release_blocked(bi);
6123 }
6124 const RouteEntry re2 = draw_node_route(node, job.cls);
6125 Job onward;
6126 onward.cls = re2.cls;
6127 onward.t_sys = job.t_sys;
6128 onward.sys_cls = job.sys_cls;
6129 onward.parent = job.parent;
6130 deliver(re2.node, onward, M);
6131 return;
6132 }
6133 Job moved = job;
6134 // A closed class completes its passage on reaching its reference
6135 // station: that crossing IS the system completion, and the elapsed time
6136 // is the cycle time.
6137 if (j < M && sn.classes[job.cls].type != lang::JobClassType::OPEN &&
6138 j + 1 == sn.classes[job.cls].refstat) {
6139 sys_resp_sum[job.cls] += now - job.t_sys;
6140 sys_resp_cnt[job.cls] += 1.0;
6141 sys_completed[job.cls] += 1.0;
6142 moved.t_sys = now;
6143 moved.sys_cls = static_cast<int>(moved.cls);
6144 }
6145 if (!admit(j, moved, from) && sn.classes[job.cls].type != lang::JobClassType::OPEN)
6146 throw InputError("SolverLDES (native engine): a closed job was dropped at "
6147 "station '" + sn.stations[j].name +
6148 "'; a closed class cannot lose population");
6149 };
6150
6151 release_delayed_hits = [&](CacheState& cs, std::size_t item, std::size_t node) {
6152 if (item >= cs.held.size() || cs.held[item].empty()) return;
6153 std::vector<CacheState::HeldRequest> freed;
6154 freed.swap(cs.held[item]);
6155 for (std::size_t i = 0; i < freed.size(); ++i) {
6156 const CacheState::HeldRequest& hr = freed[i];
6157 cs.delayed[hr.cls] += 1.0;
6158 cs.delayed_wait += now - hr.hold_time;
6159 Job out;
6160 out.cls = (cs.hit_class[hr.cls] >= 0) ? static_cast<std::size_t>(cs.hit_class[hr.cls])
6161 : hr.cls;
6162 out.t_sys = hr.t_sys;
6163 out.sys_cls = hr.sys_cls;
6164 const RouteEntry e = draw_node_route(node, out.cls);
6165 out.cls = e.cls;
6166 if (e.node != 0 && sn.nodes[e.node - 1].nodetype == NodeType::Sink)
6167 ++total_completions;
6168 deliver(e.node, out, M);
6169 }
6170 };
6171
6172
6173 /**
6174 * The marking as one flat vector over (place slot, class), `p * K + r`,
6175 * which is what a mode's arcs are indexed by.
6176 *
6177 * SUMMED OVER CLASSES UNTIL 2026-08-12, which made every arc colourless and
6178 * let a token of one class satisfy another's pre-arc.
6179 */
6180 auto flat_marking = [&]() {
6181 std::vector<double> tok(place_nodes.size() * K, 0.0);
6182 for (std::size_t p = 0; p < place_nodes.size(); ++p)
6183 for (std::size_t r = 0; r < K; ++r) tok[p * K + r] = marking[p][r];
6184 return tok;
6185 };
6186
6187 /**
6188 * The tokens the ARCS can see, in the same layout.
6189 *
6190 * Identical to the marking at an ordinary place and the DEPOSITORY at a
6191 * queueing one, which is the whole difference between the two: enabling,
6192 * inhibiting and the immediate pick are decided on this vector, while a
6193 * MARKING-DEPENDENT FIRING RATE is still a function of the marking, because
6194 * `Transition.setFiringRateDependence` is declared over token counts and a
6195 * place's token count includes the ones it is still serving.
6196 */
6197 auto flat_avail = [&]() {
6198 std::vector<double> tok(place_nodes.size() * K, 0.0);
6199 for (std::size_t p = 0; p < place_nodes.size(); ++p)
6200 for (std::size_t r = 0; r < K; ++r) tok[p * K + r] = avail[p][r];
6201 return tok;
6202 };
6203
6204 /**
6205 * Move the tokens of one firing of `m`.
6206 *
6207 * CONSUME FIRST AND DEPOSIT SECOND, which is what a self-loop arc needs: a
6208 * mode that takes a token from a queueing place and puts one back takes the
6209 * SERVED one out of the depository and queues the new one for service again.
6210 * Netting the two against each other would leave the token where it was and
6211 * the place would never serve anything.
6212 */
6213 auto spn_apply = [&](const SpnMode& m) {
6214 for (std::size_t p = 0; p < place_nodes.size(); ++p)
6215 for (std::size_t r = 0; r < K; ++r) {
6216 const double e = m.enabling[p * K + r];
6217 if (e > 0.0) place_take(p, r, e);
6218 }
6219 for (std::size_t p = 0; p < place_nodes.size(); ++p)
6220 for (std::size_t r = 0; r < K; ++r) {
6221 const double f = m.firing[p * K + r];
6222 if (f > 0.0) place_deposit(p, r, f);
6223 }
6224 // A token leaving the net to a Sink completes a passage with no response time to
6225 // charge; one sent to a station enters it as a fresh job, as `routeTokenFromTransition`.
6226 for (const auto& ex : m.exits) {
6227 const std::size_t nd = std::get<0>(ex), r = std::get<1>(ex);
6228 const double n = std::get<2>(ex);
6229 if (sn.nodes[nd - 1].nodetype == NodeType::Sink) {
6230 sys_completed[r] += n;
6231 continue;
6232 }
6233 for (double t = 0.0; t + 0.5 < n; t += 1.0) {
6234 Job job;
6235 job.cls = r;
6236 job.t_sys = now;
6237 job.sys_cls = static_cast<int>(r);
6238 deliver(nd, job, M);
6239 }
6240 }
6241 };
6242
6243 /**
6244 * Fire every enabled IMMEDIATE mode, then arm the timed ones.
6245 *
6246 * The immediate modes are exhausted FIRST and to a fixed point: a marking
6247 * that enables one is not a marking the net rests in, so letting a timed
6248 * mode fire from it would visit a state the model does not have. The guard
6249 * bounds a net whose immediate modes form a cycle, which is a modelling
6250 * error rather than something to simulate forever.
6251 */
6252 std::uint64_t fire_tag = 0;
6253 // The tags of the clocks each (transition, mode) runs; an event whose tag is gone was cancelled.
6254 std::vector<std::vector<std::vector<std::uint64_t>>> spn_clocks(transitions.size());
6255 for (std::size_t t = 0; t < transitions.size(); ++t)
6256 spn_clocks[t].resize(transitions[t].modes.size());
6257 spn_settle = [&]() {
6258 if (transitions.empty()) return;
6259 for (int guard = 0; guard < 1000000; ++guard) {
6260 bool fired_any = false;
6261 std::vector<double> tok = flat_avail();
6262 for (std::size_t t = 0; t < transitions.size(); ++t) {
6263 const int k = spn_pick_immediate(transitions[t].modes, tok, uniform01(g_routing));
6264 if (k < 0) continue;
6265 const SpnMode& m = transitions[t].modes[static_cast<std::size_t>(k)];
6266 // The tokens move in THEIR OWN CLASS: an arc names a (place,
6267 // class) pair, so a Class2 pre-arc consumes Class2 tokens.
6268 spn_apply(m);
6269 transitions[t].fired[static_cast<std::size_t>(k)] += 1.0;
6270 ++total_completions;
6271 fired_any = true;
6272 break;
6273 }
6274 if (!fired_any) break;
6275 }
6276 // EVERY timed mode runs min(servers, enabling degree) clocks of its own law on the full
6277 // marking, as Solver_ssj's phase 2. A clock survives a marking change it does not lose its
6278 // enabling to, so a non-exponential law keeps its age; excess clocks are cancelled
6279 // uniformly at random. A marking-dependent mode is resampled on every change instead,
6280 // because its rate is a function of the marking (exact for an exponential law).
6281 const std::vector<double> tok = flat_avail();
6282 const std::vector<double> mk = flat_marking();
6283 for (std::size_t t = 0; t < transitions.size(); ++t)
6284 for (std::size_t k = 0; k < transitions[t].modes.size(); ++k) {
6285 const SpnMode& m = transitions[t].modes[k];
6286 if (m.immediate) continue;
6287 std::vector<std::uint64_t>& live = spn_clocks[t][k];
6288 const bool on = spn_enabled(m, tok) && !spn_law[t][k].disabled();
6289 double g = 1.0;
6290 if (on && m.dep) {
6291 g = m.dep(mk);
6292 live.clear();
6293 }
6294 const std::size_t target =
6295 (on && g > 0.0) ? static_cast<std::size_t>(spn_active_servers(m, tok)) : 0;
6296 while (live.size() > target) {
6297 const std::size_t pick = std::min(
6298 live.size() - 1, static_cast<std::size_t>(uniform01(g_spn) * live.size()));
6299 live.erase(live.begin() + static_cast<std::ptrdiff_t>(pick));
6300 }
6301 while (live.size() < target) {
6302 Event e;
6303 e.t = now + spn_law[t][k].next(g_spn) / g;
6304 e.kind = EV_FIRING;
6305 e.station = t;
6306 e.cls = k;
6307 e.tag = ++fire_tag;
6308 live.push_back(e.tag);
6309 push(e);
6310 }
6311 }
6312 };
6313
6314 // ---- sample-path recorder (`spInit`) --------------------------------------
6315 /**
6316 * Configures the recorder BEFORE the initial placement, as the reference does,
6317 * so the service draws the placement takes are captured and bound like any
6318 * other. Decides per stateful node whether its detailed LINE State rows can be
6319 * encoded; a node that cannot still contributes its counts and its events.
6320 */
6321 if (sp_on) {
6322 for (std::size_t nd = 0; nd < sn.nodes.size(); ++nd) {
6323 const NodeType nt = sn.nodes[nd].nodetype;
6324 if (nt == NodeType::Fork || nt == NodeType::Join || nt == NodeType::Place ||
6325 nt == NodeType::Transition || nt == NodeType::Cache)
6326 throw UnsupportedError(ErrorKind{"SamplePath"},
6327 std::string("SolverLDES: the sample-path export does not support ") +
6328 lang::node_type_to_text(nt) + " node '" + sn.nodes[nd].name + "'.");
6329 }
6330 spt.M = M;
6331 spt.R = K;
6332 spt.node_of.assign(M, -1);
6333 spt.is_source.assign(M, false);
6334 spt.is_service.assign(M, false);
6335 spt.detail.assign(M, false);
6336 spt.fcfs_buffer.assign(M, false);
6337 spt.phases.assign(M, std::vector<int>(K, 1));
6338 spt.map_vars.assign(M, std::vector<int>(K, 0));
6339 spt.map_var_init.assign(M, std::vector<double>(K, 1.0));
6340 spt.src_script.assign(M, std::vector<sp::ScriptP>(K));
6341 spt.src_start.assign(M, std::vector<double>(K, 0.0));
6342 // The declared initial row of a node: the most probable row of its space.
6343 auto declared_row = [&](std::size_t ind) -> std::vector<double> {
6344 std::vector<double> row;
6345 typename std::map<std::size_t, Matrix<T>>::const_iterator it = sn.statespace.find(ind);
6346 if (it == sn.statespace.end() || it->second.rows() == 0) return row;
6347 std::size_t best = 0;
6348 typename std::map<std::size_t, std::vector<T>>::const_iterator pr = sn.stateprior.find(ind);
6349 if (pr != sn.stateprior.end())
6350 for (std::size_t r = 1; r < pr->second.size() && r < it->second.rows(); ++r)
6351 if (num_traits<T>::to_double(pr->second[r]) > num_traits<T>::to_double(pr->second[best]))
6352 best = r;
6353 for (std::size_t c = 0; c < it->second.cols(); ++c)
6354 row.push_back(num_traits<T>::to_double(it->second(best, c)));
6355 return row;
6356 };
6357 // Global, as the reference's hasLld/hasCd/hasGd: one dependent station
6358 // takes the detailed rows away from every station.
6359 bool sp_dependent = has_gd;
6360 for (std::size_t i = 0; i < M; ++i)
6361 if (!S[i].lld.empty() || S[i].has_cd) sp_dependent = true;
6362 std::vector<std::string> why(M);
6363 for (std::size_t i = 0; i < M; ++i) {
6364 const StationState& s = S[i];
6365 const std::size_t ind = sn.node_of_station(i + 1);
6366 spt.node_of[i] = static_cast<long long>(ind) - 1;
6367 if (s.role == Role::Source) {
6368 spt.is_source[i] = true;
6369 const std::vector<std::size_t>& mk = sn.stations[i].marked_classes;
6370 for (std::size_t k = 0; k < K; ++k) {
6371 const lang::ProcessType pt = s.off[k] ? lang::ProcessType::DISABLED : s.svc[k].type();
6372 int np = sp::phase_count(s.svc[k], s.off[k], true);
6373 for (std::size_t m = 1; m < mk.size(); ++m)
6374 if (mk[m] == k + 1 && mk[0] != k + 1) np = 1; // the stream lives on the carrier
6375 if (np < 0 || pt == lang::ProcessType::NHPP || pt == lang::ProcessType::NNPP) {
6376 why[i] = "a time-inhomogeneous arrival process";
6377 np = 1;
6378 }
6379 spt.phases[i][k] = np;
6380 }
6381 continue;
6382 }
6383 if (s.role != Role::Queue && s.role != Role::Delay) continue;
6384 spt.is_service[i] = true;
6385 const bool delay = s.role == Role::Delay;
6386 for (std::size_t k = 0; k < K; ++k) {
6387 int np = sp::phase_count(s.svc[k], s.off[k], false);
6388 if (!s.off[k] && lang::process_is_marked_stationary(s.svc[k].type()))
6389 np = 1; // marked service is drawn without a walk
6390 if (np < 0) {
6391 why[i] = "a time-inhomogeneous service process";
6392 np = 1;
6393 }
6394 spt.phases[i][k] = np;
6395 }
6396 std::string w = why[i];
6397 if (w.empty() && !delay && s.sched != SchedStrategy::FCFS &&
6398 !(s.ps && s.sched != SchedStrategy::LPS)) {
6399 std::string nm = lang::sched_to_text(s.sched);
6400 for (char& ch : nm) ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
6401 w = "scheduling " + nm + " (supported: FCFS, the PS family but LPS, and Delay)";
6402 }
6403 if (w.empty() && sp_dependent) w = "load-, class-, state- or globally dependent service";
6404 if (w.empty() && (s.pas || s.polling || s.bmsp)) w = "pass-and-swap, polling or batch service";
6405 if (w.empty() && (s.has_setup || s.has_breakdown)) w = "setup, delay-off or breakdowns";
6406 if (w.empty() && s.has_pools) w = "heterogeneous server pools";
6407 if (w.empty() && !regions.empty()) w = "finite capacity regions";
6408 for (std::size_t k = 0; w.empty() && k < K; ++k) {
6409 if ((k < s.has_retrial.size() && s.has_retrial[k]) ||
6410 (k < s.has_patience.size() && s.has_patience[k]) ||
6411 (k < s.balk.size() && !s.balk[k].empty())) {
6412 w = "retrial, reneging or balking";
6413 } else if (!s.off[k] && s.svc[k].type() == lang::ProcessType::NHPP) {
6414 w = "a time-varying service rate";
6415 } else if (k < s.parallelism.size() && s.parallelism[k] > 1) {
6416 w = "server parallelism";
6417 } else if (k < s.droprule.size() && s.droprule[k] != lang::DropStrategy::DROP &&
6418 s.droprule[k] != lang::DropStrategy::WAITQ) {
6419 w = "blocking after or before service";
6420 }
6421 }
6422 const std::vector<std::size_t>& nv = sn.nvars[ind - 1];
6423 for (std::size_t c = K; w.empty() && c < nv.size(); ++c)
6424 if (nv[c] != 0) w = "routing or cache local variables";
6425 for (std::size_t k = 0; w.empty() && k < K; ++k) {
6426 const int n = k < nv.size() ? static_cast<int>(nv[k]) : 0;
6427 const lang::ProcessType pt = s.svc[k].type();
6428 const bool map_like = !s.off[k] && (pt == lang::ProcessType::MAP || pt == lang::ProcessType::MMPP2);
6429 if (n > 0 && !(map_like && n == 1 && s.sched == SchedStrategy::FCFS && !delay && s.nservers == 1))
6430 w = "a MAP service outside a single-server FCFS queue";
6431 spt.map_vars[i][k] = n;
6432 }
6433 spt.detail[i] = w.empty();
6434 spt.fcfs_buffer[i] = !delay && s.sched == SchedStrategy::FCFS;
6435 why[i] = w;
6436 if (spt.detail[i]) {
6437 // MAP local variables trail the declared row, one per MAP class, by class.
6438 const std::vector<double> init = declared_row(ind);
6439 std::size_t nv_tot = 0;
6440 for (std::size_t k = 0; k < K; ++k) nv_tot += static_cast<std::size_t>(spt.map_vars[i][k]);
6441 if (!init.empty() && init.size() >= nv_tot) {
6442 std::size_t off = init.size() - nv_tot;
6443 for (std::size_t k = 0; k < K; ++k)
6444 if (spt.map_vars[i][k] > 0) spt.map_var_init[i][k] = init[off++];
6445 }
6446 }
6447 }
6448 // The recorded node list is the REFERENCE's stateful set, in node order.
6449 // MATLAB and the JAR make EVERY Router stateful (Router < StatefulNode),
6450 // whereas this struct promotes only the dispatching ones (see
6451 // _kb/16-state-dependent-routing.md), so a PROB/RAND Router would
6452 // otherwise be missing from statefulNodes, state, aggr and phases. It
6453 // holds no job, so it records the constant row the reference records.
6454 std::vector<std::size_t> sp_sf(sn.stateful_nodes.begin(), sn.stateful_nodes.end());
6455 for (std::size_t ind = 1; ind <= sn.nodes.size(); ++ind)
6456 if (sn.nodes[ind - 1].nodetype == NodeType::Router &&
6457 std::find(sp_sf.begin(), sp_sf.end(), ind) == sp_sf.end())
6458 sp_sf.push_back(ind);
6459 std::sort(sp_sf.begin(), sp_sf.end());
6460 const std::size_t nsf = sp_sf.size();
6461 std::vector<std::size_t> sf_nodes(nsf);
6462 std::vector<std::string> refusal(nsf);
6463 std::vector<bool> refused(nsf, false);
6464 spt.station_of_sf.assign(nsf, -1);
6465 spt.const_row.assign(nsf, std::vector<double>());
6466 for (std::size_t isf = 0; isf < nsf; ++isf) {
6467 const std::size_t ind = sp_sf[isf];
6468 sf_nodes[isf] = ind - 1;
6469 std::size_t ist = 0; // 1-based station, 0 = none
6470 for (std::size_t i = 0; i < M; ++i)
6471 if (sn.node_of_station(i + 1) == ind) ist = i + 1;
6472 if (ist >= 1 && ist <= M && (spt.is_service[ist - 1] || spt.is_source[ist - 1])) {
6473 spt.station_of_sf[isf] = static_cast<long long>(ist - 1);
6474 refusal[isf] = why[ist - 1];
6475 } else {
6476 const std::vector<std::size_t>& nv = sn.nvars[ind - 1];
6477 for (std::size_t c = K; refusal[isf].empty() && c < nv.size(); ++c)
6478 if (nv[c] != 0) refusal[isf] = "routing or cache local variables";
6479 std::vector<double> init = declared_row(ind);
6480 spt.const_row[isf] = init.empty() ? std::vector<double>(K, 0.0) : init;
6481 }
6482 refused[isf] = !refusal[isf].empty();
6483 }
6484 spt.rec = sp::Recorder(static_cast<std::size_t>(o.sample_path_events), sf_nodes, K, refusal, refused);
6485 spt.seed(o.seed > 0 ? static_cast<long long>(o.seed) : 0LL);
6486 }
6487
6488 // ---- initial state -----------------------------------------------------
6489 /**
6490 * WARM START, `--initsol`: the placement a companion solver's steady state
6491 * implies, as a STATION-MAJOR vector [st0_cl0, ..., stM-1_clK-1].
6492 *
6493 * It REPLACES the reference-station placement of the closed classes; the
6494 * open arrival streams are armed either way. A Petri net is exempt: its
6495 * tokens live in Places and not in the service queues this vector
6496 * describes, so a station-based placement would put nothing anywhere and
6497 * then fail the conservation check.
6498 *
6499 * CLASSES DESCEND WITHIN A STATION. Every initial job arrives at time 0, so
6500 * under an order-preserving discipline the LAST one injected holds the
6501 * server; ascending order puts the highest-index class in service, which is
6502 * the mirror of what `State.initDefault` encodes and selects the other
6503 * closed communicating class on a chain made reducible by non-overtaking
6504 * routing -- a different stationary distribution, not a different tie-break.
6505 */
6506 /**
6507 * The stations whose job-level state init_jobs and track_jobs can carry:
6508 * FCFS queues, the PS family and Delays, in a model with no feature that
6509 * keeps state outside the jobs' residual work. Refused by name otherwise,
6510 * as `ldes_engine_reject` does, because a restored run that silently lost
6511 * that state reports numbers nothing downstream can tell from correct ones.
6512 */
6513 auto job_state_check = [&](std::size_t i) {
6514 const StationState& s = S[i];
6515 std::string why;
6516 if (!place_nodes.empty() || !regions.empty() || !sn.fj.empty() || has_spawn)
6517 why = "Petri-net places, finite capacity regions, fork-join or spawning";
6518 else if (has_removal_signal || has_sync_call)
6519 why = "G-network removal signals or synchronous calls";
6520 else if (has_gd || slotted)
6521 why = "global state dependence or slotted time";
6522 else if (!s.lld.empty() || s.has_cd || s.state_dependent)
6523 why = "load-, class- or state-dependent service";
6524 else if (s.pas || s.polling || s.bmsp)
6525 why = "pass-and-swap, polling or batch service";
6526 else if (s.has_setup || s.has_breakdown || s.has_pools || s.has_parallelism)
6527 why = "setup, breakdowns, server pools or server parallelism";
6528 else if (s.role == Role::Queue && !s.ps && s.sched != SchedStrategy::FCFS)
6529 why = std::string("scheduling ") + lang::sched_to_text(s.sched) +
6530 " (supported: FCFS, the PS family and Delay)";
6531 else
6532 for (std::size_t r = 0; r < K && why.empty(); ++r) {
6533 if (s.off[r]) continue;
6534 if ((r < s.has_retrial.size() && s.has_retrial[r]) ||
6535 (r < s.has_patience.size() && s.has_patience[r]) || s.svc[r].time_varying())
6536 why = "retrial, reneging or a time-varying service law";
6537 }
6538 if (!why.empty())
6539 throw UnsupportedError(ErrorKind{"InitJobs"},
6540 "SolverLDES (native engine): init_jobs/track_jobs do not support station '" +
6541 sn.stations[i].name + "': " + why);
6542 };
6543
6544 /**
6545 * JOB-LEVEL INITIAL STATE, `options.init_jobs`, one row per job:
6546 * [station, class, remaining, elapsed, qage, sage, order, id].
6547 *
6548 * Each row carries the job's residual work, so a run continues exactly where
6549 * an earlier one stopped; `finalJobs` is the export in the same layout. A
6550 * positive `remaining` is used as given; -1 draws a full service time and -2
6551 * draws the residual given the attained `elapsed`, by rejection (S given
6552 * S > elapsed), which is exact for any law. qage and sage become arrival
6553 * instants in the past, so response times count the time already spent.
6554 * Rows are injected per station in increasing `order`: the first ones take
6555 * the free servers and the rest wait in that order, which the FCFS heap
6556 * honours only if the arrival instants increase strictly, so they are
6557 * nudged by one ulp where `qage` ties or disagrees with `order`.
6558 */
6559 if (init_jobs_on) {
6560 const Matrix<double>& J = o.init_jobs;
6561 if (J.cols() < 7)
6562 throw InputError("SolverLDES (native engine): init_jobs needs the columns [station, class, "
6563 "remaining, elapsed, qage, sage, order(, id)], got " +
6564 std::to_string(J.cols()) + " columns");
6565 std::vector<std::size_t> rows(J.rows());
6566 std::iota(rows.begin(), rows.end(), std::size_t(0));
6567 std::stable_sort(rows.begin(), rows.end(), [&](std::size_t a, std::size_t b) {
6568 if (J(a, 0) != J(b, 0)) return J(a, 0) < J(b, 0);
6569 return J(a, 6) < J(b, 6);
6570 });
6571 std::size_t last_station = M;
6572 double last_arrival = -std::numeric_limits<double>::infinity();
6573 for (std::size_t row : rows) {
6574 const double sv = J(row, 0), kv = J(row, 1);
6575 if (!(sv >= 0.0 && sv < static_cast<double>(M) && kv >= 0.0 && kv < static_cast<double>(K)))
6576 throw InputError("SolverLDES (native engine): init_jobs row " + std::to_string(row) +
6577 " names station " + std::to_string(sv) + ", class " + std::to_string(kv) +
6578 "; the model has " + std::to_string(M) + " stations and " +
6579 std::to_string(K) + " classes");
6580 const std::size_t i = static_cast<std::size_t>(sv), k = static_cast<std::size_t>(kv);
6581 if (S[i].role != Role::Queue && S[i].role != Role::Delay)
6582 throw InputError("SolverLDES (native engine): init_jobs row " + std::to_string(row) +
6583 " places a job at station '" + sn.stations[i].name +
6584 "', which is not a Queue or Delay");
6585 job_state_check(i);
6586 const double remaining = J(row, 2), el = J(row, 3), qage = J(row, 4), sage = J(row, 5);
6587 if (!(el >= 0.0 && qage >= 0.0 && sage >= qage))
6588 throw InputError("SolverLDES (native engine): init_jobs row " + std::to_string(row) +
6589 " needs elapsed >= 0 and sage >= qage >= 0");
6590 Job job;
6591 job.cls = k;
6592 job.t_sys = now - sage;
6593 job.sys_cls = static_cast<int>(k);
6594 if (i != last_station) {
6595 last_station = i;
6596 last_arrival = -std::numeric_limits<double>::infinity();
6597 }
6598 job.t_arr = std::max(now - qage,
6599 std::nextafter(last_arrival, std::numeric_limits<double>::infinity()));
6600 last_arrival = job.t_arr;
6601 job.ext = (J.cols() >= 8) ? static_cast<std::int64_t>(J(row, 7)) : -1;
6602 if (remaining > 0.0) {
6603 job.service = remaining;
6604 } else if (remaining == -2.0) {
6605 const int max_tries = 1000000;
6606 int t = 0;
6607 for (; t < max_tries; ++t) {
6608 const double v = S[i].svc[k].next_at(g_svc[i][k], now);
6609 if (v > el) {
6610 job.service = v - el;
6611 break;
6612 }
6613 }
6614 if (t == max_tries)
6615 throw InputError("SolverLDES (native engine): init_jobs could not draw a residual for "
6616 "class '" + sn.classes[k].name + "' with elapsed = " +
6617 std::to_string(el) + " (P(S > elapsed) is below 1e-6); give it explicitly");
6618 } else if (remaining != -1.0) {
6619 throw InputError("SolverLDES (native engine): init_jobs row " + std::to_string(row) +
6620 " has remaining = " + std::to_string(remaining) +
6621 "; use a positive residual, -1 (draw a full service) or -2 (draw given elapsed)");
6622 }
6623 if (job.service > 0.0) {
6624 job.preset = true;
6625 job.remaining = job.service;
6626 job.elapsed = el;
6627 }
6628 pending_preset = true;
6629 if (!admit(i, job, M))
6630 throw InputError("SolverLDES (native engine): init_jobs row " + std::to_string(row) +
6631 " does not fit station '" + sn.stations[i].name + "'");
6632 }
6633 for (std::size_t r = 0; r < K; ++r) {
6634 if (sn.classes[r].type == lang::JobClassType::OPEN) continue;
6635 double held = 0.0;
6636 for (std::size_t i = 0; i < M; ++i) held += acc.qlen[i][r];
6637 const double want = sn.classes[r].population;
6638 if (std::fabs(held - want) > 0.5)
6639 throw InputError("SolverLDES (native engine): init_jobs holds " +
6640 std::to_string(static_cast<long>(held + 0.5)) + " jobs of class '" +
6641 sn.classes[r].name + "' against a population of " +
6642 std::to_string(static_cast<long>(want + 0.5)));
6643 }
6644 }
6645 // The placement is `init_sol` when given, else the model's declared initial state.
6646 const std::vector<double> placement =
6647 init_jobs_on ? std::vector<double>()
6648 : (!o.init_sol.empty() ? o.init_sol : ldes_declared_placement(sn));
6649 const bool warm_start = !init_jobs_on && !placement.empty() && place_nodes.empty();
6650 if (warm_start) {
6651 for (std::size_t i = 0; i < M; ++i) {
6652 if (S[i].role != Role::Queue && S[i].role != Role::Delay) continue;
6653 for (std::size_t k = K; k-- > 0;) {
6654 const std::size_t idx = i * K + k;
6655 if (idx >= placement.size()) continue;
6656 const double v = placement[idx];
6657 if (!(v > 0.0)) continue;
6658 const std::size_t count = static_cast<std::size_t>(v);
6659 for (std::size_t j = 0; j < count; ++j) {
6660 Job job;
6661 job.cls = k;
6662 job.t_sys = 0.0;
6663 job.sys_cls = static_cast<int>(k);
6664 if (!admit(i, job, M))
6665 throw InputError("SolverLDES (native engine): the warm-start placement "
6666 "of class '" + sn.classes[k].name + "' does not fit "
6667 "station '" + sn.stations[i].name + "'");
6668 }
6669 }
6670 }
6671 // A closed class must be placed in full: a warm start that loses jobs is
6672 // a different model, and the loss is invisible in every mean it reports.
6673 for (std::size_t r = 0; r < K; ++r) {
6674 if (sn.classes[r].type == lang::JobClassType::OPEN) continue;
6675 double held = 0.0;
6676 for (std::size_t i = 0; i < M; ++i) held += acc.qlen[i][r];
6677 const double want = sn.classes[r].population;
6678 if (std::fabs(held - want) > 0.5)
6679 throw InputError("SolverLDES (native engine): the warm-start placement holds " +
6680 std::to_string(static_cast<long>(held + 0.5)) + " jobs of class '" +
6681 sn.classes[r].name + "' against a population of " +
6682 std::to_string(static_cast<long>(want + 0.5)));
6683 }
6684 }
6685 // Every breakdown-carrying station starts UP with its first failure armed,
6686 // which is the reference's initial condition: a model that started down
6687 // would report a transient nobody asked for.
6688 for (std::size_t i = 0; i < M; ++i) {
6689 if (!S[i].has_breakdown) continue;
6690 Event e;
6691 e.t = S[i].failure_time.next_at(g_aux[i], 0.0);
6692 e.kind = EV_BREAKDOWN;
6693 e.station = i;
6694 push(e);
6695 }
6696
6697 std::vector<Sampler> arrival(K);
6698 std::vector<double> lambda(K, 0.0);
6699 // `Source.setArrivalBatch`: a batch-size law bolted onto a renewal stream, drawn
6700 // alongside the interarrival time and consumed by the release loop below. It is
6701 // the SEPARATE mechanism from a process that carries its own sizes -- the two are
6702 // refused together above -- and it rides a stream of its own on the reference's
6703 // own `seed + 991*(srcIdx+1) + 97*(k+1)` band, so adding a batch law to a model
6704 // does not shift any other draw. The LAW matches the reference; the sample path
6705 // does not, because the reference inverts its discrete families off
6706 // java.util.Random and these invert off the MRG stream.
6707 std::vector<Sampler> arr_batch(K);
6708 std::vector<bool> has_arr_batch(K, false);
6709 std::vector<Rng> g_arr_batch;
6710 g_arr_batch.reserve(K);
6711 for (std::size_t k = 0; k < K; ++k)
6712 g_arr_batch.push_back(Rng(seed_ll, 991LL + 97LL * (static_cast<long long>(k) + 1LL)));
6713 if (source_st < M) {
6714 const auto& sb = sn.stations[source_st].arrival_batch;
6715 for (std::size_t r = 0; r < K && r < sb.size(); ++r) {
6716 if (sb[r].disabled) continue;
6717 arr_batch[r] = Sampler(sb[r], "the arrival batch of class '" + sn.classes[r].name +
6718 "' at station '" + sn.stations[source_st].name + "'");
6719 has_arr_batch[r] = true;
6720 }
6721 }
6722
6723 // ---- the Source's mark -> class binding -------------------------------
6724 //
6725 // `marked_classes` is 1-based and ordered by mark, so mark k names class
6726 // `mark_class[k-1]` in the 0-based form used here. The FIRST marked class is the
6727 // CARRIER: only its stream is armed, and every arrival it produces is routed to
6728 // the class its mark names. The other marked classes share the one modulating
6729 // chain and must NOT arm streams of their own, or the model would run K
6730 // independent copies of the process instead of one marked process. This mirrors
6731 // `Solver_ssj`'s markedGroupClass / markedCarrierClass.
6732 //
6733 // Their SOURCE THROUGHPUT is the per-mark rate pie*D1k*e, not the aggregate: the
6734 // whole binding shares one Distrib, so `1/mean()` would report the total stream
6735 // K times over.
6736 std::vector<std::size_t> mark_class;
6737 std::vector<double> mark_rate;
6738 std::size_t mark_carrier = K;
6739 if (source_st < M) {
6740 for (std::size_t c : sn.stations[source_st].marked_classes)
6741 if (c >= 1 && c <= K) mark_class.push_back(c - 1);
6742 }
6743 /**
6744 * The width-weighted time average of one segment list, i.e. the nominal block.
6745 *
6746 * `sched_dist` builds the nominal D0/D1 this way and `mmapt` the nominal per-mark
6747 * blocks; this is the same average applied to a (mark, batch) list, which nothing
6748 * stores because `Dmark` carries the MARK reading for a BMMAPt.
6749 */
6750 auto nominal_of = [](const std::vector<T>& bp, const std::vector<Matrix<T>>& segs) {
6751 const T zero = num_traits<T>::from_int(0);
6752 Matrix<T> acc(segs[0].rows(), segs[0].cols(), zero);
6753 T total = zero;
6754 for (std::size_t k = 0; k + 1 < bp.size(); ++k) total += T(bp[k + 1] - bp[k]);
6755 for (std::size_t k = 0; k < segs.size(); ++k) {
6756 const T w = T(T(bp[k + 1] - bp[k]) / total);
6757 for (std::size_t a = 0; a < acc.rows(); ++a)
6758 for (std::size_t b = 0; b < acc.cols(); ++b) acc(a, b) += w * segs[k](a, b);
6759 }
6760 return acc;
6761 };
6762 /**
6763 * JOBS PER EPOCH of an arrival process that carries its own batch sizes, and 1.0
6764 * for one that does not.
6765 *
6766 * A batch epoch is ONE EVENT and `b` JOBS, so the Source row of TN -- which is
6767 * analytic here, not counted -- has to report the JOB rate or it will not balance
6768 * against the counted throughput of the stations downstream. Getting this wrong
6769 * reads an M[3]/M/2 as an M/M/2 at a third of the task rate, which is exactly the
6770 * failure the old `arrival_batch` refusal existed to prevent. An unbatched
6771 * process returns 1.0, so every existing model's Source row is untouched.
6772 */
6773 auto mean_batch_of = [&](const lang::Distrib<T>& cd) -> double {
6774 std::vector<Matrix<T>> blocks;
6775 std::vector<std::size_t> sizes;
6776 if (cd.type == lang::ProcessType::BMAP) {
6777 for (std::size_t b = 0; b < cd.Dmark.size(); ++b) {
6778 blocks.push_back(cd.Dmark[b]);
6779 sizes.push_back(b + 1);
6780 }
6781 } else if (cd.has_batch_schedule()) {
6782 for (std::size_t c = 0; c < cd.sched_Dbatch.size(); ++c)
6783 for (std::size_t b = 0; b < cd.sched_Dbatch[c].size(); ++b) {
6784 blocks.push_back(nominal_of(cd.sched_bp, cd.sched_Dbatch[c][b]));
6785 sizes.push_back(b + 1);
6786 }
6787 }
6788 if (blocks.empty()) return 1.0;
6789 mam::Mmap<T> mm;
6790 mm.D0 = cd.D0;
6791 mm.D1 = cd.D1;
6792 mm.Dc = blocks;
6793 const std::vector<T> lam = mam::mmap_lambda(mm);
6794 double epochs = 0.0, jobs = 0.0;
6795 for (std::size_t b = 0; b < blocks.size(); ++b) {
6796 const double v = num_traits<T>::to_double(lam[b]);
6797 epochs += v;
6798 jobs += static_cast<double>(sizes[b]) * v;
6799 }
6800 return (epochs > 0.0) ? (jobs / epochs) : 1.0;
6801 };
6802 if (!mark_class.empty()) {
6803 mark_carrier = mark_class[0];
6804 const lang::Distrib<T>& cd = sn.service[source_st][mark_carrier];
6805 if (cd.Dmark.size() < mark_class.size())
6806 throw InputError("SolverLDES (native engine): the Source binds " +
6807 std::to_string(mark_class.size()) +
6808 " marks but its arrival process carries only " +
6809 std::to_string(cd.Dmark.size()) + " marked blocks");
6810 if (cd.has_batch_schedule()) {
6811 // A BMMAPt's per-mark JOB rate, sum_b b * theta * D_(c,b) * e. Through the
6812 // same `mmap_lambda` as the unbatched case, on the (mark, batch) nominals
6813 // flattened mark-major: the weighting is by the STATIONARY phase
6814 // distribution and must not be re-implemented per axis.
6815 const std::size_t B = cd.sched_Dbatch[0].size();
6816 std::vector<Matrix<T>> blocks;
6817 for (std::size_t c = 0; c < cd.sched_Dbatch.size(); ++c)
6818 for (std::size_t b = 0; b < B; ++b)
6819 blocks.push_back(nominal_of(cd.sched_bp, cd.sched_Dbatch[c][b]));
6820 mam::Mmap<T> mm;
6821 mm.D0 = cd.D0;
6822 mm.D1 = cd.D1;
6823 mm.Dc = blocks;
6824 const std::vector<T> lam = mam::mmap_lambda(mm);
6825 for (std::size_t k = 0; k < mark_class.size(); ++k) {
6826 double jobs = 0.0;
6827 for (std::size_t b = 0; b < B; ++b)
6828 jobs += static_cast<double>(b + 1) *
6829 num_traits<T>::to_double(lam[k * B + b]);
6830 mark_rate.push_back(jobs);
6831 }
6832 } else {
6833 mam::Mmap<T> mm;
6834 mm.D0 = cd.D0;
6835 mm.D1 = cd.D1;
6836 mm.Dc = cd.Dmark;
6837 const std::vector<T> lam = mam::mmap_lambda(mm);
6838 for (std::size_t k = 0; k < mark_class.size(); ++k)
6839 mark_rate.push_back(num_traits<T>::to_double(lam[k]));
6840 }
6841 }
6842 // True for a marked class that is not the carrier.
6843 const std::vector<std::size_t>& mkc = mark_class;
6844 auto marked_non_carrier = [&mkc, &mark_carrier](std::size_t r) {
6845 if (mkc.empty() || r == mark_carrier) return false;
6846 for (std::size_t c : mkc)
6847 if (c == r) return true;
6848 return false;
6849 };
6850
6851 for (std::size_t r = 0; r < K; ++r) {
6852 if (sn.classes[r].type == lang::JobClassType::OPEN) {
6853 if (source_st >= M)
6854 throw InputError("SolverLDES (native engine): an open class with no Source");
6855 if (S[source_st].off[r]) continue;
6856 arrival[r] = S[source_st].svc[r];
6857 // The EPOCH rate, scaled to a JOB rate by the mean batch each epoch
6858 // releases: its own, for a BMAP or BMMAPt, or the separate
6859 // `Source.setArrivalBatch` law. Both are 1 for an unbatched stream.
6860 lambda[r] = mean_batch_of(sn.service[source_st][r]) / arrival[r].mean();
6861 if (has_arr_batch[r]) lambda[r] = arr_batch[r].mean() / arrival[r].mean();
6862 for (std::size_t k = 0; k < mark_class.size(); ++k)
6863 if (mark_class[k] == r) lambda[r] = mark_rate[k];
6864 // A non-carrier receives its jobs through the carrier's arrivals.
6865 if (marked_non_carrier(r)) continue;
6866 Event e;
6867 e.t = sp_draw_arr(source_st, r, arrival[r], g_arr[r], 0.0);
6868 e.kind = EV_ARRIVAL;
6869 e.station = source_st;
6870 e.cls = r;
6871 push(e);
6872 }
6873 }
6874 // CLOSED CLASSES ARE INJECTED IN DESCENDING ORDER, as the warm-start path
6875 // above and the reference's `initClosedClassPopulations` do, so the job ids
6876 // and the job holding the server agree in sample paths and Logger traces.
6877 for (std::size_t r = K; r-- > 0;) {
6878 if (sn.classes[r].type != lang::JobClassType::OPEN) {
6879 if (warm_start || init_jobs_on) continue; // already placed from the warm start
6880 const double n = sn.classes[r].population;
6881 if (!(n >= 0.0) || !std::isfinite(n))
6882 throw InputError("SolverLDES (native engine): class '" + sn.classes[r].name +
6883 "' has a population that is not a finite count");
6884 const std::size_t refst = sn.classes[r].refstat;
6885 if (refst == 0 || refst > M)
6886 throw InputError("SolverLDES (native engine): class '" + sn.classes[r].name +
6887 "' has no reference station");
6888 // A CLOSED CLASS OF A PETRI NET IS ALREADY PLACED: its jobs are
6889 // TOKENS and they live in the initial marking, which the SPN section
6890 // above widened by exactly this population. Admitting them here as
6891 // well would both double the population and fail outright, since a
6892 // place serves no job through `admit` -- which is how every Petri
6893 // net reaching this engine used to die, queueing or not, under a
6894 // message about a station that "does not serve" the class.
6895 // `initClosedClassPopulations` skips the injection on a Place for
6896 // the same reason.
6897 if (sn.stations[refst - 1].nodetype == NodeType::Place) continue;
6898 const std::size_t count = static_cast<std::size_t>(n + 0.5);
6899 for (std::size_t j = 0; j < count; ++j) {
6900 Job job;
6901 job.cls = r;
6902 job.t_sys = 0.0;
6903 job.sys_cls = static_cast<int>(r);
6904 if (!admit(refst - 1, job, M))
6905 throw InputError("SolverLDES (native engine): the initial population of "
6906 "class '" + sn.classes[r].name +
6907 "' does not fit its reference station's capacity");
6908 }
6909 }
6910 }
6911
6912 // ---- convergence-based stopping -----------------------------------------
6913 Convergence cnvg;
6914 cnvg.init(M, K, o, max_events);
6915 std::vector<std::size_t> servers_of(M, 1);
6916 std::vector<bool> delay_of(M, false);
6917 std::vector<std::vector<bool>> off_of(M, std::vector<bool>(K, true));
6918 std::vector<std::vector<bool>> cnvg_lost(M, std::vector<bool>(K, false));
6919 for (std::size_t i = 0; i < M; ++i) {
6920 servers_of[i] = S[i].nservers;
6921 delay_of[i] = S[i].role == Role::Delay;
6922 for (std::size_t r = 0; r < K; ++r)
6923 off_of[i][r] = S[i].off[r] || S[i].role == Role::Source ||
6924 S[i].role == Role::Synchronization;
6925 }
6926 std::uint64_t last_cnvg_events = 0;
6927 bool converged = false;
6928
6929 // The initial tokens of a queueing place are queued, not deposited, so the
6930 // embedded queues have to be started before the net can settle: until a
6931 // token has been served it is in no depository and no output arc sees it.
6932 for (std::size_t p = 0; p < place_nodes.size(); ++p)
6933 if (qplace[p]) place_try_start(p);
6934 // The immediate modes settle the initial marking before any clock runs.
6935 spn_settle();
6936
6937 // PLACING THE INITIAL STATE IS NOT AN ARRIVAL. The closed populations, a warm
6938 // start and the settling firings above all go through `admit`, which counts
6939 // an arrival; the reference counts none of them (`arrivedCustomers` moves
6940 // only once `warmupDone`, which no filter sets before the initial state is
6941 // in place). MSER and the fixed reset hid the difference; under `--tranfilter
6942 // none` the reference station's AN read N/T above the JAR (closed 2026-11-14).
6943 for (std::size_t a = 0; a < M; ++a) std::fill(acc.arrived[a].begin(), acc.arrived[a].end(), 0.0);
6944
6945 // ---- MSER-5 and batch-means bookkeeping --------------------------------
6946 Observations obs(M, K, o.tranfilter == "mser5", o.mserbatch > 0 ? o.mserbatch : 5);
6947 for (std::size_t i = 0; i < M; ++i)
6948 if (S[i].role == Role::Source || S[i].role == Role::Synchronization) obs.in_mser[i] = 0;
6949 std::uint64_t mser_interval = max_events / 1000ULL;
6950 if (mser_interval < 1) mser_interval = 1;
6951 std::uint64_t last_mser_events = 0;
6952 // The arrival counters as the current event found them, armed only when the
6953 // event may trigger an observation (see `Observations::collect`).
6954 std::vector<std::vector<double>> arrived_at_event = acc.arrived;
6955
6956
6957 // ---- transient sampling and the joint-state histogram ---------------------
6958 /**
6959 * A TRANSIENT run is bounded by SIMULATED TIME, not by completions.
6960 *
6961 * `options.timespan = [t0, t1]` sets the horizon and the completion budget
6962 * is then ignored, exactly as the reference does: a transient trajectory is
6963 * a function of time, so stopping on an event count would end it at a
6964 * different instant on every path and make the series incomparable across
6965 * seeds.
6966 */
6967 const bool transient_run = o.has_timespan && std::isfinite(o.t1) && o.t1 > o.t0;
6968 const double horizon = transient_run ? o.t1 : std::numeric_limits<double>::infinity();
6969 // o.tranobs points when given, else ~1000: enough to draw and few enough that
6970 // the series is not itself a memory problem on a long horizon. Same default as the JAR.
6971 const double tran_points = (o.tranobs > 0) ? static_cast<double>(o.tranobs) : 1000.0;
6972 const double tran_interval = transient_run ? (o.t1 - o.t0) / tran_points : 0.0;
6973 double next_tran_sample = transient_run ? o.t0 + tran_interval : 0.0;
6974 double last_tran_time = transient_run ? o.t0 : 0.0;
6975 std::vector<double> tran_times;
6976 std::vector<std::vector<std::vector<double>>> tran_q(M, std::vector<std::vector<double>>(K));
6977 std::vector<std::vector<std::vector<double>>> tran_u(M, std::vector<std::vector<double>>(K));
6978 std::vector<std::vector<std::vector<double>>> tran_t(M, std::vector<std::vector<double>>(K));
6979 std::vector<std::vector<double>> last_tran_q(M, std::vector<double>(K, 0.0));
6980 std::vector<std::vector<double>> last_tran_b(M, std::vector<double>(K, 0.0));
6981 std::vector<std::vector<double>> last_tran_c(M, std::vector<double>(K, 0.0));
6982
6983 /**
6984 * The EXACT joint-state residence time, keyed by the aggregate state row.
6985 *
6986 * `histogram_space` plus `histogram_time` let a caller evaluate its own
6987 * reward on the empirical distribution, INCLUDING a nonlinear one:
6988 * E[r] = sum_s (t_s / sum t) r(state_s) is exact only because the residence
6989 * time of each distinct state is kept, which a trajectory of means cannot
6990 * reconstruct.
6991 */
6992 std::map<std::vector<int>, double> histogram;
6993 std::vector<std::pair<double, std::vector<int>>> trajectory;
6994 double hist_last = 0.0;
6995 // A transient run needs the state walk anyway; a steady-state one pays for
6996 // it only when asked.
6997 const bool want_traj = transient_run || o.export_trajectory;
6998 const bool want_hist = transient_run || o.export_histogram || want_traj;
6999
7000 auto joint_state = [&]() {
7001 std::vector<int> row(M * K, 0);
7002 for (std::size_t i = 0; i < M; ++i)
7003 for (std::size_t r = 0; r < K; ++r)
7004 row[i * K + r] = static_cast<int>(acc.qlen[i][r] + acc.held[i][r] + 0.5);
7005 return row;
7006 };
7007 auto hist_accumulate = [&]() {
7008 if (!want_hist) return;
7009 const double dt = now - hist_last;
7010 if (dt > 0.0) {
7011 const std::vector<int> row = joint_state();
7012 histogram[row] += dt;
7013 if (want_traj) trajectory.push_back(std::make_pair(hist_last, row));
7014 }
7015 hist_last = now;
7016 };
7017
7018 auto tran_sample = [&]() {
7019 const double dt = now - last_tran_time;
7020 tran_times.push_back(now);
7021 for (std::size_t i = 0; i < M; ++i)
7022 for (std::size_t r = 0; r < K; ++r) {
7023 if (dt > 0.0) {
7024 tran_q[i][r].push_back((acc.tot_qlen[i][r] - last_tran_q[i][r]) / dt);
7025 const double c = S[i].util_peak;
7026 tran_u[i][r].push_back(
7027 (S[i].role == Role::Delay)
7028 ? (acc.tot_qlen[i][r] - last_tran_q[i][r]) / dt
7029 : (acc.tot_busy[i][r] - last_tran_b[i][r]) / (dt * c));
7030 tran_t[i][r].push_back((acc.completed[i][r] - last_tran_c[i][r]) / dt);
7031 } else {
7032 tran_q[i][r].push_back(acc.qlen[i][r] + acc.held[i][r]);
7033 tran_u[i][r].push_back(0.0);
7034 tran_t[i][r].push_back(0.0);
7035 }
7036 last_tran_q[i][r] = acc.tot_qlen[i][r];
7037 last_tran_b[i][r] = acc.tot_busy[i][r];
7038 last_tran_c[i][r] = acc.completed[i][r];
7039 }
7040 last_tran_time = now;
7041 };
7042
7043 // ---- sample-path snapshots (`spSnapshot`) --------------------------------
7044 /**
7045 * The jobs held at every detailed station NOW, with the phase segment each one
7046 * has reached; `prev` carries the segments already reached, so a phase never
7047 * runs backwards across two snapshots. A station that is not detailed reports
7048 * its counts only. Reads the stations and changes nothing.
7049 */
7050 auto sp_snapshot = [&](double t, const sp::Snap* prev) -> sp::Snap {
7051 sp::Snap snap;
7052 snap.jobs.assign(M, std::vector<sp::Job>());
7053 snap.counts.assign(M, std::vector<int>(K, 0));
7054 std::map<std::uint64_t, const sp::Job*> prev_jobs;
7055 if (prev)
7056 for (const std::vector<sp::Job>& l : prev->jobs)
7057 for (const sp::Job& j : l) prev_jobs[j.key] = &j;
7058 auto prev_of = [&](std::uint64_t key) -> const sp::Job* {
7059 std::map<std::uint64_t, const sp::Job*>::const_iterator it = prev_jobs.find(key);
7060 return it == prev_jobs.end() ? nullptr : it->second;
7061 };
7062 for (std::size_t i = 0; i < M; ++i) {
7063 if (!spt.is_service[i]) continue;
7064 StationState& s = S[i];
7065 if (!spt.detail[i]) {
7066 for (std::size_t k = 0; k < K; ++k)
7067 snap.counts[i][k] = static_cast<int>(acc.qlen[i][k] + acc.held[i][k] + 0.5);
7068 continue;
7069 }
7070 std::vector<sp::Job>& jobs = snap.jobs[i];
7071 if (!s.buffer.empty()) {
7072 std::vector<Job> waiting(s.buffer);
7073 std::stable_sort(waiting.begin(), waiting.end(),
7074 [&s](const Job& a, const Job& b) { return s.cmp(b, a); });
7075 for (const Job& c : waiting) {
7076 sp::Job j;
7077 j.key = c.id;
7078 j.cls = c.cls;
7079 j.in_service = false;
7080 j.t0 = t;
7081 std::map<std::uint64_t, sp::ScriptP>::const_iterator it = spt.scripts.find(c.id);
7082 if (it != spt.scripts.end()) {
7083 j.script = it->second;
7084 } else if (c.service > 0.0) {
7085 j.script = spt.script_for(c.id, i, c.cls, c.service, t);
7086 }
7087 jobs.push_back(j);
7088 }
7089 }
7090 if (s.role == Role::Delay) {
7091 std::vector<const Job*> live;
7092 for (const Job& c : delay_live[i]) live.push_back(&c);
7093 std::stable_sort(live.begin(), live.end(), [](const Job* a, const Job* b) {
7094 if (a->t_arr != b->t_arr) return a->t_arr < b->t_arr;
7095 return a->t_sys < b->t_sys;
7096 });
7097 for (const Job* c : live) {
7098 sp::Job j;
7099 j.key = c->id;
7100 j.cls = c->cls;
7101 j.in_service = true;
7102 j.t0 = c->t_arr;
7103 j.att0 = 0.0;
7104 j.rate = 1.0;
7105 j.script = spt.script_for(c->id, i, c->cls, c->due - c->t_arr, t);
7106 const sp::Job* pj = prev_of(c->id);
7107 j.seg = j.script->seg_at(t - c->t_arr, (pj && pj->in_service) ? pj->seg : 0);
7108 jobs.push_back(j);
7109 }
7110 } else if (s.ps) {
7111 const std::vector<double> rates =
7112 s.ps_jobs.empty() ? std::vector<double>()
7113 : ps_shares(s.sched, s.ps_jobs, ps_servers(i), s.weight, K);
7114 const double dt = t - s.ps_last_update;
7115 for (std::size_t q = 0; q < s.ps_jobs.size(); ++q) {
7116 const PsJob& pc = s.ps_jobs[q];
7117 sp::Job j;
7118 j.key = pc.id;
7119 j.cls = pc.cls;
7120 j.in_service = true;
7121 j.script = spt.script_for(pc.id, i, pc.cls, pc.total, t);
7122 const double att = pc.total - (pc.remaining - rates[q] * dt);
7123 const sp::Job* pj = prev_of(pc.id);
7124 j.seg = j.script->seg_at(att, pj ? pj->seg : 0);
7125 j.t0 = t;
7126 j.att0 = att;
7127 j.rate = rates[q];
7128 jobs.push_back(j);
7129 }
7130 } else {
7131 std::vector<std::size_t> slots;
7132 for (std::size_t c = 0; c < s.server.size(); ++c)
7133 if (s.server_busy[c] && !(c < s.server_blocked.size() && s.server_blocked[c]))
7134 slots.push_back(c);
7135 std::stable_sort(slots.begin(), slots.end(), [&s](std::size_t a, std::size_t b) {
7136 if (s.server_start[a] != s.server_start[b]) return s.server_start[a] < s.server_start[b];
7137 if (s.server[a].t_arr != s.server[b].t_arr) return s.server[a].t_arr < s.server[b].t_arr;
7138 return s.server[a].t_sys < s.server[b].t_sys;
7139 });
7140 for (std::size_t c : slots) {
7141 const Job& job = s.server[c];
7142 const double start = s.server_start[c];
7143 sp::Job j;
7144 j.key = job.id;
7145 j.cls = job.cls;
7146 j.in_service = true;
7147 j.t0 = start;
7148 j.att0 = 0.0;
7149 j.rate = 1.0;
7150 j.script = spt.script_for(job.id, i, job.cls, (start + job.service) - start, t);
7151 const sp::Job* pj = prev_of(job.id);
7152 j.seg = j.script->seg_at(t - start, (pj && pj->in_service) ? pj->seg : 0);
7153 jobs.push_back(j);
7154 }
7155 }
7156 for (const sp::Job& j : jobs) snap.counts[i][j.cls] += 1;
7157 }
7158 spt.snap_sources(snap, t, prev);
7159 return snap;
7160 };
7161 auto sp_sampler_phase = [&](std::size_t i, std::size_t k) -> int { return S[i].svc[k].sp_phase(); };
7162
7163 /**
7164 * FIXED WARMUP, `--tranfilter fixed --warmupfrac f` (closed 2026-11-14).
7165 *
7166 * The reference's `resetStatistics`: once the counted completions reach
7167 * floor(maxEvents * f), every statistic restarts at that instant and the
7168 * run is measured from there (`getActualSimTime` = now - warmupEndTime).
7169 * The state (queues, jobs in service, cache contents, the marking) is kept;
7170 * the integrals, tallies and counters are zeroed, including the ones the
7171 * reference only starts counting once `warmupDone` holds (arrivals, drops,
7172 * balks, reneging, retrials, system completions, region and orbit
7173 * integrals), which is the same thing. An arrival the crossing completion
7174 * causes downstream belongs to the measured window, as in the reference,
7175 * whose check runs before the departing job is routed. The observation
7176 * series restarts too, so the confidence intervals read the post-warmup
7177 * run only. A transient run and the sample path take no warmup.
7178 */
7179 const bool fixed_warmup = !sp_on && !transient_run && o.tranfilter == "fixed";
7180 std::uint64_t warmup_threshold = [&]() -> std::uint64_t {
7181 const double th = static_cast<double>(max_events) * o.warmupfrac;
7182 return (th >= 1.0) ? static_cast<std::uint64_t>(th) : 1ULL;
7183 }();
7184 // The CLOCK arm of the same rule (2026-11-14), Solver_ssj's warmupDeadlineNanos:
7185 // with a wall-clock budget (--maxtime / options.timeout, whichever is smaller,
7186 // as armed above) warmup also ends at the first completion at which the same
7187 // fraction of THAT budget is spent, so a run its clock cuts short measures the
7188 // rest of what it simulated instead of keeping statistics from t = 0. Once the
7189 // deadline passes, the threshold drops to the next completion, which keeps the
7190 // pre-event arrival snapshot below exact. No budget leaves the event rule alone.
7191 const double warm_clock_budget = util::timeout_remaining();
7192 const bool has_warm_deadline = fixed_warmup && o.warmupfrac > 0.0 && std::isfinite(warm_clock_budget);
7193 const auto warm_deadline = std::chrono::steady_clock::now() +
7194 std::chrono::duration_cast<std::chrono::steady_clock::duration>(std::chrono::duration<double>(
7195 has_warm_deadline ? o.warmupfrac * std::max(warm_clock_budget, 0.0) : 0.0));
7196 std::uint64_t fixed_warmup_at = 0; ///< total_completions at the reset: later ones are measured
7197 bool fixed_warmup_done = false;
7198 double fixed_warmup_end = 0.0;
7199 std::vector<std::vector<double>> arrived_at_warmup = acc.arrived;
7200 std::vector<std::vector<double>> reply_passed_at_warmup = reply_passed;
7201 // The same pre-event snapshot for every counter the crossing completion can
7202 // move DOWNSTREAM of its own station, i.e. after the reference's reset point:
7203 // the job's own sink departure (system XN and CN) and a drop, balk or block
7204 // at the next station. The reference resets before routing, so those belong
7205 // to the measured window; zeroing them here put system XN/CN about 1e-5 off
7206 // the JAR under `fixed` (closed 2026-11-14).
7207 std::vector<double> sys_completed_at_warmup = sys_completed, sys_resp_sum_at_warmup = sys_resp_sum,
7208 sys_resp_cnt_at_warmup = sys_resp_cnt;
7209 std::vector<std::vector<double>> dropped_at_warmup = dropped, balked_at_warmup = balked,
7210 blocked_at_warmup = blocked_count;
7211 auto fixed_warmup_reset = [&]() {
7212 for (std::size_t a = 0; a < M; ++a) {
7213 if (S[a].ps) ps_advance(a);
7214 for (std::size_t r = 0; r < K; ++r) {
7215 acc.update_qlen(a, r, now);
7216 acc.update_busy(a, r, now);
7217 acc.tot_qlen[a][r] = 0.0;
7218 acc.tot_busy[a][r] = 0.0;
7219 acc.completed[a][r] = reply_passed[a][r] - reply_passed_at_warmup[a][r];
7220 acc.resp_sum[a][r] = 0.0;
7221 acc.resp_cnt[a][r] = 0.0;
7222 acc.resp_avg[a][r] = 0.0;
7223 acc.resp_m2[a][r] = 0.0;
7224 acc.join_dropped[a][r] = 0.0;
7225 acc.arrived[a][r] -= arrived_at_warmup[a][r];
7226 dropped[a][r] -= dropped_at_warmup[a][r];
7227 balked[a][r] -= balked_at_warmup[a][r];
7228 reneged[a][r] = 0.0;
7229 blocked_count[a][r] -= blocked_at_warmup[a][r];
7230 if (want_respt) resp_samples[a][r].clear();
7231 }
7232 StationState& sa = S[a];
7233 if (!sa.tot_orbit.empty()) {
7234 orbit_tick(a);
7235 std::fill(sa.tot_orbit.begin(), sa.tot_orbit.end(), 0.0);
7236 }
7237 std::fill(sa.retried.begin(), sa.retried.end(), 0.0);
7238 std::fill(sa.retrial_lost.begin(), sa.retrial_lost.end(), 0.0);
7239 }
7240 for (std::size_t r = 0; r < K; ++r) {
7241 sys_resp_sum[r] -= sys_resp_sum_at_warmup[r];
7242 sys_resp_cnt[r] -= sys_resp_cnt_at_warmup[r];
7243 sys_completed[r] -= sys_completed_at_warmup[r];
7244 }
7245 for (std::size_t p = 0; p < fj_pairs.size(); ++p)
7246 for (std::size_t r = 0; r < K; ++r) {
7247 fj_resp_sum[p][r] = 0.0;
7248 fj_resp_cnt[p][r] = 0.0;
7249 fj_release[p][r].clear();
7250 }
7251 for (Region& R : regions) {
7252 R.update(now);
7253 std::fill(R.tot_jobs.begin(), R.tot_jobs.end(), 0.0);
7254 std::fill(R.tot_weight.begin(), R.tot_weight.end(), 0.0);
7255 std::fill(R.tot_mem.begin(), R.tot_mem.end(), 0.0);
7256 std::fill(R.completed.begin(), R.completed.end(), 0.0);
7257 std::fill(R.resp_sum.begin(), R.resp_sum.end(), 0.0);
7258 std::fill(R.resp_cnt.begin(), R.resp_cnt.end(), 0.0);
7259 std::fill(R.dropped.begin(), R.dropped.end(), 0.0);
7260 }
7261 // Cache statistics restart; the contents are state and stay.
7262 for (auto& kv : caches) {
7263 CacheState& cs = kv.second;
7264 std::fill(cs.hits.begin(), cs.hits.end(), 0.0);
7265 std::fill(cs.misses.begin(), cs.misses.end(), 0.0);
7266 for (auto& row : cs.hits_per_list) std::fill(row.begin(), row.end(), 0.0);
7267 for (auto& row : cs.item_level_time) std::fill(row.begin(), row.end(), 0.0);
7268 cs.occ_last = now;
7269 std::fill(cs.delayed.begin(), cs.delayed.end(), 0.0);
7270 cs.delayed_wait = 0.0;
7271 cs.total_fetch_time = 0.0;
7272 cs.completed_fetches = 0.0;
7273 }
7274 bp.reset();
7275 // The observation series restarts at the reset, so the intervals read
7276 // the measured window only.
7277 obs.time.clear();
7278 for (std::size_t a = 0; a < M; ++a)
7279 for (std::size_t r = 0; r < K; ++r) {
7280 obs.qlen[a][r].clear();
7281 obs.qt[a][r].clear();
7282 obs.bt[a][r].clear();
7283 obs.cmp[a][r].clear();
7284 obs.drp[a][r].clear();
7285 obs.arv[a][r].clear();
7286 obs.last_qt[a][r] = 0.0;
7287 }
7288 for (std::size_t r = 0; r < K; ++r) obs.sys[r].clear();
7289 obs.last_time = now;
7290 last_mser_events = total_completions;
7291 fixed_warmup_end = now;
7292 fixed_warmup_done = true;
7293 fixed_warmup_at = total_completions;
7294 };
7295
7296 // ---- the event loop ----------------------------------------------------
7297 // The MSER observation and then the convergence check owed to the
7298 // completion that just ran, in the order `checkEventCountStop` takes them.
7299 // Returns true when the run has converged.
7300 auto observe_completion = [&]() -> bool {
7301 if ((total_completions - last_mser_events) >= mser_interval) {
7302 for (std::size_t a = 0; a < M; ++a) {
7303 if (S[a].ps) ps_advance(a);
7304 for (std::size_t r = 0; r < K; ++r) {
7305 acc.update_qlen(a, r, now);
7306 acc.update_busy(a, r, now);
7307 }
7308 }
7309 obs.collect(acc, now, arrived_at_event);
7310 obs.collect_system(sys_completed);
7311 last_mser_events = total_completions;
7312 }
7313 if (cnvg.enabled() && (total_completions - last_cnvg_events) >= cnvg.interval()) {
7314 for (std::size_t a = 0; a < M; ++a) {
7315 if (S[a].ps) ps_advance(a);
7316 for (std::size_t r = 0; r < K; ++r) {
7317 acc.update_qlen(a, r, now);
7318 acc.update_busy(a, r, now);
7319 }
7320 }
7321 // A class has lost a job unserved since the statistics were last
7322 // reset: the reference's `lostUnserved` counters, read mid-run.
7323 for (std::size_t a = 0; a < M; ++a)
7324 for (std::size_t r = 0; r < K; ++r)
7325 cnvg_lost[a][r] = last_lost[a][r] >= fixed_warmup_end;
7326 cnvg.observe(acc, servers_of, delay_of, cnvg_lost, now);
7327 last_cnvg_events = total_completions;
7328 if (cnvg.converged(off_of)) {
7329 converged = true;
7330 return true;
7331 }
7332 }
7333 return false;
7334 };
7335 while (!evq.empty() && (transient_run || total_completions < max_events)) {
7336 // THE OBSERVATIONS OF THE COMPLETION THAT JUST RAN, taken before the next
7337 // event is pulled. They used to sit at the foot of the loop, which every
7338 // `continue` after `++total_completions` jumped over (immediate feedback,
7339 // a parked synchronous call, a blocked hop ...), so those completions
7340 // were never observed and MSER truncated somewhere else. The reference
7341 // observes inside the completion (`checkEventCountStop`), and no
7342 // simulated time passes between there and here, so every integral reads
7343 // the same at either point (closed 2026-11-14).
7344 if (fixed_warmup && !fixed_warmup_done && total_completions >= warmup_threshold)
7345 fixed_warmup_reset();
7346 if (observe_completion()) break;
7347 // Between two events, so the state the loop leaves is a consistent one.
7348 if ((++wall_tick & 1023u) == 0 && util::timeout_exceeded()) {
7349 time_stopped = true;
7350 break;
7351 }
7352 if ((total_completions + 1 - last_mser_events) >= mser_interval) arrived_at_event = acc.arrived;
7353 if (has_warm_deadline && !fixed_warmup_done && warmup_threshold > total_completions + 1 &&
7354 std::chrono::steady_clock::now() >= warm_deadline)
7355 warmup_threshold = total_completions + 1;
7356 if (fixed_warmup && !fixed_warmup_done && total_completions + 1 >= warmup_threshold) {
7357 arrived_at_warmup = acc.arrived;
7358 reply_passed_at_warmup = reply_passed;
7359 sys_completed_at_warmup = sys_completed;
7360 sys_resp_sum_at_warmup = sys_resp_sum;
7361 sys_resp_cnt_at_warmup = sys_resp_cnt;
7362 dropped_at_warmup = dropped;
7363 balked_at_warmup = balked;
7364 blocked_at_warmup = blocked_count;
7365 }
7366 // Sample-path export (`spBoundary`): record what the event that just ran
7367 // changed, and the phase changes due before the next one, while the clock
7368 // still reads the epoch of the event that just ran.
7369 if (sp_on && !spt.done) {
7370 const int spr = spt.boundary(false, now, evq.top().t, sp_snapshot, sp_sampler_phase);
7371 if (spr == 1) break;
7372 if (spr == 2) {
7373 now = spt.stop_time;
7374 break;
7375 }
7376 }
7377 const Event ev = evq.top();
7378 if (transient_run && ev.t > horizon) break;
7379 evq.pop();
7380 now = ev.t;
7381
7382 // THE STATE IS WALKED BEFORE THE EVENT IS APPLIED, so the interval just
7383 // ended is charged to the state that held during it. A steady-state run
7384 // asked for the histogram takes the same walk and nothing else.
7385 if (want_hist) hist_accumulate();
7386 if (transient_run) {
7387 while (now >= next_tran_sample && next_tran_sample <= horizon) {
7388 const double save = now;
7389 now = next_tran_sample;
7390 for (std::size_t a = 0; a < M; ++a) {
7391 if (S[a].ps) ps_advance(a);
7392 for (std::size_t r = 0; r < K; ++r) {
7393 acc.update_qlen(a, r, now);
7394 acc.update_busy(a, r, now);
7395 }
7396 }
7397 tran_sample();
7398 next_tran_sample += tran_interval;
7399 now = save;
7400 }
7401 }
7402
7403 if (ev.kind == EV_BREAKDOWN) {
7404 // FREEZE AT THE OLD RATE, FLIP, RE-TIME AT THE NEW, in that order,
7405 // for the same reason sd_advance runs before a population change:
7406 // the rate in force over the elapsed interval is the one the OLD
7407 // state implied. The stale departures are neutralised by the tag.
7408 StationState& s = S[ev.station];
7409 if (s.ps)
7410 ps_advance(ev.station);
7411 else
7412 sd_advance(ev.station);
7413 s.up = !s.up;
7414 if (s.ps)
7415 ps_reschedule(ev.station);
7416 else
7417 sd_reschedule(ev.station);
7418 // The next transition is drawn from the clock now in force. A job
7419 // stalled by the outage has no departure event at all; the repair's
7420 // reschedule is what gives it one back, with its residual intact.
7421 // `next_at` returns a DURATION, not an instant: it takes `from`
7422 // only so a time-inhomogeneous family can read its own schedule.
7423 // Assigning it straight to `nxt.t` puts the next flip in the PAST,
7424 // which the loop pops immediately and re-arms -- an infinite
7425 // cascade at one simulated instant.
7426 Event nxt;
7427 nxt.t = now + (s.up ? s.failure_time.next_at(g_aux[ev.station], now)
7428 : s.repair_time.next_at(g_aux[ev.station], now));
7429 nxt.kind = EV_BREAKDOWN;
7430 nxt.station = ev.station;
7431 push(nxt);
7432 continue;
7433 }
7434
7435 if (ev.kind == EV_FIRING) {
7436 // A cancelled clock: its mode lost the enabling degree that ran it, or was resampled.
7437 if (ev.station >= transitions.size()) continue;
7438 std::vector<std::uint64_t>& live = spn_clocks[ev.station][ev.cls];
7439 const auto it = std::find(live.begin(), live.end(), ev.tag);
7440 if (it == live.end()) continue;
7441 live.erase(it);
7442 SpnTransition& tr = transitions[ev.station];
7443 const SpnMode& m = tr.modes[ev.cls];
7444 if (spn_enabled(m, flat_avail())) {
7445 spn_apply(m);
7446 tr.fired[ev.cls] += 1.0;
7447 ++total_completions;
7448 }
7449 spn_settle();
7450 continue;
7451 }
7452
7453 /**
7454 * A token finished its embedded service: it leaves the place's servers
7455 * for its depository, where the output arcs can take it.
7456 *
7457 * THE MARKING DOES NOT MOVE. The token is still at the place -- it has
7458 * only changed compartment -- so QN is untouched and only UN and the
7459 * arcs' view of the place change. The next waiting token is taken into
7460 * service before the net settles, which is `placeDepartureActions`.
7461 */
7462 if (ev.kind == EV_PLACE_SVC) {
7463 const std::size_t p = ev.station;
7464 const std::size_t r = ev.cls;
7465 const std::size_t ist = place_station[p];
7466 if (ist < M) {
7467 acc.update_busy(ist, r, now);
7468 place_insvc[p][r] -= 1.0;
7469 acc.busy[ist][r] = place_insvc[p][r];
7470 }
7471 --place_busy[p];
7472 avail[p][r] += 1.0;
7473 place_try_start(p);
7474 spn_settle();
7475 continue;
7476 }
7477
7478 if (ev.kind == EV_POLL_TIMER) {
7479 poll_timer_expired(ev.station, ev.tag);
7480 continue;
7481 }
7482
7483 if (ev.kind == EV_SWITCHOVER) {
7484 StationState& sp = S[ev.station];
7485 sp.poll_switching = false;
7486 if (sp.poll_ext) {
7487 // ev.cls is the POSITION the server reaches
7488 sp.poll_pos = ev.cls;
7489 sp.poll_at = sp.poll_ring[ev.cls];
7490 poll_ext_advance(ev.station, true);
7491 continue;
7492 }
7493 sp.poll_at = ev.cls;
7494 poll_open_visit(sp);
7495 bool work = false;
7496 for (const Job& j : sp.buffer)
7497 if (j.cls == sp.poll_at) {
7498 work = true;
7499 break;
7500 }
7501 if (work)
7502 poll_serve(ev.station);
7503 else
7504 poll_advance(ev.station);
7505 continue;
7506 }
7507
7508 if (ev.kind == EV_RETRIAL) {
7509 StationState& sr = S[ev.station];
7510 const std::size_t c = ev.cls;
7511 if (ev.tag == 0) sr.const_pending[c] = false; // the CONSTANT policy's shared clock
7512 std::deque<Job>& ob = sr.orbit[c];
7513 std::size_t at = ob.size();
7514 if (ev.tag == 0) {
7515 if (!ob.empty()) at = 0;
7516 } else {
7517 for (std::size_t j = 0; j < ob.size(); ++j)
7518 if (ob[j].id == ev.tag) {
7519 at = j;
7520 break;
7521 }
7522 }
7523 if (at == ob.size()) continue; // the job abandoned the orbit meanwhile
7524 if (retrial_server_free(ev.station, c)) {
7525 const Job job = ob[at];
7526 orbit_leave(ev.station, c, at, false);
7527 sr.retried[c] += 1.0;
7528 // It decided to join long ago, so it does not balk; it is already
7529 // in the station population, so admit does not count it again.
7530 pending_retry = true;
7531 pending_orbit_exit = true;
7532 admit(ev.station, job, M);
7533 } else {
7534 ob[at].attempts += 1;
7535 if (sr.max_attempts[c] > 0 && ob[at].attempts >= sr.max_attempts[c]) {
7536 orbit_leave(ev.station, c, at, true);
7537 sr.retrial_lost[c] += 1.0;
7538 dropped[ev.station][c] += 1.0;
7539 } else if (sr.retrial_policy[c] == 2) {
7540 // the shared clock goes round the orbit, oldest first
7541 const Job jb = ob[at];
7542 ob.erase(ob.begin() + static_cast<std::ptrdiff_t>(at));
7543 ob.push_back(jb);
7544 } else {
7545 arm_retrial(ev.station, c, ob[at].id);
7546 }
7547 }
7548 if (sr.retrial_policy[c] == 2) arm_retrial(ev.station, c, 0);
7549 continue;
7550 }
7551
7552 if (ev.kind == EV_ORBIT_ABANDON) {
7553 StationState& sr = S[ev.station];
7554 const std::size_t c = ev.cls;
7555 std::deque<Job>& ob = sr.orbit[c];
7556 std::size_t at = ob.size();
7557 for (std::size_t j = 0; j < ob.size(); ++j)
7558 if (ob[j].id == ev.tag) {
7559 at = j;
7560 break;
7561 }
7562 if (at == ob.size()) continue; // it reached a server first
7563 orbit_leave(ev.station, c, at, true);
7564 dropped[ev.station][c] += 1.0;
7565 if (sr.retrial_policy[c] == 2) arm_retrial(ev.station, c, 0);
7566 continue;
7567 }
7568
7569 if (ev.kind == EV_SETUP) {
7570 // The end of one server's power timer. A tag that no longer matches
7571 // belongs to a delay-off an arrival cancelled.
7572 StationState& ss = S[ev.station];
7573 const std::size_t sl = ev.slot;
7574 if (sl >= ss.power_tag.size() || ss.power_tag[sl] != ev.tag) continue;
7575 if (ss.power[sl] == PW_DELAYOFF) {
7576 // `DelayoffCompletion`: the server shuts down.
7577 ss.power[sl] = PW_OFF;
7578 continue;
7579 }
7580 if (ss.power[sl] != PW_SETUP) continue;
7581 // `SetupCompletion`: the server is up and takes the head of the
7582 // queue; with nobody left (another server took them) it idles
7583 // ACTIVE, with no delay-off timer until it next serves a job.
7584 ss.power[sl] = PW_ACTIVE;
7585 if (buffer_has_for_slot(ev.station, sl)) {
7586 Job nextjob = buffer_pop_for_slot(ev.station, sl);
7587 start_service(ev.station, sl, nextjob);
7588 sd_reschedule(ev.station);
7589 }
7590 continue;
7591 }
7592
7593 if (ev.kind == EV_QUANTUM) {
7594 // ROUND ROBIN: the time slice of the job in `slot` has run out
7595 // (`Solver_ssj.rrQuantumExpiryActions`). A clock whose job has
7596 // departed, or whose slot has since started another job, finds a
7597 // different `rr_qtag` and is dropped. Otherwise the job is preempted
7598 // with its residual work (resume: the phase kept), rejoins the TAIL
7599 // of the waiting room, and the head enters service with a fresh
7600 // quantum -- the same job when it was alone. No switch overhead.
7601 const std::size_t qi = ev.station;
7602 StationState& sq = S[qi];
7603 if (!sq.rr || ev.slot >= sq.rr_qtag.size() || sq.rr_qtag[ev.slot] != ev.tag ||
7604 !sq.server_busy[ev.slot] || sq.server_blocked[ev.slot])
7605 continue;
7606 sq.rr_qtag[ev.slot] = 0;
7607 // Integrate the residuals at the rate in force first, as before any
7608 // preemption; at a station with no dependence the rate is 1 and
7609 // `preempt` reads the served time off the start instant.
7610 sd_advance(qi);
7611 sq.server[ev.slot].order_time = now;
7612 preempt(qi, ev.slot);
7613 serve_next_on_slot(qi, ev.slot);
7614 continue;
7615 }
7616
7617 if (ev.kind == EV_RENEGE) {
7618 // The job abandons only if it is STILL WAITING. Having entered
7619 // service, departed, or been dropped all leave the timer with
7620 // nothing to find, which is the ordinary case and not an error.
7621 StationState& sr = S[ev.station];
7622 std::size_t at = sr.buffer.size();
7623 for (std::size_t j = 0; j < sr.buffer.size(); ++j)
7624 if (sr.buffer[j].id == ev.tag) {
7625 at = j;
7626 break;
7627 }
7628 if (at == sr.buffer.size()) continue;
7629 const std::size_t rc = sr.buffer[at].cls;
7630 sd_advance(ev.station);
7631 acc.update_qlen(ev.station, rc, now);
7632 acc.qlen[ev.station][rc] -= 1.0;
7633 bp.track(ev.station, rc, -1, now);
7634 if (sr.sched != SchedStrategy::FSP)
7635 jpq_remove_at(sr.buffer, at, sr.cmp);
7636 else
7637 sr.buffer.erase(sr.buffer.begin() + static_cast<std::ptrdiff_t>(at));
7638 reneged[ev.station][rc] += 1.0;
7639 last_lost[ev.station][rc] = now;
7640 sd_reschedule(ev.station);
7641 continue;
7642 }
7643
7644 if (ev.kind == EV_ARRIVAL) {
7645 // The mark of THIS arrival, read BEFORE the draw below overwrites it with
7646 // the next one's. Same ordering as `Solver_ssj`'s arrivalPendingMark, and
7647 // it is not cosmetic: reading it after the draw would label every job with
7648 // its successor's mark.
7649 const int mark = arrival[ev.cls].last_mark();
7650 // ... and the BATCH SIZE of this arrival, for the same reason and from
7651 // the same two sources: a BMAP or BMMAPt carries its own sizes in the
7652 // blocks that fired, while `Source.setArrivalBatch` is a separate law
7653 // drawn on its own stream. They are mutually exclusive, checked above.
7654 std::size_t batch = 1;
7655 if (arrival[ev.cls].batched()) {
7656 const int b = arrival[ev.cls].last_batch();
7657 if (b > 0) batch = static_cast<std::size_t>(b);
7658 } else if (has_arr_batch[ev.cls]) {
7659 const double sampled = arr_batch[ev.cls].next(g_arr_batch[ev.cls]);
7660 const double rounded = std::floor(sampled + 0.5);
7661 if (!(rounded >= 1.0) || std::fabs(sampled - rounded) > 1e-9)
7662 throw InputError(
7663 "SolverLDES (native engine): the arrival batch of class '" +
7664 sn.classes[ev.cls].name + "' sampled " + std::to_string(sampled) +
7665 ", which is not a positive integer; a batch-size law must be "
7666 "supported on {1,2,...}");
7667 batch = static_cast<std::size_t>(rounded);
7668 }
7669 Event nxt;
7670 const double gap = sp_draw_arr(ev.station, ev.cls, arrival[ev.cls], g_arr[ev.cls], now);
7671 // A non-cyclic schedule past its horizon yields NO further arrival:
7672 // the stream has ended, and re-arming it at rate zero would loop.
7673 if (!(gap > 0.0) && arrival[ev.cls].time_varying()) continue;
7674 nxt.t = now + gap;
7675 nxt.kind = EV_ARRIVAL;
7676 nxt.station = ev.station;
7677 nxt.cls = ev.cls;
7678 push(nxt);
7679
7680 // A marked Source routes on the mark: the event stays on the carrier
7681 // class, and the job that arrives belongs to the class the mark names.
7682 std::size_t arv_cls = ev.cls;
7683 if (mark > 0 && static_cast<std::size_t>(mark) <= mark_class.size())
7684 arv_cls = mark_class[static_cast<std::size_t>(mark) - 1];
7685
7686 // ONE EPOCH, `batch` JOBS, ALL OF THE SAME CLASS. The route is redrawn
7687 // per member, matching the reference's `selectDestination` inside its own
7688 // release loop: a batch that took one route for all of its members would
7689 // correlate their destinations, which is a different model wherever the
7690 // Source feeds more than one station.
7691 for (std::size_t b = 0; b < batch; ++b) {
7692 if (sp_on) spt.source_departure(ev.station, arv_cls);
7693 const RouteEntry e = draw_node_route(sn.station_to_node[ev.station], arv_cls);
7694 Job job;
7695 job.cls = e.cls;
7696 job.t_sys = now;
7697 job.sys_cls = static_cast<int>(arv_cls);
7698 deliver(e.node, job, M);
7699 }
7700 continue;
7701 }
7702
7703 // ---- a service completion ------------------------------------------
7704 const std::size_t i = ev.station;
7705 StationState& s = S[i];
7706 Job job;
7707
7708 /**
7709 * A BULK SERVER'S FIRING. One event, min(b, present) completions.
7710 *
7711 * TWO PHASES, and the order is load-bearing: every served job is removed
7712 * and recorded BEFORE any of them is routed, because a job routed back to
7713 * this same station would otherwise re-arm the clock while the remaining
7714 * count is still unsettled and the station would fire twice for one batch.
7715 * The Java engine's `batchServiceDepartureActions` has the same split for
7716 * the same reason.
7717 */
7718 if (s.bmsp) {
7719 if (s.bmsp_tag != ev.tag) continue; // a superseded firing
7720 const std::size_t r = s.bmsp_cls;
7721 const std::size_t want = s.bmsp_pending;
7722 std::vector<Job> served;
7723 for (std::size_t d = 0; d < want && !s.buffer.empty(); ++d)
7724 served.push_back(buffer_pop(i));
7725 for (std::size_t d = 0; d < served.size(); ++d) {
7726 const Job& sj = served[d];
7727 acc.update_qlen(i, sj.cls, now);
7728 acc.qlen[i][sj.cls] -= 1.0;
7729 bp.track(i, sj.cls, -1, now);
7730 acc.completed[i][sj.cls] += 1.0;
7731 acc.tally_resp(i, sj.cls, now - sj.t_arr + sj.region_wait);
7732 if (want_respt) resp_samples[i][sj.cls].push_back(now - sj.t_arr + sj.region_wait);
7733 ++total_completions;
7734 }
7735 // Re-arm while work remains, or idle the single server. The clock is
7736 // armed from THIS instant, which is what makes the schedule walk of a
7737 // BMMAPt clock exact: a bulk server runs continuously while non-empty.
7738 if (!s.buffer.empty()) {
7739 bmsp_arm(i);
7740 } else {
7741 acc.update_busy(i, r, now);
7742 if (acc.busy[i][r] > 0.0) acc.busy[i][r] -= 1.0;
7743 s.server_busy[0] = false;
7744 s.bmsp_tag = 0;
7745 }
7746 // Phase B: route the served jobs, now that the station's own state is
7747 // settled.
7748 for (std::size_t d = 0; d < served.size(); ++d) {
7749 const Job& sj = served[d];
7750 const RouteEntry re2 = draw_node_route(sn.station_to_node[i], sj.cls);
7751 if (region_of[i] >= 0) {
7752 const std::size_t rg = static_cast<std::size_t>(region_of[i]);
7753 const bool inside = !re2.sink && re2.station < M &&
7754 region_of[re2.station] == region_of[i];
7755 if (!inside) {
7756 regions[rg].update(now);
7757 regions[rg].leave(sj.cls);
7758 regions[rg].completed[sj.cls] += 1.0;
7759 release_region(rg);
7760 }
7761 }
7762 Job moved;
7763 moved.cls = re2.cls;
7764 moved.t_sys = sj.t_sys;
7765 moved.sys_cls = sj.sys_cls;
7766 moved.parent = sj.parent;
7767 moved.call = sj.call;
7768 deliver(re2.node, moved, i);
7769 }
7770 if (total_completions >= max_events) break;
7771 continue;
7772 }
7773
7774 if (s.role == Role::Delay) {
7775 job = ev.job;
7776 if (track_delay_jobs) {
7777 // The registry is the Delay's cancellation handle: no entry
7778 // means a signal already destroyed this job, and a generation
7779 // that no longer matches means a global dependence has re-timed
7780 // it. Serving the departure in either case would put a job back
7781 // into circulation that has already left, or left twice.
7782 std::size_t at = delay_live[i].size();
7783 for (std::size_t j = 0; j < delay_live[i].size(); ++j)
7784 if (delay_live[i][j].id == job.id) {
7785 at = j;
7786 break;
7787 }
7788 if (at == delay_live[i].size()) continue;
7789 if (delay_live[i][at].tag != ev.tag) continue;
7790 delay_live[i].erase(delay_live[i].begin() + static_cast<std::ptrdiff_t>(at));
7791 }
7792 } else if (s.ps) {
7793 ps_advance(i);
7794 std::size_t idx = s.ps_jobs.size();
7795 for (std::size_t j = 0; j < s.ps_jobs.size(); ++j)
7796 if (s.ps_jobs[j].tag == ev.tag) {
7797 idx = j;
7798 break;
7799 }
7800 // A superseded departure: the job it named has since been
7801 // rescheduled by a population change. Dropping it here is the
7802 // engine's substitute for cancelling the event.
7803 if (idx == s.ps_jobs.size()) continue;
7804 const PsJob& pj = s.ps_jobs[idx];
7805 job.cls = pj.cls;
7806 job.t_arr = pj.t_arr;
7807 job.region_wait = pj.region_wait;
7808 job.t_sys = pj.t_sys;
7809 job.sys_cls = pj.sys_cls;
7810 job.parent = pj.parent;
7811 job.ext = pj.ext;
7812 s.ps_jobs.erase(s.ps_jobs.begin() + static_cast<std::ptrdiff_t>(idx));
7813 } else if (s.pas) {
7814 // A stale aggregate clock: the list changed after it was armed, so
7815 // its total rate no longer describes the station.
7816 if (s.pas_tag != ev.tag || s.pas_list.empty()) continue;
7817 job = pas_complete(i);
7818 acc.update_busy(i, job.cls, now);
7819 if (acc.busy[i][job.cls] > 0.0) acc.busy[i][job.cls] -= 1.0;
7820 pas_reschedule(i);
7821 } else {
7822 // A preemption leaves its victim's departure in the list with no
7823 // way to cancel it; the tag mismatch is what neutralises it.
7824 if (!s.server_busy[ev.slot] || s.server_tag[ev.slot] != ev.tag) continue;
7825 // Round robin: the service ended first, so its quantum is cancelled.
7826 if (s.rr) s.rr_qtag[ev.slot] = 0;
7827 sd_advance(i);
7828 job = s.server[ev.slot];
7829 s.server_busy[ev.slot] = false;
7830 s.server_tag[ev.slot] = 0;
7831 const double freed = release_slots(i, ev.slot);
7832 acc.update_busy(i, job.cls, now);
7833 acc.busy[i][job.cls] -= freed;
7834 }
7835
7836 sd_advance(i);
7837 acc.update_qlen(i, job.cls, now);
7838 acc.qlen[i][job.cls] -= 1.0;
7839 bp.track(i, job.cls, -1, now);
7840 acc.completed[i][job.cls] += 1.0;
7841 acc.tally_resp(i, job.cls, now - job.t_arr + job.region_wait);
7842 if (want_respt) resp_samples[i][job.cls].push_back(now - job.t_arr + job.region_wait);
7843 ++total_completions;
7844 if (track_jobs && job.ext >= 0)
7845 job_departure_log.push_back({static_cast<double>(job.ext), static_cast<double>(i),
7846 static_cast<double>(job.cls), now});
7847
7848 if (s.ps) {
7849 if (s.lps_limit > 0 && !s.buffer.empty() && s.ps_jobs.size() < s.lps_limit) {
7850 Job nextjob = buffer_pop(i);
7851 PsJob pj;
7852 pj.cls = nextjob.cls;
7853 pj.priority = nextjob.priority;
7854 pj.t_arr = nextjob.t_arr;
7855 pj.region_wait = nextjob.region_wait;
7856 pj.t_sys = nextjob.t_sys;
7857 pj.sys_cls = nextjob.sys_cls;
7858 pj.total = nextjob.preset ? nextjob.elapsed + nextjob.service : nextjob.service;
7859 pj.remaining = nextjob.service;
7860 pj.parent = nextjob.parent;
7861 pj.ext = nextjob.ext;
7862 pj.id = nextjob.id;
7863 s.ps_jobs.push_back(pj);
7864 }
7865 ps_reschedule(i);
7866 }
7867
7868 const RouteEntry re = draw_node_route(sn.station_to_node[i], job.cls);
7869 const bool to_sink = re.sink;
7870 const std::size_t dst = re.station, dcls = re.cls;
7871
7872 /**
7873 * IMMEDIATE FEEDBACK: the completing job goes straight back into THE
7874 * SAME SERVER under the destination class, holding the slot instead of
7875 * re-queueing behind whoever is waiting.
7876 *
7877 * That is the whole content of the feature and it is not the same model
7878 * as a self-loop: a self-loop puts the job at the tail and lets the head
7879 * of the queue in, while feedback lets one job hold the server for as
7880 * many services as its routing keeps returning it. It also never leaves
7881 * the station, so it exits no region, releases no blocked upstream
7882 * server and is not a system completion.
7883 */
7884 const RouteEntry fb = has_immfeed ? resolve_forced_dest(re) : re;
7885 const std::size_t fcls = fb.cls;
7886 if (has_immfeed && !fb.sink && fb.station == i && s.role == Role::Queue && !s.ps &&
7887 !s.pas && ev.slot < s.nservers && fcls < sn.immfeed[i].size() && sn.immfeed[i][fcls]) {
7888 // The fed-back job never reaches `deliver`, so the Loggers it crossed record it here.
7889 if (!fb_loggers.empty()) {
7890 const std::uint64_t walk = log_walk_id++;
7891 for (std::size_t q = 0; q < fb_loggers.size(); ++q)
7892 log_passage(fb_loggers[q].first, fb_loggers[q].second, walk);
7893 }
7894 Job fed;
7895 fed.cls = fcls;
7896 fed.t_sys = job.t_sys;
7897 fed.sys_cls = job.sys_cls;
7898 fed.parent = job.parent;
7899 fed.t_arr = now;
7900 fed.priority = classprio[fcls];
7901 if (draw_at_arrival(i, fcls)) {
7902 fed.service = sp_draw_svc(i, fcls, s.svc[fcls], g_svc[i][fcls], now);
7903 fed.remaining = fed.service;
7904 fed.elapsed = 0.0;
7905 }
7906 fed.rank = g_siro.aux.next_double();
7907 fed.deadline = now + classdeadline[fcls];
7908 fed.id = ++job_id;
7909 sd_advance(i);
7910 acc.update_qlen(i, fcls, now);
7911 acc.qlen[i][fcls] += 1.0;
7912 // THE FED-BACK JOB IS AN ARRIVAL. It joins the station under its new
7913 // class, which is where `station_arrival` counts one, and both the
7914 // Java engine and SolverSSA report it: leaving it out halved AN on a
7915 // 50% self-loop (0.8036 -> 0.4006 against a reference 0.8001) and
7916 // turned AN < TN, which no station can do.
7917 acc.arrived[i][fcls] += 1.0;
7918 bp.track(i, fcls, +1, now);
7919 start_service(i, ev.slot, fed);
7920 sd_reschedule(i);
7921 if (total_completions >= max_events) break;
7922 continue;
7923 }
7924
7925 /**
7926 * A SYNCHRONOUS CALL PARKS THE SERVER. The completing job leaves for the
7927 * callee and its slot stays held until the matching reply comes back:
7928 * no waiter is promoted into it, and the time it spends held counts as
7929 * BUSY, because the server is unavailable and reporting it idle would
7930 * credit the station with capacity it does not have. That is the same
7931 * rule the BAS branch below applies for the same reason.
7932 *
7933 * A hop that ALREADY switched into the reply class is not a call: it is
7934 * the answer, and parking on it would wait for a reply to a reply.
7935 * That switch may not show on `dcls` yet -- see `resolve_final_cls` --
7936 * when the routing matrix moves this edge through a synthesized
7937 * ClassSwitch node, so the check resolves through it rather than
7938 * reading `dcls` directly.
7939 */
7940 if (has_sync_call && sync_reply[job.cls] < K &&
7941 !is_reply_signal[resolve_final_cls(re.node, dcls)] &&
7942 s.role == Role::Queue && !s.ps && !s.pas && ev.slot < s.nservers) {
7943 const std::uint64_t call = ++next_call;
7944 PendingCall pc;
7945 pc.station = i;
7946 pc.slot = ev.slot;
7947 pc.cls = job.cls;
7948 pc.since = now;
7949 pending_reply[call] = pc;
7950 s.server_held[ev.slot] = true;
7951 s.held_cls[ev.slot] = job.cls;
7952 acc.update_busy(i, job.cls, now);
7953 acc.busy[i][job.cls] += 1.0;
7954 // The parked caller is still a job AT THIS STATION for QLen (the reference's
7955 // currentBlockedServers), but not in `qlen`, which the admission and rate logic reads.
7956 acc.update_qlen(i, job.cls, now);
7957 acc.held[i][job.cls] += 1.0;
7958 Job moved;
7959 moved.cls = re.cls;
7960 moved.t_sys = job.t_sys;
7961 moved.sys_cls = job.sys_cls;
7962 moved.parent = job.parent;
7963 moved.call = call;
7964 deliver(re.node, moved, i);
7965 if (total_completions >= max_events) break;
7966 continue;
7967 }
7968
7969 // BLOCKING IS DECIDED BEFORE THE SLOT IS REUSED. If the destination is
7970 // full and declares BAS or BBS, this server keeps the completed job and
7971 // stops serving; taking the next waiting job first would let the station
7972 // run at full rate while its output is stopped, which is precisely the
7973 // behaviour blocking removes.
7974 if (!to_sink && dst < M && s.role == Role::Queue && !s.ps && ev.slot < s.nservers &&
7975 !dest_has_room(dst, dcls)) {
7976 const lang::DropStrategy rule = dest_policy(dst, dcls);
7977 if (rule == lang::DropStrategy::BAS || rule == lang::DropStrategy::BBS) {
7978 Job held = job;
7979 held.cls = dcls;
7980 s.server_blocked[ev.slot] = true;
7981 s.blocked_job[ev.slot] = held;
7982 s.blocked_dest[ev.slot] = dst;
7983 s.blocked_dest_cls[ev.slot] = dcls;
7984 // Charged to the DESTINATION it is queueing for, not to the
7985 // station whose server it occupies.
7986 // The blocked job IS part of the destination's queue length --
7987 // the reference's effectiveQueueLength adds basBlockedAtDest and
7988 // bbsBlockedAtDest to it -- so it is carried in `qlen` and the
7989 // counter beside it is bookkeeping, not a second population.
7990 acc.update_qlen(dst, dcls, now);
7991 acc.qlen[dst][dcls] += 1.0;
7992 S[dst].blocked_at[dcls] += 1.0;
7993 // The upstream server is BLOCKED, not idle. Utilization counts
7994 // blocking time as busy time (the reference divides
7995 // busy + blocking by the horizon), because the server is
7996 // unavailable either way and reporting it idle would credit the
7997 // station with capacity it does not have.
7998 acc.update_busy(i, job.cls, now);
7999 acc.busy[i][job.cls] += 1.0;
8000 blocked_count[i][job.cls] += 1.0;
8001 continue;
8002 }
8003 }
8004
8005 // ONLY NOW may the freed slot take the next waiting job: a slot that
8006 // blocked above must not also start serving, or the station holds two
8007 // jobs in one server and the blocked one is duplicated on release.
8008 if (s.polling) {
8009 // The controller decides what happens next, not the buffer order:
8010 // it may keep serving this buffer, or walk on under its budget.
8011 poll_serve(i);
8012 } else if (s.role == Role::Queue && !s.ps && !s.pas && !s.server_blocked.empty() &&
8013 ev.slot < s.nservers && !s.server_blocked[ev.slot] &&
8014 !s.server_held[ev.slot]) {
8015 serve_next_on_slot(i, ev.slot);
8016 sd_reschedule(i);
8017 }
8018 // THE FORK IDENTITY IS HANDED OVER, NOT COPIED. A continuation that
8019 // stands in for the trigger at a Join must take its sibling slot; if
8020 // the trigger kept it too, one fork would present two siblings and the
8021 // Join would release early and discard the second.
8022 std::uint64_t spawn_parent = 0;
8023 if (has_spawn && spawn_of[job.cls] < K && spawn_joins_at[spawn_of[job.cls]]) {
8024 spawn_parent = job.parent;
8025 job.parent = 0;
8026 }
8027 // THE REGION IS LEFT FIRST, AS IN THE JAVA ENGINE: the completing job gives up its slot, the phase-2
8028 // continuation (if any) is admitted into it, and only then is the job routed. A hop to another member of the
8029 // same region under the SAME class completes nothing and releases no waiter: admit re-gates it into the
8030 // slot it just freed. Any other hop completes, and the waiters parked on the region are released.
8031 const int dep_rg = region_of[i];
8032 if (dep_rg >= 0) {
8033 regions[static_cast<std::size_t>(dep_rg)].update(now);
8034 regions[static_cast<std::size_t>(dep_rg)].leave(job.cls);
8035 }
8036 // THE PHASE-2 CONTINUATION IS INJECTED HERE, after the completing job's release of its region slot and
8037 // before the job is routed or anything parked on the region is released: the continuation takes over the
8038 // slot the trigger just freed, ahead of the blocked queue, which is the order `maybeSpawnOnCompletion` is
8039 // called in.
8040 if (has_spawn && spawn_of[job.cls] < K) {
8041 const std::size_t scls = spawn_of[job.cls];
8042 Job spawned;
8043 spawned.cls = scls;
8044 spawned.t_sys = now;
8045 spawned.sys_cls = static_cast<int>(scls);
8046 // A continuation aimed at a Join stands in for the trigger at the
8047 // fork it belongs to (phase 2 at an AND-join branch tail), so it
8048 // inherits the fork identity rather than arriving as an orphan the
8049 // Join would discard.
8050 spawned.parent = spawn_parent;
8051 admit(i, spawned, M);
8052 }
8053 {
8054 Job moved;
8055 moved.cls = re.cls;
8056 moved.t_sys = job.t_sys;
8057 moved.sys_cls = job.sys_cls;
8058 moved.parent = job.parent;
8059 // The identity travels WITH the job, through the callee and back on
8060 // the reply: a call answered two stations downstream is still this
8061 // caller's call, and dropping the tag here would strand its server.
8062 moved.call = job.call;
8063 hop_old_cls = job.cls;
8064 hop_internal = false;
8065 deliver(re.node, moved, i);
8066 hop_old_cls = K;
8067 }
8068 // The verdict on the hop is admit's, which sees the station it really reaches: `re.station` is M when the
8069 // edge runs through a ClassSwitch node. A Fork, Join, Sink or signal destination has no region: a crossing.
8070 if (dep_rg >= 0) {
8071 const bool stays_inside = hop_internal;
8072 hop_internal = false;
8073 if (!stays_inside) {
8074 regions[static_cast<std::size_t>(dep_rg)].completed[job.cls] += 1.0;
8075 release_region(static_cast<std::size_t>(dep_rg));
8076 }
8077 }
8078 // THE FREED SERVER FOUND NOBODY WAITING: it enters its delay-off under
8079 // the DEPARTING class's law, as `departureActions` does when
8080 // `waitQueues` is empty. Decided after the job was routed, so a job
8081 // routed straight back here finds the server ACTIVE and idle, which is
8082 // where the reference's ordering (route, then free) leaves it too.
8083 if (s.has_setup && ev.slot < s.nservers && s.buffer.empty() &&
8084 s.power[ev.slot] == PW_ACTIVE && !s.server_busy[ev.slot] &&
8085 !s.server_blocked[ev.slot] && !s.server_held[ev.slot])
8086 power_down(i, ev.slot, job.cls);
8087 release_blocked(i);
8088
8089 if (total_completions >= max_events) break;
8090 }
8091 // THE COMPLETION THAT REACHED max_events IS OBSERVED TOO. The reference
8092 // takes the observation inside that completion before its stop test, so its
8093 // series holds max_events/interval entries; this loop leaves before the
8094 // observation at its head, and before 2026-11-14 every series was one entry
8095 // short, which showed as QNSamples/TNSamples one below the reference's.
8096 if (!transient_run && !converged && !time_stopped && total_completions >= max_events)
8097 (void)observe_completion();
8098
8099 // A fixed-warmup run its wall-clock budget stopped before any completion was
8100 // measured past the reset has nothing to report: its statistics are still the
8101 // warmup's or all zero, and both read as an answer. Solver_ssj.assertMeasuredSpan
8102 // raises the same error (the layered engines' rule, _kb/17).
8103 if (time_stopped && fixed_warmup &&
8104 (!fixed_warmup_done || total_completions <= fixed_warmup_at || !(now - fixed_warmup_end > 0.0)))
8105 throw NumericError(ErrorKind{"Timeout"},
8106 "SolverLDES: the wall-clock budget ran out after " + std::to_string(total_completions) +
8107 " completions, before any were measured past the fixed warmup; no valid partial result "
8108 "exists. Raise the budget (--maxtime / options.timeout).");
8109
8110 // The run ran dry (or stopped) before the recorder filled: one last boundary,
8111 // which on an empty event list also plays out the phases still scripted.
8112 if (sp_on && !spt.done) {
8113 const int spr = spt.boundary(!evq.empty(), now, std::numeric_limits<double>::infinity(), sp_snapshot,
8114 sp_sampler_phase);
8115 if (spr == 2) now = spt.stop_time;
8116 }
8117 // Close every open integral at the final instant.
8118 for (std::size_t i = 0; i < M; ++i) {
8119 if (S[i].ps) ps_advance(i);
8120 for (std::size_t r = 0; r < K; ++r) {
8121 acc.update_qlen(i, r, now);
8122 acc.update_busy(i, r, now);
8123 }
8124 }
8125
8126 bp.commit();
8127 // A fixed warmup has already restarted every statistic at its end, so the
8128 // window runs from there with nothing left to difference.
8129 Truncation tr = obs.truncate();
8130 if (fixed_warmup_done) {
8131 tr = Truncation();
8132 tr.warmup_end = fixed_warmup_end;
8133 }
8134 const double sim_time = now - tr.warmup_end;
8135 const double elapsed = tr.applied ? (now - obs.time[tr.index]) : sim_time;
8136 // Classes that lost jobs unserved INSIDE the measured window (post-truncation), as the JAR counts them post-warmup.
8137 const double t_meas = tr.applied ? obs.time[tr.index] : tr.warmup_end;
8138 std::vector<std::vector<bool>> lost_unserved(M, std::vector<bool>(K, false));
8139 for (std::size_t i = 0; i < M; ++i)
8140 for (std::size_t r = 0; r < K; ++r) lost_unserved[i][r] = last_lost[i][r] >= t_meas;
8141
8142 // ---- result -------------------------------------------------------------
8143 LdesResult res;
8144 res.nstations = M;
8145 res.nclasses = K;
8146 res.nchains = sn.nchains;
8147 for (std::size_t i = 0; i < M; ++i) res.station_names.push_back(sn.stations[i].name);
8148 for (std::size_t r = 0; r < K; ++r) res.class_names.push_back(sn.classes[r].name);
8149 res.QN = Matrix<double>(M, K, 0.0);
8150 res.UN = Matrix<double>(M, K, 0.0);
8151 res.RN = Matrix<double>(M, K, 0.0);
8152 res.TN = Matrix<double>(M, K, 0.0);
8153 res.CN = Matrix<double>(1, K, 0.0);
8154 res.XN = Matrix<double>(1, K, 0.0);
8155 res.AN = Matrix<double>(M, K, 0.0);
8156 res.WN = Matrix<double>(M, K, 0.0);
8157 // U per unit of T under the utilization law each row of UN is read against (S/c, S/peak, S/gd_peak at a delay),
8158 // which carries TNCI into UNCI as MATLAB's U = T*S/c does; 0 where no law applies.
8159 Matrix<double> u_law(M, K, 0.0);
8160
8161 for (std::size_t i = 0; i < M; ++i) {
8162 for (std::size_t r = 0; r < K; ++r) {
8163 if (S[i].role == Role::Source) {
8164 res.TN(i, r) = lambda[r];
8165 continue;
8166 }
8167 if (S[i].off[r]) continue;
8168 if (elapsed > 0.0) {
8169 const double q0 = tr.applied ? obs.qt[i][r][tr.index] : 0.0;
8170 const double b0 = tr.applied ? obs.bt[i][r][tr.index] : 0.0;
8171 const double c0 = tr.applied ? obs.cmp[i][r][tr.index] : 0.0;
8172 res.QN(i, r) = (acc.tot_qlen[i][r] - q0) / elapsed;
8173 res.TN(i, r) = (acc.completed[i][r] - c0) / elapsed;
8174 if (S[i].role == Role::Delay) {
8175 // An infinite server has no capacity to be busy against: the
8176 // reference reports the traffic intensity T/mu, which is what
8177 // SolverNC and SolverMVA return for a Delay. A GLOBAL
8178 // DEPENDENCE RE-TIMES THE THINK TIME TOO, so its declared
8179 // peak normalizes this row as well -- `solver_ctmc_analyzer`
8180 // runs the T/(mu*peak) division over EVERY station once a
8181 // handle is present, and there is no other peak a delay can
8182 // carry.
8183 res.UN(i, r) = res.TN(i, r) * S[i].class_mean[r] / S[i].gd_peak[r];
8184 u_law(i, r) = S[i].class_mean[r] / S[i].gd_peak[r];
8185 } else if (sn.stations[i].nodetype == NodeType::Place && !sn.is_queueing_place(i)) {
8186 // An ordinary Place is an INF station: U == Q, as SolverCTMC, SolverSSA and SolverNC report.
8187 res.UN(i, r) = res.QN(i, r);
8188 if (res.TN(i, r) > 0.0) u_law(i, r) = res.QN(i, r) / res.TN(i, r);
8189 } else if (S[i].has_cd || has_gd ||
8190 std::any_of(S[i].lld.begin(), S[i].lld.end(),
8191 [](double a) { return a != 1.0 && a > 0.0; })) {
8192 // A CLASS-, JOINT- OR GLOBALLY DEPENDENT STATION IS READ
8193 // THROUGH THE LAW, not the busy integral, which is what the
8194 // Java engine does (`getUtilization` returns
8195 // T/(mu*peakScaling) here). beta_r(n) and phi(n) scale the
8196 // RATE, so a busy server delivers beta*phi times the work;
8197 // the head-count integral would report the fraction of TIME
8198 // occupied and divide it by a peak that counts work, mixing
8199 // the two conventions in one number. A LOAD-DEPENDENT
8200 // station is read the same way (closed 2026-11-14): the
8201 // reference's `getUtilization` takes T/(mu*peak) whenever
8202 // `isLoadDependent` holds (some alpha(n) != 1). Under
8203 // residual rescaling no draw is discarded, so the
8204 // alpha-weighted busy integral and T*E[S]/peak agree in
8205 // expectation; the law is kept because it is the JAR's
8206 // reading and so matches it on one seed.
8207 //
8208 // THE PEAKS MULTIPLY, and the server count drops out as soon
8209 // as any of them is declared: that is `getPeakScaling` and
8210 // `solver_ssa_analyzer_serial`, which take the product of
8211 // whichever peaks the model declares. With only a global
8212 // dependence the peak is phi's alone; with a class or load
8213 // dependence beside it, `util_peak` already holds that
8214 // factor.
8215 const double base =
8216 (S[i].has_cd && r < S[i].cd_peak_class.size()) ? S[i].cd_peak_class[r]
8217 : (S[i].has_cd || !S[i].lld.empty()) ? S[i].util_peak : 1.0;
8218 const double peak = base * S[i].gd_peak[r];
8219 res.UN(i, r) =
8220 (peak > 0.0) ? res.TN(i, r) * S[i].class_mean[r] / peak : 0.0;
8221 if (peak > 0.0) u_law(i, r) = S[i].class_mean[r] / peak;
8222 } else {
8223 res.UN(i, r) = (acc.tot_busy[i][r] - b0) / (elapsed * S[i].util_peak);
8224 if (S[i].util_peak > 0.0) u_law(i, r) = S[i].class_mean[r] / S[i].util_peak;
8225 }
8226 }
8227 if (lost_unserved[i][r]) {
8228 // JOBS LEFT UNSERVED (reneging, G-network removal): the sojourn tally sees only the survivors, a biased
8229 // subset (G-queue lambda+ 0.5, lambda- 0.2, mu 1: ~1.476 against QN/TN = 1.7143), so RN is read by
8230 // Little's law on the completion throughput, the CTMC/SSA/MATLAB convention, as the JAR does (F87).
8231 res.RN(i, r) = (res.TN(i, r) > 0.0) ? res.QN(i, r) / res.TN(i, r) : 0.0;
8232 } else if (acc.resp_cnt[i][r] > 0.0) {
8233 // The Welford running mean, `Tally.average()`'s `curAverage`, not sum/count.
8234 res.RN(i, r) = acc.resp_avg[i][r];
8235 } else if (sn.stations[i].nodetype == NodeType::Place && res.TN(i, r) > 0.0) {
8236 // A PLACE MEASURES NO PER-TOKEN SOJOURN, so its response time is
8237 // read off Little's law, E[N]/X, which is what the reference
8238 // engine reports for a place and what JMT calls a place's
8239 // residence time. There is no per-token stamp to average: a
8240 // token is not a job passing through a service station, and at a
8241 // queueing place it may sit in the depository for as long as the
8242 // output transitions leave it there.
8243 res.RN(i, r) = res.QN(i, r) / res.TN(i, r);
8244 }
8245 // AN is the OFFERED rate, as `getArrivalRate` measures it: the
8246 // arrivals since the truncation point over the same window as TN; WN is the residence time, which for
8247 // this engine's single-visit accounting is the response time. Both
8248 // are part of the result contract every client reads, and leaving
8249 // them at zero reads as "no arrivals" rather than "not measured".
8250 const double a0 = tr.applied ? obs.arv[i][r][tr.index] : 0.0;
8251 if (elapsed > 0.0) res.AN(i, r) = (acc.arrived[i][r] - a0) / elapsed;
8252 res.WN(i, r) = res.RN(i, r);
8253 }
8254 }
8255 // Sample counts, on the reference's serviceStations (Queue and Delay rows
8256 // only) and by its getLDESResultTail rule: QN counts the observations past
8257 // the truncation index, TN and UN the rates differenced from them (one
8258 // fewer, none below two), RN the response-time observations. Before
8259 // 2026-11-14 the four matrices were never filled and the JSON reported zero
8260 // samples for every station.
8261 res.QNSamples = Matrix<double>(M, K, 0.0);
8262 res.UNSamples = Matrix<double>(M, K, 0.0);
8263 res.RNSamples = Matrix<double>(M, K, 0.0);
8264 res.TNSamples = Matrix<double>(M, K, 0.0);
8265 {
8266 const std::size_t tidx = tr.applied ? tr.index : 0;
8267 for (std::size_t i = 0; i < M; ++i) {
8268 const NodeType nt = sn.stations[i].nodetype;
8269 if (nt != NodeType::Queue && nt != NodeType::Delay) continue;
8270 for (std::size_t r = 0; r < K; ++r) {
8271 const std::size_t nq = obs.qlen[i][r].size();
8272 res.QNSamples(i, r) = static_cast<double>(nq > tidx ? nq - tidx : 0);
8273 const std::size_t nc = obs.cmp[i][r].size();
8274 const std::size_t post = nc > tidx ? nc - tidx : 0;
8275 const double rates = static_cast<double>(post >= 2 ? post - 1 : 0);
8276 res.TNSamples(i, r) = rates;
8277 res.UNSamples(i, r) = rates;
8278 res.RNSamples(i, r) = acc.resp_cnt[i][r];
8279 }
8280 }
8281 }
8282 // Sibling drops at a Join, on the Join rows only. Emitted whenever the model
8283 // HAS a fork-join, drops or none: a MEASURED zero is what a standard join
8284 // loses, and it is a better answer than the client's derived AN - K*TN,
8285 // which carries the finite-sample gap between the two rates. An absent
8286 // matrix means "this engine does not count", not "nothing was lost".
8287 if (!sn.fj.empty()) {
8288 res.DropRateJoin = Matrix<double>(M, K, 0.0);
8289 for (std::size_t i = 0; i < M; ++i)
8290 for (std::size_t r = 0; r < K; ++r) {
8291 const double d0 = tr.applied ? obs.drp[i][r][tr.index] : 0.0;
8292 if (elapsed > 0.0)
8293 res.DropRateJoin(i, r) = (acc.join_dropped[i][r] - d0) / elapsed;
8294 }
8295 }
8296 // The "forkJoin" block: FJRespT is the full sojourn tally (as RN), FJTput the releases after the truncation
8297 // point over the same window as TN, and FJQLen = FJTput * FJRespT by Little's law.
8298 if (!fj_pairs.empty()) {
8299 const std::size_t P = fj_pairs.size();
8300 res.FJQLen = Matrix<double>(P, K, 0.0);
8301 res.FJRespT = Matrix<double>(P, K, 0.0);
8302 res.FJTput = Matrix<double>(P, K, 0.0);
8303 const double t_trunc = tr.applied ? obs.time[tr.index] : -1.0;
8304 for (std::size_t p = 0; p < P; ++p) {
8305 res.fj_forks.push_back(sn.nodes[fj_pairs[p].first - 1].name);
8306 res.fj_joins.push_back(sn.nodes[fj_pairs[p].second - 1].name);
8307 for (std::size_t r = 0; r < K; ++r) {
8308 if (fj_resp_cnt[p][r] > 0.0) res.FJRespT(p, r) = fj_resp_sum[p][r] / fj_resp_cnt[p][r];
8309 double nrel = 0.0;
8310 for (double tr_k : fj_release[p][r])
8311 if (tr_k > t_trunc) nrel += 1.0;
8312 if (elapsed > 0.0) res.FJTput(p, r) = nrel / elapsed;
8313 res.FJQLen(p, r) = res.FJTput(p, r) * res.FJRespT(p, r);
8314 }
8315 }
8316 }
8317 for (std::size_t r = 0; r < K; ++r) {
8318 // AN OPEN CLASS THE SOURCE NEVER EMITS HAS NO SYSTEM METRICS: a class
8319 // reached only by class switching (a REPLY, a post-switch class) leaves
8320 // XN and CN at 0. MATLAB defines a class's XN as its rate through its
8321 // reference station, which for an open class is the Source, and the JAR
8322 // fills XN/CN only when that class's Source rate is positive. Completions
8323 // are credited to the ENTRY class (Job::sys_cls), so such a class gathers
8324 // none anyway; the guard also covers an init_jobs job seeded in it. The
8325 // engine used to credit the class a job LEAVES in. The threshold is
8326 // GlobalConstants::Zero, not 0: an Exp(0) Source stream is stored as
8327 // Exp.fitRate(0), i.e. at the rate Zero itself, which is the sentinel for
8328 // "no stream" (the JAR reads the raw sn.rates and sees 0 there).
8329 if (sn.classes[r].type == lang::JobClassType::OPEN &&
8330 !(lambda[r] > lang::GlobalConstants::Zero))
8331 continue;
8332 // The crossing count is differenced against the truncation point, so
8333 // numerator and denominator span the same MSER window, as Java's
8334 // mserWindowRate does for the same series (closed 2026-11-14: the count
8335 // used to run from time zero over a window that ran from the cut).
8336 if (tr.applied && tr.index < obs.sys[r].size()) {
8337 if (elapsed > 0.0) res.XN(0, r) = (sys_completed[r] - obs.sys[r][tr.index]) / elapsed;
8338 } else if (sim_time > 0.0) {
8339 res.XN(0, r) = sys_completed[r] / sim_time;
8340 }
8341 if (sys_resp_cnt[r] > 0.0) res.CN(0, r) = sys_resp_sum[r] / sys_resp_cnt[r];
8342 // A CLOSED class's system throughput is the TN row of its reference
8343 // station, so it is measured over the same MSER window as every other
8344 // rate. The crossing count above runs from time zero while sim_time runs
8345 // from the truncation point, which put closed2's XN 0.6% above the
8346 // reference station's own TN (closed 2026-11-14). The reference engine
8347 // reads the FIRST service station with a positive TN instead, which is
8348 // the same number whenever the reference station comes first (and not
8349 // otherwise, which is a defect on the JAR side).
8350 {
8351 const std::size_t rsq = sn.classes[r].refstat;
8352 if (std::isfinite(sn.classes[r].population) && rsq != 0 && rsq <= M &&
8353 (sn.stations[rsq - 1].nodetype == NodeType::Queue ||
8354 sn.stations[rsq - 1].nodetype == NodeType::Delay) &&
8355 res.TN(rsq - 1, r) > 0.0)
8356 res.XN(0, r) = res.TN(rsq - 1, r);
8357 }
8358 // A PETRI NET COMPLETES NOTHING AT A SINK AND CROSSES NO REFERENCE
8359 // STATION, because its tokens move by the firing rules and never pass
8360 // through `deliver`, so `sys_completed` stays at zero and the system
8361 // throughput of a closed net would be reported as none at all. It is the
8362 // token rate out of the class's reference PLACE, which is that row of TN
8363 // and is what the reference engine reports. CN is left alone: a token
8364 // carries no arrival stamp -- the marking is a count, not a queue of
8365 // identified jobs -- so there is no cycle time to average, and the
8366 // reference reports none either.
8367 const std::size_t rs = sn.classes[r].refstat;
8368 if (res.XN(0, r) == 0.0 && rs != 0 && rs <= M &&
8369 sn.stations[rs - 1].nodetype == NodeType::Place)
8370 res.XN(0, r) = res.TN(rs - 1, r);
8371 }
8372
8373 // ---- busy periods --------------------------------------------------------
8374 for (std::size_t ti = 0; ti < bp.targets().size(); ++ti) {
8376 out.name = bp.targets()[ti].name;
8377 out.stations = bp.targets()[ti].stations;
8378 out.job_class = bp.targets()[ti].job_class;
8379 for (std::size_t oi = 0; oi < static_cast<std::size_t>(bp.orders()); ++oi) {
8380 out.mean.push_back(bp.mean(ti, oi));
8381 out.count.push_back(bp.count(ti, oi));
8382 }
8383 res.busy_periods.push_back(out);
8384 }
8385
8386 // ---- transient trajectory and histogram -----------------------------------
8387 if (transient_run) {
8388 now = std::min(now, horizon);
8389 hist_accumulate();
8390 res.t = tran_times;
8391 res.QNt.assign(M, std::vector<Matrix<double>>(K));
8392 res.UNt.assign(M, std::vector<Matrix<double>>(K));
8393 res.TNt.assign(M, std::vector<Matrix<double>>(K));
8394 for (std::size_t i = 0; i < M; ++i)
8395 for (std::size_t r = 0; r < K; ++r) {
8396 const std::size_t n = tran_times.size();
8397 // Columns are [value, time], which is the layout the reference
8398 // emits and the clients read.
8399 Matrix<double> q(n, 2, 0.0), u(n, 2, 0.0), t(n, 2, 0.0);
8400 for (std::size_t k = 0; k < n; ++k) {
8401 q(k, 0) = tran_q[i][r][k];
8402 q(k, 1) = tran_times[k];
8403 u(k, 0) = tran_u[i][r][k];
8404 u(k, 1) = tran_times[k];
8405 t(k, 0) = tran_t[i][r][k];
8406 t(k, 1) = tran_times[k];
8407 }
8408 res.QNt[i][r] = q;
8409 res.UNt[i][r] = u;
8410 res.TNt[i][r] = t;
8411 }
8412 }
8413
8414 if (want_respt) {
8415 res.respTimeSamples.assign(M, std::vector<std::vector<double>>(K));
8416 for (std::size_t i = 0; i < M; ++i)
8417 for (std::size_t r = 0; r < K; ++r) res.respTimeSamples[i][r] = resp_samples[i][r];
8418 }
8419
8420 // ---- the joint-state histogram and the state path -------------------------
8421 // OUTSIDE the transient branch: a steady-state run that asked for either
8422 // fills it too, which is what `--export-histogram` and `--trajectory` mean.
8423 // The last interval is closed here, or the state the run ended in would
8424 // carry no residence time at all.
8425 if (want_hist && !transient_run) hist_accumulate();
8426 if (!histogram.empty()) {
8427 res.histogram_space = Matrix<double>(histogram.size(), M * K, 0.0);
8428 res.histogram_time = Matrix<double>(histogram.size(), 1, 0.0);
8429 std::size_t row = 0;
8430 for (const auto& kv : histogram) {
8431 for (std::size_t c = 0; c < kv.first.size(); ++c)
8432 res.histogram_space(row, c) = kv.first[c];
8433 res.histogram_time(row, 0) = kv.second;
8434 ++row;
8435 }
8436 }
8437 if (!trajectory.empty()) {
8438 res.traj_space = Matrix<double>(trajectory.size(), M * K, 0.0);
8439 res.traj_time = Matrix<double>(trajectory.size(), 1, 0.0);
8440 for (std::size_t k = 0; k < trajectory.size(); ++k) {
8441 for (std::size_t c = 0; c < trajectory[k].second.size(); ++c)
8442 res.traj_space(k, c) = trajectory[k].second[c];
8443 res.traj_time(k, 0) = trajectory[k].first;
8444 }
8445 }
8446
8447 // ---- cache metrics --------------------------------------------------------
8448 for (auto& kv : caches) {
8449 CacheState& cs = kv.second;
8451 cm.hit = Matrix<double>(1, K, 0.0);
8452 cm.miss = Matrix<double>(1, K, 0.0);
8453 // A DELAYED HIT IS ITS OWN OUTCOME, so it enters the denominator beside
8454 // the other two: with a retrieval system the three fractions partition
8455 // the reads, and dividing by hits + misses alone would report fractions
8456 // that sum above one.
8457 if (cs.has_retrieval) cm.delayed = Matrix<double>(1, K, 0.0);
8458 for (std::size_t r = 0; r < K; ++r) {
8459 const double dl = cs.has_retrieval ? cs.delayed[r] : 0.0;
8460 const double tot = cs.hits[r] + cs.misses[r] + dl;
8461 if (tot > 0.0) {
8462 cm.hit(0, r) = cs.hits[r] / tot;
8463 cm.miss(0, r) = cs.misses[r] / tot;
8464 if (cs.has_retrieval) cm.delayed(0, r) = dl / tot;
8465 }
8466 }
8467 // The measured retrieval latency: the total time requests WAITED on the
8468 // retrieval system, summed over BOTH populations that wait -- the one
8469 // that triggered the fetch and every request parked behind it -- and
8470 // averaged over ALL read requests, a hit waiting zero. A parked request
8471 // waits the RESIDUAL of the fetch period, not the whole of it, so
8472 // summing the fetch sojourns alone would read high where the fetch
8473 // period is not memoryless (6.5% on `retrieval_chain`, hypoexponential).
8474 //
8475 // ALL READS IS WHAT MAKES THE PAIR (ArvR, ResidT) MEAN ANYTHING.
8476 // `getAvgCacheTable` reports ArvR = lambda (hits + delayed + misses),
8477 // the read rate AT THE CACHE, so the residence time beside it must be
8478 // Little-consistent with that rate: E[N] = sum_i (phi_i + d_i) =
8479 // lambda * Z. That is the paper's eq. (latency tot), what the analytic
8480 // reference computes -- `retrieval_fpi_latency`'s
8481 // Z = sum(phi + d) / sum(lambda) -- and what `Solver_ssj.exportCacheResults`
8482 // measures. Reported only where measured.
8483 double reads = 0.0;
8484 if (cs.has_retrieval)
8485 for (std::size_t r = 0; r < K; ++r) reads += cs.hits[r] + cs.misses[r] + cs.delayed[r];
8486 if (reads > 0.0) {
8487 cm.latency = Matrix<double>(1, K, 0.0);
8488 const double mean_wait = (cs.total_fetch_time + cs.delayed_wait) / reads;
8489 for (std::size_t r = 0; r < K; ++r)
8490 cm.latency(0, r) = (cs.hits[r] + cs.misses[r] + cs.delayed[r] > 0.0)
8491 ? mean_wait
8492 : std::numeric_limits<double>::quiet_NaN();
8493 }
8494 // Per-list hits [classes x lists], over the same reads as `hit` (NaN on classes that never read),
8495 // the item position law [items x (lists+1)] as a time average with column 0 the not-cached share,
8496 // and the mean storage cost held per list, sum_i size_i * itemProb(i, l), when sizes are declared.
8497 // Transcribed from Solver_ssj.exportCacheResults.
8498 const std::size_t H = cs.lists.size();
8499 const double nan = std::numeric_limits<double>::quiet_NaN();
8500 cm.hitList = Matrix<double>(K, H, nan);
8501 for (std::size_t r = 0; r < K; ++r) {
8502 const double tot = cs.hits[r] + cs.misses[r] + (cs.has_retrieval ? cs.delayed[r] : 0.0);
8503 if (tot > 0.0)
8504 for (std::size_t l = 0; l < H; ++l) cm.hitList(r, l) = cs.hits_per_list[r][l] / tot;
8505 }
8506 cs.accumulate(now);
8507 cm.itemProb = Matrix<double>(cs.nitems, H + 1, nan);
8508 if (now > fixed_warmup_end) {
8509 for (std::size_t it = 0; it < cs.nitems; ++it) {
8510 double in_cache = 0.0;
8511 for (std::size_t l = 0; l < H; ++l) {
8512 const double p = cs.item_level_time[it][l] / (now - fixed_warmup_end);
8513 cm.itemProb(it, l + 1) = p;
8514 in_cache += p;
8515 }
8516 cm.itemProb(it, 0) = std::max(0.0, 1.0 - in_cache);
8517 }
8518 if (!cs.item_size.empty()) {
8519 cm.listCost = Matrix<double>(1, H, 0.0);
8520 for (std::size_t l = 0; l < H; ++l)
8521 for (std::size_t it = 0; it < cs.nitems; ++it)
8522 cm.listCost(0, l) += cs.size_of(it) * cm.itemProb(it, l + 1);
8523 }
8524 }
8525 res.cache_metrics[sn.nodes[cs.node - 1].name] = cm;
8526 }
8527
8528 // ---- finite capacity regions ---------------------------------------------
8529 if (!regions.empty()) {
8530 const std::size_t NR = regions.size();
8531 res.nregions = NR;
8532 res.QNfcr = Matrix<double>(NR, K, 0.0);
8533 res.TNfcr = Matrix<double>(NR, K, 0.0);
8534 res.WeightNfcr = Matrix<double>(NR, K, 0.0);
8535 res.MemOccNfcr = Matrix<double>(NR, K, 0.0);
8536 res.DropRateNfcr = Matrix<double>(NR, K, 0.0);
8537 for (std::size_t g = 0; g < NR; ++g) {
8538 regions[g].update(now);
8539 for (std::size_t r = 0; r < K; ++r) {
8540 if (sim_time > 0.0) {
8541 // JMT's convention: the region's queue length counts only
8542 // the jobs INSIDE it. A WAITQ job parked outside has not
8543 // entered and is not part of the region's occupancy.
8544 res.QNfcr(g, r) = regions[g].tot_jobs[r] / sim_time;
8545 res.WeightNfcr(g, r) = regions[g].tot_weight[r] / sim_time;
8546 res.MemOccNfcr(g, r) = regions[g].tot_mem[r] / sim_time;
8547 res.TNfcr(g, r) = regions[g].completed[r] / sim_time;
8548 res.DropRateNfcr(g, r) = regions[g].dropped[r] / sim_time;
8549 }
8550 }
8551 }
8552 }
8553
8554 // ---- confidence intervals ------------------------------------------------
8555 // The event count is set BEFORE the intervals, not after: `batch_means_ci`
8556 // plans a run length from it when the caller asked for one, and reading a
8557 // zero there would silently fall back to the BUDGET, which an early
8558 // convergence stop never spent.
8559 res.total_simulated_events = static_cast<long long>(total_completions);
8560 batch_means_ci(obs, tr, acc, o, res, u_law, &lost_unserved);
8561
8562 // The impatience block is reported only when the model declares one: an
8563 // all-zero matrix would read as "measured, and none happened".
8564 double any_balk = 0.0, any_renege = 0.0;
8565 for (std::size_t i = 0; i < M; ++i)
8566 for (std::size_t r = 0; r < K; ++r) {
8567 any_balk += balked[i][r];
8568 any_renege += reneged[i][r];
8569 }
8570 // The orbit block follows the DECLARATION, not the traffic: a retrial station whose orbit stayed empty (a capacity
8571 // pinned to the server count loses every blocked job) still reports its drops, and an absent block read as 0x0.
8572 bool any_orbit = false;
8573 for (std::size_t i = 0; i < M; ++i)
8574 for (std::size_t r = 0; r < K; ++r) any_orbit = any_orbit || S[i].has_retrial[r];
8575 if (any_orbit) {
8576 res.retriedCustomers = Matrix<double>(M, K, 0.0);
8577 res.retrialDropped = Matrix<double>(M, K, 0.0);
8578 res.avgOrbitSize = Matrix<double>(M, K, 0.0);
8579 for (std::size_t i = 0; i < M; ++i) {
8580 const double dt = now - S[i].orbit_last;
8581 for (std::size_t r = 0; r < K; ++r) {
8582 double tot = S[i].tot_orbit[r];
8583 if (dt > 0.0) tot += S[i].orbit_size[r] * dt;
8584 res.retriedCustomers(i, r) = S[i].retried[r];
8585 res.retrialDropped(i, r) = S[i].retrial_lost[r];
8586 if (sim_time > 0.0) res.avgOrbitSize(i, r) = tot / sim_time;
8587 }
8588 }
8589 }
8590
8591 if (any_balk > 0.0 || any_renege > 0.0) {
8592 res.balkedCustomers = Matrix<double>(M, K, 0.0);
8593 res.renegedCustomers = Matrix<double>(M, K, 0.0);
8594 res.renegingRate = Matrix<double>(M, K, 0.0);
8595 for (std::size_t i = 0; i < M; ++i)
8596 for (std::size_t r = 0; r < K; ++r) {
8597 res.balkedCustomers(i, r) = balked[i][r];
8598 res.renegedCustomers(i, r) = reneged[i][r];
8599 if (sim_time > 0.0) res.renegingRate(i, r) = reneged[i][r] / sim_time;
8600 }
8601 }
8602
8603 /**
8604 * THE JOB-LEVEL END STATE, `finalJobs`, in the init_jobs layout, and the
8605 * departure log of tagged jobs. A transient run is read at its horizon, not
8606 * at its last event; untagged jobs get fresh ids above every tag in use. It
8607 * runs last, once every other block is filled, because it advances the
8608 * sharing stations to that instant.
8609 */
8610 if (track_jobs) {
8611 if (transient_run) now = horizon;
8612 std::int64_t next_id = 0;
8613 for (std::size_t r = 0; r < o.init_jobs.rows() && o.init_jobs.cols() >= 8; ++r)
8614 next_id = std::max(next_id, static_cast<std::int64_t>(o.init_jobs(r, 7)) + 1);
8615 std::vector<std::array<double, 8>> out;
8616 auto emit = [&](std::size_t i, const Job& j, double remaining, double el, double& order) {
8617 out.push_back({static_cast<double>(i), static_cast<double>(j.cls),
8618 std::max(remaining, std::numeric_limits<double>::min()), el, now - j.t_arr,
8619 now - j.t_sys, order, static_cast<double>(j.ext)});
8620 order += 1.0;
8621 };
8622 for (std::size_t i = 0; i < M; ++i) {
8623 StationState& s = S[i];
8624 if (s.role != Role::Queue && s.role != Role::Delay) continue;
8625 const std::size_t before = out.size();
8626 double order = 0.0;
8627 if (s.role == Role::Delay) {
8628 for (const Job& d : delay_live[i]) emit(i, d, d.due - now, d.elapsed + d.service - (d.due - now), order);
8629 } else if (s.ps) {
8630 ps_advance(i);
8631 for (const PsJob& pj : s.ps_jobs) {
8632 Job j;
8633 j.cls = pj.cls;
8634 j.t_arr = pj.t_arr;
8635 j.t_sys = pj.t_sys;
8636 j.sys_cls = pj.sys_cls;
8637 j.ext = pj.ext;
8638 emit(i, j, pj.remaining, pj.total - pj.remaining, order);
8639 }
8640 } else {
8641 std::vector<std::size_t> busy;
8642 for (std::size_t sl = 0; sl < s.nservers; ++sl) {
8643 if (s.server_blocked[sl] || s.server_held[sl])
8644 throw UnsupportedError(ErrorKind{"InitJobs"},
8645 "SolverLDES (native engine): track_jobs cannot export station '" +
8646 sn.stations[i].name + "', whose server is blocked or held");
8647 if (s.server_busy[sl]) busy.push_back(sl);
8648 }
8649 std::sort(busy.begin(), busy.end(), [&](std::size_t a, std::size_t b) {
8650 return s.server[a].t_arr < s.server[b].t_arr;
8651 });
8652 for (std::size_t sl : busy) {
8653 const Job& j = s.server[sl];
8654 const double done = svc_work(i, j.cls, s.server_start[sl], now);
8655 emit(i, j, j.remaining - done, j.elapsed + done, order);
8656 }
8657 }
8658 // The waiting room, in the order the station would serve it.
8659 std::vector<Job> waiting = s.buffer;
8660 while (!waiting.empty()) {
8661 const Job j = jpq_poll(waiting, s.cmp);
8662 emit(i, j, j.remaining, j.elapsed, order);
8663 }
8664 if (out.size() > before) job_state_check(i);
8665 }
8666 for (const auto& row : out) next_id = std::max(next_id, static_cast<std::int64_t>(row[7]) + 1);
8667 res.finalJobs = Matrix<double>(out.size(), 8, 0.0);
8668 for (std::size_t r = 0; r < out.size(); ++r) {
8669 if (out[r][7] < 0.0) out[r][7] = static_cast<double>(next_id++);
8670 for (std::size_t c = 0; c < 8; ++c) res.finalJobs(r, c) = out[r][c];
8671 }
8672 res.jobDepartures = Matrix<double>(job_departure_log.size(), 4, 0.0);
8673 for (std::size_t r = 0; r < job_departure_log.size(); ++r)
8674 for (std::size_t c = 0; c < 4; ++c) res.jobDepartures(r, c) = job_departure_log[r][c];
8675 }
8676 res.converged = converged;
8677 res.convergence_batches = cnvg.batches();
8678 // A transient run that reached its horizon stopped on its event schedule,
8679 // not on the wall clock: it is labelled as the JAR labels it, max_events.
8680 // Only a run the budget actually cut short is max_time.
8681 res.stopping_reason = time_stopped ? "max_time" : (converged ? "convergence" : "max_events");
8682 if (sp_on) {
8683 if (spt.stopped_run) res.stopping_reason = "sample_path";
8684 LdesSamplePath& out = res.sample_path;
8685 const sp::Recorder& rc = spt.rec;
8686 out.t = rc.times();
8687 out.events = rc.events();
8688 out.unbound_scripts = rc.unbound_scripts();
8689 out.sim_time = now;
8690 out.phases = spt.phases;
8691 for (std::size_t isf = 0; isf < rc.num_stateful(); ++isf) {
8692 out.stateful_nodes.push_back(static_cast<int>(rc.stateful_node(isf)));
8693 out.refusals.push_back(rc.refused(isf) ? rc.refusal(isf) : std::string());
8694 const std::vector<std::vector<double>> st = rc.state(isf);
8695 const std::vector<std::vector<double>> ag = rc.aggr(isf);
8696 Matrix<double> sm(st.size(), st.empty() ? 0 : st[0].size());
8697 for (std::size_t r = 0; r < st.size(); ++r)
8698 for (std::size_t c = 0; c < st[r].size(); ++c) sm(r, c) = st[r][c];
8699 Matrix<double> am(ag.size(), K);
8700 for (std::size_t r = 0; r < ag.size(); ++r)
8701 for (std::size_t c = 0; c < ag[r].size() && c < K; ++c) am(r, c) = ag[r][c];
8702 out.state.push_back(rc.refused(isf) ? Matrix<double>() : sm);
8703 out.aggr.push_back(am);
8704 }
8705 res.has_sample_path = true;
8706 }
8707 res.engine = "native";
8708 res.method = o.method;
8709 return res;
8710}
8711
8712/**
8713 * Simulate `sn`, over independent REPLICATIONS when `options.replications > 1`.
8714 *
8715 * Each replication is one path with its OWN seed, `seed + r`, exactly as
8716 * `Solver_ldes_analyzer_parallel` derives them. That is what makes the paths
8717 * independent while keeping the whole run reproducible; sharing a seed would
8718 * make every replication identical and collapse the interval to zero, and
8719 * drawing them randomly would make the run irreproducible.
8720 *
8721 * THE INTERVAL COMES FROM THE SPREAD BETWEEN REPLICATIONS, not from within a
8722 * path, and it is the honest one: independent paths need no assumption about
8723 * the correlation structure that batch means has to model. The cost is that
8724 * `replications - 1` degrees of freedom is few, so the t critical value is
8725 * large and the interval wide -- which is the estimate, not a defect of it.
8726 *
8727 * A single replication yields NO interval rather than a zero-width one: with
8728 * one path there is no spread to measure, and reporting zero would read as
8729 * perfect precision.
8730 */
8731template <class T>
8733 using namespace engine;
8734 const int R = o.replications;
8735 if (R <= 1) return ldes_engine_solve_one(sn, o);
8736
8737 // THE BUDGET IS SPLIT ACROSS THE PATHS, as `Solver_ldes_analyzer_parallel` does: each replication runs
8738 // ceil(budget / R) completions with a floor of 1000, so --replications buys an interval at the cost of
8739 // the single path's work rather than R times it. `events` is the same budget as `samples` here and is
8740 // split the same way.
8741 const std::size_t budget = o.events > 0 ? o.events : o.samples;
8742 const std::size_t rep_budget =
8743 std::max<std::size_t>(1000, (budget + static_cast<std::size_t>(R) - 1) / static_cast<std::size_t>(R));
8744 std::vector<LdesResult> reps(static_cast<std::size_t>(R));
8745 // ONE wall-clock budget for the whole ensemble. A pool worker starts with an
8746 // empty deadline stack, so each replication is handed what is left of it.
8748 const double wall_rem0 = util::timeout_remaining();
8749 const std::chrono::steady_clock::time_point wall_t0 = std::chrono::steady_clock::now();
8750 auto run_rep = [&](int r) {
8751 LdesOptions ro = o;
8752 ro.replications = 0;
8753 if (std::isfinite(wall_rem0)) {
8754 const double used =
8755 std::chrono::duration<double>(std::chrono::steady_clock::now() - wall_t0).count();
8756 ro.timeout = std::max(1e-9, wall_rem0 - used);
8757 }
8758 ro.samples = rep_budget;
8759 if (o.events > 0) ro.events = rep_budget;
8760 // A replication measures its OWN interval nowhere: the spread across
8761 // paths is the estimate, so the within-path machinery is switched off.
8762 ro.cimethod = "none";
8763 ro.seed = (o.seed >= 0) ? (o.seed + r) : o.seed;
8764 reps[static_cast<std::size_t>(r)] = ldes_engine_solve_one(sn, ro);
8765 };
8766
8767 // THE POOL. Each replication owns its seed and writes only its own slot, so the result is
8768 // the serial one bit for bit, whatever the interleaving. An unset --numthreads takes half
8769 // the cores, the JAR's LDESOptions.numThreads default. A Logger node forces one thread:
8770 // every path truncates and rewrites the same trace file, and serially the last one wins.
8771 bool has_logger = false;
8772 for (std::size_t nd = 0; nd < sn.nof_nodes(); ++nd)
8773 if (sn.nodes[nd].nodetype == lang::NodeType::Logger) has_logger = true;
8774 unsigned hw = std::thread::hardware_concurrency();
8775 if (hw == 0) hw = 1;
8776 const unsigned want = o.numthreads > 0 ? static_cast<unsigned>(o.numthreads) : (hw + 1) / 2;
8777 const int nthreads = has_logger ? 1 : static_cast<int>(std::min<unsigned>(want, static_cast<unsigned>(R)));
8778 if (nthreads <= 1) {
8779 for (int r = 0; r < R; ++r) run_rep(r);
8780 } else {
8781 // A failing replication is rethrown after the join, the LOWEST index first, so the error
8782 // a caller sees is the one the serial loop would have raised.
8783 std::vector<std::exception_ptr> errs(static_cast<std::size_t>(R));
8784 std::vector<std::thread> pool;
8785 pool.reserve(static_cast<std::size_t>(nthreads));
8786 for (int t = 0; t < nthreads; ++t) {
8787 pool.emplace_back([&, t]() {
8788 for (int r = t; r < R; r += nthreads) {
8789 try {
8790 run_rep(r);
8791 } catch (...) {
8792 errs[static_cast<std::size_t>(r)] = std::current_exception();
8793 }
8794 }
8795 });
8796 }
8797 for (std::size_t t = 0; t < pool.size(); ++t) pool[t].join();
8798 for (int r = 0; r < R; ++r)
8799 if (errs[static_cast<std::size_t>(r)]) std::rethrow_exception(errs[static_cast<std::size_t>(r)]);
8800 }
8801
8802 LdesResult res = reps[0];
8803 // THE PER-JOB RESPONSE TIMES ARE KEPT PER REPLICATION and pooled in replication order, as the JAR's
8804 // parallel analyzer does: a quantile procedure over independent replications (FIRQUEST) needs each path
8805 // apart, and every reader of the pooled block (getCdfRespT) sees all R paths rather than path 0 alone.
8806 // Steady state only: a transient run's samples are tied to the one path its trajectory came from.
8807 res.respTimeSamplesRep.clear();
8808 if (!o.has_timespan && !res.respTimeSamples.empty()) {
8809 res.respTimeSamplesRep.resize(static_cast<std::size_t>(R));
8810 for (int r = 0; r < R; ++r)
8811 res.respTimeSamplesRep[static_cast<std::size_t>(r)] =
8812 std::move(reps[static_cast<std::size_t>(r)].respTimeSamples);
8813 for (std::size_t i = 0; i < res.respTimeSamples.size(); ++i)
8814 for (std::size_t k = 0; k < res.respTimeSamples[i].size(); ++k) {
8815 std::vector<double>& pooled = res.respTimeSamples[i][k];
8816 pooled.clear();
8817 for (int r = 0; r < R; ++r) {
8818 const std::vector<double>& x = res.respTimeSamplesRep[static_cast<std::size_t>(r)][i][k];
8819 pooled.insert(pooled.end(), x.begin(), x.end());
8820 }
8821 }
8822 }
8823 // finalJobs and jobDepartures describe ONE path; the mean over paths has no end state.
8824 res.finalJobs = Matrix<double>();
8826 res.QNCI = Matrix<double>();
8827 res.UNCI = Matrix<double>();
8828 res.RNCI = Matrix<double>();
8829 res.TNCI = Matrix<double>();
8830
8831 const std::size_t M = res.nstations, K = res.nclasses;
8832 Matrix<double>* means[4] = {&res.QN, &res.UN, &res.RN, &res.TN};
8833 Matrix<double>* cis[4] = {&res.QNCI, &res.UNCI, &res.RNCI, &res.TNCI};
8834 const Matrix<double>* per_rep[4];
8835
8836 for (int q = 0; q < 4; ++q) {
8837 *means[q] = Matrix<double>(M, K, 0.0);
8838 *cis[q] = Matrix<double>(M, K, 0.0);
8839 }
8840 const double tcrit = t_critical(o.confint > 0.0 ? o.confint : 0.95, R - 1);
8841
8842 for (std::size_t i = 0; i < M; ++i)
8843 for (std::size_t k = 0; k < K; ++k)
8844 for (int q = 0; q < 4; ++q) {
8845 double sum = 0.0;
8846 for (int r = 0; r < R; ++r) {
8847 per_rep[q] = (q == 0) ? &reps[static_cast<std::size_t>(r)].QN
8848 : (q == 1) ? &reps[static_cast<std::size_t>(r)].UN
8849 : (q == 2) ? &reps[static_cast<std::size_t>(r)].RN
8850 : &reps[static_cast<std::size_t>(r)].TN;
8851 sum += (*per_rep[q])(i, k);
8852 }
8853 const double mean = sum / R;
8854 (*means[q])(i, k) = mean;
8855 double ss = 0.0;
8856 for (int r = 0; r < R; ++r) {
8857 per_rep[q] = (q == 0) ? &reps[static_cast<std::size_t>(r)].QN
8858 : (q == 1) ? &reps[static_cast<std::size_t>(r)].UN
8859 : (q == 2) ? &reps[static_cast<std::size_t>(r)].RN
8860 : &reps[static_cast<std::size_t>(r)].TN;
8861 const double d = (*per_rep[q])(i, k) - mean;
8862 ss += d * d;
8863 }
8864 (*cis[q])(i, k) = tcrit * std::sqrt((ss / (R - 1)) / R);
8865 }
8866
8867 // The system-level rows average the same way; they carry no interval,
8868 // matching what the single-path engine reports for them.
8869 res.XN = Matrix<double>(1, K, 0.0);
8870 res.CN = Matrix<double>(1, K, 0.0);
8871 for (std::size_t k = 0; k < K; ++k) {
8872 double sx = 0.0, sc = 0.0;
8873 for (int r = 0; r < R; ++r) {
8874 sx += reps[static_cast<std::size_t>(r)].XN(0, k);
8875 sc += reps[static_cast<std::size_t>(r)].CN(0, k);
8876 }
8877 res.XN(0, k) = sx / R;
8878 res.CN(0, k) = sc / R;
8879 }
8880
8881 // The fork-join sections average across replications like the station means; FJQLen is re-formed from the
8882 // averaged pair so that Little's law still holds exactly on the reported numbers.
8883 if (!res.FJTput.empty()) {
8884 Matrix<double> x(res.FJTput.rows(), res.FJTput.cols(), 0.0), w = x;
8885 for (int r = 0; r < R; ++r) {
8886 const LdesResult& rp = reps[static_cast<std::size_t>(r)];
8887 for (std::size_t p = 0; p < x.rows() && p < rp.FJTput.rows(); ++p)
8888 for (std::size_t k = 0; k < x.cols() && k < rp.FJTput.cols(); ++k) {
8889 x(p, k) += rp.FJTput(p, k) / R;
8890 w(p, k) += rp.FJRespT(p, k) / R;
8891 }
8892 }
8893 res.FJTput = x;
8894 res.FJRespT = w;
8895 for (std::size_t p = 0; p < x.rows(); ++p)
8896 for (std::size_t k = 0; k < x.cols(); ++k) res.FJQLen(p, k) = x(p, k) * w(p, k);
8897 }
8898
8899 long long total = 0;
8900 for (int r = 0; r < R; ++r) total += reps[static_cast<std::size_t>(r)].total_simulated_events;
8901 res.total_simulated_events = total;
8902 // Any path the budget cut short makes the ensemble an interim one.
8903 for (int r = 0; r < R; ++r)
8904 if (reps[static_cast<std::size_t>(r)].stopping_reason == "max_time") {
8905 res.stopping_reason = "max_time";
8907 }
8908 return res;
8909}
8910
8911} // namespace ldes
8912} // namespace line
8913
8914#endif // LINE_SOLVERS_LDES_LDES_ENGINE_H
Delay(model, name): the infinite-server station.
Definition nodes.h:173
InputError(const std::string &what)
Definition error.h:105
std::size_t cols() const
Definition matrix.h:90
std::size_t rows() const
Definition matrix.h:89
bool empty() const
Definition matrix.h:92
NumericError(const std::string &what)
Definition error.h:112
Queue(model, name, strategy).
Definition nodes.h:165
Source(model, name): the external arrival station.
Definition nodes.h:179
UnsupportedError(const std::string &what)
Definition error.h:119
One variate generator, holding whatever state its family needs.
A network plus its refreshed NetworkStruct.
The RAII frame timeout_arm returns.
The exception types the port throws.
Fork-join section metrics: FJQLen, FJRespT and FJTput of every Fork/Join pair.
Busy period measurement for the native LDES engine.
The Cache node of the native LDES engine.
The option and result records of SolverLDES, the discrete-event simulator.
Finite capacity regions for the native LDES engine.
The exact sample-path recorder of the native LDES engine (--sample-path N).
The variate generators of the native LDES engine.
The Petri-net layer of the native LDES engine: Places and Transitions.
The scheduling disciplines of the native LDES engine.
The estimators of the native LDES engine: running integrals, the MSER-5 warmup filter,...
options.timeout: one wall-clock budget per top-level solve, on a per-THREAD deadline stack.
Dense matrix and non-owning view.
Marked MAP (MMAP) algebra: per-class rates, class probabilities, superposition, normalization and sca...
CacheMissResult< T > cache_miss(const Matrix< T > &gamma, const std::vector< int > &m, const Matrix< T > &lambda)
Exact cache miss rates from the recursive normalizing constant.
Definition cache_miss.h:65
UnsupportedError refusal(const lang::Distrib< double > &d, const std::string &where)
Definition markov.h:68
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
DropStrategy
Blocking and loss rules, with the values of MATLAB DropStrategy.
Definition lang_types.h:465
@ IMMEDIATE
fires with zero delay, resolved by weight and priority
Definition lang_types.h:384
SignalType
G-network signal classes, with the values of MATLAB SignalType.
Definition lang_types.h:180
@ REPLY
completes a synchronous call, releasing a held server
Definition lang_types.h:181
@ NEGATIVE
removes a batch of jobs (Gelenbe's negative customer)
Definition lang_types.h:182
@ CATASTROPHE
removes EVERY job at the station
Definition lang_types.h:183
bool process_is_batch(ProcessType p)
True when an EVENT of this process releases (or, as a service process, completes) a BATCH of jobs who...
Definition lang_types.h:771
PollingOrder
Visit-order rules of a polling server, with the values of MATLAB PollingOrder.
Definition lang_types.h:404
@ THRESHOLD
a priority buffer above its threshold, else SKIPEMPTY
Definition lang_types.h:408
@ CYCLIC
fixed cyclic order (or the polling table)
Definition lang_types.h:405
@ LQF
longest buffer first, ties to the cyclic successor
Definition lang_types.h:407
@ SDR
Krzesinski (1987) product-form state-dependent routing.
Definition lang_types.h:439
PollingTimer
Visit-timer scopes of a polling server, with the values of MATLAB PollingTimer.
Definition lang_types.h:412
@ LOCAL
a timer per visit, drawn at the polling instant
Definition lang_types.h:414
@ GLOBAL
a timed token: per-class target rotation timers
Definition lang_types.h:415
@ NONE
no visit timer
Definition lang_types.h:413
DepartureDiscipline
When a Place releases a served token, MATLAB DepartureDiscipline.
Definition lang_types.h:499
RemovalPolicy
Which job a negative signal removes, with the values of MATLAB RemovalPolicy.
Definition lang_types.h:187
@ FCFS
the oldest waiting job; servers only once nobody waits
Definition lang_types.h:189
@ LCFS
the newest waiting job; servers only once nobody waits
Definition lang_types.h:190
@ RANDOM
uniform over waiting AND in-service jobs
Definition lang_types.h:188
HeteroSchedPolicy
How a heterogeneous station picks among its server types, MATLAB HeteroSchedPolicy.
Definition lang_types.h:492
PollingType
Polling service disciplines, with the values of MATLAB PollingType.
Definition lang_types.h:391
@ KLIMITED
serve at most K per visit (K in pollingPar)
Definition lang_types.h:394
@ EXHAUSTIVE
serve until the queue empties
Definition lang_types.h:393
@ GATED
serve exactly the jobs present at the polling instant
Definition lang_types.h:392
@ GLIMITED
serve at most K of the jobs present at the polling instant
Definition lang_types.h:396
@ DECREMENTING
serve until the queue is one shorter than at arrival
Definition lang_types.h:395
const char * node_type_to_text(NodeType t)
Name of a node kind, for diagnostics.
Definition lang_types.h:362
ProcessType
Distribution kinds, with the values of MATLAB ProcessType.
Definition lang_types.h:524
@ NHPP
The time-INHOMOGENEOUS families of Ko and Pender (ORL 45, 2017): an NHPP is a rate schedule lambda(t)...
Definition lang_types.h:577
@ NNPP
A nonstationary non-Poisson arrival process (thinning + SCIATA): a rate function lambda(t) on [0,...
Definition lang_types.h:633
const char * sched_to_text(SchedStrategy s)
Definition lang_types.h:248
const char * process_to_text(ProcessType p)
The MATLAB ProcessType name, as sn.procid prints it.
Definition lang_types.h:655
bool process_is_marked_stationary(ProcessType p)
True when the type carries PER-MARK arrival blocks, i.e.
Definition lang_types.h:742
std::function< std::vector< T >(const std::vector< T > &)> CdScaling
A class-dependent scaling map, sn.cdscaling.
Definition lang_types.h:794
NodeType
Node kinds, with the values of MATLAB NodeType.
Definition lang_types.h:345
std::size_t preemption_victim(lang::SchedStrategy sched, const std::vector< Job > &in_service, const std::vector< double > &started, const Job &arriving, double c, double now)
Which job in service arriving displaces, or in_service.size() for none.
PowerState
The power state of one server of a setup/delay-off station, the reference's Solver_ssj....
EventKind
Event tags, ordered so that a service completion precedes an arrival scheduled for the same instant.
@ EV_PLACE_SVC
A service completion in the EMBEDDED QUEUE of a queueing place: the token leaves the place's servers ...
@ EV_ORBIT_ABANDON
A job abandons the retrial orbit (sn.orbitImpatience); tag is its id.
@ EV_POLL_TIMER
A polling visit timer expires; station is the station and tag the timer id.
@ EV_QUANTUM
Round robin: the quantum of the job in slot expires; tag is the slot's rr_qtag when it was armed.
double spn_active_servers(const SpnMode &m, const std::vector< double > &tok)
The clocks an enabled timed mode runs at once: min(servers, enabling degree), the degree being the fl...
Definition ldes_spn.h:109
void ldes_engine_reject(const qn::NetworkStruct< T > &sn, const LdesOptions &o)
Refuse, by name, every model outside this engine's scope.
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
void jpq_offer(std::vector< T > &es, const T &x, const Cmp &cmp)
PriorityQueue.offer: append, then sift the new element up.
bool is_preemptive(lang::SchedStrategy s)
True for the disciplines that interrupt a job already in service.
double fsp_virtual_finish(const std::vector< double > &residuals, double target_work, double c, double now)
FSP's virtual finish time: when target would finish if the station ran processor sharing from now on.
std::vector< double > ldes_declared_placement(const qn::NetworkStruct< T > &sn)
The job placement the model's DECLARED initial state stands for, station-major like init_sol,...
int spn_pick_immediate(const std::vector< SpnMode > &modes, const std::vector< double > &tok, double u)
Pick among the enabled IMMEDIATE modes: the highest priority first (lowest value),...
Definition ldes_spn.h:129
void cache_hit(CacheState &cs, std::size_t item, std::size_t at, double u_random)
Serve a HIT in list at.
Definition ldes_cache.h:160
std::vector< double > ps_shares(lang::SchedStrategy sched, const std::vector< PsJob > &jobs, double c, const std::vector< double > &weight, std::size_t nclasses)
The per-job shares of a sharing discipline, in units of one server.
Role
Station roles this engine simulates.
std::string java_double_str(double v)
A double as Java's Double.toString spells it, which is how the reference's Logger writes its time col...
bool is_ps_family(lang::SchedStrategy s)
True for the disciplines that share the server instead of ordering a queue.
void jpq_remove_at(std::vector< T > &es, std::size_t i, const Cmp &cmp)
PriorityQueue.removeAt: the last element fills the hole, down then up.
T jpq_poll(std::vector< T > &es, const Cmp &cmp)
PriorityQueue.poll: take the root, sift the LAST element down from it.
bool spn_enabled(const SpnMode &m, const std::vector< double > &tok)
True when m is enabled by the marking tok, which is indexed the same way as the mode's own vectors – ...
Definition ldes_spn.h:85
LdesResult ldes_engine_solve(const qn::NetworkStruct< T > &sn, const LdesOptions &o)
Simulate sn, over independent REPLICATIONS when options.replications > 1.
LdesResult ldes_engine_solve_one(const qn::NetworkStruct< T > &sn, const LdesOptions &o_in)
Simulate sn in process and return the same record the subprocess client parses out of an ldes-result ...
double tot(const std::vector< double > &pops)
double re(double x)
std::string name(const Element *el, const std::string &key="name")
std::vector< T > mmap_lambda(const Mmap< T > &m)
Alias kept for parity with the MATLAB name.
std::vector< double > pfqn_sdrprob(const SdrCoeff &c, const std::vector< double > &n)
SDR routing probabilities of eq.
Definition pfqn_sdr.h:207
SdrCoeff pfqn_sdrcoeff(const SdrStruct &sdr)
Validates an SDR structure and returns its derived coefficients.
Definition pfqn_sdr.h:105
double pfqn_sdrped(const std::vector< double > &P)
Probability of being denied entry and routed straight to the departure centre.
Definition pfqn_sdr.h:239
void push(EventOutcome< T > &out, const std::vector< T > &row, const T &rate, const T &prob, const std::vector< std::size_t > &start, const std::vector< std::size_t > &preempt)
Append one successor with its tags.
void walk(const PollingInfo< T > &pi, PollingAdvance< T > &B, std::vector< long > c, const std::vector< long > &nbuf, std::size_t p, bool arrived, std::size_t steps_left, T prob, std::size_t startpos)
Marginal< T > to_marginal(const NetworkStruct< T > &sn, std::size_t ist, const std::vector< T > &state_i, const std::vector< std::size_t > &phasesz, const std::vector< std::size_t > &phaseshift, std::size_t nvar=0)
Port of State.toMarginal for a STATION, one state row at a time.
Definition state.h:139
T cd_factor(const NetworkStruct< T > &sn, std::size_t ist, const std::vector< T > &nir, std::size_t cls)
Port of State.cdclassfactor: the class-dependence multiplier of a class-cls rate at the per-class pop...
T lld_factor(const NetworkStruct< T > &sn, std::size_t ist, double n)
The limited-load-dependent multiplier at population n, 1 when unset.
std::vector< std::pair< std::size_t, std::size_t > > fj_sorted_pairs(const S &sn)
The Fork/Join pairs of a struct, sortrows([forks joins]) over find(sn.fj): ascending in fork node,...
Definition fj_metrics.h:62
double elapsed(const Frame &f)
bool timeout_exceeded()
The checkpoint: true when the innermost budget has run out, marking it tripped.
void timeout_trip()
Mark the innermost budget tripped without reading the clock: for an external engine that REPORTS it s...
TimeoutScope timeout_arm(double budget)
Arm budget seconds for the scope's lifetime, capped by the outer frame's remaining time.
double timeout_remaining()
Seconds left on the innermost armed budget; +Inf when none is armed.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
Port of the MATLAB +State package: the encoding that turns a station's state row into marginal job co...
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
std::string name
Definition error.h:38
static constexpr double Zero
Definition lang_types.h:825
Per-cache hit/miss/latency, as the cacheMetrics block carries them.
Matrix< double > hit
(1 x nclasses) hit probability
The knobs of one LDES run.
double confint
Confidence level of the reported half-widths.
long seed
–seed; -1 requests a random stream
bool slotted
–slotted, run on the slot lattice
bool cnvgon
–cnvgon
std::string cimethod
–cimethod: obm | bm | spectral | none
double slot_length
–slotlength
int replications
–replications; 0 = not given (one path)
int sample_path_events
–sample-path N: record the exact sample path, N rows of SolverSSA-style events plus LINE State,...
std::size_t events
0 = not given; overrides samples when set
std::string tranfilter
–tranfilter: mser5 | fixed | none
int numthreads
–numthreads; 0 = not given
std::size_t samples
-s, service-completion budget
double timeout
–maxtime, a COOPERATIVE wall-clock budget the event loop polls; the wrapper caps it by any options....
bool has_timespan
true when [t0,t1] was set: a TRANSIENT run
One measured busy period target (–busyperiod): a station, a station-class pair, or a declared station...
One ldes-result document, parsed.
Matrix< double > FJTput
getAvgFJ, FJQLen = FJTput * FJRespT
Matrix< double > TNCI
Matrix< double > XN
(1 x nclasses), per-class visits and system tput
std::vector< std::vector< std::vector< double > > > respTimeSamples
[station][class] -> the per-job response times the engine recorded, in departure order.
Matrix< double > FJQLen
Matrix< double > FJRespT
std::vector< std::vector< std::vector< std::vector< double > > > > respTimeSamplesRep
[rep][station][class][j] -> the same samples kept PER REPLICATION, each in departure order with the w...
Matrix< double > UN
std::string stopping_reason
convergence | max_events | max_sim_events | max_time.
Matrix< double > TN
Matrix< double > UNCI
Matrix< double > RN
Matrix< double > QNCI
Matrix< double > CN
long long total_simulated_events
Matrix< double > jobDepartures
[id, station, class, time] of every departure of a tagged init_jobs job (track_jobs).
Matrix< double > RNCI
Matrix< double > QN
Matrix< double > finalJobs
The jobs present at the end of the run, in the init_jobs layout (track_jobs).
The samplePath block (--sample-path N): one simulated path in SolverSSA's row convention.
std::vector< double > t
Later-is-greater, so the priority queue pops the earliest event.
bool operator()(const Event &a, const Event &b) const
One scheduled event.
Job job
Delay and PS carry the job in the event.
std::size_t slot
server slot at a buffered station
std::uint64_t tag
Identifies the job the event was scheduled for.
A job held by a station.
One destination NODE of a (node, class) pair, with the class it switches to.
std::size_t node
1-based destination NODE
std::vector< std::pair< std::size_t, double > > cls
(class, probability)
std::size_t station
its station index, or M when it is not one
double mass
total probability into this node, over classes
One routing alternative out of a (node, class) pair.
std::size_t station
its station index, or M when it is not one
std::size_t node
1-based destination NODE
Balking: the (min, max, probability) triples an arrival consults.
double max_jobs
-1 = unbounded above, the wire's spelling
One station's mutable state.
bool state_dependent
True when the station's service RATE depends on its own population, i.e.
bool has_setup
SETUP AND DELAY-OFF: servers that power down when they fall idle.
bool rr
ROUND ROBIN (SchedStrategy::RR): the per-class quantum law, and per slot the identity of the quantum ...
std::vector< double > retried
std::vector< std::vector< double > > type_rate
[pool][class], 1/mean, for FSF
std::vector< lang::DropStrategy > droprule
sn.droprule, per class, declared on the DESTINATION station.
std::vector< bool > has_orbit_abandon
std::vector< double > down_rate_raw
The declared absolute rate, kept so the scale can be formed once E[S] is known.
lang::CdScaling< double > cd
sn.cdscaling: beta_r(n), a per-class RATE at the station's population.
lang::HeteroSchedPolicy hetero_policy
std::size_t poll_pos
current position in the ring
std::vector< bool > server_busy
std::vector< bool > doff_zero
a delay-off is declared with zero mean
std::vector< double > poll_trt
GLOBAL: token rotation timer expiry per class.
std::vector< std::size_t > held_cls
std::size_t poll_budget
remaining visit budget; 0 = exhausted
std::vector< std::deque< Job > > orbit
per class, oldest first
std::vector< Sampler > orbit_abandon
std::vector< int > max_attempts
std::vector< Sampler > switchover
std::vector< int > power
[slot] PowerState
std::vector< std::vector< BalkRule > > balk
std::vector< bool > poll_has_tlaw
std::uint64_t poll_timer_tag
the live visit timer, 0 = none
std::vector< Sampler > setup_law
[class], valid where has_setup_law
std::vector< std::size_t > type_first
per pool, its first slot
bool draw_at_start
True when the service requirement is drawn when a server TAKES the job, not when it joins the station...
std::vector< double > retrial_lost
std::vector< std::size_t > poll_ring
class (0-based) at each position
std::vector< std::vector< Sampler > > type_svc
[pool][class]
std::size_t poll_thr_class
THRESHOLD priority class, 0-based.
std::vector< std::uint64_t > power_tag
[slot] generation of the live power timer
std::vector< double > class_mean
mean service per class, for SEPT/LEPT
std::vector< bool > server_held
A server HELD ACROSS A SYNCHRONOUS CALL.
std::vector< std::vector< bool > > type_compat
[pool][class]
std::vector< int > retrial_policy
1 = LINEAR (a clock per job), 2 = CONSTANT (one per orbit)
std::vector< double > blocked_at
Jobs held OUTSIDE this station's buffer but counted in its queue length: a BAS or BBS job whose desti...
std::vector< Job > buffer
The waiting room, as an EXPLICIT HEAP rather than a std::priority_queue.
std::vector< std::size_t > blocked_dest_cls
bool powers_down_after(std::size_t r) const
Does a server freed by class r enter DELAYOFF (or power down at once)?
bool resume
PR (continue the residual) as against PI (redraw).
std::vector< double > ps_cd
The class-dependent speed a SHARING station is running at right now, one entry per class.
std::vector< bool > poll_polled
std::vector< std::vector< bool > > type_has_svc
[pool][class], a law of its own
std::vector< bool > has_patience
std::vector< double > weight
schedparam, the DPS/GPS weights
std::vector< Sampler > patience
Reneging: the abandonment timer of a WAITING job, per class.
std::vector< double > gd_peak
The declared peak of the GLOBAL (Whittle) dependence at this station, one entry per class,...
std::vector< bool > has_retrial
std::vector< Sampler > retrial
RETRIAL: a retrial station has NO WAITING ROOM.
std::function< double(const std::vector< std::size_t > &)> pas_rate
bool size_ordered
The waiting room is ranked by the job's SAMPLED size, so the size has to exist before the job enters ...
std::vector< std::uint64_t > server_tag
bool polling
A POLLING SERVER visits the per-class buffers in a fixed cyclic order, paying a SWITCHOVER on each le...
std::vector< double > lld
sn.lldscaling: the RATE multiplier when n jobs are present, indexed n-1.
std::vector< std::size_t > alfs_order
ALFS walks the pools least-flexible first: fewest compatible classes.
std::vector< std::size_t > server_type
per slot, its pool
std::vector< double > down_scale
std::vector< Sampler > rr_quantum
std::vector< double > orbit_size
live, per class
std::vector< std::uint64_t > rr_qtag
std::size_t lps_limit
LPS admission cap; 0 = none.
double util_peak
max(c, max(alpha)): the peak capacity the utilization is reported against.
std::uint64_t bmsp_tag
neutralises a superseded firing
std::vector< std::vector< bool > > pas_swap
std::vector< std::size_t > type_count
per pool, its server count
std::size_t poll_gate
DECREMENTING: jobs found at the polling instant.
std::vector< double > tot_orbit
time integral of the orbit size
std::vector< Sampler > doff_law
[class], valid where has_doff_law
std::vector< bool > has_doff_law
a delay-off of positive mean is declared
std::vector< bool > const_pending
CONSTANT: the shared clock is armed.
std::vector< std::size_t > type_order
ALIS/FAIRNESS rotate this order; a used pool goes to the back.
std::vector< bool > has_setup_law
a setup of positive mean is declared
std::size_t poll_at
the buffer the server is serving or heading to
std::vector< double > server_start
instant the held job entered service
std::vector< bool > server_blocked
A server holding a completed job it cannot hand on, because its destination is full.
std::vector< PsJob > ps_jobs
std::vector< std::size_t > parallelism
Queue.setServerParallelism(class, n): the servers a class-r job seizes for the whole of its service,...
std::vector< Sampler > svc
bool poll_expired
non-preemptive: end the visit at the next completion
std::vector< Sampler > poll_leg
std::size_t bmsp_pending
jobs the armed firing will complete
bool poll_ext
POLLING EXTENSIONS (set_polling_table, set_polling_order, set_polling_timer), the event-driven counte...
std::vector< std::size_t > blocked_dest
std::vector< std::vector< std::size_t > > held_extra
The further slots held beside each primary one, so that releasing the primary releases the whole set.
std::vector< double > classcap
bool has_breakdown
Server breakdown: the server alternates up and down on two clocks.
std::vector< bool > poll_has_leg
std::size_t bmsp_cls
the one enabled class
bool has_pools
HETEROGENEOUS SERVER POOLS, empty on a station whose servers are alike.
std::vector< double > cd_peak_class
Class or joint dependence: the declared peak per class, the product over the declared families of the...
bool pas
A PASS-AND-SWAP station serves an ORDERED LIST whose total rate is a function of the whole class sequ...
std::vector< Sampler > poll_tlaw
visit timer law per class
std::vector< bool > has_switchover
bool bmsp
BULK SERVICE (BMSP): a THIRD station kind, beside the buffered one and the sharing one.
The waiting-room order of a buffered discipline.
The parameters of a Cache node, MATLAB's sn.nodeparam{ind} for a Cache.
std::vector< std::vector< Matrix< T > > > accost
(u) x (n) of (h+1)x(h+1), or empty
What State.toMarginal returns for one station and one state row.
Definition state.h:56
std::vector< T > nir
jobs per class
Definition state.h:58
Setup and delay-off of a station that powers down when it falls idle.
A heterogeneous server pool: count servers that serve only compatible classes, each with its own serv...
std::vector< bool > compatible
per class; empty = every class
std::vector< Distrib< T > > service
per class
std::string name
Definition xml.h:55