LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_ctmc_waitq.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 */
5#ifndef LINE_SOLVERS_CTMC_SOLVER_CTMC_WAITQ_H
6#define LINE_SOLVERS_CTMC_SOLVER_CTMC_WAITQ_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * Port of `solver_ctmc_fcr_waitq.m`: the reachability-built generator of a model
12 * whose finite capacity region applies WAITQ.
13 *
14 * WHY THIS IS A SEPARATE GENERATOR AND NOT A FILTER. Under DROP a refused job is
15 * destroyed, so the chain never occupies a forbidden state and censoring the
16 * enumerated space IS the censored chain -- that is `solver_ctmc_fcr.h`. Under
17 * WAITQ the refused job LEAVES its upstream station and parks in a per-region
18 * FIFO of (class, destination) tokens that sits outside every station. That FIFO
19 * is state, it is owned by the region rather than by any node, and no filter on
20 * the per-node state space can represent it. The state here is therefore
21 * augmented as [per-node states, buf_1, ..., buf_F] and the transition relation
22 * is rebuilt around it.
23 *
24 * THE FOUR RULES THAT MAKE WAITQ WHAT IT IS, all from the JMT reference:
25 *
26 * 1. RELEASE IS STRICTLY HEAD-OF-LINE. After every transition that frees
27 * capacity, tokens leave in FIFO order and a head that still does not fit
28 * blocks the whole queue behind it, even where a token further back would
29 * fit. Releasing the first token that fits instead would be a different
30 * discipline with a different mean.
31 * 2. A FRESH ARRIVAL IS NOT QUEUED BEHIND THE FIFO. It is admitted whenever the
32 * constraints permit, so it overtakes a head stuck on a different
33 * constraint. The FIFO gates only the jobs already in it.
34 * 3. THE RELEASE CASCADE IS PART OF THE SAME TRANSITION. Freeing one slot can
35 * release a token whose admission frees another slot, and so on; the chain
36 * jumps straight to the settled state. Splitting the cascade into separate
37 * transitions would invent intermediate states with a residence time the
38 * model does not have.
39 * 4. PARKED JOBS ARE IN NO STATION AND IN NO REGION. Station queue lengths
40 * exclude them, which is the JMT report convention; they are visible only
41 * through `ctmc_waitq_parked`, and any population accounting has to add
42 * them back by hand.
43 *
44 * A CLASS SWITCH INSIDE ONE REGION IS THE SUBTLE CASE. Such a hop leaves the
45 * region occupancy unchanged in total but moves one job between the per-class
46 * counts, so it can violate a per-class cap that the pre-transition state
47 * satisfied. It cannot be tested before the transition either, because the
48 * departure frees the old class's slot first. It is therefore deferred: the
49 * re-entry is resolved after the release cascade has settled, and parked at the
50 * TAIL if it still does not fit, since it was refused after every token already
51 * in the queue.
52 */
53
54#include <algorithm>
55#include <cmath>
56#include <cstddef>
57#include <deque>
58#include <map>
59#include <memory>
60#include <string>
61#include <tuple>
62#include <type_traits>
63#include <utility>
64#include <vector>
65
70#include "line/lang/qn/state.h"
75#include "line/util/error.h"
76#include "line/util/matrix.h"
77
78namespace line {
79namespace ctmc {
80
81/**
82 * One augmented state: the network state, plus the token FIFO of every region.
83 *
84 * A token is `(dest_node - 1) * K + cls`, both 1-based, which is the reference's
85 * encoding: a parked job knows the class it will enter in and the node it was on
86 * its way to when it was refused.
87 */
88template <class T>
89struct WaitqState {
91 std::vector<std::vector<std::size_t>> buf;
92};
93
94/** The chain the WAITQ walk produces, alongside the FIFOs its states carry. */
95template <class T>
97 CtmcResult<T> chain; ///< Q, the net halves, rates, filt
98 std::vector<std::vector<std::vector<std::size_t>>> buf; ///< per state, per region
99};
100
101namespace waitq_detail {
102
103/**
104 * The admission constraints of one region, flattened out of the Region struct
105 * once so the inner loop is not re-deriving them at every candidate state.
106 *
107 * The predicate this feeds is the one `ctmc_region_admissible` applies to a
108 * whole state; it is restated per region because WAITQ has to ask about ONE
109 * region at a time, on a candidate population vector that no state realizes yet.
110 */
111template <class T>
112struct RegionCaps {
113 std::vector<bool> member; ///< per station, 0-based
114 std::vector<double> ccap; ///< per class, -1 = unbounded
115 double gcap = -1.0;
116 double memcap = -1.0;
117 std::vector<double> size; ///< per class memory footprint
118 Matrix<T> A; ///< the linear constraint A x <= b
119 std::vector<T> b;
120 std::vector<bool> iswaitq; ///< per class; false = this class is DROP here
121 std::size_t lmax = 0; ///< FIFO length bound
122 std::vector<std::size_t> tokbound; ///< per class (0-based) FIFO bound: chain population, or the open-class cutoff
123};
124
125/**
126 * True if the region FIFO BUF already holds the per-class bound of class CLS (1-based) tokens. The bound is per class:
127 * a total-length test lets an open class fill the slots reserved for the closed chains, whose parking arcs were then dropped.
128 */
129template <class T>
130bool tok_full(const RegionCaps<T>& cap, const std::vector<std::size_t>& buf, std::size_t cls, std::size_t K) {
131 std::size_t n = 0;
132 for (std::size_t t : buf)
133 if ((t - 1) % K + 1 == cls) ++n;
134 return n >= (cls - 1 < cap.tokbound.size() ? cap.tokbound[cls - 1] : 0);
135}
136
137template <class T>
138std::vector<RegionCaps<T>> extract_caps(const NetworkStruct<T>& sn) {
139 const std::size_t M = sn.stations.size(), K = sn.nclasses;
140 std::vector<RegionCaps<T>> out;
141 out.reserve(sn.regions.size());
142 for (std::size_t f = 0; f < sn.regions.size(); ++f) {
143 const typename NetworkStruct<T>::Region& rg = sn.regions[f];
144 RegionCaps<T> c;
145 c.member.assign(M, false);
146 c.ccap.assign(K, -1.0);
147 c.size.assign(K, 1.0);
148 c.iswaitq.assign(K, false);
149 for (std::size_t i = 0; i < M; ++i) {
150 if (i >= rg.members.size() || !rg.members[i]) continue;
151 c.member[i] = true;
152 // The caps are replicated on every member row, so taking the
153 // tightest is both correct and safe against a hand-built struct.
154 for (std::size_t k = 0; k < K && k < rg.cap[i].size(); ++k)
155 if (rg.cap[i][k] != -1.0)
156 c.ccap[k] = c.ccap[k] == -1.0 ? rg.cap[i][k] : std::min(c.ccap[k], rg.cap[i][k]);
157 if (K < rg.cap[i].size() && rg.cap[i][K] != -1.0)
158 c.gcap = c.gcap == -1.0 ? rg.cap[i][K] : std::min(c.gcap, rg.cap[i][K]);
159 if (i < rg.maxmem.size() && rg.maxmem[i] != -1.0)
160 c.memcap = c.memcap == -1.0 ? rg.maxmem[i] : std::min(c.memcap, rg.maxmem[i]);
161 }
162 for (std::size_t k = 0; k < K; ++k) {
163 if (k < rg.size.size()) c.size[k] = num_traits<T>::to_double(rg.size[k]);
164 c.iswaitq[k] = k < rg.rule.size() && rg.rule[k] != DropStrategy::DROP;
165 }
166 c.A = rg.lincon_A;
167 c.b = rg.lincon_b;
168 out.push_back(c);
169 }
170 return out;
171}
172
173/** The reference's `violates`: does this per-class population break region f. */
174template <class T>
175bool violates(const RegionCaps<T>& c, const std::vector<double>& x) {
176 double total = 0, memory = 0;
177 for (std::size_t k = 0; k < x.size(); ++k) {
178 total += x[k];
179 memory += x[k] * c.size[k];
180 if (c.ccap[k] != -1.0 && x[k] > c.ccap[k] + 1e-9) return true;
181 }
182 if (c.gcap != -1.0 && total > c.gcap + 1e-9) return true;
183 if (c.memcap != -1.0 && memory > c.memcap + 1e-9) return true;
184 for (std::size_t row = 0; row < c.A.rows() && row < c.b.size(); ++row) {
185 double lhs = 0;
186 for (std::size_t k = 0; k < x.size() && k < c.A.cols(); ++k)
187 lhs += num_traits<T>::to_double(c.A(row, k)) * x[k];
188 if (lhs > num_traits<T>::to_double(c.b[row]) + 1e-9) return true;
189 }
190 return false;
191}
192
193/**
194 * The reference's `regionAggr`: the per-class population a region currently
195 * holds, summed over its member stations.
196 *
197 * `to_marginal_aggr` rather than `to_marginal`, for the reason the reference's
198 * arrival branch uses it: it leaves a preempted job out of the count, and
199 * counting one twice would refuse an admission the region has room for.
200 */
201template <class T>
202std::vector<double> region_aggr(const NetworkStruct<T>& sn, const RegionCaps<T>& c,
203 const NetState<T>& net) {
204 const std::size_t K = sn.nclasses;
205 std::vector<double> x(K, 0.0);
206 for (std::size_t i = 0; i < c.member.size(); ++i) {
207 if (!c.member[i]) continue;
208 const std::size_t ind = sn.node_of_station(i + 1);
209 const std::size_t isf = sn.stateful_index(ind);
210 if (isf == 0) continue;
211 const std::pair<T, std::vector<T>> mg = qn::to_marginal_aggr(sn, ind, net.local[isf - 1]);
212 for (std::size_t k = 0; k < K && k < mg.second.size(); ++k) {
213 const double v = num_traits<T>::to_double(mg.second[k]);
214 // A Source reports an infinite reservoir, which describes the
215 // encoding and not an occupancy; adding it would make every region
216 // permanently full.
217 if (std::isfinite(v)) x[k] += v;
218 }
219 }
220 return x;
221}
222
223/** The flattened key of an augmented state, for exact index lookup. */
224template <class T>
225std::vector<double> waitq_key(const WaitqState<T>& ws) {
226 std::vector<double> key = ctmc_detail::state_key(ws.net);
227 for (std::size_t f = 0; f < ws.buf.size(); ++f) {
228 key.push_back(-3.0); // a separator no node block and no token emits
229 for (std::size_t j = 0; j < ws.buf[f].size(); ++j)
230 key.push_back(static_cast<double>(ws.buf[f][j]));
231 }
232 return key;
233}
234
235/**
236 * The FIFO length bound of each region: at most every job that could be parked
237 * at once.
238 *
239 * A CLOSED CLASS IS BOUNDED BY ITS WHOLE CHAIN, not by its own population, since
240 * a job may switch into the class before being refused. An open class has no
241 * population to bound it and takes the state-space cutoff instead, which is what
242 * makes the FIFO finite at all -- and what makes the walk TRUNCATE rather than
243 * refuse when the bound is reached, exactly as the reference does.
244 */
245template <class T>
246void resolve_lmax(const NetworkStruct<T>& sn, const std::vector<std::size_t>& cutoff,
247 std::vector<RegionCaps<T>>& caps) {
248 const std::size_t K = sn.nclasses;
249 const std::vector<double> N = sn.njobs();
250 std::vector<std::size_t> tokbound(K, 0);
251 for (std::size_t r = 0; r < K; ++r) {
252 bool any = false;
253 for (std::size_t f = 0; f < caps.size(); ++f)
254 if (caps[f].iswaitq[r]) any = true;
255 if (!any) continue;
256 double chainpop = 0;
257 bool finite = true;
258 for (std::size_t c = 0; c < sn.nchains; ++c) {
259 bool holds = false;
260 for (std::size_t a = 0; a < sn.inchain[c].size(); ++a)
261 if (sn.inchain[c][a] == r + 1) holds = true;
262 if (!holds) continue;
263 for (std::size_t a = 0; a < sn.inchain[c].size(); ++a) {
264 const double nj = N[sn.inchain[c][a] - 1];
265 if (std::isfinite(nj))
266 chainpop += nj;
267 else
268 finite = false;
269 }
270 }
271 tokbound[r] = finite ? static_cast<std::size_t>(chainpop)
272 : (r < cutoff.size() ? cutoff[r] : 0);
273 }
274 for (std::size_t f = 0; f < caps.size(); ++f) {
275 std::size_t s = 0;
276 for (std::size_t r = 0; r < K; ++r)
277 if (caps[f].iswaitq[r]) s += tokbound[r];
278 caps[f].lmax = s;
279 caps[f].tokbound = tokbound;
280 }
281}
282
283/**
284 * The widest local row stateful node `ind` admits, which is the width every
285 * state of that node carries in the ENUMERATED space.
286 *
287 * WHY A WALK NEEDS THIS AND THE ENUMERATION DOES NOT. `space_generator` builds
288 * each node's rows for every marginal and RIGHT-ALIGNS the narrow ones into the
289 * widest it saw (the reference's `fromMarginalBounds`), so an FCFS station whose
290 * buffer is one slot wide when empty carries the buffer of its FULLEST marginal
291 * in every state. A walk seeded from `default_init_state` gets the row at the
292 * NATURAL width of the initial marginal instead -- for an empty FCFS station a
293 * one-slot buffer -- and nothing ever widens it: the arrival branch here places a
294 * job in an existing empty slot and refuses when there is none, where MATLAB's
295 * `afterEventStation` prepends a column first. The station then holds nservers+1
296 * jobs and no more; for a CLOSED class the refusal is a BLOCK rather than a loss,
297 * so no successor is emitted at all and the upstream departure never fires.
298 *
299 * MEASURED on Think -> Q1 -> Q2 with three jobs and an UNBOUNDED region, which
300 * must reproduce the region-less solution exactly: X came out 0.935049 against
301 * 0.962806. That is not a perturbation, it is the exact answer for a different
302 * model -- the same network truncated to two jobs per queue, which is what a
303 * one-slot buffer in front of one server means.
304 *
305 * The width of a node's row is a property of that node alone: for an ordered
306 * (class-tag) buffer it grows with the TOTAL jobs held and not with how they
307 * split across classes, and for every other encoding it is constant. So one call
308 * to `from_marginal_node` at a maximal admissible marginal settles it. The
309 * descent to a smaller total is not defensive padding: `from_marginal_node`
310 * returns NO rows for a marginal the station cannot hold, and the joint bound
311 * (`cap` against the sum of the per-class bounds) can be met by a marginal that
312 * some other constraint inside the handler still rejects.
313 *
314 * `ssa::serial_detail::max_row_width` is this same computation, which the serial
315 * simulator needs for this same reason -- it walks the encoding too. The two are
316 * stated twice because a CTMC generator has no business including the
317 * simulator's header, and they must be changed together; the one place that
318 * would hold a single copy is `State` itself.
319 */
320template <class T>
321std::size_t max_row_width(const NetworkStruct<T>& sn, std::size_t ind,
322 const std::vector<std::size_t>& cutoff) {
323 const std::size_t R = sn.nclasses;
324 const std::size_t ist = sn.nodes[ind - 1].station;
325 std::vector<std::size_t> ph(R, 1);
326 if (ist != 0)
327 for (std::size_t r = 0; r < R; ++r) ph[r] = sn.phasessz_of(ist, r + 1);
328
329 // A Source and a stateful non-station (a Cache, a Join) hold a per-class
330 // count and their local variables, both of fixed width, so the empty
331 // marginal already gives the final width.
332 if (ist == 0 || sn.stations[ist - 1].nodetype == NodeType::Source) {
333 std::vector<T> row;
334 if (!qn::from_marginal_node_first(sn, ind, std::vector<std::size_t>(R, 0), ph, row))
335 throw UnsupportedError(ErrorKind{"Model"}, "SolverCTMC: node '" + sn.nodes[ind - 1].name +
336 "' admits no state at all, so the WAITQ walk cannot start");
337 return row.size();
338 }
339
340 // The per-class bound: the class population when closed, the state-space
341 // cutoff when open, never above the station's own per-class capacity.
342 const std::vector<double> N = sn.njobs();
343 std::vector<std::size_t> bound(R, 0);
344 for (std::size_t r = 0; r < R; ++r) {
345 double b = std::isfinite(N[r]) ? N[r]
346 : static_cast<double>(r < cutoff.size() ? cutoff[r] : 0);
347 const double cc = sn.classcap[ist - 1][r];
348 if (cc < b) b = cc;
349 bound[r] = b > 0 ? static_cast<std::size_t>(b) : 0;
350 }
351 std::size_t total = 0;
352 for (std::size_t r = 0; r < R; ++r) total += bound[r];
353 const double tcap = sn.cap[ist - 1];
354 if (std::isfinite(tcap) && tcap < static_cast<double>(total))
355 total = tcap > 0 ? static_cast<std::size_t>(tcap) : 0;
356
357 for (std::size_t t = total + 1; t-- > 0;) {
358 std::vector<std::size_t> n(R, 0);
359 std::size_t left = t;
360 for (std::size_t r = 0; r < R && left > 0; ++r) {
361 n[r] = std::min(left, bound[r]);
362 left -= n[r];
363 }
364 if (left > 0) continue; // this total does not fit the per-class bounds
365 const std::vector<std::vector<T>> rows = qn::from_marginal_node(sn, ind, n, ph);
366 if (rows.empty()) continue;
367 // A setup/delay-off or server-parallelism station can hold EVERY job
368 // waiting -- servers OFF or setting up, or too few free for the head --
369 // so its ordered buffer needs a slot per job, not per job beyond the
370 // servers (`reachable_seed_widen`, python `_widen_ordered_buffer`).
371 const lang::SchedStrategy sched = sn.stations[ist - 1].sched;
372 const std::size_t percol = qn::state_detail::buffer_is_class_tag(sched) ? 1
373 : qn::state_detail::buffer_is_tag_phase_pairs(sched) ? 2 : 0;
374 const bool holds_idle = (sn.setupparam.count(ist) && qn::ctmc_tail_width(sn, ind) > 0) ||
375 !qn::parallelism_of(sn, ind).empty();
376 if (holds_idle && percol > 0) {
377 std::size_t srvw = 0;
378 for (std::size_t r = 0; r < R; ++r) srvw += ph[r];
379 const std::size_t fixed = srvw + sn.nvars_of(ind);
380 const std::size_t bufw = rows[0].size() > fixed ? rows[0].size() - fixed : 0;
381 const std::size_t want = std::max<std::size_t>(t, 1) * percol;
382 if (want > bufw) return rows[0].size() + (want - bufw);
383 }
384 return rows[0].size();
385 }
386 throw UnsupportedError(ErrorKind{"Model"}, "SolverCTMC: station '" + sn.stations[ist - 1].name +
387 "' admits no state at all, so the WAITQ walk cannot start");
388}
389
390/**
391 * The initial network state, padded to the encoding width of every node.
392 *
393 * The LEFT pad is not a convention chosen here: it is what `space_generator`
394 * does to the narrow rows, and every slicer in `state_events.h` measures its
395 * blocks from the RIGHT-hand end, so a right pad would shift the server block
396 * and silently decode the wrong queue.
397 */
398template <class T>
399NetState<T> wide_init_state(const NetworkStruct<T>& sn,
400 const std::vector<std::size_t>& cutoff) {
401 NetState<T> init;
402 if (!analyzer_detail::default_init_state(sn, init))
403 throw UnsupportedError(ErrorKind{"Model"},
404 "SolverCTMC: the model's initial state admits no state at some node; check the class "
405 "populations against their reference stations");
406 for (std::size_t f = 0; f < sn.stateful_nodes.size() && f < init.local.size(); ++f) {
407 const std::size_t w = max_row_width(sn, sn.stateful_nodes[f], cutoff);
408 if (init.local[f].size() >= w) continue;
409 init.local[f].insert(init.local[f].begin(), w - init.local[f].size(),
410 num_traits<T>::from_int(0));
411 }
412 return init;
413}
414
415/**
416 * One tentative successor, before the release cascade has run on it.
417 *
418 * `arv` and `dep_isf` carry the per-class rate bookkeeping through the cascade
419 * rather than letting the caller add it: the cascade can DROP a branch (a full
420 * FIFO), and a rate charged before that happens would count a transition that
421 * never fired.
422 */
423template <class T>
424struct Emission {
425 NetState<T> net;
426 std::vector<std::vector<std::size_t>> buf;
427 T w = num_traits<T>::from_int(0);
428 std::vector<std::pair<std::size_t, std::size_t>> arv; ///< (stateful index, class), 1-based
429 std::size_t dep_isf = 0, dep_cls = 0; ///< 0 when the active half is not a DEP
430 std::size_t pf = 0; ///< deferred re-entry region, 1-based
431 std::size_t pcls = 0, pdest = 0;
432 bool pwaitq = false;
433 /// False when the region parked (WAITQ) or destroyed (DROP) the action's passive arrival
434 bool admitted = true;
435};
436
437/** One item of the release cascade: a tentative state and how it got there. */
438template <class T>
439struct Work {
440 NetState<T> net;
441 std::vector<std::vector<std::size_t>> buf;
442 T prob;
443 std::vector<std::pair<std::size_t, std::size_t>> arv;
444 std::size_t dep_isf = 0, dep_cls = 0;
445 std::size_t pf = 0, pcls = 0, pdest = 0;
446 bool pwaitq = false;
447 bool admitted = true;
448 std::vector<std::pair<std::size_t, std::size_t>> rel; ///< (node, class) of each released job, 1-based
449};
450
451/**
452 * One SETTLED successor of an augmented state: where the transition goes, what
453 * it weighs, and the rate statistics it carries.
454 *
455 * "Settled" means the release cascade has run to its fixed point, so a caller
456 * never sees an intermediate state with a token that could still have left. The
457 * weight is the rate times the probability of this particular leaf of the
458 * cascade tree, which is why one synchronization can appear several times.
459 */
460template <class T>
461struct Successor {
462 std::size_t sync = 0; ///< index into the `sync` list the enumeration was given
463 WaitqState<T> next;
464 T w = num_traits<T>::from_int(0);
465 std::vector<std::pair<std::size_t, std::size_t>> arv; ///< (stateful, class), 1-based
466 std::size_t dep_isf = 0, dep_cls = 0; ///< 0 when nothing departed
467 /**
468 * The events that happened on this arc, for the LAL embedding: whether the
469 * action's passive arrival entered its node (false when the region parked
470 * it under WAITQ or destroyed it under DROP, so it arrived nowhere), and the
471 * (destination node, class), 1-based, of every head-of-line job the release
472 * cascade let into the region, each an arrival there.
473 */
474 bool admitted = true;
475 std::vector<std::pair<std::size_t, std::size_t>> rel;
476};
477
478/**
479 * Every transition enabled in one augmented state, with its settled successor.
480 *
481 * THIS IS THE WAITQ TRANSITION RELATION, and it is written once. The chain
482 * builder walks it breadth-first to fill a generator; the SSA serial engine
483 * draws one of the returned moves at each step. Two copies of the four rules in
484 * this file's header would be two chances for the region discipline to differ
485 * between the exact solver and the simulator while both looked correct.
486 *
487 * `sync` and `caps` are passed in rather than rebuilt because both are loop
488 * invariants of either caller, and `resolve_lmax` has to have run on `caps`
489 * already -- an unbounded FIFO admits every token and the walk would not
490 * terminate.
491 */
492template <class T>
493void waitq_successors(const NetworkStruct<T>& sn, const std::vector<Sync<T>>& sync,
494 const std::vector<RegionCaps<T>>& caps, const WaitqState<T>& ws,
495 std::vector<Successor<T>>& out) {
496 const std::size_t K = sn.nclasses;
497 const std::size_t F = caps.size();
498 const std::size_t local = sn.nodes.size() + 1;
499 const NetState<T>& net = ws.net;
500 const std::vector<std::vector<std::size_t>>& buf = ws.buf;
501 out.clear();
502
503 std::vector<std::vector<double>> xf(F);
504 for (std::size_t f = 0; f < F; ++f) xf[f] = region_aggr(sn, caps[f], net);
505
506 // State-dependent routing (SDR, JSQ, SQ), evaluated once at the state the transitions leave
507 // from, exactly as the ordinary generator does. A region and an SDR
508 // subnetwork are independent constructs, so this relation must carry eq. (10)
509 // too -- reading the uniform placeholder in `sn.rt` here would answer a
510 // uniformly-routed model under an SDR name at every model that has both.
511 Matrix<T> rt_now;
512 const bool sdr = sn.has_rtfun_routing();
513 if (sdr) rt_now = qn::rt_state(sn, net.local);
514
515 /*
516 * The reference's `emit`: run the release cascade to a fixed point, then
517 * record one successor per settled leaf.
518 *
519 * A WORK LIST and not a recursion because a release can have several
520 * outcomes -- an arrival that splits over the phase it starts service in --
521 * so the cascade is a tree, every leaf is a distinct successor of the SAME
522 * transition, and each carries its own share of the probability.
523 */
524 const auto emit = [&](std::size_t a, const Emission<T>& e) {
525 if (num_traits<T>::to_double(e.w) <= 0) return;
526 std::deque<Work<T>> work;
527 Work<T> w0;
528 w0.net = e.net;
529 w0.buf = e.buf;
530 w0.prob = num_traits<T>::from_int(1);
531 w0.arv = e.arv;
532 w0.dep_isf = e.dep_isf;
533 w0.dep_cls = e.dep_cls;
534 w0.pf = e.pf;
535 w0.pcls = e.pcls;
536 w0.pdest = e.pdest;
537 w0.pwaitq = e.pwaitq;
538 w0.admitted = e.admitted;
539 work.push_back(w0);
540
541 while (!work.empty()) {
542 const Work<T> it = work.front();
543 work.pop_front();
544
545 bool progressed = false;
546 for (std::size_t f = 0; f < F && !progressed; ++f) {
547 if (it.buf[f].empty()) continue;
548 const std::size_t tok = it.buf[f][0];
549 const std::size_t dest = (tok - 1) / K + 1;
550 const std::size_t r = (tok - 1) % K + 1;
551 std::vector<double> x = region_aggr(sn, caps[f], it.net);
552 x[r - 1] += 1.0;
553 // Head of line: this region's FIFO stays blocked even where a
554 // token behind the head would fit.
555 if (violates(caps[f], x)) continue;
556 const std::size_t isf_d = sn.stateful_index(dest);
557 if (isf_d == 0) continue;
558 const qn::EventOutcome<T> od =
559 qn::after_event(sn, dest, it.net.local[isf_d - 1], EventType::ARV, r);
560 if (od.space.empty()) continue;
561 for (std::size_t id = 0; id < od.space.size(); ++id) {
562 if (num_traits<T>::to_double(od.prob[id]) <= 0) continue;
563 Work<T> nx = it;
564 nx.net.local[isf_d - 1] = od.space[id];
565 nx.buf[f].erase(nx.buf[f].begin());
566 nx.prob = T(it.prob * od.prob[id]);
567 nx.arv.push_back(std::make_pair(isf_d, r));
568 nx.rel.push_back(std::make_pair(dest, r));
569 work.push_back(nx);
570 }
571 progressed = true;
572 }
573 if (progressed) continue;
574
575 if (it.pf != 0) {
576 // The cascade has settled, so the deferred class switch can be
577 // tested against a region occupancy that already reflects the
578 // departure which freed the old class's slot.
579 const std::size_t f = it.pf - 1;
580 std::vector<double> x = region_aggr(sn, caps[f], it.net);
581 x[it.pcls - 1] += 1.0;
582 Work<T> nx = it;
583 nx.pf = 0;
584 nx.admitted = false; // re-set below on the branches that admit it
585 if (violates(caps[f], x)) {
586 // A DROP class loses the switching job outright; a WAITQ one
587 // joins the tail.
588 if (it.pwaitq) {
589 if (tok_full(caps[f], nx.buf[f], it.pcls, K)) continue;
590 nx.buf[f].push_back((it.pdest - 1) * K + it.pcls);
591 }
592 work.push_back(nx);
593 continue;
594 }
595 const std::size_t isf_d = sn.stateful_index(it.pdest);
596 bool admitted = false;
597 if (isf_d != 0) {
598 const qn::EventOutcome<T> od = qn::after_event(
599 sn, it.pdest, it.net.local[isf_d - 1], EventType::ARV, it.pcls);
600 for (std::size_t id = 0; id < od.space.size(); ++id) {
601 if (num_traits<T>::to_double(od.prob[id]) <= 0) continue;
602 Work<T> ny = nx;
603 ny.net.local[isf_d - 1] = od.space[id];
604 ny.prob = T(it.prob * od.prob[id]);
605 ny.arv.push_back(std::make_pair(isf_d, it.pcls));
606 ny.admitted = true;
607 work.push_back(ny);
608 admitted = true;
609 }
610 }
611 if (!admitted) {
612 // The region had room but the destination's own state does
613 // not admit the job -- its station capacity, say -- so it
614 // parks rather than vanishing.
615 if (tok_full(caps[f], nx.buf[f], it.pcls, K)) continue;
616 nx.buf[f].push_back((it.pdest - 1) * K + it.pcls);
617 work.push_back(nx);
618 }
619 continue;
620 }
621
622 const T contrib = T(e.w * it.prob);
623 if (num_traits<T>::to_double(contrib) <= 0) continue;
624 Successor<T> s;
625 s.sync = a;
626 s.next.net = it.net;
627 s.next.buf = it.buf;
628 s.w = contrib;
629 s.arv = it.arv;
630 s.dep_isf = it.dep_isf;
631 s.dep_cls = it.dep_cls;
632 s.admitted = it.admitted;
633 s.rel = it.rel;
634 out.push_back(s);
635 }
636 };
637
638 for (std::size_t a = 0; a < sync.size(); ++a) {
639 const Sync<T>& sy = sync[a];
640 const std::size_t node_a = sy.active.node;
641 const std::size_t isf_a = sn.stateful_index(node_a);
642 if (isf_a == 0) continue;
643 const std::size_t cls_a = sy.active.cls;
644 const std::size_t stat_a = sn.nodes[node_a - 1].station;
645
646 // Immediate feedback (sn.immfeed): the departure half of a self-loop must
647 // run with no_promote or the fed-back job re-queues. See
648 // qn::immfeed_self_loop.
649 const qn::EventOutcome<T> oa =
650 qn::after_event(sn, node_a, net.local[isf_a - 1], sy.active.event, cls_a,
651 qn::immfeed_self_loop(sn, sy));
652 // A round-robin dispatcher decides the destination from its own pointer, as in solver_ctmc.h.
653 const bool rr_here = sy.active.event == EventType::DEP && sn.rr_var_slot(node_a, cls_a) != 0;
654 for (std::size_t ia = 0; ia < oa.space.size(); ++ia) {
655 // The active half's own share counts, as in solver_ctmc.h: SIRO's random promotion returns it below 1.
656 const T rate = T(oa.rate[ia] * oa.prob[ia]);
657 if (num_traits<T>::to_double(rate) <= 0) continue;
658
659 const std::size_t node_p = sy.passive.node;
660 if (node_p == local) {
661 Emission<T> e;
662 e.net = net;
663 e.net.local[isf_a - 1] = oa.space[ia];
664 e.buf = buf;
665 e.w = rate;
666 emit(a, e);
667 continue;
668 }
669 const std::size_t isf_p = sn.stateful_index(node_p);
670 if (isf_p == 0) continue;
671 const std::size_t cls_p = sy.passive.cls;
672 const std::size_t stat_p = sn.nodes[node_p - 1].station;
673 // The route is decided at departure and kept by a refused job: SDR, JSQ and SQ read the state the job leaves from,
674 // round-robin the pointer the active row carries once its departure advanced it. Neither reads the passive
675 // row, so the same weight applies whether the region admits, parks or drops the job, as in LDES.
676 T proute = sy.passive.statedep ? rt_now(sy.passive.rt_row, sy.passive.rt_col) : sy.passive.prob;
677 if (rr_here) {
678 const std::size_t nv = sn.nvars_of(node_a);
679 const std::vector<T>& arow = oa.space[ia];
680 std::size_t dest = 0;
681 if (arow.size() >= nv) {
682 const std::vector<T> var(arow.end() - nv, arow.end());
683 dest = sn.rr_dest(node_a, cls_a, var);
684 }
685 proute = (dest == node_p && sy.passive.cls == cls_a) ? num_traits<T>::from_int(1)
686 : num_traits<T>::from_int(0);
687 }
688 const T w = T(rate * proute);
689 if (num_traits<T>::to_double(w) <= 0) continue;
690 const std::size_t dep_isf = sy.active.event == EventType::DEP ? isf_a : 0;
691
692 // REGION ENTRY is the only place the caps are tested on the way
693 // in: the passive station is inside the region and the active
694 // node is not, so this transition raises the region's occupancy.
695 std::size_t blockedf = 0, droppedf = 0;
696 if (sy.passive.event == EventType::ARV && stat_p != 0) {
697 for (std::size_t f = 0; f < F; ++f) {
698 if (!caps[f].member[stat_p - 1]) continue;
699 if (stat_a != 0 && caps[f].member[stat_a - 1]) continue;
700 std::vector<double> xn = xf[f];
701 xn[cls_p - 1] += 1.0;
702 if (!violates(caps[f], xn)) continue;
703 if (caps[f].iswaitq[cls_p - 1])
704 blockedf = f + 1;
705 else
706 droppedf = f + 1;
707 break;
708 }
709 }
710
711 if (droppedf != 0) {
712 // DROP: the refused job is destroyed, so only the active
713 // half applies. It still departed, which is why the loss
714 // shows up downstream as ArvR - Tput.
715 Emission<T> e;
716 e.net = net;
717 e.net.local[isf_a - 1] = oa.space[ia];
718 e.buf = buf;
719 e.w = w;
720 e.dep_isf = dep_isf;
721 e.dep_cls = cls_a;
722 e.admitted = false;
723 emit(a, e);
724 continue;
725 }
726
727 // A class switch between two members of the same region: see the
728 // file header. Deferred, not tested here.
729 std::size_t switchf = 0;
730 if (blockedf == 0 && sy.passive.event == EventType::ARV && cls_p != cls_a &&
731 stat_a != 0 && stat_p != 0)
732 for (std::size_t f = 0; f < F; ++f)
733 if (caps[f].member[stat_a - 1] && caps[f].member[stat_p - 1]) {
734 switchf = f + 1;
735 break;
736 }
737
738 if (switchf != 0) {
739 Emission<T> e;
740 e.net = net;
741 e.net.local[isf_a - 1] = oa.space[ia];
742 e.buf = buf;
743 e.w = w;
744 e.dep_isf = dep_isf;
745 e.dep_cls = cls_a;
746 e.pf = switchf;
747 e.pcls = cls_p;
748 e.pdest = node_p;
749 e.pwaitq = caps[switchf - 1].iswaitq[cls_p - 1];
750 emit(a, e);
751 continue;
752 }
753
754 if (blockedf != 0) {
755 // The FIFO bound is a TRUNCATION of an open class's
756 // unbounded queue, not an error: the reference drops the
757 // transition, and so does this. It is the same kind of
758 // approximation the state-space cutoff already is.
759 if (tok_full(caps[blockedf - 1], buf[blockedf - 1], cls_p, K)) continue;
760 Emission<T> e;
761 e.net = net;
762 e.net.local[isf_a - 1] = oa.space[ia];
763 e.buf = buf;
764 e.buf[blockedf - 1].push_back((node_p - 1) * K + cls_p);
765 e.w = w;
766 e.dep_isf = dep_isf;
767 e.dep_cls = cls_a;
768 e.admitted = false;
769 emit(a, e);
770 continue;
771 }
772
773 const std::vector<T>& psrc = node_p == node_a ? oa.space[ia] : net.local[isf_p - 1];
774 const qn::EventOutcome<T> op = qn::after_event(sn, node_p, psrc, sy.passive.event, cls_p);
775 // No successor at the passive node is a BLOCKED arrival, the
776 // reference's true-BAS branch. Every model that declares true
777 // blocking has already been refused by name, so what remains is
778 // a destination refusing the job outside any region, and the
779 // transition simply does not fire.
780 for (std::size_t ip = 0; ip < op.space.size(); ++ip) {
781 if (num_traits<T>::to_double(op.prob[ip]) <= 0) continue;
782 Emission<T> e;
783 e.net = net;
784 e.net.local[isf_a - 1] = oa.space[ia];
785 e.net.local[isf_p - 1] = op.space[ip];
786 e.buf = buf;
787 e.w = T(w * op.prob[ip]);
788 e.dep_isf = dep_isf;
789 e.dep_cls = cls_a;
790 if (sy.passive.event == EventType::ARV)
791 e.arv.push_back(std::make_pair(isf_p, cls_p));
792 emit(a, e);
793 }
794 }
795 }
796}
797
798} // namespace waitq_detail
799
800/** True when the model declares a region that applies anything other than DROP. */
801template <class T>
803 for (std::size_t f = 0; f < sn.regions.size(); ++f)
804 for (std::size_t r = 0; r < sn.regions[f].rule.size(); ++r)
805 if (sn.regions[f].rule[r] != DropStrategy::DROP) return true;
806 return false;
807}
808
809/**
810 * The combinations the reference gates, plus the two this port cannot represent.
811 *
812 * The first two are the reference's own: each needs a semantics for what a
813 * parked token means that the reference declines to define. The routing check
814 * and the last two are this port's, and all three are about state that does not
815 * exist here rather than about semantics.
816 */
817template <class T>
819 if (!sn.transparam.empty())
820 throw UnsupportedError(ErrorKind{"Region"},
821 "SolverCTMC: a WAITQ finite capacity region is not supported together with stochastic "
822 "Petri net transitions; a firing is atomic across its arcs and has no single "
823 "destination to park a refused token against");
824 // The station blocks of ctmc_blocks.h (setup/delay-off, attempt levels) are
825 // served here as on the lattice path, through the same handlers, but only on
826 // the struct `qn::ctmc_station_blocks` prepared (`solver_ctmc_waitq_analyzer`
827 // does): a station that declares one without its block column would be
828 // walked as a plain queue. Server parallelism needs no block, and this walk
829 // is a reachability walk, which is what it needs.
830 for (std::size_t ind = 1; ind <= sn.nodes.size(); ++ind) {
831 std::string what;
832 if (qn::setup_layout(sn, ind).valid) what = "setup and delay-off";
833 else if (qn::attempts_layout(sn, ind).valid) what = "a finite retrial maxAttempts";
834 if (!what.empty() && qn::ctmc_tail_width(sn, ind) == 0)
835 throw InputError("SolverCTMC: the WAITQ walk was handed station '" + sn.nodes[ind - 1].name +
836 "', which declares " + what + ", without its CTMC station block; prepare "
837 "the struct with qn::ctmc_station_blocks first");
838 }
839 if (sn.has_fork() || !sn.fj.empty())
840 throw UnsupportedError(ErrorKind{"Region"},
841 "SolverCTMC: a WAITQ finite capacity region is not supported together with fork-join; "
842 "a forked task refused entry would park without its siblings, and the join has no rule "
843 "for a sibling that never arrived");
844 for (std::size_t i = 0; i < sn.nodes.size(); ++i) {
845 const qn::NodeDef& nd = sn.nodes[i];
846 for (std::size_t r = 0; r < nd.routing.size(); ++r) {
847 const lang::RoutingStrategy rs = nd.routing[r];
848 // The route is drawn at departure and a refused job keeps it (LDES), so the strategies the ordinary generator
849 // evaluates, the round-robin pointer and the per-state SDR/JSQ/SQ rows, carry over to the token FIFO
850 // unchanged, as in solver_ctmc_fcr_waitq.m.
855 continue;
856 throw UnsupportedError(ErrorKind{"Region"},
857 "SolverCTMC: a WAITQ finite capacity region is not supported together with the "
858 "routing strategy at node '" +
859 nd.name +
860 "'; the generator evaluates PROB, RAND, RROBIN, WRROBIN, SDR, JSQ and SQ routing only");
861 }
862 }
863 for (std::size_t f = 0; f < sn.regions.size(); ++f)
864 for (std::size_t r = 0; r < sn.regions[f].rule.size(); ++r) {
865 const DropStrategy d = sn.regions[f].rule[r];
866 if (d == DropStrategy::DROP || d == DropStrategy::WAITQ) continue;
867 throw UnsupportedError(ErrorKind{"Region"},
868 "SolverCTMC: finite capacity region " + std::to_string(f + 1) +
869 " applies a blocking rule other than DROP or WAITQ to class " +
870 std::to_string(r + 1) +
871 "; BAS, BBS and RSRD hold the job AT ITS SERVER, which needs a blocked-server "
872 "marker column in the node state that this port does not allocate");
873 }
874 // TRUE BAS BLOCKING IS ORTHOGONAL TO THE REGION RULE and is refused on its
875 // own terms. The reference holds the completing job at its server by setting
876 // the last column of the station's state row; `refresh_local_vars` here
877 // reserves that shared column for a Cache, a breakdown or a polling
878 // controller and never for a BAS marker, so there is no column to set and no
879 // handler that would release it. Voiding the departure instead is NOT
880 // equivalent: it frees the server to re-serve the same job, which for
881 // exponential service redraws the completion and understates throughput.
882 for (std::size_t i = 0; i < sn.droprule.size() && i < sn.stations.size(); ++i)
883 for (std::size_t r = 0; r < sn.droprule[i].size(); ++r) {
884 const DropStrategy d = sn.droprule[i][r];
885 if (d != DropStrategy::BAS && d != DropStrategy::BBS && d != DropStrategy::RSRD)
886 continue;
887 throw UnsupportedError(ErrorKind{"FiniteCapacity"},
888 "SolverCTMC: station '" + sn.stations[i].name +
889 "' applies true blocking (BAS/BBS/RSRD) to class " + std::to_string(r + 1) +
890 ", which holds the completing job at its server; this port allocates no "
891 "blocked-server marker in the node state, and voiding the departure instead would "
892 "let the server re-serve the same job and understate throughput");
893 }
894}
895
896/**
897 * Port of the reachability walk of `solver_ctmc_fcr_waitq.m`.
898 *
899 * The space is WALKED and not enumerated, for the reason an SPN is: no
900 * population marginal produces a state whose region FIFO is non-empty, so a
901 * lattice enumeration would emit only the empty-buffer states and every blocking
902 * transition would land outside the space.
903 */
904template <class T>
907
908 const std::size_t K = sn.nclasses;
909 const std::size_t NF = sn.stateful_nodes.size();
910 const T zero = num_traits<T>::from_int(0);
911
912 const std::vector<Sync<T>> sync = refresh_sync(sn);
913 std::vector<waitq_detail::RegionCaps<T>> caps = waitq_detail::extract_caps(sn);
914 const std::size_t F = caps.size();
915 const std::vector<std::size_t> cutoff = analyzer_detail::resolve_cutoff(sn, opt);
916 waitq_detail::resolve_lmax(sn, cutoff, caps);
917
918 // AT THE ENCODING WIDTH, not at the width of the initial marginal: the rows
919 // never grow during the walk, so a station seeded with the narrow buffer of
920 // its empty state can never hold more than nservers+1 jobs. See
921 // `max_row_width`.
922 WaitqState<T> init;
923 init.net = waitq_detail::wide_init_state(sn, cutoff);
924 init.buf.assign(F, std::vector<std::size_t>());
925 for (std::size_t f = 0; f < F; ++f)
926 if (waitq_detail::violates(caps[f], waitq_detail::region_aggr(sn, caps[f], init.net)))
927 throw InputError(
928 "SolverCTMC: the initial state violates the constraints of finite capacity region " +
929 std::to_string(f + 1) + "; the region cannot hold the model's initial population");
930
931 std::vector<WaitqState<T>> states;
932 states.push_back(init);
933 std::map<std::vector<double>, std::size_t> index;
934 index[waitq_detail::waitq_key(init)] = 0;
935 std::deque<std::size_t> frontier;
936 frontier.push_back(0);
937
938 // Triplets rather than a matrix, because the state count is not known until
939 // the walk has finished and a growing dense matrix would be recopied at
940 // every doubling.
941 std::vector<std::size_t> ta, ti, tj;
942 std::vector<T> tv;
943 // The events each arc carries, kept only for the LAL collect (see `Successor`).
944 LalCollect* collect = nullptr;
945 if constexpr (std::is_same<T, double>::value) collect = opt.lal_collect.get();
946 std::vector<bool> tadm;
947 std::vector<std::vector<std::pair<std::size_t, std::size_t>>> trel;
948 std::vector<std::vector<std::vector<T>>> arv, dep;
949 arv.push_back(std::vector<std::vector<T>>(NF, std::vector<T>(K, zero)));
950 dep.push_back(std::vector<std::vector<T>>(NF, std::vector<T>(K, zero)));
951
952 // Index an augmented state, appending it and its rate blocks when new.
953 const auto state_index = [&](const WaitqState<T>& ws) -> std::size_t {
954 const std::vector<double> key = waitq_detail::waitq_key(ws);
955 const typename std::map<std::vector<double>, std::size_t>::const_iterator it =
956 index.find(key);
957 if (it != index.end()) return it->second;
958 if (states.size() >= opt.state_max)
959 throw UnsupportedError(ErrorKind{"StateSpace"},
960 "SolverCTMC: the WAITQ state space exceeds the cap of " +
961 std::to_string(opt.state_max) +
962 " states; the region FIFO multiplies the space by its own occupancy");
963 states.push_back(ws);
964 arv.push_back(std::vector<std::vector<T>>(NF, std::vector<T>(K, zero)));
965 dep.push_back(std::vector<std::vector<T>>(NF, std::vector<T>(K, zero)));
966 index[key] = states.size() - 1;
967 frontier.push_back(states.size() - 1);
968 return states.size() - 1;
969 };
970
971 // The walk. `frontier` is consumed from the front, so states are expanded in
972 // discovery order and the numbering matches the reference's own
973 // breadth-first construction. The transition relation itself is
974 // `waitq_successors`, shared with the SSA serial engine so that the region
975 // discipline cannot differ between the exact solver and the simulator.
976 std::vector<waitq_detail::Successor<T>> succ;
977 while (!frontier.empty()) {
978 const std::size_t s = frontier.front();
979 frontier.pop_front();
980 const WaitqState<T> ws = states[s]; // by value: `states` grows below
981 waitq_detail::waitq_successors(sn, sync, caps, ws, succ);
982 for (std::size_t e = 0; e < succ.size(); ++e) {
983 const waitq_detail::Successor<T>& su = succ[e];
984 const std::size_t dst = state_index(su.next);
985 ta.push_back(su.sync);
986 ti.push_back(s);
987 tj.push_back(dst);
988 tv.push_back(su.w);
989 if (collect) {
990 tadm.push_back(su.admitted);
991 trel.push_back(su.rel);
992 }
993 if (su.dep_isf != 0) dep[s][su.dep_isf - 1][su.dep_cls - 1] += su.w;
994 for (std::size_t q = 0; q < su.arv.size(); ++q)
995 arv[s][su.arv[q].first - 1][su.arv[q].second - 1] += su.w;
996 }
997 }
998
999 const std::size_t n = states.size();
1000 WaitqResult<T> res;
1001 res.chain.Q = Matrix<T>(n, n, zero);
1002 res.chain.space.reserve(n);
1003 res.buf.reserve(n);
1004 for (std::size_t s = 0; s < n; ++s) {
1005 res.chain.space.push_back(states[s].net);
1006 res.buf.push_back(states[s].buf);
1007 }
1008 res.chain.arv_rates = arv;
1009 res.chain.dep_rates = dep;
1010 if (opt.keep_filtration) res.chain.filt.assign(sync.size(), Matrix<T>(n, n, zero));
1011 for (std::size_t e = 0; e < tv.size(); ++e) {
1012 res.chain.Q(ti[e], tj[e]) += tv[e];
1013 if (opt.keep_filtration) res.chain.filt[ta[e]](ti[e], tj[e]) += tv[e];
1014 }
1015 // THE LAL COLLECTION (python `_build_fcr_waitq_ssg(..., collect=)`): one
1016 // event per (action, outcome), so each arc carries the events that actually
1017 // happened on it. A refused passive is PARKED (it crossed the routing path
1018 // but arrived nowhere) and every job the release cascade let in is a
1019 // RELEASED arrival at its destination. This walk has no vanishing states:
1020 // it refuses fork-join and Petri-net transitions, and an immediate Router
1021 // departure is an ordinary (fast) arc of it, as in the chain it solves.
1022 if constexpr (std::is_same<T, double>::value) {
1023 if (collect) {
1024 std::map<std::tuple<std::size_t, bool, std::vector<std::pair<std::size_t, std::size_t>>>, std::size_t>
1025 group;
1026 collect->events.clear();
1027 collect->vanishing.clear();
1028 const std::size_t local = sn.nodes.size() + 1;
1029 for (std::size_t e = 0; e < tv.size(); ++e) {
1030 if (!(tv[e] > 0)) continue;
1031 const std::size_t a = ta[e];
1032 // admitted is meaningful only for a passive that is a node
1033 const bool parked = !tadm[e] && sync[a].passive.node != local;
1034 const auto key = std::make_tuple(a, parked, trel[e]);
1035 auto it = group.find(key);
1036 if (it == group.end()) {
1039 ev.index = a;
1040 ev.immediate = false;
1041 ev.parked = parked;
1042 ev.released = trel[e];
1043 collect->events.push_back(ev);
1044 it = group.emplace(key, collect->events.size() - 1).first;
1045 }
1046 collect->events[it->second].arcs.push_back(std::make_tuple(ti[e], tj[e], tv[e]));
1047 }
1048 collect->sn = std::make_shared<const NetworkStruct<double>>(sn);
1049 collect->space = res.chain.space;
1050 collect->buf = res.buf;
1051 collect->sync = sync;
1052 collect->gsync.clear();
1053 collect->fjsync.clear();
1054 collect->initial_index = 0; // the walk stores the initial state as row 0
1055 collect->filled = true;
1056 }
1057 }
1058 // A refused arrival that leaves every node unchanged is a self-loop, and the
1059 // diagonal has to cancel it exactly as it does in the default generator.
1060 make_infgen(res.chain.Q);
1061 return res;
1062}
1063
1064/**
1065 * The mean number of parked jobs per class, over a stationary law.
1066 *
1067 * IT IS IN NO QLen. A parked job is in no station and in no region, so
1068 * `solver_ctmc_avg_from_pi` cannot see it and the model's population is
1069 * conserved only once this is added back. That is the JMT report convention,
1070 * not an omission.
1071 */
1072template <class T>
1073std::vector<T> ctmc_waitq_parked(const NetworkStruct<T>& sn, const WaitqResult<T>& r,
1074 const std::vector<T>& pi) {
1075 const std::size_t K = sn.nclasses;
1076 std::vector<T> out(K, num_traits<T>::from_int(0));
1077 for (std::size_t s = 0; s < r.buf.size() && s < pi.size(); ++s)
1078 for (std::size_t f = 0; f < r.buf[s].size(); ++f)
1079 for (std::size_t j = 0; j < r.buf[s][f].size(); ++j) {
1080 const std::size_t cls = (r.buf[s][f][j] - 1) % K + 1;
1081 out[cls - 1] += pi[s];
1082 }
1083 return out;
1084}
1085
1086/** A solved WAITQ model: the usual CTMC solution, plus what the FIFOs hold. */
1087template <class T>
1090 std::vector<std::vector<std::vector<std::size_t>>> buf;
1091 std::vector<T> parked; ///< mean parked jobs per class
1092};
1093
1094/**
1095 * Build the WAITQ chain, solve it, and map it onto the same means every other
1096 * CTMC path reports.
1097 *
1098 * NO WEAKLY-CONNECTED-COMPONENT STEP, unlike `solver_ctmc_analyzer`. That step
1099 * exists because the lattice enumeration emits states the dynamics cannot reach;
1100 * this walk starts at the initial state and applies the same handlers the
1101 * generator does, so every state it holds is reachable by construction and
1102 * restricting to a component could only remove states the model does occupy.
1103 */
1104template <class T>
1106 check_method(opt.method);
1107 WaitqSolution<T> out;
1108 // THE STATION BLOCKS FIRST, as `solve_struct` prepares them for the lattice
1109 // and reachable paths (python builds the region walk after `ctmc_setup` and
1110 // `ctmc_retrial_attempts`): setup/delay-off and attempt-level stations walk
1111 // and decode on the widened rows of `sn_blk`.
1112 NetworkStruct<T> sn_blk;
1113 bool blk_reach = false;
1114 const bool blk = qn::ctmc_station_blocks(sn, sn_blk, blk_reach);
1115 const NetworkStruct<T>& sw = blk ? sn_blk : sn;
1116 if (blk) out.sol.solved_sn = std::make_shared<const NetworkStruct<T>>(sn_blk);
1117 const WaitqResult<T> r = solver_ctmc_waitq(sw, opt);
1118 out.sol.cutoff = analyzer_detail::resolve_cutoff(sw, opt);
1119 // the LAL embedding stops at the collected arcs, before any solve
1120 if (opt.lal_collect && opt.lal_collect->filled && opt.lal_collect->stop) return out;
1121 // Seeded from the initial state, which the walk stores as row 0: a reducible chain (a synchronous-call deadlock,
1122 // say) has several closed classes, and only the one the model starts in is its answer, as in MATLAB ctmc_stationary.
1123 out.sol.pi = ctmc_stationary(r.chain.Q, 0).pi;
1124 out.sol.avg = solver_ctmc_avg_from_pi(sw, r.chain, out.sol.pi);
1125 out.sol.chain = r.chain;
1126 out.sol.actualmethod = opt.method;
1127 out.buf = r.buf;
1128 out.parked = ctmc_waitq_parked(sw, r, out.sol.pi);
1129 return out;
1130}
1131
1132/** A CTMC solve routed to whichever path the model's region rules require. */
1133template <class T>
1136 std::vector<std::vector<std::vector<std::size_t>>> buf; ///< empty off the WAITQ path
1137 std::vector<T> parked; ///< mean parked jobs per class; empty off the WAITQ path
1138 bool waitq = false;
1139};
1140
1141/**
1142 * The entry point a caller who does not know which path a model needs should
1143 * use: pick the WAITQ walk when a region asks for anything other than DROP, and
1144 * the lattice analyzer otherwise.
1145 *
1146 * IT IS A SEPARATE ENTRY POINT AND NOT A CHANGE TO `solver_ctmc_run_analyzer`. That
1147 * function is the DEFAULT path, and a WAITQ region reaching it is a defect it
1148 * must keep reporting: its generator carries no token buffer, so it would solve
1149 * the region as DROP. The dispatch is therefore placed here, where both paths
1150 * are in scope, and the default path keeps refusing by name.
1151 *
1152 * `ctmc_check_support` runs on both branches. `ctmc_check_waitq_support` covers
1153 * fork-join and true blocking on its own and needs no entry for class or joint
1154 * dependence: this generator never scales a rate itself, it walks on whatever
1155 * `EventOutcome::rate` the shared `qn::after_event` -> `after_event_station`
1156 * dispatcher hands back (state_events.h:1591, :1675), and `cd_factor` is
1157 * folded into that rate INSIDE the dispatcher (state_events.h:831-832, :1298)
1158 * for every caller alike. `solver_ctmc.h`'s default generator calls the same
1159 * `qn::after_event`, so the two paths scale identically by construction, not
1160 * by coincidence. GREPPING THIS FILE FOR `cd_factor` FINDS NOTHING BY DESIGN --
1161 * that is not a missing call, it is this generator having no rate arithmetic
1162 * of its own to put one in. Trace the dispatcher, not the grep, before
1163 * concluding otherwise. MATLAB has the identical shape for the identical
1164 * reason: `solver_ctmc_fcr_waitq.m` computes every rate through
1165 * `State.afterEventHashed`, which calls the same `State.afterEvent` the
1166 * default generator uses, so it too carries no cdscaling/jdscaling text of
1167 * its own.
1168 */
1169template <class T>
1172 // The WAITQ branch short-circuits below and would otherwise never see the
1173 // gate that solver_ctmc_analyzer applies on the default path.
1174 qn::feature_gate("SolverCTMC", qn::ctmc_feature_set(opt.method), sn);
1176 if (!ctmc_has_waitq_region(sn)) {
1178 return out;
1179 }
1181 out.sol = w.sol;
1182 out.buf = w.buf;
1183 out.parked = w.parked;
1184 out.waitq = true;
1185 return out;
1186}
1187
1188/** Solve on whichever path applies and format, mirroring `solver_ctmc_run_analyzer`. */
1189template <class T>
1193
1194} // namespace ctmc
1195} // namespace line
1196
1197// Complete: fes_solved_tables.h, skipped if it was reached while this header
1198// was open (see its top), can now be read.
1199#define LINE_SOLVERS_CTMC_SOLVER_CTMC_WAITQ_DONE
1201
1202#endif // LINE_SOLVERS_CTMC_SOLVER_CTMC_WAITQ_H
InputError(const std::string &what)
Definition error.h:105
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
Steady-state distribution of a continuous-time Markov chain.
Port of matlab/src/solvers/CTMC/ctmc_stationary.m: the single entry point for the stationary distribu...
The exception types the port throws.
FES rates from a non-product-form solve of the isolated subnetwork.
Dense matrix and non-owning view.
CtmcSolution< T > solver_ctmc_analyzer(const NetworkStruct< T > &sn_in, const CtmcOptions &opt, const CtmcStationaryHook< T > &stationary=CtmcStationaryHook< T >())
Port of solver_ctmc_analyzer.m plus the fork-join wrapper of @@SolverCTMC/runAnalyzer....
void check_method(const std::string &method)
Port of runAnalyzerChecks' method gate.
void ctmc_check_support(const NetworkStruct< T > &sn)
void make_infgen(Matrix< T > &Q)
Port of ctmc_makeinfgen: turn an off-diagonal rate matrix into a generator.
mva::AvgResult< T > solver_ctmc_avg_table(const NetworkStruct< T > &sn, const CtmcSolution< T > &d, const std::string &method)
Port of @@SolverCTMC/runAnalyzer.m's result assembly: solve, then apply the metric filter @@NetworkSo...
CtmcAvg< T > solver_ctmc_avg_from_pi(const NetworkStruct< T > &sn, const CtmcResult< T > &r, const std::vector< T > &pivec, bool stationary=true)
Port of solver_ctmc_avg_from_pi: map a state distribution to mean metrics.
CtmcAnySolution< T > solver_ctmc_analyzer_any(const NetworkStruct< T > &sn, const CtmcOptions &opt)
The entry point a caller who does not know which path a model needs should use: pick the WAITQ walk w...
CtmcStationaryResult< T > ctmc_stationary(const Matrix< T > &Q, std::size_t init_index=static_cast< std::size_t >(-1))
std::vector< T > ctmc_waitq_parked(const NetworkStruct< T > &sn, const WaitqResult< T > &r, const std::vector< T > &pi)
The mean number of parked jobs per class, over a stationary law.
WaitqSolution< T > solver_ctmc_waitq_analyzer(const NetworkStruct< T > &sn, const CtmcOptions &opt)
Build the WAITQ chain, solve it, and map it onto the same means every other CTMC path reports.
WaitqResult< T > solver_ctmc_waitq(const NetworkStruct< T > &sn, const CtmcOptions &opt)
Port of the reachability walk of solver_ctmc_fcr_waitq.m.
bool ctmc_has_waitq_region(const NetworkStruct< T > &sn)
True when the model declares a region that applies anything other than DROP.
mva::AvgResult< T > solver_ctmc_run_analyzer_any(const NetworkStruct< T > &sn, const CtmcOptions &opt)
Solve on whichever path applies and format, mirroring solver_ctmc_run_analyzer.
void ctmc_check_waitq_support(const NetworkStruct< T > &sn)
The combinations the reference gates, plus the two this port cannot represent.
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
DropStrategy
Blocking and loss rules, with the values of MATLAB DropStrategy.
Definition lang_types.h:465
RoutingStrategy
Routing strategies, with the values of MATLAB RoutingStrategy.
Definition lang_types.h:430
@ SDR
Krzesinski (1987) product-form state-dependent routing.
Definition lang_types.h:439
double var(const std::vector< double > &x)
Sample variance with the n - 1 denominator.
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
bool immfeed_self_loop(const NetworkStruct< T > &sn, const Sync< T > &sy)
True when a synchronization is an IMMEDIATE-FEEDBACK SELF-LOOP: a departure whose passive half is an ...
AttemptsLayout attempts_layout(const NetworkStruct< T > &sn, std::size_t ind)
The finite-attempt retrial of node ind as the model declares it, active or not.
FeatureSet ctmc_feature_set(const std::string &method)
SolverCTMC.getFeatureSet, the reference's 104 MATLAB names in full.
SetupInfo< T > setup_layout(const NetworkStruct< T > &sn, std::size_t ind)
The setup/delay-off layout of node ind as the model declares it, whether or not the block is active.
bool ctmc_station_blocks(const NetworkStruct< T > &in, NetworkStruct< T > &out, bool &reachable)
Prepare the copy SolverCTMC solves: validate the setup/delay-off, finite-attempt and server-paralleli...
EventOutcome< T > after_event(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventType event, std::size_t cls, bool no_promote=false, const T &aux_rate=num_traits< T >::from_int(0))
Port of State.afterEvent: the successors of one event at one NODE.
std::vector< double > parallelism_of(const NetworkStruct< T > &sn, std::size_t ind)
Per-class server degrees n_r (all >= 1) of node ind, or empty when every class seizes one server (pyt...
void feature_gate(const std::string &solver, const FeatureSet &declared, const NetworkStruct< T > &sn, const std::string &requested_method="", const std::string &resolved_method="")
runAnalyzerChecks: refuse a model the solver does not declare, by name.
std::pair< T, std::vector< T > > to_marginal_aggr(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &state_i)
Port of State.toMarginalAggr: the job counts of one node's state row, without the per-phase detail to...
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
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
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
Port of solver_ctmc.m: the infinitesimal generator of a queueing network, assembled from the enumerat...
Port of solver_ctmc_analyzer.m and the parts of @@SolverCTMC/runAnalyzer.m that surround one solve: t...
Finite Capacity Regions in SolverCTMC: the DROP rule, as a filter on the enumerated state space,...
The DECLARED side of the gate: one feature set per solver.
Port of the MATLAB +State package: the encoding that turns a station's state row into marginal job co...
Port of the event half of MATLAB's +State package: the successor states an event produces at one node...
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
A CTMC solve routed to whichever path the model's region rules require.
std::vector< T > parked
mean parked jobs per class; empty off the WAITQ path
std::vector< std::vector< std::vector< std::size_t > > > buf
empty off the WAITQ path
The SolverCTMC knobs this port honours.
The generator, the state space it is indexed by, and the event rates.
Definition solver_ctmc.h:64
Everything one CTMC solve produces.
The internal collect sink of the LAL embedding (python options.collect).
std::vector< qn::Sync< double > > sync
std::size_t initial_index
std::vector< LalCollectedEvent > events
std::shared_ptr< const qn::NetworkStruct< double > > sn
std::vector< std::vector< std::vector< std::size_t > > > buf
The region FIFOs of each state, per region (WaitqState::buf), when the chain is the WAITQ region walk...
std::vector< qn::FjSync< double > > fjsync
std::vector< qn::GlobalSync< double > > gsync
std::vector< qn::NetState< double > > space
std::vector< std::size_t > vanishing
One per-event arc set collected for the LAL embedding of a Network.
bool parked
Region records of a Sync event built by the WAITQ region walk (solver_ctmc_waitq, python RegionArriva...
std::vector< std::pair< std::size_t, std::size_t > > released
The chain the WAITQ walk produces, alongside the FIFOs its states carry.
std::vector< std::vector< std::vector< std::size_t > > > buf
per state, per region
CtmcResult< T > chain
Q, the net halves, rates, filt.
A solved WAITQ model: the usual CTMC solution, plus what the FIFOs hold.
std::vector< std::vector< std::vector< std::size_t > > > buf
std::vector< T > parked
mean parked jobs per class
One augmented state: the network state, plus the token FIFO of every region.
std::vector< std::vector< std::size_t > > buf
The metrics getAvg returns, after filtering.
One network state: the per-stateful-node local rows it is composed of.
Definition state.h:3022
A node of the network.
std::vector< RoutingStrategy > routing
sn.routing, per class.