LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_ctmc.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_H
6#define LINE_SOLVERS_CTMC_SOLVER_CTMC_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * Port of `solver_ctmc.m`: the infinitesimal generator of a queueing network,
12 * assembled from the enumerated state space and the synchronization list.
13 *
14 * THE ASSEMBLY. Every transition of the chain is one SYNCHRONIZATION: an active
15 * event that sets the rate, and a passive event that says where the job lands.
16 * For each (synchronization, state) pair the active handler is applied at its
17 * node, the passive handler at its node, and the two local successors are
18 * spliced back into a full network state whose index gives the column. The
19 * generator entry is rate * probability, accumulated -- one (s, ns) pair can be
20 * reached by several synchronizations, and each contributes.
21 *
22 * WHY THE DIAGONAL COMES LAST. Self-loops are generated deliberately (a lost
23 * arrival is one), and they must cancel: `ctmc_makeinfgen` drops the diagonal
24 * and then sets it to minus the row sum, so a self-loop contributes nothing to
25 * the balance equations while the event still fired for rate-counting purposes.
26 */
27
28#include <cmath>
29#include <cstddef>
30#include <functional>
31#include <map>
32#include <memory>
33#include <set>
34#include <tuple>
35#include <type_traits>
36#include <utility>
37#include <vector>
38
40#include "line/lang/qn/state.h"
44#include "line/util/error.h"
47#include "line/util/lu.h"
48#include "line/util/matrix.h"
49
50namespace line {
51namespace ctmc {
52
53using qn::EventOutcome;
54using qn::NetState;
55using qn::NetworkStruct;
56using qn::Sync;
57using lang::EventType;
58using lang::GlobalConstants;
59using lang::NodeType;
61
62/** The generator, the state space it is indexed by, and the event rates. */
63template <class T>
64struct CtmcResult {
65 Matrix<T> Q; ///< (n x n) infinitesimal generator
66 std::vector<NetState<T>> space; ///< row i of Q is space[i]
67 /**
68 * `arvRates` / `depRates`, indexed [state][stateful-1][class-1]: the total
69 * rate of arrivals into, and departures out of, each stateful node in each
70 * class, from each state. They are accumulated per synchronization rather
71 * than read off Q, because Q has already summed the contributions of every
72 * synchronization into one entry and they cannot be separated afterwards.
73 */
74 std::vector<std::vector<std::vector<T>>> arv_rates, dep_rates;
75 /**
76 * `Dfilt`, MATLAB's EVENT FILTRATION: `filt[a]` holds only the rates that
77 * synchronization `a` contributed, so `sum_a filt[a]` is the off-diagonal
78 * part of Q.
79 *
80 * IT CANNOT BE RECOVERED FROM Q, which is why it is carried rather than
81 * recomputed: Q has already summed every synchronization's contribution
82 * into one entry. The response-time CDF is built by splitting the generator
83 * on ONE event -- the tagged job's arrival, then its departure -- into a
84 * MAP (Q - D1, D1), and that split needs the per-event matrix.
85 *
86 * Empty unless `solver_ctmc` was asked for it: it costs one n x n matrix per
87 * synchronization, which on a model with many routing pairs dwarfs Q itself.
88 */
89 std::vector<Matrix<T>> filt;
90 /**
91 * The DERIVED START and PREEMPT filtrations, indexed [station-1][class-1]:
92 * the rate at which a transition starts a class-r service at station i, and
93 * the rate at which it pushes a class-r job in service back into the buffer.
94 *
95 * They are NOT part of `filt`, which pairs one-to-one with the
96 * synchronization list and whose sum is the off-diagonal of Q: a START rides
97 * on the SAME arc as the ARV or DEP that causes it, so adding it there would
98 * double-count the generator. Filled whenever `filt` is.
99 */
100 std::vector<std::vector<Matrix<T>>> start_filt, preempt_filt;
101 /**
102 * `Qimm`, the IMMEDIATE-ONLY part of Q: the arcs contributed by a Router or
103 * Fork pass-through, by a Join firing on an FJ-augmented struct, and by an
104 * SPN ENABLE or an IMMEDIATE-mode firing. Empty when the model has no such
105 * source.
106 *
107 * It exists for the VANISHING-ROW PURGE. A zero-sojourn state is left the
108 * instant it is entered, so a timed arc out of one describes an event that
109 * cannot occur; the purge replaces such a row by its immediate part. Q has
110 * already summed the two together, so the split cannot be recovered from it
111 * afterwards -- the same reason `filt` is carried rather than recomputed.
112 */
114 /**
115 * The parts of `arv_rates` / `dep_rates` contributed by those same immediate
116 * sources. Kept alongside the totals for two reasons, both from
117 * `solver_ctmc.m`: the purge has to restate a vanishing row's rates as its
118 * immediate part, and the RATE COMPLEMENT applies to the immediate part
119 * alone -- an event that fires only from vanishing states would otherwise be
120 * lost when those rows are eliminated. Empty when `Qimm` is.
121 */
122 std::vector<std::vector<std::vector<T>>> arv_rates_imm, dep_rates_imm;
123 /**
124 * The rows the purge restated, i.e. the vanishing states that `Qimm` gave an
125 * immediate exit. `ctmc_eliminate_vanishing` complements exactly these out;
126 * carrying them avoids re-running the predicate, which costs one event
127 * evaluation per (state, source).
128 */
129 std::vector<std::size_t> vanishing;
130};
131
132namespace ctmc_detail {
133
134/** The flattened key of a network state, for exact index lookup. */
135template <class T>
136std::vector<double> state_key(const NetState<T>& ns) {
137 std::vector<double> key;
138 for (std::size_t i = 0; i < ns.local.size(); ++i) {
139 // The separator keeps two different splits of the same concatenation
140 // from colliding, which a plain flatten would allow.
141 key.push_back(-2.0);
142 for (std::size_t j = 0; j < ns.local[i].size(); ++j)
143 key.push_back(num_traits<T>::to_double(ns.local[i][j]));
144 }
145 return key;
146}
147
148/**
149 * The largest per-class count any single stateful node holds in a state.
150 *
151 * The peak and not the sum, because the bound it feeds is per node.
152 *
153 * A TRANSITION IS SKIPPED, not counted. Its row is per MODE -- idle servers,
154 * firing phases, fired counts -- so the leading columns `to_marginal_aggr`
155 * would read as class counts are mode counts, and an infinite-server mode
156 * carries MaxInt there. It holds no jobs; the tokens are in the places.
157 */
158template <class T>
159std::vector<double> state_peak_occupancy(const NetworkStruct<T>& sn, const NetState<T>& st) {
160 std::vector<double> pk(sn.nclasses, 0.0);
161 const std::vector<std::size_t>& sfn = sn.stateful_nodes;
162 for (std::size_t f = 0; f < sfn.size() && f < st.local.size(); ++f) {
163 if (sn.nodes[sfn[f] - 1].nodetype == NodeType::Transition) continue;
164 const std::pair<T, std::vector<T>> mg = qn::to_marginal_aggr(sn, sfn[f], st.local[f]);
165 for (std::size_t r = 0; r < sn.nclasses && r < mg.second.size(); ++r) {
166 const double v = num_traits<T>::to_double(mg.second[r]);
167 if (v > pk[r]) pk[r] = v;
168 }
169 }
170 return pk;
171}
172
173/**
174 * True when no stateful node holds more of an OPEN class than `lim` allows.
175 *
176 * PER NODE AND NOT IN TOTAL, which is the reference's `capacityc(ind,r)` of
177 * `State.spaceGeneratorNodes`: an open class is capped at the cutoff AT EACH
178 * node. A total bound is wrong for an SPN whose firings do not conserve tokens
179 * -- `spn_open_sevenplaces` has a mode consuming one token and producing two --
180 * because the sum then crosses the bound on a firing that no place overflows,
181 * the arc vanishes, and the truncated chain absorbs at the boundary and reports
182 * Tput 0. A per-node bound censors only where a place itself overflows.
183 */
184template <class T>
185bool within_cutoff(const NetworkStruct<T>& sn, const NetState<T>& st,
186 const std::vector<double>& njobs, const std::vector<std::size_t>& lim,
187 const std::vector<std::vector<std::size_t>>& lim_mat =
188 std::vector<std::vector<std::size_t>>()) {
189 const std::vector<std::size_t>& sfn = sn.stateful_nodes;
190 for (std::size_t f = 0; f < sfn.size() && f < st.local.size(); ++f) {
191 if (sn.nodes[sfn[f] - 1].nodetype == NodeType::Transition) continue;
192 // The reference's cutoff may be a (station x class) MATRIX, in which
193 // case the bound at THIS node is its own row rather than the per-class
194 // maximum; a node with no station (Cache, Router) keeps the vector.
195 const std::size_t ist = sn.nodes[sfn[f] - 1].station;
196 const std::pair<T, std::vector<T>> mg = qn::to_marginal_aggr(sn, sfn[f], st.local[f]);
197 for (std::size_t r = 0; r < sn.nclasses && r < njobs.size(); ++r) {
198 if (std::isfinite(njobs[r])) continue;
199 std::size_t bound = r < lim.size() ? lim[r] : 0;
200 if (!lim_mat.empty() && ist != 0 && ist - 1 < lim_mat.size() &&
201 r < lim_mat[ist - 1].size())
202 bound = lim_mat[ist - 1][r];
203 if (bound == 0) continue;
204 if (r < mg.second.size() &&
205 num_traits<T>::to_double(mg.second[r]) > static_cast<double>(bound))
206 return false;
207 }
208 }
209 return true;
210}
211
212/**
213 * Accumulate the START/PREEMPT annotation of one successor row into the derived
214 * filtrations of the station behind NODE. W is the same weight the caller added
215 * to Q and to `filt`, so the filtration integrates rate * count and pi*F*e is a
216 * rate of starts (or of preemptions) per unit time.
217 */
218template <class T, class R>
219inline void add_aux_filt(R& res, const NetworkStruct<T>& sn, std::size_t node, std::size_t s,
220 std::size_t ns, const T& w, const qn::EventOutcome<T>& oc,
221 std::size_t row) {
222 if (num_traits<T>::to_double(w) == 0) return;
223 if (node == 0 || node > sn.nodes.size()) return;
224 const std::size_t ist = sn.nodes[node - 1].station;
225 if (ist == 0 || ist > res.start_filt.size()) return;
226 if (row < oc.start.size())
227 for (std::size_t j = 0; j < oc.start[row].size(); ++j) {
228 const std::size_t cls = oc.start[row][j];
229 if (cls >= 1 && cls <= res.start_filt[ist - 1].size())
230 res.start_filt[ist - 1][cls - 1](s, ns) += w;
231 }
232 if (row < oc.preempt.size())
233 for (std::size_t j = 0; j < oc.preempt[row].size(); ++j) {
234 const std::size_t cls = oc.preempt[row][j];
235 if (cls >= 1 && cls <= res.preempt_filt[ist - 1].size())
236 res.preempt_filt[ist - 1][cls - 1](s, ns) += w;
237 }
238}
239
240/**
241 * Solve (-Q22) X = B, one elimination shared by every column.
242 *
243 * The vanishing machinery needs the SAME solve three times over -- inside the
244 * complement, once per event filtration and once per rate vector -- so the
245 * censored block is factorized once and back-substituted per right-hand side.
246 * `ctmc_stochcomp` performs its own factorization for S; this is the one every
247 * OTHER right-hand side rides on.
248 */
249template <class T>
250Matrix<T> censored_solve(const Matrix<T>& Q22, const Matrix<T>& B) {
251 const std::size_t nd = Q22.rows();
252 if (B.rows() != nd) throw InputError("censored_solve: the right-hand side is misshapen");
253 Matrix<T> A(nd, nd, num_traits<T>::from_int(0));
254 for (std::size_t a = 0; a < nd; ++a)
255 for (std::size_t b = 0; b < nd; ++b) A(a, b) = T(-Q22(a, b));
256 const std::vector<std::size_t> piv = lu_factor(A);
257 Matrix<T> X = B;
258 std::vector<T> rhs(nd);
259 for (std::size_t c = 0; c < B.cols(); ++c) {
260 for (std::size_t d = 0; d < nd; ++d) rhs[d] = B(d, c);
261 lu_solve(A, piv, rhs);
262 for (std::size_t d = 0; d < nd; ++d) X(d, c) = rhs[d];
263 }
264 return X;
265}
266
267/**
268 * Complement ONE filtration onto the tangible states:
269 * Dnew = D(nonimm, nonimm) + Q12 (-Q22)^-1 D(imm, nonimm)
270 *
271 * All right-hand sides of one matrix go through a single elimination, since the
272 * censored block is the same for every filtration in the model.
273 */
274template <class T>
275Matrix<T> complement_one_filt(const Matrix<T>& D, const std::vector<std::size_t>& nonimm,
276 const std::vector<std::size_t>& imm,
277 const mc::StochCompResult<T>& sc) {
278 const T zero = num_traits<T>::from_int(0);
279 const std::size_t nk = nonimm.size(), nd = imm.size();
280 Matrix<T> out(nk, nk, zero);
281 for (std::size_t a = 0; a < nk; ++a)
282 for (std::size_t b = 0; b < nk; ++b) out(a, b) = D(nonimm[a], nonimm[b]);
283 if (nd == 0) return out;
284 Matrix<T> B(nd, nk, zero);
285 bool any = false;
286 for (std::size_t d = 0; d < nd; ++d)
287 for (std::size_t b = 0; b < nk; ++b) {
288 B(d, b) = D(imm[d], nonimm[b]);
289 if (num_traits<T>::to_double(B(d, b)) != 0) any = true;
290 }
291 if (!any) return out;
292 const Matrix<T> X = censored_solve(sc.Q22, B);
293 for (std::size_t a = 0; a < nk; ++a)
294 for (std::size_t b = 0; b < nk; ++b) {
295 T acc = zero;
296 for (std::size_t d = 0; d < nd; ++d) acc = T(acc + sc.Q12(a, d) * X(d, b));
297 out(a, b) = T(out(a, b) + acc);
298 }
299 return out;
300}
301
302/** Apply `complement_one_filt` to the event, START and PREEMPT filtrations. */
303template <class T, class R>
304void complement_filtrations(R& res, const std::vector<std::size_t>& nonimm,
305 const std::vector<std::size_t>& imm,
306 const mc::StochCompResult<T>& sc) {
307 for (std::size_t a = 0; a < res.filt.size(); ++a)
308 res.filt[a] = complement_one_filt(res.filt[a], nonimm, imm, sc);
309 for (std::size_t i = 0; i < res.start_filt.size(); ++i)
310 for (std::size_t r = 0; r < res.start_filt[i].size(); ++r)
311 res.start_filt[i][r] = complement_one_filt(res.start_filt[i][r], nonimm, imm, sc);
312 for (std::size_t i = 0; i < res.preempt_filt.size(); ++i)
313 for (std::size_t r = 0; r < res.preempt_filt[i].size(); ++r)
314 res.preempt_filt[i][r] = complement_one_filt(res.preempt_filt[i][r], nonimm, imm, sc);
315}
316
317} // namespace ctmc_detail
318
319/**
320 * Port of `ctmc_makeinfgen`: turn an off-diagonal rate matrix into a generator.
321 *
322 * The diagonal is discarded first and then set to minus the row sum, so any
323 * self-loop that was accumulated cancels exactly.
324 */
325template <class T>
327 const T zero = num_traits<T>::from_int(0);
328 for (std::size_t i = 0; i < Q.rows(); ++i) Q(i, i) = zero;
329 for (std::size_t i = 0; i < Q.rows(); ++i) {
330 T s = zero;
331 for (std::size_t j = 0; j < Q.cols(); ++j) s += Q(i, j);
332 Q(i, i) = T(-s);
333 }
334}
335
336template <class T>
337Matrix<T> ctmc_state_space_aggr(const NetworkStruct<T>& sn, const std::vector<NetState<T>>& space);
338
339// Defined in solver_ctmc_fcr.h, which is included at the foot of this header.
340template <class T>
341bool ctmc_region_admissible(const NetworkStruct<T>& sn, const std::vector<T>& nir);
342
343/**
344 * Tabulates the globally state-dependent rate scaling phi(n) declared through
345 * `set_global_dependence`, ONE evaluation per state.
346 *
347 * Returns an (nstates x nstations*nclasses) matrix, row-major in (station,
348 * class), of the scaling applying at each state; empty when the model declares
349 * no global dependence. Evaluating once per state rather than per transition is
350 * the whole point: phi may be expensive (a bandwidth-sharing allocation solves a
351 * convex program per call), and within a state it is a CONSTANT multiplying every
352 * rate there, which is why it factors out of the generator assembly below.
353 */
354template <class T>
355Matrix<T> ctmc_gd_factor(const NetworkStruct<T>& sn, const std::vector<NetState<T>>& space) {
356 const T zero = num_traits<T>::from_int(0);
357 if (!static_cast<bool>(sn.gdscaling)) return Matrix<T>(0, 0, zero);
358 if (!sn.regions.empty())
359 throw InputError(
360 "setGlobalDependence cannot be combined with finite capacity regions: the region "
361 "generator builds its own transitions and would ignore the scaling");
362 const std::size_t M = sn.stations.size(), K = sn.nclasses, n = space.size();
363 const std::size_t max_entries = 30000000u;
364 if (n * M * K > max_entries)
365 throw InputError(
366 "the global dependence table would exceed the state budget; lower the cutoff");
367 const Matrix<T> aggr = ctmc_state_space_aggr(sn, space);
368 Matrix<T> out(n, M * K, num_traits<T>::from_int(1));
369 std::vector<T> npop(M * K, zero);
370 for (std::size_t s = 0; s < n; ++s) {
371 for (std::size_t i = 0; i < M * K; ++i) npop[i] = aggr(s, i);
372 const std::vector<T> v = sn.gdscaling(npop);
373 for (std::size_t i = 0; i < M; ++i)
374 for (std::size_t r = 0; r < K; ++r) {
375 const T f = v.size() == 1 ? v[0] : (v.size() == M ? v[i] : v[i * K + r]);
376 if (!(num_traits<T>::to_double(f) >= 0))
377 throw InputError(
378 "the global dependence handle returned a non-finite or negative scaling");
379 out(s, i * K + r) = f;
380 }
381 }
382 return out;
383}
384
385/**
386 * Port of `ctmc_find_vanishing_states` (`solver_ctmc.m:928`): the indices of the
387 * VANISHING (zero-sojourn) global states.
388 *
389 * A state is vanishing when the model leaves it at the `GlobalConstants`
390 * Immediate scale rather than at a modelled rate, so its sojourn is an artefact
391 * of realising "instantaneous" as a very fast exponential. Four sources, which
392 * are the whole list:
393 *
394 * - a Router or Fork holding a job. Neither performs service: the job is in
395 * transit and leaves on the next event.
396 * - a Join whose sibling set is COMPLETE for some original class, so the
397 * rendezvous can fire. Only on an FJ-augmented struct -- without the tag
398 * classes a Join buffers nothing and its departures are timed elsewhere.
399 * - an SPN marking from which an ENABLE moves the Transition's own row.
400 * - an SPN marking enabling a `TimingStrategy::IMMEDIATE` firing mode.
401 *
402 * The same predicate drives BOTH the vanishing-row purge and the stochastic
403 * complementation, which is why it is one function: a row purged as vanishing
404 * and then left in the chain would carry only its immediate arcs and dominate
405 * the stationary vector with a 1e-8 sojourn, and a row complemented out without
406 * being purged would push its timed arcs into the tangible states.
407 *
408 * @return 0-based row indices, ascending and unique
409 */
410template <class T>
411std::vector<std::size_t> ctmc_find_vanishing_states(
412 const NetworkStruct<T>& sn, const std::vector<NetState<T>>& space,
413 const std::vector<qn::GlobalSync<T>>& gsync, bool isfjaug,
414 const std::vector<qn::FjSync<T>>& fjsync = std::vector<qn::FjSync<T>>()) {
415 const std::size_t n = space.size();
416 const std::size_t R = sn.nclasses;
417 std::vector<bool> mark(n, false);
418
419 // A Fork's parents MAY WAIT for a tag when an open chain or a quorum join
420 // runs through it (`fj_tag`): the tag pool is then a truncation, not the
421 // population, and with every tag in use no firing is enabled and time
422 // passes. Only a Fork-occupied state with an enabled firing is vanishing
423 // there (python `_fork_may_wait` / `_fork_fires`).
424 bool fork_may_wait = false;
425 if (isfjaug) {
426 const std::vector<double> nj = sn.njobs();
427 for (typename std::map<std::size_t, qn::FjJoinParam>::const_iterator jt = sn.fjjoinparam.begin();
428 jt != sn.fjjoinparam.end() && !fork_may_wait; ++jt) {
429 if (jt->second.debtwidth > 0) fork_may_wait = true;
430 for (std::size_t x = 0; x < jt->second.origclasses.size(); ++x) {
431 const std::size_t r = jt->second.origclasses[x];
432 if (r >= 1 && r <= nj.size() && !std::isfinite(nj[r - 1])) fork_may_wait = true;
433 }
434 }
435 }
436
437 // Router / Fork pass-through occupancy.
438 for (std::size_t ind = 1; ind <= sn.nodes.size(); ++ind) {
439 const NodeType nt = sn.nodes[ind - 1].nodetype;
440 if (nt != NodeType::Router && nt != NodeType::Fork) continue;
441 if (sn.nodes[ind - 1].station != 0) continue; // stateful and NOT a station
442 const std::size_t isf = sn.stateful_index(ind);
443 if (isf == 0) continue;
444 const bool fj_check = fork_may_wait && nt == NodeType::Fork;
445 for (std::size_t s = 0; s < n; ++s) {
446 if (mark[s]) continue;
447 const std::pair<T, std::vector<T>> mg =
448 qn::to_marginal_aggr(sn, ind, space[s].local[isf - 1]);
449 bool held = false;
450 for (std::size_t r = 0; r < R && r < mg.second.size(); ++r) {
451 const double v = num_traits<T>::to_double(mg.second[r]);
452 if (std::isfinite(v) && v > 0.0) {
453 held = true;
454 break;
455 }
456 }
457 if (!held) continue;
458 if (fj_check) {
459 bool fires = false;
460 for (std::size_t k = 0; k < fjsync.size() && !fires; ++k)
461 if (fjsync[k].fork == ind && !qn::after_fj_event(sn, fjsync[k], space[s]).space.empty())
462 fires = true;
463 if (!fires) continue;
464 }
465 mark[s] = true;
466 }
467 }
468
469 // Join rendezvous ready to fire.
470 if (isfjaug) {
471 for (std::size_t ind = 1; ind <= sn.nodes.size(); ++ind) {
472 if (sn.nodes[ind - 1].nodetype != NodeType::Join) continue;
473 const std::size_t isf = sn.stateful_index(ind);
474 if (isf == 0) continue;
475 const typename std::map<std::size_t, qn::FjJoinParam>::const_iterator jit =
476 sn.fjjoinparam.find(ind);
477 if (jit == sn.fjjoinparam.end()) continue;
478 const std::vector<std::size_t>& origcl = jit->second.origclasses;
479 for (std::size_t s = 0; s < n; ++s) {
480 if (mark[s]) continue;
481 for (std::size_t x = 0; x < origcl.size(); ++x) {
483 sn, ind, space[s].local[isf - 1], EventType::DEP, origcl[x]);
484 if (!oj.space.empty()) {
485 mark[s] = true;
486 break;
487 }
488 }
489 }
490 }
491 }
492
493 // SPN: an ENABLE that moves the Transition's row, and an IMMEDIATE firing.
494 for (std::size_t g = 0; g < gsync.size(); ++g) {
495 const qn::ModeEvent<T>& ae = gsync[g].active;
496 const std::size_t isf_t = sn.stateful_index(ae.node);
497 if (isf_t == 0) continue;
498 bool is_enable = ae.event == EventType::ENABLE;
499 bool is_imm_fire = false;
500 if (!is_enable && ae.event == EventType::FIRE) {
501 const typename std::map<std::size_t, qn::TransitionParam<T>>::const_iterator it =
502 sn.transparam.find(ae.node);
503 is_imm_fire = it != sn.transparam.end() && ae.mode >= 1 &&
504 ae.mode <= it->second.timing.size() &&
505 it->second.timing[ae.mode - 1] == lang::TimingStrategy::IMMEDIATE;
506 }
507 if (!is_enable && !is_imm_fire) continue;
508 for (std::size_t s = 0; s < n; ++s) {
509 if (mark[s]) continue;
510 const qn::GlobalOutcome<T> go = qn::after_global_event(sn, space[s], gsync[g]);
511 for (std::size_t io = 0; io < go.space.size(); ++io) {
512 if (num_traits<T>::to_double(go.rate[io]) <= 0) continue;
513 // AN ENABLE THAT LEAVES THE ROW ALONE IS NOT A MOVE. The
514 // reference tests the Transition's OWN row rather than the whole
515 // marking (`solver_ctmc.m:983`): an enabling that finds the mode
516 // already enabled re-emits the same state and takes no time to
517 // do nothing, which is not a vanishing state.
518 if (is_imm_fire || go.space[io].local[isf_t - 1] != space[s].local[isf_t - 1]) {
519 mark[s] = true;
520 break;
521 }
522 }
523 }
524 }
525
526 std::vector<std::size_t> imm;
527 for (std::size_t s = 0; s < n; ++s)
528 if (mark[s]) imm.push_back(s);
529 return imm;
530}
531
532/**
533 * One per-event arc set collected for the LAL embedding of a Network.
534 *
535 * `kind` says which list `index` points into: a synchronization of `sync`, a
536 * global (SPN) synchronization of `gsync`, a fork firing of `fjsync`, or the
537 * true-BAS become-blocked arcs, which carry no event of their own. `arcs`
538 * holds the positive `(state, successor, rate)` entries AFTER the
539 * vanishing-row purge, so a timed event leaves no arc in a vanishing state.
540 */
542 enum class Kind { Sync, Bas, Global, Fork, Batch };
544 std::size_t index = 0;
545 bool immediate = false;
546 std::vector<std::tuple<std::size_t, std::size_t, double>> arcs;
547 /**
548 * Region records of a Sync event built by the WAITQ region walk
549 * (`solver_ctmc_waitq`, python `RegionArrival`). `parked`: the region
550 * refused the action's passive arrival (parked it under WAITQ, destroyed it
551 * under DROP), so the job crossed its routing path but arrived nowhere.
552 * `released`: the (destination node, class), 1-based, of each head-of-line
553 * job the release cascade let in on this arc, each an arrival there.
554 */
555 bool parked = false;
556 std::vector<std::pair<std::size_t, std::size_t>> released;
557 /**
558 * A BMAP batch emission (Kind::Batch): `index` is the sync of the Source
559 * departure, and `jobs` has one entry per job of the batch, `(sync, lost)`:
560 * the sync whose passive half the job takes (its routing destination), and
561 * whether that destination refused it (a lost job arrives nowhere). The
562 * batch departs the Source once per job.
563 */
564 std::vector<std::pair<std::size_t, bool>> jobs;
565};
566
567/**
568 * The internal collect sink of the LAL embedding (python `options.collect`).
569 *
570 * It is NOT an `options.config` key: `line::lal::EmbeddedNetwork` sets it on
571 * its own CtmcOptions. `solver_ctmc` fills `events` and `vanishing` (every
572 * vanishing row, the ones the purge could not restate included) after the
573 * purge and before the stochastic complement; `solve_struct` adds the struct
574 * the chain was built on, its state space and the initial state index, and
575 * returns early when `stop` is set. Only the `double` instantiation collects.
576 */
578 bool stop = true;
579 bool filled = false;
580 std::vector<LalCollectedEvent> events;
581 std::vector<std::size_t> vanishing;
582 std::vector<qn::Sync<double>> sync;
583 std::vector<qn::GlobalSync<double>> gsync;
584 std::vector<qn::FjSync<double>> fjsync;
585 std::shared_ptr<const qn::NetworkStruct<double>> sn;
586 std::vector<qn::NetState<double>> space;
587 /**
588 * The region FIFOs of each state, per region (`WaitqState::buf`), when the
589 * chain is the WAITQ region walk's; empty otherwise. Several states of that
590 * walk share one network state and differ only here.
591 */
592 std::vector<std::vector<std::vector<std::size_t>>> buf;
593 std::size_t initial_index = static_cast<std::size_t>(-1);
594};
595
596namespace ctmc_detail {
597
598/** The positive entries of a dense matrix, with the rows in `drop` cleared. */
599template <class T>
600std::vector<std::tuple<std::size_t, std::size_t, double>> lal_arcs(const Matrix<T>& m,
601 const std::vector<bool>* drop) {
602 std::vector<std::tuple<std::size_t, std::size_t, double>> out;
603 for (std::size_t i = 0; i < m.rows(); ++i) {
604 if (drop && (*drop)[i]) continue;
605 for (std::size_t j = 0; j < m.cols(); ++j) {
606 const double v = num_traits<T>::to_double(m(i, j));
607 if (v > 0) out.push_back(std::make_tuple(i, j, v));
608 }
609 }
610 return out;
611}
612
613/**
614 * The BMAP Source classes (python `_bmap_source_groups`):
615 * `{(source node, class) -> [sync, ...]}`, each listed synchronization pairing
616 * the class's Source departure with one routing destination.
617 *
618 * A BMAP emits a BATCH of jobs per epoch, each routed independently, which one
619 * (active, passive) pair cannot express, so these departures are left out of
620 * the per-synchronization loop and expanded by `batch_arrival_arcs`. A
621 * state-dependent route out of such a Source (SDR, JSQ, SQ, and the
622 * round-robin pointer, which advances per departure) is refused by name: it is
623 * decided per departure from the pre-event state, which a batch of several jobs
624 * leaving at once does not define.
625 */
626template <class T>
627std::map<std::pair<std::size_t, std::size_t>, std::vector<std::size_t>> bmap_source_groups(
628 const NetworkStruct<T>& sn, const std::vector<Sync<T>>& sync) {
629 std::map<std::pair<std::size_t, std::size_t>, std::vector<std::size_t>> groups;
630 const std::size_t local = sn.nodes.size() + 1;
631 for (std::size_t a = 0; a < sync.size(); ++a) {
632 const Sync<T>& sy = sync[a];
633 if (sy.active.event != EventType::DEP) continue;
634 const std::size_t na = sy.active.node, r = sy.active.cls;
635 if (na == 0 || na > sn.nodes.size() || sn.nodes[na - 1].nodetype != NodeType::Source) continue;
636 const std::size_t ist = sn.nodes[na - 1].station;
637 if (ist == 0 || ist > sn.service.size() || r == 0 || r > sn.service[ist - 1].size()) continue;
638 if (sn.service[ist - 1][r - 1].type != lang::ProcessType::BMAP) continue;
639 if (sy.passive.node == local || sy.passive.node == 0 || sy.passive.node > sn.nodes.size()) continue;
640 if (sy.passive.statedep || sn.rr_var_slot(na, r) != 0)
641 throw UnsupportedError(ErrorKind{"Routing"},
642 "SolverCTMC cannot route the BMAP arrivals of class '" + sn.classes[r - 1].name +
643 "' by a state-dependent rule at '" + sn.nodes[na - 1].name +
644 "': a batch leaves at once, so a per-departure rule does not define where its "
645 "jobs go. Use PROB or RAND routing.");
646 groups[std::make_pair(na, r)].push_back(a);
647 }
648 return groups;
649}
650
651/**
652 * The arcs of one BMAP emission outcome (python `_batch_arrival_arcs` group):
653 * a (Source class, batch size, accepted and lost counts per destination).
654 */
655template <class T>
656struct BatchGroup {
657 std::size_t isf_src = 0, cls = 0, b = 0;
658 std::vector<std::size_t> acts; ///< one sync per routing destination, in routing order
659 std::vector<std::pair<std::size_t, std::size_t>> outcome; ///< (accepted, lost) per destination
660 std::vector<std::tuple<std::size_t, std::size_t, double>> arcs; ///< for the LAL collect
661};
662
663/**
664 * Expand the BMAP Source emissions into the generator (python
665 * `_batch_arrival_arcs`).
666 *
667 * From each state, an emission of `b` jobs that moves the Source's modulating
668 * phase from `k` to `j` fires at rate `D_b(k, j)`. Its jobs are allocated to
669 * the Source's routing destinations by the multinomial law of the routing
670 * probabilities (each job routed on its own) and are then landed ONE AT A
671 * TIME, each through the destination's own arrival handler. A job its
672 * destination refuses -- no successor row within the destination's enumerated
673 * local space -- is lost, while the emission and its phase move still happen,
674 * as for a single arrival lost at a full station. Every arc is added to Q
675 * once; the Source departs `b` jobs on it and each destination receives its
676 * accepted ones, so the rates count jobs and not epochs. The START/PREEMPT tags
677 * of every accepted arrival are carried as for an ordinary arrival.
678 *
679 * The arcs are NOT added to any `filt[a]`: a batch is no single
680 * synchronization, and the LAL collect reads it as an event of its own.
681 */
682template <class T>
683std::vector<BatchGroup<T>> batch_arrival_arcs(
684 const NetworkStruct<T>& sn, const std::vector<NetState<T>>& space,
685 const std::map<std::vector<double>, std::size_t>& index, const std::vector<Sync<T>>& sync,
686 const std::map<std::pair<std::size_t, std::size_t>, std::vector<std::size_t>>& groups, const Matrix<T>& gd,
687 bool want_filtration, bool collect, CtmcResult<T>& res) {
688 std::vector<BatchGroup<T>> out;
689 if (groups.empty()) return out;
690 const T one = num_traits<T>::from_int(1);
691 const std::size_t n = space.size(), NF = sn.stateful_nodes.size(), R = sn.nclasses;
692 // The enumerated local rows of each stateful node: a job whose successor row
693 // falls outside them is a truncation (the cutoff) and is lost, as python
694 // tests the local space hash.
695 std::vector<std::set<std::vector<double>>> local_rows(NF);
696 for (std::size_t s = 0; s < n; ++s)
697 for (std::size_t f = 0; f < NF && f < space[s].local.size(); ++f) {
698 std::vector<double> k(space[s].local[f].size());
699 for (std::size_t c = 0; c < k.size(); ++c) k[c] = num_traits<T>::to_double(space[s].local[f][c]);
700 local_rows[f].insert(k);
701 }
702 const auto in_local = [&](std::size_t isf, const std::vector<T>& row) {
703 std::vector<double> k(row.size());
704 for (std::size_t c = 0; c < k.size(); ++c) k[c] = num_traits<T>::to_double(row[c]);
705 return local_rows[isf - 1].count(k) != 0;
706 };
707 // One START/PREEMPT tag of an accepted arrival: (node, start classes, preempt classes).
708 typedef std::tuple<std::size_t, std::vector<std::size_t>, std::vector<std::size_t>> Tag;
709 struct Leaf {
710 NetState<T> st;
711 T w;
712 std::vector<std::size_t> acc, lost;
713 std::vector<Tag> tags;
714 };
715 std::map<std::tuple<std::size_t, std::size_t, std::vector<std::pair<std::size_t, std::size_t>>>, std::size_t>
716 gindex;
717
718 for (const auto& kv : groups) {
719 const std::size_t node_src = kv.first.first, r = kv.first.second;
720 const std::vector<std::size_t>& acts = kv.second;
721 const std::size_t isf_src = sn.stateful_index(node_src);
722 const std::size_t ist = sn.nodes[node_src - 1].station;
723 if (isf_src == 0) continue;
724 const lang::Distrib<T>& d = sn.service[ist - 1][r - 1];
725 const std::size_t B = d.Dmark.size();
726 const std::size_t ndest = acts.size();
727 std::vector<T> probs(ndest);
728 std::vector<std::size_t> dnode(ndest), disf(ndest), dcls(ndest);
729 for (std::size_t i = 0; i < ndest; ++i) {
730 const Sync<T>& sy = sync[acts[i]];
731 probs[i] = sy.passive.prob;
732 dnode[i] = sy.passive.node;
733 disf[i] = sn.stateful_index(sy.passive.node);
734 dcls[i] = sy.passive.cls;
735 }
736 // The multinomial allocations of b independent jobs over the destinations.
737 std::vector<std::vector<std::vector<std::size_t>>> alloc(B + 1);
738 std::vector<std::vector<T>> palloc(B + 1);
739 for (std::size_t b = 1; b <= B; ++b) {
740 std::vector<std::size_t> counts(ndest, 0);
741 std::function<void(std::size_t, std::size_t)> rec = [&](std::size_t i, std::size_t left) {
742 if (i + 1 == ndest) {
743 counts[i] = left;
744 // b! / prod(c!) * prod(p^c), built in exact integer steps
745 T p = one;
746 std::size_t done = 0;
747 for (std::size_t q = 0; q < ndest; ++q)
748 for (std::size_t c = 1; c <= counts[q]; ++c) {
749 ++done;
750 p = T(p * num_traits<T>::from_int(static_cast<long>(done)) /
751 num_traits<T>::from_int(static_cast<long>(c)) * probs[q]);
752 }
753 if (num_traits<T>::to_double(p) > 0) {
754 alloc[b].push_back(counts);
755 palloc[b].push_back(p);
756 }
757 return;
758 }
759 for (std::size_t c = left + 1; c-- > 0;) {
760 counts[i] = c;
761 rec(i + 1, left - c);
762 }
763 };
764 if (ndest > 0) rec(0, b);
765 }
766 for (std::size_t s = 0; s < n; ++s) {
767 const std::vector<T>& row = space[s].local[isf_src - 1];
768 const qn::RowLayout<T> L = qn::row_layout(sn, node_src, row.size());
769 const std::size_t base = L.bufw + L.Ks[r - 1];
770 const std::size_t K = L.K[r - 1];
771 for (std::size_t k = 0; k < K; ++k) {
772 if (num_traits<T>::to_double(row[base + k]) <= 0) continue;
773 for (std::size_t b = 1; b <= B; ++b) {
774 const Matrix<T>& Db = d.Dmark[b - 1];
775 for (std::size_t j = 0; j < K && j < Db.cols(); ++j) {
776 T rate = Db(k, j);
777 if (num_traits<T>::to_double(rate) <= 0) continue;
778 // phi(n), as the single-arrival Source departure is scaled
779 if (gd.rows() != 0) rate = T(rate * gd(s, (ist - 1) * R + (r - 1)));
780 std::vector<T> nsrc = row;
781 nsrc[base + k] -= one;
782 nsrc[base + j] += one;
783 if (!in_local(isf_src, nsrc)) continue;
784 for (std::size_t ia = 0; ia < alloc[b].size(); ++ia) {
785 const std::vector<std::size_t>& counts = alloc[b][ia];
786 std::vector<std::size_t> jobs;
787 for (std::size_t q = 0; q < ndest; ++q)
788 for (std::size_t c = 0; c < counts[q]; ++c) jobs.push_back(q);
789 // land the jobs one at a time
790 std::vector<Leaf> leaves;
791 Leaf l0;
792 l0.st = space[s];
793 l0.st.local[isf_src - 1] = nsrc;
794 l0.w = one;
795 l0.acc.assign(ndest, 0);
796 l0.lost.assign(ndest, 0);
797 std::function<void(std::size_t, const Leaf&)> land = [&](std::size_t i, const Leaf& cur) {
798 if (i == jobs.size()) {
799 leaves.push_back(cur);
800 return;
801 }
802 const std::size_t q = jobs[i];
803 const std::size_t isf_p = disf[q];
804 qn::EventOutcome<T> op;
805 if (isf_p != 0)
806 op = qn::after_event(sn, dnode[q], cur.st.local[isf_p - 1], EventType::ARV, dcls[q]);
807 std::vector<std::size_t> nxt;
808 for (std::size_t ip = 0; ip < op.space.size(); ++ip)
809 if (in_local(isf_p, op.space[ip])) nxt.push_back(ip);
810 if (nxt.empty()) {
811 Leaf lx = cur;
812 ++lx.lost[q];
813 land(i + 1, lx);
814 return;
815 }
816 for (std::size_t ip : nxt) {
817 const T p = ip < op.prob.size() ? op.prob[ip] : one;
818 if (num_traits<T>::to_double(p) <= 0) continue;
819 Leaf lx = cur;
820 lx.st.local[isf_p - 1] = op.space[ip];
821 lx.w = T(cur.w * p);
822 ++lx.acc[q];
823 lx.tags.push_back(Tag(dnode[q],
824 ip < op.start.size() ? op.start[ip] : std::vector<std::size_t>(),
825 ip < op.preempt.size() ? op.preempt[ip] : std::vector<std::size_t>()));
826 land(i + 1, lx);
827 }
828 };
829 land(0, l0);
830 for (const Leaf& lf : leaves) {
831 const typename std::map<std::vector<double>, std::size_t>::const_iterator it =
832 index.find(state_key(lf.st));
833 if (it == index.end()) continue;
834 const std::size_t ns = it->second;
835 const T eff = T(rate * palloc[b][ia] * lf.w);
836 if (num_traits<T>::to_double(eff) == 0) continue;
837 std::vector<std::pair<std::size_t, std::size_t>> oc(ndest);
838 for (std::size_t q = 0; q < ndest; ++q) oc[q] = std::make_pair(lf.acc[q], lf.lost[q]);
839 const auto gk = std::make_tuple(isf_src * (R + 1) + r, b, oc);
840 typename std::map<std::tuple<std::size_t, std::size_t,
841 std::vector<std::pair<std::size_t, std::size_t>>>,
842 std::size_t>::iterator g = gindex.find(gk);
843 if (g == gindex.end()) {
844 BatchGroup<T> bg;
845 bg.isf_src = isf_src;
846 bg.cls = r;
847 bg.b = b;
848 bg.acts = acts;
849 bg.outcome = oc;
850 out.push_back(bg);
851 g = gindex.emplace(gk, out.size() - 1).first;
852 }
853 res.Q(s, ns) += eff;
854 res.dep_rates[s][isf_src - 1][r - 1] +=
855 T(num_traits<T>::from_int(static_cast<long>(b)) * eff);
856 for (std::size_t q = 0; q < ndest; ++q)
857 if (lf.acc[q] > 0 && disf[q] != 0)
858 res.arv_rates[s][disf[q] - 1][dcls[q] - 1] +=
859 T(num_traits<T>::from_int(static_cast<long>(lf.acc[q])) * eff);
860 if (want_filtration)
861 for (const Tag& tg : lf.tags) {
862 const std::size_t ist_p = sn.nodes[std::get<0>(tg) - 1].station;
863 if (ist_p == 0 || ist_p > res.start_filt.size()) continue;
864 for (std::size_t c : std::get<1>(tg))
865 if (c >= 1 && c <= res.start_filt[ist_p - 1].size())
866 res.start_filt[ist_p - 1][c - 1](s, ns) += eff;
867 for (std::size_t c : std::get<2>(tg))
868 if (c >= 1 && c <= res.preempt_filt[ist_p - 1].size())
869 res.preempt_filt[ist_p - 1][c - 1](s, ns) += eff;
870 }
871 if (collect)
872 out[g->second].arcs.push_back(
873 std::make_tuple(s, ns, num_traits<T>::to_double(eff)));
874 }
875 }
876 }
877 }
878 }
879 }
880 }
881 return out;
882}
883
884} // namespace ctmc_detail
885
886/**
887 * Port of the generator assembly of `solver_ctmc.m`.
888 *
889 * @param sn the network struct
890 * @param space the enumerated state space, from `space_generator`
891 * @param sync the synchronization list, from `refresh_sync`
892 * @param gsync the SPN global synchronizations, from `refresh_gsync`
893 * @param fjsync the fork firing list, from `fj_tag`
894 * @param want_filtration also return the per-synchronisation rate matrices (the filtration), which sampling and reward paths need
895 * @param collect when non-null, filled with the per-event arcs for the LAL embedding (see `LalCollect`)
896 */
897template <class T>
898CtmcResult<T> solver_ctmc(const NetworkStruct<T>& sn, const std::vector<NetState<T>>& space,
899 const std::vector<Sync<T>>& sync,
900 const std::vector<qn::GlobalSync<T>>& gsync =
901 std::vector<qn::GlobalSync<T>>(),
902 bool want_filtration = false,
903 const std::vector<qn::FjSync<T>>& fjsync =
904 std::vector<qn::FjSync<T>>(),
905 LalCollect* collect = nullptr) {
906 if (!std::is_same<T, double>::value) collect = nullptr;
907 want_filtration = want_filtration || collect != nullptr;
908 if (collect) collect->vanishing.clear();
909 const std::size_t n = space.size();
910 const std::size_t local = sn.nodes.size() + 1; // the dummy passive node
911 const T zero = num_traits<T>::from_int(0);
912 CtmcResult<T> res;
913 res.space = space;
914 res.Q = Matrix<T>(n, n, zero);
915
916 const std::size_t NF = sn.stateful_nodes.size();
917 const std::size_t R = sn.nclasses;
918 res.arv_rates.assign(n, std::vector<std::vector<T>>(NF, std::vector<T>(R, zero)));
919 res.dep_rates.assign(n, std::vector<std::vector<T>>(NF, std::vector<T>(R, zero)));
920
921 if (want_filtration) {
922 res.filt.assign(sync.size(), Matrix<T>(n, n, zero));
923 res.start_filt.assign(sn.nstations, std::vector<Matrix<T>>(R, Matrix<T>(n, n, zero)));
924 res.preempt_filt.assign(sn.nstations, std::vector<Matrix<T>>(R, Matrix<T>(n, n, zero)));
925 }
926
927 // `immAction` / `immGsync` of `solver_ctmc.m:430-467`: which sources emit at
928 // the GlobalConstants::Immediate scale, and therefore land in `Qimm`. A Join
929 // counts only on an FJ-AUGMENTED struct -- without the tag classes a Join is
930 // an ordinary pass-through whose departures are timed by the siblings.
931 const bool isfjaug = !fjsync.empty();
932 std::vector<bool> imm_action(sync.size(), false);
933 bool has_imm = !fjsync.empty();
934 for (std::size_t a = 0; a < sync.size(); ++a) {
935 const std::size_t na = sync[a].active.node;
936 if (na == 0 || na > sn.nodes.size()) continue;
937 const NodeType nt = sn.nodes[na - 1].nodetype;
938 imm_action[a] = nt == NodeType::Router || nt == NodeType::Fork ||
939 (isfjaug && nt == NodeType::Join);
940 if (imm_action[a]) has_imm = true;
941 }
942 std::vector<bool> imm_gsync(gsync.size(), false);
943 for (std::size_t g = 0; g < gsync.size(); ++g) {
944 const qn::ModeEvent<T>& ae = gsync[g].active;
945 if (ae.event == EventType::ENABLE) {
946 imm_gsync[g] = true;
947 } else if (ae.event == EventType::FIRE) {
948 const typename std::map<std::size_t, qn::TransitionParam<T>>::const_iterator it =
949 sn.transparam.find(ae.node);
950 imm_gsync[g] = it != sn.transparam.end() && ae.mode >= 1 &&
951 ae.mode <= it->second.timing.size() &&
952 it->second.timing[ae.mode - 1] == lang::TimingStrategy::IMMEDIATE;
953 }
954 if (imm_gsync[g]) has_imm = true;
955 }
956 if (has_imm) {
957 res.Qimm = Matrix<T>(n, n, zero);
958 res.arv_rates_imm.assign(n, std::vector<std::vector<T>>(NF, std::vector<T>(R, zero)));
959 res.dep_rates_imm.assign(n, std::vector<std::vector<T>>(NF, std::vector<T>(R, zero)));
960 }
961
962 // The true-BAS become-blocked edges, kept out of Q until the end because they
963 // are not departures: they must reach the generator but not `dep_rates`.
964 bool any_bas = false;
965 for (std::size_t i = 0; i < sn.isbasblocking.size(); ++i)
966 if (sn.isbasblocking[i]) any_bas = true;
967 Matrix<T> bas_block(any_bas ? n : 0, any_bas ? n : 0, zero);
968
969 std::map<std::vector<double>, std::size_t> index;
970 for (std::size_t s = 0; s < n; ++s) index[ctmc_detail::state_key(space[s])] = s;
971
972 // phi(n) is constant within a state, so it factors out of every rate there
973 const Matrix<T> gd = ctmc_gd_factor(sn, space);
974 const bool has_gd = gd.rows() != 0;
975
976 // The state-dependent routing table, one per state. It is tabulated here for
977 // the same reason phi(n) is: the loop below runs synchronization-outer and
978 // state-inner, so evaluating eq. (10) inside it would redo one stochastic
979 // complement per (sync, state) pair rather than one per state.
980 std::vector<Matrix<T>> rt_by_state;
981 if (sn.has_rtfun_routing()) {
982 rt_by_state.reserve(n);
983 for (std::size_t s = 0; s < n; ++s) rt_by_state.push_back(qn::rt_state(sn, space[s].local));
984 }
985
986 // BMAP Source classes emit a batch of jobs per epoch, routed independently,
987 // which one (active, passive) pair cannot express: their departures are left
988 // out of the per-synchronization loop and expanded by `batch_arrival_arcs`.
989 const std::map<std::pair<std::size_t, std::size_t>, std::vector<std::size_t>> bmap_groups =
990 ctmc_detail::bmap_source_groups(sn, sync);
991
992 for (std::size_t a = 0; a < sync.size(); ++a) {
993 const Sync<T>& sy = sync[a];
994 const std::size_t node_a = sy.active.node;
995 const std::size_t isf_a = sn.stateful_index(node_a);
996 if (isf_a == 0) continue; // a stateless node schedules nothing
997 if (sy.active.event == EventType::DEP && bmap_groups.count(std::make_pair(node_a, sy.active.cls)))
998 continue; // a BMAP Source emission, see batch_arrival_arcs
999 const std::size_t node_p = sy.passive.node;
1000 const std::size_t isf_p = node_p == local ? 0 : sn.stateful_index(node_p);
1001 if (node_p != local && isf_p == 0) continue;
1002
1003 // PHASE is scaled too, or phase-type service would advance unscaled
1004 const bool gd_here = has_gd && sn.nodes[node_a - 1].station != 0 &&
1005 (sy.active.event == EventType::DEP ||
1006 sy.active.event == EventType::PHASE);
1007 const std::size_t gd_col = gd_here ? (sn.nodes[node_a - 1].station - 1) * sn.nclasses +
1008 (sy.active.cls - 1)
1009 : 0;
1010 // A round-robin dispatcher decides the destination from its own pointer;
1011 // see the proute branch below.
1012 const bool rr_here = sy.active.event == EventType::DEP &&
1013 sn.rr_var_slot(node_a, sy.active.cls) != 0;
1014 // Immediate feedback (sn.immfeed): the departure half of a self-loop must
1015 // not promote a waiting job, so the fed-back arrival finds the server it
1016 // just left free. See qn::immfeed_self_loop.
1017 const bool immfeed_a = qn::immfeed_self_loop(sn, sy);
1018 // TRUE BAS (BUG-110). The trailing block of a blocking station counts
1019 // the held jobs per target code (class, destination station, arriving
1020 // class), so whether this DEP is a held job's TRANSFER or a completion
1021 // still in service depends on the passive side of the synchronization.
1022 // `bas_tgt` is 1 + the block position of this sync's target code, 0 when
1023 // the target never refuses (it has no code).
1024 const bool bas_a = sy.active.event == EventType::DEP && node_p != local &&
1025 node_a <= sn.isbasblocking.size() && sn.isbasblocking[node_a - 1] &&
1026 sn.nodes[node_a - 1].station != 0;
1027 std::vector<std::size_t> bas_codes_a;
1028 std::size_t bas_nc = 0, bas_tgt = 0;
1029 bool bas_single = false;
1030 std::vector<std::size_t> bas_ph, bas_shift;
1031 if (bas_a) {
1032 bas_codes_a = sn.bas_marker_codes(node_a);
1033 bas_nc = qn::NetworkStruct<T>::bas_ncols(bas_codes_a);
1034 const std::size_t ist_a = sn.nodes[node_a - 1].station;
1035 bas_single = sn.bas_single_server(ist_a);
1036 const std::size_t jst_p = sn.nodes[node_p - 1].station;
1037 if (jst_p != 0) {
1038 const std::size_t code = sn.bas_code(sy.active.cls, jst_p, sy.passive.cls);
1039 for (std::size_t k = 0; k < bas_codes_a.size(); ++k)
1040 if (bas_codes_a[k] == code) bas_tgt = k + 1;
1041 }
1042 std::size_t w = 0;
1043 for (std::size_t k = 1; k <= sn.nclasses; ++k) {
1044 bas_ph.push_back(sn.phasessz_of(ist_a, k));
1045 bas_shift.push_back(w);
1046 w += bas_ph.back();
1047 }
1048 }
1049 for (std::size_t s = 0; s < n; ++s) {
1050 const NetState<T>& st = space[s];
1051 T fired = zero; // the rate this synchronization contributes here
1052 // One (outcome, is-transfer) pair per variant of the active half.
1053 // Outside true BAS there is exactly one, the event's own outcome.
1054 std::vector<std::pair<EventOutcome<T>, bool>> variants;
1055 // Pre-event held vector, the class's jobs in service and its held
1056 // jobs, read once per state for the become-blocked edge below.
1057 std::vector<long> bas_held;
1058 long bas_nr = 0, bas_heldr = 0;
1059 bool bas_any = false;
1060 if (!bas_a) {
1061 variants.push_back(std::make_pair(
1062 qn::after_event(sn, node_a, st.local[isf_a - 1], sy.active.event,
1063 sy.active.cls, immfeed_a),
1064 false));
1065 } else {
1066 const std::vector<T>& cur = st.local[isf_a - 1];
1067 const std::size_t w0 = cur.size() - bas_nc;
1068 bas_held.assign(bas_nc, 0);
1069 for (std::size_t k = 0; k < bas_nc; ++k) {
1070 bas_held[k] = static_cast<long>(std::llround(num_traits<T>::to_double(cur[w0 + k])));
1071 if (bas_held[k] > 0) bas_any = true;
1072 }
1073 for (std::size_t k = 0; k < bas_codes_a.size(); ++k) {
1074 std::size_t r = 0, jj = 0, ss = 0;
1075 sn.bas_decode(bas_codes_a[k], r, jj, ss);
1076 if (r == sy.active.cls) bas_heldr += bas_held[k];
1077 }
1078 const qn::Marginal<T> mg = qn::to_marginal(sn, sn.nodes[node_a - 1].station, cur,
1079 bas_ph, bas_shift, sn.nvars_of(node_a));
1080 bas_nr = static_cast<long>(
1081 std::llround(num_traits<T>::to_double(mg.sir[sy.active.cls - 1])));
1082 // A held row fires as the same row with its block cleared: the
1083 // block rides through the event layer, and each variant then
1084 // writes the block its outcome carries.
1085 std::vector<T> zrow = cur;
1086 for (std::size_t k = 0; k < bas_nc; ++k) zrow[w0 + k] = zero;
1087 const EventOutcome<T> base = qn::after_event(sn, node_a, zrow, sy.active.event,
1088 sy.active.cls, immfeed_a);
1089 if (!base.space.empty()) {
1090 // TRANSFER: a held job for exactly this target enters it, at
1091 // 1e7 VERBATIM (not GlobalConstants::Immediate, 1e8): large but
1092 // finite, so the held states keep the share of mass the
1093 // queue-length attribution reads.
1094 if (bas_any && bas_tgt != 0 && bas_held[bas_tgt - 1] > 0) {
1095 EventOutcome<T> tr = base;
1096 for (std::size_t i = 0; i < tr.space.size(); ++i) {
1097 for (std::size_t k = 0; k < bas_nc; ++k)
1098 tr.space[i][tr.space[i].size() - bas_nc + k] =
1099 num_traits<T>::from_int(bas_held[k] - (k + 1 == bas_tgt ? 1 : 0));
1100 tr.rate[i] = num_traits<T>::from_double(1e7);
1101 }
1102 variants.push_back(std::make_pair(tr, true));
1103 }
1104 // FRESH COMPLETION of a job still in service: held jobs are
1105 // not being served, so the class's rate is scaled by its free
1106 // share. A single server holding a job is blocked outright.
1107 if (!bas_any) {
1108 variants.push_back(std::make_pair(base, false));
1109 } else if (!bas_single && bas_nr > 0 && bas_nr - bas_heldr > 0) {
1110 EventOutcome<T> fr = base;
1111 const T f = T(num_traits<T>::from_int(bas_nr - bas_heldr) /
1112 num_traits<T>::from_int(bas_nr));
1113 for (std::size_t i = 0; i < fr.space.size(); ++i) {
1114 for (std::size_t k = 0; k < bas_nc; ++k)
1115 fr.space[i][fr.space[i].size() - bas_nc + k] =
1116 num_traits<T>::from_int(bas_held[k]);
1117 fr.rate[i] = T(fr.rate[i] * f);
1118 }
1119 variants.push_back(std::make_pair(fr, false));
1120 }
1121 }
1122 }
1123 for (std::size_t vi = 0; vi < variants.size(); ++vi) {
1124 const EventOutcome<T>& oa = variants[vi].first;
1125 const bool bas_transfer = variants[vi].second;
1126 for (std::size_t ia = 0; ia < oa.space.size(); ++ia) {
1127 // A BAS transfer is immediate and is not scaled by phi(n).
1128 const T rate = (gd_here && !bas_transfer) ? T(oa.rate[ia] * gd(s, gd_col))
1129 : T(oa.rate[ia]);
1130 // A zero-rate successor is a state the reference still emits so
1131 // that the event exists; it contributes nothing to the balance
1132 // equations, so skip it here rather than adding a zero.
1133 if (num_traits<T>::to_double(rate) == 0) continue;
1134
1135 if (node_p == local) {
1136 // A local action moves no job elsewhere: only the active
1137 // node's block changes.
1138 NetState<T> nsx = st;
1139 nsx.local[isf_a - 1] = oa.space[ia];
1140 const typename std::map<std::vector<double>, std::size_t>::const_iterator it =
1141 index.find(ctmc_detail::state_key(nsx));
1142 if (it == index.end()) continue;
1143 res.Q(s, it->second) += T(rate * oa.prob[ia]);
1144 if (imm_action[a]) res.Qimm(s, it->second) += T(rate * oa.prob[ia]);
1145 if (want_filtration) {
1146 res.filt[a](s, it->second) += T(rate * oa.prob[ia]);
1147 // local action: only the active node can tag
1148 ctmc_detail::add_aux_filt(res, sn, node_a, s, it->second,
1149 T(rate * oa.prob[ia]), oa, ia);
1150 }
1151 fired += T(rate * oa.prob[ia]);
1152 continue;
1153 }
1154
1155 // A self-loop synchronization reads the passive node's state
1156 // AFTER the active half has been applied, since they are the
1157 // same node; otherwise the two halves see independent blocks.
1158 const std::vector<T>& src =
1159 node_p == node_a ? oa.space[ia] : st.local[isf_p - 1];
1160 const EventOutcome<T> op =
1161 qn::after_event(sn, node_p, src, sy.passive.event, sy.passive.cls);
1162 // The routing probability, read at the state the job LEAVES from,
1163 // which is what `sub_sdr` reads: the branch it is admitted to is
1164 // decided by the populations the departing customer sees.
1165 //
1166 // ROUND-ROBIN IS THE ONE THAT READS THE STATE AFTER. Its
1167 // destination is the pointer the ACTIVE node carries once its own
1168 // departure has advanced it, so the probability is the 0/1
1169 // indicator of that pointer and not the uniform mask
1170 // `refresh_routing` wrote into `rt`. Reading `rt` here instead
1171 // would spread the job over every outlink, which is the random
1172 // routing the dispatcher exists not to be. This is the
1173 // reference's `sub_rr`, which likewise takes `state_after`.
1174 T proute = sy.passive.statedep
1175 ? rt_by_state[s](sy.passive.rt_row, sy.passive.rt_col)
1176 : sy.passive.prob;
1177 if (rr_here) {
1178 const std::size_t w = sn.nvars_of(node_a);
1179 const std::vector<T>& arow = oa.space[ia];
1180 std::size_t dest = 0;
1181 if (arow.size() >= w) {
1182 const std::vector<T> var(arow.end() - w, arow.end());
1183 dest = sn.rr_dest(node_a, sy.active.cls, var);
1184 }
1185 proute = (dest == node_p && sy.passive.cls == sy.active.cls)
1187 : zero;
1188 }
1189 // A held job's route was drawn when it blocked.
1190 if (bas_transfer) proute = num_traits<T>::from_int(1);
1191 bool placed = false;
1192 for (std::size_t ip = 0; ip < op.space.size(); ++ip) {
1193 NetState<T> nsx = st;
1194 nsx.local[isf_a - 1] = oa.space[ia];
1195 nsx.local[isf_p - 1] = op.space[ip];
1196 const typename std::map<std::vector<double>, std::size_t>::const_iterator it =
1197 index.find(ctmc_detail::state_key(nsx));
1198 if (it == index.end()) continue;
1199 placed = true;
1200 // THE ACTIVE HALF'S OWN PROBABILITY COUNTS TOO. `oa.prob[ia]`
1201 // is the share of the completion that leads to THIS successor
1202 // -- SIRO's random pick of the next job to promote is the only
1203 // branch that returns it below 1 -- and the LOCAL branch above
1204 // already multiplies by it. Omitting it here gave every
1205 // promotion candidate the FULL service rate, so a SIRO station
1206 // with two waiting classes left the state at 2*mu: on
1207 // prio_hol_open that is Source Tput 0.052334 against the
1208 // reference's 0.052281. The reference folds the same share
1209 // into its `outrate` instead (afterEventStation.m, `pick_prob`)
1210 // and keeps `outprob` at 1, which is the same product.
1211 const T w = T(rate * oa.prob[ia] * proute * op.prob[ip]);
1212 res.Q(s, it->second) += w;
1213 if (imm_action[a]) res.Qimm(s, it->second) += w;
1214 if (want_filtration) {
1215 res.filt[a](s, it->second) += w;
1216 // Both halves of the synchronization are tagged: a DEP
1217 // promotes at the sender while the paired ARV starts or
1218 // preempts at the receiver.
1219 ctmc_detail::add_aux_filt(res, sn, node_a, s, it->second, w, oa, ia);
1220 ctmc_detail::add_aux_filt(res, sn, node_p, s, it->second, w, op, ip);
1221 }
1222 fired += w;
1223 }
1224 // AN ARRIVAL A DROP REGION REFUSES IS STILL A DEPARTURE OF THE
1225 // SOURCE. The region's states are absent from the space (the
1226 // enumeration stops at the region cap and `ctmc_filter_regions`
1227 // removes the rest), so the refusal reaches this loop as a
1228 // successor that was never placed -- the event layer returns no
1229 // row, because to it the bound is a truncation and not a
1230 // declared buffer -- and the event used to vanish from the rate
1231 // arrays: on gallery_fcr (lambda 0.8, region cap 3) the Source
1232 // reported the CARRIED 0.661 where the reference reports the
1233 // OFFERED 0.8, as it does for a finite station capacity. The
1234 // lost job is a self-loop: it adds nothing to Q and is counted
1235 // in `fired` alone. The test is the REGION's, on the state with
1236 // the job admitted, so a plain cutoff truncation stays silent.
1237 if (!placed && !sn.regions.empty() && sy.active.event == EventType::DEP &&
1238 sn.nodes[node_a - 1].nodetype == NodeType::Source &&
1239 sn.nodes[node_p - 1].station != 0) {
1240 const std::size_t ist_p = sn.nodes[node_p - 1].station;
1241 bool drop_rule = false;
1242 for (std::size_t f = 0; f < sn.regions.size() && !drop_rule; ++f)
1243 drop_rule = ist_p - 1 < sn.regions[f].members.size() &&
1244 sn.regions[f].members[ist_p - 1] &&
1245 sy.passive.cls - 1 < sn.regions[f].rule.size() &&
1246 sn.regions[f].rule[sy.passive.cls - 1] ==
1248 if (drop_rule) {
1249 const Matrix<T> A =
1250 ctmc_state_space_aggr(sn, std::vector<NetState<T>>(1, st));
1251 std::vector<T> nir(A.cols());
1252 for (std::size_t c = 0; c < A.cols(); ++c) nir[c] = A(0, c);
1253 const std::size_t col = (ist_p - 1) * sn.nclasses + (sy.passive.cls - 1);
1254 if (col < nir.size()) {
1255 nir[col] = T(nir[col] + num_traits<T>::from_int(1));
1256 if (!ctmc_region_admissible(sn, nir))
1257 fired += T(rate * oa.prob[ia] * proute);
1258 }
1259 }
1260 }
1261 // TRUE BAS, the become-blocked half. The passive arrival was
1262 // refused at every outcome, so the completing job cannot leave.
1263 // Only the generator can emit this edge: the event layer sees one
1264 // node at a time and cannot know the destination is full.
1265 //
1266 // The successor is the CURRENT state with one more job held for
1267 // THIS target code, not the post-departure one: the job stays in
1268 // the server it completed in, which is the whole content of
1269 // blocking after service. It is accumulated separately from Q and
1270 // folded in below because it is NOT a departure -- counting it in
1271 // `dep_rates` would inflate throughput by the blocked transitions.
1272 //
1273 // The weight carries the routing probability to this target
1274 // (BUG-110): before, the edge added the bare rate once per refused
1275 // destination, which over-counted blocking at a station with
1276 // several destinations. `rate` already holds the free share of
1277 // the class in service and phi(n).
1278 if (!placed && bas_a && !bas_transfer && bas_tgt != 0 &&
1279 !(bas_single && bas_any) && bas_nr > 0 && bas_nr - bas_heldr > 0 &&
1280 num_traits<T>::to_double(proute) > 0) {
1281 NetState<T> nsb = st;
1282 std::vector<T>& brow = nsb.local[isf_a - 1];
1283 brow[brow.size() - bas_nc + (bas_tgt - 1)] =
1284 num_traits<T>::from_int(bas_held[bas_tgt - 1] + 1);
1285 const typename std::map<std::vector<double>, std::size_t>::const_iterator ib =
1286 index.find(ctmc_detail::state_key(nsb));
1287 if (ib != index.end()) bas_block(s, ib->second) += T(rate * oa.prob[ia] * proute);
1288 }
1289 }
1290 }
1291 // A DEP synchronization is one job LEAVING the active node and
1292 // ENTERING the passive one, so the same accumulated rate is both a
1293 // departure there and an arrival here. The passive half of a LOCAL
1294 // action is the dummy node, which is nobody's arrival.
1295 if (sy.active.event == EventType::DEP && num_traits<T>::to_double(fired) != 0) {
1296 res.dep_rates[s][isf_a - 1][sy.active.cls - 1] += fired;
1297 if (isf_p != 0) res.arv_rates[s][isf_p - 1][sy.passive.cls - 1] += fired;
1298 // ONLY AN FJ-AUGMENTED JOIN takes the rate complement, verbatim
1299 // from `solver_ctmc.m:841`: a Router or Fork DEP is restricted
1300 // to the tangible rows like any timed action, and only a Join
1301 // firing -- which exists nowhere else -- is complemented back.
1302 if (isfjaug && sn.nodes[node_a - 1].nodetype == NodeType::Join) {
1303 res.dep_rates_imm[s][isf_a - 1][sy.active.cls - 1] += fired;
1304 if (isf_p != 0)
1305 res.arv_rates_imm[s][isf_p - 1][sy.passive.cls - 1] += fired;
1306 }
1307 }
1308 }
1309 }
1310
1311 // BMAP batch emissions: one arc per (state, batch, entry phase, allocation
1312 // outcome), grouped per outcome so the rates count jobs, not epochs.
1313 const std::vector<ctmc_detail::BatchGroup<T>> batch_groups = ctmc_detail::batch_arrival_arcs(
1314 sn, space, index, sync, bmap_groups, gd, want_filtration, collect != nullptr, res);
1315
1316 // SPN global synchronizations. A firing is ATOMIC across all its arcs, so
1317 // unlike an ordinary sync it rewrites several nodes in one transition and
1318 // cannot be decomposed into per-node halves.
1319 //
1320 // A PLACE'S FLOW IS COUNTED HERE OR NOWHERE. `refresh_sync` emits no DEP
1321 // sync touching a Place -- a token crosses an arc of a firing, not a routing
1322 // edge -- so leaving this loop to write only Q left `dep_rates` and
1323 // `arv_rates` identically zero at every Place, and the AvgTable reported
1324 // Tput 0 (hence RespT 0) for a Place whose QLen and Util were right. The
1325 // reference accumulates the same two from `Dfilt_gsync_comp`
1326 // (solver_ctmc.m:624-649): the PRE passives of a FIRE are that place's
1327 // departures and the POST passives its arrivals.
1328 //
1329 // ONLY A COMPLETION COUNTS, which is what `GlobalOutcome::completion`
1330 // records and what the reference's `is_comp` gates `Dfilt_gsync_comp` on. A
1331 // FIRE outcome that merely starts a firing phase moves no token, and an
1332 // ENABLE outcome never does, so neither is a flow.
1333 // The LAL embedding reads each global synchronization and fork firing as an
1334 // event of its own, so their contributions are also kept apart.
1335 std::vector<Matrix<T>> lal_gfilt(collect ? gsync.size() : 0, Matrix<T>(collect ? n : 0, collect ? n : 0, zero));
1336 std::vector<Matrix<T>> lal_fjfilt(collect ? fjsync.size() : 0, Matrix<T>(collect ? n : 0, collect ? n : 0, zero));
1337 for (std::size_t g = 0; g < gsync.size(); ++g) {
1338 const bool is_fire = gsync[g].active.event == EventType::FIRE;
1339 for (std::size_t s = 0; s < n; ++s) {
1340 const qn::GlobalOutcome<T> go = qn::after_global_event(sn, space[s], gsync[g]);
1341 T completed = zero;
1342 for (std::size_t io = 0; io < go.space.size(); ++io) {
1343 const T contrib = T(go.rate[io] * go.prob[io]);
1344 if (num_traits<T>::to_double(contrib) == 0) continue;
1345 const typename std::map<std::vector<double>, std::size_t>::const_iterator it =
1346 index.find(ctmc_detail::state_key(go.space[io]));
1347 if (it == index.end()) continue;
1348 res.Q(s, it->second) += contrib;
1349 if (collect) lal_gfilt[g](s, it->second) += contrib;
1350 if (imm_gsync[g]) res.Qimm(s, it->second) += contrib;
1351 if (is_fire && io < go.completion.size() && go.completion[io]) completed += contrib;
1352 }
1353 if (!is_fire || num_traits<T>::to_double(completed) == 0) continue;
1354 for (std::size_t j = 0; j < gsync[g].passive.size(); ++j) {
1355 const qn::ModeEvent<T>& pev = gsync[g].passive[j];
1356 if (pev.node == 0 || pev.node > sn.nodes.size()) continue;
1357 const std::size_t isf_v = sn.stateful_index(pev.node);
1358 if (isf_v == 0 || pev.cls == 0 || pev.cls > sn.nclasses) continue;
1359 // THE ARC MULTIPLICITY IS PART OF THE FLOW. A place loses (or
1360 // gains) `weight` tokens per firing, not one, so a rate counted
1361 // per firing is a firing rate and not a job rate. Measured
1362 // against the reference: `spn_closed_fourplaces`, whose cycle moves 2
1363 // tokens a firing and the unweighted count reported exactly half
1364 // its throughput, while `spn_twomodes`, whose two arcs have
1365 // multiplicities 4 and 2, was off by exactly those two factors
1366 // at its two places. Multiplicity 1 is the common case and
1367 // leaves `spn_basic_closed`/`_open` unchanged.
1368 const T flow = T(completed * pev.weight);
1369 // EVERY FIRE completion takes the rate complement, not only an
1370 // immediate one: `solver_ctmc.m:833-855` complements
1371 // `Dfilt_gsync_comp{g}` for all of them, and for a timed mode the
1372 // vanishing rows contribute nothing so the two agree.
1373 if (pev.event == EventType::PRE) {
1374 res.dep_rates[s][isf_v - 1][pev.cls - 1] += flow;
1375 if (has_imm) res.dep_rates_imm[s][isf_v - 1][pev.cls - 1] += flow;
1376 } else if (pev.event == EventType::POST) {
1377 res.arv_rates[s][isf_v - 1][pev.cls - 1] += flow;
1378 if (has_imm) res.arv_rates_imm[s][isf_v - 1][pev.cls - 1] += flow;
1379 }
1380 }
1381 }
1382 }
1383
1384 // FORK FIRINGS. Like an SPN firing this is atomic across several nodes, so it
1385 // takes the whole network state and cannot be decomposed into sync halves.
1386 //
1387 // The rate statistics are accumulated by hand rather than through the DEP
1388 // path: a firing is one DEPARTURE of the parent class at the fork and one
1389 // ARRIVAL of the tag's auxiliary class at each branch head, which is B
1390 // arrivals for one departure and is exactly what an ordinary sync cannot
1391 // express. `refresh_sync` therefore emits no DEP sync for a Fork.
1392 for (std::size_t k = 0; k < fjsync.size(); ++k) {
1393 const qn::FjSync<T>& e = fjsync[k];
1394 const std::size_t isf_f = sn.stateful_index(e.fork);
1395 if (isf_f == 0) continue;
1396 for (std::size_t s = 0; s < n; ++s) {
1397 const qn::GlobalOutcome<T> fo = qn::after_fj_event(sn, e, space[s]);
1398 T fired = zero;
1399 for (std::size_t io = 0; io < fo.space.size(); ++io) {
1400 const T contrib = T(fo.rate[io] * fo.prob[io]);
1401 if (num_traits<T>::to_double(contrib) <= 0) continue;
1402 const typename std::map<std::vector<double>, std::size_t>::const_iterator it =
1403 index.find(ctmc_detail::state_key(fo.space[io]));
1404 if (it == index.end()) continue;
1405 res.Q(s, it->second) += contrib;
1406 res.Qimm(s, it->second) += contrib;
1407 if (collect) lal_fjfilt[k](s, it->second) += contrib;
1408 fired += contrib;
1409 }
1410 if (num_traits<T>::to_double(fired) == 0) continue;
1411 res.dep_rates[s][isf_f - 1][e.cls - 1] += fired;
1412 res.dep_rates_imm[s][isf_f - 1][e.cls - 1] += fired;
1413 for (std::size_t b = 0; b < e.branchheads.size(); ++b) {
1414 const std::size_t isf_b = sn.stateful_index(e.branchheads[b]);
1415 if (isf_b == 0) continue;
1416 res.arv_rates[s][isf_b - 1][e.auxclasses[b] - 1] += fired;
1417 res.arv_rates_imm[s][isf_b - 1][e.auxclasses[b] - 1] += fired;
1418 }
1419 }
1420 }
1421
1422 if (any_bas)
1423 for (std::size_t i = 0; i < n; ++i)
1424 for (std::size_t j = 0; j < n; ++j) res.Q(i, j) += bas_block(i, j);
1425
1426 // THE VANISHING-ROW PURGE, `solver_ctmc.m:592-620`. A zero-sojourn state is
1427 // left the instant it is entered, so a TIMED arc out of one describes an
1428 // event that cannot occur -- the state is gone before the clock advances.
1429 // Restating such a row as its immediate part is what makes the stochastic
1430 // complement below the elimination of the immediate transitions rather than
1431 // a censoring of a chain that still contains them.
1432 if (has_imm) {
1433 res.vanishing = ctmc_find_vanishing_states(sn, space, gsync, isfjaug, fjsync);
1434 // A vanishing state with NO immediate exit is a disagreement between the
1435 // predicate and the arc tagging, not a model: purging it would leave an
1436 // absorbing row and complementing it out would make the censored block
1437 // singular. The reference purges neither but complements it anyway and
1438 // lands on a NaN; drop it from both and say so.
1439 std::vector<std::size_t> keep_van;
1440 std::size_t gap = 0;
1441 for (std::size_t x = 0; x < res.vanishing.size(); ++x) {
1442 const std::size_t s = res.vanishing[x];
1443 T out_imm = zero;
1444 for (std::size_t j = 0; j < n; ++j)
1445 if (j != s) out_imm += res.Qimm(s, j);
1446 if (num_traits<T>::to_double(out_imm) > 0)
1447 keep_van.push_back(s);
1448 else
1449 ++gap;
1450 }
1451 if (gap > 0)
1453 "CTMC: %zu vanishing state(s) have no immediate outgoing arc; the vanishing "
1454 "predicate and the immediate-arc tagging disagree, so those rows keep their "
1455 "timed arcs",
1456 gap);
1457 if (collect) collect->vanishing = res.vanishing;
1458 res.vanishing.swap(keep_van);
1459 for (std::size_t x = 0; x < res.vanishing.size(); ++x) {
1460 const std::size_t s = res.vanishing[x];
1461 for (std::size_t j = 0; j < n; ++j) res.Q(s, j) = res.Qimm(s, j);
1462 res.arv_rates[s] = res.arv_rates_imm[s];
1463 res.dep_rates[s] = res.dep_rates_imm[s];
1464 for (std::size_t a = 0; a < res.filt.size(); ++a)
1465 if (!imm_action[a])
1466 for (std::size_t j = 0; j < n; ++j) res.filt[a](s, j) = zero;
1467 }
1468 }
1469
1470 // THE LAL COLLECTION (python `_build_generator_sync(..., collect=)`): the
1471 // per-event arcs after the purge, before any complementation. A timed event
1472 // keeps no arc in a purged (vanishing) row; an immediate one keeps all.
1473 if (collect) {
1474 std::vector<bool> purged(n, false);
1475 for (std::size_t x = 0; x < res.vanishing.size(); ++x) purged[res.vanishing[x]] = true;
1476 collect->events.clear();
1477 for (std::size_t a = 0; a < sync.size(); ++a) {
1478 const std::size_t na = sync[a].active.node;
1479 if (na == 0 || na > sn.nodes.size() || sn.stateful_index(na) == 0) continue;
1482 ev.index = a;
1483 ev.immediate = imm_action[a];
1484 ev.arcs = ctmc_detail::lal_arcs(res.filt[a], nullptr);
1485 collect->events.push_back(std::move(ev));
1486 }
1487 if (any_bas) {
1490 ev.arcs = ctmc_detail::lal_arcs(bas_block, &purged);
1491 collect->events.push_back(std::move(ev));
1492 }
1493 for (std::size_t g = 0; g < gsync.size(); ++g) {
1496 ev.index = g;
1497 ev.immediate = imm_gsync[g];
1498 ev.arcs = ctmc_detail::lal_arcs(lal_gfilt[g], imm_gsync[g] ? nullptr : &purged);
1499 collect->events.push_back(std::move(ev));
1500 }
1501 for (std::size_t k = 0; k < fjsync.size(); ++k) {
1504 ev.index = k;
1505 ev.immediate = true;
1506 ev.arcs = ctmc_detail::lal_arcs(lal_fjfilt[k], nullptr);
1507 collect->events.push_back(std::move(ev));
1508 }
1509 // A batch arc departs b jobs and lands each accepted one where it was
1510 // routed: one record per job, the destination's passive half, or a lost
1511 // job's record (it arrived nowhere). A timed event, so a purged
1512 // (vanishing) row keeps no arc.
1513 for (const ctmc_detail::BatchGroup<T>& bg : batch_groups) {
1516 ev.index = bg.acts.front();
1517 ev.immediate = false;
1518 for (std::size_t q = 0; q < bg.acts.size(); ++q) {
1519 for (std::size_t c = 0; c < bg.outcome[q].first; ++c) ev.jobs.push_back(std::make_pair(bg.acts[q], false));
1520 for (std::size_t c = 0; c < bg.outcome[q].second; ++c) ev.jobs.push_back(std::make_pair(bg.acts[q], true));
1521 }
1522 for (const auto& arc : bg.arcs)
1523 if (!purged[std::get<0>(arc)]) ev.arcs.push_back(arc);
1524 collect->events.push_back(std::move(ev));
1525 }
1526 }
1527
1528 make_infgen(res.Q);
1529 return res;
1530}
1531
1532/**
1533 * Port of the "now remove immediate transitions" block of `solver_ctmc.m`
1534 * (:812-870): eliminate the vanishing states by stochastic complementation.
1535 *
1536 * WHAT IT CHANGES AND WHAT IT MUST NOT. The chain shrinks to its TANGIBLE states
1537 * and every metric read from it is unchanged to the digits printed, because the
1538 * vanishing states carry ~1e-8 of the mass -- which is exactly why the omission
1539 * was invisible until a caller asked for the chain itself. `-a states` and
1540 * `-a gen` are the callers that see it: on `fj_tiny_closed` this takes the six
1541 * enumerated states to the four the other three codebases return.
1542 *
1543 * THE RATE COMPLEMENT IS NOT OPTIONAL. An action that fires ONLY from vanishing
1544 * states -- a fork firing, a join rendezvous, an immediate SPN mode -- has no
1545 * tangible row to be read off, so restricting `arv_rates` / `dep_rates` to the
1546 * tangible states alone would silently zero its flow. The rate observed from a
1547 * tangible state is its own plus the expected number of firings along the
1548 * vanishing excursion entered from it,
1549 *
1550 * r = total(nonimm) + Q12 (-Q22)^-1 imm_part(imm),
1551 *
1552 * which is `solver_ctmc_ratecomplement` applied to the immediate part and added
1553 * to the plain restriction of the total. The two agree term by term with the
1554 * reference's per-filtration form, since the totals are already the row sums.
1555 *
1556 * A no-op when the model declared no immediate source, which is the common case.
1557 */
1558template <class T>
1560 const T zero = num_traits<T>::from_int(0);
1561 if (res.vanishing.empty()) {
1562 res.Qimm = Matrix<T>();
1563 res.arv_rates_imm.clear();
1564 res.dep_rates_imm.clear();
1565 return;
1566 }
1567 const std::size_t n = res.Q.rows();
1568 std::vector<bool> is_van(n, false);
1569 for (std::size_t x = 0; x < res.vanishing.size(); ++x) is_van[res.vanishing[x]] = true;
1570 std::vector<std::size_t> nonimm;
1571 nonimm.reserve(n - res.vanishing.size());
1572 for (std::size_t s = 0; s < n; ++s)
1573 if (!is_van[s]) nonimm.push_back(s);
1574 if (nonimm.empty())
1575 throw NumericError(ErrorKind{"Degenerate"},
1576 "SolverCTMC: every state is vanishing; the chain has no tangible state to observe");
1577
1578 const mc::StochCompResult<T> sc = mc::ctmc_stochcomp(res.Q, nonimm);
1579 const std::size_t nk = nonimm.size(), nd = res.vanishing.size();
1580
1581 // The rate complement, batched: one elimination of (-Q22) serves every
1582 // (stateful, class) pair of both directions, which is what keeps the cost at
1583 // one factorization rather than 2*NF*R of them.
1584 const std::size_t NF = res.arv_rates.empty() ? 0 : res.arv_rates[0].size();
1585 const std::size_t R = NF == 0 ? 0 : res.arv_rates[0][0].size();
1586 const std::size_t ncol = 2 * NF * R;
1587 Matrix<T> corr;
1588 if (ncol > 0) {
1589 Matrix<T> B(nd, ncol, zero);
1590 for (std::size_t d = 0; d < nd; ++d) {
1591 const std::size_t s = res.vanishing[d];
1592 for (std::size_t f = 0; f < NF; ++f)
1593 for (std::size_t r = 0; r < R; ++r) {
1594 B(d, f * R + r) = res.arv_rates_imm[s][f][r];
1595 B(d, NF * R + f * R + r) = res.dep_rates_imm[s][f][r];
1596 }
1597 }
1598 const Matrix<T> X = ctmc_detail::censored_solve(sc.Q22, B);
1599 corr = Matrix<T>(nk, ncol, zero);
1600 for (std::size_t a = 0; a < nk; ++a)
1601 for (std::size_t c = 0; c < ncol; ++c) {
1602 T acc = zero;
1603 for (std::size_t d = 0; d < nd; ++d) acc = T(acc + sc.Q12(a, d) * X(d, c));
1604 corr(a, c) = acc;
1605 }
1606 }
1607
1608 std::vector<NetState<T>> space;
1609 std::vector<std::vector<std::vector<T>>> arv, dep;
1610 space.reserve(nk);
1611 arv.reserve(nk);
1612 dep.reserve(nk);
1613 for (std::size_t a = 0; a < nk; ++a) {
1614 space.push_back(res.space[nonimm[a]]);
1615 arv.push_back(res.arv_rates[nonimm[a]]);
1616 dep.push_back(res.dep_rates[nonimm[a]]);
1617 for (std::size_t f = 0; f < NF; ++f)
1618 for (std::size_t r = 0; r < R; ++r) {
1619 arv[a][f][r] = T(arv[a][f][r] + corr(a, f * R + r));
1620 dep[a][f][r] = T(dep[a][f][r] + corr(a, NF * R + f * R + r));
1621 }
1622 }
1623
1624 // Each filtration is complemented exactly as Q is: an event that reaches a
1625 // tangible state THROUGH a vanishing excursion belongs on the arc it induces,
1626 // and dropping the excursion rows would lose it from every CDF built on the
1627 // split. The derived START and PREEMPT filtrations take the same treatment --
1628 // a service start that lands on a vanishing state would otherwise undercount.
1629 ctmc_detail::complement_filtrations(res, nonimm, res.vanishing, sc);
1630
1631 res.Q = sc.S;
1632 res.space.swap(space);
1633 res.arv_rates.swap(arv);
1634 res.dep_rates.swap(dep);
1635 res.Qimm = Matrix<T>();
1636 res.arv_rates_imm.clear();
1637 res.dep_rates_imm.clear();
1638 res.vanishing.clear();
1639}
1640
1641
1642/**
1643 * Left-pad an ordered-buffer station's seed row to the width its CAPACITY
1644 * implies, rather than the width its INITIAL MARKING gave it.
1645 *
1646 * `from_marginal_node` sizes an ordered buffer from the occupancy it is asked
1647 * for -- `max(1, n - S)` waiting slots, so an empty FCFS station comes back with
1648 * exactly ONE. The lattice generator never uses that width, because it
1649 * enumerates every marginal up to the capacity and the fullest one sets the
1650 * space. The reachable walk has no such pass, and the arrival handler REFUSES a
1651 * job that finds no free slot instead of appending one -- deliberately, since
1652 * under the lattice a full row means the state-space cutoff and the state above
1653 * the cutoff is absent rather than blocked (`after_event_station`, ORDERED
1654 * BUFFER).
1655 *
1656 * Seeded at the marginal width, an ordered-buffer station therefore cannot hold
1657 * more than `S + 1` jobs for the whole walk. On a fork-join model that truncates
1658 * the chain as soon as three siblings can queue at one branch: the closed
1659 * model of `fj_closed_fcfs` reported X = 1.42385 at N = 3 against the exact
1660 * 1.436073, and got worse with N. The reference reaches the full space by
1661 * growing the buffer inside the arrival handler
1662 * (`State.afterEventStation`, "this section dynamically grows the number of
1663 * elements in the buffer"); widening the seed instead keeps this port's stricter
1664 * width rule and costs one zero-padding per station.
1665 *
1666 * The buffer is right-aligned and leads the row, so zeros on the left add empty
1667 * slots and change nothing else. A station whose capacity is NOT finite is left
1668 * alone: there the walk is bounded by the `cutoff` argument, which censors whole
1669 * states rather than sizing one row, and widening would only invite the walk to
1670 * run past it.
1671 */
1672template <class T>
1674 NetState<T> out = init;
1675 for (std::size_t isf = 0; isf < out.local.size(); ++isf) {
1676 const std::size_t ind = isf < sn.stateful_nodes.size() ? sn.stateful_nodes[isf] : 0;
1677 if (ind == 0 || ind > sn.nodes.size()) continue;
1678 const std::size_t ist = sn.nodes[ind - 1].station;
1679 if (ist == 0) continue; // a Fork, Join or Router carries no buffer/server split
1680 const SchedStrategy sched = sn.stations[ist - 1].sched;
1681 std::size_t percol = 0;
1682 if (qn::state_detail::buffer_is_class_tag(sched)) percol = 1;
1683 else if (qn::state_detail::buffer_is_tag_phase_pairs(sched)) percol = 2;
1684 else continue; // a per-class-count buffer is R wide whatever the occupancy
1685 const double S = sn.stations[ist - 1].nservers;
1686 const double capi = ist <= sn.cap.size() ? sn.cap[ist - 1] : 0.0;
1687 if (!std::isfinite(S) || !std::isfinite(capi) || capi <= 0) continue;
1688 std::size_t srvw = 0;
1689 for (std::size_t r = 0; r < sn.nclasses; ++r) srvw += sn.phasessz_of(ist, r + 1);
1690 const std::size_t nvar = sn.nvars_of(ind);
1691 if (out.local[isf].size() <= srvw + nvar) continue;
1692 const std::size_t bufw = out.local[isf].size() - srvw - nvar;
1693 // A setup/delay-off or server-parallelism station can hold EVERY job
1694 // waiting -- servers OFF or setting up, or too few free for the head --
1695 // so it needs a slot per job, not per job beyond S (python
1696 // `_widen_ordered_buffer`).
1697 const bool holds_idle = (sn.setupparam.count(ist) && qn::ctmc_tail_width(sn, ind) > 0) ||
1698 !qn::parallelism_of(sn, ind).empty();
1699 const long slots = holds_idle ? static_cast<long>(capi)
1700 : static_cast<long>(capi) - static_cast<long>(S);
1701 const std::size_t want = static_cast<std::size_t>(slots > 1 ? slots : 1) * percol;
1702 if (want <= bufw) continue;
1703 std::vector<T> row(want - bufw, num_traits<T>::from_int(0));
1704 row.insert(row.end(), out.local[isf].begin(), out.local[isf].end());
1705 out.local[isf] = row;
1706 }
1707 return out;
1708}
1709
1710
1711/**
1712 * Port of `State.reachableSpaceGenerator`: the states reachable from `init`.
1713 *
1714 * `space_generator` enumerates every state the ENCODING admits; this walks the
1715 * ones the DYNAMICS can actually occupy. The two differ whenever the encoding
1716 * is wider than the model -- a retrial station's idle-server states are
1717 * reachable, whereas an ordinary queue's are not, and enumerating the latter
1718 * leaves a generator with absorbing junk that perturbs the stationary vector
1719 * after normalization.
1720 *
1721 * The walk applies exactly the same handlers the generator does, so a state is
1722 * included precisely when some synchronization produces it at a positive rate.
1723 *
1724 * IT IS THE ONLY GENERATOR AN SPN HAS. `from_marginal_node` emits a single row
1725 * for a Transition -- every mode's servers free, nothing firing -- because a
1726 * transition's state is per-MODE and no population marginal determines it. The
1727 * lattice enumeration therefore never produces a state in which a mode is
1728 * firing, and a generator built over that space has every ENABLE landing
1729 * outside it. Walking `gsync` from the idle state is what materializes them,
1730 * which is why the reference forces `state_space_gen='reachable'` for any model
1731 * whose firings break per-chain population conservation.
1732 *
1733 * `cutoff` TRUNCATES AN OPEN CLASS, and without it this walk does not terminate.
1734 * The lattice generator bounds an open class's total population by the cutoff;
1735 * this walk had no such bound, so on ANY open SPN -- `spn_basic_open` at cutoff
1736 * 1, `spn_pareto_service`, `spn_open_sevenplaces` -- the Source kept producing
1737 * tokens and the walk ran to the `maxst` cap instead of answering. Passing the
1738 * same cutoff makes the two paths mean the same thing by "cutoff": a candidate
1739 * whose open-class population would exceed it is not a state of the truncated
1740 * chain, so the arc to it simply does not exist and `make_infgen` re-closes the
1741 * row, which is exactly what the lattice path leaves behind. Empty means
1742 * unbounded, which is right for a closed model and is what every existing
1743 * caller passes.
1744 *
1745 * THE INITIAL MARKING RAISES THE BOUND WHERE IT EXCEEDS IT. A Place may start
1746 * with more tokens than the cutoff -- `spn_open_sevenplaces` puts 2 in P1
1747 * against a default cutoff of 2 -- and a bound below the state the walk starts
1748 * from censors every successor of it, leaving the initial state alone in a
1749 * chain that is not the model's. A state space that cannot contain its own
1750 * initial state is empty by construction, so the floor is the initial marking.
1751 */
1752template <class T>
1753std::vector<NetState<T>> reachable_space_generator(
1754 const NetworkStruct<T>& sn, const NetState<T>& init, const std::vector<Sync<T>>& sync,
1755 const std::vector<qn::GlobalSync<T>>& gsync = std::vector<qn::GlobalSync<T>>(),
1756 std::size_t maxst = 3000000,
1757 const std::vector<qn::FjSync<T>>& fjsync = std::vector<qn::FjSync<T>>(),
1758 const std::vector<std::size_t>& cutoff = std::vector<std::size_t>(),
1759 const std::vector<std::vector<std::size_t>>& cutoff_mat =
1760 std::vector<std::vector<std::size_t>>()) {
1761 const std::size_t local = sn.nodes.size() + 1;
1762 // The seed carries the width of the INITIAL MARKING; the walk needs the
1763 // width the station's capacity implies, because the arrival handler refuses
1764 // rather than grows. See `reachable_seed_widen`.
1765 const NetState<T> seed = reachable_seed_widen(sn, init);
1766 std::vector<NetState<T>> out;
1767 std::map<std::vector<double>, std::size_t> seen;
1768 std::vector<std::size_t> stack;
1769 const std::vector<double> njobs = sn.njobs();
1770 // Only an OPEN class can leave the bound, so a closed model pays nothing.
1771 bool bound = false;
1772 for (std::size_t r = 0; r < sn.nclasses && r < njobs.size(); ++r)
1773 if (!std::isfinite(njobs[r]) && r < cutoff.size() && cutoff[r] > 0) bound = true;
1774 const bool bounded = bound;
1775 std::vector<std::size_t> lim = cutoff;
1776 if (bounded) {
1777 const std::vector<double> n0 = ctmc_detail::state_peak_occupancy(sn, seed);
1778 for (std::size_t r = 0; r < lim.size() && r < n0.size(); ++r) {
1779 const std::size_t p0 =
1780 n0[r] > 0 ? static_cast<std::size_t>(std::floor(n0[r] + 0.5)) : 0;
1781 if (p0 > lim[r]) lim[r] = p0;
1782 }
1783 }
1784
1785 seen[ctmc_detail::state_key(seed)] = 0;
1786 out.push_back(seed);
1787 stack.push_back(0);
1788
1789 std::size_t expanded = 0;
1790 while (!stack.empty()) {
1791 // Wall-clock budget (options.timeout), read every 1024 expanded states.
1792 // A state space cut short has no valid partial solution, so it raises.
1793 if ((++expanded & 1023u) == 0)
1794 util::timeout_check("CTMC state-space generation (lower the cutoff or raise the budget)");
1795 const std::size_t si = stack.back();
1796 stack.pop_back();
1797 const NetState<T> st = out[si]; // by value: `out` grows inside the loop
1798
1799 for (std::size_t a = 0; a < sync.size(); ++a) {
1800 const Sync<T>& sy = sync[a];
1801 const std::size_t isf_a = sn.stateful_index(sy.active.node);
1802 if (isf_a == 0) continue;
1803 const std::size_t isf_p =
1804 sy.passive.node == local ? 0 : sn.stateful_index(sy.passive.node);
1805 if (sy.passive.node != local && isf_p == 0) continue;
1806
1807 // The reachable set must be walked with the same arcs the generator
1808 // uses, or immediate feedback would reach states the generator never
1809 // fills in (and miss the ones it does). See qn::immfeed_self_loop.
1810 const EventOutcome<T> oa =
1811 qn::after_event(sn, sy.active.node, st.local[isf_a - 1], sy.active.event,
1812 sy.active.cls, qn::immfeed_self_loop(sn, sy));
1813 for (std::size_t ia = 0; ia < oa.space.size(); ++ia) {
1814 if (num_traits<T>::to_double(oa.rate[ia]) <= 0) continue;
1815
1816 std::vector<NetState<T>> cand;
1817 if (sy.passive.node == local) {
1818 NetState<T> nsx = st;
1819 nsx.local[isf_a - 1] = oa.space[ia];
1820 cand.push_back(nsx);
1821 } else {
1822 const std::vector<T>& src =
1823 sy.passive.node == sy.active.node ? oa.space[ia] : st.local[isf_p - 1];
1824 const EventOutcome<T> op = qn::after_event(sn, sy.passive.node, src,
1825 sy.passive.event, sy.passive.cls);
1826 for (std::size_t ip = 0; ip < op.space.size(); ++ip) {
1827 if (num_traits<T>::to_double(op.prob[ip]) <= 0) continue;
1828 NetState<T> nsx = st;
1829 nsx.local[isf_a - 1] = oa.space[ia];
1830 nsx.local[isf_p - 1] = op.space[ip];
1831 cand.push_back(nsx);
1832 }
1833 }
1834 for (std::size_t c = 0; c < cand.size(); ++c) {
1835 if (bounded && !ctmc_detail::within_cutoff(sn, cand[c], njobs, lim, cutoff_mat))
1836 continue;
1837 const std::vector<double> key = ctmc_detail::state_key(cand[c]);
1838 if (seen.find(key) != seen.end()) continue;
1839 if (out.size() >= maxst)
1840 throw UnsupportedError(ErrorKind{"StateSpace"},
1841 "reachable_space_generator: the reachable state space exceeds the "
1842 "cap of " + std::to_string(maxst) + " states");
1843 seen[key] = out.size();
1844 out.push_back(cand[c]);
1845 stack.push_back(out.size() - 1);
1846 }
1847 }
1848 }
1849
1850 // The SPN half of the walk. A global synchronization already returns
1851 // WHOLE network states, since a firing is atomic across every arc it
1852 // touches and cannot be decomposed into an active and a passive half.
1853 for (std::size_t g = 0; g < gsync.size(); ++g) {
1854 const qn::GlobalOutcome<T> go = qn::after_global_event(sn, st, gsync[g]);
1855 for (std::size_t io = 0; io < go.space.size(); ++io) {
1856 if (num_traits<T>::to_double(go.rate[io]) <= 0) continue;
1857 if (num_traits<T>::to_double(go.prob[io]) <= 0) continue;
1858 if (bounded && !ctmc_detail::within_cutoff(sn, go.space[io], njobs, lim, cutoff_mat))
1859 continue;
1860 const std::vector<double> key = ctmc_detail::state_key(go.space[io]);
1861 if (seen.find(key) != seen.end()) continue;
1862 if (out.size() >= maxst)
1863 throw UnsupportedError(ErrorKind{"StateSpace"},
1864 "reachable_space_generator: the reachable state space exceeds the cap of " +
1865 std::to_string(maxst) + " states");
1866 seen[key] = out.size();
1867 out.push_back(go.space[io]);
1868 stack.push_back(out.size() - 1);
1869 }
1870 }
1871
1872 // The fork-join half. A firing is atomic in the same sense and returns
1873 // whole network states too; it is walked here rather than folded into the
1874 // sync loop because it has no active/passive decomposition at all.
1875 for (std::size_t k = 0; k < fjsync.size(); ++k) {
1876 const qn::GlobalOutcome<T> fo = qn::after_fj_event(sn, fjsync[k], st);
1877 for (std::size_t io = 0; io < fo.space.size(); ++io) {
1878 if (num_traits<T>::to_double(fo.rate[io]) <= 0) continue;
1879 if (num_traits<T>::to_double(fo.prob[io]) <= 0) continue;
1880 if (bounded && !ctmc_detail::within_cutoff(sn, fo.space[io], njobs, lim, cutoff_mat))
1881 continue;
1882 const std::vector<double> key = ctmc_detail::state_key(fo.space[io]);
1883 if (seen.find(key) != seen.end()) continue;
1884 if (out.size() >= maxst)
1885 throw UnsupportedError(ErrorKind{"StateSpace"},
1886 "reachable_space_generator: the reachable state space exceeds the cap of " +
1887 std::to_string(maxst) + " states");
1888 seen[key] = out.size();
1889 out.push_back(fo.space[io]);
1890 stack.push_back(out.size() - 1);
1891 }
1892 }
1893 }
1894 return out;
1895}
1896
1897/**
1898 * Port of `StateSpaceAggr`: the per-(station, class) job counts of every state,
1899 * as an (nstates x nstations*nclasses) matrix in column block order
1900 * `(ist-1)*K + k`.
1901 *
1902 * It is what `@@SolverCTMC/getStateSpaceAggr` returns and what the transient
1903 * analyzer, the reward analyzer and the BAS shift all index; building it once
1904 * keeps the three from re-deriving the same marginal decode with three chances
1905 * to disagree about the buffer encoding.
1906 *
1907 * A SOURCE ROW IS ZERO, not Inf. `to_marginal` reports an infinite reservoir for
1908 * an EXT station, which describes the encoding rather than a queue length, and
1909 * an Inf here would propagate into every aggregate that sums this matrix.
1910 */
1911template <class T>
1913 const std::vector<NetState<T>>& space) {
1914 const std::size_t M = sn.stations.size(), K = sn.nclasses;
1915 const T zero = num_traits<T>::from_int(0);
1916 Matrix<T> A(space.size(), M * K, zero);
1917 for (std::size_t ist = 1; ist <= M; ++ist) {
1918 const std::size_t isf = sn.stateful_of_station(ist);
1919 const std::size_t ind = sn.node_of_station(ist);
1920 if (isf == 0) continue;
1921 if (sn.stations[ist - 1].nodetype == NodeType::Source) continue;
1922 std::vector<std::size_t> ph(K, 1), shift(K, 0);
1923 std::size_t w = 0;
1924 for (std::size_t k = 0; k < K; ++k) {
1925 ph[k] = sn.phasessz_of(ist, k + 1);
1926 shift[k] = w;
1927 w += ph[k];
1928 }
1929 const std::size_t nvar = sn.nvars_of(ind);
1930 for (std::size_t s = 0; s < space.size(); ++s) {
1931 const qn::Marginal<T> m =
1932 qn::to_marginal(sn, ist, space[s].local[isf - 1], ph, shift, nvar);
1933 for (std::size_t k = 0; k < K; ++k) A(s, (ist - 1) * K + k) = m.nir[k];
1934 }
1935 }
1936 return A;
1937}
1938
1939/**
1940 * Port of `ctmc_signal_lossy`: classes a G-network signal can annihilate here.
1941 *
1942 * Such a job leaves the station WITHOUT a service completion, so the
1943 * arrival-based (offered-load) utilization estimator is invalid for it and only
1944 * the departure-based carried load is meaningful -- the same reasoning as the
1945 * finite-capacity `canDropClass`, reached by a different route.
1946 *
1947 * A signal class is active at this node when its stationary arrival rate there
1948 * is positive. A TARGETED signal removes only its target class; an untargeted
1949 * one is class-agnostic and removes any non-signal class, matching
1950 * `after_event_station_signal`, MAM and LDES.
1951 */
1952template <class T>
1953std::vector<bool> ctmc_signal_lossy(const NetworkStruct<T>& sn, const CtmcResult<T>& r,
1954 const std::vector<T>& p, std::size_t isf) {
1955 const std::size_t K = sn.nclasses;
1956 std::vector<bool> lossy(K, false);
1957 bool any = false;
1958 for (std::size_t k = 0; k < K && k < sn.issignal.size(); ++k) any = any || sn.issignal[k];
1959 if (!any) return lossy;
1960
1961 for (std::size_t r2 = 1; r2 <= K; ++r2) {
1962 if (sn.issignal.size() < r2 || !sn.issignal[r2 - 1]) continue;
1963 // a REPLY completes a synchronous call and removes nobody
1964 if (sn.signaltype.size() >= r2 && sn.signaltype[r2 - 1] == lang::SignalType::REPLY) continue;
1965 T arv = num_traits<T>::from_int(0);
1966 for (std::size_t s = 0; s < r.space.size(); ++s)
1967 arv += T(p[s] * r.arv_rates[s][isf - 1][r2 - 1]);
1968 if (num_traits<T>::to_double(arv) <= 0) continue;
1969 const std::size_t tgt =
1970 sn.signaltarget.size() >= r2 ? sn.signaltarget[r2 - 1] : 0;
1971 if (tgt >= 1 && tgt <= K) {
1972 lossy[tgt - 1] = true;
1973 } else {
1974 for (std::size_t k = 0; k < K; ++k)
1975 if (k >= sn.issignal.size() || !sn.issignal[k]) lossy[k] = true;
1976 }
1977 }
1978 return lossy;
1979}
1980
1981/**
1982 * Port of `ctmc_signal_busy`: the exact per-class busy-server fraction, read
1983 * off the enumerated state space.
1984 *
1985 * WHY THE DEPARTURE ESTIMATOR IS NOT ENOUGH. `T*E[S]/c` is exact for a lossy
1986 * class only under EXPONENTIAL service: a job destroyed mid-service leaves busy
1987 * time behind with no completion to account for it, so with phase-type service
1988 * the carried-rate estimator under-counts. Measured on an M/Er2/1 with
1989 * lambda+ = 0.5 and lambda- = 0.4 it gives 0.34941 against a true 0.37696. The
1990 * in-service occupancy below is exact for any service process.
1991 *
1992 * A PS-like discipline shares the servers among every resident job, so class k
1993 * takes the weighted share n_k w_k / sum_j n_j w_j of the busy servers; every
1994 * other discipline exposes the in-service indicator directly through
1995 * `to_marginal`.
1996 */
1997template <class T>
1998std::vector<T> ctmc_signal_busy(const NetworkStruct<T>& sn, std::size_t ist,
1999 const CtmcResult<T>& r, const std::vector<T>& p,
2000 std::size_t isf) {
2001 const std::size_t K = sn.nclasses;
2002 const T zero = num_traits<T>::from_int(0);
2003 std::vector<T> unb(K, zero);
2004 const SchedStrategy sched = sn.stations[ist - 1].sched;
2005 const bool is_ps = sched == SchedStrategy::PS || sched == SchedStrategy::DPS ||
2006 sched == SchedStrategy::GPS || sched == SchedStrategy::LPS;
2007 const double S = sn.stations[ist - 1].nservers;
2008 const std::size_t ind = sn.node_of_station(ist);
2009
2010 std::vector<std::size_t> ph(K, 1), shift(K, 0);
2011 std::size_t w = 0;
2012 for (std::size_t k = 0; k < K; ++k) {
2013 ph[k] = sn.phasessz_of(ist, k + 1);
2014 shift[k] = w;
2015 w += ph[k];
2016 }
2017 const std::size_t nvar = sn.nvars_of(ind);
2018
2019 for (std::size_t s = 0; s < r.space.size(); ++s) {
2020 if (num_traits<T>::to_double(p[s]) == 0) continue;
2021 const qn::Marginal<T> m =
2022 qn::to_marginal(sn, ist, r.space[s].local[isf - 1], ph, shift, nvar);
2023 double ni = 0;
2024 for (std::size_t k = 0; k < K; ++k) ni += num_traits<T>::to_double(m.nir[k]);
2025 if (ni <= 0) continue;
2026 if (is_ps) {
2027 T wtot = zero;
2028 for (std::size_t k = 0; k < K; ++k)
2029 wtot += T(m.nir[k] * sn.stations[ist - 1].schedparam[k]);
2030 if (num_traits<T>::to_double(wtot) <= 0) continue;
2031 const double busy = std::min(ni, S) / S;
2032 for (std::size_t k = 0; k < K; ++k)
2033 unb[k] += T(p[s] * (m.nir[k] * sn.stations[ist - 1].schedparam[k] / wtot) *
2035 } else {
2036 for (std::size_t k = 0; k < K; ++k)
2037 unb[k] += T(p[s] * m.sir[k] / num_traits<T>::from_double(S));
2038 }
2039 }
2040 return unb;
2041}
2042
2043/**
2044 * MATLAB's `all(sn.isph(:))`, read off the matrices instead of off a flag.
2045 *
2046 * False as soon as one station-class process is a matrix exponential: its D0
2047 * carries negative off-diagonal entries, or its D1 negative entries, neither of
2048 * which a phase-type has. A Source keeps its arrival process in `sn.service`,
2049 * so this one scan covers arrivals and services alike.
2050 */
2051template <class T>
2053 for (std::size_t i = 0; i < sn.service.size(); ++i)
2054 for (std::size_t r = 0; r < sn.service[i].size(); ++r) {
2055 const lang::Distrib<T>& d = sn.service[i][r];
2056 if (d.disabled || d.D0.rows() == 0) continue;
2057 for (std::size_t a = 0; a < d.D0.rows(); ++a)
2058 for (std::size_t b = 0; b < d.D0.cols(); ++b)
2059 if (a != b && num_traits<T>::to_double(d.D0(a, b)) < 0) return false;
2060 for (std::size_t a = 0; a < d.D1.rows(); ++a)
2061 for (std::size_t b = 0; b < d.D1.cols(); ++b)
2062 if (num_traits<T>::to_double(d.D1(a, b)) < 0) return false;
2063 }
2064 return true;
2065}
2066
2067/** The mean performance metrics a stationary vector maps to. */
2068template <class T>
2069struct CtmcAvg {
2070 Matrix<T> QN, UN, RN, TN; ///< (nstations x nclasses)
2071 std::vector<T> XN, CN; ///< (nclasses) system throughput and response time
2072 /**
2073 * The DERIVED rates, (nstations x nclasses): how often per unit time a
2074 * class-r service STARTS at station i, and how often a class-r job in
2075 * service is PUSHED BACK into the buffer there. All zero unless the result
2076 * carried the filtrations they reduce (`solver_ctmc` was asked for them).
2077 *
2078 * At a lossless station with no in-service abandonment
2079 * StartN == TN + PreemptN,
2080 * because every job starts service once per entry into a server and every
2081 * preemption is followed by exactly one later resume or restart.
2082 */
2084};
2085
2086/**
2087 * Port of `solver_ctmc_avg_from_pi`: map a state distribution to mean metrics.
2088 *
2089 * Factored from the analyzer exactly as the reference factors it, so a caller
2090 * holding its own distribution -- a time-averaged transient one, say -- reuses
2091 * the same discipline-aware reduction instead of re-deriving it.
2092 *
2093 * `stationary` says whether `pivec` is a STATIONARY law. It is what selects the
2094 * utilization estimator: the arrival-rate and departure-rate readings coincide
2095 * only under flow balance, so `max(u_arv, u_dep)` is a numerical-noise guard at
2096 * stationarity and an UPWARD BIAS out of it. The SolverENV state-vector analyzer
2097 * passes a sojourn-averaged TRANSIENT law and must pass false; on the two-stage
2098 * environment of test_environment_statevec the max reported 1.9246 at a
2099 * single-server FCFS queue, impossible in LINE's per-server convention. MATLAB
2100 * and the JAR give the ENV path a file of its own (solver_ctmc_avg_from_pi.m,
2101 * Ctmc_avg_from_pi.java) which carries the departure-rate estimator alone; here
2102 * one function serves both callers, so the distinction is a parameter.
2103 * See _kb/06-solver-catalog.md.
2104 */
2105template <class T>
2107 const std::vector<T>& pivec, bool stationary = true) {
2108 const std::size_t M = sn.stations.size(), R = sn.nclasses, n = r.space.size();
2109 const T zero = num_traits<T>::from_int(0);
2110 CtmcAvg<T> a;
2111 a.QN = Matrix<T>(M, R, zero);
2112 a.UN = Matrix<T>(M, R, zero);
2113 a.RN = Matrix<T>(M, R, zero);
2114 a.TN = Matrix<T>(M, R, zero);
2115 a.XN.assign(R, zero);
2116 a.CN.assign(R, zero);
2117 a.StartN = Matrix<T>(M, R, zero);
2118 a.PreemptN = Matrix<T>(M, R, zero);
2119
2120 // Renormalize, clamping the numerical dust an eigenvector solve leaves
2121 // below the zero threshold. WITH A MATRIX EXPONENTIAL THE CLAMP IS SKIPPED:
2122 // the stationary vector is then a genuinely SIGNED measure, only its
2123 // aggregates over each phase block are probabilities, and deleting the
2124 // negative entries deletes real mass -- an M/CME/1 at rho = 0.3 came out
2125 // with QLen 0.4469 against the Pollaczek-Khinchine 0.3772. Every metric
2126 // below is linear in the vector and stays exact without the clamp.
2127 const bool signed_measure = !ctmc_all_phasetype(sn);
2128 std::vector<T> p = pivec;
2129 T tot = zero;
2130 for (std::size_t s = 0; s < n; ++s) {
2131 if (!signed_measure && num_traits<T>::to_double(p[s]) < GlobalConstants::Zero) p[s] = zero;
2132 tot += p[s];
2133 }
2134 if (num_traits<T>::to_double(tot) > 0)
2135 for (std::size_t s = 0; s < n; ++s) p[s] = T(p[s] / tot);
2136
2137 // System throughput is the arrival rate seen at each class's REFERENCE
2138 // station, which is what makes X a per-class quantity rather than a sum.
2139 for (std::size_t k = 1; k <= R; ++k) {
2140 const std::size_t refsf = sn.stateful_of_station(sn.classes[k - 1].refstat);
2141 for (std::size_t s = 0; s < n; ++s) a.XN[k - 1] += T(p[s] * r.arv_rates[s][refsf - 1][k - 1]);
2142 }
2143
2144 // The derived rates: pi * F * e over each filtration, the same reduction
2145 // the departure rates use, so the three are directly comparable.
2146 for (std::size_t ist = 1; ist <= M && ist <= r.start_filt.size(); ++ist)
2147 for (std::size_t k = 1; k <= R && k <= r.start_filt[ist - 1].size(); ++k) {
2148 T accs = zero, accp = zero;
2149 for (std::size_t s = 0; s < n; ++s) {
2150 T rows = zero, rowp = zero;
2151 for (std::size_t ns = 0; ns < n; ++ns) {
2152 rows += r.start_filt[ist - 1][k - 1](s, ns);
2153 rowp += r.preempt_filt[ist - 1][k - 1](s, ns);
2154 }
2155 accs += T(p[s] * rows);
2156 accp += T(p[s] * rowp);
2157 }
2158 a.StartN(ist - 1, k - 1) = accs;
2159 a.PreemptN(ist - 1, k - 1) = accp;
2160 }
2161
2162 for (std::size_t ist = 1; ist <= M; ++ist) {
2163 const std::size_t isf = sn.stateful_of_station(ist);
2164 const std::size_t ind = sn.node_of_station(ist);
2165 const bool is_source = sn.stations[ist - 1].nodetype == NodeType::Source;
2166 const double S = sn.stations[ist - 1].nservers;
2167 std::vector<std::size_t> ph(R, 1), shift(R, 0);
2168 std::size_t w = 0;
2169 for (std::size_t r2 = 0; r2 < R; ++r2) {
2170 ph[r2] = sn.phasessz_of(ist, r2 + 1);
2171 shift[r2] = w;
2172 w += ph[r2];
2173 }
2174 const std::size_t nvar = sn.nvars_of(ind);
2175
2176 for (std::size_t k = 1; k <= R; ++k)
2177 for (std::size_t s = 0; s < n; ++s)
2178 a.TN(ist - 1, k - 1) += T(p[s] * r.dep_rates[s][isf - 1][k - 1]);
2179
2180 if (is_source) {
2181 // `to_marginal` encodes a Source as nir = Inf, an infinite
2182 // reservoir. That is a statement about the ENCODING, not a queue
2183 // length; reading it as one gives Q = Inf and then R = Q/T = Inf.
2184 continue;
2185 }
2186
2187 for (std::size_t s = 0; s < n; ++s) {
2188 if (num_traits<T>::to_double(p[s]) == 0) continue;
2189 const qn::Marginal<T> m =
2190 qn::to_marginal(sn, ist, r.space[s].local[isf - 1], ph, shift, nvar);
2191 for (std::size_t k = 1; k <= R; ++k) a.QN(ist - 1, k - 1) += T(p[s] * m.nir[k - 1]);
2192 }
2193
2194 const SchedStrategy sched = sn.stations[ist - 1].sched;
2195 // PAS / order-independent: utilization is the IN-SERVICE occupancy, not
2196 // the offered load. The two coincide only when a job engages a single
2197 // server, which is exactly what a pass-and-swap station does not do.
2198 // A heterogeneous-server station reads the same way: E[jobs in service] over the bank.
2199 if (sched == SchedStrategy::PAS || (!sn.ctmcpool.empty() && sn.ctmcpool.count(ind))) {
2200 for (std::size_t s = 0; s < n; ++s) {
2201 if (num_traits<T>::to_double(p[s]) == 0) continue;
2202 const qn::Marginal<T> m =
2203 qn::to_marginal(sn, ist, r.space[s].local[isf - 1], ph, shift, nvar);
2204 for (std::size_t k = 0; k < R; ++k)
2205 a.UN(ist - 1, k) += T(p[s] * m.sir[k] / num_traits<T>::from_double(S));
2206 }
2207 continue;
2208 }
2209 // A load-dependent station has no single service rate, so `T*E[S]/c` is
2210 // not its utilization: the reference accumulates the per-state capacity
2211 // share weighted by the lld factor and divides by the EFFECTIVE server
2212 // count max(c, max lld), which is what the scaling can deliver.
2213 // A class- or joint-dependent station takes the SAME branch: none of the
2214 // three has a single service rate, so `T*E[S]/c` is not its utilization.
2215 // The reference gates all three on one `isempty(lld) && isempty(cd) &&
2216 // isempty(jd)` test, and the cd/jd cases are then OVERWRITTEN by the
2217 // declared-peak normalization at the end of this function -- this branch
2218 // is what a jd-only station keeps, and what a cd station holds until the
2219 // peak pass replaces it.
2220 const std::vector<T>& lld = sn.stations[ist - 1].lldscaling;
2221 if (!lld.empty() || sn.stations[ist - 1].cdscaling || sn.stations[ist - 1].jdscaling) {
2222 double ceff = S;
2223 for (std::size_t j = 0; j < lld.size(); ++j)
2224 ceff = std::max(ceff, num_traits<T>::to_double(lld[j]));
2225 const bool share = sched == SchedStrategy::PS || sched == SchedStrategy::DPS ||
2226 sched == SchedStrategy::GPS || sched == SchedStrategy::LPS;
2227 for (std::size_t s = 0; s < n; ++s) {
2228 if (num_traits<T>::to_double(p[s]) == 0) continue;
2229 const qn::Marginal<T> m =
2230 qn::to_marginal(sn, ist, r.space[s].local[isf - 1], ph, shift, nvar);
2231 double ni = 0;
2232 for (std::size_t k = 0; k < R; ++k) ni += num_traits<T>::to_double(m.nir[k]);
2233 if (ni <= 0) continue;
2234 double lldnow = 1.0;
2235 if (!lld.empty()) {
2236 const std::size_t li = std::min<std::size_t>(
2237 lld.size(), std::max<std::size_t>(1, static_cast<std::size_t>(ni)));
2238 lldnow = num_traits<T>::to_double(lld[li - 1]);
2239 }
2240 if (share) {
2241 T wtot = zero;
2242 for (std::size_t k = 0; k < R; ++k)
2243 wtot += T(m.nir[k] * sn.stations[ist - 1].schedparam[k]);
2244 if (num_traits<T>::to_double(wtot) <= 0) continue;
2245 for (std::size_t k = 0; k < R; ++k)
2246 a.UN(ist - 1, k) +=
2247 T(p[s] * (m.nir[k] * sn.stations[ist - 1].schedparam[k] / wtot) *
2248 num_traits<T>::from_double(lldnow / ceff));
2249 } else {
2250 double sirtot = 0;
2251 for (std::size_t k = 0; k < R; ++k)
2252 sirtot += num_traits<T>::to_double(m.sir[k]);
2253 if (sirtot <= 0) continue;
2254 for (std::size_t k = 0; k < R; ++k)
2255 a.UN(ist - 1, k) += T(p[s] * num_traits<T>::from_double(
2257 sirtot * lldnow / ceff));
2258 }
2259 }
2260 continue;
2261 }
2262 if (sched == SchedStrategy::INF) {
2263 // An infinite server is "utilized" by every job it holds: there is
2264 // no queueing, so utilization and queue length coincide.
2265 for (std::size_t k = 1; k <= R; ++k) a.UN(ist - 1, k - 1) = a.QN(ist - 1, k - 1);
2266 } else {
2267 // A class that can be DROPPED here -- an open class at a station
2268 // with a finite capacity -- must be measured on the CARRIED rate
2269 // alone. The offered rate counts arrivals that never entered
2270 // service, so `max` would report the offered load as utilization:
2271 // for an M/M/1/4 with lambda = 0.6 that is 0.6 against the true
2272 // 1 - p0 = 0.566. Where nothing can be dropped the two estimates
2273 // agree in steady state and the max only guards numerical noise.
2274 // A class a G-network SIGNAL can annihilate is droppable for the
2275 // same reason a capacity-limited one is: the job leaves without a
2276 // completion, so the offered rate is not what the server did.
2277 const std::vector<bool> lossy = ctmc_signal_lossy(sn, r, p, isf);
2278 // A station inside a DROP region loses arrivals it cannot admit,
2279 // exactly as a finite per-station capacity does, so the same
2280 // carried-rate rule applies there.
2281 bool in_drop = false;
2282 for (std::size_t f = 0; f < sn.regions.size() && !in_drop; ++f) {
2283 bool has_drop = false;
2284 for (std::size_t rr = 0; rr < sn.regions[f].rule.size(); ++rr)
2285 if (sn.regions[f].rule[rr] == lang::DropStrategy::DROP) has_drop = true;
2286 if (has_drop && ist - 1 < sn.regions[f].members.size() &&
2287 sn.regions[f].members[ist - 1])
2288 in_drop = true;
2289 }
2290 for (std::size_t k = 1; k <= R; ++k) {
2291 // A job that reneges or balks leaves without service, as a dropped one does. RENEGING counts for
2292 // closed classes too, as MATLAB ORs impatienceClass == RENEGING in unconditionally (lam 0.8, mu 1,
2293 // Exp(0.5) patience: Util 0.59525 = TN*E[S], not the offered 0.8).
2294 const qn::Station<T>& stk = sn.stations[ist - 1];
2295 const bool reneging = qn::station_renege_mu(sn, ist, k) > zero;
2296 const bool balking = k <= stk.balking.size() &&
2297 stk.balking[k - 1].strategy != lang::BalkingStrategy::NONE;
2298 // A job that fails its last allowed retry leaves the orbit unserved
2299 // (retrial with a finite maxAttempts, ctmc_blocks.h), so the class is
2300 // measured on its carried rate too.
2301 const qn::AttemptsLayout att = qn::attempts_layout(sn, ind);
2302 const bool retrial_loss = att.valid && att.cls == k;
2303 const bool can_drop =
2304 (!std::isfinite(sn.njobs()[k - 1]) &&
2305 (std::isfinite(sn.cap[ist - 1]) ||
2306 std::isfinite(sn.classcap[ist - 1][k - 1]) || in_drop || balking ||
2307 retrial_loss)) ||
2308 reneging || lossy[k - 1];
2309 const lang::Distrib<T>& d = sn.service[ist - 1][k - 1];
2310 if (d.disabled || d.D0.rows() == 0) continue;
2311 mam::Map<T> mp;
2312 mp.D0 = d.D0;
2313 mp.D1 = d.D1;
2314 const T mean = mam::map_mean(mp);
2315 const T u_dep = T(a.TN(ist - 1, k - 1) * mean / num_traits<T>::from_double(S));
2316 if (can_drop) {
2317 a.UN(ist - 1, k - 1) = u_dep;
2318 continue;
2319 }
2320 if (!stationary) {
2321 // Out of steady state the offered rate is not what the
2322 // server did; see the note on `stationary` above.
2323 a.UN(ist - 1, k - 1) = u_dep;
2324 continue;
2325 }
2326 T arv = zero;
2327 for (std::size_t s = 0; s < n; ++s)
2328 arv += T(p[s] * r.arv_rates[s][isf - 1][k - 1]);
2329 const T u_arv = T(arv * mean / num_traits<T>::from_double(S));
2330 a.UN(ist - 1, k - 1) =
2332 : u_dep;
2333 }
2334 // A job holding n servers keeps n of them busy (server parallelism,
2335 // python `_compute_metrics_sync`): T*E[S]*n_k/c.
2336 const std::vector<double> par = qn::parallelism_of(sn, ind);
2337 for (std::size_t k = 0; k < par.size() && k < R; ++k)
2338 a.UN(ist - 1, k) = T(a.UN(ist - 1, k) * num_traits<T>::from_double(par[k]));
2339 // For a lossy class the carried rate is still not exact unless the
2340 // service is exponential, so the in-service occupancy read off the
2341 // state space REPLACES it -- see `ctmc_signal_busy`.
2342 bool anylossy = false;
2343 for (std::size_t k = 0; k < R; ++k) anylossy = anylossy || lossy[k];
2344 if (anylossy) {
2345 const std::vector<T> unb = ctmc_signal_busy(sn, ist, r, p, isf);
2346 for (std::size_t k = 0; k < R; ++k)
2347 if (lossy[k]) a.UN(ist - 1, k) = unb[k];
2348 }
2349 }
2350 }
2351
2352 // TRUE BAS: a held job is counted at its DESTINATION, in the class it
2353 // enters as, not where it sits.
2354 //
2355 // The state has it at the blocking station -- that is what the held-job
2356 // block means -- but it has FINISHED service there and is on its way out, so
2357 // reporting it in the upstream queue length would double-count the time it
2358 // spends waiting for room. The block counts the held jobs per target code
2359 // (BUG-110), so the mean count of each code moves from (ist, r) to (jst, s);
2360 // a delay's utilization is its queue length, so it loses the same share. The
2361 // former single marker said only THAT a job was held, so the shift was capped
2362 // at one job and made only where the destination was unique.
2363 for (std::size_t ist = 1; ist <= M && !sn.isbasblocking.empty(); ++ist) {
2364 const std::size_t ind = sn.node_of_station(ist);
2365 const std::size_t isf = sn.stateful_of_station(ist);
2366 if (ind == 0 || isf == 0 || ind > sn.isbasblocking.size()) continue;
2367 if (!sn.isbasblocking[ind - 1]) continue;
2368 const std::vector<std::size_t> codes = sn.bas_marker_codes(ind);
2369 if (codes.empty()) continue;
2370 const std::size_t nc = qn::NetworkStruct<T>::bas_ncols(codes);
2371 const bool inf = sn.stations[ist - 1].sched == SchedStrategy::INF;
2372 for (std::size_t kk = 0; kk < codes.size(); ++kk) {
2373 std::size_t rr = 0, jst = 0, ss = 0;
2374 sn.bas_decode(codes[kk], rr, jst, ss);
2375 T shift = zero;
2376 for (std::size_t s = 0; s < n; ++s) {
2377 const std::vector<T>& row = r.space[s].local[isf - 1];
2378 if (row.size() < nc) continue;
2379 shift += T(p[s] * row[row.size() - nc + kk]);
2380 }
2381 if (!(num_traits<T>::to_double(shift) > 0)) continue;
2382 a.QN(ist - 1, rr - 1) -= shift;
2383 a.QN(jst - 1, ss - 1) += shift;
2384 if (inf) a.UN(ist - 1, rr - 1) -= shift;
2385 }
2386 }
2387
2388 // DECLARED-PEAK UTILIZATION at a class- or joint-dependent station. The
2389 // per-state capacity share accumulated above is a busy-server probability,
2390 // and at a dependent station that is not what utilization means: a beta_r(n)
2391 // emulating extra servers would report more than one. The reference REPLACES
2392 // it by T/mu/peak, restoring the T*S/c convention against the DECLARED peak.
2393 //
2394 // The `all njobs finite` guard is the reference's and is not a convenience:
2395 // with an open class the state space is a TRUNCATION, so the throughput this
2396 // divides is the truncated chain's and the ratio is not a utilization of the
2397 // model. The busy-server estimate above at least stays a probability, so it
2398 // is what an open dependent station keeps.
2399 //
2400 // THE PEAKS MULTIPLY. beta_r(n), eta_i(n) and the global phi(n) scale the
2401 // SAME nominal rate and the event layer folds them multiplicatively
2402 // (`cd_factor`), so the peak attainable rate is
2403 // `rates * cdpeak * jdpeak * gdpeak`. The reference used to run two
2404 // independent blocks each ASSIGNING UN, which let the jd peak overwrite the cd
2405 // one and dropped a factor `cdpeak` at a station carrying both; that was fixed
2406 // in `solver_ctmc_analyzer.m` / `solver_ctmc_avg_from_pi.m` together with this
2407 // port, and it is what SolverSSA already did
2408 // (`solver_ssa_analyzer_serial.m:87-90`).
2409 bool all_closed = true;
2410 for (std::size_t k = 0; k < R; ++k)
2411 if (!std::isfinite(sn.njobs()[k])) all_closed = false;
2412 const bool has_gd = static_cast<bool>(sn.gdscaling);
2413 if (all_closed) {
2414 for (std::size_t ist = 1; ist <= M; ++ist) {
2415 const qn::Station<T>& st = sn.stations[ist - 1];
2416 const bool has_cd = static_cast<bool>(st.cdscaling);
2417 const bool has_jd = static_cast<bool>(st.jdscaling);
2418 if (!has_cd && !has_jd && !has_gd) continue;
2419 for (std::size_t k = 0; k < R; ++k) {
2420 double bmax = 1.0;
2421 if (has_cd)
2422 bmax *= k < st.cdscalingpeak.size()
2424 : 0.0;
2425 if (has_jd)
2426 bmax *= k < st.jdscalingpeak.size()
2428 : 0.0;
2429 // phi(n) scales the same nominal rate from the WHOLE population,
2430 // so its declared peak joins the product at every station, the
2431 // delays among them; `sn.gdscalingpeak` is (M x R) row-major.
2432 if (has_gd)
2433 bmax *= (ist - 1) * R + k < sn.gdscalingpeak.size()
2434 ? num_traits<T>::to_double(sn.gdscalingpeak[(ist - 1) * R + k])
2435 : 0.0;
2436 const double mu = num_traits<T>::to_double(sn.rates(ist - 1, k));
2437 a.UN(ist - 1, k) = (std::isfinite(mu) && mu > 0 && bmax > 0)
2438 ? T(a.TN(ist - 1, k) /
2439 num_traits<T>::from_double(mu * bmax))
2440 : zero;
2441 }
2442 }
2443 }
2444
2445 // SYNCHRONOUS CALLS. A caller blocked waiting for its reply still HOLDS its
2446 // server, so those jobs belong in QLen and Util even though they are not in
2447 // service here. They are NOT in the response time: response time is time
2448 // spent AT the station, and the blocked job is at its callee.
2449 Matrix<T> qn_blocked(M, R, zero);
2450 if (!sn.replyblock.empty()) {
2451 for (std::size_t ist = 1; ist <= M; ++ist) {
2452 const std::size_t ind = sn.node_of_station(ist);
2453 const std::size_t isf = sn.stateful_of_station(ist);
2454 if (isf == 0 || sn.replyblock.size() < ind) continue;
2455 bool any = false;
2456 for (std::size_t k = 0; k < sn.replyblock[ind - 1].size(); ++k)
2457 any = any || sn.replyblock[ind - 1][k];
2458 if (!any) continue;
2459 const qn::ReplyBlockInfo info = qn::reply_block_info(sn, ind);
2460 if (info.width == 0) continue;
2461 const double S2 = sn.stations[ist - 1].nservers;
2462 // One counter per calling class, in the order `reply_block_info`
2463 // lists them, at its slot inside the local-variable block. They are
2464 // the LAST columns of the row unless a CTMC station block
2465 // (setup/delay-off, attempt levels; ctmc_blocks.h) trails them, so
2466 // the column is read from the slot, not from the right-hand end.
2467 const std::size_t vw = sn.nvars_of(ind);
2468 for (std::size_t s = 0; s < n; ++s) {
2469 if (num_traits<T>::to_double(p[s]) == 0) continue;
2470 const std::vector<T>& row = r.space[s].local[isf - 1];
2471 if (row.size() < vw) continue;
2472 for (std::size_t pos = 0; pos < info.classes.size(); ++pos) {
2473 const std::size_t cls = info.classes[pos];
2474 const std::size_t col = row.size() - vw + info.slot[cls - 1];
2475 qn_blocked(ist - 1, cls - 1) += T(p[s] * row[col]);
2476 }
2477 }
2478 // under server parallelism a pending call holds the n_r servers its
2479 // job seized (`qn::reply_held_servers`), not one
2480 const std::vector<double> parU = qn::parallelism_of(sn, ind);
2481 for (std::size_t k = 0; k < R; ++k) {
2482 a.QN(ist - 1, k) += qn_blocked(ist - 1, k);
2483 const double nk = k < parU.size() ? parU[k] : 1.0;
2484 a.UN(ist - 1, k) += T(qn_blocked(ist - 1, k) * num_traits<T>::from_double(nk) /
2486 }
2487 }
2488 }
2489
2490 // Little's law per station, then per class at the reference station.
2491 for (std::size_t k = 1; k <= R; ++k) {
2492 for (std::size_t ist = 1; ist <= M; ++ist)
2493 a.RN(ist - 1, k - 1) =
2494 num_traits<T>::to_double(a.TN(ist - 1, k - 1)) > 0
2495 ? T((a.QN(ist - 1, k - 1) - qn_blocked(ist - 1, k - 1)) /
2496 a.TN(ist - 1, k - 1))
2497 : zero;
2498 const double nk = sn.njobs()[k - 1];
2499 a.CN[k - 1] = std::isfinite(nk) && num_traits<T>::to_double(a.XN[k - 1]) > 0
2500 ? T(num_traits<T>::from_double(nk) / a.XN[k - 1])
2501 : zero;
2502 }
2503 return a;
2504}
2505
2506} // namespace ctmc
2507} // namespace line
2508
2509// The DROP-region admissibility test the synchronization loop above calls.
2510// Included here, after every declaration it needs, because that header
2511// includes this one.
2513
2514#endif // LINE_SOLVERS_CTMC_SOLVER_CTMC_H
Fork(model, name).
Definition nodes.h:236
InputError(const std::string &what)
Definition error.h:105
std::size_t cols() const
Definition matrix.h:90
std::size_t rows() const
Definition matrix.h:89
NumericError(const std::string &what)
Definition error.h:112
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
std::size_t stateful_index(std::size_t ind) const
1-based stateful index of node ind, 0 when the node is not stateful.
std::vector< std::size_t > stateful_nodes
1-based node indices, ascending
std::vector< std::vector< Distrib< T > > > service
service[i][r], 0-based station and class; a disabled entry marks a pair never visited.
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< JobClass > classes
std::vector< NodeDef > nodes
every node, in creation order
A network plus its refreshed NetworkStruct.
static void step(const char *fmt,...)
Write one progress line.
Equilibrium distribution of a discrete-time Markov chain, and stochastic complementation.
The exception types the port throws.
Running progress log of a LINE solver run (the "solver console").
options.timeout: one wall-clock budget per top-level solve, on a per-THREAD deadline stack.
LU factorization with partial pivoting, templated on the number type.
Markovian arrival process descriptors: stationary vectors, rate, moments, autocorrelation and the ind...
Dense matrix and non-owning view.
CtmcResult< T > solver_ctmc(const NetworkStruct< T > &sn, const std::vector< NetState< T > > &space, const std::vector< Sync< T > > &sync, const std::vector< qn::GlobalSync< T > > &gsync=std::vector< qn::GlobalSync< T > >(), bool want_filtration=false, const std::vector< qn::FjSync< T > > &fjsync=std::vector< qn::FjSync< T > >(), LalCollect *collect=nullptr)
Port of the generator assembly of solver_ctmc.m.
void ctmc_eliminate_vanishing(CtmcResult< T > &res)
Port of the "now remove immediate transitions" block of solver_ctmc.m (:812-870): eliminate the vanis...
bool ctmc_region_admissible(const NetworkStruct< T > &sn, const std::vector< T > &nir)
True when nir – the per-(station, class) counts of one state, in (ist-1)*K + k order – satisfies ever...
void make_infgen(Matrix< T > &Q)
Port of ctmc_makeinfgen: turn an off-diagonal rate matrix into a generator.
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.
NetState< T > reachable_seed_widen(const NetworkStruct< T > &sn, const NetState< T > &init)
Left-pad an ordered-buffer station's seed row to the width its CAPACITY implies, rather than the widt...
bool ctmc_all_phasetype(const NetworkStruct< T > &sn)
MATLAB's all(sn.isph(:)), read off the matrices instead of off a flag.
std::vector< T > ctmc_signal_busy(const NetworkStruct< T > &sn, std::size_t ist, const CtmcResult< T > &r, const std::vector< T > &p, std::size_t isf)
Port of ctmc_signal_busy: the exact per-class busy-server fraction, read off the enumerated state spa...
Matrix< T > ctmc_gd_factor(const NetworkStruct< T > &sn, const std::vector< NetState< T > > &space)
Tabulates the globally state-dependent rate scaling phi(n) declared through set_global_dependence,...
Matrix< T > ctmc_state_space_aggr(const NetworkStruct< T > &sn, const std::vector< NetState< T > > &space)
Port of StateSpaceAggr: the per-(station, class) job counts of every state, as an (nstates x nstation...
std::vector< NetState< T > > reachable_space_generator(const NetworkStruct< T > &sn, const NetState< T > &init, const std::vector< Sync< T > > &sync, const std::vector< qn::GlobalSync< T > > &gsync=std::vector< qn::GlobalSync< T > >(), std::size_t maxst=3000000, const std::vector< qn::FjSync< T > > &fjsync=std::vector< qn::FjSync< T > >(), const std::vector< std::size_t > &cutoff=std::vector< std::size_t >(), const std::vector< std::vector< std::size_t > > &cutoff_mat=std::vector< std::vector< std::size_t > >())
Port of State.reachableSpaceGenerator: the states reachable from init.
std::vector< std::size_t > ctmc_find_vanishing_states(const NetworkStruct< T > &sn, const std::vector< NetState< T > > &space, const std::vector< qn::GlobalSync< T > > &gsync, bool isfjaug, const std::vector< qn::FjSync< T > > &fjsync=std::vector< qn::FjSync< T > >())
Port of ctmc_find_vanishing_states (solver_ctmc.m:928): the indices of the VANISHING (zero-sojourn) g...
std::vector< bool > ctmc_signal_lossy(const NetworkStruct< T > &sn, const CtmcResult< T > &r, const std::vector< T > &p, std::size_t isf)
Port of ctmc_signal_lossy: classes a G-network signal can annihilate here.
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
@ IMMEDIATE
fires with zero delay, resolved by weight and priority
Definition lang_types.h:384
@ REPLY
completes a synchronous call, releasing a held server
Definition lang_types.h:181
EventType
The events a state can undergo, with the values of MATLAB EventType.
Definition lang_types.h:116
NodeType
Node kinds, with the values of MATLAB NodeType.
Definition lang_types.h:345
T map_mean(const Map< T > &m)
Mean inter-arrival time, 1/lambda.
Definition map_moment.h:101
StochCompResult< T > ctmc_stochcomp(const Matrix< T > &Q, const std::vector< std::size_t > &I)
Definition dtmc_solve.h:158
EventOutcome< T > after_event_join(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventType event, std::size_t cls)
Port of State.afterEventJoin: an event at a Join node of an FJ-augmented struct.
ReplyBlockInfo reply_block_info(const NetworkStruct< T > &sn, std::size_t ind)
Defined below; the departure branch records a server held for a reply.
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
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 ...
T station_renege_mu(const NetworkStruct< T > &sn, std::size_t ist, std::size_t cls)
sn.impatienceMu(ist,cls): the rate of an exponential reneging patience, 0 when the class declares non...
GlobalOutcome< T > after_global_event(const NetworkStruct< T > &sn, const NetState< T > &glspace, const GlobalSync< T > &gl)
Port of State.afterGlobalEvent: an SPN mode ENABLEs or FIREs.
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.
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...
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...
GlobalOutcome< T > after_fj_event(const NetworkStruct< T > &sn, const FjSync< T > &e, const NetState< T > &gl)
Port of State.afterFJEvent: fire ONE entry of the fork firing list.
RowLayout< T > row_layout(const NetworkStruct< T > &sn, std::size_t ind, std::size_t width)
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
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
void lu_solve(const Matrix< T > &LU, const std::vector< std::size_t > &piv, std::vector< T > &b)
Solve LUx = Pb in place on b, using the factors from lu_factor.
Definition lu.h:94
std::vector< std::size_t > lu_factor(Matrix< T > &A)
In-place LU of A (n x n).
Definition lu.h:48
A queueing network and its refreshed NetworkStruct.
Finite Capacity Regions in SolverCTMC: the DROP rule, as a filter on the enumerated state space,...
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
The mean performance metrics a stationary vector maps to.
std::vector< T > CN
(nclasses) system throughput and response time
std::vector< T > XN
Matrix< T > StartN
The DERIVED rates, (nstations x nclasses): how often per unit time a class-r service STARTS at statio...
Matrix< T > TN
(nstations x nclasses)
The generator, the state space it is indexed by, and the event rates.
Definition solver_ctmc.h:64
std::vector< std::vector< std::vector< T > > > dep_rates_imm
std::vector< std::vector< Matrix< T > > > start_filt
The DERIVED START and PREEMPT filtrations, indexed [station-1][class-1]: the rate at which a transiti...
std::vector< NetState< T > > space
row i of Q is space[i]
Definition solver_ctmc.h:66
std::vector< std::vector< std::vector< T > > > arv_rates
arvRates / depRates, indexed [state][stateful-1][class-1]: the total rate of arrivals into,...
Definition solver_ctmc.h:74
std::vector< std::vector< Matrix< T > > > preempt_filt
std::vector< std::vector< std::vector< T > > > dep_rates
Definition solver_ctmc.h:74
std::vector< Matrix< T > > filt
Dfilt, MATLAB's EVENT FILTRATION: filt[a] holds only the rates that synchronization a contributed,...
Definition solver_ctmc.h:89
std::vector< std::vector< std::vector< T > > > arv_rates_imm
The parts of arv_rates / dep_rates contributed by those same immediate sources.
std::vector< std::size_t > vanishing
The rows the purge restated, i.e.
Matrix< T > Q
(n x n) infinitesimal generator
Definition solver_ctmc.h:65
Matrix< T > Qimm
Qimm, the IMMEDIATE-ONLY part of Q: the arcs contributed by a Router or Fork pass-through,...
static constexpr double Zero
Definition lang_types.h:825
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.
std::vector< std::pair< std::size_t, bool > > jobs
A BMAP batch emission (Kind::Batch): index is the sync of the Source departure, and jobs has one entr...
std::vector< std::tuple< std::size_t, std::size_t, double > > arcs
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
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
One synchronization: an ACTIVE event and the PASSIVE event it drives.
SyncEvent< T > passive
SyncEvent< T > active
Matrix< T > D0
The (D0,D1) pair when the type carries one directly.
Definition lang_types.h:921
A MAP as the pair of matrices (D0, D1).
Definition map_moment.h:53
Matrix< T > D1
Definition map_moment.h:55
Matrix< T > D0
Definition map_moment.h:54
A finite-attempt retrial station (python attempts_info).
std::size_t cls
1-based retrial class
What one event produces at one node: the successor rows, their rates and their probabilities,...
std::vector< T > prob
per-row probability of the choice
std::vector< std::vector< T > > space
successor local state rows
std::vector< T > rate
per-row rate, -1 on a passive half
One fork firing synchronization: sn.fjsync{k}.
std::size_t fork
1-based Fork node
std::vector< std::size_t > branchheads
1-based node per branch
std::size_t cls
1-based ORIGINAL class being forked
std::vector< std::size_t > auxclasses
the tag's auxiliary class per branch
What one global event produces: a whole network state per outcome.
std::vector< T > rate
std::vector< NetState< T > > space
std::vector< T > prob
std::vector< bool > completion
True where the outcome is a firing COMPLETION, i.e.
A GLOBAL synchronization: an SPN mode event and the place arcs it drives.
What State.toMarginal returns for one station and one state row.
Definition state.h:56
std::vector< T > nir
jobs per class
Definition state.h:58
std::vector< T > sir
jobs in service per class
Definition state.h:59
One half of a GLOBAL synchronization: a mode event at a node.
std::size_t mode
1-based mode index
std::size_t node
1-based node index (a Transition, or a place)
T weight
arc multiplicity
std::size_t cls
1-based class the arc moves
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
Where node ind keeps its reply-block counters inside the local vars.
std::vector< std::size_t > slot
slot[r-1] = 0-based column, or npos
std::vector< std::size_t > classes
1-based calling classes holding a block
One station of the network.
std::vector< T > jdscalingpeak
sn.jdscalingpeak for this station: the declared peak joint-dependent scaling per class.
std::vector< BalkingParam > balking
CdScaling< T > jdscaling
sn.jdscaling for this station: MATLAB's Station.ljdScaling, the JOINT dependence map eta_i(n),...
std::vector< T > cdscalingpeak
sn.cdscalingpeak for this station: the DECLARED peak rate scaling per class, empty when the station i...
CdScaling< T > cdscaling
sn.cdscaling for this station: the class-dependence map, empty when unset.
One synchronization: an ACTIVE event and the PASSIVE event it drives.
SyncEvent< T > passive
SyncEvent< T > active