LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
state.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_LANG_QN_STATE_H
6#define LINE_LANG_QN_STATE_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * Port of the MATLAB `+State` package: the encoding that turns a station's
12 * state row into marginal job counts.
13 *
14 * WHAT A STATE ROW IS. For a station the row is [buffer | server | vars]:
15 * `nvars(ind,:)` local-variable slots at the end, `sum(phasesz)` server slots
16 * before them (one per class-phase pair, laid out by `phaseshift`), and
17 * whatever remains at the front is the buffer. The buffer encoding is NOT
18 * uniform across disciplines -- FCFS/LCFS store a CLASS TAG per waiting
19 * position, so class-r jobs are counted by matching the tag, while SIRO,
20 * POLLING, SEPT, LEPT and SRPT store a per-class COUNT in column r. Reading
21 * one as the other silently produces a plausible number, which is why the
22 * discipline switch below is transcribed case by case rather than collapsed.
23 *
24 * THE EXT SENTINEL. `to_marginal` returns nir = +Inf for a Source, and that is
25 * deliberate: a Source is an infinite reservoir and the value describes the
26 * ENCODING, not a queue length. A caller that treats it as a queue length gets
27 * Inf, which is exactly the defect that reached SolverCTMC's averagers in
28 * MATLAB (see `_kb/07-cross-language-parity.md`, the Source-row section). Any
29 * consumer must test `is_source` before using nir, not clamp the Inf away.
30 */
31
32#include <algorithm>
33#include <map>
34#include <set>
35#include <cmath>
36#include <cstddef>
37#include <functional>
38#include <limits>
39#include <vector>
40
47#include "line/util/error.h"
49#include "line/util/matrix.h"
50
51namespace line {
52namespace qn {
53
54/** What `State.toMarginal` returns for one station and one state row. */
55template <class T>
56struct Marginal {
57 T ni = T(); ///< total jobs in the station
58 std::vector<T> nir; ///< jobs per class
59 std::vector<T> sir; ///< jobs in service per class
60 std::vector<std::vector<T>> kir; ///< jobs in service per class and phase
61};
62
63namespace state_detail {
64
65/** True when the discipline stores a per-class COUNT in buffer column r. */
66inline bool buffer_is_per_class_count(SchedStrategy s) {
67 switch (s) {
68 case SchedStrategy::SIRO:
69 case SchedStrategy::POLLING:
70 case SchedStrategy::SEPT:
71 case SchedStrategy::LEPT:
72 case SchedStrategy::SRPT:
73 case SchedStrategy::SRPTPRIO:
74 return true;
75 default:
76 return false;
77 }
78}
79
80/**
81 * True when the discipline stores a CLASS TAG per waiting position. HOL is
82 * MATLAB's FCFSPRIO, so the two are the same enumerator and appear once.
83 */
84inline bool buffer_is_class_tag(SchedStrategy s) {
85 switch (s) {
86 case SchedStrategy::FCFS:
87 case SchedStrategy::HOL:
88 case SchedStrategy::LCFS:
89 case SchedStrategy::LCFSPRIO:
90 return true;
91 default:
92 return false;
93 }
94}
95
96/**
97 * True when the buffer interleaves [class, phase] pairs, so only the even
98 * positions carry class tags. The preemptive families do this to remember the
99 * phase every preempted job was interrupted in.
100 */
101inline bool buffer_is_tag_phase_pairs(SchedStrategy s) {
102 switch (s) {
103 // The whole preempt-resume / preempt-independent family, exactly as
104 // `toMarginal` groups it. PI restarts a preempted job from its entry
105 // phase and PR resumes it in place, but BOTH must record the phase per
106 // waiting job, so they share the paired encoding.
107 case SchedStrategy::FCFSPI:
108 case SchedStrategy::FCFSPIPRIO:
109 case SchedStrategy::FCFSPR:
110 case SchedStrategy::FCFSPRPRIO:
111 case SchedStrategy::LCFSPI:
112 case SchedStrategy::LCFSPIPRIO:
113 case SchedStrategy::LCFSPR:
114 case SchedStrategy::LCFSPRPRIO:
115 // Round robin keeps the FCFS preempt-resume layout: an expired job
116 // waits at the tail with its interrupted service phase. Its quantum
117 // block lives in the local variables (rr_info.h).
118 case SchedStrategy::RR:
119 return true;
120 default:
121 return false;
122 }
123}
124
125} // namespace state_detail
126
127/**
128 * Port of `State.toMarginal` for a STATION, one state row at a time.
129 *
130 * @param sn the network struct
131 * @param ist station index (1-based, as elsewhere in NetworkStruct)
132 * @param state_i the station's state row
133 * @param phasesz per-class phase counts
134 * @param phaseshift per-class offset into the server block
135 * @param nvar width of the trailing local-variable block, 0 when absent
136 * @return the marginal counts; nir is +Inf for every class at a Source
137 */
138template <class T>
140 const std::vector<T>& state_i, const std::vector<std::size_t>& phasesz,
141 const std::vector<std::size_t>& phaseshift, std::size_t nvar = 0) {
142 const std::size_t R = sn.nclasses;
143 if (ist == 0 || ist > sn.stations.size())
144 throw InputError("to_marginal: station index " + std::to_string(ist) + " is out of range");
145
146 const T zero = num_traits<T>::from_int(0);
147 Marginal<T> m;
148 m.nir.assign(R, zero);
149 m.sir.assign(R, zero);
150 std::size_t maxph = 1;
151 for (std::size_t r = 0; r < R; ++r) maxph = std::max(maxph, phasesz[r]);
152 m.kir.assign(R, std::vector<T>(maxph, zero));
153
154 // A Join of an FJ-augmented struct: the row is a bare per-class count of jobs
155 // WAITING to synchronize. Nothing is in service and nothing is in a phase,
156 // which is why `sir` and `kir` stay zero rather than mirroring `nir`.
157 const std::size_t jnd = sn.node_of_station(ist);
158 if (sn.isfjaugmented && jnd != 0 && sn.nodes[jnd - 1].nodetype == NodeType::Join &&
159 state_i.size() >= R) {
160 for (std::size_t r = 0; r < R; ++r) m.nir[r] = state_i[state_i.size() - R + r];
161 return m;
162 }
163
164 // AN ORDER-INDEPENDENT ROW HAS NO SERVER BLOCK. PAS and OI encode the
165 // station as the ORDERED LIST of the class indices present, one slot per
166 // job the buffer can hold, so its width is the capacity and not
167 // sum(phasesz). Slicing a server block off it read the last list positions
168 // as phase occupancies, and where the capacity is SMALLER than the class
169 // count the width test below fired outright: `to_marginal: state row is
170 // narrower than the server block it declares` on pas_compatibility_5class
171 // (five classes, capacity three). The arm further down decodes the list; it
172 // needs neither `srv0` nor the per-phase sum.
173 const SchedStrategy sched = sn.stations[ist - 1].sched;
174 const bool ordered_list = (sched == SchedStrategy::PAS || sched == SchedStrategy::OI);
175
176 // [buffer | server | vars]: slice from the RIGHT, since only the buffer
177 // width varies with the discipline.
178 std::size_t srvw = 0;
179 for (std::size_t r = 0; r < R; ++r) srvw += phasesz[r];
180 if (!ordered_list && state_i.size() < nvar + srvw)
181 throw InputError("to_marginal: state row is narrower than the server block it declares");
182 const std::size_t srv0 = ordered_list ? 0 : state_i.size() - nvar - srvw;
183 const std::size_t bufw = srv0;
184
185 if (!ordered_list) {
186 for (std::size_t r = 0; r < R; ++r) {
187 for (std::size_t k = 0; k < phasesz[r]; ++k) {
188 const T v = state_i[srv0 + phaseshift[r] + k];
189 m.kir[r][k] = v;
190 m.sir[r] += v;
191 }
192 }
193 }
194
195 if (sched == SchedStrategy::EXT) {
196 // Infinite reservoir: a statement about the encoding, not a queue
197 // length. Consumers must branch on the station being a Source.
198 //
199 // AN EXACT TYPE HAS NO INFINITY. Rational is a field of quotients of
200 // integers, so building one from a double Inf throws outright ("Cannot
201 // convert a non-finite number to an integer") -- and the sentinel is
202 // built for every Source row whether or not anybody reads it, which
203 // killed the whole exact run inside `after_event_station_dep`
204 // (state_events.h): it calls this on the Source before its own EXT
205 // branch ever looks at sir/kir. Clamp to MaxInt there, the same clamp
206 // `from_marginal_node` applies to an infinite server count for the same
207 // reason -- still absurd as a queue length, so a consumer that forgot
208 // its `is_source` test is still visibly wrong rather than plausibly
209 // wrong, but representable. Types that DO carry an infinity keep it, so
210 // the double path is untouched.
211 const T ext = num_traits<T>::is_exact
214 std::numeric_limits<double>::infinity());
215 for (std::size_t r = 0; r < R; ++r) m.nir[r] = ext;
216 } else if (sched == SchedStrategy::PAS || sched == SchedStrategy::OI) {
217 // `State.toMarginal`'s PAS arm (toMarginal.m:105-130), which this port
218 // did not have: the row is the ORDERED LIST of class indices and there
219 // is no server block to slice at all, so the generic sum above read the
220 // last list POSITION as a phase occupancy. A station holding jobs then
221 // reported a queue length of about zero in every consumer of this
222 // decode -- `ctmc_state_space_aggr` and with it SolverCTMC's averages,
223 // SolverSSA's serial analyzer, and the reward and transient analyzers.
224 //
225 // IN SERVICE IS NOT "IN THE SERVER" HERE but "receiving a positive rate
226 // increment": Delta mu over the prefix ending at that position, exactly
227 // as the reference computes it. That is what makes an order-independent
228 // station's utilization a quantity rather than a slot count.
229 for (std::size_t r = 0; r < R; ++r) {
230 m.nir[r] = zero;
231 m.sir[r] = zero;
232 for (std::size_t k = 0; k < maxph; ++k) m.kir[r][k] = zero;
233 }
234 const std::size_t w = state_i.size() > nvar ? state_i.size() - nvar : 0;
235 std::vector<std::size_t> clist;
236 for (std::size_t b = 0; b < w; ++b) {
237 const long tag = static_cast<long>(num_traits<T>::to_double(state_i[b]) + 0.5);
238 if (tag >= 1 && static_cast<std::size_t>(tag) <= R) {
239 m.nir[tag - 1] += num_traits<T>::from_int(1);
240 clist.push_back(static_cast<std::size_t>(tag));
241 }
242 }
243 const typename std::map<std::size_t,
244 typename NetworkStruct<T>::PasParam>::const_iterator pit =
245 sn.pasparam.find(ist);
246 if (pit != sn.pasparam.end() && pit->second.svc_rate_fun) {
247 T muprev = zero;
248 for (std::size_t p = 0; p < clist.size(); ++p) {
249 const std::vector<std::size_t> prefix(clist.begin(), clist.begin() + p + 1);
250 const T mucur = pit->second.svc_rate_fun(prefix);
251 if (num_traits<T>::to_double(T(mucur - muprev)) > 0) {
252 m.sir[clist[p] - 1] += num_traits<T>::from_int(1);
253 m.kir[clist[p] - 1][0] += num_traits<T>::from_int(1);
254 }
255 muprev = mucur;
256 }
257 } else {
258 // No rate function declared: the reference falls back to "every job
259 // present is in service", which is the OI reading of an empty swap
260 // graph.
261 m.sir = m.nir;
262 for (std::size_t r = 0; r < R; ++r) m.kir[r][0] = m.nir[r];
263 }
264 } else if (state_detail::buffer_is_class_tag(sched)) {
265 for (std::size_t r = 0; r < R; ++r) {
266 T waiting = zero;
267 for (std::size_t b = 0; b < bufw; ++b)
268 if (state_i[b] == num_traits<T>::from_int(static_cast<long>(r + 1))) waiting += num_traits<T>::from_int(1);
269 m.nir[r] = T(m.sir[r] + waiting);
270 }
271 } else if (state_detail::buffer_is_tag_phase_pairs(sched)) {
272 if (bufw > 1) {
273 for (std::size_t r = 0; r < R; ++r) {
274 T waiting = zero;
275 for (std::size_t b = 0; b < bufw; b += 2) // even positions are the class tags
276 if (state_i[b] == num_traits<T>::from_int(static_cast<long>(r + 1))) waiting += num_traits<T>::from_int(1);
277 m.nir[r] = T(m.sir[r] + waiting);
278 }
279 } else {
280 m.nir = m.sir;
281 }
282 } else if (state_detail::buffer_is_per_class_count(sched)) {
283 for (std::size_t r = 0; r < R; ++r)
284 m.nir[r] = bufw >= R ? T(m.sir[r] + state_i[r]) : m.sir[r];
285 } else {
286 // INF, PS, DPS, GPS and the rest: everything present is in service.
287 m.nir = m.sir;
288 }
289
290 // A Place is a token container: the buffer/server split in its encoding is
291 // an artifact of a transition FIRE relocating surviving tokens, so fold the
292 // buffer slot back in for the INF-family disciplines it uses. Without this
293 // the token count collapses to the oscillating server slot while the
294 // dynamics stay correct -- the measurement moves, the model does not.
295 if (sn.stations[ist - 1].nodetype == NodeType::Place) {
296 switch (sched) {
297 case SchedStrategy::INF:
298 case SchedStrategy::PS:
299 case SchedStrategy::PSPRIO:
300 case SchedStrategy::DPS:
301 case SchedStrategy::DPSPRIO:
302 case SchedStrategy::GPS:
303 case SchedStrategy::GPSPRIO:
304 case SchedStrategy::LPS:
305 if (bufw >= R)
306 for (std::size_t r = 0; r < R; ++r) m.nir[r] = T(m.sir[r] + state_i[r]);
307 break;
308 default:
309 break;
310 }
311 for (std::size_t r = 0; r < R; ++r)
312 if (sn.disabled[ist - 1][r]) {
313 for (std::size_t k = 0; k < phasesz[r]; ++k) m.kir[r][k] = zero;
314 m.sir[r] = zero;
315 }
316 } else {
317 for (std::size_t r = 0; r < R; ++r)
318 if (sn.disabled[ist - 1][r]) {
319 m.nir[r] = zero;
320 for (std::size_t k = 0; k < phasesz[r]; ++k) m.kir[r][k] = zero;
321 m.sir[r] = zero;
322 }
323 }
324
325 m.ni = zero;
326 for (std::size_t r = 0; r < R; ++r) m.ni += m.nir[r];
327 return m;
328}
329
330/**
331 * Total jobs held by every STATION at one network state, indexed by station.
332 *
333 * A Source is an infinite reservoir whose `to_marginal` reports +Inf, which
334 * describes the encoding and not a queue length, so it is reported as zero here
335 * exactly as `ctmc_state_space_aggr` does. A station with no stateful node
336 * holds nothing.
337 */
338template <class T>
339std::vector<double> station_populations(const NetworkStruct<T>& sn,
340 const std::vector<std::vector<T>>& local) {
341 const std::size_t M = sn.stations.size(), K = sn.nclasses;
342 std::vector<double> n(M, 0.0);
343 for (std::size_t ist = 1; ist <= M; ++ist) {
344 const std::size_t isf = sn.stateful_of_station(ist);
345 if (isf == 0 || isf > local.size()) continue;
346 if (sn.stations[ist - 1].nodetype == NodeType::Source) continue;
347 std::vector<std::size_t> ph(K, 1), shift(K, 0);
348 std::size_t w = 0;
349 for (std::size_t k = 0; k < K; ++k) {
350 ph[k] = sn.phasessz_of(ist, k + 1);
351 shift[k] = w;
352 w += ph[k];
353 }
354 const Marginal<T> m =
355 to_marginal(sn, ist, local[isf - 1], ph, shift, sn.nvars_of(sn.node_of_station(ist)));
356 n[ist - 1] = num_traits<T>::to_double(m.ni);
357 }
358 return n;
359}
360
361/**
362 * Port of `sn.rtfun`: the routing over the stateful nodes AT ONE STATE.
363 *
364 * `rt` is a constant matrix because almost every routing strategy is; SDR is
365 * not, and eq. (10) of Krzesinski (1987) makes the split out of the entry
366 * centre a function of the branch and subnetwork populations. This rebuilds the
367 * node-level table with the SDR rows re-evaluated at `local` and eliminates the
368 * stateless nodes through the SAME stochastic complement `rt` is built with, so
369 * a model with a Router between the centres is complemented identically either
370 * way.
371 *
372 * The residual mass returns the customer to the departure centre -- the busy
373 * form of waiting of Sec. 2.5 -- and a branch closed by its own population bound
374 * simply receives nothing, because `pfqn_sdrprob` returns zero there.
375 *
376 * `sub_sdr` returns zero off the class diagonal: SDR does not switch class, so
377 * only the (r, r) block of the entry row carries mass.
378 *
379 * JSQ and SQ(d) rows are re-evaluated the same way, from the total population
380 * each candidate holds at `local` (`sub_jsq` / `sub_sq` of refreshRoutingMatrix.m):
381 * JSQ splits uniformly over the candidates tied at the minimum, and SQ(d) samples
382 * d candidates WITH replacement and joins the first minimum of the tuple. The
383 * candidates are the row's support in `rtnodes`, where `refresh_routing` left
384 * the uniform placeholder.
385 *
386 * @param sn the refreshed network struct
387 * @param local per-stateful-node state rows, the `NetState::local` of the state
388 * @return the (nstateful * nclasses) square routing table at that state
389 */
390template <class T>
391Matrix<T> rt_state(const NetworkStruct<T>& sn, const std::vector<std::vector<T>>& local) {
392 const T zero = num_traits<T>::from_int(0);
393 const std::size_t K = sn.nclasses, I = sn.nodes.size();
394 Matrix<T> full = sn.rtnodes;
395 if (full.rows() != I * K)
396 throw InputError("rt_state: the node-level routing has not been refreshed");
397 if (!sn.has_rtfun_routing()) return sn.stoch_comp_stateful(full, K);
398 const std::vector<double> nst = station_populations(sn, local);
399
400 for (std::size_t ind = 1; ind <= I; ++ind) {
401 const NodeDef& nd = sn.nodes[ind - 1];
402 for (std::size_t r = 1; r <= K && r <= nd.routing.size(); ++r) {
403 const RoutingStrategy rs = nd.routing[r - 1];
404 if (rs != RoutingStrategy::JSQ && rs != RoutingStrategy::SQ) continue;
405 const std::size_t row = (ind - 1) * K + (r - 1);
406 std::vector<std::size_t> cand; // ascending node index, as `find(linksmat(ind,:))`
407 std::vector<double> n;
408 for (std::size_t jnd = 1; jnd <= I; ++jnd) {
409 if (num_traits<T>::to_double(sn.rtnodes(row, (jnd - 1) * K + (r - 1))) <= 0) continue;
410 const std::size_t ist = sn.nodes[jnd - 1].station;
411 if (ist == 0)
412 throw UnsupportedError(ErrorKind{"RoutingStrategy"},
413 "node '" + nd.name + "' dispatches class '" + sn.classes[r - 1].name + "' by " +
414 std::string(routing_to_text(rs)) + " to node '" + sn.nodes[jnd - 1].name +
415 "', which is not a station and so has no queue length to compare");
416 cand.push_back(jnd);
417 n.push_back(nst[ist - 1]);
418 }
419 for (std::size_t c = 0; c < I * K; ++c) full(row, c) = zero;
420 if (cand.empty()) continue;
421 const std::size_t m = cand.size();
422 std::vector<long> hits(m, 0);
423 long total = 0;
424 if (rs == RoutingStrategy::JSQ) {
425 const double best = *std::min_element(n.begin(), n.end());
426 for (std::size_t i = 0; i < m; ++i)
427 if (n[i] == best) {
428 hits[i] = 1;
429 ++total;
430 }
431 } else {
432 const int dp = nd.routing_param.size() >= r ? nd.routing_param[r - 1] : 0;
433 const std::size_t d = std::max<std::size_t>(1, std::min<std::size_t>(dp > 0 ? dp : 2, m));
434 std::vector<std::size_t> tup(d, 0);
435 for (;;) {
436 std::size_t win = tup[0];
437 for (std::size_t c = 1; c < d; ++c)
438 if (n[tup[c]] < n[win]) win = tup[c];
439 ++hits[win];
440 ++total;
441 std::size_t c = 0;
442 while (c < d && ++tup[c] == m) tup[c++] = 0;
443 if (c == d) break;
444 }
445 }
446 for (std::size_t i = 0; i < m; ++i)
447 full(row, (cand[i] - 1) * K + (r - 1)) =
449 }
450 }
451 if (sn.sdr.empty()) return sn.stoch_comp_stateful(full, K);
452
453 const pfqn::SdrCoeff co = pfqn::pfqn_sdrcoeff(sn.sdr);
454 const std::vector<double> Pb = pfqn::pfqn_sdrprob(co, nst);
455 const double Ped = pfqn::pfqn_sdrped(Pb);
456
457 // The destination split out of the entry centre, by NODE: a branch is
458 // entered at its own entry centre, and the denied customer goes to d.
459 std::vector<double> p(I, 0.0);
460 for (std::size_t b = 1; b < sn.sdr_nodes.branch.size(); ++b)
461 p[sn.sdr_nodes.entryOf[b]] += Pb[b];
462 p[sn.sdr_nodes.departure] += Ped;
463
464 for (std::size_t ind = 1; ind <= I; ++ind) {
465 const NodeDef& nd = sn.nodes[ind - 1];
466 for (std::size_t r = 1; r <= K && r <= nd.routing.size(); ++r) {
467 if (nd.routing[r - 1] != RoutingStrategy::SDR) continue;
468 for (std::size_t jnd = 1; jnd <= I; ++jnd)
469 for (std::size_t s = 1; s <= K; ++s)
470 full((ind - 1) * K + (r - 1), (jnd - 1) * K + (s - 1)) =
471 s == r ? num_traits<T>::from_double(p[jnd - 1]) : zero;
472 }
473 }
474 return sn.stoch_comp_stateful(full, K);
475}
476
477/**
478 * Port of `State.cartesian`: pair every row of `a` with every row of `b`.
479 *
480 * An empty `a` is the identity, as in the reference, so a fold over classes can
481 * start from nothing. Row order is a's outer, b's inner -- the same order
482 * `fromMarginal` relies on when it appends the server block after the buffer.
483 */
484template <class T>
485std::vector<std::vector<T>> cartesian(const std::vector<std::vector<T>>& a,
486 const std::vector<std::vector<T>>& b) {
487 if (a.empty()) return b;
488 if (b.empty()) return a;
489 std::vector<std::vector<T>> out;
490 out.reserve(a.size() * b.size());
491 for (std::size_t i = 0; i < a.size(); ++i) {
492 // Wall-clock budget (options.timeout), read every 64 rows of `a`: a
493 // closed multiclass lattice is ONE fold of this product, built before
494 // space_generator's own per-row checkpoint is reached, and on an
495 // explosive model it runs to exhaustion with nothing else in reach. A
496 // partial product has no valid partial solution, so it raises.
497 if ((i & 63u) == 63u) util::timeout_check("CTMC state-space product (lower the population or raise the budget)");
498 for (std::size_t j = 0; j < b.size(); ++j) {
499 std::vector<T> row = a[i];
500 row.insert(row.end(), b[j].begin(), b[j].end());
501 out.push_back(row);
502 }
503 }
504 return out;
505}
506
507/**
508 * Port of `State.spaceClosedSingle`: the ways to place `n` jobs over `m`
509 * phases. `m == 0` yields NO rows, not one empty row -- a class with no service
510 * process contributes nothing, and returning an empty row instead would let it
511 * multiply the product by one and silently survive the fold.
512 */
513template <class T>
514std::vector<std::vector<T>> space_closed_single(std::size_t m, std::size_t n) {
515 std::vector<std::vector<T>> out;
516 if (m == 0) return out;
517 const std::vector<std::vector<int>> rows =
518 pfqn::multichoose_rows(static_cast<int>(m), static_cast<int>(n));
519 out.reserve(rows.size());
520 for (std::size_t i = 0; i < rows.size(); ++i) {
521 std::vector<T> r;
522 r.reserve(rows[i].size());
523 for (std::size_t j = 0; j < rows[i].size(); ++j)
524 r.push_back(num_traits<T>::from_int(rows[i][j]));
525 out.push_back(r);
526 }
527 return out;
528}
529
530/**
531 * `space_closed_single` with a PER-SLOT bound, the reference's
532 * `spaceClosedSingle(M, N, caps)`.
533 *
534 * The bound is applied BEFORE recursing, which is the whole point: a slot of
535 * capacity 0 takes only the zero item, so a class that can occupy one node out
536 * of M enumerates M rows rather than binomial(n+M-1, M-1). The unbounded form
537 * generates the full lattice and leaves the caller to reject the impossible
538 * rows one at a time, at one `from_marginal` call each.
539 *
540 * `caps` is one entry per slot; an entry of `-1` means unbounded.
541 */
542template <class T>
543void space_closed_single_capped_rec(std::size_t m, long n, const std::vector<long>& caps,
544 std::size_t off, std::vector<T>& row,
545 std::vector<std::vector<T>>& out) {
546 if (m == 0) {
547 if (n == 0) out.push_back(row);
548 return;
549 }
550 long room = 0;
551 bool unbounded = false;
552 for (std::size_t k = off; k < off + m && k < caps.size(); ++k) {
553 if (caps[k] < 0) { unbounded = true; break; }
554 room += caps[k];
555 }
556 if (!unbounded && n > room) return;
557 const long here = off < caps.size() ? caps[off] : -1;
558 const long hi = here < 0 ? n : std::min<long>(n, here);
559 for (long i = 0; i <= hi; ++i) {
560 row.push_back(num_traits<T>::from_int(i));
561 space_closed_single_capped_rec(m - 1, n - i, caps, off + 1, row, out);
562 row.pop_back();
563 }
564}
565
566/** @see space_closed_single_capped_rec */
567template <class T>
568std::vector<std::vector<T>> space_closed_single_capped(std::size_t m, std::size_t n,
569 const std::vector<long>& caps) {
570 std::vector<std::vector<T>> out;
571 if (m == 0) return out;
572 std::vector<T> row;
573 row.reserve(m);
574 space_closed_single_capped_rec<T>(m, static_cast<long>(n), caps, 0, row, out);
575 return out;
576}
577
578/**
579 * Port of `matlab/util/multiset_perms.m` on an ASCENDING multiset, ROW ORDER
580 * INCLUDED. (Until 2026-08-19 the reference was the vendored `uniqueperms.m`,
581 * removed for want of a license grant; the replacement reproduces its listing
582 * exactly, so this port is unchanged.)
583 *
584 * The row order is not an aesthetic choice: row 0 is what `default_init_state`
585 * takes as the initial state, so it decides which communicating class a chain
586 * made reducible by the swap graph settles in. The reference's own ordering is
587 * inconsistent between its two branches and is mirrored here rather than
588 * normalised: an all-distinct multiset goes through `perms`, which is REVERSE
589 * lexicographic (descending first), while a multiset with a repeat recurses
590 * over its unique values in ASCENDING order. Both are reproduced.
591 *
592 * The caller supplies `vec` sorted ascending, which is what the class-major
593 * build in the PAS arm of `from_marginal_core` produces; the recursion erases
594 * one element and preserves that order.
595 */
596inline std::vector<std::vector<std::size_t> > pas_multiset_perms(
597 const std::vector<std::size_t>& vec) {
598 std::vector<std::vector<std::size_t> > pu;
599 if (vec.empty()) return pu;
600 std::vector<std::size_t> uvec = vec;
601 std::sort(uvec.begin(), uvec.end());
602 uvec.erase(std::unique(uvec.begin(), uvec.end()), uvec.end());
603 if (uvec.size() == 1) {
604 pu.push_back(vec);
605 return pu;
606 }
607 if (uvec.size() == vec.size()) {
608 std::vector<std::size_t> p(vec.rbegin(), vec.rend());
609 do {
610 pu.push_back(p);
611 } while (std::prev_permutation(p.begin(), p.end()));
612 return pu;
613 }
614 for (std::size_t i = 0; i < uvec.size(); ++i) {
615 std::vector<std::size_t> v = vec;
616 for (std::size_t j = 0; j < v.size(); ++j)
617 if (v[j] == uvec[i]) {
618 v.erase(v.begin() + static_cast<std::ptrdiff_t>(j));
619 break;
620 }
621 const std::vector<std::vector<std::size_t> > tmp = pas_multiset_perms(v);
622 for (std::size_t t = 0; t < tmp.size(); ++t) {
623 std::vector<std::size_t> row(1, uvec[i]);
624 row.insert(row.end(), tmp[t].begin(), tmp[t].end());
625 pu.push_back(row);
626 }
627 }
628 return pu;
629}
630
631/**
632 * Port of `State.fromMarginal` for the station families CTMC enumerates:
633 * every local state in which station `ist` holds exactly `n[r]` class-r jobs.
634 *
635 * COVERED: Queue, Delay, Source and Place under the disciplines whose buffer is
636 * either absent (INF/PS/DPS/GPS) or a per-class count. The row is laid out
637 * [buffer | server] to match `to_marginal`, and the server block is the
638 * cartesian fold of `space_closed_single(phases[r], n[r])` over classes.
639 *
640 * Retrial stations are covered here too, by the (in-service, orbit) split, and
641 * PAS/OI by the ordered class-index list that `to_marginal` already decoded.
642 * Transition nodes are NOT: a Transition is stateful but is not a station, so
643 * it never carries a station index -- `from_marginal_node` handles it, which is
644 * also where the reference puts it.
645 *
646 * REFUSED BY NAME, because a wrong guess is indistinguishable from a correct
647 * one downstream: a station carrying a MAP/MMPP2 arrival process under a
648 * discipline whose encoding does not carry the modulating phase.
649 */
650template <class T>
651std::vector<std::vector<T>> from_marginal_core(const NetworkStruct<T>& sn, std::size_t ist,
652 const std::vector<std::size_t>& n,
653 const std::vector<std::size_t>& phases) {
654 const std::size_t R = sn.nclasses;
655 if (ist == 0 || ist > sn.stations.size())
656 throw InputError("from_marginal: station index " + std::to_string(ist) + " is out of range");
657 if (n.size() != R || phases.size() != R)
658 throw InputError("from_marginal: n and phases must have one entry per class");
659
660 const Station<T>& st = sn.stations[ist - 1];
661 const SchedStrategy sched = st.sched;
662
663 // The reference's MAP guard. A MAP/MMPP2 arrival process modulates between
664 // phases, and only the FCFS encoding carries that phase in the state; under
665 // any other discipline the enumeration would drop the modulating chain and
666 // return states that cannot represent the process. A Source is exempt: its
667 // phase block IS the modulating chain, which the EXT branch builds.
668 for (std::size_t r = 0; r < R; ++r) {
669 const ProcessType pt = sn.procid(ist, r + 1);
670 if ((pt == ProcessType::MAP || pt == ProcessType::MMPP2) &&
671 sched != SchedStrategy::FCFS && st.nodetype != NodeType::Source)
672 throw UnsupportedError(ErrorKind{"MAP"},
673 "from_marginal: a MAP/MMPP2 process at a non-FCFS station is not supported; "
674 "only the FCFS encoding carries the modulating phase");
675 }
676
677 // RETRIAL: no waiting line. An arrival that finds every server busy joins an
678 // ORBIT and re-attempts at the retrial rate, so the state is the
679 // (in-service, orbit) SPLIT and every admissible split is a distinct state
680 // -- including the idle-server ones, which an ordinary queue cannot occupy
681 // while jobs wait. A completion does NOT promote from the orbit.
682 // The reference's own test is `any(~cellfun(@@isempty, sn.retrialProc(ist,:)))`:
683 // an entry exists only once some class actually has a retrial process, so a
684 // present-but-empty record must NOT switch the encoding.
685 bool is_retrial = false;
686 {
687 const typename std::map<std::size_t, RetrialParam<T> >::const_iterator rit =
688 sn.retrialparam.find(ist);
689 if (rit != sn.retrialparam.end())
690 for (std::size_t r = 0; r < rit->second.retrial_proc.size(); ++r)
691 if (!rit->second.retrial_proc[r].disabled) { is_retrial = true; break; }
692 }
693 if (is_retrial) {
694 std::size_t rr = R; // first class actually present
695 for (std::size_t r = 0; r < R; ++r)
696 if (n[r] > 0) { rr = r; break; }
697 if (rr == R) { // empty station: one idle row, no orbit slots
698 std::size_t w = 0;
699 for (std::size_t r = 0; r < R; ++r) w += phases[r];
700 return std::vector<std::vector<T>>{std::vector<T>(w, num_traits<T>::from_int(0))};
701 }
702 const double S = st.nservers;
703 const std::size_t maxsrv =
704 std::isfinite(S) ? std::min(n[rr], static_cast<std::size_t>(S)) : n[rr];
705 const std::size_t maxorbit = n[rr];
706 std::vector<std::vector<T>> res3;
707 for (std::size_t csrv = 0; csrv <= maxsrv; ++csrv) {
708 const std::size_t orbit = n[rr] - csrv;
709 std::vector<T> buf(maxorbit - orbit, num_traits<T>::from_int(0));
710 buf.insert(buf.end(), orbit, num_traits<T>::from_int(static_cast<long>(rr + 1)));
711 std::vector<std::vector<T>> srv3;
712 bool ok3 = true;
713 for (std::size_t cls = 0; cls < R; ++cls) {
714 const std::size_t want = cls == rr ? csrv : 0;
715 const std::vector<std::vector<T>> sc = space_closed_single<T>(phases[cls], want);
716 if (sc.empty() && want > 0) { ok3 = false; break; }
717 srv3 = cartesian(srv3, sc);
718 }
719 if (!ok3) continue;
720 for (std::size_t i3 = 0; i3 < srv3.size(); ++i3) {
721 std::vector<T> row = buf;
722 row.insert(row.end(), srv3[i3].begin(), srv3[i3].end());
723 res3.push_back(row);
724 }
725 }
726 return res3;
727 }
728
729 // The capacity gate of the reference: a Source has no finite buffer, every
730 // other station refuses a marginal it cannot hold, returning NO rows rather
731 // than an unreachable one.
732 std::vector<std::vector<T>> out;
733 if (sched != SchedStrategy::EXT)
734 for (std::size_t r = 0; r < R; ++r)
735 // Compare in DOUBLE: classcap is +Inf for an uncapped class, and
736 // casting Inf to size_t is undefined behaviour -- it made this gate
737 // reject every marginal and from_marginal returned no states at all.
738 if (sn.classcap.size() >= ist && r < sn.classcap[ist - 1].size() &&
739 static_cast<double>(n[r]) > sn.classcap[ist - 1][r])
740 return out;
741
742 if (sched == SchedStrategy::PAS || sched == SchedStrategy::OI) {
743 // `fromMarginal.m:457-475`. THE PAS/OI LOCAL STATE IS AN ORDERED LIST,
744 // not a count: the row is the class index of the job in each of the
745 // `sn.cap(ist)` positions, left-aligned and zero-padded. There is no
746 // buffer/server split, no phase block, and no server count, which is
747 // why this arm returns before the cartesian fold below.
748 //
749 // Without it a PAS station fell through to the count-shaped default,
750 // one column per class, while `to_marginal`'s PAS arm decoded the same
751 // row as a list -- the two encodings disagreed and nothing errored. A
752 // count of 2 in column 1 decoded as one class-1 job in position 0 and
753 // whatever class index 2 names in position 1, so queue length at a PAS
754 // station read near zero in every consumer of the decode: SolverSSA's
755 // serial analyzer AND SolverCTMC's averages, which share this walk.
756 //
757 // REFUSE AN INFINITE CAPACITY, as the reference does. The list encoding
758 // has no width without one and substituting a default would silently
759 // truncate the state space instead of reporting that the model is
760 // underspecified.
761 //
762 // AN EMPTY UNCAPPED STATION STILL HAS A STATE (fromMarginal.m): the empty
763 // list, one zero-padded slot, which is all the analytical routes (open OI
764 // networks, solver_oi_open_analyzer) need from the default initial state.
765 // A 1x0 row would read as no state. Any state-space solver that tries to
766 // fill it is refused here (n > 0) or in after_event_station_pas.
767 const double W = ist <= sn.cap.size() ? sn.cap[ist - 1]
768 : std::numeric_limits<double>::infinity();
769 std::size_t tot = 0;
770 for (std::size_t r = 0; r < R; ++r) tot += n[r];
771 if (!std::isfinite(W) && tot > 0)
772 throw InputError(
773 "from_marginal: PAS stations require finite capacity for state-space generation");
774 const std::size_t w = std::isfinite(W) ? static_cast<std::size_t>(W) : 1;
775 if (tot == 0)
776 return std::vector<std::vector<T> >(
777 1, std::vector<T>(w, num_traits<T>::from_int(0)));
778 if (tot > w) return out; // infeasible: exceeds the station's total capacity
779 std::vector<std::size_t> vi;
780 for (std::size_t r = 0; r < R; ++r)
781 for (std::size_t j = 0; j < n[r]; ++j) vi.push_back(r + 1);
782 const std::vector<std::vector<std::size_t> > mi = pas_multiset_perms(vi);
783 out.reserve(mi.size());
784 for (std::size_t i = 0; i < mi.size(); ++i) {
785 std::vector<T> row;
786 row.reserve(w);
787 for (std::size_t j = 0; j < mi[i].size(); ++j)
788 row.push_back(num_traits<T>::from_int(static_cast<long>(mi[i][j])));
789 row.resize(w, num_traits<T>::from_int(0));
790 out.push_back(row);
791 }
792 return out;
793 }
794
795 // `space_closed_single` is empty exactly when the class has no phase, so
796 // this is the unreachability test the eager fold below used to perform,
797 // separated from the fold itself. THE FOLD IS DEFERRED to its only reader,
798 // the INF/PS arm: it places every job of every class in a phase, which is
799 // C(n+K-1, K-1) rows for K phases, and the ordered-buffer arm right below
800 // never reads it -- it takes si[r] from the permutation tail. Building it
801 // there anyway cost 8.5e8 discarded rows on an M/ME/1 with an order-11
802 // service and cutoff 30 (test_cme_distribution.py::test_ctmc_mg1_is_exact),
803 // which reads as a hang rather than as an error.
804 //
805 // THE TEST IS ON THE CONTENT, NOT ON THE WIDTH. `phases` is the WIDTH
806 // vector (`phasessz_of`, one column per class even where the class has no
807 // process), so a disabled class still occupies a column and the emptiness
808 // has to be asked of `phases_of` directly.
809 for (std::size_t r = 0; r < R; ++r)
810 if (sn.phases_of(ist, r + 1) == 0 && n[r] > 0)
811 return out; // no service process, yet jobs demanded: unreachable
812
813 if (state_detail::buffer_is_class_tag(sched) || state_detail::buffer_is_tag_phase_pairs(sched)) {
814 // ORDERED BUFFER, as `fromMarginal`'s FCFS/LCFS branch builds it: the
815 // waiting positions record WHICH class occupies each slot, so the state
816 // is a permutation of the multiset {r repeated n[r] times}, not a count.
817 // The last S entries of each permutation are the jobs in service and
818 // the rest is the buffer, which is why the marginal alone does not
819 // determine the state and a count-shaped buffer would be wrong.
820 // The preempt family stores [class, phase] PAIRS, so one permutation of
821 // the waiting classes yields one row per assignment of an interruption
822 // phase to each waiting job, exactly as `fromMarginal` interleaves
823 // `mi_buf` with `bkstate` (fromMarginal.m:310-325).
824 const bool paired = state_detail::buffer_is_tag_phase_pairs(sched);
825 std::vector<std::size_t> vi;
826 for (std::size_t r = 0; r < R; ++r)
827 for (std::size_t j = 0; j < n[r]; ++j) vi.push_back(r + 1);
828 const double S = st.nservers;
829 const std::size_t nsrv =
830 std::isfinite(S) ? static_cast<std::size_t>(S) : vi.size();
831 if (vi.empty()) {
832 // Empty station: one state, all-zero buffer and idle servers. The
833 // preempt-resume buffer is [class, phase] pairs, so its empty width
834 // is even -- a one-column buffer there would misalign to_marginal.
835 const std::size_t bw = state_detail::buffer_is_tag_phase_pairs(sched) ? 2u : 1u;
836 std::vector<T> row(bw, num_traits<T>::from_int(0));
837 std::size_t srvw2 = 0;
838 for (std::size_t r = 0; r < R; ++r) srvw2 += phases[r];
839 row.insert(row.end(), srvw2, num_traits<T>::from_int(0));
840 return std::vector<std::vector<T>>{row};
841 }
842 // Descending first, walked down with prev_permutation: the SAME set of
843 // permutations as an ascending next_permutation walk, but row 0 is the
844 // descending buffer, which is the row MATLAB State.fromMarginalAndStarted
845 // returns. Anything taking rows[0] as the initial state (default_init_state)
846 // then agrees with the reference, and on a chain made reducible by
847 // non-overtaking routing that is what picks the closed communicating class.
848 std::sort(vi.begin(), vi.end(), [](std::size_t a, std::size_t b) { return a > b; });
849 std::vector<std::vector<T>> res2;
850 const std::size_t insrv = std::min(nsrv, vi.size());
851 // Rows of one (waiting sequence, per-class in-service count) split.
852 const auto emit_split = [&](const std::vector<std::size_t>& wait, const std::vector<std::size_t>& si) {
853 std::vector<std::vector<T>> kst;
854 for (std::size_t r = 0; r < R; ++r) {
855 const std::vector<std::vector<T>> sr = space_closed_single<T>(phases[r], si[r]);
856 if (sr.empty() && si[r] > 0) return;
857 kst = cartesian(kst, sr);
858 }
859 std::vector<std::vector<T>> bufs;
860 if (!paired) {
861 std::vector<T> b;
862 for (std::size_t j = 0; j < wait.size(); ++j)
863 b.push_back(num_traits<T>::from_int(static_cast<long>(wait[j])));
864 if (b.empty()) b.push_back(num_traits<T>::from_int(0));
865 bufs.push_back(b);
866 } else if (wait.empty()) {
867 // An empty paired buffer is still two columns wide, so that a
868 // narrower row left-padded to the widest one keeps its parity.
869 bufs.push_back(std::vector<T>(2, num_traits<T>::from_int(0)));
870 } else {
871 bufs.push_back(std::vector<T>());
872 for (std::size_t j = 0; j < wait.size(); ++j) {
873 std::vector<std::vector<T>> next;
874 for (std::size_t b = 0; b < bufs.size(); ++b)
875 for (std::size_t p = 0; p < phases[wait[j] - 1]; ++p) {
876 std::vector<T> row = bufs[b];
877 row.push_back(num_traits<T>::from_int(static_cast<long>(wait[j])));
878 row.push_back(num_traits<T>::from_int(static_cast<long>(p + 1)));
879 next.push_back(row);
880 }
881 bufs.swap(next);
882 }
883 }
884 for (std::size_t bi = 0; bi < bufs.size(); ++bi)
885 for (std::size_t i2 = 0; i2 < kst.size(); ++i2) {
886 std::vector<T> row = bufs[bi];
887 row.insert(row.end(), kst[i2].begin(), kst[i2].end());
888 res2.push_back(row);
889 }
890 };
891 if (sched == SchedStrategy::LCFSPRIO) {
892 // PRIORITY-CANONICAL BUFFERS (MATLAB State.priorityCanonicalPerms/priorityCanonicalBuffers). An LCFSPRIO
893 // server takes the newest job of the most urgent level present (lowest prio value), so the order ACROSS
894 // levels is never read: the buffer is grouped by level, least urgent leftmost and most urgent at the
895 // head (rightmost), and only the order WITHIN a level is enumerated. after_event_station keeps that
896 // layout by inserting an arrival at the tail of its own level. Every split of n into `insrv` jobs in
897 // service is crossed with the canonical buffers of the rest. The full cross-level sequence priced a
898 // two-class queue at cutoff 25 at ~1e14 states against 1301 here. HOL keeps the full sequence.
899 std::vector<std::vector<std::size_t>> splits;
900 std::vector<std::size_t> cur(R, 0);
901 std::function<void(std::size_t, std::size_t)> rec = [&](std::size_t r, std::size_t left) {
902 if (r == R) {
903 if (left == 0) splits.push_back(cur);
904 return;
905 }
906 for (std::size_t v = std::min(n[r], left) + 1; v-- > 0;) {
907 cur[r] = v;
908 rec(r + 1, left - v);
909 }
910 cur[r] = 0;
911 };
912 rec(0, insrv);
913 std::vector<int> levels;
914 for (std::size_t r = 0; r < R; ++r)
915 if (n[r] > 0) levels.push_back(sn.classes[r].prio);
916 std::sort(levels.begin(), levels.end(), std::greater<int>()); // least urgent leftmost
917 levels.erase(std::unique(levels.begin(), levels.end()), levels.end());
918 for (const std::vector<std::size_t>& si : splits) {
919 std::vector<std::vector<std::size_t>> waits(1);
920 for (int lev : levels) {
921 std::vector<std::size_t> grp; // descending first, walked down with prev_permutation
922 for (std::size_t r = R; r-- > 0;)
923 if (sn.classes[r].prio == lev)
924 for (std::size_t j = 0; j < n[r] - si[r]; ++j) grp.push_back(r + 1);
925 if (grp.empty()) continue;
926 std::vector<std::vector<std::size_t>> next;
927 do {
928 for (const std::vector<std::size_t>& w : waits) {
929 std::vector<std::size_t> w2 = w;
930 w2.insert(w2.end(), grp.begin(), grp.end());
931 next.push_back(w2);
932 }
933 } while (std::prev_permutation(grp.begin(), grp.end()));
934 waits.swap(next);
935 }
936 for (const std::vector<std::size_t>& w : waits) emit_split(w, si);
937 }
938 return res2;
939 }
940 do {
941 // Split the permutation: the tail is in service, the head waits.
942 // The servers are unordered, so permutations differing only in the tail give the
943 // same rows (the reference's `unique`). The descending tail is met first; skip others.
944 if (!std::is_sorted(vi.end() - static_cast<std::ptrdiff_t>(insrv), vi.end(),
945 std::greater<std::size_t>()))
946 continue;
947 std::vector<std::size_t> si(R, 0);
948 for (std::size_t j = vi.size() - insrv; j < vi.size(); ++j) si[vi[j] - 1] += 1;
949 std::vector<std::size_t> wait;
950 for (std::size_t j = 0; j + insrv < vi.size(); ++j) wait.push_back(vi[j]);
951 emit_split(wait, si);
952 } while (std::prev_permutation(vi.begin(), vi.end()));
953 return res2;
954 }
955
956 if (!state_detail::buffer_is_per_class_count(sched)) {
957 // The INF/PS families track only jobs in the servers, so every job of
958 // every class carries a phase and this fold IS the local state space.
959 std::vector<std::vector<T>> srv;
960 for (std::size_t r = 0; r < R; ++r)
961 srv = cartesian(srv, space_closed_single<T>(phases[r], n[r]));
962 return srv;
963 }
964
965 // Per-class-count buffer: everything beyond the servers waits. The split
966 // between in-service and waiting is NOT determined by the marginal, so it is
967 // enumerated here.
968 //
969 // THE SPLIT MUST DRIVE THE SERVER BLOCK, NOT BE RECOVERED FROM IT. The `srv`
970 // fold above places all n[r] jobs of every class, because that is what the
971 // INF and PS families need. An earlier version of this branch built the
972 // server block the same way and then tried to read the in-service count back
973 // out of it -- but that count is identically n[r], the very number just
974 // placed there, so the buffer came out identically zero and every marginal
975 // whose total exceeded the server count was discarded. A POLLING station
976 // then held at most `nservers` jobs and never queued one: a two-class model
977 // with lambda 0.2/0.3 and mu 2 reported the throughput of an M/M/1/1,
978 // 0.16/0.24 against the correct 0.20/0.30, with QLen equal to Util in every
979 // state because nothing ever waited. The buffered states were not merely
980 // improbable, they were absent, so the arrival handler's successors had
981 // nowhere to land and the generator dropped those edges.
982 //
983 // The other two branches of this function already do it this way -- the
984 // class-tag branch takes si[r] from the permutation tail, the retrial branch
985 // takes `want` from the in-service count -- and they are the two that worked.
986 //
987 // HOW MANY JOBS ARE IN SERVICE IS A PROPERTY OF THE DISCIPLINE. The
988 // reference splits this family in two, and the split is exactly the
989 // work-conservation of the station:
990 //
991 // POLLING has its own `fromMarginal` case, and it emits the EMPTY-facility
992 // row -- all n waiting, nothing served -- alongside the one-job-in-service
993 // rows. A polling server may sit idle with a backlog because it is walking
994 // between buffers or parked, so that row is a state it genuinely occupies.
995 // Its single facility also means at most one job is ever in service.
996 //
997 // SIRO, SEPT, LEPT and the SRPT pair are work conserving, and the
998 // reference enumerates EXACTLY min(S, sum n) in service (`multichoosecon`).
999 // Emitting the partially-idle rows for them would widen the space past
1000 // MATLAB's with states no transition enters.
1001 //
1002 // So the bound is `sum s == maxsrv`, relaxed to `sum s >= 0` for POLLING.
1003 const double S = st.nservers;
1004 if (sched == SchedStrategy::POLLING && S != 1.0)
1005 throw UnsupportedError(ErrorKind{"SchedStrategy_POLLING"},
1006 "from_marginal: a polling station must have exactly one server; the controller "
1007 "encoding pins the visit to a single class at a time, so a multi-server polling "
1008 "station cannot be represented (the reference refuses it the same way)");
1009 const std::size_t nsrv =
1010 std::isfinite(S) ? static_cast<std::size_t>(S) : static_cast<std::size_t>(-1);
1011 std::size_t ntot = 0;
1012 for (std::size_t r = 0; r < R; ++r) ntot += n[r];
1013 const std::size_t maxsrv = std::min(nsrv, ntot);
1014 const std::size_t minsrv = sched == SchedStrategy::POLLING ? 0 : maxsrv;
1015
1016 std::vector<std::vector<T>> res;
1017 std::vector<std::size_t> sv(R, 0);
1018 for (;;) {
1019 std::size_t stot = 0;
1020 for (std::size_t r = 0; r < R; ++r) stot += sv[r];
1021 if (stot >= minsrv && stot <= maxsrv) {
1022 std::vector<std::vector<T>> srv_s;
1023 bool ok = true;
1024 for (std::size_t r = 0; r < R && ok; ++r) {
1025 const std::vector<std::vector<T>> sr = space_closed_single<T>(phases[r], sv[r]);
1026 if (sr.empty() && sv[r] > 0) ok = false;
1027 else srv_s = cartesian(srv_s, sr);
1028 }
1029 if (ok) {
1030 std::vector<T> buf(R, num_traits<T>::from_int(0));
1031 for (std::size_t r = 0; r < R; ++r)
1032 buf[r] = num_traits<T>::from_int(static_cast<long>(n[r] - sv[r]));
1033 for (std::size_t i = 0; i < srv_s.size(); ++i) {
1034 std::vector<T> row = buf;
1035 row.insert(row.end(), srv_s[i].begin(), srv_s[i].end());
1036 res.push_back(row);
1037 }
1038 }
1039 }
1040 // Mixed-radix increment of the per-class in-service counts.
1041 std::size_t r = 0;
1042 for (; r < R; ++r) {
1043 if (sv[r] < n[r]) { ++sv[r]; break; }
1044 sv[r] = 0;
1045 }
1046 if (r == R) break;
1047 }
1048 return res;
1049}
1050
1051/**
1052 * Port of `State.pollingBlocks` + `State.pollingProject`: every controller
1053 * configuration compatible with one (buffer, server) row.
1054 *
1055 * ENUMERATING PER ROW rather than taking a blind cartesian product is what
1056 * keeps the space tight and the chain irreducible. pos is PINNED to the class
1057 * in service; a switchover excludes a busy facility; and a park excludes a
1058 * non-empty station, because with only immediate switchovers the server would
1059 * have reached the waiting work in zero time. A cartesian product would admit
1060 * "serving buffer 1 while a class-2 job holds the server", which no transition
1061 * can enter or leave consistently with the marginals.
1062 *
1063 * @param srvclass 1-based class holding the single service facility, 0 if idle
1064 * @param nbuf per-class waiting counts
1065 * @param pi the polling configuration of the station
1066 * @return one row per configuration, PROJECTED onto the columns `pinfo`
1067 * materializes; the elided ones are reconstructible from the rest of
1068 * the state (`polling_get`), so keeping them would split each state
1069 * into copies no observation can tell apart
1070 */
1071template <class T>
1072std::vector<std::vector<T>> polling_blocks(const PollingInfo<T>& pi, std::size_t srvclass,
1073 const std::vector<std::size_t>& nbuf) {
1074 const std::size_t R = pi.polled.size();
1075 std::vector<std::vector<long>> trips; // full [pos, swk, ctr, src, tht, trt_1..R]
1076 // The TRT combinations of a timed token (one zero row otherwise), in the
1077 // order `State.pollingBlocks` stacks them.
1078 std::vector<std::vector<long>> Tset(1, std::vector<long>(R, 0));
1080 for (std::size_t r = 0; r < R; ++r) {
1081 if (!pi.polled[r]) continue;
1082 std::vector<std::vector<long>> Tn;
1083 for (long k = 0; k <= static_cast<long>(pi.tk[r]); ++k)
1084 for (std::size_t t = 0; t < Tset.size(); ++t) {
1085 std::vector<long> row = Tset[t];
1086 row[r] = k;
1087 Tn.push_back(row);
1088 }
1089 Tset.swap(Tn);
1090 }
1091 auto push = [&](long pos, long swk, long ctr, long src, long tht) {
1092 for (std::size_t t = 0; t < Tset.size(); ++t) {
1093 std::vector<long> row{pos, swk, ctr, src, tht};
1094 row.insert(row.end(), Tset[t].begin(), Tset[t].end());
1095 trips.push_back(row);
1096 }
1097 };
1098 std::size_t total = 0;
1099 for (std::size_t r = 0; r < nbuf.size(); ++r) total += nbuf[r];
1100 bool anysw = false;
1101 for (bool b : pi.has_sw) anysw = anysw || b;
1102 if (srvclass > 0) {
1103 // A buffer outside the cyclic order can hold no job at all.
1104 if (!pi.polled[srvclass - 1]) return std::vector<std::vector<T>>();
1105 std::vector<long> ctrset;
1106 switch (pi.ptype) {
1108 ctrset.push_back(0);
1109 break;
1111 // ctr counts the jobs admitted at the polling instant that have
1112 // not completed, the one in service included, so ctr >= 1 and
1113 // the ctr-1 still uncompleted ones all wait in the buffer.
1114 for (long c = 1; c <= static_cast<long>(nbuf[srvclass - 1]) + 1; ++c)
1115 ctrset.push_back(c);
1116 break;
1118 for (long c = 1; c <= static_cast<long>(pi.pk); ++c) ctrset.push_back(c);
1119 break;
1121 // as GATED, with the admitted count also capped at K
1122 for (long c = 1; c <= std::min(static_cast<long>(pi.pk), static_cast<long>(nbuf[srvclass - 1]) + 1); ++c)
1123 ctrset.push_back(c);
1124 break;
1126 // ctr is the population the visit is driving the class down to.
1127 for (long c = 0; c <= static_cast<long>(nbuf[srvclass - 1]); ++c)
1128 ctrset.push_back(c);
1129 break;
1130 }
1131 std::vector<long> thtset;
1133 thtset.push_back(0);
1134 else
1135 for (long k = pi.tpreempt ? 1 : 0; k <= static_cast<long>(pi.tk[srvclass - 1]); ++k)
1136 thtset.push_back(k);
1137 std::vector<long> posset;
1138 if (pi.keep[0]) {
1139 for (std::size_t p = 0; p < pi.M; ++p)
1140 if (pi.ring[p] == srvclass) posset.push_back(static_cast<long>(p + 1));
1141 } else {
1142 posset.push_back(static_cast<long>(pi.pos_of[srvclass - 1]));
1143 }
1144 for (long pos : posset)
1145 for (long ctr : ctrset)
1146 for (long tht : thtset) push(pos, 0, ctr, 0, tht);
1147 } else if (pi.ld) {
1148 std::vector<std::size_t> srcset;
1149 for (std::size_t l = 1; l <= pi.has_sw.size(); ++l)
1150 if (pi.has_sw[l - 1]) {
1151 srcset.push_back(l);
1152 if (!pi.keep[3]) break;
1153 }
1154 for (std::size_t i : srcset)
1155 for (std::size_t j = 1; j <= R; ++j) {
1156 if (!pi.polled[j - 1]) continue;
1157 if (pi.keep[3] && j == i) continue; // a timed leg is never paid to stay put
1158 for (std::size_t k = 1; k <= pi.ksw[i - 1]; ++k)
1159 push(static_cast<long>(j), static_cast<long>(k), 0, static_cast<long>(i), 0);
1160 }
1161 if (total == 0) {
1162 if (pi.keep[0]) {
1163 for (std::size_t p = 1; p <= R; ++p)
1164 if (pi.polled[p - 1]) push(static_cast<long>(p), 0, 0, 0, 0);
1165 } else {
1166 push(static_cast<long>(pi.canon_pos), 0, 0, 0, 0);
1167 }
1168 }
1169 } else {
1170 for (std::size_t q = 1; q <= pi.has_sw.size(); ++q) {
1171 if (!pi.has_sw[q - 1]) continue;
1172 // Every phase of a non-immediate switchover is dwelt in, and jobs
1173 // may wait meanwhile: this is exactly what makes a polling station
1174 // non-work-conserving.
1175 for (std::size_t k = 1; k <= pi.ksw[q - 1]; ++k)
1176 push(static_cast<long>(q), static_cast<long>(k), 0, 0, 0);
1177 }
1178 if (!anysw && total == 0) {
1179 if (pi.keep[0]) {
1180 // a table that repeats a class: the park position is observable
1181 for (std::size_t p = 1; p <= pi.M; ++p) push(static_cast<long>(p), 0, 0, 0, 0);
1182 } else {
1183 push(static_cast<long>(pi.canon_pos), 0, 0, 0, 0);
1184 }
1185 }
1186 }
1187
1188 std::vector<std::vector<T>> out;
1189 for (std::size_t i = 0; i < trips.size(); ++i) {
1190 std::vector<T> row;
1191 for (std::size_t k = 0; k < trips[i].size() && k < pi.keep.size(); ++k)
1192 if (pi.keep[k]) row.push_back(num_traits<T>::from_int(trips[i][k]));
1193 out.push_back(row);
1194 }
1195 return out;
1196}
1197
1198/**
1199 * Port of `State.rrSpace` for one row: the round-robin quantum blocks a
1200 * [buffer | server] row can carry, one per way of splitting the server count
1201 * of every (class, service phase) pair over the quantum phases.
1202 *
1203 * The INITIAL configuration (every job in service in the first quantum phase
1204 * the quantum can start in, the reference's `initOnly` block) is emitted
1205 * FIRST, so `from_marginal_node_first` and `default_init_state` start from the
1206 * state `State.initDefault` builds.
1207 */
1208template <class T>
1209std::vector<std::vector<T>> rr_blocks(const RrInfo<T>& ri, const std::vector<T>& row) {
1210 const std::size_t R = ri.K.size();
1211 std::size_t srvw = 0;
1212 for (std::size_t r = 0; r < R; ++r) srvw += ri.K[r];
1213 const std::size_t srv0 = row.size() - srvw;
1214 std::vector<std::vector<T>> blocks;
1215 std::vector<T> init;
1216 std::size_t sh = 0;
1217 for (std::size_t r = 0; r < R; ++r) {
1218 std::size_t q0 = 0;
1219 for (std::size_t q = 0; q < ri.Q[r]; ++q)
1220 if (num_traits<T>::to_double(ri.qa[r][q]) > 0) { q0 = q; break; }
1221 for (std::size_t k = 0; k < ri.K[r]; ++k) {
1222 const double v = num_traits<T>::to_double(row[srv0 + sh + k]);
1223 const std::size_t nrk = v > 0 ? static_cast<std::size_t>(v) : 0;
1224 const std::vector<std::vector<T>> b = space_closed_single<T>(ri.Q[r], nrk);
1225 blocks = cartesian(blocks, b);
1226 for (std::size_t q = 0; q < ri.Q[r]; ++q)
1227 init.push_back(num_traits<T>::from_int(q == q0 ? static_cast<long>(nrk) : 0L));
1228 }
1229 sh += ri.K[r];
1230 }
1231 for (std::size_t b = 0; b < blocks.size(); ++b)
1232 if (blocks[b] == init) {
1233 if (b > 0) {
1234 const std::vector<T> keep = blocks[b];
1235 blocks.erase(blocks.begin() + static_cast<std::ptrdiff_t>(b));
1236 blocks.insert(blocks.begin(), keep);
1237 }
1238 break;
1239 }
1240 return blocks;
1241}
1242
1243/**
1244 * Every held-job vector a true-BAS row may carry (BUG-110), over the codes of
1245 * `NetworkStruct::bas_marker_codes`: per class r, compositions of at most
1246 * sir[r] jobs over the codes of class r, crossed over the classes in class
1247 * order (lexicographic, the zero vector first), and with at most one job in
1248 * total at a single-server station. Port of `_bas_held_combos`.
1249 */
1250template <class T>
1251std::vector<std::vector<long>> bas_held_combos(const NetworkStruct<T>& sn,
1252 const std::vector<std::size_t>& codes,
1253 const std::vector<long>& sir, bool single) {
1254 const std::size_t R = sn.nclasses;
1255 const std::size_t nc = NetworkStruct<T>::bas_ncols(codes);
1256 std::vector<std::vector<std::size_t>> by_class(R);
1257 for (std::size_t k = 0; k < codes.size(); ++k) {
1258 std::size_t r = 0, jst = 0, s = 0;
1259 sn.bas_decode(codes[k], r, jst, s);
1260 by_class[r - 1].push_back(k);
1261 }
1262 std::vector<std::vector<long>> out;
1263 std::vector<long> h(nc, 0);
1264 std::function<void(std::size_t)> rec_class;
1265 std::function<void(std::size_t, std::size_t, long)> rec_split;
1266 rec_class = [&](std::size_t r) {
1267 if (r == R) {
1268 long tot = 0;
1269 for (std::size_t k = 0; k < nc; ++k) tot += h[k];
1270 if (!single || tot <= 1) out.push_back(h);
1271 return;
1272 }
1273 const long cap = r < sir.size() ? sir[r] : 0;
1274 if (by_class[r].empty() || cap <= 0) {
1275 rec_class(r + 1);
1276 return;
1277 }
1278 rec_split(r, 0, cap);
1279 };
1280 // Position j of class r's codes takes 0..left, lexicographic as
1281 // `_compositions_upto`, then the next class.
1282 rec_split = [&](std::size_t r, std::size_t j, long left) {
1283 if (j == by_class[r].size()) {
1284 rec_class(r + 1);
1285 return;
1286 }
1287 for (long v = 0; v <= left; ++v) {
1288 h[by_class[r][j]] = v;
1289 rec_split(r, j + 1, left - v);
1290 }
1291 h[by_class[r][j]] = 0;
1292 };
1293 rec_class(0);
1294 return out;
1295}
1296
1297/**
1298 * Append the trailing local-variable block to every row the core builders
1299 * produce, which is what makes a state row as wide as `nvars_of` declares.
1300 *
1301 * Shared by `from_marginal` and `from_marginal_and_started`: the two differ in
1302 * how the (buffer, server) split is chosen, never in what follows it, so the
1303 * controller, the BAS marker and the reply counters are appended once here.
1304 *
1305 * WITHOUT THIS THE ROWS ARE ONE BLOCK TOO NARROW and every slicer that takes
1306 * `nvar` clear of the right-hand end reads the server block from the wrong
1307 * offset. Measured on a two-class EXHAUSTIVE polling station: the controller
1308 * was absent from the enumerated space entirely and the station behaved as a
1309 * capacity-one queue, reporting Tput 0.16/0.24 against MATLAB's 0.20/0.30.
1310 *
1311 * The polling controller is enumerated per row (`polling_blocks`), and so is the
1312 * ROUND-ROBIN POINTER: which link the next job takes is a coordinate of the
1313 * state, so a space that emitted it at zero would carry one configuration of a
1314 * dispatcher that has several, and the chain could never leave it. RROBIN
1315 * enumerates its outlinks and WRROBIN the positions of its weighted cycle,
1316 * exactly as `State.fromMarginal`'s `sub_routevars` does.
1317 *
1318 * The modulating phase and the REPLY blocked-server counters are still emitted
1319 * at zero: exact for a model that declares none of them, and width-correct
1320 * rather than enumerated for one that does; see `14-cpp-multiprecision.md`.
1321 */
1322template <class T>
1323std::vector<std::vector<T>> append_local_vars(const NetworkStruct<T>& sn, std::size_t ist,
1324 std::vector<std::vector<T>> rows,
1325 const std::vector<std::size_t>& n,
1326 const std::vector<std::size_t>& phases) {
1327 if (rows.empty()) return rows;
1328 const std::size_t ind = sn.node_of_station(ist);
1329 // No node means no local-variable block to append; a Layer submodel carries
1330 // stations without a node map at all.
1331 if (ind == 0) return rows;
1332 const std::size_t width = sn.nvars_of(ind);
1333 const PollingInfo<T> pi = polling_info(sn, ind);
1334 // A round-robin station's quantum block sits in the same node-block slot
1335 // the polling controller uses, and the two are mutually exclusive (an RR
1336 // station is not a polling station).
1337 const RrInfo<T> ri = rr_info(sn, ind);
1338 // A polling station is NOT done when it has no local-variable column: an
1339 // EXHAUSTIVE controller whose switchovers are all immediate materializes
1340 // nothing, yet `State.pollingBlocks` still prunes the rows it cannot occupy
1341 // (an idle facility with work waiting, which the server would have reached
1342 // in zero time). Returning early here kept those rows: 20 states against
1343 // MATLAB's 13 on a two-class station, the extras at zero probability and
1344 // the generator reducible.
1345 if (width == 0 && !pi.valid) return rows;
1346
1347 const std::size_t R = sn.nclasses;
1348 const std::size_t pw = pi.valid ? pi.width : (ri.valid ? ri.width : 0);
1349 const T zero = num_traits<T>::from_int(0);
1350
1351 // The true-BAS held-job block takes the node-block slot, so it is MUTUALLY
1352 // EXCLUSIVE with the polling controller and is enumerated instead of it. It
1353 // holds one counter per target code (BUG-110; formerly a single {0,1}
1354 // marker): how many completed jobs wait here for room at each destination.
1355 // Only a job in service can be held, so an empty marginal carries zeros.
1356 const bool bas = ind <= sn.isbasblocking.size() && sn.isbasblocking[ind - 1];
1357 const std::vector<std::size_t> bas_codes =
1358 bas ? sn.bas_marker_codes(ind) : std::vector<std::size_t>();
1359 const std::size_t bas_nc = bas ? NetworkStruct<T>::bas_ncols(bas_codes) : 0;
1360 const bool bas_single = bas && sn.bas_single_server(ist);
1361 // The server status of a breakdown station takes the same trailing column
1362 // and, unlike the BAS marker, is enumerated for EVERY marginal including the
1363 // empty one: an idle server still fails. UP (1) is emitted first, so the
1364 // default initial state (the first row) has the server up, which is the row
1365 // the reference's descending sort puts first.
1366 const bool brk = sn.has_breakdown_node(ind);
1367 // The CTMC station block (setup/delay-off or attempt levels, ctmc_blocks.h):
1368 // emitted at zero here, which is the all-ACTIVE setup state; the attempt
1369 // levels are enumerated at the end.
1370 const std::size_t tailw = ctmc_tail_width(sn, ind);
1371
1372 // The dispatch pointers, one column per class that routes round-robin, in
1373 // CLASS ORDER and immediately after the modulating phases: that is where
1374 // `rr_var_slot` reads them and where the reference appends them.
1375 std::size_t rrw = 0;
1376 if (ind <= sn.nvars.size())
1377 for (std::size_t r = 0; r < R && R + r < sn.nvars[ind - 1].size(); ++r)
1378 rrw += sn.nvars[ind - 1][R + r];
1379 std::vector<std::vector<T>> ptrsets(1, std::vector<T>());
1380 for (std::size_t r = 1; r <= R; ++r) {
1381 if (sn.rr_var_slot(ind, r) == 0) continue;
1382 std::vector<T> vals;
1383 if (sn.nodes[ind - 1].routing[r - 1] == RoutingStrategy::RROBIN) {
1384 const std::vector<std::size_t> ol = sn.rr_outlinks(ind, r);
1385 for (std::size_t d = 0; d < ol.size(); ++d)
1386 vals.push_back(num_traits<T>::from_int(static_cast<long>(ol[d])));
1387 } else {
1388 const std::vector<std::size_t> cy = sn.rr_weighted_outlinks(ind, r);
1389 for (std::size_t d = 0; d < cy.size(); ++d)
1390 vals.push_back(num_traits<T>::from_int(static_cast<long>(d + 1)));
1391 }
1392 if (vals.empty()) vals.push_back(zero);
1393 std::vector<std::vector<T>> grown;
1394 for (std::size_t g = 0; g < ptrsets.size(); ++g)
1395 for (std::size_t v = 0; v < vals.size(); ++v) {
1396 std::vector<T> row = ptrsets[g];
1397 row.push_back(vals[v]);
1398 grown.push_back(row);
1399 }
1400 ptrsets.swap(grown);
1401 }
1402
1403 std::vector<std::vector<T>> out;
1404 for (std::size_t i = 0; i < rows.size(); ++i) {
1405 // The controller depends on WHICH class holds the service facility and
1406 // on how many jobs wait, so recover both from the row just built.
1407 std::vector<std::size_t> nbuf(R, 0);
1408 std::size_t srvclass = 0;
1409 if (pi.valid) {
1410 std::size_t srvw = 0;
1411 for (std::size_t r = 0; r < R; ++r) srvw += phases[r];
1412 const std::size_t srv0 = rows[i].size() - srvw;
1413 std::size_t off = 0;
1414 for (std::size_t r = 0; r < R; ++r) {
1415 std::size_t c = 0;
1416 for (std::size_t k = 0; k < phases[r]; ++k)
1417 c += static_cast<std::size_t>(
1418 num_traits<T>::to_double(rows[i][srv0 + off + k]));
1419 off += phases[r];
1420 if (c > 0 && srvclass == 0) srvclass = r + 1;
1421 // The per-class-count buffer POLLING uses puts the waiting
1422 // count in column r, ahead of the server block.
1423 if (srv0 >= R) nbuf[r] = static_cast<std::size_t>(
1424 num_traits<T>::to_double(rows[i][r]));
1425 }
1426 }
1427 // TRUE BAS (BUG-110): one held-job counter per target code. Per class
1428 // r, the jobs held across r's codes cannot exceed the class-r jobs in
1429 // service (the row's server block), and a single-server station holds
1430 // at most one job in total. An empty marginal holds nothing.
1431 std::vector<std::vector<long>> bas_combos;
1432 if (bas) {
1433 std::size_t srvw = 0;
1434 for (std::size_t r = 0; r < R; ++r) srvw += phases[r];
1435 const std::size_t srv0 = rows[i].size() - srvw;
1436 std::vector<long> sir(R, 0);
1437 std::size_t off = 0;
1438 for (std::size_t r = 0; r < R; ++r) {
1439 for (std::size_t k = 0; k < phases[r]; ++k)
1440 sir[r] += static_cast<long>(
1441 std::llround(num_traits<T>::to_double(rows[i][srv0 + off + k])));
1442 off += phases[r];
1443 }
1444 bas_combos = bas_held_combos(sn, bas_codes, sir, bas_single);
1445 }
1446 const std::vector<std::vector<T>> blocks =
1447 pi.valid ? polling_blocks(pi, srvclass, nbuf)
1448 : ri.valid ? rr_blocks(ri, rows[i])
1449 : std::vector<std::vector<T>>(1, std::vector<T>());
1450 // No admissible controller configuration means the (buffer, server)
1451 // split itself is unoccupiable, so the row is DROPPED rather than
1452 // emitted without a controller.
1453 // ORDER IS THE ENCODING: nvars is [modulation | routing | node block |
1454 // reply], so the controller sits between the routing pointers and the
1455 // reply counters, not at the end. `polling_info` computes its offset
1456 // the same way, and the two must agree or every read is shifted.
1457 // The CTMC station block (ctmc_blocks.h) trails everything else, so the
1458 // modulation and routing columns end that many columns earlier.
1459 const std::size_t head = pi.valid ? pi.off : (ri.valid ? ri.boff : width - pw - tailw);
1460 for (std::size_t b = 0; b < blocks.size(); ++b) {
1461 for (std::size_t g = 0; g < ptrsets.size(); ++g) {
1462 std::vector<T> row = rows[i];
1463 row.insert(row.end(), head - rrw, zero); // modulating phases
1464 row.insert(row.end(), ptrsets[g].begin(), ptrsets[g].end()); // dispatch pointers
1465 row.insert(row.end(), blocks[b].begin(), blocks[b].end());
1466 row.insert(row.end(), width - head - pw, zero); // reply counters
1467 if (brk) {
1468 for (long v = 1; v >= 0; --v) {
1469 std::vector<T> r2 = row;
1470 r2.back() = num_traits<T>::from_int(v);
1471 out.push_back(r2);
1472 }
1473 continue;
1474 }
1475 if (!bas) {
1476 out.push_back(row);
1477 continue;
1478 }
1479 // The held-job block is the LAST bas_nc columns, which is where the
1480 // generator's departure split and become-blocked edge read it.
1481 // `refresh_bas_blocking` refuses BAS together with a reply block for
1482 // exactly this reason: the reply counters would trail it. One row per
1483 // held vector the (buffer, server) split admits (BUG-110), the zero
1484 // vector first so the default initial state holds nothing.
1485 for (std::size_t h = 0; h < bas_combos.size(); ++h) {
1486 std::vector<T> r2 = row;
1487 for (std::size_t k = 0; k < bas_nc; ++k)
1488 r2[r2.size() - bas_nc + k] = num_traits<T>::from_int(bas_combos[h][k]);
1489 out.push_back(r2);
1490 }
1491 }
1492 }
1493 }
1494 // A MAP service in CTMC pair form (`ctmc_mapc`) carries the landing phase of its last
1495 // started draw, 1..p: every row is enumerated over it, value 1 first for the default state.
1496 // A single server's memory is the phase of the class-r job in service when there is one,
1497 // as in `State.fromMarginal`, and 1..p otherwise.
1498 std::size_t srvw = 0;
1499 for (std::size_t r = 0; r < R && r < phases.size(); ++r) srvw += phases[r];
1500 for (std::size_t r = 1; r <= R; ++r) {
1501 const CtmcMapc<T>* mc = sn.mapc_of(ist, r);
1502 if (mc == nullptr || sn.nvars[ind - 1][r - 1] == 0) continue;
1503 const std::size_t slot = sn.map_var_slot(ind, r);
1504 std::size_t off = 0;
1505 for (std::size_t j = 0; j + 1 < r; ++j) off += phases[j];
1506 std::vector<std::vector<T>> grown;
1507 grown.reserve(out.size() * mc->p);
1508 for (std::size_t i = 0; i < out.size(); ++i) {
1509 const std::size_t srv0 = out[i].size() - width - srvw;
1510 std::size_t busy = 0;
1511 for (std::size_t k = 0; mc->single && k < phases[r - 1] && busy == 0; ++k)
1512 if (num_traits<T>::to_double(out[i][srv0 + off + k]) > 0) busy = k + 1;
1513 for (std::size_t h = 1; h <= mc->p; ++h) {
1514 if (busy != 0 && h != busy) continue;
1515 std::vector<T> row = out[i];
1516 row[row.size() - width + slot] = num_traits<T>::from_int(static_cast<long>(h));
1517 grown.push_back(row);
1518 }
1519 }
1520 out.swap(grown);
1521 }
1522 // RETRIAL WITH A FINITE NUMBER OF ATTEMPTS (python `_space_generator_nodes`):
1523 // the orbit of the retrial class split over its attempt levels, every
1524 // composition of each row's orbit size, the all-at-level-0 one first so that
1525 // the default initial state places an initial orbit at level 0.
1526 const AttemptsLayout att = tailw > 0 ? attempts_info(sn, ind) : AttemptsLayout();
1527 if (att.valid) {
1528 std::size_t off = 0;
1529 for (std::size_t r = 0; r + 1 < att.cls && r < phases.size(); ++r) off += phases[r];
1530 std::vector<std::vector<T>> grown;
1531 for (std::size_t i = 0; i < out.size(); ++i) {
1532 const std::size_t srv0 = out[i].size() - width - srvw;
1533 long sir = 0;
1534 for (std::size_t k = 0; k < phases[att.cls - 1]; ++k)
1535 sir += std::lround(num_traits<T>::to_double(out[i][srv0 + off + k]));
1536 const long nr = att.cls <= n.size() ? static_cast<long>(n[att.cls - 1]) : 0;
1537 const std::size_t orbit = nr > sir ? static_cast<std::size_t>(nr - sir) : 0;
1538 std::vector<std::vector<std::size_t>> comps;
1539 attempt_compositions(orbit, att.M, comps);
1540 for (std::size_t cpi = 0; cpi < comps.size(); ++cpi) {
1541 std::vector<T> row = out[i];
1542 for (std::size_t a = 0; a < att.M; ++a)
1543 row[row.size() - att.M + a] = num_traits<T>::from_int(static_cast<long>(comps[cpi][a]));
1544 grown.push_back(row);
1545 }
1546 }
1547 out.swap(grown);
1548 }
1549 return out;
1550}
1551
1552namespace state_detail {
1553
1554/**
1555 * The in-service allocations of `State.fromMarginalPool`: x[r][k] class-r jobs on
1556 * the k-th compatible pool of r, within the pool sizes, such that no class with a
1557 * waiting job finds a free compatible server.
1558 */
1559template <class T>
1560void pool_allocations(const CtmcPool<T>& pool, const std::vector<std::size_t>& n, std::size_t r,
1561 std::size_t k, std::vector<std::vector<std::size_t>>& x,
1562 std::vector<double>& load,
1563 std::vector<std::vector<std::vector<std::size_t>>>& out) {
1564 const std::size_t R = n.size();
1565 if (r == R) {
1566 for (std::size_t s = 0; s < R; ++s) {
1567 if (pool.pools[s].empty()) continue;
1568 std::size_t ins = 0;
1569 for (std::size_t j = 0; j < x[s].size(); ++j) ins += x[s][j];
1570 if (n[s] <= ins) continue;
1571 for (std::size_t j = 0; j < pool.pools[s].size(); ++j) {
1572 const std::size_t t = pool.pools[s][j];
1573 if (load[t - 1] < pool.count[t - 1]) return; // a waiting job has a free server
1574 }
1575 }
1576 out.push_back(x);
1577 return;
1578 }
1579 if (pool.pools[r].empty() || k == pool.pools[r].size()) {
1580 pool_allocations(pool, n, r + 1, 0, x, load, out);
1581 return;
1582 }
1583 const std::size_t t = pool.pools[r][k];
1584 std::size_t used = 0;
1585 for (std::size_t j = 0; j < k; ++j) used += x[r][j];
1586 const double room = pool.count[t - 1] - load[t - 1];
1587 const std::size_t cmax = std::min<std::size_t>(
1588 n[r] - used, room > 0 ? static_cast<std::size_t>(room + 0.5) : 0);
1589 for (std::size_t c = 0; c <= cmax; ++c) {
1590 x[r][k] = c;
1591 load[t - 1] += static_cast<double>(c);
1592 pool_allocations(pool, n, r, k + 1, x, load, out);
1593 load[t - 1] -= static_cast<double>(c);
1594 }
1595 x[r][k] = 0;
1596}
1597
1598} // namespace state_detail
1599
1600/**
1601 * Port of `State.fromMarginalPool`: the local states with marginal `n` at a station
1602 * rewritten by `ctmc::ctmc_pools`. A row is [buffer | servers | pool order]: every
1603 * split of the jobs into in-service ones (per class and pool, within the pool sizes)
1604 * and waiting ones such that no waiting job has a free compatible server, every phase
1605 * assignment of the jobs in service, every order of the waiting jobs (per-class counts
1606 * under SIRO) and, under a rotating ALIS/FAIRNESS order, every order index. The ordered
1607 * buffer is max(1, min(sum(n), cap)) wide; rows come out in descending order.
1608 */
1609template <class T>
1610std::vector<std::vector<T>> from_marginal_pool(const NetworkStruct<T>& sn, std::size_t ist,
1611 const std::vector<std::size_t>& n) {
1612 const std::size_t R = sn.nclasses;
1613 const std::size_t ind = sn.node_of_station(ist);
1614 const CtmcPool<T>& pool = sn.ctmcpool.at(ind);
1615 const T zero = num_traits<T>::from_int(0);
1616 std::vector<std::vector<T>> space;
1617 if (sn.nvars_of(ind) != (pool.rotate ? 1u : 0u))
1618 throw UnsupportedError(ErrorKind{"HeteroServers"}, "Station '" + sn.nodes[ind - 1].name +
1619 "' carries local variables that a heterogeneous server pool "
1620 "cannot hold.");
1621 std::size_t ntot = 0;
1622 for (std::size_t r = 0; r < R; ++r) {
1623 ntot += n[r];
1624 if (sn.classcap.size() >= ist && r < sn.classcap[ist - 1].size() &&
1625 static_cast<double>(n[r]) > sn.classcap[ist - 1][r])
1626 return space;
1627 if (pool.pools[r].empty() && n[r] > 0) return space;
1628 }
1629 const double cap = sn.cap[ist - 1];
1630 if (static_cast<double>(ntot) > cap) return space;
1631 const bool siro = sn.stations[ist - 1].sched == SchedStrategy::SIRO;
1632 const std::size_t W =
1633 siro ? R
1634 : std::max<std::size_t>(1, std::isfinite(cap) ? std::min<std::size_t>(
1635 ntot, static_cast<std::size_t>(cap))
1636 : ntot);
1637 std::vector<std::vector<std::size_t>> x(R);
1638 for (std::size_t r = 0; r < R; ++r) x[r].assign(pool.pools[r].size(), 0);
1639 std::vector<double> load(pool.ntypes, 0.0);
1640 std::vector<std::vector<std::vector<std::size_t>>> alloc;
1641 state_detail::pool_allocations(pool, n, 0, 0, x, load, alloc);
1642 for (std::size_t a = 0; a < alloc.size(); ++a) {
1643 std::vector<std::size_t> w = n;
1644 for (std::size_t r = 0; r < R; ++r)
1645 for (std::size_t k = 0; k < alloc[a][r].size(); ++k) w[r] -= alloc[a][r][k];
1646 // server part: the phases of the jobs of each class-pool block
1647 std::vector<std::vector<T>> srvset;
1648 bool ok = true;
1649 for (std::size_t r = 0; r < R && ok; ++r) {
1650 const std::size_t Kr = sn.phasessz_of(ist, r + 1);
1651 std::vector<std::vector<T>> blk;
1652 if (pool.pools[r].empty()) {
1653 blk.push_back(std::vector<T>(Kr, zero));
1654 } else {
1655 for (std::size_t k = 0; k < pool.pools[r].size(); ++k) {
1656 const std::vector<std::vector<T>> sc =
1657 space_closed_single<T>(pool.len[r][k], alloc[a][r][k]);
1658 if (sc.empty()) { ok = false; break; }
1659 blk = cartesian(blk, sc);
1660 }
1661 for (std::size_t b = 0; b < blk.size(); ++b)
1662 if (blk[b].size() < Kr) blk[b].resize(Kr, zero);
1663 }
1664 srvset = cartesian(srvset, blk);
1665 }
1666 if (!ok) continue;
1667 // buffer part
1668 std::vector<std::vector<T>> bufset;
1669 if (siro) {
1670 std::vector<T> b(R, zero);
1671 for (std::size_t r = 0; r < R; ++r) b[r] = num_traits<T>::from_int(static_cast<long>(w[r]));
1672 bufset.push_back(b);
1673 } else {
1674 std::vector<std::size_t> vi;
1675 for (std::size_t r = 0; r < R; ++r) vi.insert(vi.end(), w[r], r + 1);
1676 if (vi.size() > W) continue;
1677 do {
1678 std::vector<T> b(W - vi.size(), zero);
1679 for (std::size_t j = 0; j < vi.size(); ++j)
1680 b.push_back(num_traits<T>::from_int(static_cast<long>(vi[j])));
1681 bufset.push_back(b);
1682 } while (std::next_permutation(vi.begin(), vi.end()));
1683 }
1684 const std::vector<std::vector<T>> part = cartesian(bufset, srvset);
1685 space.insert(space.end(), part.begin(), part.end());
1686 }
1687 if (pool.rotate) {
1688 std::vector<std::vector<T>> ords;
1689 for (std::size_t p = 1; p <= pool.perms.size(); ++p)
1690 ords.push_back(std::vector<T>(1, num_traits<T>::from_int(static_cast<long>(p))));
1691 space = cartesian(space, ords);
1692 }
1693 const auto less = [](const std::vector<T>& a, const std::vector<T>& b) {
1694 for (std::size_t i = 0; i < a.size() && i < b.size(); ++i) {
1695 const double av = num_traits<T>::to_double(a[i]), bv = num_traits<T>::to_double(b[i]);
1696 if (av != bv) return av > bv; // descending, as the reference's space(end:-1:1,:)
1697 }
1698 return a.size() < b.size();
1699 };
1700 const auto same = [](const std::vector<T>& a, const std::vector<T>& b) {
1701 if (a.size() != b.size()) return false;
1702 for (std::size_t i = 0; i < a.size(); ++i)
1703 if (num_traits<T>::to_double(a[i]) != num_traits<T>::to_double(b[i])) return false;
1704 return true;
1705 };
1706 std::sort(space.begin(), space.end(), less);
1707 space.erase(std::unique(space.begin(), space.end(), same), space.end());
1708 return space;
1709}
1710
1711template <class T>
1712std::vector<std::vector<T>> from_marginal(const NetworkStruct<T>& sn, std::size_t ist,
1713 const std::vector<std::size_t>& n,
1714 const std::vector<std::size_t>& phases) {
1715 const std::size_t jnd0 = sn.node_of_station(ist);
1716 // heterogeneous server pools rewritten for the CTMC enumerate in their own layout
1717 if (jnd0 != 0 && !sn.ctmcpool.empty() && sn.ctmcpool.count(jnd0))
1718 return from_marginal_pool(sn, ist, n);
1719 // A Join of an FJ-augmented struct: its state is the per-class count vector
1720 // itself, DETERMINED by the marginal rather than enumerated from it. There is
1721 // no buffer order to choose and no phase to be in, so exactly one row exists.
1722 if (sn.isfjaugmented && jnd0 != 0 && sn.nodes[jnd0 - 1].nodetype == NodeType::Join) {
1723 // A QUORUM join's row leads with its debt counters, all zero at the start
1724 // (`FjJoinParam::debtwidth`, python fjtag); the counts are the last R.
1725 const std::map<std::size_t, FjJoinParam>::const_iterator jp = sn.fjjoinparam.find(jnd0);
1726 const std::size_t dw = jp == sn.fjjoinparam.end() ? 0 : jp->second.debtwidth;
1727 std::vector<T> row(dw + sn.nclasses, num_traits<T>::from_int(0));
1728 for (std::size_t r = 0; r < sn.nclasses && r < n.size(); ++r)
1729 row[dw + r] = num_traits<T>::from_int(static_cast<long>(n[r]));
1730 return std::vector<std::vector<T>>(1, row);
1731 }
1732 // SYNCHRONOUS CALL (REPLY signal), `State.fromMarginal:44-90`. A node with a
1733 // reply block holds one server per job that has left for its callee and is
1734 // waiting for the reply, and THAT COUNT IS NOT DERIVABLE FROM THE MARGINAL:
1735 // the job is at the callee, not here. So the held counts are ENUMERATED and
1736 // the rest of the state is built with the REMAINING servers -- with b held,
1737 // only S-b jobs can be in service, a configuration the plain enumeration
1738 // never produces. Without this the counter column exists but is zero in
1739 // every row, the departure that would hold a server has no successor in the
1740 // space, and the chain dead-ends: measured on the `test_ctmc_reply` model,
1741 // 11 states with the whole population frozen at the caller and every rate
1742 // zero, against 21 enumerated and X = 0.47059 in MATLAB, the JAR and Python.
1743 if (jnd0 != 0 && sn.replyblock.size() >= jnd0) {
1744 std::vector<std::size_t> rclasses;
1745 for (std::size_t r = 0; r < sn.replyblock[jnd0 - 1].size(); ++r)
1746 if (sn.replyblock[jnd0 - 1][r]) rclasses.push_back(r + 1);
1747 if (!rclasses.empty()) {
1748 const double Sd = sn.stations[ist - 1].nservers;
1749 const std::size_t S =
1750 std::isfinite(Sd) ? static_cast<std::size_t>(Sd) : static_cast<std::size_t>(0);
1751 // The recursion runs on a struct with the block CLEARED, which is
1752 // what terminates it: the copy takes this branch no further.
1753 NetworkStruct<T> snb = sn;
1754 snb.replyblock[jnd0 - 1].assign(snb.replyblock[jnd0 - 1].size(), false);
1755 if (snb.nvars.size() >= jnd0)
1756 for (std::size_t r = 1; r <= sn.nclasses && 2 * sn.nclasses + r < snb.nvars[jnd0 - 1].size();
1757 ++r)
1758 snb.nvars[jnd0 - 1][2 * sn.nclasses + r] = 0;
1759 std::vector<std::vector<std::size_t>> bspace(1, std::vector<std::size_t>());
1760 for (std::size_t i = 0; i < rclasses.size(); ++i) {
1761 std::vector<std::vector<std::size_t>> next;
1762 for (std::size_t j = 0; j < bspace.size(); ++j)
1763 for (std::size_t v = 0; v <= S; ++v) {
1764 std::vector<std::size_t> row = bspace[j];
1765 row.push_back(v);
1766 next.push_back(row);
1767 }
1768 bspace.swap(next);
1769 }
1770 std::vector<std::vector<std::vector<T>>> subs(bspace.size());
1771 std::size_t maxw = 0;
1772 for (std::size_t bi = 0; bi < bspace.size(); ++bi) {
1773 std::size_t tot = 0;
1774 for (std::size_t i = 0; i < bspace[bi].size(); ++i) tot += bspace[bi][i];
1775 if (tot > S) continue;
1776 snb.stations[ist - 1].nservers = static_cast<double>(S - tot);
1777 subs[bi] = from_marginal(snb, ist, n, phases);
1778 for (std::size_t i = 0; i < subs[bi].size(); ++i)
1779 maxw = std::max(maxw, subs[bi][i].size());
1780 }
1781 // A held server pushes a job into the buffer, so the sub-spaces come
1782 // out at DIFFERENT buffer widths. The buffer is RIGHT-aligned, empty
1783 // slots padding the left, so widen the narrow rows on the left.
1784 //
1785 // The counters sit at their `reply_block_info` slots, which is the
1786 // end of the row unless a CTMC station block (setup/delay-off or
1787 // attempt levels, ctmc_blocks.h) trails them: the recursion emits
1788 // that block (it keeps its own nvars column), so the counters are
1789 // inserted just before it.
1790 const std::size_t tailw = ctmc_tail_width(sn, jnd0);
1791 std::vector<std::vector<T>> out;
1792 for (std::size_t bi = 0; bi < bspace.size(); ++bi) {
1793 for (std::size_t i = 0; i < subs[bi].size(); ++i) {
1794 std::vector<T> row;
1795 row.reserve(maxw + bspace[bi].size());
1796 if (subs[bi][i].size() < maxw)
1797 row.assign(maxw - subs[bi][i].size(), num_traits<T>::from_int(0));
1798 row.insert(row.end(), subs[bi][i].begin(), subs[bi][i].end());
1799 const std::size_t at = row.size() >= tailw ? row.size() - tailw : row.size();
1800 std::vector<T> cnt;
1801 for (std::size_t j = 0; j < bspace[bi].size(); ++j)
1802 cnt.push_back(num_traits<T>::from_int(static_cast<long>(bspace[bi][j])));
1803 row.insert(row.begin() + at, cnt.begin(), cnt.end());
1804 out.push_back(row);
1805 }
1806 }
1807 std::sort(out.begin(), out.end(), [](const std::vector<T>& a, const std::vector<T>& b) {
1808 for (std::size_t i = 0; i < a.size() && i < b.size(); ++i) {
1809 const double av = num_traits<T>::to_double(a[i]);
1810 const double bv = num_traits<T>::to_double(b[i]);
1811 if (av != bv) return av < bv;
1812 }
1813 return a.size() < b.size();
1814 });
1815 out.erase(std::unique(out.begin(), out.end(),
1816 [](const std::vector<T>& a, const std::vector<T>& b) {
1817 if (a.size() != b.size()) return false;
1818 for (std::size_t i = 0; i < a.size(); ++i)
1819 if (num_traits<T>::to_double(a[i]) !=
1820 num_traits<T>::to_double(b[i]))
1821 return false;
1822 return true;
1823 }),
1824 out.end());
1825 // Rows with fewer held servers first (stable), so the first row --
1826 // the default initial state -- holds none: a marginal places no job
1827 // at a callee, and a server held for a call nobody is serving is
1828 // never released (every arrival then waits forever, and the
1829 // reachable walk explores only that dead end). MATLAB/python
1830 // `fromMarginal`.
1831 const std::size_t nrc = rclasses.size();
1832 const auto held_of = [nrc, tailw](const std::vector<T>& row) -> double {
1833 double h = 0;
1834 const std::size_t end = row.size() >= tailw ? row.size() - tailw : 0;
1835 for (std::size_t j = 0; j < nrc && j < end; ++j)
1836 h += num_traits<T>::to_double(row[end - nrc + j]);
1837 return h;
1838 };
1839 std::stable_sort(out.begin(), out.end(),
1840 [&held_of](const std::vector<T>& a, const std::vector<T>& b) -> bool {
1841 return held_of(a) < held_of(b);
1842 });
1843 return out;
1844 }
1845 }
1846 return append_local_vars(sn, ist, from_marginal_core(sn, ist, n, phases), n, phases);
1847}
1848
1849/**
1850 * Port of `State.fromMarginalAndStarted`: ONE state realizing both a per-class
1851 * occupancy `n` and a per-class STARTED count `s`.
1852 *
1853 * HOW IT DIFFERS FROM `from_marginal_core`, which is the reason it is a separate
1854 * builder rather than a filter over it. `from_marginal` ENUMERATES every
1855 * (buffer, server) split consistent with a marginal, because the marginal alone
1856 * does not determine which jobs hold the servers. Here the split is GIVEN: `s`
1857 * says how many jobs of each class are in service, so exactly one split is
1858 * meant and the buffer contents follow as `n - s`. Filtering the enumeration
1859 * would be both quadratic and wrong at an empty station, where the reference
1860 * emits a row of a prescribed width rather than selecting one.
1861 *
1862 * EVERY STARTED JOB IS PLACED IN PHASE ONE, which is what makes the result an
1863 * INITIAL state rather than a member of the stationary space: a job that has
1864 * just started service has not advanced through its phase-type law yet.
1865 *
1866 * ONE BUFFER ORDERING IS EMITTED under the ordered-buffer disciplines, the
1867 * descending-sorted one. The reference enumerates every permutation and then
1868 * keeps the lexicographic maximum through its trailing unique/flip, so building
1869 * that row directly is the same answer without the factorial.
1870 *
1871 * A SHARED SERVER IGNORES `s` ENTIRELY. Under INF/PS/DPS/GPS/LPS and their
1872 * priority variants every job present is in a server, so the state holds `n`,
1873 * not `s`; writing `s` there would lose the queued jobs. That is not a
1874 * simplification but the reference's own branch, and it was a real defect in
1875 * the Python twin until 2026-08-09.
1876 *
1877 * PAS/OI ignores `s` for a different reason: its local state is the ordered
1878 * class-index list of the jobs present, which carries no service split at all,
1879 * so this delegates to the marginal builder there.
1880 *
1881 * @param sn the network struct
1882 * @param ist station index (1-based)
1883 * @param n per-class occupancy
1884 * @param s per-class started count; must satisfy s[r] <= n[r]
1885 * @param phases per-class phase counts
1886 */
1887template <class T>
1888std::vector<std::vector<T>> from_marginal_and_started_core(const NetworkStruct<T>& sn,
1889 std::size_t ist,
1890 const std::vector<std::size_t>& n,
1891 const std::vector<std::size_t>& s,
1892 const std::vector<std::size_t>& phases) {
1893 const std::size_t R = sn.nclasses;
1894 if (ist == 0 || ist > sn.stations.size())
1895 throw InputError("from_marginal_and_started: station index " + std::to_string(ist) +
1896 " is out of range");
1897 if (n.size() != R || s.size() != R || phases.size() != R)
1898 throw InputError("from_marginal_and_started: n, s and phases must have one entry per class");
1899
1900 const Station<T>& st = sn.stations[ist - 1];
1901 const SchedStrategy sched = st.sched;
1902 std::vector<std::vector<T>> out;
1903
1904 std::size_t ntot = 0, stot = 0;
1905 for (std::size_t r = 0; r < R; ++r) {
1906 if (s[r] > n[r]) return out; // more started than present: no such state
1907 ntot += n[r];
1908 stot += s[r];
1909 }
1910
1911 // The reference's two pre-switch guards. Both are "no such state" rather
1912 // than an error, since the caller may be sweeping a lattice.
1913 if (ist <= sn.classcap.size())
1914 for (std::size_t r = 0; r < R && r < sn.classcap[ist - 1].size(); ++r)
1915 if (static_cast<double>(n[r]) > sn.classcap[ist - 1][r]) return out;
1916 const double S = st.nservers;
1917 if (S > 0.0 && std::isfinite(S) && static_cast<double>(stot) > S) return out;
1918
1919 // PAS/OI: the started counts are immaterial to the list encoding.
1920 if (sched == SchedStrategy::PAS || sched == SchedStrategy::OI)
1921 return from_marginal_core(sn, ist, n, phases);
1922
1923 // A Source generates rather than holds: its phase block IS the arrival
1924 // process, seeded in phase one for every class it serves, and the leading
1925 // column is the infinite population the reference marks with Inf.
1926 if (sched == SchedStrategy::EXT || st.nodetype == NodeType::Source) {
1927 // ONE BLOCK PER CLASS, INCLUDING A CLASS THE SOURCE DOES NOT GENERATE:
1928 // `phases` is the width vector, so a disabled arrival contributes one
1929 // always-zero column rather than nothing. That is the reference's row
1930 // (`[Inf 1 0 0 0 0 0]` for a Source generating the first of six
1931 // classes), and a narrower one cannot be decoded by anyone who built it
1932 // from `sn.phasessz` -- see `NetworkStruct::phasessz_of`.
1933 std::vector<std::vector<T>> srv;
1934 for (std::size_t r = 0; r < R; ++r) {
1935 if (phases[r] == 0) continue;
1936 std::vector<T> init(phases[r], num_traits<T>::from_int(0));
1937 // A NON-CARRIER MARK holds an ALL-ZERO column: its arrivals are
1938 // driven by the chain in the carrier's block, so seeding a token
1939 // here would claim a second chain the process does not have.
1940 if (r < sn.classes.size() && std::isinf(sn.classes[r].population) &&
1941 !sn.disabled[ist - 1][r] && sn.markidx_of(ist, r + 1) <= 1)
1942 init[0] = num_traits<T>::from_int(1);
1943 srv = cartesian(srv, std::vector<std::vector<T>>(1, init));
1944 }
1945 if (srv.empty()) srv.push_back(std::vector<T>());
1946 for (std::size_t i = 0; i < srv.size(); ++i) {
1947 std::vector<T> row(1, num_traits<T>::from_double(
1948 std::numeric_limits<double>::infinity()));
1949 row.insert(row.end(), srv[i].begin(), srv[i].end());
1950 out.push_back(row);
1951 }
1952 return out;
1953 }
1954
1955 /** The server block: `cnt[r]` jobs of class r, all of them in phase one. */
1956 const auto phase_one_block = [&](const std::vector<std::size_t>& cnt,
1957 bool* ok) -> std::vector<T> {
1958 std::vector<T> blk;
1959 *ok = true;
1960 for (std::size_t r = 0; r < R; ++r) {
1961 // No service process, yet jobs demanded there: unreachable. An
1962 // empty factor must annihilate the fold, not be absorbed by it.
1963 // The COLUMN is still emitted -- `phases` is the width vector and a
1964 // disabled class holds an always-zero column, as the reference does.
1965 if (sn.phases_of(ist, r + 1) == 0 && cnt[r] > 0) *ok = false;
1966 if (phases[r] == 0) continue;
1967 blk.push_back(num_traits<T>::from_int(static_cast<long>(cnt[r])));
1968 blk.insert(blk.end(), phases[r] - 1, num_traits<T>::from_int(0));
1969 }
1970 return blk;
1971 };
1972 std::size_t srvw = 0;
1973 for (std::size_t r = 0; r < R; ++r) srvw += phases[r];
1974
1975 if (state_detail::buffer_is_per_class_count(sched)) {
1976 // UNORDERED buffer: one waiting COUNT per class ahead of the server
1977 // block. Below the server count every job is in service and the buffer
1978 // is empty, which is the reference's own special case.
1979 const bool all_in_service = std::isfinite(S) && static_cast<double>(ntot) <= S;
1980 std::vector<std::size_t> insrv(R, 0), wait(R, 0);
1981 for (std::size_t r = 0; r < R; ++r) {
1982 insrv[r] = all_in_service ? n[r] : s[r];
1983 wait[r] = n[r] - insrv[r];
1984 }
1985 bool ok = false;
1986 const std::vector<T> blk = phase_one_block(insrv, &ok);
1987 if (!ok) return out;
1988 std::vector<T> row;
1989 for (std::size_t r = 0; r < R; ++r)
1990 row.push_back(num_traits<T>::from_int(static_cast<long>(wait[r])));
1991 row.insert(row.end(), blk.begin(), blk.end());
1992 out.push_back(row);
1993 return out;
1994 }
1995
1996 const bool paired = state_detail::buffer_is_tag_phase_pairs(sched);
1997 if (state_detail::buffer_is_class_tag(sched) || paired) {
1998 // ORDERED buffer: the waiting positions carry class tags, and under the
1999 // preempt family a [class, phase] PAIR per position. The empty buffer
2000 // keeps the width the decoder expects -- one column, or two when
2001 // paired, since an odd-width paired buffer is half a pair and
2002 // `to_marginal` would read every slot shifted.
2003 const std::size_t bw = paired ? 2u : 1u;
2004 if (ntot == 0) {
2005 std::vector<T> row(bw + srvw, num_traits<T>::from_int(0));
2006 out.push_back(row);
2007 return out;
2008 }
2009 std::vector<std::size_t> inbuf;
2010 for (std::size_t r = 0; r < R; ++r)
2011 for (std::size_t j = 0; j < n[r] - s[r]; ++j) inbuf.push_back(r + 1);
2012 // Descending, which is the lexicographic maximum the reference's
2013 // trailing unique/flip leaves standing.
2014 std::sort(inbuf.begin(), inbuf.end(),
2015 [](std::size_t a, std::size_t b) { return a > b; });
2016 if (sched == SchedStrategy::LCFSPRIO) {
2017 // Priority-canonical layout (from_marginal): least urgent level leftmost, the most urgent at the head
2018 // (rightmost), descending class within a level, as MATLAB fromMarginalAndStarted sorts it.
2019 std::stable_sort(inbuf.begin(), inbuf.end(), [&](std::size_t a, std::size_t b) {
2020 return sn.classes[a - 1].prio > sn.classes[b - 1].prio;
2021 });
2022 }
2023
2024 bool ok = false;
2025 const std::vector<T> blk = phase_one_block(s, &ok);
2026 if (!ok) return out;
2027
2028 std::vector<T> row;
2029 if (inbuf.empty()) {
2030 row.assign(bw, num_traits<T>::from_int(0));
2031 } else {
2032 for (std::size_t j = 0; j < inbuf.size(); ++j) {
2033 row.push_back(num_traits<T>::from_int(static_cast<long>(inbuf[j])));
2034 // A preempted job is recorded in its LAST service phase, as the
2035 // reference builds the lexicographic maximum.
2036 if (paired)
2037 row.push_back(num_traits<T>::from_int(
2038 static_cast<long>(phases[inbuf[j] - 1])));
2039 }
2040 }
2041 row.insert(row.end(), blk.begin(), blk.end());
2042 out.push_back(row);
2043 return out;
2044 }
2045
2046 // SHARED SERVER (INF/PS/DPS/GPS/LPS and the priority variants): no buffer,
2047 // and every job present is in a server, so the block holds n and not s.
2048 bool ok = false;
2049 const std::vector<T> blk = phase_one_block(n, &ok);
2050 if (!ok) return out;
2051 out.push_back(blk);
2052 return out;
2053}
2054
2055/**
2056 * `State.fromMarginalAndStarted` with the trailing local-variable block
2057 * appended, i.e. the counterpart of `from_marginal` for a prescribed service
2058 * split. A Join of an FJ-augmented struct carries its per-class counts and no
2059 * split, exactly as in `from_marginal`.
2060 */
2061template <class T>
2062std::vector<std::vector<T>> from_marginal_and_started(const NetworkStruct<T>& sn, std::size_t ist,
2063 const std::vector<std::size_t>& n,
2064 const std::vector<std::size_t>& s,
2065 const std::vector<std::size_t>& phases) {
2066 const std::size_t jnd0 = sn.node_of_station(ist);
2067 if (sn.isfjaugmented && jnd0 != 0 && sn.nodes[jnd0 - 1].nodetype == NodeType::Join) {
2068 // A QUORUM join's row leads with its debt counters, all zero at the start
2069 // (`FjJoinParam::debtwidth`, python fjtag); the counts are the last R.
2070 const std::map<std::size_t, FjJoinParam>::const_iterator jp = sn.fjjoinparam.find(jnd0);
2071 const std::size_t dw = jp == sn.fjjoinparam.end() ? 0 : jp->second.debtwidth;
2072 std::vector<T> row(dw + sn.nclasses, num_traits<T>::from_int(0));
2073 for (std::size_t r = 0; r < sn.nclasses && r < n.size(); ++r)
2074 row[dw + r] = num_traits<T>::from_int(static_cast<long>(n[r]));
2075 return std::vector<std::vector<T>>(1, row);
2076 }
2077 return append_local_vars(sn, ist, from_marginal_and_started_core(sn, ist, n, s, phases), n,
2078 phases);
2079}
2080
2081
2082/**
2083 * Port of `State.fromMarginalAndRunning`: EVERY local state of station `ist`
2084 * holding `n[r]` class-r jobs of which exactly `s[r]` are RUNNING.
2085 *
2086 * WHERE IT SITS BETWEEN ITS TWO SIBLINGS. `from_marginal` enumerates every
2087 * (buffer, server) split a marginal admits; `from_marginal_and_started` takes
2088 * the split as given and returns ONE row, every started job in phase one. This
2089 * one takes the split as given too, but ENUMERATES what the other two leave
2090 * open: every phase assignment of the running jobs and, under an ordered
2091 * buffer, every order of the waiting ones (under the preempt family also every
2092 * phase each waiting job was interrupted in). It is the space the reference's
2093 * `initFromMarginalAndRunning` draws an initial state and its prior from.
2094 *
2095 * WHAT THE SPLIT DOES NOT CONTROL, as in the reference. A shared server
2096 * (INF/PS/DPS/GPS/LPS and the priority variants) serves every job present, so
2097 * the block places `n`, not `s`. A per-class-count buffer at or below its
2098 * server count has every job in service, so it does the same.
2099 *
2100 * WHAT IS NOT APPENDED. The reference returns the bare [buffer | server] rows
2101 * of the discipline arms, with no local-variable block, and so does this port;
2102 * a caller that needs the trailing block appends it, as `from_marginal` does.
2103 *
2104 * NO ROWS, NOT AN ERROR, for a marginal the station cannot hold (class
2105 * capacity), for more running jobs than servers, for `s[r] > n[r]`, and for a
2106 * discipline the reference gives no arm (SJF/LJF, PAS, POLLING): the reference
2107 * returns an empty space for each, and a caller sweeping a lattice relies on
2108 * that.
2109 *
2110 * Rows come out in the reference's order, its trailing `unique` and flip:
2111 * lexicographically DESCENDING, duplicates removed.
2112 *
2113 * @param sn the network struct
2114 * @param ist station index (1-based)
2115 * @param n per-class occupancy
2116 * @param s per-class running count
2117 * @param phases per-class phase counts (the width vector, `phasessz_of`)
2118 */
2119template <class T>
2120std::vector<std::vector<T>> from_marginal_and_running(const NetworkStruct<T>& sn, std::size_t ist,
2121 const std::vector<std::size_t>& n,
2122 const std::vector<std::size_t>& s,
2123 const std::vector<std::size_t>& phases) {
2124 const std::size_t R = sn.nclasses;
2125 if (ist == 0 || ist > sn.stations.size())
2126 throw InputError("from_marginal_and_running: station index " + std::to_string(ist) +
2127 " is out of range");
2128 if (n.size() != R || s.size() != R || phases.size() != R)
2129 throw InputError("from_marginal_and_running: n, s and phases must have one entry per class");
2130 const Station<T>& st = sn.stations[ist - 1];
2131 const SchedStrategy sched = st.sched;
2132 const T zero = num_traits<T>::from_int(0);
2133 std::vector<std::vector<T>> out;
2134
2135 std::size_t ntot = 0, stot = 0, srvw = 0;
2136 for (std::size_t r = 0; r < R; ++r) {
2137 if (s[r] > n[r]) return out; // more running than present: no such state
2138 ntot += n[r];
2139 stot += s[r];
2140 srvw += phases[r];
2141 }
2142 if (ist <= sn.classcap.size())
2143 for (std::size_t r = 0; r < R && r < sn.classcap[ist - 1].size(); ++r)
2144 if (static_cast<double>(n[r]) > sn.classcap[ist - 1][r]) return out;
2145 const double S = st.nservers;
2146 if (S > 0.0 && static_cast<double>(stot) > S) return out;
2147
2148 // The server block of `cnt`: every placement of cnt[r] jobs over the phases
2149 // of class r, folded over the classes. A class with no service process and
2150 // jobs demanded there is unreachable, and its empty factor ends the fold.
2151 const auto server_block = [&](const std::vector<std::size_t>& cnt,
2152 std::vector<std::vector<T>>* blk) -> bool {
2153 blk->clear();
2154 for (std::size_t r = 0; r < R; ++r) {
2155 const std::vector<std::vector<T>> sc = space_closed_single<T>(phases[r], cnt[r]);
2156 if (sc.empty()) {
2157 if (cnt[r] > 0) return false;
2158 continue;
2159 }
2160 *blk = cartesian(*blk, sc);
2161 }
2162 return true;
2163 };
2164 const auto finish = [](std::vector<std::vector<T>> rows) {
2165 const auto greater = [](const std::vector<T>& a, const std::vector<T>& b) {
2166 for (std::size_t i = 0; i < a.size() && i < b.size(); ++i) {
2167 const double av = num_traits<T>::to_double(a[i]);
2168 const double bv = num_traits<T>::to_double(b[i]);
2169 if (av != bv) return av > bv;
2170 }
2171 return a.size() > b.size();
2172 };
2173 const auto same = [](const std::vector<T>& a, const std::vector<T>& b) {
2174 if (a.size() != b.size()) return false;
2175 for (std::size_t i = 0; i < a.size(); ++i)
2176 if (num_traits<T>::to_double(a[i]) != num_traits<T>::to_double(b[i])) return false;
2177 return true;
2178 };
2179 std::sort(rows.begin(), rows.end(), greater);
2180 rows.erase(std::unique(rows.begin(), rows.end(), same), rows.end());
2181 return rows;
2182 };
2183
2184 // A Source generates rather than holds: [Inf | arrival phases], every open
2185 // class it serves seeded in phase one, a non-carrier mark left all-zero.
2186 if (sched == SchedStrategy::EXT || st.nodetype == NodeType::Source) {
2187 std::vector<T> row(1, num_traits<T>::from_double(std::numeric_limits<double>::infinity()));
2188 for (std::size_t r = 0; r < R; ++r) {
2189 if (phases[r] == 0) continue;
2190 std::vector<T> init(phases[r], zero);
2191 if (r < sn.classes.size() && std::isinf(sn.classes[r].population) &&
2192 !sn.disabled[ist - 1][r] && sn.markidx_of(ist, r + 1) <= 1)
2193 init[0] = num_traits<T>::from_int(1);
2194 row.insert(row.end(), init.begin(), init.end());
2195 }
2196 out.push_back(row);
2197 return out;
2198 }
2199
2200 switch (sched) {
2201 case SchedStrategy::INF:
2202 case SchedStrategy::PS:
2203 case SchedStrategy::DPS:
2204 case SchedStrategy::GPS:
2205 case SchedStrategy::PSPRIO:
2206 case SchedStrategy::DPSPRIO:
2207 case SchedStrategy::GPSPRIO:
2208 case SchedStrategy::LPS: {
2209 std::vector<std::vector<T>> blk;
2210 if (!server_block(n, &blk)) return out;
2211 return finish(blk);
2212 }
2213 case SchedStrategy::SIRO:
2214 case SchedStrategy::SEPT:
2215 case SchedStrategy::LEPT:
2216 case SchedStrategy::SRPT:
2217 case SchedStrategy::SRPTPRIO:
2218 case SchedStrategy::SETF:
2219 case SchedStrategy::FSP: {
2220 // Unordered buffer: one waiting count per class ahead of the servers.
2221 const bool all_in_service = static_cast<double>(ntot) <= S;
2222 std::vector<std::vector<T>> blk;
2223 if (!server_block(all_in_service ? n : s, &blk)) return out;
2224 std::vector<T> buf(R, zero);
2225 if (!all_in_service)
2226 for (std::size_t r = 0; r < R; ++r)
2227 buf[r] = num_traits<T>::from_int(static_cast<long>(n[r] - s[r]));
2228 for (std::size_t i = 0; i < blk.size(); ++i) {
2229 std::vector<T> row = buf;
2230 row.insert(row.end(), blk[i].begin(), blk[i].end());
2231 out.push_back(row);
2232 }
2233 return finish(out);
2234 }
2235 default:
2236 break;
2237 }
2238
2239 const bool paired = state_detail::buffer_is_tag_phase_pairs(sched) || sched == SchedStrategy::EDF;
2240 if (!(paired || state_detail::buffer_is_class_tag(sched) || sched == SchedStrategy::EDD))
2241 return out; // SJF/LJF, PAS, POLLING, ...: the reference has no arm
2242
2243 // ORDERED BUFFER. An empty station keeps the width the decoder expects: one
2244 // buffer column, two under the preempt family's [class, phase] pairs.
2245 if (ntot == 0) {
2246 out.push_back(std::vector<T>((paired ? 2u : 1u) + srvw, zero));
2247 return out;
2248 }
2249 std::vector<std::vector<T>> kstate;
2250 if (!server_block(s, &kstate)) return out;
2251
2252 std::vector<std::size_t> w(R, 0), inbuf;
2253 for (std::size_t r = 0; r < R; ++r) {
2254 w[r] = n[r] - s[r];
2255 inbuf.insert(inbuf.end(), w[r], r + 1);
2256 }
2257 // Every order of the waiting jobs. LCFSPRIO keeps only the PRIORITY-
2258 // CANONICAL ones (`State.priorityCanonicalBuffers`): grouped by level, least
2259 // urgent leftmost, only the order within a level enumerated. With nobody
2260 // waiting the buffer is the single empty slot.
2261 std::vector<std::vector<std::size_t>> bufs;
2262 if (inbuf.empty()) {
2263 bufs.push_back(std::vector<std::size_t>(1, 0));
2264 } else if (sched == SchedStrategy::LCFSPRIO) {
2265 std::vector<int> levels;
2266 for (std::size_t r = 0; r < R; ++r)
2267 if (w[r] > 0) levels.push_back(sn.classes[r].prio);
2268 std::sort(levels.begin(), levels.end(), std::greater<int>());
2269 levels.erase(std::unique(levels.begin(), levels.end()), levels.end());
2270 bufs.push_back(std::vector<std::size_t>());
2271 for (int lev : levels) {
2272 std::vector<std::size_t> grp;
2273 for (std::size_t r = 0; r < R; ++r)
2274 if (sn.classes[r].prio == lev) grp.insert(grp.end(), w[r], r + 1);
2275 std::vector<std::vector<std::size_t>> next;
2276 do {
2277 for (const std::vector<std::size_t>& b : bufs) {
2278 std::vector<std::size_t> b2 = b;
2279 b2.insert(b2.end(), grp.begin(), grp.end());
2280 next.push_back(b2);
2281 }
2282 } while (std::next_permutation(grp.begin(), grp.end()));
2283 bufs.swap(next);
2284 }
2285 } else {
2286 std::vector<std::size_t> p = inbuf; // ascending by construction
2287 do {
2288 bufs.push_back(p);
2289 } while (std::next_permutation(p.begin(), p.end()));
2290 }
2291
2292 for (const std::vector<std::size_t>& b : bufs) {
2293 std::vector<std::vector<T>> brows(1, std::vector<T>());
2294 for (std::size_t j = 0; j < b.size(); ++j) {
2295 std::vector<std::vector<T>> next;
2296 const std::size_t np = (paired && b[j] > 0) ? phases[b[j] - 1] : 1;
2297 for (const std::vector<T>& br : brows)
2298 for (std::size_t p = 1; p <= np; ++p) {
2299 std::vector<T> row = br;
2300 row.push_back(num_traits<T>::from_int(static_cast<long>(b[j])));
2301 // A waiting job under the preempt family carries the phase
2302 // it was interrupted in; an empty slot carries phase 0.
2303 if (paired)
2304 row.push_back(num_traits<T>::from_int(b[j] > 0 ? static_cast<long>(p) : 0));
2305 next.push_back(row);
2306 }
2307 brows.swap(next);
2308 }
2309 for (const std::vector<T>& br : brows) {
2310 if (kstate.empty()) out.push_back(br);
2311 for (const std::vector<T>& ks : kstate) {
2312 std::vector<T> row = br;
2313 row.insert(row.end(), ks.begin(), ks.end());
2314 out.push_back(row);
2315 }
2316 }
2317 }
2318 return finish(out);
2319}
2320
2321/**
2322 * Port of `State.fromMarginal` at its OWN signature: the reference indexes by
2323 * NODE, not by station, and derives the station internally. That distinction is
2324 * load-bearing, not cosmetic -- a Transition is stateful but is NOT a station,
2325 * so it carries no station index and the station-indexed overload can never
2326 * reach it. Routing every caller through here is what makes the Transition
2327 * branch below live rather than dead code.
2328 *
2329 * A node that is not stateful holds no jobs and contributes no local state.
2330 */
2331template <class T>
2332std::vector<std::vector<T>> from_marginal_node(const NetworkStruct<T>& sn, std::size_t ind,
2333 const std::vector<std::size_t>& n,
2334 const std::vector<std::size_t>& phases) {
2335 if (ind == 0 || ind > sn.nodes.size())
2336 throw InputError("from_marginal_node: node index " + std::to_string(ind) +
2337 " is out of range");
2338 const NodeDef& nd = sn.nodes[ind - 1];
2339 if (nd.station != 0) return from_marginal(sn, nd.station, n, phases);
2340 if (!nd.stateful) return std::vector<std::vector<T>>();
2341
2342 const std::size_t R = sn.nclasses;
2343 if (n.size() != R)
2344 throw InputError("from_marginal_node: n must have one entry per class");
2345
2346 if (nd.nodetype == NodeType::Transition) {
2347 // PER-MODE state, not per-class: [free servers | firing phases | fired].
2348 // The reference emits the all-idle row -- every mode's servers free, no
2349 // firing in progress -- and lets the event handlers walk from there, so
2350 // the marginal n plays no part. An infinite server count is clamped to
2351 // MaxInt because the row is a COUNT vector and Inf is not a count.
2352 const typename std::map<std::size_t, TransitionParam<T> >::const_iterator it =
2353 sn.transparam.find(ind);
2354 if (it == sn.transparam.end())
2355 throw InputError(
2356 "from_marginal_node: transition node has no TransitionParam; build it with "
2357 "add_transition");
2358 const TransitionParam<T>& tp = it->second;
2359 std::vector<T> row;
2360 for (std::size_t mm = 0; mm < tp.nmodes; ++mm) {
2361 const double sv = mm < tp.nmodeservers.size() ? tp.nmodeservers[mm] : 1.0;
2362 row.push_back(num_traits<T>::from_double(
2363 std::isfinite(sv) ? sv : static_cast<double>(GlobalConstants::MaxInt)));
2364 }
2365 std::size_t fph = 0;
2366 for (std::size_t mm = 0; mm < tp.nmodes; ++mm)
2367 fph += mm < tp.firingphases.size() && tp.firingphases[mm] > 0 ? tp.firingphases[mm] : 1;
2368 row.insert(row.end(), fph, num_traits<T>::from_int(0));
2369 row.insert(row.end(), tp.nmodes, num_traits<T>::from_int(0));
2370 return std::vector<std::vector<T> >{row};
2371 }
2372
2373 // A CACHE HOLDS ONE READING JOB, which is what makes the read a decision
2374 // rather than a queue: `spaceGeneratorNodes` caps every class there at 1 and
2375 // the node at 1 job in total. Without the cap the lattice admits a cache
2376 // holding two reads, and since `after_event_cache` fires a READ only on a
2377 // node holding exactly one job, that state is ABSORBING -- on an open model
2378 // the whole stationary mass ends up in it and every cache rate reads zero.
2379 //
2380 // A completing fetch is the one exception: it releases every merged
2381 // secondary request into the hit class in ONE immediate transition, so the
2382 // hit classes momentarily hold up to `max_pending_retrieval` extra jobs.
2383 if (nd.nodetype == NodeType::Cache) {
2384 const typename std::map<std::size_t, CacheParam<T> >::const_iterator cc =
2385 sn.nodeparam.find(ind);
2386 if (cc != sn.nodeparam.end()) {
2387 const std::size_t pend =
2388 cc->second.retrieval_capacity > 0 && cc->second.max_pending_retrieval > 0
2389 ? static_cast<std::size_t>(cc->second.max_pending_retrieval)
2390 : 0;
2391 std::size_t tot = 0;
2392 for (std::size_t r = 0; r < R; ++r) {
2393 bool is_hit = false;
2394 for (std::size_t u = 0; u < cc->second.hitclass.size(); ++u)
2395 if (cc->second.hitclass[u] == r + 1) is_hit = true;
2396 if (n[r] > (is_hit ? 1 + pend : 1)) return std::vector<std::vector<T> >();
2397 tot += n[r];
2398 }
2399 if (tot > 1 + pend) return std::vector<std::vector<T> >();
2400 }
2401 }
2402
2403 // Any other stateful non-station (a Cache, a stateful ClassSwitch): the
2404 // reference folds `spaceClosedSingle(1, n(r))` per class, i.e. one column
2405 // per class holding its count, with no phase and no buffer.
2406 std::vector<std::vector<T> > acc;
2407 for (std::size_t r = 0; r < R; ++r) {
2408 const std::vector<std::vector<T> > sr = space_closed_single<T>(1, n[r]);
2409 if (sr.empty() && n[r] > 0) return std::vector<std::vector<T> >();
2410 acc = cartesian(acc, sr);
2411 }
2412
2413 // A DISPATCHER CARRIES ITS POINTER IN THE STATE, for the same reason a cache
2414 // carries its contents: which link the next job takes is not derivable from
2415 // the marginal. RROBIN enumerates its outlinks and WRROBIN the positions of
2416 // its weighted cycle, exactly as `sub_routevars` does, and the columns sit
2417 // in CLASS ORDER right after the per-class counts, where `rr_var_slot` reads
2418 // them. Emitting the node one column narrower than `nvars_of` declares makes
2419 // every successor a state the space does not contain, so the node becomes
2420 // ABSORBING and the whole chain stalls with the jobs sitting in it.
2421 {
2422 std::vector<std::vector<T> > ptrsets(1, std::vector<T>());
2423 bool any = false;
2424 for (std::size_t r = 1; r <= R; ++r) {
2425 if (sn.rr_var_slot(ind, r) == 0) continue;
2426 any = true;
2427 std::vector<T> vals;
2428 if (sn.nodes[ind - 1].routing[r - 1] == RoutingStrategy::RROBIN) {
2429 const std::vector<std::size_t> ol = sn.rr_outlinks(ind, r);
2430 for (std::size_t u = 0; u < ol.size(); ++u)
2431 vals.push_back(num_traits<T>::from_int(static_cast<long>(ol[u])));
2432 } else {
2433 const std::vector<std::size_t> cy = sn.rr_weighted_outlinks(ind, r);
2434 for (std::size_t u = 0; u < cy.size(); ++u)
2435 vals.push_back(num_traits<T>::from_int(static_cast<long>(u + 1)));
2436 }
2437 if (vals.empty()) vals.push_back(num_traits<T>::from_int(0));
2438 std::vector<std::vector<T> > grown;
2439 for (std::size_t g = 0; g < ptrsets.size(); ++g)
2440 for (std::size_t v = 0; v < vals.size(); ++v) {
2441 std::vector<T> row = ptrsets[g];
2442 row.push_back(vals[v]);
2443 grown.push_back(row);
2444 }
2445 ptrsets.swap(grown);
2446 }
2447 if (any) acc = cartesian(acc, ptrsets);
2448 }
2449
2450 // A CACHE CARRIES ITS CONTENTS IN THE STATE, and they are not derivable
2451 // from any marginal: the row is [per-class counts | contents | occupancy],
2452 // exactly as `after_event_cache` slices it. Enumerating only the counts
2453 // left the contents region absent, so every READ landed on a state one
2454 // block wider than anything enumerated and the space came out EMPTY.
2455 //
2456 // A contents slot holds an ITEM INDEX and an item sits in at most one slot --
2457 // a cache holding two copies of one item is not a state the replacement
2458 // policies can reach or leave.
2459 //
2460 // THE ENUMERATED CACHE IS FULL, which is what `State.spaceCache` builds:
2461 // every ordered placement of `tcc` DISTINCT items, with no empty slot. Under
2462 // every replacement policy a cache that has once been filled never empties
2463 // again, so a partly empty configuration is transient and enumerating it
2464 // only spreads stationary mass over states the model leaves for good. It is
2465 // load-bearing beyond tidiness for a retrieval cache: block A may be set
2466 // only for an item that is NOT cached, and the count of such items is the
2467 // retrieval-system capacity `nitems - tcc`, which is a number only if the
2468 // cached set is full. A cache with more slots than items can never fill, so
2469 // the empty slot survives there.
2470 if (nd.nodetype == NodeType::Cache) {
2471 const typename std::map<std::size_t, CacheParam<T> >::const_iterator ci =
2472 sn.nodeparam.find(ind);
2473 if (ci == sn.nodeparam.end()) return acc;
2474 const CacheParam<T>& cp = ci->second;
2475 std::size_t tcc = 0;
2476 for (std::size_t u = 0; u < cp.itemcap.size(); ++u)
2477 if (cp.itemcap[u] > 0) tcc += static_cast<std::size_t>(cp.itemcap[u]);
2478
2479 const std::size_t first_item = tcc <= cp.nitems ? 1 : 0;
2480 std::vector<std::vector<T> > contents(1, std::vector<T>());
2481 for (std::size_t slot = 0; slot < tcc; ++slot) {
2482 std::vector<std::vector<T> > grown;
2483 for (std::size_t c = 0; c < contents.size(); ++c)
2484 for (std::size_t item = first_item; item <= cp.nitems; ++item) {
2485 bool dup = false;
2486 if (item > 0)
2487 for (std::size_t j = 0; j < contents[c].size(); ++j)
2488 if (num_traits<T>::to_double(contents[c][j]) ==
2489 static_cast<double>(item)) { dup = true; break; }
2490 if (dup) continue;
2491 std::vector<T> row = contents[c];
2492 row.push_back(num_traits<T>::from_int(static_cast<long>(item)));
2493 grown.push_back(row);
2494 }
2495 contents.swap(grown);
2496 }
2497 // Block A, the delayed-hit occupancy bitmap: one bit per item, set while
2498 // a retrieval for it is in flight.
2499 if (cp.retrieval_capacity > 0)
2500 for (std::size_t i = 0; i < cp.nitems; ++i) {
2501 std::vector<std::vector<T> > grown;
2502 for (std::size_t c = 0; c < contents.size(); ++c)
2503 for (int b = 0; b <= 1; ++b) {
2504 std::vector<T> row = contents[c];
2505 row.push_back(num_traits<T>::from_int(b));
2506 grown.push_back(row);
2507 }
2508 contents.swap(grown);
2509 }
2510 // Block B, the merged secondary requests: one count per retrieval class,
2511 // nonzero only where that class's item is in flight (block A is set) and
2512 // summing to at most the declared truncation level. `State.spaceCache`
2513 // enumerates the same compositions; -1 means the caller is walking a
2514 // sample path rather than enumerating, so no pending state is generated.
2515 if (cp.retrieval_capacity > 0) {
2516 std::vector<std::size_t> rcl, rci, rco;
2517 cache_retrieval_class_map(cp, rcl, rci, rco);
2518 if (!rcl.empty()) {
2519 const long maxpend =
2521 std::vector<std::vector<T> > grown;
2522 for (std::size_t c = 0; c < contents.size(); ++c) {
2523 // which slots may carry a count in THIS row: the ones whose
2524 // item is currently being fetched
2525 std::vector<std::size_t> active;
2526 for (std::size_t j = 0; j < rcl.size(); ++j)
2527 if (num_traits<T>::to_double(contents[c][tcc + rci[j] - 1]) != 0)
2528 active.push_back(j);
2529 std::vector<std::vector<long> > pend(1, std::vector<long>(rcl.size(), 0));
2530 for (std::size_t a = 0; a < active.size(); ++a) {
2531 std::vector<std::vector<long> > next;
2532 for (std::size_t q = 0; q < pend.size(); ++q) {
2533 long used = 0;
2534 for (std::size_t j = 0; j < rcl.size(); ++j) used += pend[q][j];
2535 for (long v = 0; v + used <= maxpend; ++v) {
2536 std::vector<long> row = pend[q];
2537 row[active[a]] = v;
2538 next.push_back(row);
2539 }
2540 }
2541 pend.swap(next);
2542 }
2543 for (std::size_t q = 0; q < pend.size(); ++q) {
2544 std::vector<T> row = contents[c];
2545 for (std::size_t j = 0; j < rcl.size(); ++j)
2546 row.push_back(num_traits<T>::from_int(pend[q][j]));
2547 grown.push_back(row);
2548 }
2549 }
2550 contents.swap(grown);
2551 }
2552 }
2553 std::vector<std::vector<T> > joint = cartesian(acc, contents);
2554 if (cp.retrieval_capacity <= 0) return joint;
2555
2556 // THE LOCALLY INVALID ROWS OF A RETRIEVAL CACHE, `spaceGeneratorNodes.m`
2557 // lines 206-280. The cartesian product above enumerates combinations the
2558 // dynamics can never reach, and they are not harmless: a row holding a
2559 // returning retrieval job BESIDE another job disables the READ (which
2560 // needs the node to hold exactly one) while leaving the departure
2561 // enabled, so the fetch bounces back to its queue without completing.
2562 // That inflated the retrieval flow by 20% on retrieval_simple while the
2563 // hit and miss shares, being ratios, stayed exactly right -- the kind of
2564 // defect only a flow identity catches.
2565 std::vector<bool> is_hit(R, false), is_miss(R, false);
2566 for (std::size_t u = 0; u < cp.hitclass.size(); ++u)
2567 if (cp.hitclass[u] >= 1 && cp.hitclass[u] <= R) is_hit[cp.hitclass[u] - 1] = true;
2568 for (std::size_t u = 0; u < cp.missclass.size(); ++u)
2569 if (cp.missclass[u] >= 1 && cp.missclass[u] <= R) is_miss[cp.missclass[u] - 1] = true;
2570 const long maxpend = cp.max_pending_retrieval > 0 ? cp.max_pending_retrieval : 0;
2571 std::vector<std::vector<T> > kept;
2572 for (std::size_t row = 0; row < joint.size(); ++row) {
2573 const std::vector<T>& st = joint[row];
2574 double tot = 0, other = 0, miss = 0;
2575 for (std::size_t r = 0; r < R; ++r) {
2576 const double v = num_traits<T>::to_double(st[r]);
2577 tot += v;
2578 if (is_miss[r]) miss += v;
2579 else if (!is_hit[r]) other += v;
2580 }
2581 // ONE JOB READS AT A TIME. The single exception is the state a
2582 // completing fetch lands in: the miss-class job that was the fetch,
2583 // together with the delayed hits it released in the same transition.
2584 if (!(tot <= 1 || (other == 0 && miss <= 1 && tot <= 1 + maxpend))) continue;
2585 bool ok = true;
2586 long nbits = 0;
2587 for (std::size_t i = 0; i < cp.nitems && ok; ++i) {
2588 if (num_traits<T>::to_double(st[R + tcc + i]) == 0) continue;
2589 ++nbits;
2590 // An item cannot be cached and in flight at the same time.
2591 for (std::size_t c = 0; c < tcc; ++c)
2592 if (static_cast<std::size_t>(num_traits<T>::to_double(st[R + c])) == i + 1)
2593 ok = false;
2594 }
2595 if (!ok || nbits > cp.retrieval_capacity) continue;
2596 kept.push_back(st);
2597 }
2598 return kept;
2599 }
2600 return acc;
2601}
2602
2603/**
2604 * Port of `State.fromMarginalAndStarted` at its OWN signature, which indexes by
2605 * NODE rather than by station, mirroring `from_marginal_node`.
2606 *
2607 * A Petri-net element is REFUSED BY NAME, as the reference refuses it: a
2608 * Transition's local state is per MODE, not per class, and a Place holds
2609 * tokens, so neither has a notion of a started job to prescribe. A node that is
2610 * not stateful holds no jobs and contributes no local state.
2611 */
2612template <class T>
2613std::vector<std::vector<T>> from_marginal_node_and_started(
2614 const NetworkStruct<T>& sn, std::size_t ind, const std::vector<std::size_t>& n,
2615 const std::vector<std::size_t>& s, const std::vector<std::size_t>& phases) {
2616 if (ind == 0 || ind > sn.nodes.size())
2617 throw InputError("from_marginal_node_and_started: node index " + std::to_string(ind) +
2618 " is out of range");
2619 const NodeDef& nd = sn.nodes[ind - 1];
2620 if (nd.nodetype == NodeType::Transition || nd.nodetype == NodeType::Place)
2621 throw UnsupportedError(ErrorKind{"Place"},
2622 "from_marginal_node_and_started cannot be used on Petri net elements");
2623 if (nd.station != 0) return from_marginal_and_started(sn, nd.station, n, s, phases);
2624 if (!nd.stateful) return std::vector<std::vector<T>>();
2625 // Every other stateful non-station carries no service split, so the
2626 // marginal builder answers it: a Cache holds its reading job and its
2627 // contents, a stateful ClassSwitch one count per class.
2628 return from_marginal_node(sn, ind, n, phases);
2629}
2630
2631/**
2632 * Port of `State.fromMarginalAndRunning` at its OWN signature, which indexes by
2633 * NODE, as `from_marginal_node_and_started` does. The reference resolves the
2634 * node to its station first, so a node that is not a station has no running
2635 * split to prescribe and is refused, and a Petri-net element by name.
2636 */
2637template <class T>
2638std::vector<std::vector<T>> from_marginal_node_and_running(
2639 const NetworkStruct<T>& sn, std::size_t ind, const std::vector<std::size_t>& n,
2640 const std::vector<std::size_t>& s, const std::vector<std::size_t>& phases) {
2641 if (ind == 0 || ind > sn.nodes.size())
2642 throw InputError("from_marginal_node_and_running: node index " + std::to_string(ind) +
2643 " is out of range");
2644 const NodeDef& nd = sn.nodes[ind - 1];
2645 if (nd.nodetype == NodeType::Transition || nd.nodetype == NodeType::Place)
2646 throw UnsupportedError(ErrorKind{"Place"},
2647 "from_marginal_node_and_running cannot be used on Petri net elements");
2648 if (nd.station == 0)
2649 throw InputError("from_marginal_node_and_running: node " + std::to_string(ind) +
2650 " is not a station");
2651 return from_marginal_and_running(sn, nd.station, n, s, phases);
2652}
2653
2654/**
2655 * Port of `State.fromMarg`: the state space with a given TOTAL queue length.
2656 *
2657 * This is the class-summed counterpart of `from_marginal_node`. Where that one
2658 * fixes how many jobs of EACH class the node holds, this one fixes only how
2659 * many it holds ALTOGETHER and returns the union over every class split of
2660 * `ntot` the node can hold.
2661 *
2662 * A class DISABLED at the station has `classcap` 0 and is excluded from the
2663 * split enumeration up front rather than after the fact. Asking
2664 * `from_marginal_node` for a job of such a class yields an EMPTY local space,
2665 * and `space_closed_single(0,1)` returning no rows empties the whole cartesian
2666 * product, so the job would silently disappear -- the trap documented at
2667 * `space_closed_single` above.
2668 *
2669 * `ntot == 0` has the single empty split, which `from_marginal_node` answers
2670 * with the per-discipline empty state; the width is NOT re-derived here.
2671 *
2672 * The buffer is RIGHT-aligned, so sub-spaces of different width are padded on
2673 * the LEFT before they are stacked, exactly as the reference does for the
2674 * reply-block sub-spaces. Rows are then uniqued and reversed, which puts the
2675 * empty state first and the states with jobs in phase 1 earlier.
2676 *
2677 * The twin over BOTH totals is `from_marg_node_started` below.
2678 */
2679template <class T>
2680std::vector<std::vector<T>> from_marg_node(const NetworkStruct<T>& sn, std::size_t ind,
2681 std::size_t ntot,
2682 const std::vector<std::size_t>& phases) {
2683 if (ind == 0 || ind > sn.nodes.size())
2684 throw InputError("from_marg_node: node index " + std::to_string(ind) + " is out of range");
2685 const NodeDef& nd = sn.nodes[ind - 1];
2686 const std::size_t R = sn.nclasses;
2687
2688 // Per-class capacity of the node, unbounded when it is not a station.
2689 std::vector<double> ccap(R, std::numeric_limits<double>::infinity());
2690 if (nd.station != 0 && sn.classcap.size() >= nd.station) {
2691 const std::vector<double>& row = sn.classcap[nd.station - 1];
2692 for (std::size_t r = 0; r < R && r < row.size(); ++r) ccap[r] = row[r];
2693 }
2694
2695 std::vector<std::vector<int>> nset;
2696 if (ntot == 0) {
2697 nset.push_back(std::vector<int>(R, 0));
2698 } else {
2699 const std::vector<std::vector<int>> all =
2700 pfqn::multichoose_rows(static_cast<int>(R), static_cast<int>(ntot));
2701 for (std::size_t j = 0; j < all.size(); ++j) {
2702 bool ok = true;
2703 for (std::size_t r = 0; r < R && ok; ++r)
2704 if (static_cast<double>(all[j][r]) > ccap[r]) ok = false;
2705 if (ok) nset.push_back(all[j]);
2706 }
2707 }
2708
2709 std::vector<std::vector<T>> space;
2710 std::size_t maxw = 0;
2711 std::vector<std::vector<std::vector<T>>> subspaces;
2712 for (std::size_t j = 0; j < nset.size(); ++j) {
2713 std::vector<std::size_t> nj(R, 0);
2714 for (std::size_t r = 0; r < R; ++r) nj[r] = static_cast<std::size_t>(nset[j][r]);
2715 const std::vector<std::vector<T>> sj = from_marginal_node(sn, ind, nj, phases);
2716 if (sj.empty()) continue;
2717 for (std::size_t a = 0; a < sj.size(); ++a) maxw = std::max(maxw, sj[a].size());
2718 subspaces.push_back(sj);
2719 }
2720 for (std::size_t j = 0; j < subspaces.size(); ++j)
2721 for (std::size_t a = 0; a < subspaces[j].size(); ++a) {
2722 std::vector<T> row = subspaces[j][a];
2723 if (row.size() < maxw)
2724 row.insert(row.begin(), maxw - row.size(), num_traits<T>::from_int(0));
2725 space.push_back(row);
2726 }
2727 if (space.empty()) return space;
2728
2729 std::sort(space.begin(), space.end());
2730 space.erase(std::unique(space.begin(), space.end()), space.end());
2731 std::reverse(space.begin(), space.end());
2732 return space;
2733}
2734
2735namespace state_detail {
2736
2737/**
2738 * Port of `multichoosecon.m`: the ways to draw `S` units from the availability
2739 * vector `n`.
2740 *
2741 * Unlike `multichoose_rows`, the count drawn from category r is capped by
2742 * `n[r]`, so the enumeration never proposes a job of a class the station does
2743 * not hold -- which is what keeps `from_marg_node_started` from asking the
2744 * per-class builder for a state that cannot exist.
2745 */
2746inline std::vector<std::vector<std::size_t> > multichoosecon(const std::vector<std::size_t>& n,
2747 std::size_t S) {
2748 const std::size_t R = n.size();
2749 std::vector<std::vector<std::size_t> > out;
2750 if (R == 0) return out;
2751 if (S == 0) {
2752 out.push_back(std::vector<std::size_t>(R, 0));
2753 return out;
2754 }
2755 if (S == 1) {
2756 for (std::size_t i = 0; i < R; ++i)
2757 if (n[i] > 0) {
2758 std::vector<std::size_t> row(R, 0);
2759 row[i] = 1;
2760 out.push_back(row);
2761 }
2762 return out;
2763 }
2764 for (std::size_t i = 0; i < R; ++i) {
2765 if (n[i] == 0) continue;
2766 std::vector<std::size_t> n1 = n;
2767 --n1[i];
2768 const std::vector<std::vector<std::size_t> > tail = multichoosecon(n1, S - 1);
2769 for (std::size_t k = 0; k < tail.size(); ++k) {
2770 std::vector<std::size_t> row = tail[k];
2771 ++row[i];
2772 out.push_back(row);
2773 }
2774 }
2775 return out;
2776}
2777
2778} // namespace state_detail
2779
2780/**
2781 * Port of `State.fromMargAndStarted`: the states with a given TOTAL queue
2782 * length AND a given TOTAL number of started jobs.
2783 *
2784 * Where `from_marginal_node_and_started` takes one per-class occupancy and one
2785 * per-class started vector and builds ONE row, this takes only the two totals
2786 * and returns the union of that row over every pair consistent with them:
2787 * `sum(n) == ntot`, `sum(s) == stot`, and `s <= n` elementwise.
2788 *
2789 * The started counts are drawn with `multichoosecon` from the jobs actually
2790 * present rather than from `multichoose_rows` over all classes, so a split is
2791 * never proposed that puts more of a class in service than the station holds.
2792 * Classes disabled at the station are excluded through `classcap` for the
2793 * reason documented on `from_marg_node`: an empty local space is ABSORBED by
2794 * the cartesian product instead of annihilating it, so the job would silently
2795 * disappear rather than the state being rejected.
2796 *
2797 * Widths are unified on the LEFT and the rows uniqued and reversed, exactly as
2798 * `from_marg_node` does, since the buffer is right-aligned.
2799 */
2800template <class T>
2801std::vector<std::vector<T>> from_marg_node_started(const NetworkStruct<T>& sn, std::size_t ind,
2802 std::size_t ntot, std::size_t stot,
2803 const std::vector<std::size_t>& phases) {
2804 if (ind == 0 || ind > sn.nodes.size())
2805 throw InputError("from_marg_node_started: node index " + std::to_string(ind) +
2806 " is out of range");
2807 std::vector<std::vector<T>> space;
2808 if (stot > ntot) return space;
2809
2810 const NodeDef& nd = sn.nodes[ind - 1];
2811 const std::size_t R = sn.nclasses;
2812
2813 std::vector<double> ccap(R, std::numeric_limits<double>::infinity());
2814 if (nd.station != 0 && sn.classcap.size() >= nd.station) {
2815 const std::vector<double>& row = sn.classcap[nd.station - 1];
2816 for (std::size_t r = 0; r < R && r < row.size(); ++r) ccap[r] = row[r];
2817 }
2818
2819 std::vector<std::vector<int>> nset;
2820 if (ntot == 0) {
2821 nset.push_back(std::vector<int>(R, 0));
2822 } else {
2823 const std::vector<std::vector<int>> all =
2824 pfqn::multichoose_rows(static_cast<int>(R), static_cast<int>(ntot));
2825 for (std::size_t j = 0; j < all.size(); ++j) {
2826 bool ok = true;
2827 for (std::size_t r = 0; r < R && ok; ++r)
2828 if (static_cast<double>(all[j][r]) > ccap[r]) ok = false;
2829 if (ok) nset.push_back(all[j]);
2830 }
2831 }
2832
2833 std::size_t maxw = 0;
2834 std::vector<std::vector<std::vector<T>>> subspaces;
2835 for (std::size_t j = 0; j < nset.size(); ++j) {
2836 std::vector<std::size_t> nj(R, 0);
2837 for (std::size_t r = 0; r < R; ++r) nj[r] = static_cast<std::size_t>(nset[j][r]);
2838 const std::vector<std::vector<std::size_t> > sset =
2839 state_detail::multichoosecon(nj, stot);
2840 for (std::size_t k = 0; k < sset.size(); ++k) {
2841 const std::vector<std::vector<T>> sjk =
2842 from_marginal_node_and_started(sn, ind, nj, sset[k], phases);
2843 if (sjk.empty()) continue;
2844 for (std::size_t a = 0; a < sjk.size(); ++a) maxw = std::max(maxw, sjk[a].size());
2845 subspaces.push_back(sjk);
2846 }
2847 }
2848 for (std::size_t j = 0; j < subspaces.size(); ++j)
2849 for (std::size_t a = 0; a < subspaces[j].size(); ++a) {
2850 std::vector<T> row = subspaces[j][a];
2851 if (row.size() < maxw)
2852 row.insert(row.begin(), maxw - row.size(), num_traits<T>::from_int(0));
2853 space.push_back(row);
2854 }
2855 if (space.empty()) return space;
2856
2857 std::sort(space.begin(), space.end());
2858 space.erase(std::unique(space.begin(), space.end()), space.end());
2859 std::reverse(space.begin(), space.end());
2860 return space;
2861}
2862
2863/**
2864 * The FIRST row `from_marginal_node` emits, BUILT rather than enumerated.
2865 *
2866 * Every caller that seeds a sample path takes row 0 and discards the rest, and
2867 * for a Cache the rest is the ordered placement of distinct items into its
2868 * slots -- (nitems+1)*nitems*(nitems-1)*... rows. Materializing that to read one
2869 * row's contents is what took SolverSSA on tut06_cache_lru_zipf (1000 items, 50
2870 * slots) to 12 GB and an OOM kill of the whole host; the peak is invariant in
2871 * `samples` precisely because the walk itself is lazy and only the SEED costs
2872 * this. A simulator must not pay an exact solver's enumeration to start.
2873 *
2874 * Row 0 holds items 1..tcc in slot order, by construction and not by choice:
2875 * `cartesian` emits `a[0] ++ b[0]`, the contents loop offers the lowest
2876 * admissible item first at every slot and its duplicate test rejects the ones
2877 * already placed, and the delayed-hit occupancy bits start clear. So the row is
2878 * the per-class counts, the first `tcc` items, then zeros -- bit for bit what
2879 * the enumeration returned, which is what lets the CTMC find its declared
2880 * initial state in the space. A cache with more slots than items cannot fill
2881 * and starts empty, as the enumeration also has it. Every other node kind
2882 * delegates, its first row already being cheap.
2883 *
2884 * @return false when the node admits no state at all, as an empty return does
2885 */
2886template <class T>
2887bool from_marginal_node_first(const NetworkStruct<T>& sn, std::size_t ind,
2888 const std::vector<std::size_t>& n,
2889 const std::vector<std::size_t>& phases, std::vector<T>& out) {
2890 if (ind == 0 || ind > sn.nodes.size())
2891 throw InputError("from_marginal_node_first: node index " + std::to_string(ind) +
2892 " is out of range");
2893 const NodeDef& nd = sn.nodes[ind - 1];
2894 if (nd.station != 0 || !nd.stateful || nd.nodetype != NodeType::Cache) {
2895 const std::vector<std::vector<T> > rows = from_marginal_node(sn, ind, n, phases);
2896 if (rows.empty()) return false;
2897 out = rows[0];
2898 return true;
2899 }
2900
2901 const std::size_t R = sn.nclasses;
2902 if (n.size() != R)
2903 throw InputError("from_marginal_node_first: n must have one entry per class");
2904 out.clear();
2905 for (std::size_t r = 0; r < R; ++r) {
2906 const std::vector<std::vector<T> > sr = space_closed_single<T>(1, n[r]);
2907 // an absent placement drops the class's column, exactly as the fold does
2908 if (sr.empty()) {
2909 if (n[r] > 0) return false;
2910 continue;
2911 }
2912 out.insert(out.end(), sr[0].begin(), sr[0].end());
2913 }
2914
2915 const typename std::map<std::size_t, CacheParam<T> >::const_iterator ci =
2916 sn.nodeparam.find(ind);
2917 if (ci == sn.nodeparam.end()) return true;
2918 const CacheParam<T>& cp = ci->second;
2919 std::size_t tcc = 0;
2920 for (std::size_t u = 0; u < cp.itemcap.size(); ++u)
2921 if (cp.itemcap[u] > 0) tcc += static_cast<std::size_t>(cp.itemcap[u]);
2922 for (std::size_t slot = 0; slot < tcc; ++slot)
2923 out.push_back(num_traits<T>::from_int(
2924 tcc <= cp.nitems ? static_cast<long>(slot + 1) : 0L));
2925 if (cp.retrieval_capacity > 0) {
2926 out.insert(out.end(), cp.nitems, num_traits<T>::from_int(0));
2927 std::vector<std::size_t> rcl, rci, rco;
2928 cache_retrieval_class_map(cp, rcl, rci, rco);
2929 out.insert(out.end(), rcl.size(), num_traits<T>::from_int(0));
2930 }
2931 return true;
2932}
2933
2934/**
2935 * Port of `State.spaceClosedMulti`: how N[r] class-r jobs distribute over M
2936 * stateful nodes, for every class, as the cartesian fold of the per-class
2937 * placements. Column block r holds class r's counts, M columns wide.
2938 */
2939template <class T>
2940std::vector<std::vector<T>> space_closed_multi(
2941 std::size_t M, const std::vector<std::size_t>& N,
2942 const std::vector<std::vector<long>>& caps = std::vector<std::vector<long>>()) {
2943 std::vector<std::vector<T>> ss;
2944 for (std::size_t r = 0; r < N.size(); ++r) {
2945 const std::vector<std::vector<T>> sr =
2946 r < caps.size() && !caps[r].empty() ? space_closed_single_capped<T>(M, N[r], caps[r])
2947 : space_closed_single<T>(M, N[r]);
2948 if (sr.empty()) return std::vector<std::vector<T>>();
2949 ss = r == 0 ? sr : cartesian(ss, sr);
2950 }
2951 return ss;
2952}
2953
2954/**
2955 * Port of `State.spaceClosedMultiCS`: the same, but a CHAIN's population is
2956 * shared among its classes, so the split between them is itself enumerated.
2957 *
2958 * Class switching moves a job between classes of one chain, so only the CHAIN
2959 * total is invariant. Enumerating over per-class populations alone would fix a
2960 * split the model does not fix, and drop every state reachable by a switch.
2961 *
2962 * @param M number of stateful nodes (sources excluded by the caller)
2963 * @param N per-class populations
2964 * @param chains chains[c][r] true when class r belongs to chain c
2965 */
2966template <class T>
2967std::vector<std::vector<T>> space_closed_multi_cs(
2968 std::size_t M, const std::vector<std::size_t>& N,
2969 const std::vector<std::vector<bool>>& chains,
2970 const std::vector<std::vector<long>>& caps = std::vector<std::vector<long>>()) {
2971 const std::size_t C = chains.size();
2972 const std::size_t R = N.size();
2973 // Per chain, the ways its total splits across the classes it contains.
2974 std::vector<std::vector<std::vector<int>>> chainInitPos(C);
2975 std::vector<std::size_t> inchain_sz(C, 0);
2976 for (std::size_t c = 0; c < C; ++c) {
2977 std::size_t tot = 0, k = 0;
2978 for (std::size_t r = 0; r < R; ++r)
2979 if (chains[c][r]) { tot += N[r]; ++k; }
2980 inchain_sz[c] = k;
2981 chainInitPos[c] = k == 0 ? std::vector<std::vector<int>>{std::vector<int>()}
2982 : pfqn::multichoose_rows(static_cast<int>(k), static_cast<int>(tot));
2983 }
2984 std::vector<std::vector<T>> ss;
2985 std::vector<std::size_t> v(C, 0);
2986 for (;;) {
2987 std::vector<std::size_t> subN;
2988 subN.reserve(R);
2989 for (std::size_t c = 0; c < C; ++c) {
2990 const std::vector<int>& row = chainInitPos[c][v[c]];
2991 for (std::size_t j = 0; j < row.size(); ++j)
2992 subN.push_back(static_cast<std::size_t>(row[j]));
2993 }
2994 // THE SPLIT IS SCATTERED BACK ONTO GLOBAL CLASS POSITIONS, with or
2995 // without caps: `subN` is built chain by chain, so its order is the
2996 // concatenation of the chains, not the class order `caps` and every
2997 // caller of the result are indexed by.
2998 std::vector<std::size_t> subNg(R, 0);
2999 {
3000 std::size_t k = 0;
3001 for (std::size_t c = 0; c < C; ++c)
3002 for (std::size_t r = 0; r < R; ++r)
3003 if (chains[c][r]) subNg[r] = subN[k++];
3004 }
3005 const std::vector<std::vector<T>> blk =
3006 caps.empty() ? space_closed_multi<T>(M, subNg)
3007 : space_closed_multi<T>(M, subNg, caps);
3008 ss.insert(ss.end(), blk.begin(), blk.end());
3009 // odometer over the per-chain splits
3010 std::size_t c = 0;
3011 for (; c < C; ++c) {
3012 if (++v[c] < chainInitPos[c].size()) break;
3013 v[c] = 0;
3014 }
3015 if (c == C) break;
3016 }
3017 return ss;
3018}
3019
3020/** One network state: the per-stateful-node local rows it is composed of. */
3021template <class T>
3022struct NetState {
3023 std::vector<std::vector<T>> local; ///< local[isf] is that node's state row
3024};
3025
3026/**
3027 * Port of `State.initialOccupancy`: the class-r jobs node `ind` holds in the
3028 * DECLARED initial state, or 0 when there is none.
3029 *
3030 * Only a Place answers nonzero. Every other node type encodes its local state
3031 * differently, so column r there is not an occupancy -- and a station whose
3032 * visit ratio is zero is genuinely never entered, while a Place with no input
3033 * arc is a TRANSIENT state of the chain rather than an absent one.
3034 */
3035template <class T>
3036std::size_t state_initial_occupancy(const NetworkStruct<T>& sn, std::size_t ind, std::size_t r) {
3037 if (ind == 0 || ind > sn.nodes.size()) return 0;
3038 if (sn.nodes[ind - 1].nodetype != NodeType::Place) return 0;
3039 const typename std::map<std::size_t, std::vector<T>>::const_iterator it =
3040 sn.initmarking.find(ind);
3041 if (it == sn.initmarking.end() || r >= it->second.size()) return 0;
3042 const double v = num_traits<T>::to_double(it->second[r]);
3043 return v > 0 ? static_cast<std::size_t>(v) : 0;
3044}
3045
3046/**
3047 * Port of the `capacityc` table of `State.spaceGeneratorNodes`: the largest
3048 * class-r marginal node `ind` may hold in the enumerated space.
3049 *
3050 * WITHOUT THIS TABLE THE LATTICE IS PLACED BLIND. `space_closed_multi_cs`
3051 * spreads a class's population over EVERY stateful node, including the ones the
3052 * class never visits, so a mixed model enumerates open jobs at a closed-only
3053 * station and closed jobs at an open-only one. Those states are unreachable, but
3054 * they are not free: they enlarge the generator, and on `mqn_multiserver_fcfs`
3055 * (1904 states against the reference's 1304) they moved the Source's departure
3056 * rate from 0.24763 to 0.26040 -- an arrival rate the model never offers.
3057 *
3058 * The bound is the reference's, in its order: a class that does not visit the
3059 * node is capped at its DECLARED initial occupancy (nonzero only for an SPN
3060 * Place, which may hold tokens at time zero without ever being re-entered), a
3061 * disabled service at 0, an open class at its cutoff and a closed one at its
3062 * chain population, both cut down by the station's per-class buffer and then by
3063 * any finite-capacity region the station belongs to.
3064 *
3065 * @param sn the network struct
3066 * @param cutoff per-class population bound for open classes
3067 * @param cutoff_mat optional (nstations x nclasses) bound, the reference's
3068 * matrix `options.cutoff`; overrides `cutoff` per station
3069 * @return (nnodes x nclasses) capacities, 0-based in both indices
3070 */
3071template <class T>
3072std::vector<std::vector<std::size_t>> space_capacity_c(
3073 const NetworkStruct<T>& sn, const std::vector<std::size_t>& cutoff,
3074 const std::vector<std::vector<std::size_t>>& cutoff_mat =
3075 std::vector<std::vector<std::size_t>>()) {
3076 const std::size_t R = sn.nclasses, N = sn.nodes.size();
3077 std::vector<std::vector<std::size_t>> cap(N, std::vector<std::size_t>(R, 0));
3078 const std::vector<double> njobs = sn.njobs();
3079
3080 // maxPending mirrors `State.spaceGeneratorNodes`: a completing fetch
3081 // releases every merged secondary request in one immediate transition.
3082 std::size_t maxpend = 0;
3083 for (std::size_t r = 0; r < R; ++r)
3084 if (!std::isfinite(njobs[r])) maxpend = std::max(maxpend, cutoff[r]);
3085 if (maxpend > 0) --maxpend;
3086
3087 for (std::size_t ind = 1; ind <= N; ++ind) {
3088 const NodeDef& nd = sn.nodes[ind - 1];
3089 if (!nd.stateful) continue;
3090 const std::size_t ist = nd.station;
3091 const std::size_t isf = sn.stateful_index(ind);
3092 if (ist != 0 && nd.nodetype != NodeType::Source) {
3093 for (std::size_t r = 0; r < R; ++r) {
3094 std::size_t c = R; // r's chain, or R when the struct carries none
3095 for (std::size_t cc = 0; cc < sn.chains.size(); ++cc)
3096 if (r < sn.chains[cc].size() && sn.chains[cc][r]) { c = cc; break; }
3097 const bool novisit = c < sn.visits.size() && sn.visits[c].rows() != 0 &&
3098 isf != 0 && isf - 1 < sn.visits[c].rows() &&
3099 num_traits<T>::to_double(sn.visits[c](isf - 1, r)) == 0;
3100 if (novisit) {
3101 cap[ind - 1][r] = state_initial_occupancy(sn, ind, r);
3102 continue;
3103 }
3104 if (nd.nodetype != NodeType::Place && ist - 1 < sn.disabled.size() &&
3105 r < sn.disabled[ist - 1].size() && sn.disabled[ist - 1][r]) {
3106 cap[ind - 1][r] = 0;
3107 continue;
3108 }
3109 double b;
3110 if (!std::isfinite(njobs[r])) {
3111 // `capacityc(ind,r) = min(cutoff(ist,r), classcap(ist,r))`:
3112 // the reference's cutoff is a (station x class) MATRIX
3113 // wherever a model needs a different truncation per station,
3114 // and only the uniform case collapses to one number.
3115 b = static_cast<double>(
3116 (!cutoff_mat.empty() && ist - 1 < cutoff_mat.size() &&
3117 r < cutoff_mat[ist - 1].size())
3118 ? cutoff_mat[ist - 1][r]
3119 : cutoff[r]);
3120 } else {
3121 b = 0.0; // the whole CHAIN's population may sit here
3122 for (std::size_t k = 0; k < R; ++k)
3123 if (c < sn.chains.size() && k < sn.chains[c].size() && sn.chains[c][k] &&
3124 std::isfinite(njobs[k]))
3125 b += njobs[k];
3126 }
3127 if (ist - 1 < sn.classcap.size() && r < sn.classcap[ist - 1].size())
3128 b = std::min(b, sn.classcap[ist - 1][r]);
3129 if (b > 0)
3130 for (std::size_t f = 0; f < sn.regions.size(); ++f) {
3131 const typename NetworkStruct<T>::Region& rg = sn.regions[f];
3132 if (ist - 1 >= rg.cap.size()) continue;
3133 if (r < rg.cap[ist - 1].size() && rg.cap[ist - 1][r] >= 0)
3134 b = std::min(b, rg.cap[ist - 1][r]);
3135 if (R < rg.cap[ist - 1].size() && rg.cap[ist - 1][R] >= 0)
3136 b = std::min(b, rg.cap[ist - 1][R]);
3137 }
3138 if (!(b > 0)) b = 0;
3139 cap[ind - 1][r] = std::isfinite(b) ? static_cast<std::size_t>(b)
3140 : static_cast<std::size_t>(-1);
3141 }
3142 continue;
3143 }
3144 switch (nd.nodetype) {
3145 case NodeType::Cache: {
3146 for (std::size_t r = 0; r < R; ++r) cap[ind - 1][r] = 1;
3147 const typename std::map<std::size_t, CacheParam<T>>::const_iterator ci =
3148 sn.nodeparam.find(ind);
3149 if (ci != sn.nodeparam.end() && ci->second.retrieval_capacity > 0)
3150 for (std::size_t r = 0; r < R; ++r)
3151 for (std::size_t k = 0; k < ci->second.hitclass.size(); ++k)
3152 if (ci->second.hitclass[k] == r + 1) cap[ind - 1][r] = 1 + maxpend;
3153 break;
3154 }
3155 case NodeType::Router:
3156 for (std::size_t r = 0; r < R; ++r) {
3157 std::size_t c = R;
3158 for (std::size_t cc = 0; cc < sn.chains.size(); ++cc)
3159 if (r < sn.chains[cc].size() && sn.chains[cc][r]) { c = cc; break; }
3160 cap[ind - 1][r] =
3161 (c < sn.nodevisits.size() && sn.nodevisits[c].rows() != 0 &&
3162 ind - 1 < sn.nodevisits[c].rows() &&
3163 num_traits<T>::to_double(sn.nodevisits[c](ind - 1, r)) > 0)
3164 ? 1
3165 : 0;
3166 }
3167 break;
3168 default:
3169 // A Transition holds no class-indexed job, and a Source is an
3170 // infinite reservoir the lattice never places into.
3171 for (std::size_t r = 0; r < R; ++r)
3172 cap[ind - 1][r] = static_cast<std::size_t>(-1);
3173 break;
3174 }
3175 }
3176 return cap;
3177}
3178
3179/**
3180 * Port of `State.spaceGenerator`: every network state, reachable or not.
3181 *
3182 * The population lattice is walked with `space_closed_multi_cs`, and each
3183 * lattice row is expanded per node through `from_marginal`; the network states
3184 * are the cartesian product of those local spaces. An open class has no finite
3185 * population, so `cutoff` bounds it -- WITHOUT a cutoff the lattice is infinite
3186 * and the reference errors rather than truncating silently.
3187 *
3188 * @param sn the network struct
3189 * @param cutoff per-class population bound for open classes
3190 * @param maxst refuse beyond this many states (the reference's ctmc_max_states)
3191 * @param cutoff_mat optional (nstations x nclasses) bound, the reference's
3192 * matrix `options.cutoff`
3193 */
3194template <class T>
3195std::vector<NetState<T>> space_generator(
3196 const NetworkStruct<T>& sn, const std::vector<std::size_t>& cutoff,
3197 std::size_t maxst = 3000000,
3198 const std::vector<std::vector<std::size_t>>& cutoff_mat =
3199 std::vector<std::vector<std::size_t>>()) {
3200 const std::size_t R = sn.nclasses;
3201 if (cutoff.size() != R)
3202 throw InputError("space_generator: cutoff must have one entry per class");
3203
3204 // Closed classes carry their own population; open ones are bounded by the
3205 // cutoff. A missing cutoff on an open class is an error in the reference,
3206 // because a silently truncated lattice yields a state space that looks
3207 // complete and is not.
3208 // `njobs()` is a population COUNT, always a plain double; it is not carried
3209 // in T, so reading it as a vector<T> fails to compile on every backend but
3210 // double -- which is how this survived until SolverCTMC was instantiated at
3211 // higher precision.
3212 const std::vector<double> njobs = sn.njobs();
3213 std::vector<std::size_t> Np(R, 0);
3214 for (std::size_t r = 0; r < R; ++r) {
3215 const double nj = njobs[r];
3216 if (std::isfinite(nj)) {
3217 Np[r] = static_cast<std::size_t>(nj);
3218 } else {
3219 if (cutoff[r] == 0)
3220 throw InputError(
3221 "space_generator: class " + std::to_string(r) +
3222 " is open, so its population is unbounded; supply a cutoff for it");
3223 Np[r] = cutoff[r];
3224 }
3225 }
3226
3227 // The per-node bound the reference places the lattice under. An open class's
3228 // lattice height is then the LARGEST capacity any node grants it, not the raw
3229 // cutoff: levels above that produce only rows every node refuses.
3230 const std::vector<std::vector<std::size_t>> capc = space_capacity_c(sn, cutoff, cutoff_mat);
3231 const std::size_t unbounded = static_cast<std::size_t>(-1);
3232 for (std::size_t r = 0; r < R; ++r) {
3233 if (std::isfinite(njobs[r])) continue;
3234 std::size_t hi = 0;
3235 bool any_unbounded = false;
3236 for (std::size_t ind = 1; ind <= sn.nodes.size(); ++ind) {
3237 if (!sn.nodes[ind - 1].stateful || sn.nodes[ind - 1].nodetype == NodeType::Source)
3238 continue;
3239 if (capc[ind - 1][r] == unbounded) any_unbounded = true;
3240 else hi = std::max(hi, capc[ind - 1][r]);
3241 }
3242 if (!any_unbounded) Np[r] = std::min(Np[r], hi);
3243 }
3244
3245 std::vector<std::vector<bool>> chains = sn.chains;
3246 if (chains.empty()) { // no class switching: each class is its own chain
3247 chains.assign(R, std::vector<bool>(R, false));
3248 for (std::size_t r = 0; r < R; ++r) chains[r][r] = true;
3249 }
3250
3251 // The lattice is over the STATEFUL NODES, not the stations: a Transition or
3252 // a Cache is stateful without being a station, and iterating stations drops
3253 // its local block entirely. Sources hold no jobs, so they take no column.
3254 const std::vector<std::size_t>& sfn = sn.stateful_nodes;
3255 const std::size_t NF = sfn.size();
3256 std::vector<std::size_t> lat_col(NF, static_cast<std::size_t>(-1));
3257 std::size_t Mp = 0;
3258 for (std::size_t k = 0; k < NF; ++k)
3259 if (sn.nodes[sfn[k] - 1].nodetype != NodeType::Source) lat_col[k] = Mp++;
3260
3261 // The population LATTICE, not just its top row. An open class has no fixed
3262 // population, so every level from 0 to its cutoff is a distinct set of
3263 // states; only a CLOSED class is pinned to its own N. Enumerating the top
3264 // row alone yields a chain that can never empty -- for an M/M/1/K it left
3265 // exactly one state, and a one-state generator is trivially valid, which is
3266 // why the closed-model test could not detect this.
3267 std::vector<bool> is_open(R, false);
3268 for (std::size_t r = 0; r < R; ++r)
3269 is_open[r] = !std::isfinite(njobs[r]);
3270
3271 // THE LATTICE IS CAPACITY-BOUND, not just the per-node local rows. `capc`
3272 // already zeroes a (node, class) pair the class never visits, and the
3273 // composition below drops the rows that breach it -- but it drops them ONE
3274 // AT A TIME, after `space_closed_multi_cs` has spread every class over every
3275 // slot. On the class-switching chain Source->Q1(A)->Q2(B)->Q3(C) that is
3276 // (cutoff+1)^(3*3) candidates for (cutoff+1)^3 reachable states, and the
3277 // rejection is not free: each candidate costs a `from_marginal`.
3278 // `lat_caps[class][slot]` is `capc` in the SLOT order the lattice row uses.
3279 std::vector<std::vector<long>> lat_caps(R, std::vector<long>(Mp, -1));
3280 {
3281 bool ok = Mp > 0;
3282 for (std::size_t k = 0; k < NF && ok; ++k) {
3283 if (lat_col[k] == static_cast<std::size_t>(-1)) continue;
3284 const std::size_t ind = sfn[k];
3285 for (std::size_t r = 0; r < R; ++r) {
3286 const std::size_t cap = capc[ind - 1][r];
3287 lat_caps[r][lat_col[k]] =
3288 cap == unbounded ? -1 : static_cast<long>(cap);
3289 }
3290 }
3291 if (!ok) lat_caps.clear();
3292 }
3293 std::vector<std::vector<T>> pos;
3294 std::vector<std::size_t> nlev(R, 0);
3295 for (;;) {
3296 bool admissible = true;
3297 for (std::size_t r = 0; r < R; ++r)
3298 if (!is_open[r] && nlev[r] != Np[r]) { admissible = false; break; }
3299 if (admissible) {
3300 const std::vector<std::vector<T>> part =
3301 space_closed_multi_cs<T>(Mp, nlev, chains, lat_caps);
3302 pos.insert(pos.end(), part.begin(), part.end());
3303 if (pos.size() > maxst)
3304 throw UnsupportedError(ErrorKind{"StateSpace"},
3305 "space_generator: the population lattice exceeds the cap of " +
3306 std::to_string(maxst) + " states; raise it or use another solver");
3307 }
3308 // Mixed-radix increment over the per-class levels, the reference's pprod.
3309 std::size_t r = 0;
3310 for (; r < R; ++r) {
3311 if (nlev[r] < Np[r]) { ++nlev[r]; break; }
3312 nlev[r] = 0;
3313 }
3314 if (r == R) break;
3315 }
3316 // Distinct levels can yield the same lattice row when a class is absent
3317 // from it, so drop the duplicates the reference removes with `unique`.
3318 std::sort(pos.begin(), pos.end());
3319 pos.erase(std::unique(pos.begin(), pos.end()), pos.end());
3320 // Per node and per lattice row, the local rows -- collected BEFORE any
3321 // composition because their width is not uniform. A marginal of 3 jobs at
3322 // an FCFS station needs two buffer columns where a marginal of 2 needs one,
3323 // and the reference unifies the two by RIGHT-ALIGNING the narrower row into
3324 // the widest (`fromMarginalBounds`), padding zeros on the left. Composing
3325 // before padding leaves an arrival unable to match its own successor,
3326 // because the successor is a wider vector and no index lookup can find it.
3327 std::vector<std::vector<std::vector<std::vector<T>>>> allper(pos.size());
3328 std::vector<bool> row_ok(pos.size(), true);
3329 std::vector<std::size_t> maxw(NF, 0);
3330 std::vector<NetState<T>> out;
3331 for (std::size_t j = 0; j < pos.size(); ++j) {
3332 // Wall-clock budget (options.timeout), read every 1024 lattice rows: a
3333 // state space cut short has no valid partial solution, so it raises.
3334 if ((j & 1023u) == 1023u) util::timeout_check("CTMC state-space generation (lower the cutoff or raise the budget)");
3335 std::vector<std::vector<std::vector<T>>> per(NF);
3336 bool ok = true;
3337 for (std::size_t k = 0; k < NF && ok; ++k) {
3338 const std::size_t ind = sfn[k];
3339 const std::size_t ist = sn.nodes[ind - 1].station;
3340 std::vector<std::size_t> ph(R, 1), nmarg(R, 0);
3341 // phases_of takes a 1-BASED class index, as elsewhere in NetworkStruct.
3342 if (ist != 0)
3343 for (std::size_t r = 0; r < R; ++r) ph[r] = sn.phasessz_of(ist, r + 1);
3344 if (lat_col[k] == static_cast<std::size_t>(-1)) {
3345 // A Source is an infinite reservoir: one job per class in
3346 // service, no marginal of its own -- but ONLY for the classes it
3347 // actually generates. A class the Source does not generate has a
3348 // disabled arrival, so phases_of is 0, and demanding one job of
3349 // it makes space_closed_single(0, 1) return nothing: the Source
3350 // yields no local row and the WHOLE state space comes out empty.
3351 // Invisible on a single-class open model, because its one class
3352 // is generated; a Source-Cache-Sink model, whose Hit and Miss
3353 // classes exist only downstream, hits it immediately.
3354 for (std::size_t r = 0; r < R; ++r)
3355 if (!sn.disabled[ist - 1][r]) nmarg[r] = 1;
3356 } else {
3357 for (std::size_t r = 0; r < R; ++r)
3358 nmarg[r] = static_cast<std::size_t>(
3359 num_traits<T>::to_double(pos[j][r * Mp + lat_col[k]]));
3360 // `any(stateMarg_i > capacityc(ind,:))` of the reference: the node
3361 // yields NO row, so the whole lattice row is dropped by the
3362 // cartesian product below.
3363 for (std::size_t r = 0; r < R && ok; ++r)
3364 if (capc[ind - 1][r] != static_cast<std::size_t>(-1) &&
3365 nmarg[r] > capc[ind - 1][r])
3366 ok = false;
3367 if (!ok) break;
3368 }
3369 per[k] = from_marginal_node(sn, ind, nmarg, ph);
3370 if (per[k].empty()) ok = false;
3371 for (std::size_t b = 0; b < per[k].size(); ++b)
3372 maxw[k] = std::max(maxw[k], per[k][b].size());
3373 }
3374 row_ok[j] = ok;
3375 allper[j].swap(per);
3376 }
3377
3378 for (std::size_t j = 0; j < pos.size(); ++j) {
3379 if ((j & 1023u) == 1023u) util::timeout_check("CTMC state-space generation (lower the cutoff or raise the budget)");
3380 if (!row_ok[j]) continue;
3381 std::vector<std::vector<std::vector<T>>>& per = allper[j];
3382 // Right-align every row into the node's widest, as the reference does.
3383 for (std::size_t k = 0; k < NF; ++k)
3384 for (std::size_t b = 0; b < per[k].size(); ++b)
3385 if (per[k][b].size() < maxw[k])
3386 per[k][b].insert(per[k][b].begin(), maxw[k] - per[k][b].size(),
3388 // Cartesian product across nodes, carrying the per-node rows.
3389 std::vector<NetState<T>> acc(1);
3390 for (std::size_t i = 0; i < NF; ++i) {
3391 std::vector<NetState<T>> next;
3392 for (std::size_t a = 0; a < acc.size(); ++a)
3393 for (std::size_t b = 0; b < per[i].size(); ++b) {
3394 NetState<T> ns = acc[a];
3395 ns.local.push_back(per[i][b]);
3396 next.push_back(ns);
3397 }
3398 acc.swap(next);
3399 if (out.size() + acc.size() > maxst)
3400 throw UnsupportedError(ErrorKind{"StateSpace"},
3401 "space_generator: the state space exceeds the cap of " +
3402 std::to_string(maxst) + " states; raise it or use another solver");
3403 }
3404 out.insert(out.end(), acc.begin(), acc.end());
3405 }
3406 // The same network state can be produced by two lattice rows once the
3407 // widths are unified, so drop duplicates as the reference's `unique` does,
3408 // keeping the FIRST occurrence in place. The lookup is an ordered set: a
3409 // linear scan of the kept rows made this pass quadratic, and on a large
3410 // space it ran for hours after every other stage had finished.
3411 // The set holds INDICES into `out`, not copies of the rows, so the pass
3412 // does not double the memory of a space that is already the largest object.
3413 const auto row_less = [&out](std::size_t a, std::size_t b) { return out[a].local < out[b].local; };
3414 std::set<std::size_t, decltype(row_less)> seen(row_less);
3415 std::vector<NetState<T>> uniq;
3416 for (std::size_t i = 0; i < out.size(); ++i) {
3417 if ((i & 1023u) == 1023u) util::timeout_check("CTMC state-space generation (lower the cutoff or raise the budget)");
3418 if (!seen.insert(i).second) continue;
3419 uniq.push_back(out[i]);
3420 }
3421 return uniq;
3422}
3423
3424} // namespace qn
3425} // namespace line
3426
3427#endif // LINE_LANG_QN_STATE_H
InputError(const std::string &what)
Definition error.h:105
std::size_t size() const
Definition matrix.h:91
std::size_t rows() const
Definition matrix.h:89
bool empty() const
Definition matrix.h:92
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
std::vector< std::vector< bool > > replyblock
sn.replyblock (nnodes x nclasses) and sn.syncreply (nclasses).
std::vector< std::vector< std::size_t > > nvars
sn.nvars, (nnodes x 3R+1): the LOCAL VARIABLE columns each node appends to its state,...
static std::size_t bas_ncols(const std::vector< std::size_t > &codes)
Width of the held-job block: one counter per code, at least one column.
std::vector< Station< T > > stations
stations[k-1] is the k-th station
The station blocks SolverCTMC appends to a station's local state for three features the population la...
The exception types the port throws.
Enumerations and the minimal distribution descriptor shared by the model layer of the C++ port.
options.timeout: one wall-clock budget per top-level solve, on a per-THREAD deadline stack.
Dense matrix and non-owning view.
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
RoutingStrategy
Routing strategies, with the values of MATLAB RoutingStrategy.
Definition lang_types.h:430
@ GLOBAL
a timed token: per-class target rotation timers
Definition lang_types.h:415
@ NONE
no visit timer
Definition lang_types.h:413
@ 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
ProcessType
Distribution kinds, with the values of MATLAB ProcessType.
Definition lang_types.h:524
std::vector< double > pfqn_sdrprob(const SdrCoeff &c, const std::vector< double > &n)
SDR routing probabilities of eq.
Definition pfqn_sdr.h:207
std::vector< std::vector< int > > multichoose_rows(int n, int k)
All n-vectors of nonnegative integers summing to k, in MATLAB multichoose(n,k) order.
SdrCoeff pfqn_sdrcoeff(const SdrStruct &sdr)
Validates an SDR structure and returns its derived coefficients.
Definition pfqn_sdr.h:105
double pfqn_sdrped(const std::vector< double > &P)
Probability of being denied entry and routed straight to the departure centre.
Definition pfqn_sdr.h:239
std::vector< std::vector< T > > from_marginal(const NetworkStruct< T > &sn, std::size_t ist, const std::vector< std::size_t > &n, const std::vector< std::size_t > &phases)
Definition state.h:1712
std::vector< std::vector< T > > polling_blocks(const PollingInfo< T > &pi, std::size_t srvclass, const std::vector< std::size_t > &nbuf)
Port of State.pollingBlocks + State.pollingProject: every controller configuration compatible with on...
Definition state.h:1072
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,...
std::vector< std::vector< long > > bas_held_combos(const NetworkStruct< T > &sn, const std::vector< std::size_t > &codes, const std::vector< long > &sir, bool single)
Every held-job vector a true-BAS row may carry (BUG-110), over the codes of NetworkStruct::bas_marker...
Definition state.h:1251
Marginal< T > to_marginal(const NetworkStruct< T > &sn, std::size_t ist, const std::vector< T > &state_i, const std::vector< std::size_t > &phasesz, const std::vector< std::size_t > &phaseshift, std::size_t nvar=0)
Port of State.toMarginal for a STATION, one state row at a time.
Definition state.h:139
void attempt_compositions(std::size_t total, std::size_t parts, std::vector< std::vector< std::size_t > > &out, std::vector< std::size_t > head=std::vector< std::size_t >())
Every vector of parts nonnegative integers summing to total, in the order of python compositions: the...
std::vector< double > station_populations(const NetworkStruct< T > &sn, const std::vector< std::vector< T > > &local)
Total jobs held by every STATION at one network state, indexed by station.
Definition state.h:339
std::vector< NetState< T > > space_generator(const NetworkStruct< T > &sn, const std::vector< std::size_t > &cutoff, std::size_t maxst=3000000, const std::vector< std::vector< std::size_t > > &cutoff_mat=std::vector< std::vector< std::size_t > >())
Port of State.spaceGenerator: every network state, reachable or not.
Definition state.h:3195
std::vector< std::vector< T > > from_marginal_core(const NetworkStruct< T > &sn, std::size_t ist, const std::vector< std::size_t > &n, const std::vector< std::size_t > &phases)
Port of State.fromMarginal for the station families CTMC enumerates: every local state in which stati...
Definition state.h:651
std::vector< std::vector< T > > from_marginal_node(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< std::size_t > &n, const std::vector< std::size_t > &phases)
Port of State.fromMarginal at its OWN signature: the reference indexes by NODE, not by station,...
Definition state.h:2332
bool from_marginal_node_first(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< std::size_t > &n, const std::vector< std::size_t > &phases, std::vector< T > &out)
The FIRST row from_marginal_node emits, BUILT rather than enumerated.
Definition state.h:2887
std::size_t state_initial_occupancy(const NetworkStruct< T > &sn, std::size_t ind, std::size_t r)
Port of State.initialOccupancy: the class-r jobs node ind holds in the DECLARED initial state,...
Definition state.h:3036
RrInfo< T > rr_info(const NetworkStruct< T > &sn, std::size_t ind)
Port of State.rrInfo.
Definition rr_info.h:95
std::vector< std::vector< T > > from_marg_node(const NetworkStruct< T > &sn, std::size_t ind, std::size_t ntot, const std::vector< std::size_t > &phases)
Port of State.fromMarg: the state space with a given TOTAL queue length.
Definition state.h:2680
void space_closed_single_capped_rec(std::size_t m, long n, const std::vector< long > &caps, std::size_t off, std::vector< T > &row, std::vector< std::vector< T > > &out)
space_closed_single with a PER-SLOT bound, the reference's spaceClosedSingle(M, N,...
Definition state.h:543
std::vector< std::vector< T > > space_closed_single(std::size_t m, std::size_t n)
Port of State.spaceClosedSingle: the ways to place n jobs over m phases.
Definition state.h:514
std::vector< std::vector< T > > from_marg_node_started(const NetworkStruct< T > &sn, std::size_t ind, std::size_t ntot, std::size_t stot, const std::vector< std::size_t > &phases)
Port of State.fromMargAndStarted: the states with a given TOTAL queue length AND a given TOTAL number...
Definition state.h:2801
std::vector< std::vector< T > > from_marginal_and_started_core(const NetworkStruct< T > &sn, std::size_t ist, const std::vector< std::size_t > &n, const std::vector< std::size_t > &s, const std::vector< std::size_t > &phases)
Port of State.fromMarginalAndStarted: ONE state realizing both a per-class occupancy n and a per-clas...
Definition state.h:1888
std::vector< std::vector< T > > cartesian(const std::vector< std::vector< T > > &a, const std::vector< std::vector< T > > &b)
Port of State.cartesian: pair every row of a with every row of b.
Definition state.h:485
std::vector< std::vector< T > > from_marginal_and_running(const NetworkStruct< T > &sn, std::size_t ist, const std::vector< std::size_t > &n, const std::vector< std::size_t > &s, const std::vector< std::size_t > &phases)
Port of State.fromMarginalAndRunning: EVERY local state of station ist holding n[r] class-r jobs of w...
Definition state.h:2120
std::vector< std::vector< T > > from_marginal_node_and_started(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< std::size_t > &n, const std::vector< std::size_t > &s, const std::vector< std::size_t > &phases)
Port of State.fromMarginalAndStarted at its OWN signature, which indexes by NODE rather than by stati...
Definition state.h:2613
std::vector< std::vector< T > > from_marginal_node_and_running(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< std::size_t > &n, const std::vector< std::size_t > &s, const std::vector< std::size_t > &phases)
Port of State.fromMarginalAndRunning at its OWN signature, which indexes by NODE, as from_marginal_no...
Definition state.h:2638
AttemptsLayout attempts_info(const NetworkStruct< T > &sn, std::size_t ind)
The ACTIVE attempt block of node ind: the layout, when SolverCTMC appended it.
std::vector< std::vector< T > > rr_blocks(const RrInfo< T > &ri, const std::vector< T > &row)
Port of State.rrSpace for one row: the round-robin quantum blocks a [buffer | server] row can carry,...
Definition state.h:1209
const char * routing_to_text(RoutingStrategy r)
Definition lang_types.h:443
std::size_t ctmc_tail_width(const NetworkStruct< T > &sn, std::size_t ind)
Width of the CTMC station block of node ind (1-based), 0 when it has none.
Definition ctmc_blocks.h:65
std::vector< std::vector< std::size_t > > space_capacity_c(const NetworkStruct< T > &sn, const std::vector< std::size_t > &cutoff, const std::vector< std::vector< std::size_t > > &cutoff_mat=std::vector< std::vector< std::size_t > >())
Port of the capacityc table of State.spaceGeneratorNodes: the largest class-r marginal node ind may h...
Definition state.h:3072
PollingInfo< T > polling_info(const NetworkStruct< T > &sn, std::size_t ind)
Matrix< T > rt_state(const NetworkStruct< T > &sn, const std::vector< std::vector< T > > &local)
Port of sn.rtfun: the routing over the stateful nodes AT ONE STATE.
Definition state.h:391
std::vector< std::vector< std::size_t > > pas_multiset_perms(const std::vector< std::size_t > &vec)
Port of matlab/util/multiset_perms.m on an ASCENDING multiset, ROW ORDER INCLUDED.
Definition state.h:596
std::vector< std::vector< T > > from_marginal_and_started(const NetworkStruct< T > &sn, std::size_t ist, const std::vector< std::size_t > &n, const std::vector< std::size_t > &s, const std::vector< std::size_t > &phases)
State.fromMarginalAndStarted with the trailing local-variable block appended, i.e.
Definition state.h:2062
std::vector< std::vector< T > > space_closed_multi_cs(std::size_t M, const std::vector< std::size_t > &N, const std::vector< std::vector< bool > > &chains, const std::vector< std::vector< long > > &caps=std::vector< std::vector< long > >())
Port of State.spaceClosedMultiCS: the same, but a CHAIN's population is shared among its classes,...
Definition state.h:2967
std::vector< std::vector< T > > append_local_vars(const NetworkStruct< T > &sn, std::size_t ist, std::vector< std::vector< T > > rows, const std::vector< std::size_t > &n, const std::vector< std::size_t > &phases)
Append the trailing local-variable block to every row the core builders produce, which is what makes ...
Definition state.h:1323
std::vector< std::vector< T > > space_closed_single_capped(std::size_t m, std::size_t n, const std::vector< long > &caps)
Definition state.h:568
std::vector< std::vector< T > > space_closed_multi(std::size_t M, const std::vector< std::size_t > &N, const std::vector< std::vector< long > > &caps=std::vector< std::vector< long > >())
Port of State.spaceClosedMulti: how N[r] class-r jobs distribute over M stateful nodes,...
Definition state.h:2940
std::vector< std::vector< T > > from_marginal_pool(const NetworkStruct< T > &sn, std::size_t ist, const std::vector< std::size_t > &n)
Port of State.fromMarginalPool: the local states with marginal n at a station rewritten by ctmc::ctmc...
Definition state.h:1610
void timeout_check(const char *where)
The raising checkpoint, for a computation with no valid partial result: throws LINE:numerical:Timeout...
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
Integer-composition enumeration shared by the CoMoM and MVAC ports.
State.pollingInfo and the controller description it returns.
State.rrInfo: the quantum-phase block of a round-robin station.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
Derived coefficients of an SDR structure, eqs.
Definition pfqn_sdr.h:81
A finite-attempt retrial station (python attempts_info).
std::size_t M
maxAttempts, the number of attempt levels
std::size_t cls
1-based retrial class
The parameters of a Cache node, MATLAB's sn.nodeparam{ind} for a Cache.
int retrieval_capacity
Delayed-hit retrieval system (Cache.setRetrievalSystem).
long max_pending_retrieval
Truncation level of block B: how many secondary requests may be merged onto the in-flight fetches of ...
std::vector< int > itemcap
std::vector< std::size_t > missclass
std::vector< std::size_t > hitclass
CTMC pair form of a MAP service at an FCFS station, written by ctmc::ctmc_mapc on the solver's privat...
CTMC bookkeeping of a heterogeneous-server station, written by ctmc::ctmc_pools on the solver's priva...
std::vector< std::vector< std::size_t > > len
offset and length of block k of class r
std::vector< std::vector< std::size_t > > pools
pools[r-1]: compatible pools of r, ascending
bool rotate
ALIS/FAIRNESS order is part of the state.
std::vector< std::vector< std::size_t > > perms
every pool order, identity first
static constexpr double MaxInt
Stand-in for an unbounded COUNT, MATLAB GlobalConstants.MaxInt.
Definition lang_types.h:834
What State.toMarginal returns for one station and one state row.
Definition state.h:56
std::vector< std::vector< T > > kir
jobs in service per class and phase
Definition state.h:60
T ni
total jobs in the station
Definition state.h:57
std::vector< T > nir
jobs per class
Definition state.h:58
std::vector< T > sir
jobs in service per class
Definition state.h:59
One network state: the per-stateful-node local rows it is composed of.
Definition state.h:3022
std::vector< std::vector< T > > local
local[isf] is that node's state row
Definition state.h:3023
The pass-and-swap / order-independent parameters of a PAS station, keyed by station index (Dorsman an...
FINITE CAPACITY REGIONS, MATLAB's refreshRegions output.
std::vector< std::vector< double > > cap
(nstations x nclasses+1), -1 = unbounded
A node of the network.
std::vector< int > routing_param
The scalar parameter of a parameterized dispatcher, per class: the d of a power-of-d (SQ) choice.
std::vector< RoutingStrategy > routing
sn.routing, per class.
Port of State.pollingInfo: the derived description of a polling controller.
std::vector< std::size_t > ring
1-based classes, length M
std::vector< bool > has_sw
std::vector< std::size_t > pos_of
1-based first position of each class
std::vector< std::size_t > ksw
std::vector< bool > keep
std::vector< std::size_t > tk
timer phases per class (0 = none)
lang::PollingTimer tmode
std::vector< bool > polled
lang::PollingType ptype
The derived description of an RR station's quantum block, MATLAB's rinfo.
Definition rr_info.h:60
std::size_t width
Definition rr_info.h:65
std::vector< std::vector< T > > qa
Definition rr_info.h:63
std::vector< std::size_t > K
Definition rr_info.h:61
std::vector< std::size_t > Q
Definition rr_info.h:61
std::size_t boff
Definition rr_info.h:66
One station of the network.
SchedStrategy sched
double nservers
may be infinite (a Delay, or an inf-scheduled task)
The parameters of a Transition node: MATLAB sn.nodeparam{ind} for an SPN transition,...
std::vector< double > nmodeservers
servers per mode, may be infinite
std::vector< std::size_t > firingphases
phase count per mode, 0 when non-Markovian