LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_ag.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_AG_SOLVER_AG_H
6#define LINE_SOLVERS_AG_SOLVER_AG_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * Port of `solver_ag.m`: the RCAT (Reversed Compound Agent Theorem)
12 * analyzers, reached by methods 'inap', 'inaprc', 'inapinf' and 'exact'.
13 *
14 * THE METHOD. Each (station, class) pair that carries jobs becomes an isolated
15 * CTMC, and the pairs are coupled only through the REVERSED RATES x_l of the
16 * synchronizing actions. A component is a QBD whose LEVEL is the queue length
17 * and whose PHASE is the pair (arrival phase, service phase), laid out in the
18 * Kronecker order of qbd_mapmap1.h: an arrival moves the level up carrying
19 * kron(D1^a, I), a service completion moves it down carrying kron(I, D1^s),
20 * the busy levels evolve under krons(D0^a, D0^s) and level zero under
21 * kron(D0^a, I), because no server is running there. With exponential
22 * processes every block is 1 x 1 and the QBD collapses to the scalar
23 * birth-death chain this analyzer built before, entry for entry. A departure from one
24 * component is an active transition there and a passive one at the destination;
25 * RCAT says that if the reversed rate of every active label is
26 * state-independent, the joint chain has a product form whose factors are the
27 * isolated components solved with the passive rates set to those x_l. INAP is
28 * the fixed point that looks for such an x: solve the components, re-estimate
29 * each x_l from the resulting marginals, repeat.
30 *
31 * THESE ARE APPROXIMATIONS, and the reference is explicit about it. The
32 * reversed rate is state-independent only for genuinely product-form models; on
33 * everything else INAP converges to an x that is merely a good average, and the
34 * marginals it returns are not the model's. The 'inapinf' variant reports the
35 * RCAT residual of Remark 2, max_l ||pi (x_l I - T_l)||, which is zero exactly
36 * when the product form is real, and it is exposed here as `rcat_residual` for
37 * the same reason: it is the only honest indication of how far off the answer
38 * is. Nothing in this header should be compared against an exact solver at a
39 * tolerance that pretends otherwise.
40 *
41 * THE THREE VARIANTS differ only in how x_l is re-estimated and how the open
42 * components are solved:
43 * inap x_l = mean over the support of the state-wise reversed rate
44 * (pi A_l)_j / pi_j, which on a birth-death component is the
45 * entrywise mean of A_l(i,j) pi(i)/pi(j) term for term
46 * inaprc x_l = sum over the support of A_l(i,j) pi(i), the rate-conserving
47 * estimator, which INAP also switches to on any component that is
48 * not a birth-death chain (a catastrophe or batch removal reaches
49 * beyond the neighbouring LEVEL, and the mean-of-ratios estimator
50 * is meaningless there) and on any component with more than one
51 * phase per level, where the same failure appears
52 * inapinf x_l from the closed-form geometric tail, with each OPEN component
53 * solved on its infinite state space by the scalar QBD root instead
54 * of being truncated at maxStates (Marin, Rota Bulo and Balsamo,
55 * MASCOTS 2012)
56 *
57 * TWO REFERENCE QUIRKS THAT LOOK LIKE BUGS AND ARE HARMLESS, both worth knowing
58 * before editing. First, `compute_equilibrium` subtracts unscaled row-sum
59 * diagonals while adding x(c)-scaled off-diagonal blocks, which is inconsistent;
60 * it does not matter because `ctmc_makeinfgen` discards the diagonal outright
61 * and rebuilds it from the row sums. Second, and for the same reason, the
62 * self-service term `L(n,n) = mu * P(self)` that `build_local_rates` writes on
63 * the DIAGONAL is discarded too, so self-routing at a station has no effect on
64 * the answer. Both are reproduced rather than corrected: correcting either
65 * would change every number this analyzer returns.
66 *
67 * NOT PORTED, AND WHY. The reference's self-looping-class override reads
68 * `sn.isslc`, which NetworkStruct does not carry. MATLAB guards that block with
69 * `isfield(sn,'isslc')`, so a struct without the field skips it and the port
70 * takes the same path; a model that genuinely has self-looping classes would
71 * differ, and there is no way to detect one here without inventing the concept.
72 *
73 * ARITHMETIC. The fixed point stops on a tolerance and the QBD root takes a
74 * square root, so the whole body is gated on transcendental arithmetic, as
75 * solver_mam_basic.h and solver_mam_ldqbd.h are.
76 */
77
78#include <algorithm>
79#include <sstream>
80#include <cmath>
81#include <cstddef>
82#include <iostream>
83#include <limits>
84#include <memory>
85#include <string>
86#include <utility>
87#include <vector>
88
91#include "line/api/mam/qbd_r.h"
96#include "line/num/number.h"
100#include "line/util/error.h"
101#include "line/util/linalg.h"
102#include "line/util/lu.h"
103#include "line/util/matrix.h"
104
105namespace line {
106namespace ag {
107
108// Kronecker products and Neuts' logarithmic reduction are MAM primitives, not
109// RCAT ones: they live in api/mam and are shared with every matrix-analytic
110// analyzer. Named explicitly rather than pulled in wholesale, so the split
111// between what AG owns and what it merely uses stays visible.
112using mam::kron;
113using mam::krons;
115
116namespace ag_detail {
117
118/** One synchronizing action: a departure from (from) that arrives at (to). */
119struct RcatAction {
120 std::size_t from_station = 0, from_class = 0; ///< 0-based
121 std::size_t to_station = 0, to_class = 0; ///< 0-based
122 double prob = 0.0;
123 bool is_negative = false;
124 bool is_catastrophe = false;
125 std::size_t removal_class = 0; ///< 0-based class whose signalremdist applies
126 bool has_removal_dist = false;
127};
128
129/** The RCAT form of the network: components, actions, and their rate matrices. */
130template <class T>
131struct RcatModel {
132 std::size_t num_processes = 0;
133 /** 1-based process id per (station, class), 0 where the pair carries no jobs. */
134 std::vector<std::vector<std::size_t>> process_map;
135 std::vector<RcatAction> actions;
136 std::vector<std::size_t> N; ///< state count per process, nlev * mph
137 std::vector<Matrix<T>> Aa, Pb; ///< active and passive matrix per action
138 std::vector<Matrix<T>> L; ///< local (hidden) rate matrix per process
139 std::vector<std::size_t> act, psv; ///< 0-based active/passive process per action
140 std::vector<bool> is_open_proc;
141 std::vector<std::size_t> nlev; ///< QBD levels per process
142 std::vector<std::size_t> mph; ///< phases per level per process
143 std::vector<std::vector<std::size_t>> level; ///< level index of every state
144 /** Service completion rate out of every state; zero on level 0. */
145 std::vector<std::vector<T>> svcrate;
146 /** The same rate per phase at a busy level. */
147 std::vector<std::vector<T>> svcdown;
148 /**
149 * Per process: whether a signal, a catastrophe, a batch removal or a void
150 * signal reaches it from outside the synchronizing actions, which takes its
151 * chain out of the closed-chain conditioning (closed_chain_condition).
152 */
153 std::vector<bool> extsig;
154};
155
156/**
157 * One component's Markovian processes: the service MAP of its station and the
158 * arrival MAP of the external streams reaching it, plus the removal signals,
159 * which stay scalar because a signal is a trigger with no service.
160 */
161template <class T>
162struct RcatComponent {
163 std::size_t ist = 0, r = 0;
164 Matrix<T> Da0, Da1; ///< arrival MAP of the external streams
165 Matrix<T> Ds0, Ds1; ///< service MAP
166 Matrix<T> Dsvc; ///< kron(I_na, D1^s): a completion, level down
167 std::size_t na = 1, ns = 1, mph = 1, nlev = 0, N = 0;
168 T lam_neg = num_traits<T>::from_int(0);
169 T lam_cat = num_traits<T>::from_int(0);
170 std::vector<std::pair<T, std::size_t>> batch; ///< (rate, signal class)
171 /** Departures turned into a signal that finds no positive process. */
172 T prob_void = num_traits<T>::from_int(0);
173};
174
175/** Row/column offset of level N (0-based) in a component with MPH phases. */
176inline std::size_t blk(std::size_t n, std::size_t mph) { return n * mph; }
177
178/** Elementwise sum of two same-shaped matrices. */
179template <class T>
180Matrix<T> madd_local(const Matrix<T>& A, const Matrix<T>& B) {
181 Matrix<T> C(A.rows(), A.cols(), num_traits<T>::from_int(0));
182 for (std::size_t i = 0; i < A.rows(); ++i)
183 for (std::size_t j = 0; j < A.cols(); ++j) C(i, j) = T(A(i, j) + B(i, j));
184 return C;
185}
186
187/** Add SCALE times BLOCK into the (LI, LJ) level block of TARGET. */
188template <class T>
189void add_block(Matrix<T>& target, std::size_t li, std::size_t lj, std::size_t mph,
190 const Matrix<T>& block, const T& scale) {
191 const std::size_t r0 = blk(li, mph), c0 = blk(lj, mph);
192 for (std::size_t i = 0; i < mph; ++i)
193 for (std::size_t j = 0; j < mph; ++j) target(r0 + i, c0 + j) += T(scale * block(i, j));
194}
195
196/** Add SCALE times the identity into the (LI, LJ) level block of TARGET. */
197template <class T>
198void add_identity(Matrix<T>& target, std::size_t li, std::size_t lj, std::size_t mph,
199 const T& scale) {
200 const std::size_t r0 = blk(li, mph), c0 = blk(lj, mph);
201 for (std::size_t i = 0; i < mph; ++i) target(r0 + i, c0 + i) += scale;
202}
203
204/** Set the (LI, LJ) level block of TARGET to the identity. */
205template <class T>
206void set_identity(Matrix<T>& target, std::size_t li, std::size_t lj, std::size_t mph) {
207 const std::size_t r0 = blk(li, mph), c0 = blk(lj, mph);
208 const T one = num_traits<T>::from_int(1);
209 for (std::size_t i = 0; i < mph; ++i) target(r0 + i, c0 + i) = one;
210}
211
212/** The (LI, LJ) level block of Q. */
213template <class T>
214Matrix<T> level_block(const Matrix<T>& Q, std::size_t li, std::size_t lj, std::size_t mph) {
215 Matrix<T> out(mph, mph, num_traits<T>::from_int(0));
216 const std::size_t r0 = blk(li, mph), c0 = blk(lj, mph);
217 for (std::size_t i = 0; i < mph; ++i)
218 for (std::size_t j = 0; j < mph; ++j) out(i, j) = Q(r0 + i, c0 + j);
219 return out;
220}
221
222/**
223 * True when (D0, D1) is a genuine MAP rather than a RAP or an ME process:
224 * non-negative off-diagonal rates in D0, non-negative rates in D1, and
225 * (D0 + D1) an infinitesimal generator. A CTMC assembled from anything else is
226 * a rational generator whose stationary solution is a signed vector.
227 */
228template <class T>
229bool is_markovian_map(const Matrix<T>& D0, const Matrix<T>& D1) {
230 const std::size_t n = D0.rows();
231 if (n == 0 || D0.cols() != n || D1.rows() != n || D1.cols() != n) return false;
232 double scale = 1.0;
233 for (std::size_t i = 0; i < n; ++i)
234 for (std::size_t j = 0; j < n; ++j) {
235 const double a = num_traits<T>::to_double(D0(i, j));
236 const double b = num_traits<T>::to_double(D1(i, j));
237 if (!std::isfinite(a) || !std::isfinite(b)) return false;
238 scale = std::max(scale, std::max(std::fabs(a), std::fabs(b)));
239 }
240 const double tol = 1e-9 * scale;
241 for (std::size_t i = 0; i < n; ++i) {
242 double row = 0.0;
243 for (std::size_t j = 0; j < n; ++j) {
244 const double a = num_traits<T>::to_double(D0(i, j));
245 const double b = num_traits<T>::to_double(D1(i, j));
246 if (i != j && a < -tol) return false;
247 if (b < -tol) return false;
248 row += a + b;
249 }
250 if (std::fabs(row) > tol) return false;
251 }
252 return true;
253}
254
255/**
256 * (D0,D1) of the process at (IST,R), or the exponential pair built from
257 * `rates` when the station carries no usable matrix representation.
258 *
259 * A non-Markovian pair is refused here and answered as its mean rate; the
260 * runner-level gate rejects those models before they reach this point.
261 */
262template <class T>
263std::pair<Matrix<T>, Matrix<T>> proc_map(const qn::NetworkStruct<T>& L, std::size_t ist,
264 std::size_t r) {
265 const T zero = num_traits<T>::from_int(0);
266 if (L.has_service_law(ist, r)) {
267 try {
268 const mam::Map<T> m = lang::dist_to_map(L.service[ist][r]);
269 if (is_markovian_map(m.D0, m.D1)) return std::make_pair(m.D0, m.D1);
270 } catch (const std::exception&) {
271 // no usable representation: fall through to the exponential pair
272 }
273 }
274 T rate = L.disabled[ist][r] ? zero : L.rates(ist, r);
275 if (!(rate > zero) || !std::isfinite(num_traits<T>::to_double(rate))) rate = zero;
276 Matrix<T> D0(1, 1, zero), D1(1, 1, zero);
277 D0(0, 0) = T(zero - rate);
278 D1(0, 0) = rate;
279 return std::make_pair(D0, D1);
280}
281
282template <class T>
283bool is_tridiagonal(const Matrix<T>& Q) {
284 const std::size_t n = Q.rows();
285 for (std::size_t i = 0; i < n; ++i)
286 for (std::size_t j = 0; j < n; ++j) {
287 const std::size_t d = (i > j) ? (i - j) : (j - i);
288 if (d > 1 && std::fabs(num_traits<T>::to_double(Q(i, j))) > 1e-14) return false;
289 }
290 return true;
291}
292
293/**
294 * True when every transition of Q stays within the neighbouring level, LVL
295 * being the level index of each state.
296 */
297template <class T>
298bool is_block_tridiagonal(const Matrix<T>& Q, const std::vector<std::size_t>& lvl) {
299 const std::size_t n = Q.rows();
300 for (std::size_t i = 0; i < n; ++i)
301 for (std::size_t j = 0; j < n; ++j) {
302 const std::size_t d = (lvl[i] > lvl[j]) ? (lvl[i] - lvl[j]) : (lvl[j] - lvl[i]);
303 if (d > 1 && std::fabs(num_traits<T>::to_double(Q(i, j))) > 1e-14) return false;
304 }
305 return true;
306}
307
308/**
309 * Equilibrium of a birth-death chain by the ratio recursion.
310 *
311 * Preferred over the null-space solve wherever the generator is tridiagonal
312 * because the recursion is stable at the state-space sizes this analyzer builds
313 * (maxStates is 100 by default), where the linear system is already
314 * ill-conditioned.
315 */
316template <class T>
317std::vector<T> birth_death_solve(const Matrix<T>& Q) {
318 const std::size_t n = Q.rows();
319 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
320 if (n <= 1) return std::vector<T>(1, one);
321
322 std::vector<T> pi(n, zero);
323 pi[0] = one;
324 for (std::size_t i = 1; i < n; ++i) {
325 const T birth = Q(i - 1, i);
326 const T death = Q(i, i - 1);
327 pi[i] = (death > zero) ? T(pi[i - 1] * birth / death) : zero;
328 }
329 T total = zero;
330 for (const T& v : pi) total += v;
331 if (total > zero) {
332 for (T& v : pi) v /= total;
333 } else {
334 const T u = one / num_traits<T>::from_int(static_cast<long>(n));
335 for (T& v : pi) v = u;
336 }
337 return pi;
338}
339
340/**
341 * Stationary vector of a generator C, allowing a reducible one.
342 *
343 * Replaces the first balance equation by the normalization, which is the
344 * equation it is redundant with (the columns of a generator sum to zero), and
345 * solves the resulting square system. Unlike a null-space solve this stays well
346 * posed when the chain is reducible with ONE closed class, which the level-0
347 * chain of a phase-expanded component routinely is: a phase-type restarts in
348 * the support of alpha, so every service phase outside that support is
349 * unreachable once the queue has emptied at least once.
350 */
351template <class T>
352std::vector<T> stat_vector(const Matrix<T>& C) {
353 const std::size_t m = C.rows();
354 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
355 // Solve v A = e_0, i.e. A^T v^T = e_0^T.
356 Matrix<T> At(m, m, zero);
357 for (std::size_t i = 0; i < m; ++i)
358 for (std::size_t j = 0; j < m; ++j) At(j, i) = (j == 0) ? one : C(i, j);
359 std::vector<T> rhs(m, zero);
360 rhs[0] = one;
361 const std::vector<std::size_t> piv = lu_factor(At);
362 lu_solve(At, piv, rhs);
363 return rhs;
364}
365
366/**
367 * Stationary vector of a finite block-tridiagonal generator.
368 *
369 * Linear level reduction: censor the chain level by level from the top,
370 * C(nlev-1) = B(nlev-1), C(n) = B(n) + F(n) (-C(n+1))^-1 D(n+1),
371 * with B, F and D the diagonal, up and down blocks. C(0) is the generator of
372 * the chain censored on level 0, so pi_0 is its stationary vector and the rest
373 * follows from pi_(n+1) = pi_n F(n) (-C(n+1))^-1. This is the block form of
374 * birth_death_solve and reduces to it entry for entry when m == 1.
375 */
376template <class T>
377std::vector<T> qbd_finite_solve(const Matrix<T>& Q, std::size_t m, std::size_t nlev) {
378 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
379 if (nlev <= 1) return mc::ctmc_solve(Q);
380
381 std::vector<Matrix<T>> C(nlev);
382 C[nlev - 1] = level_block(Q, nlev - 1, nlev - 1, m);
383 for (std::size_t t = nlev - 1; t-- > 0;) {
384 const Matrix<T> F = level_block(Q, t, t + 1, m);
385 const Matrix<T> D = level_block(Q, t + 1, t, m);
386 Matrix<T> negC = C[t + 1];
387 for (std::size_t i = 0; i < m; ++i)
388 for (std::size_t j = 0; j < m; ++j) negC(i, j) = T(zero - negC(i, j));
389 const Matrix<T> step = matmul(F, inverse(negC));
390 Matrix<T> Cn = level_block(Q, t, t, m);
391 const Matrix<T> corr = matmul(step, D);
392 for (std::size_t i = 0; i < m; ++i)
393 for (std::size_t j = 0; j < m; ++j) Cn(i, j) += corr(i, j);
394 C[t] = Cn;
395 }
396
397 std::vector<T> pi(nlev * m, zero);
398 const std::vector<T> p0 = stat_vector(C[0]);
399 for (std::size_t i = 0; i < m; ++i) pi[i] = p0[i];
400 for (std::size_t n = 0; n + 1 < nlev; ++n) {
401 Matrix<T> negC = C[n + 1];
402 for (std::size_t i = 0; i < m; ++i)
403 for (std::size_t j = 0; j < m; ++j) negC(i, j) = T(zero - negC(i, j));
404 const Matrix<T> step = matmul(level_block(Q, n, n + 1, m), inverse(negC));
405 for (std::size_t j = 0; j < m; ++j) {
406 T acc = zero;
407 for (std::size_t i = 0; i < m; ++i) acc += T(pi[blk(n, m) + i] * step(i, j));
408 pi[blk(n + 1, m) + j] = acc;
409 }
410 }
411
412 T total = zero;
413 for (const T& v : pi) total += v;
414 if (total > zero) {
415 for (T& v : pi) v /= total;
416 } else {
417 const T u = one / num_traits<T>::from_int(static_cast<long>(nlev * m));
418 for (T& v : pi) v = u;
419 }
420 return pi;
421}
422
423/**
424 * Stationary vector of one isolated component.
425 *
426 * A component with a single phase per level is the birth-death chain the
427 * analyzer has always built, and the ratio recursion is both exact and stable
428 * there; a phase-expanded component is block tridiagonal instead, and the matrix
429 * analogue of that recursion keeps the same stability at the 100-level
430 * truncation, where a null-space solve is already ill-conditioned. Anything that
431 * reaches beyond the neighbouring level -- a catastrophe, a batch removal -- is
432 * neither, and falls back to ctmc_solve.
433 */
434template <class T>
435std::vector<T> solve_component(const Matrix<T>& Q, std::size_t mph, std::size_t nlev,
436 const std::vector<std::size_t>& lvl) {
437 if (mph == 1) {
438 if (is_tridiagonal(Q)) return birth_death_solve(Q);
439 } else if (is_block_tridiagonal(Q, lvl)) {
440 return qbd_finite_solve(Q, mph, nlev);
441 }
442 return mc::ctmc_solve(Q);
443}
444
445/** The matrix-geometric tail of one open component with more than one phase. */
446template <class T>
447struct QbdTail {
448 Matrix<T> R;
449 std::vector<T> pi0, pi1;
450 std::vector<T> busy; ///< sum_{n>=1} pi_n = pi_1 (I - R)^-1
451 T qlen = num_traits<T>::from_int(0);
452 bool ok = false;
453};
454
455/**
456 * Neuts' matrix-geometric solution of one open component with MPH phases per
457 * level: R from logarithmic reduction, then the boundary equations of levels 0
458 * and 1,
459 * pi_0 B00 + pi_1 A2 = 0, pi_0 A0 + pi_1 (A1 + R A2) = 0,
460 * normalized by pi_0 e + pi_1 (I - R)^-1 e = 1. Returns ok = false when R has no
461 * sub-unit spectral radius, i.e. when the isolated component is unstable and has
462 * no stationary tail to report.
463 *
464 * Logarithmic reduction rather than successive substitutions: this runs once per
465 * component per fixed-point sweep, and the quadratic convergence is what keeps
466 * that affordable. The cap is small for the same reason -- an unstable component
467 * must bail rather than grind to the library default of 1e5.
468 */
469template <class T>
470QbdTail<T> qbd_matrix_tail(const Matrix<T>& Qk, const Matrix<T>& A0, const Matrix<T>& A1,
471 const Matrix<T>& A2, std::size_t mph) {
472 QbdTail<T> out;
473 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
474 Matrix<T> R;
475 try {
476 R = qbd_R_logred(A2, A1, A0, 500u, T(num_traits<T>::from_double(1e-14)));
477 } catch (const std::exception&) {
478 return out;
479 }
480 for (std::size_t i = 0; i < mph; ++i)
481 for (std::size_t j = 0; j < mph; ++j) {
482 const double v = num_traits<T>::to_double(R(i, j));
483 // The minimal solution of a QBD is NON-NEGATIVE; anything else is
484 // the iteration having failed rather than a rate matrix.
485 if (!std::isfinite(v) || v < -1e-12) return out;
486 }
487
488 const Matrix<T> B00 = level_block(Qk, 0, 0, mph);
489 Matrix<T> IR = eye<T>(mph);
490 for (std::size_t i = 0; i < mph; ++i)
491 for (std::size_t j = 0; j < mph; ++j) IR(i, j) = T(IR(i, j) - R(i, j));
492 std::vector<T> tail_mass;
493 try {
494 tail_mass = mulvec(inverse(IR), ones<T>(mph));
495 } catch (const std::exception&) {
496 return out;
497 }
498 // STABILITY WITHOUT AN EIGENSOLVER. (I-R)^-1 = I + R + R^2 + ... converges
499 // exactly when the spectral radius is below one, and every row of that
500 // series is e_i plus non-negative terms, so (I-R)^-1 e >= 1 entrywise. When
501 // the isolated component is unstable the series diverges and the inverse
502 // picks up negative entries, so the test below is the spectral condition
503 // without the LAPACK dependency an eigensolve would carry.
504 for (std::size_t i = 0; i < mph; ++i) {
505 const double w = num_traits<T>::to_double(tail_mass[i]);
506 if (!std::isfinite(w) || w < 1.0 - 1e-9) return out;
507 }
508
509 // [pi_0 pi_1] Sys = 0, with the first column replaced by the normalization.
510 const Matrix<T> lower_right = madd_local(A1, matmul(R, A2));
511 const std::size_t n2 = 2 * mph;
512 Matrix<T> SysT(n2, n2, zero); // transposed: solve Sys^T v = e_0
513 for (std::size_t i = 0; i < mph; ++i)
514 for (std::size_t j = 0; j < mph; ++j) {
515 SysT(j, i) = B00(i, j);
516 SysT(mph + j, i) = A0(i, j);
517 SysT(j, mph + i) = A2(i, j);
518 SysT(mph + j, mph + i) = lower_right(i, j);
519 }
520 for (std::size_t i = 0; i < mph; ++i) {
521 SysT(0, i) = one;
522 SysT(0, mph + i) = tail_mass[i];
523 }
524 std::vector<T> v(n2, zero);
525 v[0] = one;
526 try {
527 Matrix<T> lu = SysT;
528 const std::vector<std::size_t> piv = lu_factor(lu);
529 lu_solve(lu, piv, v);
530 } catch (const std::exception&) {
531 return out;
532 }
533 for (std::size_t i = 0; i < n2; ++i)
534 if (!std::isfinite(num_traits<T>::to_double(v[i]))) return out;
535
536 out.pi0.assign(v.begin(), v.begin() + static_cast<long>(mph));
537 out.pi1.assign(v.begin() + static_cast<long>(mph), v.end());
538 const Matrix<T> IRinv = inverse(IR);
539 out.busy = vecmul(out.pi1, IRinv);
540 const std::vector<T> qv = vecmul(out.busy, IRinv);
541 T q = zero;
542 for (const T& t : qv) q += t;
543 out.qlen = q;
544 out.R = R;
545 out.ok = true;
546 return out;
547}
548
549/**
550 * Materialize the matrix-geometric tail over NLEV levels, so the block norm of
551 * the fixed point and the RCAT residual read one vector shape for every
552 * component. The metrics use the closed forms in the tail instead.
553 */
554template <class T>
555std::vector<T> qbd_tail_expand(const QbdTail<T>& g, std::size_t nlev, std::size_t mph) {
556 std::vector<T> pi(nlev * mph, num_traits<T>::from_int(0));
557 for (std::size_t i = 0; i < mph; ++i) pi[i] = g.pi0[i];
558 std::vector<T> v = g.pi1;
559 for (std::size_t n = 1; n < nlev; ++n) {
560 for (std::size_t i = 0; i < mph; ++i) pi[blk(n, mph) + i] = v[i];
561 v = vecmul(v, g.R);
562 }
563 return pi;
564}
565
566/** P(batch = k) off the pmf indexed by batch size, zero past its end. */
567template <class T>
568T pmf_at(const std::vector<T>& pmf, std::size_t k) {
569 return k < pmf.size() ? pmf[k] : num_traits<T>::from_int(0);
570}
571
572/**
573 * Accumulate the n -> m block of a batch removal into `B`, scaled by `rate`.
574 *
575 * Landing on the empty state absorbs the whole upper tail of the pmf, which is
576 * what keeps the block stochastic once the batch exceeds the queue length.
577 */
578template <class T>
579void add_batch_removal(Matrix<T>& B, const std::vector<T>& pmf, const T& rate,
580 std::size_t nlev, std::size_t mph) {
581 const T one = num_traits<T>::from_int(1), zero = num_traits<T>::from_int(0);
582 for (std::size_t n = 1; n < nlev; ++n) {
583 for (std::size_t m = 1; m <= n; ++m) {
584 const T p = pmf_at(pmf, n - m);
585 if (p > zero) add_identity(B, n, m, mph, T(rate * p));
586 }
587 T cdf = zero;
588 for (std::size_t j = 0; j + 1 <= n; ++j) cdf += pmf_at(pmf, j);
589 const T tail = T(one - cdf);
590 if (tail > zero) add_identity(B, n, 0, mph, T(rate * tail));
591 }
592}
593
594/** Sub-unit root of b rho^2 - (f+b+g) rho + f = 0, the block-size-1 Neuts R. */
595inline double qbd_scalar_rho(double f, double b, double g) {
596 const double inf = std::numeric_limits<double>::infinity();
597 if (b <= 1e-14) {
598 // Degenerate without a down transition: the catastrophe drain is the
599 // only thing that keeps the chain stable.
600 if (f + g <= 0.0) return inf;
601 return f / (f + g);
602 }
603 const double c1 = -(f + b + g);
604 const double disc = c1 * c1 - 4.0 * b * f;
605 if (disc < 0.0) return inf;
606 const double sq = std::sqrt(disc);
607 double r1 = (-c1 - sq) / (2.0 * b), r2 = (-c1 + sq) / (2.0 * b);
608 if (r1 > r2) std::swap(r1, r2);
609 return (r1 > 0.0) ? r1 : r2;
610}
611
612/**
613 * `sn.issignal(r)` under the struct's own convention: the five G-network arrays
614 * are allocated together, and only when `set_signal` declares one, so an EMPTY
615 * `issignal` means "no class is a signal" and is the ORDINARY case rather than a
616 * malformed struct.
617 *
618 * IT MUST BE READ THROUGH A SIZE TEST, and not merely because the subscript is
619 * out of range. `issignal` is a `std::vector<bool>`, whose empty state holds a
620 * NULL word pointer, so `issignal[r]` dereferences null and takes the process
621 * down -- it does not read a stray byte and carry on. That is what `build_rcat`
622 * did on the first signal-free model ever handed to it, Source -> Q1 -> Sink,
623 * and the SIGSEGV surfaced in a test whose subject is the M/M/1 marginal, with
624 * nothing about it pointing at G-networks. Every other reader of these arrays in
625 * the tree already guards: `solver_ctmc.h`, `state_events.h`, `tag_chain.h`.
626 */
627template <class T>
628bool is_signal_class(const qn::NetworkStruct<T>& L, std::size_t r) {
629 return r < L.issignal.size() && L.issignal[r];
630}
631
632/**
633 * The declared signal type, defaulting exactly as `set_signal` initializes the
634 * array. Only ever consulted for a class `is_signal_class` admits, so the
635 * default is unreachable through this header; it is stated so that the pair of
636 * arrays cannot disagree about how far they extend.
637 */
638template <class T>
639lang::SignalType signal_type_of(const qn::NetworkStruct<T>& L, std::size_t r) {
640 return r < L.signaltype.size() ? L.signaltype[r] : lang::SignalType::NEGATIVE;
641}
642
643/**
644 * External (Source) streams reaching the component, as one arrival MAP for the
645 * positive customers plus the scalar rates of the removal signals.
646 *
647 * Each stream is thinned by its routing probability -- a MAP thinned with
648 * probability p is (D0 + (1-p) D1, p D1) -- and the streams are superposed by
649 * the Kronecker sum, so several Poisson sources still collapse to the single
650 * rate sum this analyzer used before. Removal signals stay scalar: a signal is a
651 * trigger with no service, and its arrival process is required exponential.
652 */
653template <class T>
654void arrival_map(const qn::NetworkStruct<T>& L, RcatComponent<T>& c,
655 const std::vector<std::size_t>& source_stations) {
656 using lang::SignalType;
657 const std::size_t K = L.nclasses;
658 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
659 bool have_arrival = false;
660 Matrix<T> Da0(1, 1, zero), Da1(1, 1, zero);
661
662 for (std::size_t isrc : source_stations)
663 for (std::size_t s = 0; s < K; ++s) {
664 const bool is_signal = is_signal_class(L, s);
665 T prob_src = zero;
666 if (is_signal) {
667 // A signal routes to itself, so its effect on this component is
668 // its total probability of reaching this STATION in any class.
669 for (std::size_t sd = 0; sd < K; ++sd)
670 prob_src += L.rt(isrc * K + s, c.ist * K + sd);
671 } else {
672 prob_src = L.rt(isrc * K + s, c.ist * K + c.r);
673 }
674 if (!(prob_src > zero) || L.disabled[isrc][s]) continue;
675 const T src_rate = L.rates(isrc, s);
676 const bool removal_signal =
677 is_signal && (signal_type_of(L, s) == SignalType::NEGATIVE ||
678 signal_type_of(L, s) == SignalType::CATASTROPHE);
679 if (removal_signal) {
680 if (signal_type_of(L, s) == SignalType::CATASTROPHE) {
681 c.lam_cat += T(src_rate * prob_src);
682 } else if (s < L.signalremdist.size() && !L.signalremdist[s].empty()) {
683 c.batch.emplace_back(T(src_rate * prob_src), s);
684 } else {
685 c.lam_neg += T(src_rate * prob_src);
686 }
687 continue;
688 }
689 if (!(src_rate > zero)) continue;
690
691 std::pair<Matrix<T>, Matrix<T>> sm = proc_map(L, isrc, s);
692 Matrix<T> S0 = sm.first, S1 = sm.second;
693 if (prob_src < one) {
694 const T keep = prob_src, drop = T(one - prob_src);
695 for (std::size_t i = 0; i < S0.rows(); ++i)
696 for (std::size_t j = 0; j < S0.cols(); ++j) S0(i, j) += T(drop * S1(i, j));
697 for (std::size_t i = 0; i < S1.rows(); ++i)
698 for (std::size_t j = 0; j < S1.cols(); ++j) S1(i, j) = T(keep * S1(i, j));
699 }
700 if (have_arrival) {
701 Da0 = krons(Da0, S0);
702 Da1 = krons(Da1, S1);
703 } else {
704 Da0 = S0;
705 Da1 = S1;
706 have_arrival = true;
707 }
708 }
709 c.Da0 = Da0;
710 c.Da1 = Da1;
711}
712
713/** Build the local (hidden) rate matrix of the component at (station, class). */
714template <class T>
715Matrix<T> build_local_rates(const qn::NetworkStruct<T>& L, const RcatComponent<T>& c,
716 const std::vector<std::size_t>& sink_nodes) {
717 const std::size_t K = L.nclasses;
718 const std::size_t mph = c.mph, nlev = c.nlev;
719 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
720 Matrix<T> Lm(c.N, c.N, zero);
721
722 // Level-local blocks: the arrival phase always runs, the service phase only
723 // while the server is busy (qbd_mapmap1's Lbar = kron(D0^a, I) at level 0
724 // and L = krons(D0^a, D0^s) above it). With one phase each these are pure
725 // diagonals, which ctmc_makeinfgen discards and rebuilds from the row sums.
726 add_block(Lm, 0, 0, mph, kron(c.Da0, eye<T>(c.ns)), one);
727 const Matrix<T> Lbusy = krons(c.Da0, c.Ds0);
728 for (std::size_t n = 1; n < nlev; ++n) add_block(Lm, n, n, mph, Lbusy, one);
729
730 // Positive arrivals: level n -> n+1, carrying kron(D1^a, I).
731 const Matrix<T> Aup = kron(c.Da1, eye<T>(c.ns));
732 for (std::size_t n = 0; n + 1 < nlev; ++n) add_block(Lm, n, n + 1, mph, Aup, one);
733 // At the truncation the job is lost but the arrival process still moves on,
734 // so the block stays on the top level. With a single arrival phase this is a
735 // pure diagonal and is discarded, exactly as before.
736 add_block(Lm, nlev - 1, nlev - 1, mph, Aup, one);
737
738 // Catastrophe arrivals: every busy level drops to level 0.
739 if (c.lam_cat > zero)
740 for (std::size_t n = 1; n < nlev; ++n) add_identity(Lm, n, 0, mph, c.lam_cat);
741 for (const std::pair<T, std::size_t>& ba : c.batch)
742 add_batch_removal(Lm, L.signalremdist[ba.second], ba.first, nlev, mph);
743 // Single-removal negative arrivals: level n -> n-1 (busy levels only).
744 if (c.lam_neg > zero)
745 for (std::size_t n = 1; n < nlev; ++n) add_identity(Lm, n, n - 1, mph, c.lam_neg);
746
747 // Service completions that are not synchronizing actions: departures to a
748 // Sink (level down) and self-routing (level unchanged, service restarted).
749 if (L.disabled[c.ist][c.r]) return Lm;
750 const T mu = L.rates(c.ist, c.r);
751 if (!(mu > zero)) return Lm;
752
753 // The node index IS needed here -- rtnodes is indexed by node, not by
754 // station -- so a station the map does not cover has no row to read and
755 // contributes no sink probability. Tested up front rather than relying on
756 // the range check below to catch the wrapped `node - 1`.
757 const std::size_t node = L.node_of_station(c.ist + 1);
758 T prob_sink = zero;
759 if (node != 0)
760 for (std::size_t jsnk : sink_nodes)
761 for (std::size_t s = 0; s < K; ++s) {
762 const std::size_t from = (node - 1) * K + c.r, to = (jsnk - 1) * K + s;
763 if (from < L.rtnodes.rows() && to < L.rtnodes.cols())
764 prob_sink += L.rtnodes(from, to);
765 }
766 // A departure turned into a signal at a station with no positive process
767 // removes nothing and leaves, exactly as a departure to a Sink does.
768 prob_sink += c.prob_void;
769 const T prob_self = L.rt(c.ist * K + c.r, c.ist * K + c.r);
770
771 if (prob_sink > zero)
772 for (std::size_t n = 1; n < nlev; ++n) add_block(Lm, n, n - 1, mph, c.Dsvc, prob_sink);
773 // With one service phase this lands on the diagonal, hence is discarded by
774 // ctmc_makeinfgen and self-routing has no effect, exactly as the reference
775 // records; with a phase block it restarts the service, which is the physics.
776 if (prob_self > zero)
777 for (std::size_t n = 1; n < nlev; ++n) add_block(Lm, n, n, mph, c.Dsvc, prob_self);
778 return Lm;
779}
780
781/** Port of `build_rcat`: the network to its RCAT components and actions. */
782template <class T>
783RcatModel<T> build_rcat(const qn::NetworkStruct<T>& L, std::size_t max_states) {
784 using lang::SignalType;
785 const std::size_t M = L.nstations, K = L.nclasses;
786 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
787 RcatModel<T> m;
788 m.process_map.assign(M, std::vector<std::size_t>(K, 0));
789
790 std::vector<std::size_t> source_stations, queue_stations, sink_nodes;
791 for (std::size_t i = 0; i < L.nof_nodes(); ++i)
792 if (L.nodes[i].nodetype == qn::NodeType::Sink) sink_nodes.push_back(i + 1);
793 for (std::size_t ist = 0; ist < M; ++ist) {
794 // FROM THE STATION, not through the node map. `add_station` copies the
795 // type into both, so the two always agree -- but `node_of_station`
796 // returns 0 for a station the map does not cover (a Layer built by the
797 // LQN path carries fewer entries than stations), and `nodes[node - 1]`
798 // then wraps to SIZE_MAX and reads off the end of the vector.
799 const qn::NodeType ty = L.stations[ist].nodetype;
800 if (ty == qn::NodeType::Source) source_stations.push_back(ist);
801 else if (ty != qn::NodeType::Sink) queue_stations.push_back(ist);
802 }
803
804 // A signal class never gets a component of its own: it has no queue, it
805 // only edits the state of the positive-customer components it reaches.
806 std::size_t pidx = 0;
807 for (std::size_t ist : queue_stations)
808 for (std::size_t r = 0; r < K; ++r) {
809 if (is_signal_class(L, r) || L.disabled[ist][r]) continue;
810 if (!(L.rates(ist, r) > zero)) continue;
811 m.process_map[ist][r] = ++pidx;
812 }
813 m.num_processes = pidx;
814 if (m.num_processes == 0) return m;
815
816 // The QBD shape of every component: both the service MAP of its station and
817 // the arrival MAP of the external streams reaching it.
818 const std::vector<double> njobs = L.njobs();
819 std::vector<RcatComponent<T>> comp(m.num_processes);
820 m.N.assign(m.num_processes, 0);
821 m.nlev.assign(m.num_processes, 0);
822 m.mph.assign(m.num_processes, 1);
823 m.level.assign(m.num_processes, std::vector<std::size_t>());
824 m.svcrate.assign(m.num_processes, std::vector<T>());
825 m.svcdown.assign(m.num_processes, std::vector<T>());
826 m.is_open_proc.assign(m.num_processes, false);
827 for (std::size_t ist : queue_stations)
828 for (std::size_t r = 0; r < K; ++r) {
829 const std::size_t p = m.process_map[ist][r];
830 if (p == 0 || m.N[p - 1] != 0) continue;
831 RcatComponent<T>& c = comp[p - 1];
832 c.ist = ist;
833 c.r = r;
834 const std::pair<Matrix<T>, Matrix<T>> svc = proc_map(L, ist, r);
835 c.Ds0 = svc.first;
836 c.Ds1 = svc.second;
837 arrival_map(L, c, source_stations);
838 c.ns = c.Ds0.rows();
839 c.na = c.Da0.rows();
840 c.mph = c.na * c.ns;
841 if (std::isfinite(njobs[r])) {
842 // A closed component holds up to its CHAIN population: with
843 // class switching every job of the chain can sit in this one
844 // class, so njobs(r) alone would truncate the level space.
845 double popc = 0.0;
846 for (const std::vector<bool>& ch : L.chains)
847 if (r < ch.size() && ch[r]) {
848 for (std::size_t s = 0; s < K; ++s)
849 if (ch[s]) popc += njobs[s];
850 break;
851 }
852 c.nlev = static_cast<std::size_t>(popc) + 1;
853 } else {
854 c.nlev = max_states; // open class: truncate
855 m.is_open_proc[p - 1] = true;
856 }
857 // Service completion: level down, arrival phase untouched.
858 c.Dsvc = kron(eye<T>(c.na), c.Ds1);
859 c.N = c.nlev * c.mph;
860
861 m.N[p - 1] = c.N;
862 m.nlev[p - 1] = c.nlev;
863 m.mph[p - 1] = c.mph;
864 m.level[p - 1].assign(c.N, 0);
865 for (std::size_t n = 0; n < c.nlev; ++n)
866 for (std::size_t j = 0; j < c.mph; ++j) m.level[p - 1][n * c.mph + j] = n;
867 m.svcdown[p - 1].assign(c.mph, zero);
868 for (std::size_t i = 0; i < c.mph; ++i) {
869 T acc = zero;
870 for (std::size_t j = 0; j < c.mph; ++j) acc += c.Dsvc(i, j);
871 m.svcdown[p - 1][i] = acc;
872 }
873 m.svcrate[p - 1].assign(c.N, zero);
874 for (std::size_t n = 1; n < c.nlev; ++n)
875 for (std::size_t j = 0; j < c.mph; ++j)
876 m.svcrate[p - 1][n * c.mph + j] = m.svcdown[p - 1][j];
877 }
878
879 for (std::size_t ist : queue_stations)
880 for (std::size_t r = 0; r < K; ++r) {
881 if (m.process_map[ist][r] == 0) continue;
882 const bool is_removal =
883 is_signal_class(L, r) && (signal_type_of(L, r) == SignalType::NEGATIVE ||
884 signal_type_of(L, r) == SignalType::CATASTROPHE);
885 const bool is_cat = is_removal && signal_type_of(L, r) == SignalType::CATASTROPHE;
886 const bool has_dist =
887 is_removal && r < L.signalremdist.size() && !L.signalremdist[r].empty();
888 for (std::size_t jst : queue_stations)
889 for (std::size_t s = 0; s < K; ++s) {
890 if (m.process_map[jst][s] == 0) continue;
891 if (ist == jst && r == s) continue;
892 const T pr = L.rt(ist * K + r, jst * K + s);
893 if (!(pr > zero)) continue;
894 RcatAction a;
895 a.from_station = ist;
896 a.from_class = r;
897 a.to_station = jst;
898 a.to_class = s;
899 a.prob = num_traits<T>::to_double(pr);
900 a.is_negative = is_removal;
901 a.is_catastrophe = is_cat;
902 a.has_removal_dist = has_dist;
903 a.removal_class = r;
904 m.actions.push_back(a);
905 }
906
907 // A departure that class-switches into a signal. The signal has no
908 // process of its own: it acts on arrival at jst and is annihilated
909 // there, so it is an action whose passive side is the positive
910 // process it removes from. Skipping it, as the loop above does for
911 // any destination without a process, deletes that share of the
912 // service completions and inflates the queue (SUS-9).
913 for (std::size_t jst : queue_stations)
914 for (std::size_t s = 0; s < K; ++s) {
915 if (!is_signal_class(L, s)) continue;
916 const T pr = L.rt(ist * K + r, jst * K + s);
917 if (!(pr > zero)) continue;
918 const SignalType st = signal_type_of(L, s);
919 const bool s_cat = st == SignalType::CATASTROPHE;
920 if (!s_cat && st != SignalType::NEGATIVE)
921 throw UnsupportedError(ErrorKind{"Signal"},
922 "solver_ag: class '" + L.classes[r].name + "' switches into signal class '" +
923 L.classes[s].name + "' at station '" + L.stations[jst].name +
924 "', but only a NEGATIVE or CATASTROPHE signal has a G-network effect RCAT "
925 "can represent");
926 std::vector<std::size_t> targets;
927 for (std::size_t t = 0; t < K; ++t)
928 if (m.process_map[jst][t] != 0) targets.push_back(t);
929 if (targets.size() > 1)
930 throw UnsupportedError(ErrorKind{"Signal"},
931 "solver_ag: signal class '" + L.classes[s].name +
932 "', produced by departures of class '" + L.classes[r].name +
933 "', reaches station '" + L.stations[jst].name + "', which serves " +
934 std::to_string(targets.size()) +
935 " positive classes. A departure synchronizes with ONE component in RCAT, "
936 "so the removal cannot be split across classes");
937 if (targets.empty()) {
938 // nothing to remove: the job leaves the network
939 comp[m.process_map[ist][r] - 1].prob_void += pr;
940 continue;
941 }
942 RcatAction a;
943 a.from_station = ist;
944 a.from_class = r;
945 a.to_station = jst;
946 a.to_class = targets[0];
947 a.prob = num_traits<T>::to_double(pr);
948 a.is_negative = true;
949 a.is_catastrophe = s_cat;
950 a.has_removal_dist =
951 !s_cat && s < L.signalremdist.size() && !L.signalremdist[s].empty();
952 a.removal_class = s;
953 m.actions.push_back(a);
954 }
955 }
956
957 m.L.reserve(m.num_processes);
958 for (std::size_t p = 0; p < m.num_processes; ++p)
959 m.L.push_back(build_local_rates(L, comp[p], sink_nodes));
960 m.extsig.assign(m.num_processes, false);
961 for (std::size_t p = 0; p < m.num_processes; ++p)
962 m.extsig[p] = comp[p].lam_neg > zero || comp[p].lam_cat > zero ||
963 !comp[p].batch.empty() || comp[p].prob_void > zero;
964
965 const std::size_t A = m.actions.size();
966 m.Aa.reserve(A);
967 m.Pb.reserve(A);
968 m.act.reserve(A);
969 m.psv.reserve(A);
970 for (const RcatAction& a : m.actions) {
971 const std::size_t pa = m.process_map[a.from_station][a.from_class] - 1;
972 const std::size_t pp = m.process_map[a.to_station][a.to_class] - 1;
973 m.act.push_back(pa);
974 m.psv.push_back(pp);
975
976 const RcatComponent<T>& ca = comp[pa];
977 const T prob = num_traits<T>::from_double(a.prob);
978 Matrix<T> Am(ca.N, ca.N, zero);
979 for (std::size_t n = 1; n < ca.nlev; ++n)
980 add_block(Am, n, n - 1, ca.mph, ca.Dsvc, prob);
981 // The boundary self-loop is physical only for a closed class, where the
982 // top state is the real population bound. On an open class the top state
983 // is the artefact of the maxStates truncation, and a self-loop there
984 // would feed the truncation bias straight into the reversed rate. It is
985 // written on the DIAGONAL so it stays inert in the generator while still
986 // contributing the pi(i)/pi(i) = 1 ratio the INAP estimators read off.
987 if (std::isfinite(njobs[a.from_class])) {
988 const std::size_t off = blk(ca.nlev - 1, ca.mph);
989 for (std::size_t i = 0; i < ca.mph; ++i)
990 Am(off + i, off + i) += T(m.svcdown[pa][i] * prob);
991 }
992 m.Aa.push_back(Am);
993
994 const RcatComponent<T>& cp = comp[pp];
995 Matrix<T> Bm(cp.N, cp.N, zero);
996 if (a.is_negative) {
997 if (a.is_catastrophe) {
998 for (std::size_t n = 0; n < cp.nlev; ++n) set_identity(Bm, n, 0, cp.mph);
999 } else if (a.has_removal_dist) {
1000 add_batch_removal(Bm, L.signalremdist[a.removal_class], one, cp.nlev, cp.mph);
1001 set_identity(Bm, 0, 0, cp.mph); // an empty queue absorbs the signal
1002 } else {
1003 set_identity(Bm, 0, 0, cp.mph);
1004 for (std::size_t n = 1; n < cp.nlev; ++n) set_identity(Bm, n, n - 1, cp.mph);
1005 }
1006 } else {
1007 // The phase is untouched: a job joining does not restart the server,
1008 // and the service phase frozen at level 0 is the one the last
1009 // completion left behind, which for a phase-type is already its
1010 // entry distribution.
1011 for (std::size_t n = 0; n + 1 < cp.nlev; ++n) set_identity(Bm, n, n + 1, cp.mph);
1012 set_identity(Bm, cp.nlev - 1, cp.nlev - 1, cp.mph);
1013 }
1014 m.Pb.push_back(Bm);
1015 }
1016 return m;
1017}
1018
1019/** Assemble a component's generator from the local rates and the current x. */
1020template <class T>
1021Matrix<T> assemble_generator(const RcatModel<T>& m, const std::vector<T>& x, std::size_t k) {
1022 Matrix<T> Qk = m.L[k];
1023 for (std::size_t c = 0; c < m.actions.size(); ++c) {
1024 if (m.psv[c] == k) {
1025 for (std::size_t i = 0; i < Qk.rows(); ++i)
1026 for (std::size_t j = 0; j < Qk.cols(); ++j) Qk(i, j) += T(x[c] * m.Pb[c](i, j));
1027 } else if (m.act[c] == k) {
1028 for (std::size_t i = 0; i < Qk.rows(); ++i)
1029 for (std::size_t j = 0; j < Qk.cols(); ++j) Qk(i, j) += m.Aa[c](i, j);
1030 }
1031 }
1032 // ctmc_makeinfgen discards whatever sits on the diagonal and rebuilds it
1033 // from the row sums, which is why the reference's unscaled diagonal
1034 // corrections here are inert. See the header note.
1035 return mc::ctmc_makeinfgen(Qk);
1036}
1037
1038/** A matrix in double, whatever arithmetic the model carries. */
1039template <class T>
1040Matrix<double> ag_as_double(const Matrix<T>& m) {
1041 Matrix<double> out(m.rows(), m.cols(), 0.0);
1042 for (std::size_t i = 0; i < m.rows(); ++i)
1043 for (std::size_t j = 0; j < m.cols(); ++j)
1044 out(i, j) = num_traits<T>::to_double(m(i, j));
1045 return out;
1046}
1047
1048/**
1049 * Agent k's static half, as the ag-worker protocol carries it. Double only,
1050 * because the wire is JSON; ag_sweep_cluster refuses any other arithmetic before
1051 * this is reached.
1052 */
1053template <class T>
1054AgWirePayload wire_payload(const RcatModel<T>& m, std::size_t k) {
1055 AgWirePayload a;
1056 a.k = static_cast<int>(k);
1057 a.n = static_cast<int>(m.N[k]);
1058 a.mph = static_cast<int>(m.mph[k]);
1059 a.nlev = static_cast<int>(m.nlev[k]);
1060 a.level.assign(m.level[k].begin(), m.level[k].end());
1061 a.L = ag_triplets(ag_as_double(m.L[k]));
1062 for (std::size_t c = 0; c < m.actions.size(); ++c) {
1063 if (m.psv[c] == k) {
1064 a.passive_c.push_back(static_cast<int>(c));
1065 a.passive_m.push_back(ag_triplets(ag_as_double(m.Pb[c])));
1066 } else if (m.act[c] == k) {
1067 a.active_c.push_back(static_cast<int>(c));
1068 a.active_m.push_back(ag_triplets(ag_as_double(m.Aa[c])));
1069 }
1070 }
1071 return a;
1072}
1073
1074/**
1075 * Port of `compute_equilibrium`: every component solved in isolation.
1076 *
1077 * Agent k reads the rest of the model only through the scalar reversed rates x
1078 * and writes only its own slot, so this is a fan-out and not a recurrence. That
1079 * is what lets @p exec evaluate the agents on a thread pool or on remote workers
1080 * and still walk the same iterates as the serial loop; any cross-agent read
1081 * added here would silently make those backends race.
1082 */
1083template <class T>
1084void compute_equilibrium(const RcatModel<T>& m, const std::vector<T>& x,
1085 std::vector<std::vector<T>>& pi, std::vector<Matrix<T>>& Q,
1086 const AgOptions* opt = nullptr, AgWorkerPool* pool = nullptr) {
1087 pi.assign(m.num_processes, std::vector<T>());
1088 Q.assign(m.num_processes, Matrix<T>());
1089
1090 auto gen = [&](std::size_t k) { return assemble_generator(m, x, k); };
1091 auto sol = [&](const Matrix<T>& Qk, std::size_t k) {
1092 return solve_component(Qk, m.mph[k], m.nlev[k], m.level[k]);
1093 };
1094
1095 const std::string mode = (opt == nullptr) ? std::string(exec_serial()) : opt->exec;
1096 if (exec_is_parallel(mode)) {
1097 ag_sweep_parallel<T>(m.num_processes, opt->nworkers, gen, sol, Q, pi);
1098 } else if (mode == exec_cluster()) {
1099 auto payload = [&](std::size_t k) { return wire_payload(m, k); };
1100 ag_sweep_cluster<T>(m.num_processes, *pool, x, gen, sol, payload, Q, pi);
1101 } else {
1102 ag_sweep_serial<T>(m.num_processes, gen, sol, Q, pi);
1103 }
1104}
1105
1106
1107/**
1108 * Port of `compute_equilibrium_qbd`: open components on their infinite state
1109 * space, closed ones as before.
1110 */
1111template <class T>
1112void compute_equilibrium_qbd(const RcatModel<T>& m, const std::vector<T>& x,
1113 std::vector<std::vector<T>>& pi, std::vector<Matrix<T>>& Q,
1114 std::vector<double>& rho_proc, std::vector<bool>& is_geom,
1115 std::vector<QbdTail<T>>& geom_data) {
1116 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
1117 pi.assign(m.num_processes, std::vector<T>());
1118 Q.assign(m.num_processes, Matrix<T>());
1119 rho_proc.assign(m.num_processes, 0.0);
1120 is_geom.assign(m.num_processes, false);
1121 geom_data.assign(m.num_processes, QbdTail<T>());
1122
1123 for (std::size_t k = 0; k < m.num_processes; ++k) {
1124 const std::size_t Nk = m.N[k];
1125 Matrix<T> Off = m.L[k];
1126 for (std::size_t i = 0; i < Nk; ++i) Off(i, i) = zero;
1127 for (std::size_t c = 0; c < m.actions.size(); ++c) {
1128 if (m.psv[c] == k) {
1129 for (std::size_t i = 0; i < Nk; ++i)
1130 for (std::size_t j = 0; j < Nk; ++j) Off(i, j) += T(x[c] * m.Pb[c](i, j));
1131 } else if (m.act[c] == k) {
1132 for (std::size_t i = 0; i < Nk; ++i)
1133 for (std::size_t j = 0; j < Nk; ++j) Off(i, j) += m.Aa[c](i, j);
1134 }
1135 }
1136 for (std::size_t i = 0; i < Nk; ++i) Off(i, i) = zero;
1137 Q[k] = mc::ctmc_makeinfgen(Off);
1138
1139 const std::size_t mph = m.mph[k], nlev = m.nlev[k];
1140 bool solved_geom = false;
1141 if (m.is_open_proc[k] && nlev >= 5) {
1142 if (mph == 1) {
1143 // Read the homogeneous interior one level below the truncation,
1144 // so the reflecting boundary of Off does not contaminate it.
1145 const std::size_t s0 = Nk - 2;
1146 const double f = num_traits<T>::to_double(Off(s0, s0 + 1));
1147 const double b = num_traits<T>::to_double(Off(s0, s0 - 1));
1148 const double g0 = num_traits<T>::to_double(Off(s0, 0));
1149 // A jump to a strictly interior lower level is batch removal onto
1150 // a non-empty state, which is not a scalar QBD; defer to the
1151 // finite solve rather than fit a geometric that does not hold.
1152 double inter_down = 0.0;
1153 for (std::size_t j = 1; j + 3 < Nk; ++j)
1154 inter_down += num_traits<T>::to_double(Off(s0, j));
1155 if (inter_down <= 1e-11 && f > 0.0) {
1156 const double rho = qbd_scalar_rho(f, b, g0);
1157 if (std::isfinite(rho) && rho > 0.0 && rho < 1.0 - 1e-12) {
1158 rho_proc[k] = rho;
1159 is_geom[k] = true;
1160 pi[k].assign(Nk, zero);
1161 const T rt = num_traits<T>::from_double(rho);
1162 T acc = T(one - rt);
1163 for (std::size_t n = 0; n < Nk; ++n) {
1164 pi[k][n] = acc;
1165 acc = T(acc * rt);
1166 }
1167 solved_geom = true;
1168 }
1169 }
1170 } else if (is_block_tridiagonal(Q[k], m.level[k])) {
1171 // Read the homogeneous interior BLOCKS one level below the
1172 // truncation, for the same reason the scalar branch reads the
1173 // interior row there.
1174 const std::size_t s0 = nlev - 2;
1175 const Matrix<T> A0 = level_block(Q[k], s0, s0 + 1, mph); // up
1176 const Matrix<T> A1 = level_block(Q[k], s0, s0, mph); // local
1177 const Matrix<T> A2 = level_block(Q[k], s0, s0 - 1, mph); // down
1178 bool any_up = false;
1179 for (std::size_t i = 0; i < mph && !any_up; ++i) {
1180 T rs = zero;
1181 for (std::size_t j = 0; j < mph; ++j) rs += A0(i, j);
1182 if (rs > zero) any_up = true;
1183 }
1184 if (any_up) {
1185 const QbdTail<T> g = qbd_matrix_tail(Q[k], A0, A1, A2, mph);
1186 if (g.ok) {
1187 is_geom[k] = true;
1188 geom_data[k] = g;
1189 pi[k] = qbd_tail_expand(g, nlev, mph);
1190 solved_geom = true;
1191 }
1192 }
1193 }
1194 }
1195 if (!solved_geom) pi[k] = solve_component(Q[k], mph, nlev, m.level[k]);
1196 }
1197}
1198
1199/** The reference's block norm: the largest 1-norm change over the components. */
1200template <class T>
1201double block_norm(const std::vector<std::vector<T>>& a, const std::vector<std::vector<T>>& b) {
1202 double e = 0.0;
1203 for (std::size_t k = 0; k < a.size() && k < b.size(); ++k) {
1204 const std::size_t n = std::min(a[k].size(), b[k].size());
1205 double s = 0.0;
1206 for (std::size_t i = 0; i < n; ++i)
1207 s += std::fabs(num_traits<T>::to_double(T(a[k][i] - b[k][i])));
1208 if (s > e) e = s;
1209 }
1210 return e;
1211}
1212
1213/**
1214 * Port of `closed_chain_condition`: population-conditioned marginals of every
1215 * closed chain.
1216 *
1217 * The INAP estimators read a reversed rate off an ISOLATED component, which
1218 * neither knows the chain population nor sees the traffic equations, so the
1219 * marginals did not sum to N_c and the throughputs did not balance around a
1220 * cycle (ag_closed_network, N = 10: populations summing to 10.61, throughputs
1221 * 1.4568 against 0.99485). For every closed chain whose components synchronize
1222 * only with each other through positive actions, the answer is replaced by the
1223 * RCAT product form restricted to the chain population. The convolution runs
1224 * over STATIONS, not (station, class) components, because classes of one chain
1225 * at one station share its server:
1226 * 1. x_a = s v_ACT(a) p_a, with v the visit ratios of the routing among the
1227 * chain's components and s a throughput scale;
1228 * 2. each station gets level masses M_i(n) for the chain population held
1229 * there: a product-form single server (PS or LCFS-PR, or FCFS or SIRO with
1230 * exponential service and equal rates) gives rho_i^n, an infinite server
1231 * rho_i^n / n!, with rho_i = sum_r s v_ir / mu_ir; any other single server
1232 * holding ONE chain class uses its isolated component at those rates;
1233 * 3. prod_i M_i(n_i) is conditioned on sum_i n_i = N_c by convolution,
1234 * P_i(n) = M_i(n) G_{-i}(N_c - n) / G(N_c), and at an aggregated station
1235 * the split across classes is multinomial with p_r = rho_ir / rho_i;
1236 * 4. s is moved until G(N_c - 1) / G(N_c) = 1 (a warning if it does not
1237 * converge within maxiter).
1238 * EXACT when every station the chain visits serves no class outside the chain
1239 * and is an infinite server, a PS or LCFS-PR single server (any service law),
1240 * or an exponential single server where chain classes meet only under FCFS or
1241 * SIRO with equal rates, and no signal or removal reaches the chain. Otherwise
1242 * APPROXIMATE with a warning: a non-exponential component alone at a single
1243 * server that is not PS or LCFS-PR, or a station shared with another chain, is
1244 * still conditioned (population and flow balance hold); several chain classes
1245 * at a single server that is not product form, or signals, keep the INAP
1246 * answer. OVR receives (QLen, Util, Tput) per component of an aggregated
1247 * station (NaN rows elsewhere), which rcat_metrics reads first.
1248 */
1249template <class T>
1250void closed_chain_condition(const qn::NetworkStruct<T>& L, const RcatModel<T>& m,
1251 std::vector<T>& x, std::vector<std::vector<T>>& pi,
1252 double tol, int maxiter, std::vector<std::vector<double>>& ovr) {
1253 const std::size_t A = m.actions.size(), np = m.num_processes, K = L.nclasses;
1254 ovr.assign(np, std::vector<double>(3, std::numeric_limits<double>::quiet_NaN()));
1255 if (A == 0 || np == 0) return;
1256 const T zero = num_traits<T>::from_int(0);
1257 const std::vector<double> njobs = L.njobs();
1258 std::vector<std::size_t> pstat(np, 0), pclass(np, 0);
1259 for (std::size_t ist = 0; ist < m.process_map.size(); ++ist)
1260 for (std::size_t r = 0; r < m.process_map[ist].size(); ++r)
1261 if (m.process_map[ist][r] != 0) {
1262 pstat[m.process_map[ist][r] - 1] = ist;
1263 pclass[m.process_map[ist][r] - 1] = r;
1264 }
1265 // Truncated convolution of the level masses of every component but SKIP.
1266 auto convolve_all = [](const std::vector<std::vector<double>>& Mk, std::size_t skip,
1267 std::size_t Nc) {
1268 std::vector<double> G(Nc + 1, 0.0);
1269 G[0] = 1.0;
1270 for (std::size_t i = 0; i < Mk.size(); ++i) {
1271 if (i == skip) continue;
1272 std::vector<double> H(Nc + 1, 0.0);
1273 for (std::size_t a = 0; a <= Nc; ++a) {
1274 if (G[a] == 0.0) continue;
1275 for (std::size_t b = 0; a + b <= Nc; ++b) H[a + b] += G[a] * Mk[i][b];
1276 }
1277 G = H;
1278 }
1279 return G;
1280 };
1281 for (std::size_t c = 0; c < L.chains.size(); ++c) {
1282 const std::vector<bool>& ch = L.chains[c];
1283 double popc = 0.0;
1284 for (std::size_t r = 0; r < K && r < ch.size(); ++r)
1285 if (ch[r]) popc += njobs[r];
1286 if (!std::isfinite(popc) || !(popc > 0.0)) continue;
1287 const std::size_t Nc = static_cast<std::size_t>(std::llround(popc));
1288 std::vector<long> pos(np, -1);
1289 std::vector<std::size_t> kc;
1290 for (std::size_t k = 0; k < np; ++k)
1291 if (pclass[k] < ch.size() && ch[pclass[k]]) {
1292 pos[k] = static_cast<long>(kc.size());
1293 kc.push_back(k);
1294 }
1295 if (kc.empty()) continue;
1296 const std::size_t nk = kc.size();
1297 std::vector<bool> touch(A, false);
1298 bool any = false, eligible = true;
1299 Matrix<double> P(nk, nk, 0.0);
1300 for (std::size_t a = 0; a < A; ++a) {
1301 touch[a] = pos[m.act[a]] >= 0 || pos[m.psv[a]] >= 0;
1302 if (!touch[a]) continue;
1303 any = true;
1304 if (m.actions[a].is_negative || pos[m.act[a]] < 0 || pos[m.psv[a]] < 0)
1305 eligible = false;
1306 else
1307 P(static_cast<std::size_t>(pos[m.act[a]]), static_cast<std::size_t>(pos[m.psv[a]])) +=
1308 m.actions[a].prob;
1309 }
1310 if (!any) continue; // self-looping chain: no synchronization
1311 for (std::size_t i = 0; i < nk; ++i) {
1312 const std::size_t k = kc[i];
1313 const std::size_t idx = pstat[k] * K + pclass[k];
1314 P(i, i) += num_traits<T>::to_double(L.rt(idx, idx));
1315 if (m.extsig[k]) eligible = false;
1316 }
1317 for (std::size_t i = 0; i < nk && eligible; ++i) {
1318 double rs = 0.0;
1319 for (std::size_t j = 0; j < nk; ++j) rs += P(i, j);
1320 if (std::abs(rs - 1.0) > 1e-10) eligible = false;
1321 }
1322 if (!eligible) {
1323 if (Nc > 1) {
1324 // left unconditioned, an infinite server of the chain would be
1325 // answered as a single server; inf_supports_reason should have refused
1326 for (std::size_t k : kc) {
1327 const auto& sta = L.stations[pstat[k]];
1328 if (sta.sched == lang::SchedStrategy::INF || std::isinf(sta.nservers))
1329 throw UnsupportedError(ErrorKind{"Structure"},
1330 "Closed chain " + std::to_string(c + 1) + " visits an infinite-server "
1331 "station and interacts with signals or loses jobs outside its "
1332 "components, so it cannot be conditioned on its population; its "
1333 "single-server components would answer for a different model. Use "
1334 "SolverMVA, SolverNC or SolverCTMC");
1335 }
1336 }
1337 std::cerr << "[LINE] Warning: Closed chain " << (c + 1)
1338 << " interacts with signals or loses jobs outside its components; its "
1339 "RCAT marginals are not conditioned on the chain population, so "
1340 "population and flow balance are approximate.\n";
1341 continue;
1342 }
1343 // Station groups of the chain's components, in station order, and the
1344 // kind of each: "single", "shared", "inf" or "blocked".
1345 std::vector<std::size_t> gstat;
1346 std::vector<std::string> gkind;
1347 std::vector<std::vector<std::size_t>> gmem;
1348 std::string blocked, approx;
1349 for (std::size_t ist = 0; ist < L.nstations; ++ist) {
1350 std::vector<std::size_t> mem;
1351 for (std::size_t i = 0; i < nk; ++i)
1352 if (pstat[kc[i]] == ist) mem.push_back(i);
1353 if (mem.empty()) continue;
1354 const auto& sta = L.stations[ist];
1355 for (std::size_t r = 0; r < K && approx.empty(); ++r) {
1356 const std::size_t p = ist < m.process_map.size() && r < m.process_map[ist].size()
1357 ? m.process_map[ist][r] : 0;
1358 if (p != 0 && !(r < ch.size() && ch[r]))
1359 approx = "station " + sta.name + " also serves class " + L.classes[r].name +
1360 " outside the chain, and RCAT does not model a server shared across "
1361 "chains";
1362 }
1363 bool all_exp = true;
1364 for (std::size_t i : mem)
1365 if (m.mph[kc[i]] != 1) all_exp = false;
1366 std::string kind;
1367 if (sta.sched == lang::SchedStrategy::INF || std::isinf(sta.nservers)) {
1368 kind = "inf";
1369 } else if (sta.sched == lang::SchedStrategy::PS || sta.sched == lang::SchedStrategy::LCFSPR) {
1370 kind = "shared";
1371 } else if (mem.size() == 1) {
1372 kind = "single";
1373 if (!all_exp && approx.empty())
1374 approx = "class " + L.classes[pclass[kc[mem[0]]]].name + " at station " +
1375 sta.name + " is not exponential, so its population-conditioned "
1376 "marginal is not a product form";
1377 } else {
1378 const double mu0 = num_traits<T>::to_double(L.rates(ist, pclass[kc[mem[0]]]));
1379 bool equal = true;
1380 for (std::size_t i : mem)
1381 if (std::abs(num_traits<T>::to_double(L.rates(ist, pclass[kc[i]])) - mu0) >
1382 1e-12 * std::abs(mu0))
1383 equal = false;
1384 if (all_exp && equal &&
1385 (sta.sched == lang::SchedStrategy::FCFS || sta.sched == lang::SchedStrategy::SIRO)) {
1386 kind = "shared";
1387 } else {
1388 kind = "blocked";
1389 if (blocked.empty()) {
1390 std::string names;
1391 for (std::size_t i : mem)
1392 names += (names.empty() ? "" : ", ") + L.classes[pclass[kc[i]]].name;
1393 blocked = "classes " + names + " of the chain share the single server of "
1394 "station " + sta.name + ", which is not a product-form station "
1395 "(needs PS or LCFS-PR, or exponential service with equal rates "
1396 "under FCFS or SIRO)";
1397 }
1398 }
1399 }
1400 gstat.push_back(ist);
1401 gkind.push_back(kind);
1402 gmem.push_back(mem);
1403 }
1404 if (!blocked.empty()) {
1405 if (Nc > 1 && std::find(gkind.begin(), gkind.end(), "inf") != gkind.end())
1406 throw UnsupportedError(ErrorKind{"Structure"},
1407 "Closed chain " + std::to_string(c + 1) + " visits an infinite-server station "
1408 "but cannot be conditioned on its population: " + blocked +
1409 ". Use SolverMVA, SolverNC or SolverCTMC");
1410 std::cerr << "[LINE] Warning: Closed chain " << (c + 1) << ": " << blocked
1411 << ". Its RCAT marginals are not conditioned on the chain population, so "
1412 "its results are approximate.\n";
1413 continue;
1414 }
1415 if (!approx.empty())
1416 std::cerr << "[LINE] Warning: Closed chain " << (c + 1) << ": " << approx
1417 << ". Population and flow balance are exact, the marginals are "
1418 "approximate.\n";
1419 const std::size_t nst = gstat.size();
1420 std::vector<double> v = mc::dtmc_solve(P);
1421 double vmax = 0.0;
1422 for (double vi : v) vmax = std::max(vmax, vi);
1423 for (double& vi : v) vi /= vmax;
1424 std::vector<double> demand(nk);
1425 for (std::size_t i = 0; i < nk; ++i)
1426 demand[i] = v[i] / num_traits<T>::to_double(L.rates(pstat[kc[i]], pclass[kc[i]]));
1427 std::vector<double> nfact(Nc + 1, 1.0);
1428 for (std::size_t n = 1; n <= Nc; ++n) nfact[n] = nfact[n - 1] * static_cast<double>(n);
1429
1430 // initial scale: the asymptotic throughput bound min_k mu_k / v_k
1431 double s = std::numeric_limits<double>::infinity();
1432 for (std::size_t i = 0; i < nk; ++i)
1433 s = std::min(s, num_traits<T>::to_double(L.rates(pstat[kc[i]], pclass[kc[i]])) / v[i]);
1434 std::vector<std::vector<double>> mass(nk, std::vector<double>(Nc + 1, 0.0));
1435 std::vector<std::vector<double>> Ms(nst, std::vector<double>(Nc + 1, 0.0));
1436 std::vector<std::vector<T>> pik(nk);
1437 std::vector<double> G;
1438 double gamma = std::numeric_limits<double>::quiet_NaN();
1439 bool converged = false;
1440 for (int it = 0; it < maxiter; ++it) {
1441 for (std::size_t a = 0; a < A; ++a)
1442 if (touch[a])
1443 x[a] = num_traits<T>::from_double(
1444 s * v[static_cast<std::size_t>(pos[m.act[a]])] * m.actions[a].prob);
1445 for (std::size_t i = 0; i < nk; ++i) {
1446 const std::size_t k = kc[i];
1447 pik[i] = solve_component(assemble_generator(m, x, k), m.mph[k], m.nlev[k], m.level[k]);
1448 std::fill(mass[i].begin(), mass[i].end(), 0.0);
1449 for (std::size_t st = 0; st < m.N[k]; ++st)
1450 mass[i][m.level[k][st]] += num_traits<T>::to_double(pik[i][st]);
1451 }
1452 for (std::size_t g = 0; g < nst; ++g) {
1453 if (gkind[g] == "single") {
1454 Ms[g] = mass[gmem[g][0]];
1455 } else {
1456 double rho = 0.0;
1457 for (std::size_t i : gmem[g]) rho += demand[i];
1458 rho *= s;
1459 const bool inf = gkind[g] == "inf";
1460 for (std::size_t n = 0; n <= Nc; ++n)
1461 Ms[g][n] = std::pow(rho, static_cast<double>(n)) / (inf ? nfact[n] : 1.0);
1462 }
1463 }
1464 G = convolve_all(Ms, nst, Nc);
1465 gamma = G[Nc - 1] / G[Nc];
1466 if (std::abs(gamma - 1.0) < tol) {
1467 converged = true;
1468 break;
1469 }
1470 s *= gamma;
1471 }
1472 if (!converged)
1473 std::cerr << "[LINE] Warning: Closed chain " << (c + 1)
1474 << ": the throughput scale did not converge in " << maxiter
1475 << " iterations (|G(N-1)/G(N) - 1| = " << std::abs(gamma - 1.0)
1476 << " > tol = " << tol
1477 << "); its conditioned marginals do not balance flow exactly.\n";
1478 for (std::size_t g = 0; g < nst; ++g) {
1479 const std::vector<double> Gm = convolve_all(Ms, g, Nc);
1480 if (gkind[g] == "single") {
1481 const std::size_t i = gmem[g][0], k = kc[i];
1482 std::vector<T> cond(m.N[k], zero);
1483 for (std::size_t st = 0; st < m.N[k]; ++st)
1484 cond[st] = T(pik[i][st] *
1485 num_traits<T>::from_double(Gm[Nc - m.level[k][st]] / G[Nc]));
1486 pi[k] = cond;
1487 continue;
1488 }
1489 std::vector<double> Pst(Nc + 1, 0.0);
1490 double qst = 0.0, tot = 0.0;
1491 for (std::size_t n = 0; n <= Nc; ++n) {
1492 Pst[n] = Ms[g][n] * Gm[Nc - n] / G[Nc];
1493 qst += static_cast<double>(n) * Pst[n];
1494 }
1495 const double busy = 1.0 - Pst[0];
1496 for (std::size_t i : gmem[g]) tot += demand[i];
1497 for (std::size_t i : gmem[g]) {
1498 const std::size_t k = kc[i];
1499 const double p = tot > 0.0 ? demand[i] / tot : 0.0;
1500 // multinomial thinning of the station population to class k
1501 std::vector<double> Pk(Nc + 1, 0.0);
1502 for (std::size_t j = 0; j <= Nc; ++j)
1503 for (std::size_t n = j; n <= Nc; ++n) {
1504 double b = 1.0;
1505 for (std::size_t t = 1; t <= j; ++t)
1506 b = b * static_cast<double>(n - j + t) / static_cast<double>(t);
1507 Pk[j] += Pst[n] * b * std::pow(p, static_cast<double>(j)) *
1508 std::pow(1.0 - p, static_cast<double>(n - j));
1509 }
1510 std::vector<T> cond(m.N[k], zero);
1511 for (std::size_t st = 0; st < m.N[k]; ++st) {
1512 const std::size_t lv = m.level[k][st];
1513 if (mass[i][lv] > 0.0)
1514 cond[st] = T(pik[i][st] * num_traits<T>::from_double(Pk[lv] / mass[i][lv]));
1515 }
1516 pi[k] = cond;
1517 const double mu = num_traits<T>::to_double(L.rates(pstat[k], pclass[k]));
1518 const double qk = p * qst;
1519 const double uk = gkind[g] == "inf" ? qk : p * busy;
1520 ovr[k][0] = qk;
1521 ovr[k][1] = uk;
1522 ovr[k][2] = mu * uk;
1523 }
1524 }
1525 }
1526}
1527
1528/** Port of `rcat_metrics`. */
1529template <class T>
1530mva::MvaSolution<T> rcat_metrics(const qn::NetworkStruct<T>& L, const RcatModel<T>& m,
1531 const std::vector<std::vector<T>>& pi,
1532 const std::vector<double>& rho_proc,
1533 const std::vector<bool>& is_geom,
1534 const std::vector<QbdTail<T>>& geom_data,
1535 const std::vector<std::vector<double>>& ovr = {}) {
1536 const std::size_t M = L.nstations, K = L.nclasses;
1537 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
1538 mva::MvaSolution<T> s;
1539 s.Q = Matrix<T>(M, K, zero);
1540 s.U = Matrix<T>(M, K, zero);
1541 s.R = Matrix<T>(M, K, zero);
1542 s.Tp = Matrix<T>(M, K, zero);
1543 s.C.assign(K, zero);
1544 s.X.assign(K, zero);
1545
1546 for (std::size_t ist = 0; ist < M; ++ist)
1547 for (std::size_t r = 0; r < K; ++r) {
1548 const std::size_t p = m.process_map.empty() ? 0 : m.process_map[ist][r];
1549 if (p == 0 || p > pi.size() || pi[p - 1].empty()) continue;
1550 // a component of an aggregated closed-chain station (closed_chain_condition)
1551 if (p <= ovr.size() && !std::isnan(ovr[p - 1][0])) {
1552 s.Q(ist, r) = num_traits<T>::from_double(ovr[p - 1][0]);
1553 s.U(ist, r) = num_traits<T>::from_double(ovr[p - 1][1]);
1554 s.Tp(ist, r) = num_traits<T>::from_double(ovr[p - 1][2]);
1555 continue;
1556 }
1557 const bool disabled = L.disabled[ist][r];
1558 const std::size_t mph = m.mph[p - 1];
1559 if (!is_geom.empty() && p <= is_geom.size() && is_geom[p - 1]) {
1560 if (mph == 1) {
1561 // The infinite geometric marginal pi_n = (1-rho) rho^n, whose
1562 // moments are closed forms; using the truncated vector here
1563 // would put the truncation back into the answer.
1564 const T mu = disabled ? zero : L.rates(ist, r);
1565 const T rho = num_traits<T>::from_double(rho_proc[p - 1]);
1566 s.Q(ist, r) = T(rho / (one - rho));
1567 s.U(ist, r) = rho;
1568 if (mu > zero) s.Tp(ist, r) = T(mu * rho);
1569 } else {
1570 // The matrix-geometric tail pi_(n+1) = pi_n R.
1571 const QbdTail<T>& g = geom_data[p - 1];
1572 T busy = zero, tput = zero;
1573 for (std::size_t i = 0; i < mph; ++i) {
1574 busy += g.busy[i];
1575 tput += T(g.busy[i] * m.svcdown[p - 1][i]);
1576 }
1577 s.Q(ist, r) = g.qlen;
1578 s.U(ist, r) = busy;
1579 s.Tp(ist, r) = tput;
1580 }
1581 } else {
1582 const std::vector<T>& v = pi[p - 1];
1583 T q = zero, tput = zero;
1584 for (std::size_t n = 0; n < v.size(); ++n) {
1585 q += T(num_traits<T>::from_int(static_cast<long>(m.level[p - 1][n])) * v[n]);
1586 // The rate of service completions, i.e. the phase-dependent
1587 // departure rate averaged over the marginal. With one phase
1588 // this is the mean rate times P(N>0).
1589 tput += T(m.svcrate[p - 1][n] * v[n]);
1590 }
1591 s.Q(ist, r) = q;
1592 T level0 = zero;
1593 for (std::size_t i = 0; i < mph; ++i) level0 += v[i];
1594 s.U(ist, r) = T(one - level0);
1595 s.Tp(ist, r) = tput;
1596 }
1597 }
1598
1599 for (std::size_t ist = 0; ist < M; ++ist)
1600 for (std::size_t r = 0; r < K; ++r)
1601 if (s.Tp(ist, r) > zero) s.R(ist, r) = T(s.Q(ist, r) / s.Tp(ist, r));
1602
1603 // A SOURCE'S THROUGHPUT IS ITS ARRIVAL RATE, and the loop above cannot fill
1604 // it: a Source has no queue and no service process, so the RCAT process map
1605 // covers no station of that type and every one of its cells stayed zero. The
1606 // reference reports lambda there, and -- far more than a cosmetic row -- the
1607 // whole open network's ARRIVAL RATES are derived from the throughput vector
1608 // by `sn_get_arvr_from_tput`, so a zero at the Source propagated to zero
1609 // arrivals everywhere downstream: `ag_tandem_open` reported ArvR 0 at Queue1
1610 // against a golden of 0.5, and `ag_gnetwork` lost its Negative class's rows
1611 // entirely. It is the same fact `s.X[r]` below already reads off the Source
1612 // for an open class, written into the table it belongs in.
1613 for (std::size_t ist = 0; ist < M; ++ist) {
1614 if (L.stations[ist].nodetype != qn::NodeType::Source) continue;
1615 for (std::size_t r = 0; r < K; ++r)
1616 s.Tp(ist, r) = L.disabled[ist][r] ? zero : L.rates(ist, r);
1617 }
1618
1619 const std::vector<double> njobs = L.njobs();
1620 for (std::size_t r = 0; r < K; ++r) {
1621 if (!std::isfinite(njobs[r])) {
1622 for (std::size_t ist = 0; ist < M; ++ist) {
1623 // From the STATION, for the reason `build_rcat` reads it there.
1624 if (L.stations[ist].nodetype == qn::NodeType::Source) {
1625 s.X[r] = L.disabled[ist][r] ? zero : L.rates(ist, r);
1626 break;
1627 }
1628 }
1629 T c = zero;
1630 for (std::size_t ist = 0; ist < M; ++ist) c += s.R(ist, r);
1631 s.C[r] = c;
1632 } else {
1633 const std::size_t refst = L.classes[r].refstat;
1634 if (refst > 0 && refst <= M) {
1635 s.X[r] = s.Tp(refst - 1, r);
1636 if (s.X[r] > zero)
1637 s.C[r] = T(num_traits<T>::from_double(njobs[r]) / s.X[r]);
1638 }
1639 }
1640 }
1641 return s;
1642}
1643
1644} // namespace ag_detail
1645
1646/**
1647 * The process types the RCAT construction can give a phase dimension to.
1648 *
1649 * After `sn_nonmarkov_toph` (which the RCAT methods run with the phase-type
1650 * fit and no Det preservation) each of these holds a genuine (D0,D1) pair with
1651 * non-negative off-diagonal rates and a single arrival per epoch. The list is
1652 * an ALLOW-list on purpose: a process type nobody has checked against this
1653 * construction must be refused, not answered. Refused are the laws whose
1654 * matrices are not a generator (ME, RAP), those that are not time-homogeneous
1655 * (NHPP, MAPt, PHt), those that are not continuous-time (DMAP), and those that
1656 * arrive in batches (BMAP, MMAP), since a batch moves the level by more than
1657 * one.
1658 */
1686
1687/**
1688 * Why the RCAT decomposition cannot serve an infinite-server station of this
1689 * model, or "" when it can (MATLAB ag_inf_supports).
1690 *
1691 * EVERY RCAT COMPONENT IS A SINGLE-SERVER QBD: build_rcat never reads the
1692 * station's scheduling or server count, so a Delay is decomposed as an M/PH/1
1693 * queue (and 'inapinf' returns its geometric marginal). A CLOSED chain is
1694 * conditioned, the infinite server getting the level masses rho^n / n! (kind
1695 * "inf" in the conditioning step), which needs no BLOCKED station in the chain
1696 * (several chain classes at a single server that is not a product-form
1697 * station) and no signal class in the model (a negative action reaching the
1698 * chain makes the conditioning skip it; solver_ag throws if it would still
1699 * skip such a chain). An OPEN class is refused: nothing conditions it, so the
1700 * component serves at mu where the station serves at n*mu (an open Source ->
1701 * Delay(1) at lambda = 0.5 reported 1.0 jobs at the Delay against the exact
1702 * 0.5). A self-looping class is exempt, being reported from its population.
1703 * The CHAIN population decides, because of class switching.
1704 */
1705template <class T>
1707 using ag_detail::is_signal_class;
1708 const std::size_t M = L.nstations, K = L.nclasses;
1709 const std::vector<double> njobs = L.njobs();
1710 bool any_signal = false;
1711 for (std::size_t r = 0; r < K; ++r)
1712 if (is_signal_class(L, r)) any_signal = true;
1713 // a component exists for (ist, r): not a Source, not a signal, positive rate
1714 auto has_proc = [&](std::size_t ist, std::size_t r) {
1715 if (L.stations[ist].nodetype == qn::NodeType::Source || is_signal_class(L, r)) return false;
1716 const double rate = num_traits<T>::to_double(L.rates(ist, r));
1717 return std::isfinite(rate) && rate > 0.0;
1718 };
1719 // the first reason chain c cannot be conditioned at all, as the
1720 // conditioning step classifies its stations
1721 auto blocked_reason = [&](std::size_t c) -> std::string {
1722 const std::vector<bool>& ch = L.chains[c];
1723 for (std::size_t ist = 0; ist < M; ++ist) {
1724 std::vector<std::size_t> cls;
1725 for (std::size_t r = 0; r < K; ++r)
1726 if (r < ch.size() && ch[r] && has_proc(ist, r)) cls.push_back(r);
1727 const auto& sta = L.stations[ist];
1728 if (cls.size() < 2 || sta.sched == lang::SchedStrategy::INF || std::isinf(sta.nservers) ||
1729 sta.sched == lang::SchedStrategy::PS || sta.sched == lang::SchedStrategy::LCFSPR)
1730 continue;
1731 bool all_exp = true, equal = true;
1732 const double mu0 = num_traits<T>::to_double(L.rates(ist, cls[0]));
1733 for (std::size_t r : cls) {
1734 if (L.phases_of(ist, r) != 1) all_exp = false;
1735 if (std::abs(num_traits<T>::to_double(L.rates(ist, r)) - mu0) > 1e-12 * std::abs(mu0))
1736 equal = false;
1737 }
1738 if (all_exp && equal &&
1739 (sta.sched == lang::SchedStrategy::FCFS || sta.sched == lang::SchedStrategy::SIRO))
1740 continue;
1741 std::string names;
1742 for (std::size_t r : cls) names += (names.empty() ? "" : ", ") + L.classes[r].name;
1743 return "classes " + names + " of the chain share the single server of station " +
1744 sta.name + ", which is not a product-form station (needs PS or LCFS-PR, or "
1745 "exponential service with equal rates under FCFS or SIRO)";
1746 }
1747 return std::string();
1748 };
1749 for (std::size_t ist = 0; ist < M; ++ist) {
1750 if (L.stations[ist].sched != lang::SchedStrategy::INF) continue;
1751 for (std::size_t r = 0; r < K; ++r) {
1752 const double rate = num_traits<T>::to_double(L.rates(ist, r));
1753 if (L.classes[r].self_looping || std::isnan(rate) || !(rate > 0.0)) continue;
1754 std::size_t c = 0;
1755 while (c < L.chains.size() && !(r < L.chains[c].size() && L.chains[c][r])) ++c;
1756 if (c == L.chains.size()) continue;
1757 double popc = 0.0;
1758 for (std::size_t s = 0; s < K && s < L.chains[c].size(); ++s)
1759 if (L.chains[c][s]) popc += njobs[s];
1760 const std::string where = "the infinite-server station '" + L.stations[ist].name + "'";
1761 if (std::isinf(popc))
1762 return "SolverAG decomposes every station into a single-server component "
1763 "(build_rcat never reads sn.nservers), and only a closed chain is "
1764 "conditioned back onto the infinite server, so " + where +
1765 " cannot serve the open class '" + L.classes[r].name +
1766 "'. Use SolverMVA, SolverNC or SolverCTMC";
1767 if (popc <= 1.0) continue;
1768 std::ostringstream pop;
1769 pop << popc;
1770 const std::string head = "SolverAG serves " + where + " for the closed class '" +
1771 L.classes[r].name + "' (chain population " + pop.str() +
1772 ") only by conditioning its chain on the population, ";
1773 if (any_signal)
1774 return head + "and a signal class in the model can make that step skip the "
1775 "chain, leaving a single-server component in its place. Use "
1776 "SolverMVA, SolverNC or SolverCTMC";
1777 const std::string why = blocked_reason(c);
1778 if (!why.empty())
1779 return head + "which it cannot do here: " + why +
1780 ". Use SolverMVA, SolverNC or SolverCTMC";
1781 }
1782 }
1783 return std::string();
1784}
1785
1786/** What the RCAT analyzer returns beyond the metrics. */
1787template <class T>
1788struct AgResult {
1790 std::string actualmethod;
1791 /**
1792 * The RCAT product-form residual of Remark 2, max_l ||pi (x_l I - T_l)||_2,
1793 * computed by 'inapinf' only. Zero exactly when the reversed rates came out
1794 * state-independent, i.e. when the product form the method assumes is real;
1795 * anything else is the size of the modelling error, not of a numerical one.
1796 */
1797 double rcat_residual = 0.0;
1798};
1799
1800/**
1801 * Port of `solver_ag.m`.
1802 *
1803 * `max_states` is the reference's `options.config.maxStates`, the truncation of
1804 * every OPEN component. It defaults to AgOptions::max_states, which carries the
1805 * reference's 100; the explicit parameter overrides it for a caller that has no
1806 * options object to hand.
1807 */
1808template <class T>
1810 std::size_t max_states = 0) {
1811 if (max_states == 0) max_states = opt.max_states;
1812 if constexpr (!num_traits<T>::has_transcendental) {
1813 throw UnsupportedError(ErrorKind{"Arithmetic"},
1814 "solver_ag: the RCAT analyzers stop on a tolerance and the matrix-geometric "
1815 "variant takes a square root, so they need transcendental arithmetic; rerun this "
1816 "model with --arith double or --arith real");
1817 } else {
1818 using namespace ag_detail;
1819 const T zero = num_traits<T>::from_int(0);
1820 const std::size_t M = L.nstations, K = L.nclasses;
1821
1822 std::string method = opt.method;
1823 if (method == "default") method = "inap";
1824 if (method == "exact") {
1825 // The reference warns and falls back rather than erroring, because
1826 // autocat moved out of the tree; solver_mam_autocat.h records that.
1827 method = "inap";
1828 }
1829 if (method != "inap" && method != "inaprc" && method != "inapinf")
1830 throw UnsupportedError(ErrorKind{"Method"}, "solver_ag: unknown method '" + opt.method + "'");
1831
1832 AgResult<T> out;
1833 out.actualmethod = method;
1834
1835 if (opt.exec == exec_cluster() && method == "inapinf") {
1836 // The remote worker implements the FINITE agent solve. 'inapinf' replaces
1837 // it with the matrix-geometric treatment of an open agent -- Neuts' R
1838 // matrix and the scalar-tail detection that precedes it -- which the
1839 // worker does not carry, and answering with the finite solve instead
1840 // would silently change the method.
1841 throw UnsupportedError(ErrorKind{"Method"},
1842 "solver_ag: the 'cluster' execution backend does not carry the 'inapinf' agent "
1843 "solve (the matrix-geometric tail of an open agent runs on the coordinator "
1844 "only); use exec 'serial' or 'parallel' with 'inapinf', or method 'inap'/"
1845 "'inaprc' with 'cluster'");
1846 }
1847 if (opt.exec != exec_serial() && !exec_is_parallel(opt.exec)
1848 && opt.exec != exec_cluster()) {
1849 // 'threads' was this backend's name until 2026-08-19. Naming the rename
1850 // costs one branch and saves a caller with an old script from reading
1851 // "unknown backend" about a backend that still exists.
1852 const std::string hint = (opt.exec == "threads")
1853 ? "; 'threads' was renamed to 'parallel' (alias 'para')" : "";
1854 throw InputError("solver_ag: unknown execution backend '" + opt.exec +
1855 "'; use 'serial', 'parallel' (alias 'para') or 'cluster'" + hint);
1856 }
1857
1858 std::unique_ptr<AgWorkerPool> pool;
1859 if (opt.exec == exec_cluster()) {
1860 pool.reset(new AgWorkerPool(opt.endpoints, opt.worker_timeout));
1861 }
1862
1863 const RcatModel<T> m = build_rcat(L, max_states);
1864
1865 if (m.num_processes == 0) {
1866 // The reference warns and returns zeros rather than erroring: a model
1867 // with no serving station is degenerate, not invalid.
1868 out.sol.Q = Matrix<T>(M, K, zero);
1869 out.sol.U = Matrix<T>(M, K, zero);
1870 out.sol.R = Matrix<T>(M, K, zero);
1871 out.sol.Tp = Matrix<T>(M, K, zero);
1872 out.sol.C.assign(K, zero);
1873 out.sol.X.assign(K, zero);
1874 out.sol.method = opt.method;
1875 out.sol.iter = 0;
1876 return out;
1877 }
1878
1879 const std::size_t A = m.actions.size();
1880 std::vector<std::vector<T>> pi;
1881 std::vector<Matrix<T>> Q;
1882
1883 if (A == 0) {
1884 // No synchronizing action, so there is no fixed point to run: every
1885 // component is already closed under its local rates alone. This is the
1886 // single-queue G-network shape (Source -> Queue -> Sink).
1887 // Solved through the same dispatcher the fixed point uses: this branch
1888 // carries a whole M/PH/1 on its own, whose marginal spans tens of orders
1889 // of magnitude over the truncation, and the level recursions are stable
1890 // there where a null-space solve is not.
1891 pi.assign(m.num_processes, std::vector<T>());
1892 for (std::size_t k = 0; k < m.num_processes; ++k) {
1893 const Matrix<T> Qk = mc::ctmc_makeinfgen(m.L[k]);
1894 pi[k] = solve_component(Qk, m.mph[k], m.nlev[k], m.level[k]);
1895 }
1896 out.sol = rcat_metrics(L, m, pi, std::vector<double>(), std::vector<bool>(),
1897 std::vector<QbdTail<T>>());
1898 out.sol.method = opt.method;
1899 out.sol.iter = 0;
1900 return out;
1901 }
1902
1903 // A component reaching beyond the NEIGHBOURING LEVEL is not a birth-death
1904 // chain, and the mean-of-ratios estimator is meaningless there, so INAP
1905 // switches it to the rate-conserving one that INAP+ uses everywhere. The
1906 // within-level phase transitions of a PH sit far off the diagonal and are
1907 // NOT such a departure, which is why the test is on the level index.
1908 //
1909 // A PHASE-EXPANDED component takes the same estimator, for the same reason.
1910 // On a birth-death chain every state-wise reversed rate equals lambda, so
1911 // their mean is exact; with a phase block per level they do not, the deep
1912 // truncation levels dominate the unweighted mean, and the mean-of-ratios
1913 // overestimates the departure rate exactly as it does on a catastrophe
1914 // (measured on a tandem with Erlang(2) service at Q1: the reversed rate came
1915 // out 1.27 against the exact 0.5, so flow was not conserved).
1916 std::vector<bool> not_birth_death(m.num_processes, false);
1917 for (std::size_t k = 0; k < m.num_processes; ++k) {
1918 if (m.mph[k] > 1) not_birth_death[k] = true;
1919 for (std::size_t n = 0; n < m.N[k]; ++n)
1920 for (std::size_t j = 0; j < m.N[k]; ++j) {
1921 const std::size_t ln = m.level[k][n], lj = m.level[k][j];
1922 const std::size_t d = (ln > lj) ? (ln - lj) : (lj - ln);
1923 if (d > 1 && m.L[k](n, j) > zero) not_birth_death[k] = true;
1924 }
1925 }
1926
1927 // Columns of each active matrix that carry any rate. Aa does not depend on
1928 // x, so this is fixed for the whole fixed point.
1929 std::vector<std::vector<std::size_t>> active_cols(A);
1930 for (std::size_t a = 0; a < A; ++a)
1931 for (std::size_t j = 0; j < m.Aa[a].cols(); ++j) {
1932 T colsum = zero;
1933 for (std::size_t i = 0; i < m.Aa[a].rows(); ++i) colsum += m.Aa[a](i, j);
1934 if (colsum > zero) active_cols[a].push_back(j);
1935 }
1936
1937 // Deterministic initial guess, so the answer does not depend on a seed.
1938 std::vector<T> x(A, zero);
1939 for (std::size_t a = 0; a < A; ++a)
1940 x[a] = num_traits<T>::from_double(static_cast<double>(a + 1) /
1941 static_cast<double>(A + 1));
1942
1943 std::vector<double> rho_proc;
1944 std::vector<bool> is_geom;
1945 std::vector<QbdTail<T>> geom_data;
1946 const bool qbd = (method == "inapinf");
1947 if (qbd) compute_equilibrium_qbd(m, x, pi, Q, rho_proc, is_geom, geom_data);
1948 else compute_equilibrium(m, x, pi, Q, &opt, pool.get());
1949
1950 std::vector<std::vector<T>> a_rowsum(A);
1951 for (std::size_t a = 0; a < A; ++a) {
1952 a_rowsum[a].assign(m.Aa[a].rows(), zero);
1953 for (std::size_t i = 0; i < m.Aa[a].rows(); ++i)
1954 for (std::size_t j = 0; j < m.Aa[a].cols(); ++j) a_rowsum[a][i] += m.Aa[a](i, j);
1955 }
1956
1957 // The fixed point is written out rather than driven by da_fpi: the
1958 // reference installs a custom `da_norm` (the per-component 1-norm above),
1959 // and the C++ da_fpi hard-codes the max-abs norm of a flat vector, which is
1960 // a strictly weaker stopping test and would stop earlier.
1961 const double tol = opt.tol;
1962 std::size_t iter = 0;
1963 bool converged = false;
1964 for (iter = 1; iter <= static_cast<std::size_t>(opt.iter_max); ++iter) {
1965 const std::vector<std::vector<T>> pi_ref = pi;
1966 for (std::size_t a = 0; a < A; ++a) {
1967 const std::size_t k = m.act[a];
1968 if (qbd) {
1969 if (is_geom[k]) {
1970 if (m.mph[k] == 1) {
1971 // On a geometric tail the active label fires only from an
1972 // occupied state, so x = (per-state rate) * P(occupied).
1973 const std::size_t idx = std::min<std::size_t>(1, m.N[k] - 1);
1974 x[a] = T(a_rowsum[a][idx] * num_traits<T>::from_double(rho_proc[k]));
1975 } else {
1976 // Matrix-geometric tail: sum_{n>=1} pi_n = pi_1 (I-R)^-1,
1977 // and the active label has the same row sums at every
1978 // busy level.
1979 T acc = zero;
1980 for (std::size_t i = 0; i < m.mph[k]; ++i)
1981 acc += T(geom_data[k].busy[i] * a_rowsum[a][m.mph[k] + i]);
1982 x[a] = acc;
1983 }
1984 } else {
1985 T acc = zero;
1986 for (std::size_t i = 0; i < pi[k].size() && i < a_rowsum[a].size(); ++i)
1987 acc += T(pi[k][i] * a_rowsum[a][i]);
1988 x[a] = acc;
1989 }
1990 } else {
1991 // pi Aa, the row vector both estimators are read off.
1992 const std::vector<T> v = vecmul(pi[k], m.Aa[a]);
1993 if (method == "inaprc" || not_birth_death[k]) {
1994 // The departure rate of the active component.
1995 T sum = zero;
1996 for (std::size_t j = 0; j < v.size(); ++j) sum += v[j];
1997 if (sum > zero) x[a] = sum;
1998 } else {
1999 // The mean over the support of the STATE-WISE reversed rate
2000 // (pi Aa)_j / pi_j, which RCAT requires to be independent of
2001 // j. On a birth-death component every column of Aa holds one
2002 // entry, so this is the reference's entrywise mean of
2003 // Aa(i,j) pi(i) / pi(j) term for term.
2004 T sum = zero;
2005 std::size_t cnt = 0;
2006 for (std::size_t j : active_cols[a])
2007 if (pi[k][j] > zero && v[j] > zero) {
2008 sum += T(v[j] / pi[k][j]);
2009 ++cnt;
2010 }
2011 if (cnt > 0) x[a] = T(sum / num_traits<T>::from_int(static_cast<long>(cnt)));
2012 }
2013 }
2014 }
2015 if (qbd) compute_equilibrium_qbd(m, x, pi, Q, rho_proc, is_geom, geom_data);
2016 else compute_equilibrium(m, x, pi, Q, &opt, pool.get());
2017
2018 if (block_norm<T>(pi, pi_ref) < tol) {
2019 converged = true;
2020 break;
2021 }
2022 }
2023 // The reference's legacy while-loop leaves the counter one past the cap
2024 // when it never converged, and callers read that as the "did not converge"
2025 // marker; reproduced so the iteration counts agree.
2026 if (!converged) iter = static_cast<std::size_t>(opt.iter_max) + 1;
2027
2028 if (qbd) {
2029 double res = 0.0;
2030 for (std::size_t a = 0; a < A; ++a) {
2031 const std::size_t k = m.act[a];
2032 double s = 0.0;
2033 for (std::size_t j = 0; j < m.N[k]; ++j) {
2034 T acc = T(x[a] * pi[k][j]);
2035 for (std::size_t i = 0; i < m.N[k]; ++i) acc -= T(pi[k][i] * m.Aa[a](i, j));
2036 const double d = num_traits<T>::to_double(acc);
2037 s += d * d;
2038 }
2039 res = std::max(res, std::sqrt(s));
2040 }
2041 out.rcat_residual = res;
2042 }
2043
2044 std::vector<std::vector<double>> ovr;
2045 closed_chain_condition(L, m, x, pi, tol, opt.iter_max, ovr);
2046 out.sol = rcat_metrics(L, m, pi, rho_proc, is_geom, geom_data, ovr);
2047 // Report what ran: 'exact' falls back to inap and must not label the
2048 // approximation as exact.
2049 out.sol.method = (opt.method == "exact") ? method : opt.method;
2050 out.sol.iter = static_cast<int>(iter);
2051 return out;
2052 } // if constexpr has_transcendental
2053}
2054
2055} // namespace ag
2056} // namespace line
2057
2058#endif // LINE_SOLVERS_AG_SOLVER_AG_H
Execution backends of the reversed-rate fixed point.
Options of the agent-based (RCAT) solver.
InputError(const std::string &what)
Definition error.h:105
UnsupportedError(const std::string &what)
Definition error.h:119
AgWorkerPool(const std::vector< std::string > &endpoints, double timeout_seconds)
A network plus its refreshed NetworkStruct.
std::size_t phases_of(std::size_t ist, std::size_t r) const
sn.phases(i,r): the order of the process representation.
std::vector< std::vector< bool > > chains
(nchains x nclasses)
std::vector< JobClass > classes
std::vector< Station< T > > stations
stations[k-1] is the k-th station
Matrix< T > rates
(nstations x nclasses) service rates and SCVs, with a PARALLEL disabled flag instead of MATLAB's NaN ...
std::vector< double > njobs() const
sn.njobs: the population of each class, infinite for an open one.
Steady-state distribution of a continuous-time Markov chain.
What refreshProcessRepresentations and refreshLST compute FROM a distribution: the (D0,...
Equilibrium distribution of a discrete-time Markov chain, and stochastic complementation.
The exception types the port throws.
Dense linear algebra over the templated number type: products, identity, inverse, and powers.
LU factorization with partial pivoting, templated on the number type.
The option and result types SolverMAM shares with its analyzers.
Markovian arrival process descriptors: stationary vectors, rate, moments, autocorrelation and the ind...
Dense matrix and non-owning view.
Marked MAP (MMAP) algebra: per-class rates, class probabilities, superposition, normalization and sca...
void ag_sweep_cluster(std::size_t n, AgWorkerPool &workers, const std::vector< T > &x, Gen gen, Sol sol, Payload payload, std::vector< Matrix< T > > &Q, std::vector< std::vector< T > > &pi)
The same sweep with the agents partitioned over remote ag-worker processes.
Definition ag_exec.h:114
std::vector< std::array< double, 3 > > ag_triplets(const Matrix< double > &m)
Non-zero entries of M as [row, col, value] triplets, 0-based.
void ag_sweep_serial(std::size_t n, Gen gen, Sol sol, std::vector< Matrix< T > > &Q, std::vector< std::vector< T > > &pi)
Evaluate every agent of one sweep.
Definition ag_exec.h:64
Matrix< T > krons(const Matrix< T > &A, const Matrix< T > &B)
Kronecker sum, MATLAB's krons: kron(A, I_nb) + kron(I_na, B).
Definition mmap_lambda.h:71
std::string inf_supports_reason(const qn::NetworkStruct< T > &L)
Why the RCAT decomposition cannot serve an infinite-server station of this model, or "" when it can (...
Definition solver_ag.h:1706
Matrix< T > kron(const Matrix< T > &A, const Matrix< T > &B)
Kronecker product.
Definition mmap_lambda.h:57
const char * exec_cluster()
Partition the agents over remote ag-worker processes.
Definition ag_types.h:47
const char * exec_serial()
The caller's own loop, in agent order.
Definition ag_types.h:28
Matrix< T > qbd_R_logred(const Matrix< T > &B, const Matrix< T > &L, const Matrix< T > &F, unsigned iter_max, const T &tol)
R by logarithmic reduction (qbd_R_logred.m).
Definition qbd_r.h:217
AgResult< T > solver_ag(const qn::NetworkStruct< T > &L, const AgOptions &opt, std::size_t max_states=0)
Port of solver_ag.m.
Definition solver_ag.h:1809
void ag_sweep_parallel(std::size_t n, unsigned nworkers, Gen gen, Sol sol, std::vector< Matrix< T > > &Q, std::vector< std::vector< T > > &pi)
The same sweep over a thread pool.
Definition ag_exec.h:78
bool exec_is_parallel(const std::string &mode)
True for either spelling of the local-thread-pool backend.
Definition ag_types.h:43
bool rcat_supports_process(lang::ProcessType t)
The process types the RCAT construction can give a phase dimension to.
Definition solver_ag.h:1659
mam::Map< T > dist_to_map(const Distrib< T > &d)
The (D0,D1) pair that reaches sn.proc.
SignalType
G-network signal classes, with the values of MATLAB SignalType.
Definition lang_types.h:180
@ NEGATIVE
removes a batch of jobs (Gelenbe's negative customer)
Definition lang_types.h:182
ProcessType
Distribution kinds, with the values of MATLAB ProcessType.
Definition lang_types.h:524
@ LOGLOGISTIC
Three reliability laws of Trivedi and Bobbio, "Reliability andAvailability Engineering" (2017),...
Definition lang_types.h:622
NodeType
Node kinds, with the values of MATLAB NodeType.
Definition lang_types.h:345
double tot(const std::vector< double > &pops)
Matrix< T > krons(const Matrix< T > &A, const Matrix< T > &B)
Kronecker sum, MATLAB's krons: kron(A, I_nb) + kron(I_na, B).
Definition mmap_lambda.h:71
Matrix< T > kron(const Matrix< T > &A, const Matrix< T > &B)
Kronecker product.
Definition mmap_lambda.h:57
Matrix< T > qbd_R_logred(const Matrix< T > &B, const Matrix< T > &L, const Matrix< T > &F, unsigned iter_max, const T &tol)
R by logarithmic reduction (qbd_R_logred.m).
Definition qbd_r.h:217
std::vector< T > ctmc_solve(const Matrix< T > &Qin, const std::string &linsolver=std::string())
Steady-state distribution of a continuous-time Markov chain.
Definition ctmc_solve.h:133
Matrix< T > ctmc_makeinfgen(const Matrix< T > &Q)
Set the diagonal so that every row sums to zero (ctmc_makeinfgen).
Definition ctmc_solve.h:61
std::vector< T > dtmc_solve(const Matrix< T > &P)
Stationary distribution of a stochastic matrix P.
Definition dtmc_solve.h:106
@ Gm
the reference's alias of 'cub'
Definition pfqn_nc.h:111
std::vector< std::size_t > lu(Mat &A)
LU with partial pivoting in place; returns the row permutation.
Definition spn_ispn.h:208
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< T > vecmul(const std::vector< T > &v, const Matrix< T > &A)
Row vector times matrix, v A.
Definition linalg.h:50
std::vector< std::size_t > lu_factor(Matrix< T > &A)
In-place LU of A (n x n).
Definition lu.h:48
Matrix< T > inverse(const Matrix< T > &A)
Inverse by LU with one factorization and n back substitutions.
Definition linalg.h:72
Matrix< T > matmul(const Matrix< T > &A, const Matrix< T > &B)
Matrix product A B.
Definition linalg.h:36
std::vector< T > mulvec(const Matrix< T > &A, const std::vector< T > &v)
Matrix times column vector, A v.
Definition linalg.h:62
std::vector< T > ones(std::size_t n)
Column vector of ones, the ubiquitous e in MAP algebra.
Definition linalg.h:104
Matrix< T > eye(std::size_t n)
Identity of order n.
Definition linalg.h:28
A queueing network and its refreshed NetworkStruct.
Number-type abstraction for the templated API port.
Quasi-birth-death processes: the rate matrix R, the fundamental matrix G, the caudal characteristic,...
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
What the RCAT analyzer returns beyond the metrics.
Definition solver_ag.h:1788
double rcat_residual
The RCAT product-form residual of Remark 2, max_l ||pi (x_l I - T_l)||_2, computed by 'inapinf' only.
Definition solver_ag.h:1797
mva::MvaSolution< T > sol
Definition solver_ag.h:1789
std::string actualmethod
Definition solver_ag.h:1790
Class-level results, the [Q,U,R,T,C,X] of the MATLAB analyzers.
Definition mva_types.h:97