LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_ssa_nrm.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_SSA_SOLVER_SSA_NRM_H
6#define LINE_SOLVERS_SSA_SOLVER_SSA_NRM_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * SolverSSA, the `nrm` method: a port of `solver_ssa_nrm.m` and its analyzer
12 * `solver_ssa_analyzer_nrm.m`.
13 *
14 * WHAT THE METHOD IS. The queueing network is rewritten as a REACTION NETWORK
15 * over a state vector counting jobs per (node, class, service phase), and the
16 * sample path is generated by Gibson and Bruck's Next Reaction Method: every
17 * reaction carries an absolute exponential clock `Pk`, the elapsed integrated
18 * propensity `Tk`, and fires at `tau = (Pk - Tk)/Ak`; only the reactions in the
19 * fired reaction's dependency set have their propensity recomputed. Metrics are
20 * accumulated as time integrals along the path rather than from a stored
21 * trajectory, so the memory cost is independent of the sample count.
22 *
23 * NRM IS NOT THE SERIAL SIMULATOR. `method='serial'` is a different engine with
24 * a different random stream and a different event granularity. A seed-fixed
25 * result from one cannot be reproduced by the other, and a mismatch between
26 * them is not evidence of a defect in either.
27 *
28 * DOUBLE ONLY. A sample path is generated from exponential clocks, which are
29 * `-log(u)` of a uniform; there is no exact rational value to compute and no
30 * additional information a wider float could carry, since the answer's error is
31 * the Monte Carlo error and not the rounding. A non-`double` backend is
32 * therefore refused BY NAME rather than silently narrowed, exactly as
33 * `solver_fluid` refuses one.
34 *
35 * WHAT IS PORTED AND WHAT REFUSES lives in `ssa_dispatch.h`, which holds the
36 * eligibility gate. This file assumes the gate has already passed and refuses
37 * again, by name, for anything it meets that the gate should have caught -- a
38 * second gate is cheap and a silently wrong sample path is not.
39 *
40 * ONE DELIBERATE DIVERGENCE, and it is a reference defect. In
41 * `solver_ssa_nrm.m` lines 1511-1521 the finite-capacity loss test is applied
42 * to the destination of EVERY single-destination firing, with only the renege
43 * and retry columns excluded -- `isPhaseRx` is not in the exclusion list. A
44 * PHASE CHANGE is a single-destination firing whose "destination" is another
45 * phase slot of the same job at the same station, so at a station that is at
46 * its physical capacity with an open class the reference declares the phase
47 * change a loss and DESTROYS the job. The condition is reachable (an M/PH/1/K
48 * queue under PS, which `phaseNrmOK` admits). This port excludes phase changes
49 * from the loss test. The divergence is stated rather than hidden because
50 * reproducing it would silently violate job conservation, and it is not fixed
51 * in the reference from here because that file is outside this port's scope.
52 */
53
55#include <algorithm>
56#include <cmath>
57#include <cstddef>
58#include <limits>
59#include <string>
60#include <vector>
61
68#include "line/util/error.h"
70#include "line/util/matrix.h"
71
72namespace line {
73namespace ssa {
74
75namespace detail {
76
78
79/** True for the non-preemptive disciplines that hold waiting jobs in a buffer. */
80inline bool sched_is_buffered(SchedStrategy s) {
84}
85
86/**
87 * The pass-and-swap family, whose buffer is the FULL ordered job list (oldest
88 * first) rather than the waiting jobs: `isListSched`. The reference canonicalizes
89 * OI to PAS with an all-zero swap graph; here OI keeps its own tag and
90 * `sn.pasparam` carries the zero graph, so both read the same machinery.
91 */
92inline bool sched_is_list(SchedStrategy s) {
93 return s == SchedStrategy::PAS || s == SchedStrategy::OI;
94}
95
96/**
97 * Of those, the ones whose in-service phase composition the NRM can track.
98 *
99 * LCFSPR is excluded: preempt-resume would need the preempted job's phase
100 * remembered in the buffer, which the waiting-only buffer does not record.
101 * `phaseNrmOK` in the reference draws the same line.
102 */
103inline bool sched_is_buf_ph(SchedStrategy s) {
104 return s == SchedStrategy::FCFS || s == SchedStrategy::LCFS || s == SchedStrategy::SIRO ||
106}
107
108/**
109 * The DPS / GPS family, whose rate law reads per-class weights from schedparam.
110 *
111 * THE PRIORITY VARIANTS BELONG HERE TOO. `dpsprioshare` and `gpsprioshare` call
112 * straight through to `dpsshare` / `gpsshare` -- with the priority-restricted
113 * population above capacity and the full one below it -- so they read the same
114 * weights. Leaving them out left `wnorm_` all zeros at such a station, which
115 * makes every share zero and every reaction zero-rate: the engine reports a
116 * DEADLOCK rather than a wrong number, which is at least loud.
117 */
118inline bool sched_is_weighted(SchedStrategy s) {
119 return s == SchedStrategy::DPS || s == SchedStrategy::GPS ||
121}
122
123/** One reaction of the network: a departure, or a phase change within a service process. */
124struct NrmReaction {
125 std::size_t node = 0; ///< 0-based node the reaction consumes a job at
126 std::size_t cls = 0; ///< 0-based class
127 std::size_t from = 0; ///< 0-based state slot the propensity reads
128 double rate = 0.0; ///< the service-process rate the reaction carries
129 bool is_phase = false; ///< an internal D0 phase change rather than a departure
130 std::size_t phase_from = 0, phase_to = 0; ///< 0-based phases of a phase change
131 std::size_t dep_phase = 0; ///< 0-based phase a departure absorbs from
132 bool is_buf_svc = false; ///< departure of a buffered-PH class
133 /** A polling SWITCHOVER step: moves no job, reads and advances the controller. */
134 bool is_sw = false;
135 /** A cache READ: the outcome class and the contents update are drawn at firing. */
136 bool is_cache = false;
137
138 /** `find(P(:,k))` and its cumulative weights, when the destination is drawn. */
139 std::vector<std::size_t> to_slots;
140 std::vector<double> cdf;
141 /** `find(S(:,k) < 0)`, the slots the firing decrements. */
142 std::vector<std::size_t> from_slots;
143 std::size_t nnzP = 0;
144 /** `find(S(:,k) > 0)` when the destination is deterministic; npos = none. */
145 std::size_t det_dest = static_cast<std::size_t>(-1);
146
147 /**
148 * A STATE-DEPENDENT destination, resolved at firing time rather than drawn
149 * from `cdf`.
150 *
151 * `refresh_routing` expands RROBIN, WRROBIN, JSQ and SQ into a probability
152 * split so that the matrix solvers have a matrix to read, and that split is
153 * what `cdf` above would carry. It is the right answer for a mean-value
154 * solver and the WRONG one for a sample path: a round-robin dispatcher
155 * sends the k-th job to the k-th target, not to a uniformly drawn one, and
156 * that is precisely the variance the strategy exists to remove. So a
157 * reaction leaving a node that declares one of the four keeps the CANDIDATE
158 * list instead, in the order `refresh_routing` enumerates it, and picks
159 * from the live population.
160 */
162 /** One candidate per declared out-arc: the destination (node, class). */
163 std::vector<std::size_t> sd_node, sd_class;
164 /** WRROBIN weights, normalised; empty for the other three. */
165 std::vector<double> sd_weight;
166 /** Per-candidate entry-phase slots and their `pie` weights. */
167 std::vector<std::vector<std::size_t>> sd_slots;
168 std::vector<std::vector<double>> sd_pie;
169};
170
171} // namespace detail
172
173/**
174 * The NRM engine: the reaction network built from `sn`, and the sample path.
175 *
176 * It is a class rather than a chain of free functions because the run loop
177 * threads eight pieces of mutable state (the population vector, the per-node
178 * buffers, the in-service phase multisets, the clocks, the propensities and the
179 * three metric accumulators) through every step, and the reference threads the
180 * same eight as arguments to a single 700-line function.
181 */
182template <class T>
184public:
186 : sn_(sn), opt_(opt), rng_(opt.seed) {
187 build_layout();
188 check_peaks();
189 build_regions();
190 build_reactions();
191 rr_cursor_.assign(I_ * K_ + K_ + 1, 0);
192 build_dependencies();
193 build_initial_state();
194 }
195
196 /** Run `opt.samples` firings and return the time-averaged metrics. */
198
199 /** The state-vector length, for the tests that assert the phase expansion. */
200 std::size_t nstates() const { return NS_; }
201 /** The reaction count, likewise. */
202 std::size_t nreactions() const { return rx_.size(); }
203 /** The cache write-back of the last `run()`, one entry per Cache node. */
204 const std::vector<SsaCacheRatio>& cache() const { return cache_out_; }
205
206private:
207 using SchedStrategy = lang::SchedStrategy;
208 using Rx = detail::NrmReaction;
209
210 // ---- the model ---------------------------------------------------------
211 const qn::NetworkStruct<T>& sn_;
212 SsaOptions opt_;
213 SsaRng rng_;
214
215 std::size_t I_ = 0, K_ = 0, M_ = 0, NS_ = 0, maxnph_ = 1;
216
217 // ---- the (node, class, phase) slot layout ------------------------------
218 std::vector<std::vector<std::size_t>> phoff_, nph_;
219 std::vector<std::size_t> slot_node_, slot_class_;
220
221 // ---- per-node and per-station data read by the rate laws ---------------
222 std::vector<bool> is_station_;
223 std::vector<std::size_t> to_station_; ///< 0-based station, npos when not a station
224 std::vector<double> mi_; ///< servers, infinite off a station
225 std::vector<std::vector<double>> rate_;
226 std::vector<std::vector<std::vector<double>>> pie_; ///< entry-phase law per (node, class)
227 std::vector<std::vector<bool>> buf_ph_class_;
228 std::vector<bool> buf_ph_node_;
229 std::vector<SchedStrategy> sched_;
230 std::vector<std::vector<double>> lld_; ///< per station, empty when not load dependent
231 std::vector<std::vector<double>> wnorm_; ///< per station, normalized DPS/GPS weights
232 std::vector<double> classprio_;
233 std::vector<double> nservers_;
234
235 // ---- the reaction network ---------------------------------------------
236 std::vector<Rx> rx_;
238 std::vector<std::vector<std::size_t>> D_;
239 /** Departure reactions of each (station, class), for the throughput integral. */
240 std::vector<std::vector<std::vector<std::size_t>>> dep_rx_;
241 /**
242 * Stations and classes at which a refused arrival must BLOCK rather than be
243 * lost, and whether any exist at all. See `capacity_block`.
244 */
245 std::vector<std::vector<char>> blk_can_;
246 bool blk_on_ = false;
247
248 // ---- the sample path ---------------------------------------------------
249 std::vector<double> nvec0_;
250 std::vector<std::vector<std::size_t>> buffers0_;
251 std::vector<Matrix<double>> svcph0_;
252 /**
253 * The derived START and PREEMPT tags, as COUNTS of events along the path;
254 * `run` divides them by the simulated time. This engine has no
255 * `EventOutcome` to annotate -- it is a reaction network, not a state
256 * machine -- so the tags are raised where the buffer moves, which is the
257 * only place a job can take or lose a server here. Both engines must carry
258 * them or the counters would depend on `options.method`.
259 */
260 Matrix<double> start_cnt_, preempt_cnt_;
261 /**
262 * Departures that were BLOCKED, per (station, class). `TN` integrates the
263 * PROPENSITY, which counts a departure the station never makes once its
264 * successor is full (0.744 against the exact 0.652 on the BUG-81 tandem), so
265 * the blocked firings are subtracted from that integral before it is
266 * normalized. In expectation the count IS the integral of the blocked share
267 * of the rate, so the difference is unbiased -- and unlike recomputing that
268 * share it needs no second evaluation of a state-dependent dispatcher, whose
269 * draw would otherwise have to be replayed.
270 */
271 Matrix<double> block_cnt_;
272
273 /**
274 * One finite capacity region, `fcrPrecompute`: its member NODES, so the gate
275 * reads the population straight off the state vector, the caps reduced over
276 * the member rows (infinity = unbounded), and the per-class rule.
277 */
278 struct FcrRegion {
279 std::vector<char> member_node; ///< per node
280 std::vector<double> ccap; ///< per class
281 double gcap = std::numeric_limits<double>::infinity();
282 double memcap = std::numeric_limits<double>::infinity();
283 std::vector<double> sz; ///< per-class memory footprint
284 Matrix<double> A; ///< optional linear constraint A n <= b
285 std::vector<double> b;
286 std::vector<char> waitq; ///< per class: WAITQ parks, DROP loses
287 };
288 std::vector<FcrRegion> fcr_;
289 bool fcr_any_waitq_ = false;
290
291 /**
292 * The polling controller of each node, the reference's `buffers{ind} =
293 * [mode, pos, swk, ctr]`: mode 0 parked, 1 serving `pos`, 2 switching
294 * towards `pos` in switchover phase `swk` (0-based). `pos` is 1-based, as
295 * `qn::polling_next` reads it. Mutable path state, like the buffers, but a
296 * member so the propensity can read it without widening its signature.
297 */
298 // ---- the Cache sub-engine, `solver_ssa_nrm.m` lines 103-160 / cacheAccess --
299 /** 1 at a Cache node; `cache_read_[ind][r]` marks the classes that READ there. */
300 std::vector<char> is_cache_node_;
301 std::vector<std::vector<char>> cache_read_;
302 /** The contents row of each cache, laid out as `after_event_cache` reads it. */
303 std::vector<std::vector<T>> cache_var0_, cache_var_;
304 /** Jobs PRODUCED per (cache node, class), and merges per (cache node, read class). */
305 Matrix<double> cache_prod_, cache_dly_;
306 std::vector<SsaCacheRatio> cache_out_;
307 void cache_fire(const Rx& x, std::vector<double>& X, std::size_t& dest_pos, bool& have_dest);
308 void cache_write_back();
309
310 struct PollCtrl {
311 int mode = 0;
312 std::size_t pos = 1;
313 std::size_t swk = 0;
314 long ctr = 0;
315 };
316 std::vector<char> is_poll_;
317 std::vector<qn::PollingInfo<T>> poll_info_;
318 std::vector<PollCtrl> poll_ctrl_;
319 /** The controller row `pollLandCtrl` lands in; raises the START of a visit. */
320 PollCtrl poll_land(std::size_t ind, std::size_t q, int mode, long budget, bool raise = true);
321 /** Per-class populations at node `ind`, as `polling_next` reads them. */
322 std::vector<long> poll_nbuf(const std::vector<double>& X, std::size_t ind) const {
323 std::vector<long> nb(K_, 0);
324 for (std::size_t r = 0; r < K_; ++r) nb[r] = std::lround(class_pop(X, ind, r));
325 return nb;
326 }
327
328 // ---- construction ------------------------------------------------------
329 void build_layout();
330 void build_regions();
331 void build_reactions();
332 void build_dependencies();
333 void build_initial_state();
334
335 // ---- rate-law helpers, one per reference subfunction -------------------
336 double class_pop(const std::vector<double>& X, std::size_t ind, std::size_t r) const {
337 double s = 0.0;
338 for (std::size_t k = 0; k < nph_[ind][r]; ++k) s += X[phoff_[ind][r] + k];
339 return s;
340 }
341 std::vector<double> class_counts(const std::vector<double>& X, std::size_t ind) const {
342 std::vector<double> v(K_, 0.0);
343 for (std::size_t r = 0; r < K_; ++r) v[r] = class_pop(X, ind, r);
344 return v;
345 }
346 double kir_frac(const std::vector<double>& X, std::size_t slot, std::size_t ind,
347 std::size_t r) const {
348 const double nir = class_pop(X, ind, r);
349 return nir <= 0.0 ? 0.0 : X[slot] / nir;
350 }
351 double lldfac(std::size_t ist, double ntot) const {
352 if (ist == npos || lld_[ist].empty() || ntot < 1.0) return 1.0;
353 const std::size_t lim = lld_[ist].size();
354 std::size_t k = static_cast<std::size_t>(std::llround(ntot));
355 if (k > lim) k = lim;
356 return lld_[ist][k - 1];
357 }
358 static double dpsshare(const std::vector<double>& w, const std::vector<double>& n,
359 std::size_t r) {
360 double den = 0.0;
361 for (std::size_t s = 0; s < n.size(); ++s) den += w[s] * n[s];
362 return den <= 0.0 ? 0.0 : w[r] * n[r] / den;
363 }
364 static double gpsshare(const std::vector<double>& w, const std::vector<double>& n,
365 std::size_t r) {
366 if (n[r] <= 0.0) return 0.0;
367 double den = 0.0;
368 for (std::size_t s = 0; s < n.size(); ++s) den += n[s] > 0.0 ? w[s] : 0.0;
369 return den <= 0.0 ? 0.0 : w[r] / den;
370 }
371 /**
372 * The three PRIORITY sharing disciplines, ported 2026-08-15.
373 *
374 * ALL THREE SPLIT AT THE SERVER COUNT, and that is the whole idea: below
375 * capacity every job is in service and the station behaves as its
376 * non-priority twin, so priority cannot matter; above capacity only the
377 * MOST URGENT NON-EMPTY group shares the servers and everyone else is
378 * frozen. LINE orders priorities with the LOWER value more urgent.
379 *
380 * "Non-empty" is doing real work in `urgent`: an empty class never defines
381 * the urgent group, so a station holding only low-priority jobs serves them
382 * rather than stalling on a priority class that is not there.
383 */
384 bool urgent(const std::vector<double>& n, std::size_t r) const {
385 double best = 0.0;
386 bool any = false;
387 for (std::size_t s = 0; s < n.size(); ++s)
388 if (n[s] > 0.0 && (!any || classprio_[s] < best)) {
389 best = classprio_[s];
390 any = true;
391 }
392 return any && classprio_[r] == best;
393 }
394 /** The population vector restricted to r's priority group, and its total. */
395 std::vector<double> prio_group(const std::vector<double>& n, std::size_t r,
396 double* total = nullptr) const {
397 std::vector<double> act(n.size(), 0.0);
398 double tot = 0.0;
399 for (std::size_t s = 0; s < n.size(); ++s)
400 if (classprio_[s] == classprio_[r]) {
401 act[s] = n[s];
402 tot += n[s];
403 }
404 if (total) *total = tot;
405 return act;
406 }
407 double psprioshare(const std::vector<double>& n, std::size_t r, double c) const {
408 double ni = 0.0;
409 for (double v : n) ni += v;
410 if (ni <= 0.0) return 0.0;
411 if (ni <= c) return (n[r] / ni) * std::min(ni, c);
412 if (!urgent(n, r)) return 0.0;
413 double niprio = 0.0;
414 prio_group(n, r, &niprio);
415 return niprio <= 0.0 ? 0.0 : (n[r] / niprio) * std::min(niprio, c);
416 }
417 double dpsprioshare(const std::vector<double>& w, const std::vector<double>& n, std::size_t r,
418 double c) const {
419 double ni = 0.0;
420 for (double v : n) ni += v;
421 if (ni <= 0.0) return 0.0;
422 if (ni <= c) return dpsshare(w, n, r);
423 if (!urgent(n, r)) return 0.0;
424 return dpsshare(w, prio_group(n, r), r);
425 }
426 double gpsprioshare(const std::vector<double>& w, const std::vector<double>& n, std::size_t r,
427 double c) const {
428 double ni = 0.0;
429 for (double v : n) ni += v;
430 if (ni <= 0.0) return 0.0;
431 if (ni <= c) return gpsshare(w, n, r);
432 if (!urgent(n, r)) return 0.0;
433 return gpsshare(w, prio_group(n, r), r);
434 }
435 /**
436 * The population the LOAD-DEPENDENT factor is read at.
437 *
438 * PSPRIO uses the FULL vector in both branches while DPSPRIO and GPSPRIO
439 * use the priority-restricted one above capacity. That asymmetry is
440 * inherited from `State.afterEventStation` and is reproduced rather than
441 * tidied: the two conventions give different lld factors on the same state,
442 * and the reference's numbers were computed with these.
443 */
444 double prio_pop(const std::vector<double>& n, std::size_t r, double c) const {
445 double ni = 0.0;
446 for (double v : n) ni += v;
447 if (ni <= c || !urgent(n, r)) return ni;
448 double niprio = 0.0;
449 prio_group(n, r, &niprio);
450 return niprio;
451 }
452 /** `prioVec`: the vector DPSPRIO / GPSPRIO read the class dependence at. */
453 std::vector<double> prio_vec(const std::vector<double>& n, std::size_t r, double c) const {
454 double ni = 0.0;
455 for (double v : n) ni += v;
456 if (ni <= c || !urgent(n, r)) return n;
457 return prio_group(n, r);
458 }
459 /** Utilization at a dependent station is T*S/peak, so a peak must be declared. */
460 void check_peaks() const {
461 for (std::size_t ist = 0; ist < M_; ++ist) {
462 const auto& st = sn_.stations[ist];
463 const bool on[2] = {static_cast<bool>(st.cdscaling), static_cast<bool>(st.jdscaling)};
464 const std::vector<T>* pks[2] = {&st.cdscalingpeak, &st.jdscalingpeak};
465 const char* names[2] = {"setClassDependence", "setJointDependence"};
466 for (std::size_t h = 0; h < 2; ++h) {
467 if (!on[h]) continue;
468 bool ok = pks[h]->size() >= K_;
469 for (std::size_t k = 0; ok && k < K_; ++k)
470 ok = num_traits<T>::to_double((*pks[h])[k]) > 0.0;
471 if (!ok)
472 throw InputError("SolverSSA(method='nrm'): station '" + st.name +
473 "' declares a dependent scaling with no declared peak rate. "
474 "Utilization there is T*E[S]/peak, so pass the peak to " +
475 names[h]);
476 }
477 }
478 }
479
480 /**
481 * `cdfac`: the class-r entry of eta_i(n) .* beta_{i,r}(n), evaluated on the
482 * station's per-class population at firing time, as `State.afterEventInit`
483 * folds the joint handle into the class one. 1 when neither is declared.
484 */
485 double cdfac(std::size_t ist, const std::vector<double>& n, std::size_t r) const {
486 if (ist == npos) return 1.0;
487 const auto& st = sn_.stations[ist];
488 if (!st.cdscaling && !st.jdscaling) return 1.0;
489 std::vector<T> nt(n.size());
490 for (std::size_t s = 0; s < n.size(); ++s) nt[s] = T(n[s]);
491 double f = 1.0;
492 for (const auto* h : {&st.cdscaling, &st.jdscaling}) {
493 if (!*h) continue;
494 const std::vector<T> v = (*h)(nt);
495 f *= num_traits<T>::to_double(v[std::min(r, v.size() - 1)]);
496 }
497 return f;
498 }
499
500 // ---- the sample path ---------------------------------------------------
501 double propensity(std::size_t j, const std::vector<double>& X,
502 const std::vector<std::vector<std::size_t>>& bufs,
503 const std::vector<Matrix<double>>& svc) const;
504 std::size_t pick_from_buffer(const std::vector<std::size_t>& buf, std::size_t ist);
505 std::size_t draw_entry_phase(std::size_t ind, std::size_t r);
506 bool capacity_loss(const std::vector<double>& X, std::size_t slot) const;
507 /** The PAS parameters of 0-based station `ist`; refuses a station with no mu(c). */
508 const typename qn::NetworkStruct<T>::PasParam& pas_of(std::size_t ist) const;
509 /** `oiIncrements`: Delta_mu of each position of the ordered list `c` (0-based classes). */
510 std::vector<double> pas_increments(std::size_t ist, const std::vector<std::size_t>& c) const;
511 /** `oirate`: the class-r departure rate of the list `c`. */
512 double pas_rate(std::size_t ist, const std::vector<std::size_t>& c, std::size_t r) const;
513 /** `pasInSvc`: class-r jobs at a served position (Delta_mu > 0). */
514 double pas_in_service(std::size_t ist, const std::vector<std::size_t>& c, std::size_t r) const;
515 /** `oiStarted`: tag a START for each position served in `cnew` and not in `cold`. */
516 void pas_tag_started(std::size_t ind, const std::vector<std::size_t>& cold,
517 const std::vector<std::size_t>& cnew);
518 /** `oiDepart`: the pass-and-swap rewrite of a class-r departure. */
519 void pas_depart(std::size_t ind, std::vector<std::size_t>& c, std::size_t r);
520 std::size_t fcr_refusing_region(const std::vector<double>& X, std::size_t src_node,
521 std::size_t src_class, std::size_t dst_node,
522 std::size_t dst_class) const;
523 void fcr_outcome(const std::vector<double>& X, const Rx& x, std::size_t dst_node,
524 std::size_t dst_class, std::vector<std::vector<std::size_t>>& fcr_buf,
525 bool& lost, bool& blocked) const;
526 std::size_t fcr_release_cascade(std::vector<double>& X,
527 std::vector<std::vector<std::size_t>>& bufs,
528 std::vector<std::vector<std::size_t>>& fcr_buf,
529 std::vector<Matrix<double>>& svc, bool& svc_changed);
530 bool capacity_block(const std::vector<double>& X, std::size_t slot,
531 std::size_t src_slot) const;
532 std::size_t pick_preempted(const std::vector<double>& X,
533 const std::vector<std::size_t>& buf, std::size_t jnd,
534 std::size_t arr_class);
535 void apply_arrival_buffer(std::size_t jnd, std::size_t s, const std::vector<double>& X,
536 std::vector<std::vector<std::size_t>>& bufs,
537 std::vector<Matrix<double>>& svc, bool& svc_changed);
538 void update_buffers(std::size_t kfire, const std::vector<double>& X,
539 std::vector<std::vector<std::size_t>>& bufs, std::size_t dest_pos,
540 bool have_dest, std::vector<Matrix<double>>& svc, bool& svc_changed);
541
542 /** Fill `sd_*` on a reaction leaving a node that routes by strategy. */
543 void build_state_dependent_dest(Rx& x);
544 /** Pick the destination slot of a state-dependent firing from the live state. */
545 std::size_t resolve_state_dependent_dest(std::size_t kfire, const std::vector<double>& X);
546
547 /**
548 * Round-robin cursor per (SOURCE NODE, CLASS), keyed `node * K_ + cls`.
549 * Not per reaction: a phase-type service splits one dispatcher across
550 * several reactions and a pointer each would let the phases cycle
551 * independently, which is not a round robin.
552 */
553 std::vector<std::size_t> rr_cursor_;
554
555 /** Raise a START (or, with `preempt`, a PREEMPT) for class R at node IND. */
556 void tag(std::size_t ind, std::size_t r, bool preempt) {
557 if (!is_station_[ind] || r >= K_) return;
558 const std::size_t ist = to_station_[ind];
559 if (ist >= M_) return;
560 // A Source CREATES jobs rather than admitting them to service, so it
561 // seizes nothing; every codebase reports a zero row for it.
562 if (sched_[ist] == SchedStrategy::EXT) return;
563 (preempt ? preempt_cnt_ : start_cnt_)(ist, r) += 1.0;
564 }
565
566 static constexpr std::size_t npos = static_cast<std::size_t>(-1);
567};
568
569// ---------------------------------------------------------------------------
570// Construction
571// ---------------------------------------------------------------------------
572
573/**
574 * The phase slot map, `solver_ssa_nrm.m` lines 33-111.
575 *
576 * The state vector counts jobs per (node, class, PHASE) so phase-type service
577 * is represented exactly instead of collapsed onto its mean rate. With one
578 * phase everywhere the layout degenerates to the flat (node, class) index, so
579 * an exponential model is unaffected -- which is the self-check the reference
580 * names for this generalization.
581 */
582template <class T>
583void NrmEngine<T>::build_layout() {
584 I_ = sn_.nof_nodes();
585 K_ = sn_.nclasses;
586 M_ = sn_.nstations;
587
588 is_station_.assign(I_, false);
589 to_station_.assign(I_, npos);
590 for (std::size_t i = 0; i < I_; ++i)
591 if (sn_.nodes[i].station != 0) {
592 is_station_[i] = true;
593 to_station_[i] = sn_.nodes[i].station - 1;
594 }
595
596 sched_.assign(M_, SchedStrategy::FCFS);
597 nservers_.assign(M_, 1.0);
598 for (std::size_t i = 0; i < M_; ++i) {
599 sched_[i] = sn_.stations[i].sched;
600 nservers_[i] = sn_.stations[i].nservers;
601 }
602
603 // Phase counts. `sn.phasessz` floors at one, so a disabled pair still owns
604 // exactly one slot and its zero rate silences the reaction.
605 nph_.assign(I_, std::vector<std::size_t>(K_, 1));
606 pie_.assign(I_, std::vector<std::vector<double>>(K_));
607 for (std::size_t i = 0; i < I_; ++i) {
608 for (std::size_t r = 0; r < K_; ++r) {
609 pie_[i][r].assign(1, 1.0);
610 if (!is_station_[i]) continue;
611 const std::size_t ist = to_station_[i];
612 if (sn_.disabled[ist][r]) continue;
613 const mam::Map<T> m = lang::dist_to_map(sn_.service[ist][r]);
614 const std::size_t n = m.D0.rows();
615 if (n <= 1) continue;
616 nph_[i][r] = n;
617 const std::vector<T> p = lang::dist_pie(sn_.service[ist][r]);
618 std::vector<double> pd(n, 0.0);
619 double tot = 0.0;
620 for (std::size_t k = 0; k < n && k < p.size(); ++k) {
621 pd[k] = num_traits<T>::to_double(p[k]);
622 if (!(pd[k] > 0.0)) pd[k] = 0.0;
623 tot += pd[k];
624 }
625 if (tot > 0.0) {
626 for (double& x : pd) x /= tot;
627 } else {
628 pd.assign(n, 0.0);
629 pd[0] = 1.0;
630 }
631 pie_[i][r] = pd;
632 }
633 }
634
635 phoff_.assign(I_, std::vector<std::size_t>(K_, 0));
636 NS_ = 0;
637 maxnph_ = 1;
638 for (std::size_t i = 0; i < I_; ++i)
639 for (std::size_t r = 0; r < K_; ++r) {
640 phoff_[i][r] = NS_;
641 NS_ += nph_[i][r];
642 maxnph_ = std::max(maxnph_, nph_[i][r]);
643 }
644 slot_node_.assign(NS_, 0);
645 slot_class_.assign(NS_, 0);
646 for (std::size_t i = 0; i < I_; ++i)
647 for (std::size_t r = 0; r < K_; ++r)
648 for (std::size_t k = 0; k < nph_[i][r]; ++k) {
649 slot_node_[phoff_[i][r] + k] = i;
650 slot_class_[phoff_[i][r] + k] = r;
651 }
652
653 // Buffered phase-type service: only the jobs ACTUALLY in service carry a
654 // phase, so their composition lives in svcph and not in the population.
655 buf_ph_class_.assign(I_, std::vector<bool>(K_, false));
656 buf_ph_node_.assign(I_, false);
657 for (std::size_t i = 0; i < I_; ++i) {
658 if (!is_station_[i] || !detail::sched_is_buf_ph(sched_[to_station_[i]])) continue;
659 for (std::size_t r = 0; r < K_; ++r)
660 if (nph_[i][r] > 1) {
661 buf_ph_class_[i][r] = true;
662 buf_ph_node_[i] = true;
663 }
664 }
665
666 // Rates, server counts and the scaling tables the rate laws read.
667 const double inf = std::numeric_limits<double>::infinity();
668 mi_.assign(I_, inf);
669 rate_.assign(I_, std::vector<double>(K_, 0.0));
670 for (std::size_t i = 0; i < I_; ++i) {
671 if (is_station_[i]) {
672 const std::size_t ist = to_station_[i];
673 mi_[i] = sn_.stations[ist].nservers;
674 for (std::size_t r = 0; r < K_; ++r)
675 if (!sn_.disabled[ist][r])
676 rate_[i][r] = num_traits<T>::to_double(sn_.rates(ist, r));
677 } else {
678 for (std::size_t r = 0; r < K_; ++r)
680 }
681 }
682
683 lld_.assign(M_, std::vector<double>());
684 wnorm_.assign(M_, std::vector<double>(K_, 0.0));
685 for (std::size_t i = 0; i < M_; ++i) {
686 for (const T& x : sn_.stations[i].lldscaling)
687 lld_[i].push_back(num_traits<T>::to_double(x));
688 if (!detail::sched_is_weighted(sched_[i])) continue;
689 double tot = 0.0;
690 for (std::size_t r = 0; r < K_ && r < sn_.stations[i].schedparam.size(); ++r)
691 tot += num_traits<T>::to_double(sn_.stations[i].schedparam[r]);
692 if (!(tot > 0.0))
693 throw InputError("solver_ssa_nrm: station '" + sn_.stations[i].name + "' has " +
694 std::string(lang::sched_to_text(sched_[i])) +
695 " scheduling with non-positive total weight");
696 if (sn_.stations[i].nservers > 1.0)
697 throw UnsupportedError(ErrorKind{"MultiServer"},
698 "solver_ssa_nrm: multi-server " + std::string(lang::sched_to_text(sched_[i])) +
699 " at station '" + sn_.stations[i].name +
700 "' is not supported; the reference's State.afterEventStation rejects it too");
701 for (std::size_t r = 0; r < K_ && r < sn_.stations[i].schedparam.size(); ++r)
702 wnorm_[i][r] = num_traits<T>::to_double(sn_.stations[i].schedparam[r]) / tot;
703 }
704
705 classprio_.assign(K_, 0.0);
706 for (std::size_t r = 0; r < K_; ++r) classprio_[r] = sn_.classes[r].prio;
707}
708
709/**
710 * `fcrPrecompute`: the finite capacity regions, field for field.
711 *
712 * A region constrains an aggregate of the per-class populations of its member
713 * stations, which is a linear function of the NRM state vector, so admission is
714 * a 0/1 gate on the drawn destination. DROP loses the refused job at the gate,
715 * as a balked arrival is lost; WAITQ parks it in the refusing region's FIFO,
716 * which is state the reaction network does not carry and therefore rides beside
717 * the buffers (`fcr_buf` in `run`).
718 */
719template <class T>
720void NrmEngine<T>::build_regions() {
721 const double inf = std::numeric_limits<double>::infinity();
722 fcr_.clear();
723 fcr_any_waitq_ = false;
724 for (const typename qn::NetworkStruct<T>::Region& rg : sn_.regions) {
725 FcrRegion f;
726 f.member_node.assign(I_, 0);
727 f.ccap.assign(K_, inf);
728 f.sz.assign(K_, 1.0);
729 f.waitq.assign(K_, 0);
730 for (std::size_t i = 0; i < M_ && i < rg.members.size(); ++i) {
731 if (!rg.members[i]) continue;
732 f.member_node[sn_.station_to_node[i] - 1] = 1;
733 for (std::size_t r = 0; r < K_; ++r)
734 if (rg.cap[i][r] != -1.0) f.ccap[r] = std::min(f.ccap[r], rg.cap[i][r]);
735 if (rg.cap[i][K_] != -1.0) f.gcap = std::min(f.gcap, rg.cap[i][K_]);
736 if (i < rg.maxmem.size() && rg.maxmem[i] != -1.0)
737 f.memcap = std::min(f.memcap, rg.maxmem[i]);
738 }
739 for (std::size_t r = 0; r < K_ && r < rg.size.size(); ++r)
740 f.sz[r] = num_traits<T>::to_double(rg.size[r]);
741 for (std::size_t r = 0; r < K_ && r < rg.rule.size(); ++r) {
742 const qn::DropStrategy d = rg.rule[r];
743 if (d == qn::DropStrategy::BAS || d == qn::DropStrategy::BBS ||
744 d == qn::DropStrategy::RSRD)
745 throw UnsupportedError(ErrorKind{"Region"},
746 "solver_ssa_nrm: finite capacity region '" + rg.name + "' declares a "
747 "blocking rule for class '" + sn_.classes[r].name + "'; only DROP and WAITQ "
748 "are region rules in any codebase's NRM");
749 f.waitq[r] = d != qn::DropStrategy::DROP;
750 if (f.waitq[r]) fcr_any_waitq_ = true;
751 }
752 if (rg.lincon_A.rows() > 0) {
753 f.A = Matrix<double>(rg.lincon_A.rows(), rg.lincon_A.cols(), 0.0);
754 for (std::size_t a = 0; a < rg.lincon_A.rows(); ++a)
755 for (std::size_t c = 0; c < rg.lincon_A.cols(); ++c)
756 f.A(a, c) = num_traits<T>::to_double(rg.lincon_A(a, c));
757 for (const T& v : rg.lincon_b) f.b.push_back(num_traits<T>::to_double(v));
758 }
759 fcr_.push_back(f);
760 }
761}
762
763/**
764 * `fcrRefusingRegion`: the 1-based index of the FIRST region that refuses a
765 * class-`dst_class` job entering `dst_node` having just left `src_node` as
766 * `src_class`, or 0 when every region admits it.
767 *
768 * Only a region holding the destination can refuse; a source in the same region
769 * frees its slot first. `src_node == npos` is a WAITQ release, whose job already
770 * left its source when it was parked, so no slot is freed.
771 */
772template <class T>
773std::size_t NrmEngine<T>::fcr_refusing_region(const std::vector<double>& X, std::size_t src_node,
774 std::size_t src_class, std::size_t dst_node,
775 std::size_t dst_class) const {
776 for (std::size_t f = 0; f < fcr_.size(); ++f) {
777 const FcrRegion& g = fcr_[f];
778 if (!g.member_node[dst_node]) continue;
779 std::vector<double> x(K_, 0.0);
780 for (std::size_t jnd = 0; jnd < I_; ++jnd)
781 if (g.member_node[jnd])
782 for (std::size_t r = 0; r < K_; ++r) x[r] += class_pop(X, jnd, r);
783 if (src_node != npos && g.member_node[src_node]) x[src_class] -= 1.0;
784 x[dst_class] += 1.0;
785 double tot = 0.0, mem = 0.0;
786 bool bad = false;
787 for (std::size_t r = 0; r < K_; ++r) {
788 tot += x[r];
789 mem += x[r] * g.sz[r];
790 if (x[r] > g.ccap[r]) bad = true;
791 }
792 if (tot > g.gcap || mem > g.memcap) bad = true;
793 for (std::size_t a = 0; !bad && a < g.A.rows() && a < g.b.size(); ++a) {
794 double lhs = 0.0;
795 for (std::size_t c = 0; c < K_ && c < g.A.cols(); ++c) lhs += g.A(a, c) * x[c];
796 if (lhs > g.b[a]) bad = true;
797 }
798 if (bad) return f + 1;
799 }
800 return 0;
801}
802
803template <class T>
804const typename qn::NetworkStruct<T>::PasParam& NrmEngine<T>::pas_of(std::size_t ist) const {
805 const auto it = sn_.pasparam.find(ist + 1);
806 if (it == sn_.pasparam.end() || !it->second.svc_rate_fun)
807 throw InputError("solver_ssa_nrm: PAS/OI station '" + sn_.stations[ist].name +
808 "' has no service rate function mu(c); set one with set_pas");
809 return it->second;
810}
811
812template <class T>
813std::vector<double> NrmEngine<T>::pas_increments(std::size_t ist,
814 const std::vector<std::size_t>& c) const {
815 const auto& mu = pas_of(ist).svc_rate_fun;
816 std::vector<double> inc(c.size(), 0.0);
817 std::vector<std::size_t> prefix;
818 double prev = 0.0;
819 for (std::size_t p = 0; p < c.size(); ++p) {
820 prefix.push_back(c[p] + 1); // mu(c) reads 1-based class indices
821 const double cur = num_traits<T>::to_double(mu(prefix));
822 inc[p] = cur - prev;
823 prev = cur;
824 }
825 return inc;
826}
827
828template <class T>
829double NrmEngine<T>::pas_rate(std::size_t ist, const std::vector<std::size_t>& c,
830 std::size_t r) const {
831 if (c.empty()) return 0.0;
832 const std::vector<double> inc = pas_increments(ist, c);
833 std::vector<std::size_t> c1(c.size());
834 for (std::size_t p = 0; p < c.size(); ++p) c1[p] = c[p] + 1;
835 const auto& G = pas_of(ist).swap_graph;
836 double rt = 0.0;
837 for (std::size_t p = 0; p < c.size(); ++p) {
838 if (inc[p] <= 0.0) continue; // position p receives no service
839 if (qn::pass_and_swap<T>(c1, p, G).second == r + 1) rt += inc[p];
840 }
841 return rt;
842}
843
844template <class T>
845double NrmEngine<T>::pas_in_service(std::size_t ist, const std::vector<std::size_t>& c,
846 std::size_t r) const {
847 if (c.empty()) return 0.0;
848 const std::vector<double> inc = pas_increments(ist, c);
849 double n = 0.0;
850 for (std::size_t p = 0; p < c.size(); ++p)
851 if (inc[p] > 0.0 && c[p] == r) n += 1.0;
852 return n;
853}
854
855template <class T>
856void NrmEngine<T>::pas_tag_started(std::size_t ind, const std::vector<std::size_t>& cold,
857 const std::vector<std::size_t>& cnew) {
858 const std::size_t ist = to_station_[ind];
859 const std::vector<double> inc_new = pas_increments(ist, cnew);
860 const std::vector<double> inc_old = pas_increments(ist, cold);
861 for (std::size_t p = 0; p < inc_new.size(); ++p) {
862 if (inc_new[p] <= 0.0) continue;
863 if (p < inc_old.size() && inc_old[p] > 0.0) continue; // already served
864 tag(ind, cnew[p], false);
865 }
866}
867
868/**
869 * The completing position is drawn among those whose pass-and-swap ejects class
870 * r, weighted by that position's own Delta_mu -- the split whose total is the
871 * propensity that just fired.
872 */
873template <class T>
874void NrmEngine<T>::pas_depart(std::size_t ind, std::vector<std::size_t>& c, std::size_t r) {
875 const std::size_t ist = to_station_[ind];
876 const std::vector<double> inc = pas_increments(ist, c);
877 std::vector<std::size_t> c1(c.size());
878 for (std::size_t p = 0; p < c.size(); ++p) c1[p] = c[p] + 1;
879 const auto& G = pas_of(ist).swap_graph;
880 std::vector<std::size_t> pos;
881 std::vector<double> w;
882 double tot = 0.0;
883 for (std::size_t p = 0; p < c.size(); ++p) {
884 if (inc[p] <= 0.0) continue;
885 if (qn::pass_and_swap<T>(c1, p, G).second != r + 1) continue;
886 pos.push_back(p);
887 w.push_back(inc[p]);
888 tot += inc[p];
889 }
890 if (pos.empty()) return; // this class cannot depart from the current list
891 const double u = rng_.uniform() * tot;
892 double acc = 0.0;
893 std::size_t pick = pos.back();
894 for (std::size_t x = 0; x < pos.size(); ++x) {
895 acc += w[x];
896 if (u < acc) {
897 pick = pos[x];
898 break;
899 }
900 }
901 const std::vector<std::size_t> nc = qn::pass_and_swap<T>(c1, pick, G).first;
902 c.assign(nc.size(), 0);
903 for (std::size_t p = 0; p < nc.size(); ++p) c[p] = nc[p] - 1;
904}
905
906/**
907 * `pollLandCtrl`: SERVING q with the visit budget, SWITCHING into q with the
908 * entry phase drawn from the switchover PH, or PARKED. A landing in SERVING is
909 * the moment a class-q job takes the server, so it raises that START here: the
910 * reference raises none at a polling station at all, which leaves StartN zero
911 * there although jobs plainly start service.
912 */
913template <class T>
914typename NrmEngine<T>::PollCtrl NrmEngine<T>::poll_land(std::size_t ind, std::size_t q, int mode,
915 long budget, bool raise) {
916 PollCtrl c;
917 c.pos = q;
918 c.mode = mode;
919 if (mode == 1) {
920 c.ctr = budget;
921 if (raise) tag(ind, q - 1, false);
922 } else if (mode == 2) {
923 const std::vector<T>& pie = poll_info_[ind].sw_pie[q - 1];
924 std::vector<double> w(pie.size());
925 for (std::size_t k = 0; k < pie.size(); ++k) w[k] = num_traits<T>::to_double(pie[k]);
926 c.swk = rng_.draw(w);
927 }
928 return c;
929}
930
931/**
932 * What a region refusal does to the firing, by the refusing region's rule for
933 * the destination class.
934 *
935 * WAITQ parks the job in that region's FIFO: it leaves its source and joins no
936 * station until `fcr_release_cascade` admits it. DROP LOSES an open job, as a
937 * balked arrival is lost. A CLOSED job refused under DROP is BLOCKED instead --
938 * the firing is cancelled and the job keeps its place -- which is this
939 * codebase's reading of the rule (SolverCTMC censors the transition and the
940 * serial engine does not take it, so the population is conserved). The
941 * reference's NRM, CTMC and serial engines instead all lose the closed job, so
942 * the population decays until the region can never refuse again: 1 job of 3 on
943 * the capped three-station cycle. That cross-language divergence belongs to the
944 * rule, not to this engine; see `_kb/07-cross-language-parity.md`.
945 */
946template <class T>
947void NrmEngine<T>::fcr_outcome(const std::vector<double>& X, const Rx& x, std::size_t dst_node,
948 std::size_t dst_class,
949 std::vector<std::vector<std::size_t>>& fcr_buf, bool& lost,
950 bool& blocked) const {
951 const std::size_t fref = fcr_refusing_region(X, x.node, x.cls, dst_node, dst_class);
952 if (fref == 0) return;
953 if (fcr_[fref - 1].waitq[dst_class]) {
954 lost = true;
955 fcr_buf[fref - 1].push_back(dst_node * K_ + dst_class);
956 } else if (std::isinf(sn_.classes[dst_class].population)) {
957 lost = true;
958 } else {
959 blocked = true;
960 }
961}
962
963/**
964 * `fcrReleaseCascade`: strict-FIFO head-of-line release of the parked WAITQ
965 * jobs. Each region's head is admitted while its constraints permit, joining the
966 * destination as a routed arrival does (entry phase drawn at release, buffer
967 * join, START tag); the loop repeats until a full pass frees nothing, so a
968 * release that relieves another region cascades. Returns the jobs released.
969 */
970template <class T>
971std::size_t NrmEngine<T>::fcr_release_cascade(std::vector<double>& X,
972 std::vector<std::vector<std::size_t>>& bufs,
973 std::vector<std::vector<std::size_t>>& fcr_buf,
974 std::vector<Matrix<double>>& svc,
975 bool& svc_changed) {
976 std::size_t released = 0;
977 bool progress = true;
978 while (progress) {
979 progress = false;
980 for (std::size_t f = 0; f < fcr_buf.size(); ++f) {
981 if (fcr_buf[f].empty()) continue;
982 const std::size_t tok = fcr_buf[f].front();
983 const std::size_t jnd = tok / K_, r = tok % K_;
984 if (fcr_refusing_region(X, npos, r, jnd, r) != 0) continue; // head-of-line
985 // A buffered-PH destination counts the job in its class total slot;
986 // whether and in which phase it enters service is decided against the
987 // server occupancy by `apply_arrival_buffer`, as for a routed arrival.
988 const std::size_t ke = buf_ph_node_[jnd] ? 0 : draw_entry_phase(jnd, r);
989 X[phoff_[jnd][r] + ke] += 1.0;
990 apply_arrival_buffer(jnd, r, X, bufs, svc, svc_changed);
991 fcr_buf[f].erase(fcr_buf[f].begin());
992 ++released;
993 progress = true;
994 }
995 }
996 return released;
997}
998
999/**
1000 * The stoichiometry and the reaction list, `solver_ssa_nrm.m` lines 190-355.
1001 *
1002 * A departure is the ABSORPTION of the phase-type service process, so it fires
1003 * at the D1 row sum of the phase it leaves and the job re-enters its
1004 * destination in an entry phase drawn from pie -- which is why the destination
1005 * weight is the product of the routing probability and the entry probability. A
1006 * phase change is an off-diagonal of D0 and never leaves the node.
1007 */
1008template <class T>
1009void NrmEngine<T>::build_reactions() {
1010 rx_.clear();
1011 // A class READS at a cache iff it has a popularity row and either a hit class
1012 // or is one of the cache's retrieval classes, which read to COMPLETE a miss.
1013 is_cache_node_.assign(I_, 0);
1014 cache_read_.assign(I_, std::vector<char>(K_, 0));
1015 for (std::size_t ind = 0; ind < I_; ++ind) {
1016 if (sn_.nodes[ind].nodetype != qn::NodeType::Cache) continue;
1017 const auto ci = sn_.nodeparam.find(ind + 1);
1018 if (ci == sn_.nodeparam.end())
1019 throw InputError("solver_ssa_nrm: Cache node '" + sn_.nodes[ind].name +
1020 "' has no cache parameters");
1021 const qn::CacheParam<T>& cp = ci->second;
1022 is_cache_node_[ind] = 1;
1023 std::vector<std::size_t> rcl, rci, rco;
1024 if (cp.retrieval_capacity > 0) qn::cache_retrieval_class_map(cp, rcl, rci, rco);
1025 for (std::size_t r = 0; r < K_; ++r) {
1026 if (r >= cp.pread.size() || cp.pread[r].empty()) continue;
1027 const bool is_retr = std::find(rcl.begin(), rcl.end(), r + 1) != rcl.end();
1028 const std::size_t hc = r < cp.hitclass.size() ? cp.hitclass[r] : 0;
1029 const std::size_t mc = r < cp.missclass.size() ? cp.missclass[r] : 0;
1030 if (hc == 0 && !is_retr) continue;
1031 // A read class that is its own hit or miss class would read again on
1032 // the spot: the reference NRM livelocks there, so it is refused.
1033 if (hc == r + 1 || mc == r + 1)
1034 throw UnsupportedError(ErrorKind{"Cache"},
1035 "solver_ssa_nrm: class '" + sn_.classes[r].name + "' at Cache '" +
1036 sn_.nodes[ind].name + "' is its own hit or miss class, so the NRM's cache "
1037 "read would fire again at once; ask for method='serial'");
1038 cache_read_[ind][r] = 1;
1039 }
1040 }
1041 // Departures, one per (node, class, phase).
1042 for (std::size_t ind = 0; ind < I_; ++ind) {
1043 for (std::size_t r = 0; r < K_; ++r) {
1044 for (std::size_t kk = 0; kk < nph_[ind][r]; ++kk) {
1045 Rx x;
1046 x.node = ind;
1047 x.cls = r;
1048 x.dep_phase = kk;
1049 x.is_buf_svc = buf_ph_class_[ind][r];
1050 // At a buffered-PH source the population lives entirely in the
1051 // first phase slot; which phase completed is carried in
1052 // dep_phase and consumed from svcph at firing.
1053 x.from = buf_ph_class_[ind][r] ? phoff_[ind][r] : phoff_[ind][r] + kk;
1054 x.rate = rate_[ind][r];
1055 x.is_cache = is_cache_node_[ind] && cache_read_[ind][r];
1056 if (is_station_[ind] && nph_[ind][r] > 1) {
1057 const std::size_t ist = to_station_[ind];
1058 const mam::Map<T> m = lang::dist_to_map(sn_.service[ist][r]);
1059 double s = 0.0;
1060 for (std::size_t c = 0; c < m.D1.cols(); ++c)
1061 s += num_traits<T>::to_double(m.D1(kk, c));
1062 x.rate = s;
1063 }
1064 rx_.push_back(x);
1065 }
1066 }
1067 }
1068 const std::size_t ndep = rx_.size();
1069
1070 // Phase transitions, one per (node, class, ka -> kb) with D0(ka,kb) > 0.
1071 for (std::size_t ind = 0; ind < I_; ++ind) {
1072 if (!is_station_[ind]) continue;
1073 const std::size_t ist = to_station_[ind];
1074 for (std::size_t r = 0; r < K_; ++r) {
1075 if (nph_[ind][r] <= 1 || sn_.disabled[ist][r]) continue;
1076 const mam::Map<T> m = lang::dist_to_map(sn_.service[ist][r]);
1077 for (std::size_t ka = 0; ka < nph_[ind][r]; ++ka)
1078 for (std::size_t kb = 0; kb < nph_[ind][r]; ++kb) {
1079 if (ka == kb) continue;
1080 const double d = num_traits<T>::to_double(m.D0(ka, kb));
1081 if (!(d > 0.0)) continue;
1082 Rx x;
1083 x.node = ind;
1084 x.cls = r;
1085 x.is_phase = true;
1086 x.phase_from = ka;
1087 x.phase_to = kb;
1088 x.rate = d;
1089 // A buffered-PH phase change moves a job inside svcph and
1090 // leaves the population alone, so its stoichiometry column
1091 // is all zeros and its propensity reads the first slot.
1092 x.from = buf_ph_class_[ind][r] ? phoff_[ind][r] : phoff_[ind][r] + ka;
1093 rx_.push_back(x);
1094 }
1095 }
1096 }
1097
1098 // Polling switchover reactions, `solver_ssa_nrm.m` lines 419-482. A walk
1099 // between buffers is a timed event that moves no job, so it is one reaction
1100 // per polling node with a timed switchover: an all-zero stoichiometry column
1101 // whose propensity reads the controller. Only EXPONENTIAL service is taken at
1102 // a polling station: the controller tracks no in-service phase, and spreading
1103 // the class over phases would serve several fictitious phase-jobs at once.
1104 is_poll_.assign(I_, 0);
1105 poll_info_.assign(I_, qn::PollingInfo<T>());
1106 // The controller below is the plain cyclic one: a polling table,
1107 // load-dependent order or visit timer has no reaction form here.
1108 {
1109 const std::string pext = api::sn_polling_extension(sn_);
1110 if (!pext.empty())
1111 throw UnsupportedError(ErrorKind{pext},
1112 "The NRM method has no form for the " + pext +
1113 " polling extension; use options.method='serial'.");
1114 }
1115 for (std::size_t ind = 0; ind < I_; ++ind) {
1116 if (!is_station_[ind] || sched_[to_station_[ind]] != SchedStrategy::POLLING) continue;
1117 is_poll_[ind] = 1;
1118 poll_info_[ind] = qn::polling_info(sn_, ind + 1);
1119 qn::polling_require_ph(poll_info_[ind]);
1120 for (std::size_t r = 0; r < K_; ++r)
1121 if (nph_[ind][r] > 1)
1122 throw UnsupportedError(ErrorKind{"SchedStrategy_POLLING"},
1123 "solver_ssa_nrm: polling station '" + sn_.stations[to_station_[ind]].name +
1124 "' serves class '" + sn_.classes[r].name + "' with phase-type service. The "
1125 "NRM polling controller supports exponential service only, as the reference's "
1126 "does; ask for method='serial'");
1127 bool anysw = false;
1128 for (bool h : poll_info_[ind].has_sw) anysw = anysw || h;
1129 if (!anysw) continue; // every switchover immediate: the server never dwells
1130 Rx x;
1131 x.node = ind;
1132 x.cls = 0;
1133 x.from = phoff_[ind][0];
1134 x.is_sw = true;
1135 rx_.push_back(x);
1136 }
1137
1138 // The stoichiometry matrix, states x reactions.
1139 S_ = Matrix<double>(NS_, rx_.size(), 0.0);
1140 for (std::size_t k = 0; k < rx_.size(); ++k) {
1141 Rx& x = rx_[k];
1142 if (x.is_sw) continue; // a switchover moves no job
1143 if (x.is_cache) {
1144 // The read consumes the job; where it reappears is drawn at firing.
1145 S_(x.from, k) -= 1.0;
1146 continue;
1147 }
1148 if (x.is_phase) {
1149 if (!buf_ph_class_[x.node][x.cls]) {
1150 S_(phoff_[x.node][x.cls] + x.phase_from, k) -= 1.0;
1151 S_(phoff_[x.node][x.cls] + x.phase_to, k) += 1.0;
1152 }
1153 continue;
1154 }
1155 S_(x.from, k) -= 1.0;
1156 for (std::size_t jnd = 0; jnd < I_; ++jnd)
1157 for (std::size_t s = 0; s < K_; ++s) {
1158 const double p =
1159 num_traits<T>::to_double(sn_.rtnodes(x.node * K_ + x.cls, jnd * K_ + s));
1160 if (!(p > 0.0)) continue;
1161 if (buf_ph_class_[jnd][s]) {
1162 // The arrival lands in the total-population slot; whether it
1163 // enters service, and in which phase, is decided at firing
1164 // from the server occupancy and pie.
1165 S_(phoff_[jnd][s], k) += p;
1166 } else {
1167 for (std::size_t ke = 0; ke < nph_[jnd][s]; ++ke) {
1168 const double pe = pie_[jnd][s][ke];
1169 if (!(pe > 0.0)) continue;
1170 S_(phoff_[jnd][s] + ke, k) += p * pe;
1171 }
1172 }
1173 }
1174 }
1175
1176 // `P = S; P(P<0) = P(P<0)+1` selects the destination draw: nnz(P) > 1 means
1177 // the firing must pick among several destination slots, and the weights are
1178 // read off P so a class that routes back into its own slot competes with the
1179 // others on equal footing.
1180 for (std::size_t k = 0; k < rx_.size(); ++k) {
1181 Rx& x = rx_[k];
1182 std::vector<double> Pcol(NS_, 0.0);
1183 for (std::size_t i = 0; i < NS_; ++i) {
1184 const double v = S_(i, k);
1185 Pcol[i] = v < 0.0 ? v + 1.0 : v;
1186 if (v < 0.0) x.from_slots.push_back(i);
1187 if (v > 0.0 && x.det_dest == npos) x.det_dest = i;
1188 }
1189 for (std::size_t i = 0; i < NS_; ++i)
1190 if (Pcol[i] != 0.0) ++x.nnzP;
1191 if (x.nnzP > 1) {
1192 double acc = 0.0;
1193 for (std::size_t i = 0; i < NS_; ++i)
1194 if (Pcol[i] != 0.0) {
1195 x.to_slots.push_back(i);
1196 acc += Pcol[i];
1197 x.cdf.push_back(acc);
1198 }
1199 }
1200 if (!x.is_phase && !x.is_sw) build_state_dependent_dest(x);
1201 }
1202
1203 // Departure reactions of each (station, class): the reference rescans all
1204 // reactions inside the metric loop, which is the same set every step.
1205 dep_rx_.assign(M_, std::vector<std::vector<std::size_t>>(K_));
1206 for (std::size_t k = 0; k < ndep; ++k)
1207 if (is_station_[rx_[k].node]) dep_rx_[to_station_[rx_[k].node]][rx_[k].cls].push_back(k);
1208
1209 // Stations and classes where a refusal BLOCKS; see `capacity_block`.
1210 // A cap that CANNOT BIND is not a blocking site. Every closed model carries
1211 // cap[ist] = N by default, and a station that can hold the whole population
1212 // never refuses one: the arriving job is itself one of the N, so the
1213 // pre-arrival count is at most N-1. Excluding those keeps `blk_on_` false --
1214 // and the per-firing test unpaid -- on ordinary models. An open class present
1215 // anywhere makes a finite station cap binding again, its jobs not being in N.
1216 double closed_total = 0.0;
1217 bool any_open = false;
1218 for (std::size_t r = 0; r < K_; ++r) {
1219 const double nj = sn_.classes[r].population;
1220 if (std::isinf(nj))
1221 any_open = true;
1222 else
1223 closed_total += nj;
1224 }
1225 blk_can_.assign(M_, std::vector<char>(K_, 0));
1226 blk_on_ = false;
1227 for (std::size_t ist = 0; ist < M_; ++ist)
1228 for (std::size_t r = 0; r < K_; ++r) {
1229 const double nj = sn_.classes[r].population;
1230 if (std::isinf(nj)) continue; // open: refusal LOSES
1231 const double ccap = sn_.classcap[ist][r];
1232 const bool binds_st =
1233 !std::isinf(sn_.cap[ist]) && (any_open || sn_.cap[ist] < closed_total);
1234 const bool binds_cl = ccap > 0.0 && !std::isinf(ccap) && ccap < nj;
1235 if (binds_st || binds_cl) {
1236 blk_can_[ist][r] = 1;
1237 blk_on_ = true;
1238 }
1239 }
1240}
1241
1242/**
1243 * The candidate destinations of a reaction whose node routes BY STRATEGY.
1244 *
1245 * The candidates are the DECLARED out-arcs, `P(r,s)(i,j) > 0`, enumerated in
1246 * the order `refresh_routing` uses, and not the probability split it wrote into
1247 * `rtnodes` from them: the split is what a matrix solver needs and it is not
1248 * what the dispatcher does. Nothing is filled for PROB, RAND or DISABLED, which
1249 * are draws or refusals and stay on the `cdf` path.
1250 */
1251template <class T>
1252void NrmEngine<T>::build_state_dependent_dest(Rx& x) {
1253 const qn::NodeDef& nd = sn_.nodes[x.node];
1254 const lang::RoutingStrategy rs = nd.routing.size() > x.cls
1255 ? nd.routing[x.cls]
1259 return;
1260 for (std::size_t s = 1; s <= K_; ++s)
1261 for (std::size_t j = 1; j <= I_; ++j) {
1262 if (!(num_traits<T>::to_double(sn_.get_route(x.cls + 1, s, x.node + 1, j)) > 0.0))
1263 continue;
1264 x.sd_node.push_back(j - 1);
1265 x.sd_class.push_back(s - 1);
1266 }
1267 if (x.sd_node.size() < 2) { // one arc is not a dispatch decision
1268 x.sd_node.clear();
1269 x.sd_class.clear();
1270 return;
1271 }
1272 x.sd_strategy = rs;
1273 // The entry-phase law of each candidate, so the phase is drawn AFTER the
1274 // destination is chosen rather than folded into one joint distribution.
1275 x.sd_slots.resize(x.sd_node.size());
1276 x.sd_pie.resize(x.sd_node.size());
1277 for (std::size_t d = 0; d < x.sd_node.size(); ++d) {
1278 const std::size_t jnd = x.sd_node[d], s = x.sd_class[d];
1279 if (buf_ph_class_[jnd][s]) {
1280 x.sd_slots[d].push_back(phoff_[jnd][s]);
1281 x.sd_pie[d].push_back(1.0);
1282 continue;
1283 }
1284 for (std::size_t ke = 0; ke < nph_[jnd][s]; ++ke) {
1285 const double pe = pie_[jnd][s][ke];
1286 if (pe > 0.0) {
1287 x.sd_slots[d].push_back(phoff_[jnd][s] + ke);
1288 x.sd_pie[d].push_back(pe);
1289 }
1290 }
1291 }
1293 const std::map<std::size_t, double>* w =
1294 nd.routing_weights.size() > x.cls ? &nd.routing_weights[x.cls] : NULL;
1295 double total = 0.0;
1296 x.sd_weight.assign(x.sd_node.size(), 0.0);
1297 if (w != NULL)
1298 for (std::size_t d = 0; d < x.sd_node.size(); ++d) {
1299 const std::map<std::size_t, double>::const_iterator it =
1300 w->find(x.sd_node[d] + 1);
1301 x.sd_weight[d] = (it == w->end()) ? 0.0 : it->second;
1302 total += x.sd_weight[d];
1303 }
1304 if (!(total > 0.0)) {
1305 // No weights declared is plain round robin, which is what the
1306 // reference's WRROBIN degenerates to with a uniform weight vector.
1307 x.sd_weight.clear();
1308 x.sd_strategy = lang::RoutingStrategy::RROBIN;
1309 } else {
1310 for (std::size_t d = 0; d < x.sd_weight.size(); ++d) x.sd_weight[d] /= total;
1311 }
1312 }
1313}
1314
1315/**
1316 * The destination slot of a state-dependent firing, from the LIVE population.
1317 *
1318 * Each rule is the reference's (`solver_ssa_nrm.m` lines 1162-1200, 1390-1430):
1319 *
1320 * JSQ the candidate holding the smallest TOTAL population, each
1321 * evaluated on its own queue and never on the routing node's, with
1322 * TIES SPLIT UNIFORMLY. The tie split is not a detail: on a fleet of
1323 * identical servers the system starts with every queue equal, so a
1324 * first-candidate tie-break sends a run of jobs to candidate one and
1325 * reports a skew the policy does not have.
1326 * SQ(d) the power-of-d-choices rule, NOT "shortest queue": sample d
1327 * candidates uniformly WITH replacement and join the smallest of
1328 * those, ties by first occurrence in the sampled tuple. `d` is the
1329 * node's `routing_param`, 2 when unset, as `sub_sq` reads `nodeparam.d`.
1330 * RROBIN a pointer advanced once per firing, kept per (SOURCE NODE, CLASS)
1331 * and NOT per reaction: a phase-type service splits one dispatcher
1332 * across several reactions, and a pointer each would let the phases
1333 * cycle independently and undo the determinism.
1334 * WRROBIN the same pointer, spent in proportion to the declared weights.
1335 *
1336 * The destination NODE is what the rule fixes; the entry PHASE is drawn after,
1337 * from `pie` among that node's candidates, since taking the first match would
1338 * bias the service time.
1339 */
1340template <class T>
1341std::size_t NrmEngine<T>::resolve_state_dependent_dest(std::size_t kfire,
1342 const std::vector<double>& X) {
1343 Rx& x = rx_[kfire];
1344 const std::size_t nd = x.sd_node.size();
1345 const std::size_t cursor_key = x.node * K_ + x.cls;
1346 std::size_t pick = 0;
1347 if (x.sd_strategy == lang::RoutingStrategy::JSQ) {
1348 std::vector<double> load(nd, 0.0);
1349 double best = 0.0;
1350 for (std::size_t d = 0; d < nd; ++d) {
1351 const std::vector<double> cc = class_counts(X, x.sd_node[d]);
1352 for (double v : cc) load[d] += v;
1353 if (d == 0 || load[d] < best) best = load[d];
1354 }
1355 std::vector<std::size_t> amins;
1356 for (std::size_t d = 0; d < nd; ++d)
1357 if (load[d] == best) amins.push_back(d);
1358 pick = amins[std::min(amins.size() - 1,
1359 std::size_t(rng_.uniform() * double(amins.size())))];
1360 } else if (x.sd_strategy == lang::RoutingStrategy::SQ) {
1361 const std::vector<int>& rp = sn_.nodes[x.node].routing_param;
1362 const int dp = rp.size() > x.cls ? rp[x.cls] : 0;
1363 const std::size_t dsample = std::max<std::size_t>(1, std::min<std::size_t>(dp > 0 ? dp : 2, nd));
1364 double best = 0.0;
1365 for (std::size_t t = 0; t < dsample; ++t) {
1366 const std::size_t cand =
1367 std::min(nd - 1, std::size_t(rng_.uniform() * double(nd)));
1368 const std::vector<double> cc = class_counts(X, x.sd_node[cand]);
1369 double load = 0.0;
1370 for (double v : cc) load += v;
1371 if (t == 0 || load < best) {
1372 best = load;
1373 pick = cand;
1374 }
1375 }
1376 } else if (x.sd_strategy == lang::RoutingStrategy::WRROBIN) {
1377 // The pointer is spent in proportion to the declared weights: candidate
1378 // d owns the slice [sum w_{<d}, sum w_{<=d}) of one full turn.
1379 const std::size_t c = rr_cursor_[cursor_key];
1380 const double u = double(c % nd) / double(nd);
1381 double acc = 0.0;
1382 pick = nd - 1;
1383 for (std::size_t d = 0; d < nd; ++d) {
1384 acc += x.sd_weight[d];
1385 if (u < acc - 1e-12) {
1386 pick = d;
1387 break;
1388 }
1389 }
1390 rr_cursor_[cursor_key] = c + 1;
1391 } else {
1392 pick = rr_cursor_[cursor_key] % nd;
1393 rr_cursor_[cursor_key] = rr_cursor_[cursor_key] + 1;
1394 }
1395 // the entry phase, drawn within the chosen destination
1396 const std::vector<std::size_t>& slots = x.sd_slots[pick];
1397 if (slots.size() == 1) return slots[0];
1398 const double u = rng_.uniform();
1399 double acc = 0.0;
1400 for (std::size_t k = 0; k + 1 < slots.size(); ++k) {
1401 acc += x.sd_pie[pick][k];
1402 if (u < acc) return slots[k];
1403 }
1404 return slots.back();
1405}
1406
1407/**
1408 * The dependency sets, `solver_ssa_nrm.m` lines 1003-1050.
1409 *
1410 * A reaction's firing changes the slots its stoichiometry touches; every rate
1411 * law reads its node's WHOLE class-count vector (and, for the per-phase share,
1412 * the sibling phases of its own class), so the affected set is every slot of
1413 * every touched node, and the reactions to refresh are those that consume from
1414 * one of those slots.
1415 */
1416template <class T>
1417void NrmEngine<T>::build_dependencies() {
1418 const std::size_t nrx = rx_.size();
1419 D_.assign(nrx, std::vector<std::size_t>());
1420 for (std::size_t k = 0; k < nrx; ++k) {
1421 std::vector<bool> touched_node(I_, false);
1422 for (std::size_t i = 0; i < NS_; ++i)
1423 if (S_(i, k) != 0.0) touched_node[slot_node_[i]] = true;
1424 std::vector<bool> hit(nrx, false);
1425 for (std::size_t ind = 0; ind < I_; ++ind) {
1426 if (!touched_node[ind]) continue;
1427 for (std::size_t r = 0; r < K_; ++r)
1428 for (std::size_t p = 0; p < nph_[ind][r]; ++p) {
1429 const std::size_t slot = phoff_[ind][r] + p;
1430 for (std::size_t j = 0; j < nrx; ++j)
1431 if (S_(slot, j) < 0.0) hit[j] = true;
1432 }
1433 }
1434 for (std::size_t j = 0; j < nrx; ++j)
1435 if (hit[j]) D_[k].push_back(j);
1436 }
1437}
1438
1439/**
1440 * The initial state.
1441 *
1442 * THIS PORT HAS NO State PACKAGE, so the reference's `sn.state` cannot be read;
1443 * the same position `solver_fluid` takes applies here and for the same reason.
1444 * A closed class starts entirely at its reference station and an open class
1445 * puts the single fictitious token at the Source that the EXT rate law needs
1446 * (the reference substitutes exactly that for the infinite marginal). The chain
1447 * is ergodic, so the steady-state averages this engine reports do not depend on
1448 * the choice; a TRANSIENT would, which is why `getTranAvg` is not offered.
1449 */
1450template <class T>
1451void NrmEngine<T>::build_initial_state() {
1452 nvec0_.assign(NS_, 0.0);
1453 // The cache contents: the declared warm start when there is one (its row
1454 // after the per-class counts), else slot i holding item i, as the reference
1455 // NRM seeds it; with a retrieval system blocks A and B follow, empty.
1456 cache_var0_.assign(I_, std::vector<T>());
1457 for (std::size_t ind = 0; ind < I_; ++ind) {
1458 if (!is_cache_node_[ind]) continue;
1459 const qn::CacheParam<T>& cp = sn_.nodeparam.find(ind + 1)->second;
1460 std::size_t tcc = 0;
1461 for (int c : cp.itemcap)
1462 if (c > 0) tcc += static_cast<std::size_t>(c);
1463 std::vector<std::size_t> rcl, rci, rco;
1464 const bool retr = cp.retrieval_capacity > 0 && !cp.retrieval_classes.empty();
1465 if (retr) qn::cache_retrieval_class_map(cp, rcl, rci, rco);
1466 std::vector<T>& v = cache_var0_[ind];
1467 if (cp.initstate.size() > K_) {
1468 v.assign(cp.initstate.begin() + static_cast<std::ptrdiff_t>(K_), cp.initstate.end());
1469 } else {
1470 for (std::size_t c = 0; c < tcc; ++c)
1471 v.push_back(num_traits<T>::from_int(static_cast<long>(c + 1)));
1472 }
1473 const std::size_t want = tcc + (retr ? cp.nitems + rcl.size() : 0);
1474 v.resize(want, num_traits<T>::from_int(0));
1475 }
1476 buffers0_.assign(I_, std::vector<std::size_t>());
1477 svcph0_.assign(I_, Matrix<double>());
1478 for (std::size_t i = 0; i < I_; ++i)
1479 if (buf_ph_node_[i]) svcph0_[i] = Matrix<double>(K_, maxnph_, 0.0);
1480
1481 std::vector<std::vector<double>> nir(I_, std::vector<double>(K_, 0.0));
1482 for (std::size_t r = 0; r < K_; ++r) {
1483 const double pop = sn_.classes[r].population;
1484 if (std::isinf(pop)) {
1485 if (sn_.sourceIdx == 0)
1486 throw InputError(
1487 "solver_ssa_nrm: the open class '" + sn_.classes[r].name +
1488 "' has no Source; an open model must carry one for the arrival reaction");
1489 nir[sn_.station_to_node[sn_.sourceIdx - 1] - 1][r] = 1.0;
1490 } else if (pop > 0.0) {
1491 const std::size_t rs = sn_.classes[r].refstat;
1492 if (rs < 1 || rs > M_)
1493 throw InputError("solver_ssa_nrm: class '" + sn_.classes[r].name +
1494 "' has no reference station");
1495 nir[sn_.station_to_node[rs - 1] - 1][r] = pop;
1496 }
1497 }
1498
1499 for (std::size_t ind = 0; ind < I_; ++ind) {
1500 for (std::size_t r = 0; r < K_; ++r) {
1501 const double n = nir[ind][r];
1502 if (n <= 0.0) continue;
1503 if (nph_[ind][r] <= 1 || buf_ph_class_[ind][r]) {
1504 nvec0_[phoff_[ind][r]] = n;
1505 } else {
1506 double left = n;
1507 for (std::size_t ke = 0; ke < nph_[ind][r]; ++ke) {
1508 const double take = (ke + 1 == nph_[ind][r])
1509 ? left
1510 : std::min(left, std::round(n * pie_[ind][r][ke]));
1511 nvec0_[phoff_[ind][r] + ke] = take;
1512 left -= take;
1513 }
1514 }
1515 }
1516 // A PAS / OI list holds EVERY job, oldest first, in class order.
1517 if (is_station_[ind] && detail::sched_is_list(sched_[to_station_[ind]]))
1518 for (std::size_t r = 0; r < K_; ++r)
1519 for (std::size_t c = 0; c < static_cast<std::size_t>(nir[ind][r]); ++c)
1520 buffers0_[ind].push_back(r);
1521 // The buffer holds exactly the waiting jobs, `numel(buf) == max(0,
1522 // total - mi)`; which classes they are is immaterial to the steady
1523 // state, so they are taken in class order.
1524 if (is_station_[ind] && detail::sched_is_buffered(sched_[to_station_[ind]])) {
1525 double total = 0.0;
1526 for (std::size_t r = 0; r < K_; ++r) total += nir[ind][r];
1527 double waiting = std::max(0.0, total - mi_[ind]);
1528 for (std::size_t r = 0; r < K_ && waiting > 0.0; ++r) {
1529 double take = std::min(waiting, nir[ind][r]);
1530 for (std::size_t c = 0; c < static_cast<std::size_t>(take); ++c)
1531 buffers0_[ind].push_back(r);
1532 waiting -= take;
1533 }
1534 }
1535 if (!buf_ph_node_[ind]) continue;
1536 for (std::size_t r = 0; r < K_; ++r) {
1537 double waiting_r = 0.0;
1538 for (std::size_t c : buffers0_[ind])
1539 if (c == r) waiting_r += 1.0;
1540 const double insvc = std::max(0.0, nir[ind][r] - waiting_r);
1541 if (nph_[ind][r] <= 1) {
1542 svcph0_[ind](r, 0) = insvc;
1543 } else {
1544 double left = insvc;
1545 for (std::size_t ke = 0; ke < nph_[ind][r]; ++ke) {
1546 const double take = (ke + 1 == nph_[ind][r])
1547 ? left
1548 : std::min(left, std::round(insvc * pie_[ind][r][ke]));
1549 svcph0_[ind](r, ke) = take;
1550 left -= take;
1551 }
1552 }
1553 }
1554 }
1555}
1556
1557// ---------------------------------------------------------------------------
1558// The rate laws
1559// ---------------------------------------------------------------------------
1560
1561/**
1562 * The propensity of reaction `j`, `solver_ssa_nrm.m` lines 795-948.
1563 *
1564 * The reference builds one closure per reaction; this is the same switch
1565 * evaluated on demand, which avoids an indirect call per reaction per step and
1566 * cannot drift from the utilization accumulators that reuse the same sharing
1567 * factors.
1568 */
1569template <class T>
1570double NrmEngine<T>::propensity(std::size_t j, const std::vector<double>& X,
1571 const std::vector<std::vector<std::size_t>>& bufs,
1572 const std::vector<Matrix<double>>& svc) const {
1573 const Rx& x = rx_[j];
1574 const std::size_t ind = x.node, r = x.cls;
1575 if (!is_station_[ind])
1576 return x.rate * kir_frac(X, x.from, ind, r) * std::min(1.0, class_pop(X, ind, r));
1577
1578 const std::size_t ist = to_station_[ind];
1579 const double eps = lang::GlobalConstants::Zero;
1580
1581 // `pollSwRate`: the total leaving rate -D0(swk,swk) of the switchover phase
1582 // the walking server occupies; which transition it takes is drawn at firing.
1583 if (x.is_sw) {
1584 const PollCtrl& c = poll_ctrl_[ind];
1585 if (c.mode != 2) return 0.0;
1586 return -num_traits<T>::to_double(poll_info_[ind].sw_d0[c.pos - 1](c.swk, c.swk));
1587 }
1588
1589 // Buffered phase-type service: the rate reads the in-service multiset, not
1590 // the class total, which also counts the jobs still waiting.
1591 if (buf_ph_class_[ind][r]) {
1592 const std::size_t kk = x.is_phase ? x.phase_from : x.dep_phase;
1593 const std::vector<double> n = class_counts(X, ind);
1594 double tot = 0.0;
1595 for (double v : n) tot += v;
1596 return x.rate * svc[ind](r, kk) * lldfac(ist, tot) * cdfac(ist, n, r);
1597 }
1598
1599 const double kf = kir_frac(X, x.from, ind, r);
1600 switch (sched_[ist]) {
1601 case SchedStrategy::EXT:
1602 // A Source fires at a constant arrival rate: its token is
1603 // fictitious, so applying the population share would silence it and
1604 // deadlock every open model.
1605 return x.rate;
1606 case SchedStrategy::INF:
1607 return x.rate * kf * class_pop(X, ind, r) * cdfac(ist, class_counts(X, ind), r);
1608 case SchedStrategy::PS:
1609 case SchedStrategy::LPS: {
1610 if (K_ == 1)
1611 return x.rate * kf * std::min(mi_[ind], class_pop(X, ind, r)) *
1612 lldfac(ist, class_pop(X, ind, r)) * cdfac(ist, class_counts(X, ind), r);
1613 const std::vector<double> n = class_counts(X, ind);
1614 double tot = 0.0;
1615 for (double v : n) tot += v;
1616 return x.rate * kf * (n[r] / (eps + tot)) * std::min(mi_[ind], eps + tot) *
1617 lldfac(ist, tot) * cdfac(ist, n, r);
1618 }
1619 case SchedStrategy::DPS: {
1620 const std::vector<double> n = class_counts(X, ind);
1621 double tot = 0.0;
1622 for (double v : n) tot += v;
1623 return x.rate * kf * dpsshare(wnorm_[ist], n, r) * lldfac(ist, tot) *
1624 cdfac(ist, n, r);
1625 }
1626 case SchedStrategy::GPS: {
1627 const std::vector<double> n = class_counts(X, ind);
1628 double tot = 0.0;
1629 for (double v : n) tot += v;
1630 return x.rate * kf * gpsshare(wnorm_[ist], n, r) * lldfac(ist, tot) *
1631 cdfac(ist, n, r);
1632 }
1633 // The three PRIORITY sharing disciplines. Below the server count each
1634 // is its non-priority twin; above it only the most urgent non-empty
1635 // group shares the servers. Note that PSPRIO reads the lld factor at
1636 // the FULL population and the other two at the priority-restricted one
1637 // -- `prio_pop` carries that asymmetry, which comes from the reference.
1638 case SchedStrategy::PSPRIO: {
1639 const std::vector<double> n = class_counts(X, ind);
1640 double tot = 0.0;
1641 for (double v : n) tot += v;
1642 return x.rate * kf * psprioshare(n, r, mi_[ind]) * lldfac(ist, tot) *
1643 cdfac(ist, n, r);
1644 }
1645 case SchedStrategy::DPSPRIO: {
1646 const std::vector<double> n = class_counts(X, ind);
1647 return x.rate * kf * dpsprioshare(wnorm_[ist], n, r, mi_[ind]) *
1648 lldfac(ist, prio_pop(n, r, mi_[ind])) *
1649 cdfac(ist, prio_vec(n, r, mi_[ind]), r);
1650 }
1651 case SchedStrategy::GPSPRIO: {
1652 const std::vector<double> n = class_counts(X, ind);
1653 return x.rate * kf * gpsprioshare(wnorm_[ist], n, r, mi_[ind]) *
1654 lldfac(ist, prio_pop(n, r, mi_[ind])) *
1655 cdfac(ist, prio_vec(n, r, mi_[ind]), r);
1656 }
1657 case SchedStrategy::FCFS:
1658 case SchedStrategy::LCFS:
1659 case SchedStrategy::SIRO:
1660 case SchedStrategy::HOL:
1661 case SchedStrategy::SEPT:
1662 case SchedStrategy::LEPT:
1663 case SchedStrategy::LCFSPR: {
1664 // Invariant: numel(buf) == max(0, total - mi), so the jobs in
1665 // service are the class population minus its share of the buffer.
1666 double waiting = 0.0;
1667 for (std::size_t c : bufs[ind])
1668 if (c == r) waiting += 1.0;
1669 const std::vector<double> n = class_counts(X, ind);
1670 double tot = 0.0;
1671 for (double v : n) tot += v;
1672 return x.rate * kf * std::max(0.0, n[r] - waiting) * lldfac(ist, tot) *
1673 cdfac(ist, n, r);
1674 }
1675 case SchedStrategy::POLLING: {
1676 // One server serving one job, of the class its controller attends:
1677 // the class-r departure fires only while the controller SERVES r, at
1678 // the plain rate, never scaled by the class population.
1679 const PollCtrl& c = poll_ctrl_[ind];
1680 if (c.mode != 1 || c.pos != r + 1) return 0.0;
1681 const std::vector<double> n = class_counts(X, ind);
1682 double tot = 0.0;
1683 for (double v : n) tot += v;
1684 return x.rate * lldfac(ist, tot) * cdfac(ist, n, r);
1685 }
1686 case SchedStrategy::PAS:
1687 case SchedStrategy::OI:
1688 // Position p is served at Delta_mu(c1..cp) and pass-and-swap
1689 // decides which class that completion ejects, so the class-r rate
1690 // is the total increment over the positions that eject class r.
1691 return pas_rate(ist, bufs[ind], r);
1692 default:
1693 throw UnsupportedError(ErrorKind{"SchedStrategy"},
1694 "solver_ssa_nrm: the scheduling policy '" +
1695 std::string(lang::sched_to_text(sched_[ist])) + "' at station '" +
1696 sn_.stations[ist].name + "' has no NRM rate law in this port");
1697 }
1698}
1699
1700// ---------------------------------------------------------------------------
1701// Buffer maintenance
1702// ---------------------------------------------------------------------------
1703
1704/** `pickFromBuffer`: the waiting job the discipline promotes, newest-first buffer. */
1705template <class T>
1706std::size_t NrmEngine<T>::pick_from_buffer(const std::vector<std::size_t>& buf, std::size_t ist) {
1707 switch (sched_[ist]) {
1708 case SchedStrategy::FCFS:
1709 return buf.size() - 1; // oldest
1710 case SchedStrategy::LCFS:
1711 case SchedStrategy::LCFSPR:
1712 return 0; // newest, or the most recently preempted
1713 case SchedStrategy::SIRO:
1714 return rng_.index(buf.size());
1715 case SchedStrategy::HOL: {
1716 // Highest priority (lowest value), FCFS within the group, so the
1717 // oldest is the LAST matching position.
1718 double best = std::numeric_limits<double>::infinity();
1719 for (std::size_t c : buf) best = std::min(best, classprio_[c]);
1720 for (std::size_t p = buf.size(); p-- > 0;)
1721 if (classprio_[buf[p]] == best) return p;
1722 return buf.size() - 1;
1723 }
1724 case SchedStrategy::SEPT:
1725 case SchedStrategy::LEPT: {
1726 // schedparam carries the rank of the class's mean service time,
1727 // ascending for SEPT and descending for LEPT, so both promote the
1728 // waiting class of least rank.
1729 double best = std::numeric_limits<double>::infinity();
1730 for (std::size_t c : buf)
1731 best = std::min(best, num_traits<T>::to_double(sn_.stations[ist].schedparam[c]));
1732 for (std::size_t p = buf.size(); p-- > 0;)
1733 if (num_traits<T>::to_double(sn_.stations[ist].schedparam[buf[p]]) == best)
1734 return p;
1735 return buf.size() - 1;
1736 }
1737 default:
1738 throw UnsupportedError(ErrorKind{"SchedStrategy"}, "solver_ssa_nrm: '" +
1739 std::string(lang::sched_to_text(sched_[ist])) +
1740 "' is not a buffered policy this port promotes from");
1741 }
1742}
1743
1744/** `drawEntryPhase`: the phase a job starts service in, drawn from pie. */
1745template <class T>
1746std::size_t NrmEngine<T>::draw_entry_phase(std::size_t ind, std::size_t r) {
1747 if (nph_[ind][r] <= 1) return 0;
1748 return rng_.draw(pie_[ind][r]);
1749}
1750
1751/**
1752 * `capacityLoss`: an OPEN arrival at a full physically-capped station is lost.
1753 *
1754 * A refused CLOSED job must block rather than vanish from the conserved
1755 * population, so it is not dropped here; `State.arrivalIsLost` draws that line
1756 * on the class type and this reproduces it. `isPhysicalCapacity` is the drop
1757 * rule test -- a bound that exists only as a state-space cutoff keeps the WAITQ
1758 * default and must not become a loss.
1759 */
1760template <class T>
1761bool NrmEngine<T>::capacity_loss(const std::vector<double>& X, std::size_t slot) const {
1762 const std::size_t jnd = slot_node_[slot], dst = slot_class_[slot];
1763 if (!is_station_[jnd]) return false;
1764 const std::size_t ist = to_station_[jnd];
1765 const qn::DropStrategy dr = sn_.droprule[ist][dst];
1766 if (dr == qn::DropStrategy::WAITQ) return false; // cutoff-only, or unset
1767 if (dr == qn::DropStrategy::BAS || dr == qn::DropStrategy::BBS ||
1768 dr == qn::DropStrategy::RSRD)
1769 throw UnsupportedError(ErrorKind{"FiniteCapacity"}, "solver_ssa_nrm: station '" + sn_.stations[ist].name +
1770 "' declares the blocking drop rule for class '" +
1771 sn_.classes[dst].name +
1772 "'; blocking-after-service is not ported to the C++ NRM");
1773 if (!std::isinf(sn_.classes[dst].population)) return false; // closed: block, never lose
1774 const std::vector<double> cc = class_counts(X, jnd);
1775 double tot = 0.0;
1776 for (double v : cc) tot += v;
1777 if (!std::isinf(sn_.cap[ist]) && tot >= sn_.cap[ist]) return true;
1778 const double ccap = sn_.classcap[ist][dst];
1779 return ccap > 0.0 && !std::isinf(ccap) && cc[dst] >= ccap;
1780}
1781
1782/**
1783 * `capacityBlock`: a refused arrival that may NOT be dropped cancels the firing.
1784 *
1785 * `capacity_loss` above answers the OPEN half of the same question and returns
1786 * false for a closed class precisely because a closed network's population is an
1787 * invariant. Nothing then stopped the reaction, so the NRM fired into the full
1788 * station anyway and reported the UNCONSTRAINED answer (BUG-81): on a closed
1789 * 3-queue tandem, N=6, Q2 capped at 2, QLen came back [1.96 2.07 1.97] against
1790 * the exact [3.609 0.971 1.420] -- a mean of 2.07 at a station that holds 2 --
1791 * while the serial engine, whose producer already implements the contract, gave
1792 * the exact answer.
1793 *
1794 * Blocking is the THIRD outcome of a firing, next to moving the job and losing
1795 * it. The departure does not occur, the source is not decremented, no buffer
1796 * moves; only the reaction's own clock is redrawn, which is exact by
1797 * memorylessness -- the residual of an exponential, or of the current PH phase,
1798 * is that same exponential. It is what `solver_ctmc` does when the target state
1799 * is absent from the enumerated space and the arc is dropped, which is why the
1800 * two agree.
1801 *
1802 * The population read is the PRE-arrival one, minus the departing job when it
1803 * currently sits at the destination node: a self-loop or a feedback arc at a
1804 * station already at cap would otherwise block itself forever, while the
1805 * reference producer sees the state AFTER the departure half.
1806 */
1807template <class T>
1808bool NrmEngine<T>::capacity_block(const std::vector<double>& X, std::size_t slot,
1809 std::size_t src_slot) const {
1810 if (!blk_on_) return false;
1811 const std::size_t jnd = slot_node_[slot], dst = slot_class_[slot];
1812 if (!is_station_[jnd]) return false;
1813 const std::size_t ist = to_station_[jnd];
1814 if (!blk_can_[ist][dst]) return false;
1815 const bool same_node = src_slot != npos && slot_node_[src_slot] == jnd;
1816 const std::vector<double> cc = class_counts(X, jnd);
1817 if (!std::isinf(sn_.cap[ist])) {
1818 double tot = 0.0;
1819 for (double v : cc) tot += v;
1820 if (same_node) tot -= 1.0;
1821 if (tot >= sn_.cap[ist]) return true;
1822 }
1823 const double ccap = sn_.classcap[ist][dst];
1824 if (ccap > 0.0 && !std::isinf(ccap)) {
1825 double pop = cc[dst];
1826 if (same_node && slot_class_[src_slot] == dst) pop -= 1.0;
1827 if (pop >= ccap) return true;
1828 }
1829 return false;
1830}
1831
1832/** `pickPreempted`: the incumbent an LCFSPR arrival displaces, by server occupancy. */
1833template <class T>
1834std::size_t NrmEngine<T>::pick_preempted(const std::vector<double>& X,
1835 const std::vector<std::size_t>& buf, std::size_t jnd,
1836 std::size_t arr_class) {
1837 std::vector<double> insvc = class_counts(X, jnd);
1838 for (std::size_t r = 0; r < K_; ++r) {
1839 for (std::size_t c : buf)
1840 if (c == r) insvc[r] -= 1.0;
1841 if (r == arr_class) insvc[r] -= 1.0; // the job that just arrived
1842 if (insvc[r] < 0.0) insvc[r] = 0.0;
1843 }
1844 double tot = 0.0;
1845 for (double v : insvc) tot += v;
1846 if (tot <= 0.0) return npos;
1847 const double u = rng_.uniform() * tot;
1848 double acc = 0.0;
1849 std::size_t last = npos;
1850 for (std::size_t r = 0; r < K_; ++r) {
1851 if (!(insvc[r] > 0.0)) continue;
1852 last = r;
1853 acc += insvc[r];
1854 if (u < acc) return r;
1855 }
1856 return last;
1857}
1858
1859/** `applyArrivalBuffer`: join a just-arrived class-s job to node jnd's buffer. */
1860template <class T>
1861void NrmEngine<T>::apply_arrival_buffer(std::size_t jnd, std::size_t s,
1862 const std::vector<double>& X,
1863 std::vector<std::vector<std::size_t>>& bufs,
1864 std::vector<Matrix<double>>& svc, bool& svc_changed) {
1865 if (is_station_[jnd] && detail::sched_is_list(sched_[to_station_[jnd]])) {
1866 // PAS / OI: the arrival joins the BACK of the ordered list; there is no
1867 // server/buffer split. An arrival past the station's cap was already
1868 // lost or blocked by the capacity gates before it got here.
1869 const std::vector<std::size_t> old = bufs[jnd];
1870 bufs[jnd].push_back(s);
1871 pas_tag_started(jnd, old, bufs[jnd]);
1872 return;
1873 }
1874 // Polling: the controller, not the arrival, opens a service (`poll_land`).
1875 if (!is_poll_.empty() && is_poll_[jnd]) return;
1876 if (!is_station_[jnd] || !detail::sched_is_buffered(sched_[to_station_[jnd]])) {
1877 // A station that holds no waiting line serves every job it admits at
1878 // once (INF, PS, LPS, DPS, GPS), so the arrival IS the service start.
1879 if (is_station_[jnd]) tag(jnd, s, false);
1880 return;
1881 }
1882 const std::vector<double> cc = class_counts(X, jnd);
1883 double total = 0.0;
1884 for (double v : cc) total += v;
1885 bool entered = false;
1886 if (total > mi_[jnd]) {
1887 if (sched_[to_station_[jnd]] == SchedStrategy::LCFSPR) {
1888 // Preempt-resume: the arrival seizes a server and the incumbent it
1889 // displaces is the one that joins the buffer, which is what leaves
1890 // the new job in service (in-service is population minus buffer).
1891 const std::size_t c = pick_preempted(X, bufs[jnd], jnd, s);
1892 if (c != npos) {
1893 bufs[jnd].insert(bufs[jnd].begin(), c);
1894 tag(jnd, c, true); // the incumbent is pushed back into the buffer
1895 }
1896 entered = true;
1897 } else {
1898 bufs[jnd].insert(bufs[jnd].begin(), s); // it waits: it starts nothing
1899 }
1900 } else {
1901 entered = true;
1902 }
1903 if (entered) tag(jnd, s, false); // the arrival seized a server
1904 if (entered && buf_ph_node_[jnd]) {
1905 svc[jnd](s, draw_entry_phase(jnd, s)) += 1.0;
1906 svc_changed = true;
1907 }
1908}
1909
1910/**
1911 * `cacheAccess`: one READ at a cache, drawn from `after_event_cache`.
1912 *
1913 * The reference NRM re-implements State.afterEventCache's simulation branch;
1914 * this port draws from the enumerating port itself instead, so the NRM, the
1915 * serial engine and SolverCTMC read one set of replacement rules. The reading
1916 * job is presented ALONE (the enumerator requires exactly one job at the cache,
1917 * and other jobs at an immediate node are immaterial to a read), and the one
1918 * successor is drawn in proportion to its rate. Its per-class block, against the
1919 * one-hot input, says what happened:
1920 *
1921 * all zero the request MERGED onto an in-flight fetch (block B);
1922 * a retrieval class a fetch BEGINS: the in-flight bit is set, as the
1923 * departure that carries the job out would set it, and
1924 * the job is placed straight at the retrieval station,
1925 * as `cacheRetrDest` does, so that a job at
1926 * [cache, retrieval class] is always an inbound one;
1927 * otherwise a hit or a completed miss, plus the delayed hits the
1928 * completion releases, all at the cache in their classes.
1929 */
1930template <class T>
1931void NrmEngine<T>::cache_fire(const Rx& x, std::vector<double>& X, std::size_t& dest_pos,
1932 bool& have_dest) {
1933 const std::size_t ind = x.node, r = x.cls;
1934 const qn::CacheParam<T>& cp = sn_.nodeparam.find(ind + 1)->second;
1935 std::vector<T> row(K_, num_traits<T>::from_int(0));
1936 row[r] = num_traits<T>::from_int(1);
1937 row.insert(row.end(), cache_var_[ind].begin(), cache_var_[ind].end());
1938 const qn::EventOutcome<T> o =
1939 qn::after_event_cache(sn_, ind + 1, row, lang::EventType::READ, r + 1);
1940 std::vector<double> w(o.space.size(), 0.0);
1941 double tot = 0.0;
1942 for (std::size_t j = 0; j < o.space.size(); ++j) {
1943 w[j] = num_traits<T>::to_double(o.rate[j]) * num_traits<T>::to_double(o.prob[j]);
1944 if (!(w[j] > 0.0)) w[j] = 0.0;
1945 tot += w[j];
1946 }
1947 if (!(tot > 0.0))
1948 throw NumericError(ErrorKind{"Degenerate"}, "solver_ssa_nrm: the READ of class '" + sn_.classes[r].name +
1949 "' at Cache '" + sn_.nodes[ind].name + "' has no enabled outcome");
1950 const std::vector<T>& nx = o.space[rng_.draw(w)];
1951 X[x.from] -= 1.0;
1952 cache_var_[ind].assign(nx.begin() + static_cast<std::ptrdiff_t>(K_), nx.end());
1953
1954 std::vector<std::size_t> rcl, rci, rco;
1955 if (cp.retrieval_capacity > 0) qn::cache_retrieval_class_map(cp, rcl, rci, rco);
1956 const bool from_retr = std::find(rcl.begin(), rcl.end(), r + 1) != rcl.end();
1957 double produced = 0.0;
1958 for (std::size_t c = 0; c < K_; ++c) produced += num_traits<T>::to_double(nx[c]);
1959 if (produced == 0.0) {
1960 cache_dly_(ind, r) += 1.0; // merged: held in block B until its fetch completes
1961 return;
1962 }
1963 for (std::size_t c = 0; c < K_; ++c) {
1964 const double d = num_traits<T>::to_double(nx[c]);
1965 if (!(d > 0.0)) continue;
1966 const bool begins = !from_retr && std::find(rcl.begin(), rcl.end(), c + 1) != rcl.end();
1967 if (!begins) {
1968 X[phoff_[ind][c]] += d;
1969 cache_prod_(ind, c) += d;
1970 if (!have_dest) {
1971 dest_pos = phoff_[ind][c];
1972 have_dest = true;
1973 }
1974 continue;
1975 }
1976 // BEGIN a fetch. The in-flight bit of the item whose retrieval class c is.
1977 std::size_t tcc = 0;
1978 for (int m : cp.itemcap)
1979 if (m > 0) tcc += static_cast<std::size_t>(m);
1980 for (std::size_t it = 0; it < cp.retrieval_classes.size(); ++it)
1981 if (r < cp.retrieval_classes[it].size() && cp.retrieval_classes[it][r] == c + 1 &&
1982 tcc + it < cache_var_[ind].size())
1983 cache_var_[ind][tcc + it] = num_traits<T>::from_int(1);
1984 // The retrieval station the class routes to, drawn over the routing row
1985 // and the entry phases there.
1986 std::vector<std::size_t> slots;
1987 std::vector<double> sw;
1988 for (std::size_t jnd = 0; jnd < I_; ++jnd)
1989 for (std::size_t s = 0; s < K_; ++s) {
1990 const double p =
1991 num_traits<T>::to_double(sn_.rtnodes(ind * K_ + c, jnd * K_ + s));
1992 if (!(p > 0.0)) continue;
1993 if (buf_ph_class_[jnd][s]) {
1994 slots.push_back(phoff_[jnd][s]);
1995 sw.push_back(p);
1996 continue;
1997 }
1998 for (std::size_t ke = 0; ke < nph_[jnd][s]; ++ke)
1999 if (pie_[jnd][s][ke] > 0.0) {
2000 slots.push_back(phoff_[jnd][s] + ke);
2001 sw.push_back(p * pie_[jnd][s][ke]);
2002 }
2003 }
2004 if (slots.empty())
2005 throw InputError("solver_ssa_nrm: retrieval class '" + sn_.classes[c].name +
2006 "' at Cache '" + sn_.nodes[ind].name + "' routes nowhere");
2007 const std::size_t slot = slots[rng_.draw(sw)];
2008 X[slot] += 1.0;
2009 dest_pos = slot;
2010 have_dest = true;
2011 }
2012}
2013
2014/**
2015 * The realized hit, miss and delayed-hit shares, as the serial engine reports
2016 * them: every read leaves as exactly one of the three, the released delayed
2017 * hits are carved out of the hit class's production, and the retrieval
2018 * classes, which have no hit class, get no share of their own.
2019 */
2020template <class T>
2021void NrmEngine<T>::cache_write_back() {
2022 cache_out_.clear();
2023 const double nan = std::numeric_limits<double>::quiet_NaN();
2024 for (std::size_t ind = 0; ind < I_; ++ind) {
2025 if (!is_cache_node_[ind]) continue;
2026 const qn::CacheParam<T>& cp = sn_.nodeparam.find(ind + 1)->second;
2027 SsaCacheRatio cr;
2028 cr.node = ind + 1;
2029 cr.hitprob.assign(K_, nan);
2030 cr.missprob.assign(K_, nan);
2031 cr.residt.assign(K_, nan);
2032 std::vector<double> dly(K_, 0.0);
2033 bool any_delayed = false;
2034 for (std::size_t k = 0; k < K_; ++k) {
2035 if (k >= cp.hitclass.size() || k >= cp.missclass.size()) continue;
2036 const std::size_t h = cp.hitclass[k], mi = cp.missclass[k];
2037 if (h == 0 || mi == 0 || h > K_ || mi > K_) continue;
2038 const double th = cache_prod_(ind, h - 1), tm = cache_prod_(ind, mi - 1);
2039 const double td = cache_dly_(ind, k);
2040 if (th + tm > 0.0) {
2041 cr.hitprob[k] = std::max(th - td, 0.0) / (th + tm);
2042 cr.missprob[k] = tm / (th + tm);
2043 dly[k] = td / (th + tm);
2044 if (td > 0.0) any_delayed = true;
2045 }
2046 }
2047 if (any_delayed) cr.delayedprob = dly;
2048 cache_out_.push_back(cr);
2049 }
2050}
2051
2052/** `updateBuffers`: promote on a departure, join on an arrival. */
2053template <class T>
2054void NrmEngine<T>::update_buffers(std::size_t kfire, const std::vector<double>& X,
2055 std::vector<std::vector<std::size_t>>& bufs,
2056 std::size_t dest_pos, bool have_dest,
2057 std::vector<Matrix<double>>& svc, bool& svc_changed) {
2058 const Rx& x = rx_[kfire];
2059 const std::size_t ind = x.node;
2060 // The completing job leaves the phase it occupied; the promotion below
2061 // refills the freed server at a fresh entry phase.
2062 if (buf_ph_node_[ind] && x.is_buf_svc && !x.is_phase) {
2063 svc[ind](x.cls, x.dep_phase) -= 1.0;
2064 svc_changed = true;
2065 }
2066 // A PAS / OI departure is not a promotion but a pass-and-swap rewrite of the
2067 // whole list. Unlike the reference, which returns here, the ARRIVAL half
2068 // below still runs: a PAS station feeding a buffered one must join the job
2069 // to that station's buffer, and returning early would leave it counted in
2070 // the population but absent from the buffer.
2071 if (is_station_[ind] && detail::sched_is_list(sched_[to_station_[ind]]) &&
2072 !bufs[ind].empty() && !x.is_phase) {
2073 const std::vector<std::size_t> old = bufs[ind];
2074 pas_depart(ind, bufs[ind], x.cls);
2075 pas_tag_started(ind, old, bufs[ind]);
2076 } else if (is_station_[ind] && detail::sched_is_buffered(sched_[to_station_[ind]]) &&
2077 !bufs[ind].empty() && !x.is_phase) {
2078 const std::size_t pos = pick_from_buffer(bufs[ind], to_station_[ind]);
2079 const std::size_t promoted = bufs[ind][pos];
2080 bufs[ind].erase(bufs[ind].begin() + static_cast<std::ptrdiff_t>(pos));
2081 tag(ind, promoted, false); // it takes the server the completion freed
2082 if (buf_ph_node_[ind]) {
2083 svc[ind](promoted, draw_entry_phase(ind, promoted)) += 1.0;
2084 svc_changed = true;
2085 }
2086 }
2087 if (have_dest)
2088 apply_arrival_buffer(slot_node_[dest_pos], slot_class_[dest_pos], X, bufs, svc,
2089 svc_changed);
2090}
2091
2092// ---------------------------------------------------------------------------
2093// The sample path
2094// ---------------------------------------------------------------------------
2095
2096/** `next_reaction_method_direct`: the Gibson and Bruck loop with metrics in line. */
2097template <class T>
2099 const std::size_t nrx = rx_.size();
2100 SsaSolution out;
2101 out.QN = Matrix<double>(M_, K_, 0.0);
2102 out.UN = Matrix<double>(M_, K_, 0.0);
2103 out.RN = Matrix<double>(M_, K_, 0.0);
2104 out.TN = Matrix<double>(M_, K_, 0.0);
2105 out.CN.assign(K_, 0.0);
2106 out.XN.assign(K_, 0.0);
2107 out.StartN = Matrix<double>(M_, K_, 0.0);
2108 out.PreemptN = Matrix<double>(M_, K_, 0.0);
2109 out.method = "nrm";
2110 start_cnt_ = Matrix<double>(M_, K_, 0.0);
2111 preempt_cnt_ = Matrix<double>(M_, K_, 0.0);
2112 block_cnt_ = Matrix<double>(M_, K_, 0.0);
2113 if (nrx == 0) return out;
2114
2115 std::vector<double> nvec = nvec0_;
2116 std::vector<std::vector<std::size_t>> bufs = buffers0_;
2117 std::vector<Matrix<double>> svc = svcph0_;
2118 // The WAITQ FIFO of each region, tokens `node * K + class` of the parked jobs.
2119 std::vector<std::vector<std::size_t>> fcr_buf(fcr_.size());
2120 cache_var_ = cache_var0_;
2121 cache_prod_ = Matrix<double>(I_, K_, 0.0);
2122 cache_dly_ = Matrix<double>(I_, K_, 0.0);
2123 // Seed each polling controller as `State.pollingInit` does: walk from buffer
2124 // 1 and settle on the first tangible state, so the seed is reachable.
2125 poll_ctrl_.assign(I_, PollCtrl());
2126 for (std::size_t ind = 0; ind < I_; ++ind) {
2127 if (!is_poll_[ind]) continue;
2128 std::size_t q = 1;
2129 int mode = 0;
2130 long budget = 0;
2131 qn::polling_next(poll_info_[ind], 1, poll_nbuf(nvec, ind), K_, true, q, mode, budget);
2132 poll_ctrl_[ind] = poll_land(ind, q, mode, budget, false);
2133 }
2134
2135 std::vector<double> Ak(nrx, 0.0), Pk(nrx, 0.0), Tk(nrx, 0.0), tau(nrx, 0.0);
2136 for (std::size_t k = 0; k < nrx; ++k) {
2137 Ak[k] = propensity(k, nvec, bufs, svc);
2138 Pk[k] = -std::log(rng_.uniform());
2139 tau[k] = Ak[k] > 0.0 ? (Pk[k] - Tk[k]) / Ak[k] : std::numeric_limits<double>::infinity();
2140 }
2141
2142 double total_time = 0.0;
2143 std::size_t n = 0;
2144 line::util::LineConsole::loop("drawing the sample path: %zu samples requested",
2145 static_cast<std::size_t>(opt_.samples));
2146 const std::size_t console_every = std::max<std::size_t>(1, opt_.samples / 20);
2147 // Warmup discard (`ssa_resolve_warmupfrac`): the tallies restart once
2148 // `n_warm` firings have been drawn, so the initial transient enters no
2149 // estimate; the path itself runs on, as `solver_ssa_nrm.m` does.
2150 const std::size_t n_warm = ssa_warmup_firings(opt_.warmupfrac, opt_.samples);
2151 bool time_stopped = false;
2152 for (; n < opt_.samples; ++n) {
2153 // Wall-clock budget (options.timeout), read every 1024 firings, as
2154 // `solver_ssa_nrm.m` does: the tallies so far are the interim solution.
2155 if (n > 0 && (n & 1023u) == 0 && util::timeout_exceeded()) {
2156 time_stopped = true;
2157 break;
2158 }
2159 if (n == n_warm && n_warm > 0) {
2160 out.QN = Matrix<double>(M_, K_, 0.0);
2161 out.UN = Matrix<double>(M_, K_, 0.0);
2162 out.TN = Matrix<double>(M_, K_, 0.0);
2163 total_time = 0.0;
2164 start_cnt_ = Matrix<double>(M_, K_, 0.0);
2165 preempt_cnt_ = Matrix<double>(M_, K_, 0.0);
2166 block_cnt_ = Matrix<double>(M_, K_, 0.0);
2167 cache_prod_ = Matrix<double>(I_, K_, 0.0);
2168 cache_dly_ = Matrix<double>(I_, K_, 0.0);
2169 }
2170 if ((n + 1) % console_every == 0)
2172 static_cast<long>((n + 1) / console_every),
2173 "simulated %zu of %zu samples (%.0f%%), simulated time %.4g", n + 1,
2174 static_cast<std::size_t>(opt_.samples),
2175 100.0 * static_cast<double>(n + 1) / static_cast<double>(opt_.samples),
2176 total_time);
2177 std::size_t kfire = 0;
2178 double dt = std::numeric_limits<double>::infinity();
2179 for (std::size_t k = 0; k < nrx; ++k)
2180 if (tau[k] < dt) {
2181 dt = tau[k];
2182 kfire = k;
2183 }
2184 if (std::isinf(dt))
2185 throw NumericError(ErrorKind{"Degenerate"},
2186 "solver_ssa_nrm: deadlock -- every reaction has propensity zero, so the sample "
2187 "path cannot advance");
2188 total_time += dt;
2189
2190 // Time-integrate the metrics over this interval.
2191 for (std::size_t ist = 0; ist < M_; ++ist) {
2192 const std::size_t ind = sn_.station_to_node[ist] - 1;
2193 const std::vector<double> npop = class_counts(nvec, ind);
2194 double totpop = 0.0;
2195 for (double v : npop) totpop += v;
2196 // A Source's state slot is a FICTITIOUS TOKEN, not a queue. It is
2197 // seeded at 1, decremented by every arrival and replenished only
2198 // when a job reaches the Sink and is forwarded back, so its time
2199 // average is 1 - E[jobs in system] -- negative on any model with
2200 // more than one job in system, which is what it was reporting. A
2201 // Source holds no jobs, so QLen, Util and hence RespT/ResidT are
2202 // ZERO BY DEFINITION there and only its throughput (the arrival
2203 // rate) is a quantity; MVA, NC and MAM print exactly that row, and
2204 // the reference SSA applies the same rule downstream in
2205 // `solver_ssa.py` / `@@NetworkSolver/getAvg.m`. This is a
2206 // definition, not a clamp: it is keyed on the station's discipline
2207 // and never on the sign, so a negative anywhere else stays visible.
2208 const bool is_source = sched_[ist] == SchedStrategy::EXT;
2209 for (std::size_t k = 0; k < K_; ++k) {
2210 double dep = 0.0;
2211 for (std::size_t jd : dep_rx_[ist][k]) dep += Ak[jd];
2212 out.TN(ist, k) += dep * dt;
2213 if (is_source) continue;
2214 out.QN(ist, k) += npop[k] * dt;
2215 switch (sched_[ist]) {
2216 case SchedStrategy::INF:
2217 out.UN(ist, k) += npop[k] * dt;
2218 break;
2219 case SchedStrategy::PS:
2220 case SchedStrategy::LPS:
2221 if (totpop > 0.0)
2222 out.UN(ist, k) += (npop[k] / totpop) *
2223 std::min(nservers_[ist], totpop) / nservers_[ist] *
2224 dt;
2225 break;
2226 case SchedStrategy::DPS:
2227 out.UN(ist, k) += dpsshare(wnorm_[ist], npop, k) / nservers_[ist] * dt;
2228 break;
2229 case SchedStrategy::GPS:
2230 out.UN(ist, k) += gpsshare(wnorm_[ist], npop, k) / nservers_[ist] * dt;
2231 break;
2232 // The utilization of a PRIORITY discipline is the SAME
2233 // share the rate law uses, which is the invariant this
2234 // accumulator exists to preserve: reusing the sharing
2235 // factor is what keeps U = T E[S] from drifting away from
2236 // the sample path that produced T.
2237 case SchedStrategy::PSPRIO:
2238 out.UN(ist, k) += psprioshare(npop, k, nservers_[ist]) / nservers_[ist] * dt;
2239 break;
2240 case SchedStrategy::DPSPRIO:
2241 out.UN(ist, k) +=
2242 dpsprioshare(wnorm_[ist], npop, k, nservers_[ist]) / nservers_[ist] * dt;
2243 break;
2244 case SchedStrategy::GPSPRIO:
2245 out.UN(ist, k) +=
2246 gpsprioshare(wnorm_[ist], npop, k, nservers_[ist]) / nservers_[ist] * dt;
2247 break;
2248 // Busy on one class-k job exactly while the controller serves k.
2249 case SchedStrategy::POLLING:
2250 if (poll_ctrl_[ind].mode == 1 && poll_ctrl_[ind].pos == k + 1)
2251 out.UN(ist, k) += dt / nservers_[ist];
2252 break;
2253 // The positions with a positive Delta_mu over the servers, so a
2254 // job served by several server types counts once.
2255 case SchedStrategy::PAS:
2256 case SchedStrategy::OI:
2257 out.UN(ist, k) += pas_in_service(ist, bufs[ind], k) / nservers_[ist] * dt;
2258 break;
2259 case SchedStrategy::FCFS:
2260 case SchedStrategy::LCFS:
2261 case SchedStrategy::SIRO:
2262 case SchedStrategy::HOL:
2263 case SchedStrategy::SEPT:
2264 case SchedStrategy::LEPT:
2265 case SchedStrategy::LCFSPR: {
2266 if (sn_.disabled[ist][k]) break;
2267 double waiting = 0.0;
2268 for (std::size_t c : bufs[ind])
2269 if (c == k) waiting += 1.0;
2270 out.UN(ist, k) += ((npop[k] - waiting) / nservers_[ist]) * dt;
2271 break;
2272 }
2273 default:
2274 break;
2275 }
2276 }
2277 }
2278
2279 // Apply the firing.
2280 const Rx& x = rx_[kfire];
2281 std::size_t dest_pos = npos;
2282 bool have_dest = false;
2283 // A firing has THREE outcomes, not two: it moves the job, it loses it
2284 // (the source departs either way), or it is BLOCKED -- cancelled with
2285 // the source keeping the job and no slot changing. See `capacity_block`.
2286 bool blocked = false;
2287 if (x.is_cache) {
2288 cache_fire(x, nvec, dest_pos, have_dest);
2289 } else if (x.nnzP > 1 || !x.sd_node.empty()) {
2290 std::size_t slot;
2291 if (!x.sd_node.empty()) {
2292 // the dispatcher decides, from the state, not from a draw
2293 slot = resolve_state_dependent_dest(kfire, nvec);
2294 } else {
2295 const double u = rng_.uniform();
2296 std::size_t sel = x.cdf.size() - 1;
2297 for (std::size_t i = 0; i < x.cdf.size(); ++i)
2298 if (x.cdf[i] > u) {
2299 sel = i;
2300 break;
2301 }
2302 slot = x.to_slots[sel];
2303 }
2304 // A closed job that finds no room BLOCKS: the firing is cancelled
2305 // outright and nothing below runs, because a job that cannot leave
2306 // its station never departs at all. See `capacity_block`.
2307 if (capacity_block(nvec, slot, x.from)) {
2308 blocked = true;
2309 } else {
2310 // The loss is decided on the PRE-arrival population, so it is drawn
2311 // before the state is updated: the source still releases the job and
2312 // the destination never receives it.
2313 bool lost = capacity_loss(nvec, slot);
2314 // A region refuses on the same pre-arrival population; see
2315 // `fcr_outcome` for what each rule does with the refused job.
2316 if (!lost && !fcr_.empty())
2317 fcr_outcome(nvec, x, slot_node_[slot], slot_class_[slot], fcr_buf, lost, blocked);
2318 if (!blocked) {
2319 for (std::size_t s : x.from_slots) nvec[s] -= 1.0;
2320 if (!lost) {
2321 nvec[slot] += 1.0;
2322 dest_pos = slot;
2323 have_dest = true;
2324 }
2325 }
2326 }
2327 } else if (x.det_dest != npos && !x.is_phase &&
2328 capacity_block(nvec, x.det_dest, x.from)) {
2329 blocked = true; // same closed-class block; a phase change is never one
2330 } else {
2331 bool lost = x.det_dest != npos && !x.is_phase && capacity_loss(nvec, x.det_dest);
2332 // Single-destination departures cross region boundaries too; a phase
2333 // change is not an arrival and is never gated.
2334 if (!lost && x.det_dest != npos && !x.is_phase && !fcr_.empty())
2335 fcr_outcome(nvec, x, slot_node_[x.det_dest], slot_class_[x.det_dest], fcr_buf, lost,
2336 blocked);
2337 if (blocked) {
2338 // censored: nothing moves, as for `capacity_block`
2339 } else if (lost) {
2340 nvec[x.from] -= 1.0;
2341 } else {
2342 for (std::size_t i = 0; i < NS_; ++i)
2343 if (S_(i, kfire) != 0.0) nvec[i] += S_(i, kfire);
2344 if (x.det_dest != npos) {
2345 dest_pos = x.det_dest;
2346 have_dest = true;
2347 }
2348 }
2349 }
2350
2351 bool svc_changed = false;
2352 if (blocked) {
2353 // nothing moved, so no buffer and no service phase may change
2354 if (is_station_[x.node]) block_cnt_(to_station_[x.node], x.cls) += 1.0;
2355 } else if (x.is_phase && buf_ph_node_[x.node]) {
2356 // A buffered-PH phase change frees no server and adds no arrival:
2357 // only the in-service multiset moves.
2358 svc[x.node](x.cls, x.phase_from) -= 1.0;
2359 svc[x.node](x.cls, x.phase_to) += 1.0;
2360 svc_changed = true;
2361 } else if (!x.is_sw) {
2362 update_buffers(kfire, nvec, bufs, dest_pos, have_dest, svc, svc_changed);
2363 }
2364 // A read rewrites the contents and places jobs outside the stoichiometry.
2365 if (x.is_cache) svc_changed = true;
2366
2367 // Polling controller advance, `solver_ssa_nrm.m` lines 1710-1774: a
2368 // switchover step, a completion that ends or continues the visit, and an
2369 // arrival that wakes a parked server. Each can flip a service gate or the
2370 // switchover rate outside the static dependency set, so any move forces a
2371 // full refresh below.
2372 if (!is_poll_.empty() && !blocked) {
2373 if (x.is_sw) {
2374 const std::size_t ind = x.node;
2375 PollCtrl& c = poll_ctrl_[ind];
2376 const Matrix<T>& D0 = poll_info_[ind].sw_d0[c.pos - 1];
2377 const std::size_t Ksw = D0.rows();
2378 std::vector<double> w(Ksw + 1, 0.0);
2379 double rowsum = 0.0;
2380 for (std::size_t kd = 0; kd < Ksw; ++kd) {
2381 const double v = num_traits<T>::to_double(D0(c.swk, kd));
2382 rowsum += v;
2383 if (kd != c.swk && v > 0.0) w[kd] = v;
2384 }
2385 w[Ksw] = std::max(0.0, -rowsum); // absorption: the D1 row sum
2386 const std::size_t pick = rng_.draw(w);
2387 if (pick < Ksw && pick != c.swk) {
2388 c.swk = pick; // an internal phase advance of the walk
2389 } else {
2390 std::size_t q = c.pos;
2391 int mode = 0;
2392 long budget = 0;
2393 qn::polling_next(poll_info_[ind], c.pos, poll_nbuf(nvec, ind), K_, true, q,
2394 mode, budget);
2395 c = poll_land(ind, q, mode, budget);
2396 }
2397 svc_changed = true;
2398 } else if (is_poll_[x.node] && !x.is_phase) {
2399 const std::size_t ind = x.node;
2400 PollCtrl& c = poll_ctrl_[ind];
2401 const qn::PollingInfo<T>& pi = poll_info_[ind];
2402 const std::vector<long> nb = poll_nbuf(nvec, ind); // after the departure
2403 long ctrnext = 0;
2404 bool goon = false;
2405 switch (pi.ptype) {
2407 goon = nb[c.pos - 1] > 0;
2408 break;
2411 ctrnext = c.ctr - 1;
2412 goon = ctrnext > 0;
2413 break;
2415 ctrnext = c.ctr - 1;
2416 goon = ctrnext > 0 && nb[c.pos - 1] > 0;
2417 break;
2419 ctrnext = c.ctr;
2420 goon = nb[c.pos - 1] > c.ctr;
2421 break;
2422 default:
2423 throw UnsupportedError(ErrorKind{"SchedStrategy_POLLING"}, "solver_ssa_nrm: unsupported polling type");
2424 }
2425 if (goon) {
2426 c = poll_land(ind, c.pos, 1, ctrnext);
2427 } else {
2428 std::size_t q = c.pos;
2429 int mode = 0;
2430 long budget = 0;
2431 qn::polling_next(pi, c.pos, nb, K_, false, q, mode, budget);
2432 c = poll_land(ind, q, mode, budget);
2433 }
2434 svc_changed = true;
2435 }
2436 if (have_dest && is_poll_[slot_node_[dest_pos]]) {
2437 const std::size_t jnd = slot_node_[dest_pos];
2438 PollCtrl& c = poll_ctrl_[jnd];
2439 if (c.mode == 0) {
2440 std::size_t q = c.pos;
2441 int mode = 0;
2442 long budget = 0;
2443 qn::polling_next(poll_info_[jnd], c.pos, poll_nbuf(nvec, jnd), K_, true, q,
2444 mode, budget);
2445 c = poll_land(jnd, q, mode, budget);
2446 svc_changed = true;
2447 }
2448 }
2449 }
2450
2451 // WAITQ: admit parked jobs whose regions this firing may have relieved.
2452 // A release changes populations at arbitrary nodes, so it forces a full
2453 // propensity refresh below, as a service-phase move does.
2454 if (fcr_any_waitq_ && !blocked &&
2455 fcr_release_cascade(nvec, bufs, fcr_buf, svc, svc_changed) > 0)
2456 svc_changed = true;
2457
2458 for (std::size_t k = 0; k < nrx; ++k) Tk[k] += Ak[k] * dt;
2459
2460 // svcph is not part of the stoichiometry, so the static dependency set
2461 // cannot see a change to it; a move there forces a full refresh.
2462 if (svc_changed) {
2463 for (std::size_t k = 0; k < nrx; ++k) Ak[k] = propensity(k, nvec, bufs, svc);
2464 } else {
2465 for (std::size_t k : D_[kfire]) Ak[k] = propensity(k, nvec, bufs, svc);
2466 }
2467
2468 Pk[kfire] -= std::log(rng_.uniform());
2469 for (std::size_t k = 0; k < nrx; ++k)
2470 tau[k] =
2471 Ak[k] > 0.0 ? (Pk[k] - Tk[k]) / Ak[k] : std::numeric_limits<double>::infinity();
2472 }
2473 // A budget that ran out inside the warmup leaves only warmup tallies, which
2474 // the estimate is defined to exclude: no interim solution exists.
2475 if (time_stopped && n_warm > 0 && n <= n_warm)
2476 throw NumericError(ErrorKind{"Timeout"},
2477 "solver_ssa_nrm: the wall-clock time budget (options.timeout) ran out "
2478 "inside the warmup, before any sample was collected");
2479
2480 if (total_time > 0.0)
2481 for (std::size_t ist = 0; ist < M_; ++ist)
2482 for (std::size_t k = 0; k < K_; ++k) {
2483 out.QN(ist, k) /= total_time;
2484 out.UN(ist, k) /= total_time;
2485 // net the blocked firings out of the departure-rate integral
2486 out.TN(ist, k) = (out.TN(ist, k) - block_cnt_(ist, k)) / total_time;
2487 // COUNTS over the simulated time, where TN above integrates a
2488 // rate: the two estimators of the same quantity agree in the
2489 // limit and differ by simulation error at any finite budget.
2490 out.StartN(ist, k) = start_cnt_(ist, k) / total_time;
2491 out.PreemptN(ist, k) = preempt_cnt_(ist, k) / total_time;
2492 }
2493
2494 // A class- or joint-dependent station reports U = T*S/peak against the
2495 // product of its declared cd and jd peaks, the T*S/c convention of the
2496 // analytic solvers and serial SSA; busy time divided by the server count is
2497 // not that quantity once beta(n) != 1.
2498 for (std::size_t ist = 0; ist < M_; ++ist) {
2499 const auto& st = sn_.stations[ist];
2500 if (!st.cdscaling && !st.jdscaling) continue;
2501 for (std::size_t k = 0; k < K_; ++k) {
2502 double peak = 1.0;
2503 if (st.cdscaling) peak *= num_traits<T>::to_double(st.cdscalingpeak[k]);
2504 if (st.jdscaling) peak *= num_traits<T>::to_double(st.jdscalingpeak[k]);
2505 const double rate = num_traits<T>::to_double(sn_.rates(ist, k));
2506 out.UN(ist, k) = (std::isfinite(rate) && rate > 0.0 && peak > 0.0)
2507 ? out.TN(ist, k) / rate / peak
2508 : 0.0;
2509 }
2510 }
2511
2512 // Every LOAD-DEPENDENT station reports the work-based T*S/peak instead,
2513 // peak = max(c, max(alpha)). The loop above integrates BUSY TIME, which is a
2514 // different quantity once alpha(n) != 1: a server running alpha(n) times
2515 // faster does the same work in less time, so busy time reads it as no busier
2516 // than one at its nominal rate. That put NRM at 0.9587 on a 4-job closed
2517 // model with alpha = [1 1.5 2 2.5] where CTMC, MVA, NC and serial SSA all
2518 // report 0.6612, and left the two SSA engines disagreeing with each other.
2519 // INF and EXT keep U = Q, as everywhere else.
2520 for (std::size_t ist = 0; ist < M_; ++ist) {
2521 if (lld_[ist].empty()) continue;
2522 double peak = nservers_[ist];
2523 bool non_unit = false;
2524 for (double a : lld_[ist]) {
2525 if (a != 1.0) non_unit = true;
2526 if (a > peak) peak = a;
2527 }
2528 if (!non_unit) continue;
2529 if (sched_[ist] == SchedStrategy::INF || sched_[ist] == SchedStrategy::EXT)
2530 continue;
2531 for (std::size_t k = 0; k < K_; ++k) {
2532 const double rate = num_traits<T>::to_double(sn_.rates(ist, k));
2533 out.UN(ist, k) = (std::isfinite(rate) && rate > 0.0 && peak > 0.0)
2534 ? out.TN(ist, k) / rate / peak
2535 : 0.0;
2536 }
2537 }
2538
2539 for (std::size_t k = 0; k < K_; ++k) {
2540 out.XN[k] = out.TN(sn_.classes[k].refstat - 1, k);
2541 for (std::size_t ist = 0; ist < M_; ++ist)
2542 out.RN(ist, k) = out.TN(ist, k) > 0.0 ? out.QN(ist, k) / out.TN(ist, k) : 0.0;
2543 if (out.XN[k] > 0.0) out.CN[k] = sn_.classes[k].population / out.XN[k];
2544 }
2545 out.simulated_time = total_time;
2546 out.samples = n;
2547 cache_write_back();
2548 return out;
2549}
2550
2551} // namespace ssa
2552} // namespace line
2553
2554#endif // LINE_SOLVERS_SSA_SOLVER_SSA_NRM_H
InputError(const std::string &what)
Definition error.h:105
std::size_t rows() const
Definition matrix.h:89
NumericError(const std::string &what)
Definition error.h:112
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
std::size_t sourceIdx
1-based station index of the Source, 0 = none
T get_route(std::size_t r, std::size_t s, std::size_t i, std::size_t j) const
P{r,s}(i,j), AS THE USER SET IT.
std::size_t nof_nodes() const
std::vector< std::vector< Distrib< T > > > service
service[i][r], 0-based station and class; a disabled entry marks a pair never visited.
std::vector< std::vector< bool > > disabled
std::map< std::size_t, CacheParam< T > > nodeparam
Cache parameters by 1-based NODE index; only Cache nodes have an entry.
std::map< std::size_t, PasParam > pasparam
std::vector< double > cap
sn.cap and sn.classcap: the total and per-class buffers.
std::vector< JobClass > classes
std::vector< Station< T > > stations
stations[k-1] is the k-th station
Matrix< T > rates
(nstations x nclasses) service rates and SCVs, with a PARALLEL disabled flag instead of MATLAB's NaN ...
std::vector< NodeDef > nodes
every node, in creation order
std::vector< std::vector< double > > classcap
std::vector< std::vector< DropStrategy > > droprule
std::vector< std::size_t > station_to_node
(nstations) 1-based node index
std::vector< Region > regions
std::size_t nreactions() const
The reaction count, likewise.
NrmEngine(const qn::NetworkStruct< T > &sn, const SsaOptions &opt)
std::size_t nstates() const
The state-vector length, for the tests that assert the phase expansion.
const std::vector< SsaCacheRatio > & cache() const
The cache write-back of the last run(), one entry per Cache node.
SsaSolution run()
Run opt.samples firings and return the time-averaged metrics.
The uniform source, MATLAB's rand.
Definition ssa_types.h:202
std::size_t draw(const std::vector< double > &p)
Index drawn from the unnormalized nonnegative weights p, the reference's drawFromDist: an all-zero we...
Definition ssa_types.h:223
std::size_t index(std::size_t n)
Uniform index in [0, n), the reference's 1 + floor(rand*n).
Definition ssa_types.h:213
static void loop(const char *fmt,...)
Announce an iteration loop and reset its reporting budget.
static void iter(long k, const char *fmt,...)
Report iteration k of the current loop.
What refreshProcessRepresentations and refreshLST compute FROM a distribution: the (D0,...
The exception types the port throws.
Running progress log of a LINE solver run (the "solver console").
options.timeout: one wall-clock budget per top-level solve, on a per-THREAD deadline stack.
Dense matrix and non-owning view.
std::string sn_polling_extension(const qn::NetworkStruct< T > &sn)
mam::Map< T > dist_to_map(const Distrib< T > &d)
The (D0,D1) pair that reaches sn.proc.
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
RoutingStrategy
Routing strategies, with the values of MATLAB RoutingStrategy.
Definition lang_types.h:430
@ READ
a cache item is read
Definition lang_types.h:122
@ 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
std::vector< T > dist_pie(const Distrib< T > &d)
sn.pie: the phase distribution seen by an arriving job.
const char * sched_to_text(SchedStrategy s)
Definition lang_types.h:248
double tot(const std::vector< double > &pops)
void cache_retrieval_class_map(const CacheParam< T > &cp, std::vector< std::size_t > &rc_list, std::vector< std::size_t > &rc_items, std::vector< std::size_t > &rc_orig)
Port of State.cacheRetrievalClassMap: the canonical order of a cache's retrieval classes,...
void polling_next(const PollingInfo< T > &pi, std::size_t pos, const std::vector< long > &nbuf, std::size_t R, bool arrived, std::size_t &q, int &mode, long &budget)
Port of State.pollingNext: where the server goes from buffer pos.
void polling_require_ph(const PollingInfo< T > &pi)
Refuses a polling station whose switchover legs are not all phase-type.
EventOutcome< T > after_event_cache(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventType event, std::size_t cls)
Port of State.afterEventCache: events at a Cache node.
PrioPop< T > prio_pop(const NetworkStruct< T > &sn, std::size_t ist, const Marginal< T > &m, std::size_t cls, double ni, double S)
Compute the *PRIO effective population; a no-op for every other discipline.
void pas_tag_started(EventOutcome< T > &out, const F &mu_fun, const std::vector< std::size_t > &cold, const std::vector< std::size_t > &cnew)
Tag the successor just appended to OUT with the PAS positions that started service on it: those of CN...
std::pair< std::vector< std::size_t >, std::size_t > pass_and_swap(const std::vector< std::size_t > &c, std::size_t p, const std::vector< std::vector< bool > > &G)
Port of State.passAndSwap: the transition a service completion triggers at a pass-and-swap station (D...
std::vector< double > pas_increments(const F &mu_fun, const std::vector< std::size_t > &c)
Per-position service rate increments Delta_mu(c1..cp) = mu(c1..cp) - mu(c1..c_{p-1}...
PollingInfo< T > polling_info(const NetworkStruct< T > &sn, std::size_t ind)
std::size_t ssa_warmup_firings(double warmupfrac, std::size_t samples)
Firings whose tallies an engine discards: floor(warmupfrac * samples), with an unset (negative) fract...
Definition ssa_types.h:148
bool timeout_exceeded()
The checkpoint: true when the innermost budget has run out, marking it tripped.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
State.pollingInfo and the controller description it returns.
Port of matlab/src/api/sn/sn_polling_extension.m.
Controls, results and the random source of SolverSSA.
Port of the event half of MATLAB's +State package: the successor states an event produces at one node...
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
static constexpr double Immediate
Rate of an Immediate distribution; its mean is 1/Immediate = 1e-8.
Definition lang_types.h:829
static constexpr double Zero
Definition lang_types.h:825
Port of State.pollingInfo: the derived description of a polling controller.
lang::PollingType ptype
What the cache write-back of solver_ssa_analyzer_serial.m produces (and the NRM's).
Definition ssa_types.h:174
std::size_t node
1-based Cache node index
Definition ssa_types.h:175
Controls, defaulting to SolverOptions('SSA') in the reference.
Definition ssa_types.h:71
What the analyzer returns, in the same shape as the MVA and fluid results.
Definition ssa_types.h:154
std::vector< double > XN
Definition ssa_types.h:156
std::vector< double > CN
Definition ssa_types.h:156
Matrix< double > UN
Definition ssa_types.h:155
Matrix< double > RN
Definition ssa_types.h:155
Matrix< double > StartN
The DERIVED rates, (nstations x nclasses): how often per unit time a class-r service STARTS at statio...
Definition ssa_types.h:164
double simulated_time
Simulated time the metrics are averaged over; the reference's totalTime.
Definition ssa_types.h:168
Matrix< double > TN
Definition ssa_types.h:155
std::size_t samples
Reaction firings actually performed.
Definition ssa_types.h:170
Matrix< double > QN
Definition ssa_types.h:155
std::string method
The concrete algorithm, as the reference's method.
Definition ssa_types.h:166
Matrix< double > PreemptN
Definition ssa_types.h:164