LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_mva.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_MVA_SOLVER_MVA_H
6#define LINE_SOLVERS_MVA_SOLVER_MVA_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * SolverMVA over a SolverLN layer.
12 *
13 * Ports of matlab/src/solvers/MVA/solver_mva.m (exact BCMP MVA),
14 * solver_amvald.m + solver_amvald_forward.m (the general approximate MVA), and
15 * solver_amva.m + solver_mva_analyzer.m (the method dispatch that chooses
16 * between them). The chain aggregation they all sit on is in sn_chain.h.
17 *
18 * SCOPE. The dispatch reproduces the `default` ladder in full, since it is what
19 * decides which algorithm each layer gets and therefore what the numbers are.
20 * The algorithms behind it are ported for the disciplines a layered model
21 * produces -- INF, PS, FCFS, SIRO, LCFSPR -- with the `default` and `seidmann`
22 * multiserver approximations and the `default` high-variance setting. Priority
23 * (HOL), discriminatory sharing (DPS), load- and class-dependence, the `suri`
24 * and `softmin` multiserver variants, the queue-line and fraction-line
25 * estimators and open classes are REFUSED by name. Each is a distinct
26 * approximation, and mapping any of them onto a neighbour would return a
27 * plausible number that is not the reference's.
28 *
29 * ARITHMETIC. Everything here is field arithmetic. The AMVA loops stop on a
30 * tolerance, so an exact run returns the iterate its stopping rule selected,
31 * computed without rounding; see the gate note in pfqn_egflinearizer.h.
32 */
33
35#include <algorithm>
36#include <cctype>
37#include <cmath>
38#include <limits>
39#include <string>
40#include <utility>
41#include <vector>
42
74#include "line/util/error.h"
76
77namespace line {
78namespace mva {
79
80// ---------------------------------------------------------------------------
81// Exact MVA
82// ---------------------------------------------------------------------------
83
84/**
85 * Port of `solver_mva_lcfsqn.m`: the closed two-station LCFS + LCFS-PR network.
86 *
87 * `pfqn_lcfsqn_mva` returns the throughput, the queue lengths and the
88 * utilizations for the pair directly; everything else here is the mapping back
89 * onto the model's station indexing, with the response times from Little's law
90 * and the cycle time as their sum. `lG` is NaN: this recursion carries no
91 * normalizing constant, and the reference says so rather than reporting zero.
92 */
93template <class T>
95 std::size_t lcfspr_ist) {
96 const T zero = num_traits<T>::from_int(0);
97 const T one = num_traits<T>::from_int(1);
98 const std::size_t M = L.nstations, R = L.nclasses;
99
100 // A CLASS OF ZERO POPULATION NEEDS A PLACEHOLDER RATE, not a zero. The
101 // reference initializes these to zeros (solver_mva_lcfsqn.m:31-34) and gets
102 // away with it because pfqn_lcfsqn_mva.m validates nothing; the C++ api
103 // added a check that rejects a non-positive alpha for EVERY class
104 // regardless of its population (pfqn_lcfsqn_mva.h:97-99), so a closed LCFS
105 // model carrying an empty class threw where MATLAB answers. One is inert:
106 // it enters only as 1^0 in the product A = prod alpha_r^{n_r}, as
107 // alpha_r * T_r with T_r = 0 in the throughput sum, and as U = T*alpha = 0.
108 std::vector<T> alpha(R, one), beta(R, one);
109 std::vector<int> N(R, 0);
110 for (std::size_t r = 0; r < R; ++r) {
111 const double nr = L.classes[r].population;
112 if (!(nr > 0.0)) continue;
113 N[r] = static_cast<int>(std::llround(nr));
114 const T mu_l = L.rates(lcfs_ist - 1, r);
115 const T mu_p = L.rates(lcfspr_ist - 1, r);
116 if (!(mu_l > zero) || !std::isfinite(num_traits<T>::to_double(mu_l)))
117 throw InputError("solver_mva_lcfsqn: invalid service rate at the LCFS station for class " +
118 std::to_string(r + 1));
119 if (!(mu_p > zero) || !std::isfinite(num_traits<T>::to_double(mu_p)))
120 throw InputError("solver_mva_lcfsqn: invalid service rate at the LCFS-PR station for "
121 "class " + std::to_string(r + 1));
122 alpha[r] = T(one / mu_l);
123 beta[r] = T(one / mu_p);
124 }
125
126 const pfqn::LcfsMvaResult<T> res = pfqn::pfqn_lcfsqn_mva(alpha, beta, N);
127
128 MvaSolution<T> out;
129 out.Q = Matrix<T>(M, R, zero);
130 out.U = Matrix<T>(M, R, zero);
131 out.R = Matrix<T>(M, R, zero);
132 out.Tp = Matrix<T>(M, R, zero);
133 out.C.assign(R, zero);
134 out.X.assign(R, zero);
135 for (std::size_t r = 0; r < R; ++r) {
136 out.Q(lcfs_ist - 1, r) = res.Q(0, r);
137 out.Q(lcfspr_ist - 1, r) = res.Q(1, r);
138 out.U(lcfs_ist - 1, r) = res.U(0, r);
139 out.U(lcfspr_ist - 1, r) = res.U(1, r);
140 if (N[r] <= 0) continue;
141 out.X[r] = res.T_[r];
142 out.Tp(lcfs_ist - 1, r) = res.T_[r];
143 out.Tp(lcfspr_ist - 1, r) = res.T_[r];
144 }
145 for (std::size_t i : {lcfs_ist - 1, lcfspr_ist - 1})
146 for (std::size_t r = 0; r < R; ++r)
147 if (out.Tp(i, r) > zero) out.R(i, r) = T(out.Q(i, r) / out.Tp(i, r));
148 for (std::size_t r = 0; r < R; ++r)
149 if (N[r] > 0) out.C[r] = T(out.R(lcfs_ist - 1, r) + out.R(lcfspr_ist - 1, r));
150 // REPORTED AS 'exact', not as 'lcfsqn'. `solver_mva_analyzer` names the
151 // method AFTER solver_mva returns, so the reference reports every internal
152 // branch of it under the one name; a caller that saw 'lcfsqn' here would
153 // disagree with MATLAB on `actualmethod` while agreeing on every number.
154 out.method = "exact";
155 out.lG = std::numeric_limits<double>::quiet_NaN();
156 return out;
157}
158
159/** Port of solver_mva.m, closed and mixed product-form networks. */
160template <class T>
162 using qn::SchedStrategy;
163 const T zero = num_traits<T>::from_int(0);
164 const std::size_t M = L.nstations, C = L.nchains;
165
166 // The special-cased LCFS + LCFS-PR pair, BEFORE the product-form test: an
167 // LCFS station is not product-form on its own, and the reference reaches
168 // this branch on a model the generic path would reject.
169 std::vector<std::size_t> lcfs, lcfspr; // 1-based station indices
170 for (std::size_t i = 0; i < M; ++i) {
171 if (L.stations[i].sched == SchedStrategy::LCFS) lcfs.push_back(i + 1);
172 if (L.stations[i].sched == SchedStrategy::LCFSPR) lcfspr.push_back(i + 1);
173 }
174 if (!lcfs.empty() && !lcfspr.empty()) {
175 if (lcfs.size() != 1 || lcfspr.size() != 1)
176 throw UnsupportedError(ErrorKind{"SchedStrategy_LCFS"},
177 "solver_mva: LCFS MVA requires exactly one LCFS and one LCFS-PR station");
178 for (std::size_t c = 0; c < C; ++c)
179 if (std::isinf(d.Nchain[c]))
180 throw UnsupportedError(ErrorKind{"OpenClass"}, "solver_mva: LCFS MVA requires a closed queueing network");
181 // A self-loop would let a job re-enter the station it just left, which
182 // the two-station recursion has no term for.
183 const std::size_t S = L.nof_stateful(), Rn = L.nclasses;
184 for (std::size_t ist : {lcfs[0], lcfspr[0]}) {
185 const std::size_t sf = L.stateful_of_station(ist) - 1;
186 for (std::size_t r = 0; r < Rn; ++r)
187 if (L.rt.rows() == S * Rn && L.rt(sf * Rn + r, sf * Rn + r) > zero)
188 throw UnsupportedError(ErrorKind{"SchedStrategy_LCFS"},
189 "solver_mva: LCFS MVA does not support self-loops at stations");
190 }
191 return solver_mva_lcfsqn(L, lcfs[0], lcfspr[0]);
192 }
193 if (!lcfs.empty())
194 throw UnsupportedError(ErrorKind{"SchedStrategy_LCFS"}, "solver_mva: LCFS scheduling requires a paired LCFS-PR station");
195
196 // METHOD 'mva' IS THE DELIBERATE APPROXIMATION: the dispatch warns that the
197 // exact recursion is being run outside its hypotheses and promises an answer,
198 // so throwing here would contradict its own message. Only an implicit or
199 // 'exact' request is refused.
200 if (!L.has_product_form() && opt.method != "mva") {
201 // Name the first failing conjunct of has_product_form(), in the order it tests them.
202 std::string why;
203 if (!L.sched_is_product_form()) why = "a station's scheduling is outside BCMP (INF, PS, FCFS, LCFS, LCFS-PR)";
204 else if (L.has_multi_class_heter_fcfs()) why = "an FCFS station serves its classes at different rates";
205 else if (L.has_priorities()) why = "the classes have priorities";
206 else if (!L.fj.empty()) why = "the model has a fork-join";
207 else if (L.has_sd_routing()) why = "a node routes by state-dependent rules (RROBIN, WRROBIN, JSQ, SQ, SDR)";
208 else if (L.has_blocking()) why = "a station has a finite buffer or the model has a capacity region";
209 else why = "an FCFS station has non-exponential service";
210 throw UnsupportedError(ErrorKind{"ProductForm"}, "solver_mva: the model does not have a product form (" + why + ")");
211 }
212
213 std::vector<std::size_t> infSET, qSET; // 0-based station indices
214 for (std::size_t i = 0; i < M; ++i) {
215 switch (L.stations[i].sched) {
216 case SchedStrategy::EXT: break;
217 case SchedStrategy::INF: infSET.push_back(i); break;
218 case SchedStrategy::PS:
219 case SchedStrategy::LCFSPR:
220 case SchedStrategy::FCFS:
221 case SchedStrategy::SIRO: qSET.push_back(i); break;
222 default:
223 throw UnsupportedError(ErrorKind{"SchedStrategy"}, std::string("solver_mva: unsupported exact MVA analysis for ") +
224 lang::sched_to_text(L.stations[i].sched) + " scheduling");
225 }
226 }
227
228 // demands at the queueing and delay stations, chain by chain
229 Matrix<T> Lq(qSET.size(), C, zero), Zd(infSET.size(), C, zero);
230 for (std::size_t a = 0; a < qSET.size(); ++a)
231 for (std::size_t c = 0; c < C; ++c)
232 Lq(a, c) = T(d.STchain(qSET[a], c) * d.Vchain(qSET[a], c));
233 for (std::size_t a = 0; a < infSET.size(); ++a)
234 for (std::size_t c = 0; c < C; ++c)
235 Zd(a, c) = T(d.STchain(infSET[a], c) * d.Vchain(infSET[a], c));
236
237 // open-chain arrival-rate rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
238 std::vector<T> lambda(C, zero);
239 std::vector<int> N(C, 0);
240 for (std::size_t c = 0; c < C; ++c) {
241 if (!std::isfinite(d.Nchain[c])) {
242 N[c] = pfqn::OPEN_CLASS;
243 const T st = d.STchain(d.refstatchain[c] - 1, c);
244 lambda[c] = st > zero ? T(num_traits<T>::from_int(1) / st) : zero;
245 continue;
246 }
247 N[c] = static_cast<int>(std::llround(d.Nchain[c]));
248 }
249 std::vector<int> S;
250 for (std::size_t a = 0; a < qSET.size(); ++a) {
251 const double s = L.stations[qSET[a]].nservers;
252 if (!std::isfinite(s))
253 throw UnsupportedError(ErrorKind{"SchedStrategy"}, "solver_mva: a queueing station has infinitely many servers but "
254 "is not inf-scheduled");
255 S.push_back(static_cast<int>(std::llround(s)));
256 }
257
258 // Interlocked flow (Franks 1999, Eq. 4.7): a request cannot queue behind work that
259 // its own submission caused, so the arrival-instant queue drops the interlocked share
260 // of the other chains. SolverLN supplies the matrix, class-indexed.
261 const Matrix<T> IL = sn_interlock_chain<T>(L, opt.interlock);
262 // the interlocked recursion is a separate entry point: pfqn_mvams and the pfqn_mva
263 // family it dispatches to carry the standard arrival theorem only
264 const pfqn::MvaResult<T> pf =
265 IL.empty() ? pfqn::pfqn_mvams(lambda, Lq, N, Zd, std::vector<int>(qSET.size(), 1), S)
266 : pfqn::pfqn_mvams_ilock(lambda, Lq, N, Zd, std::vector<int>(qSET.size(), 1), S, IL);
267
268 Matrix<T> Qchain(M, C, zero), Wchain(M, C, zero), Tchain(M, C, zero), Uchain(M, C, zero);
269 std::vector<T> Xchain = pf.XN;
270 for (std::size_t a = 0; a < qSET.size(); ++a)
271 for (std::size_t c = 0; c < C; ++c) Qchain(qSET[a], c) = pf.QN(a, c);
272 for (std::size_t a = 0; a < infSET.size(); ++a)
273 for (std::size_t c = 0; c < C; ++c)
274 Qchain(infSET[a], c) = T(Xchain[c] * d.STchain(infSET[a], c) * d.Vchain(infSET[a], c));
275
276 std::vector<std::size_t> rset;
277 for (std::size_t c = 0; c < C; ++c)
278 if (d.Nchain[c] != 0.0) rset.push_back(c);
279
280 for (std::size_t c : rset) {
281 for (std::size_t i : infSET) Wchain(i, c) = d.STchain(i, c);
282 for (std::size_t i : qSET) {
283 if (std::isinf(L.stations[i].nservers)) {
284 Wchain(i, c) = d.STchain(i, c);
285 } else if (d.Vchain(i, c) == zero || Xchain[c] == zero) {
286 Wchain(i, c) = zero;
287 } else {
288 Wchain(i, c) = T(Qchain(i, c) / (Xchain[c] * d.Vchain(i, c)));
289 }
290 }
291 }
292
293 std::vector<T> Cc(C, zero);
294 for (std::size_t c : rset) {
295 T sw = zero;
296 for (std::size_t i = 0; i < M; ++i) sw += Wchain(i, c);
297 if (sw == zero) {
298 Xchain[c] = zero;
299 } else {
300 T cyc = zero;
301 for (std::size_t i = 0; i < M; ++i) cyc += d.Vchain(i, c) * Wchain(i, c);
302 Cc[c] = cyc;
303 // open-chain throughput rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
304 if (cyc != zero && std::isfinite(d.Nchain[c]))
305 Xchain[c] = T(num_traits<T>::from_double(d.Nchain[c]) / cyc);
306 }
307 for (std::size_t i = 0; i < M; ++i) {
308 Qchain(i, c) = T(Xchain[c] * d.Vchain(i, c) * Wchain(i, c));
309 Tchain(i, c) = T(Xchain[c] * d.Vchain(i, c));
310 }
311 }
312 for (std::size_t i = 0; i < M; ++i)
313 for (std::size_t c : rset) {
314 const T u = T(d.Vchain(i, c) * d.STchain(i, c) * Xchain[c]);
315 Uchain(i, c) = std::isinf(L.stations[i].nservers)
316 ? u
317 : T(u / num_traits<T>::from_double(L.stations[i].nservers));
318 }
319
320 // renormalise a utilization that the product-form formula pushed past one
321 for (std::size_t i = 0; i < M; ++i) {
322 if (!(L.stations[i].sched == SchedStrategy::FCFS || L.stations[i].sched == SchedStrategy::PS))
323 continue;
324 T usum = zero;
325 for (std::size_t c = 0; c < C; ++c) usum += Uchain(i, c);
326 if (num_traits<T>::to_double(usum) <= 1.0 + opt.tol) continue;
327 T den = zero;
328 for (std::size_t c = 0; c < C; ++c) den += d.Vchain(i, c) * d.STchain(i, c) * Xchain[c];
329 if (den == zero) continue;
330 const T cap = usum > num_traits<T>::from_int(1) ? num_traits<T>::from_int(1) : usum;
331 for (std::size_t c = 0; c < C; ++c) {
332 if (!(num_traits<T>::to_double(d.Vchain(i, c) * d.STchain(i, c)) > opt.tol)) continue;
333 Uchain(i, c) = T(cap * d.Vchain(i, c) * d.STchain(i, c) * Xchain[c] / den);
334 }
335 }
336
337 Matrix<T> Rchain(M, C, zero);
338 for (std::size_t i = 0; i < M; ++i)
339 for (std::size_t c = 0; c < C; ++c)
340 if (Tchain(i, c) != zero) Rchain(i, c) = T(Qchain(i, c) / Tchain(i, c));
341 // solver_mva.m:159-162 zeroes every non-finite X, U, Q and R. pfqn_mvaldmx
342 // reports a saturated open station as Inf, and getAvg derives ResidT off
343 // this R BEFORE its own instability cap writes the Inf back, so an Inf
344 // left here would turn ResidT Inf where the reference reports 0.
345 if constexpr (num_traits<T>::has_transcendental) {
346 const auto nonfinite = [](const T& v) { return !std::isfinite(num_traits<T>::to_double(v)); };
347 for (std::size_t c = 0; c < C; ++c)
348 if (nonfinite(Xchain[c])) Xchain[c] = zero;
349 for (std::size_t i = 0; i < M; ++i)
350 for (std::size_t c = 0; c < C; ++c) {
351 if (nonfinite(Uchain(i, c))) Uchain(i, c) = zero;
352 if (nonfinite(Qchain(i, c))) Qchain(i, c) = zero;
353 if (nonfinite(Rchain(i, c))) Rchain(i, c) = zero;
354 }
355 }
356 for (std::size_t c = 0; c < C; ++c) {
357 if (d.Nchain[c] != 0.0) continue;
358 Xchain[c] = zero;
359 for (std::size_t i = 0; i < M; ++i) {
360 Uchain(i, c) = zero;
361 Qchain(i, c) = zero;
362 Rchain(i, c) = zero;
363 Tchain(i, c) = zero;
364 Wchain(i, c) = zero;
365 }
366 }
367
369 L, d, Matrix<T>(), Matrix<T>(), Rchain, Tchain, Xchain);
370 MvaSolution<T> out;
371 out.Q = cr.Q;
372 out.U = cr.U;
373 out.R = cr.R;
374 out.Tp = cr.Tp;
375 out.C = cr.C;
376 out.X = cr.X;
377 out.method = "exact";
378 out.lG = pf.lG;
379 return out;
380}
381
382// ---------------------------------------------------------------------------
383// Approximate MVA, the general (chain-level) path
384// ---------------------------------------------------------------------------
385
386namespace detail {
387
388/**
389 * The multiserver capacity term of solver_amvald_forward, all four rules.
390 *
391 * softmin 1/softmin(n_i, c_i, 20) at EVERY station
392 * seidmann 1/c_i, and 1 at an infinite server
393 * default softmin, then the FCFS-family stations overridden with 1/c_i
394 * suri 1 everywhere; the multiplicity is carried by the Suri factor
395 * applied to the queue length inside the residence formula
396 *
397 * softmin is a genuine transcendental (exp), so the exact backend can evaluate
398 * this only where softmin is not reached: seidmann and suri everywhere, and
399 * default at an infinite server or an FCFS-family station. Anything else
400 * refuses by name.
401 */
402template <class T>
403std::vector<T> ms_term(const qn::NetworkStruct<T>& L, const std::vector<qn::SchedStrategy>& sched,
404 const std::vector<T>& narrival, const std::string& multiserver) {
405 using qn::SchedStrategy;
406 const std::size_t M = L.nstations;
407 const T one = num_traits<T>::from_int(1);
408 std::vector<T> r(M, one);
409 if (multiserver == "suri") return r; // no demand scaling; see suri_factor
410 if (!(multiserver == "default" || multiserver == "seidmann" || multiserver == "softmin"))
411 throw UnsupportedError(ErrorKind{"Method"}, "solver_amvald: multiserver approximation '" + multiserver +
412 "' is not implemented in this port");
413 for (std::size_t i = 0; i < M; ++i) {
414 const double c = L.stations[i].nservers;
415 const SchedStrategy sc = sched[i];
416 // a finite pool solver_amvald re-marked INF (servers >= jobs) serves each job at full rate
417 if (sc == SchedStrategy::INF) continue;
418 const bool fcfs_family =
419 sc == SchedStrategy::FCFS || sc == SchedStrategy::SIRO || sc == SchedStrategy::LCFSPR;
420 if (multiserver == "seidmann" || (multiserver == "default" && fcfs_family)) {
421 r[i] = std::isinf(c) ? one : T(one / num_traits<T>::from_double(c));
422 continue;
423 }
424 if (std::isinf(c)) {
425 r[i] = one; // delay server, pfqn_lldfun returns 1
426 continue;
427 }
428 if constexpr (num_traits<T>::has_transcendental) {
429 // 1/softmin(n, c, alpha), in the reference's numerically safe form
430 const double alpha = 20.0;
431 const double n = num_traits<T>::to_double(narrival[i]);
432 const double lo = std::min(n, c), hi = std::max(n, c);
433 const double gap = hi - lo;
434 const double w = alpha * gap > 745.0 ? 0.0 : std::exp(-alpha * gap);
435 const double sm = lo + gap * w / (1.0 + w);
436 r[i] = num_traits<T>::from_double(sm > 0.0 ? 1.0 / sm : 1.0 / std::min(n, c));
437 } else {
438 throw UnsupportedError(ErrorKind{"Arithmetic"},
439 "solver_amvald: the soft-minimum multiserver term evaluates exp, which exact "
440 "arithmetic has no representation for; use the double or real backend, the "
441 "seidmann or suri multiserver rule, or a layer whose queueing stations are "
442 "FCFS-family or infinite-server");
443 }
444 }
445 return r;
446}
447
448/**
449 * The Suri multiserver factor, applied to the arrival queue length rather than
450 * to the demand: rho^(4.464 (c^0.676 - 1)) / c at a finite multiserver station,
451 * 1/c when its utilization is zero, and 0 at an infinite or zero server.
452 *
453 * The utilization it reads is the ITERATE's, so the factor moves with the fixed
454 * point; the constants are the reference's fitted ones.
455 */
456template <class T>
457std::vector<T> suri_factor(const qn::NetworkStruct<T>& L, const Matrix<T>& Uin, double tol) {
458 const std::size_t M = L.nstations, K = Uin.cols();
459 const T one = num_traits<T>::from_int(1), zero = num_traits<T>::from_int(0);
460 std::vector<T> f(M, one);
461 if constexpr (!num_traits<T>::has_transcendental) {
462 throw UnsupportedError(ErrorKind{"Arithmetic"},
463 "solver_amvald: the Suri multiserver factor is a real power of the utilization, "
464 "which exact arithmetic has no representation for; use the double or real backend");
465 } else {
466 const double alpha = 4.464, beta = 0.676;
467 for (std::size_t i = 0; i < M; ++i) {
468 const double c = L.stations[i].nservers;
469 if (std::isinf(c) || c == 0.0) {
470 f[i] = zero;
471 continue;
472 }
473 if (!(c > 1.0)) continue; // single server: the factor stays 1
474 T usum = zero;
475 for (std::size_t s = 0; s < K; ++s) usum += Uin(i, s);
476 double rho = num_traits<T>::to_double(usum) / c;
477 if (rho > 1.0 - tol) rho = 1.0 - tol;
478 f[i] = rho > 0.0 ? num_traits<T>::from_double(
479 std::pow(rho, alpha * (std::pow(c, beta) - 1.0)) / c)
480 : T(one / num_traits<T>::from_double(c));
481 }
482 return f;
483 }
484}
485
486} // namespace detail
487
488/**
489 * Port of solver_amvald.m together with solver_amvald_forward.m, restricted to
490 * the INF / PS / FCFS-family disciplines with no load or class dependence.
491 */
492template <class T>
494 const MvaOptions& opt, const std::string& method, bool& converged,
495 const Matrix<T>& init_sol = Matrix<T>()) {
496 using qn::SchedStrategy;
497 // EXACT ARITHMETIC HAS NO BOUNDED ITERATE HERE, which is why this refuses
498 // rather than runs slowly. The exact product-form recursion is a fixed
499 // number of field operations and stays rational; this is a Picard fixed
500 // point, and every sweep multiplies the denominators of the one before it,
501 // so the bit length grows geometrically in the iteration count. A layer of
502 // lqn_ofbiz that solves in milliseconds under `double` was measured at over
503 // four and a half hours under `Rational`, with operands millions of bits
504 // wide and no answer -- and it only reaches here at all because the model
505 // failed the product-form gate. Refusing by name is the same rule the
506 // load-dependent soft minimum and the Suri factor follow below.
507 if constexpr (!num_traits<T>::has_transcendental) {
508 throw UnsupportedError(ErrorKind{"Arithmetic"},
509 "solver_amvald: the approximate MVA is an iterative fixed point whose iterates "
510 "accumulate the product of every denominator seen so far, so exact rational "
511 "arithmetic grows without bound and the solve does not terminate; rerun with "
512 "--arith double or --arith real, or give the model a product form (BCMP type 1 "
513 "asks FCFS service to be exponential) so the exact recursion applies");
514 }
515 const T zero = num_traits<T>::from_int(0);
516 const T one = num_traits<T>::from_int(1);
517 const std::size_t M = L.nstations, K = L.nchains;
518
519 for (std::size_t i = 0; i < M; ++i) {
520 const SchedStrategy s = L.stations[i].sched;
521 if (!(s == SchedStrategy::INF || s == SchedStrategy::PS || s == SchedStrategy::FCFS ||
522 s == SchedStrategy::SIRO || s == SchedStrategy::LCFSPR || s == SchedStrategy::EXT ||
523 s == SchedStrategy::DPS || s == SchedStrategy::HOL ||
524 s == SchedStrategy::FCFSPRPRIO))
525 throw UnsupportedError(ErrorKind{"SchedStrategy"}, std::string("solver_amvald: ") + lang::sched_to_text(s) +
526 " scheduling is not implemented in this port");
527 }
528 // A PURE-DELAY MODEL SELECTS NO APPROXIMATION, so the name is not asked
529 // about there. With no queueing station the arrival-instant queue length is
530 // identically zero, every AMVA scheme collapses to the same exact delay
531 // solution, and this analyzer is where `solver_amva` sends that model
532 // BECAUSE the product-form kernels would be handed a zero-row demand matrix
533 // (solver_amva.m says so in as many words). Asking the whitelist first
534 // refused twelve names -- ab, schmidt, schmidt-ext, scat, lcp, chow, pamb,
535 // pami, pamt, clust, dmlin and qsa -- on a model that needs no arm for any
536 // of them, while the report went on offering all twelve.
537 bool any_queue = false;
538 for (std::size_t i = 0; i < M && !any_queue; ++i)
539 if (L.stations[i].sched != SchedStrategy::INF && L.stations[i].sched != SchedStrategy::EXT)
540 any_queue = true;
541 const bool linmethod = (method == "lin" || method == "qdlin");
542 if (any_queue &&
543 !(linmethod || method == "qd" || method == "default" || method == "bs" ||
544 method == "egflin" || method == "gflin" || method == "qli" || method == "fli" ||
545 method == "aql" || method == "qdaql" || method == "tay" || method == "priomva"))
546 throw UnsupportedError(ErrorKind{"Method"}, "solver_amvald: method '" + method + "' is not implemented");
547
548 // Nt closed-population-only rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
549 double Nt = 0.0;
550 for (std::size_t c = 0; c < K; ++c)
551 if (std::isfinite(d.Nchain[c])) Nt += d.Nchain[c];
552 const T deltaT = Nt > 0.0 ? num_traits<T>::from_double((Nt - 1.0) / Nt) : one;
553 // deltaclass open-chain rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
554 std::vector<T> deltaclass(K, one);
555 for (std::size_t c = 0; c < K; ++c)
556 if (std::isfinite(d.Nchain[c]) && d.Nchain[c] > 0.0)
557 deltaclass[c] = num_traits<T>::from_double((d.Nchain[c] - 1.0) / d.Nchain[c]);
558
559 // nnz/ccl/ocl rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
560 std::vector<std::size_t> nnz, ccl, ocl;
561 std::vector<bool> isopen(K, false);
562 for (std::size_t c = 0; c < K; ++c) {
563 if (!(d.Nchain[c] > 0.0)) continue;
564 nnz.push_back(c);
565 if (std::isfinite(d.Nchain[c])) ccl.push_back(c);
566 else { ocl.push_back(c); isopen[c] = true; }
567 }
568
569 // Split the open chains into the EXOGENOUS ones and the fork-join auxiliary
570 // ones; only the former are open in the sense the arrival theorem means. A
571 // chain is auxiliary when EVERY class in it is an MMT auxiliary class: the
572 // transform gives the auxiliaries a chain of their own, and a chain mixing
573 // the two would carry real exogenous traffic that must not be deflated.
574 // `fjauxclass` is empty on every model the user actually wrote, and ocl_exo
575 // is then ocl exactly as before.
576 std::vector<std::size_t> ocl_exo, ocl_aux;
577 for (std::size_t c : ocl) {
578 bool allaux = false;
579 if (!L.fjauxclass.empty() && c < L.inchain.size()) {
580 allaux = !L.inchain[c].empty();
581 for (std::size_t r : L.inchain[c])
582 if (r >= L.fjauxclass.size() || !L.fjauxclass[r]) { allaux = false; break; }
583 }
584 if (allaux) ocl_aux.push_back(c); else ocl_exo.push_back(c);
585 }
586
587 // warm-start-under-outer-fixed-point rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
588 Matrix<T> Qchain(M, K, zero);
589 if (init_sol.rows() == M && init_sol.cols() == K) {
590 Qchain = init_sol;
591 } else {
592 // open-chain warm-start zeroing rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
593 for (std::size_t c = 0; c < K; ++c) {
594 if (!std::isfinite(d.Nchain[c])) continue;
595 for (std::size_t i = 0; i < M; ++i)
596 Qchain(i, c) =
598 }
599 }
600
601 std::vector<T> Xchain(K, zero);
602 for (std::size_t c = 0; c < K; ++c) {
603 if (isopen[c]) {
604 // open-chain arrival-rate rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
605 const T st = d.STchain(d.refstatchain[c] - 1, c);
606 Xchain[c] = st > zero ? T(one / st) : zero;
607 continue;
608 }
609 T s = zero;
610 for (std::size_t i = 0; i < M; ++i) s += d.STchain(i, c);
611 if (s != zero) Xchain[c] = T(one / s);
612 }
613 Matrix<T> Uchain(M, K, zero), Tchain(M, K, zero), Wchain(M, K, zero), STeff = d.STchain;
614 for (std::size_t i = 0; i < M; ++i)
615 for (std::size_t c : nnz) {
616 const T u = T(d.Vchain(i, c) * d.STchain(i, c) * Xchain[c]);
617 Uchain(i, c) = std::isinf(L.stations[i].nservers)
618 ? u
619 : T(u / num_traits<T>::from_double(L.stations[i].nservers));
620 }
621
622 // gamma(s, i, r) for 'lin'; gamma(s, i) otherwise
623 std::vector<Matrix<T>> gamma(K, Matrix<T>(M, K, zero));
624
625 const T omicron = num_traits<T>::from_double(0.5);
626 int totiter = 0;
627 const int max_totiter = std::min(opt.iter_max, 10000);
628 line::util::LineConsole::loop("running the AMVA fixed point (tolerance %g)", opt.tol);
629 const int inner_cap = static_cast<int>(std::sqrt(static_cast<double>(opt.iter_max)));
630
631 // The fixed point runs over CHAINS, so a chain takes the highest priority (lowest value)
632 // of its classes; reading L.classes[c] with a chain index gave chain c class c's priority
633 std::vector<int> chainprio(K, 0);
634 for (std::size_t c = 0; c < K && c < L.inchain.size(); ++c) {
635 bool first = true;
636 for (std::size_t k1 : L.inchain[c]) {
637 const int p = L.classes[k1 - 1].prio;
638 chainprio[c] = first ? p : std::min(chainprio[c], p);
639 first = false;
640 }
641 }
642 // priority set rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
643 const bool has_prio = [&] {
644 int lo = 0, hi = 0;
645 bool first = true;
646 for (std::size_t c = 0; c < K; ++c) {
647 const int p = chainprio[c];
648 if (first) { lo = hi = p; first = false; }
649 lo = std::min(lo, p);
650 hi = std::max(hi, p);
651 }
652 return hi != lo;
653 }();
654 std::vector<std::vector<std::size_t>> ehprio(K), hprio(K), eprio(K), lprio(K);
655 for (std::size_t r : nnz) {
656 if (!has_prio) {
657 // every class ties, so HOL degenerates to FCFS: all classes are equal-or-higher
658 for (std::size_t s : nnz) {
659 ehprio[r].push_back(s);
660 eprio[r].push_back(s);
661 }
662 continue;
663 }
664 for (std::size_t s : nnz) {
665 const int pr = chainprio[r], ps = chainprio[s];
666 if (ps <= pr) ehprio[r].push_back(s);
667 if (ps < pr) hprio[r].push_back(s);
668 if (ps == pr) eprio[r].push_back(s);
669 if (ps > pr) lprio[r].push_back(s);
670 }
671 }
672
673 // lldscaling/cdscaling emptiness rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
674 std::size_t smax = 0;
675 for (const auto& st : L.stations) smax = std::max(smax, st.lldscaling.size());
676 Matrix<T> lldscaling;
677 if (smax > 0) {
678 lldscaling = Matrix<T>(M, smax, one);
679 for (std::size_t i = 0; i < M; ++i)
680 for (std::size_t k = 0; k < L.stations[i].lldscaling.size(); ++k)
681 lldscaling(i, k) = L.stations[i].lldscaling[k];
682 }
683 std::vector<lang::CdScaling<T>> cdscaling;
684 for (const auto& st : L.stations)
685 if (st.cdscaling) {
686 cdscaling.assign(M, lang::CdScaling<T>());
687 break;
688 }
689 if (!cdscaling.empty())
690 for (std::size_t i = 0; i < M; ++i) cdscaling[i] = L.stations[i].cdscaling;
691 // sn.jdscaling is a SEPARATE list, never folded into cdscaling: the two are
692 // evaluated at DIFFERENT points below, so a single list would lose the one
693 // piece of information that tells them apart. Assembled by the same rule --
694 // empty means "no station has one", which is what pfqn_jdfun tests.
695 std::vector<lang::CdScaling<T>> jdscaling;
696 for (const auto& st : L.stations)
697 if (st.jdscaling) {
698 jdscaling.assign(M, lang::CdScaling<T>());
699 break;
700 }
701 if (!jdscaling.empty())
702 for (std::size_t i = 0; i < M; ++i) jdscaling[i] = L.stations[i].jdscaling;
703 const bool has_scaling = (smax > 0) || !cdscaling.empty() || !jdscaling.empty();
704
705 // A station with at least as many servers as the closed jobs that can ever reach it never
706 // queues, whatever its (single-server-per-job) discipline, so the forward pass treats it
707 // as the exact delay it is. The multiserver terms err there: a 6-server FCFS station
708 // visited by 4 jobs read R = 1.177 against the exact S = 1.1085, enough to give each
709 // layer of an LQN its own chain throughput. Load-, class- and joint-dependent stations
710 // keep their own rates and are excluded. Mirrors solver_amvald.m.
711 std::vector<SchedStrategy> schedfw(M);
712 for (std::size_t i = 0; i < M; ++i) {
713 schedfw[i] = L.stations[i].sched;
714 const double cs = L.stations[i].nservers;
715 if (!std::isfinite(cs)) continue;
716 bool any = false, open = false;
717 double nvis = 0.0;
718 for (std::size_t c = 0; c < K; ++c) {
719 if (!(num_traits<T>::to_double(d.Vchain(i, c)) > 0.0 && num_traits<T>::to_double(d.STchain(i, c)) > 0.0))
720 continue;
721 any = true;
722 if (std::isfinite(d.Nchain[c])) nvis += d.Nchain[c]; else open = true;
723 }
724 if (!any || open || nvis > cs) continue;
725 const SchedStrategy s = schedfw[i];
726 if (!(s == SchedStrategy::FCFS || s == SchedStrategy::SIRO || s == SchedStrategy::LCFS ||
727 s == SchedStrategy::LCFSPR || s == SchedStrategy::PS || s == SchedStrategy::HOL ||
728 s == SchedStrategy::FCFSPRPRIO))
729 continue;
730 bool hasLD = false;
731 for (const T& v : L.stations[i].lldscaling)
732 if (num_traits<T>::to_double(v) != 1.0) { hasLD = true; break; }
733 if (!hasLD && !L.stations[i].cdscaling && !L.stations[i].jdscaling) schedfw[i] = SchedStrategy::INF;
734 }
735
736 // tau(s,r) rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
737 std::vector<std::vector<T>> tau(K, std::vector<T>(K, zero));
738 // Throughput vector the tau differences were taken against, so that Xref[r] + tau[s][r]
739 // is an arrival-instant throughput from one and the same sweep. Adding tau to the moving
740 // inner iterate instead mixes two sweeps and can exceed the service capacity. Empty when
741 // no Linearizer recursion runs, and then the inner iterate is the reference.
742 std::vector<T> Xref;
743
744 // Interlocked flow (Franks 1999, Eq. 4.7): the option carries the matrix CLASS-indexed,
745 // and the forward step below works in the chain basis.
746 const Matrix<T> ILchain = sn_interlock_chain<T>(L, opt.interlock);
747
748 // one forward evaluation: residence times from the current queue lengths
749 auto forward = [&](const Matrix<T>& Qin, const std::vector<T>& Xin, const Matrix<T>& Uin,
750 const std::vector<double>& Nc, Matrix<T>& Wout, Matrix<T>& STeffOut) {
751 double Ntl = 0.0;
752 for (std::size_t c = 0; c < K; ++c)
753 if (std::isfinite(Nc[c])) Ntl += Nc[c];
754 const T deltaL = Ntl > 0.0 ? num_traits<T>::from_double((Ntl - 1.0) / Ntl) : one;
755 std::vector<T> dcl(K, one);
756 for (std::size_t c = 0; c < K; ++c)
757 if (std::isfinite(Nc[c]) && Nc[c] > 0.0)
758 dcl[c] = num_traits<T>::from_double((Nc[c] - 1.0) / Nc[c]);
759
760 std::vector<T> interpTot(M, zero);
761 Matrix<T> selfArvl(M, K, zero), totArvl(M, K, zero), totArvlOpen(M, K, zero);
762 for (std::size_t i = 0; i < M; ++i) {
763 T s = zero;
764 for (std::size_t c : nnz) s += Qin(i, c);
765 // deltaL = (Nt-1)/Nt is the arrival theorem's CLOSED-population
766 // correction, so it may deflate only the closed classes' share. An
767 // open class has no such correction (dcl is 1 for it, and deltaL is
768 // itself 1 when every chain is open), and deflating its queue length
769 // is what makes a mixed model with Nt = 1 read deltaL = 0 -- the
770 // multiserver term then evaluates at n = 1 and a c-server station
771 // serves the open traffic as if it had ONE server, diverging once
772 // the open demand exceeds it.
773 // An MMT AUXILIARY chain is the exception and counts as CLOSED here:
774 // it is open only as a modelling device, its arrivals being the
775 // sibling tasks of a job drawn from the finite population, so the
776 // correction does apply to it.
777 T sc = zero, so = zero;
778 for (std::size_t c : ccl) sc += Qin(i, c);
779 for (std::size_t c : ocl_aux) sc += Qin(i, c);
780 for (std::size_t c : ocl_exo) so += Qin(i, c);
781 interpTot[i] = T(deltaL * sc + so);
782 const bool hol = schedfw[i] == SchedStrategy::HOL;
783 for (std::size_t c : nnz) {
784 selfArvl(i, c) = T(dcl[c] * Qin(i, c));
785 if (hol) {
786 T eh = zero, ehx = zero;
787 for (std::size_t s2 : ehprio[c]) {
788 eh += Qin(i, s2);
789 if (s2 != c) ehx += Qin(i, s2);
790 }
791 totArvlOpen(i, c) = eh;
792 totArvl(i, c) = T(dcl[c] * Qin(i, c) + ehx);
793 } else {
794 totArvlOpen(i, c) = s;
795 totArvl(i, c) = T(dcl[c] * Qin(i, c) + s - Qin(i, c));
796 }
797 }
798 }
799
800 // multiserver softmin population rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
801 std::vector<T> gmean(M, zero);
802 if (!ccl.empty()) {
803 if (linmethod) {
804 // g(s,i) = sum_r deltaL * N_r * gamma(s,i,r); then mean over s
805 const T nccl = num_traits<T>::from_int(int(ccl.size()));
806 for (std::size_t i = 0; i < M; ++i) {
807 T acc = zero;
808 for (std::size_t s : ccl) {
809 T gs = zero;
810 for (std::size_t r : ccl)
811 gs += T(num_traits<T>::from_double(Nc[r]) * gamma[s](i, r));
812 acc += T(deltaL * gs);
813 }
814 gmean[i] = T(acc / nccl);
815 }
816 } else {
817 // mean(g) scalar-collapse rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
818 T acc = zero;
819 for (std::size_t i = 0; i < M; ++i)
820 for (std::size_t r : ccl)
821 acc += T(num_traits<T>::from_double(Ntl - 1.0) * gamma[r](i, r));
822 const T sc = T(acc / num_traits<T>::from_int(int(M)));
823 for (std::size_t i = 0; i < M; ++i) gmean[i] = sc;
824 }
825 }
826 std::vector<T> narrival(M, zero);
827 for (std::size_t i = 0; i < M; ++i) narrival[i] = T(one + interpTot[i] + gmean[i]);
828 const std::vector<T> msterm = detail::ms_term(L, schedfw, narrival, opt.multiserver);
829 std::vector<T> suri(M, one);
830 if (opt.multiserver == "suri") suri = detail::suri_factor(L, Uin, opt.tol);
831
832 // The load-dependent term, per class for the Linearizer (whose
833 // correction is class specific) and shared otherwise.
834 Matrix<T> lldterm(M, K, one);
835 if (smax > 0) {
836 if constexpr (!num_traits<T>::has_transcendental) {
837 throw UnsupportedError(ErrorKind{"Arithmetic"},
838 "solver_amvald: load-dependent scaling interpolates a rate lattice with a "
839 "soft minimum, which exact arithmetic has no representation for; use the "
840 "double or real backend");
841 } else {
842 if (linmethod && !ccl.empty() && !nnz.empty()) {
843 for (std::size_t r : nnz) {
844 std::vector<T> arg(M, zero);
845 for (std::size_t i = 0; i < M; ++i) {
846 T gcorr = zero;
847 for (std::size_t s : ccl)
848 gcorr += T(num_traits<T>::from_double(Nc[s]) * gamma[r](i, s));
849 gcorr -= gamma[r](i, r);
850 arg[i] = T(one + interpTot[i] + gcorr);
851 }
852 const std::vector<T> v =
853 pfqn::pfqn_lldfun(arg, lldscaling, std::vector<double>());
854 for (std::size_t i = 0; i < M; ++i) lldterm(i, r) = v[i];
855 }
856 } else {
857 std::vector<T> arg(M, zero);
858 for (std::size_t i = 0; i < M; ++i) arg[i] = T(one + interpTot[i]);
859 const std::vector<T> v =
860 pfqn::pfqn_lldfun(arg, lldscaling, std::vector<double>());
861 for (std::size_t i = 0; i < M; ++i)
862 for (std::size_t c = 0; c < K; ++c) lldterm(i, c) = v[i];
863 }
864 }
865 }
866
867 // class-dependent term rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
868 Matrix<T> cdterm(M, K, one);
869 if (!cdscaling.empty()) {
870 for (std::size_t r : nnz) {
871 Matrix<T> arg(M, K, zero);
872 const bool closed = std::isfinite(Nc[r]);
873 for (std::size_t i = 0; i < M; ++i)
874 for (std::size_t c = 0; c < K; ++c)
875 arg(i, c) = T(one + (closed ? selfArvl(i, c) : Qin(i, c)));
876 if (closed && linmethod)
877 for (std::size_t i = 0; i < M; ++i) {
878 const T gself =
879 T(num_traits<T>::from_double(Nc[r] - 1.0) * gamma[r](i, r));
880 for (std::size_t c = 0; c < K; ++c) arg(i, c) = T(arg(i, c) + gself);
881 }
882 const std::vector<T> v = pfqn::pfqn_cdfun(arg, cdscaling, r);
883 for (std::size_t i = 0; i < M; ++i) cdterm(i, r) = v[i];
884 }
885 }
886
887 // joint-dependence term eta_i (non-product-form). It is NOT evaluated at
888 // the cdterm point: beta_{i,r} reads only its OWN marginal, so the +1
889 // cdterm puts on the non-arriving classes is inert there, while eta reads
890 // the WHOLE occupancy row and every coordinate matters. The arrival
891 // theorem gives the arriving class-r job one extra job OF ITS OWN CLASS
892 // and leaves the others at their means, so the point is
893 // eta_i(Q_{i,1}, ..., 1 + delta_r Q_{i,r}, ..., Q_{i,R}),
894 // only coordinate r shifted. Classes outside nnz stay at zero, matching
895 // the stationaryQlen of solver_amvald_forward.m rather than Qin, whose
896 // rows for an empty class are not part of that point.
897 // See _kb/06-solver-catalog.md (joint-dependence section).
898 Matrix<T> jdterm(M, K, one);
899 if (!jdscaling.empty()) {
900 for (std::size_t r : nnz) {
901 const bool closed = std::isfinite(Nc[r]);
902 Matrix<T> arg(M, K, zero);
903 for (std::size_t i = 0; i < M; ++i) {
904 for (std::size_t c : nnz) arg(i, c) = Qin(i, c);
905 T self = T(one + (closed ? selfArvl(i, r) : Qin(i, r)));
906 if (closed && linmethod)
907 self = T(self + num_traits<T>::from_double(Nc[r] - 1.0) * gamma[r](i, r));
908 arg(i, r) = self;
909 }
910 const std::vector<T> v = pfqn::pfqn_jdfun(arg, jdscaling, r);
911 for (std::size_t i = 0; i < M; ++i) jdterm(i, r) = v[i];
912 }
913 }
914
915 STeffOut = Matrix<T>(M, K, zero);
916 for (std::size_t c : nnz)
917 for (std::size_t i = 0; i < M; ++i)
918 STeffOut(i, c) =
919 T(d.STchain(i, c) * lldterm(i, c) * msterm[i] * cdterm(i, c) * jdterm(i, c));
920
921 // Wang-Sevcik queue line / fraction line: both REPLACE the arrival queue
922 // length with an interpolation that needs STeff, so they run after it.
923 if (method == "qli" || method == "fli") {
924 const bool qli = (method == "qli");
925 for (std::size_t i = 0; i < M; ++i) {
926 const bool hol = schedfw[i] == SchedStrategy::HOL;
927 for (std::size_t r : nnz) {
928 T tot = zero;
929 if (hol) {
930 for (std::size_t s2 : ehprio[r]) tot += Qin(i, s2);
931 } else {
932 for (std::size_t s2 : nnz) tot += Qin(i, s2);
933 }
934 if (Nc[r] == 1.0) {
935 totArvl(i, r) = T(tot - Qin(i, r));
936 continue;
937 }
938 const T num = T(STeffOut(i, r) * (one + tot - Qin(i, r)));
939 T den = zero;
940 for (std::size_t m = 0; m < M; ++m)
941 if (schedfw[m] == SchedStrategy::INF) den += STeffOut(m, r);
942 for (std::size_t m = 0; m < M; ++m) {
943 T totm = zero;
944 if (schedfw[m] == SchedStrategy::HOL) {
945 for (std::size_t s2 : ehprio[r]) totm += Qin(m, s2);
946 } else {
947 for (std::size_t s2 : nnz) totm += Qin(m, s2);
948 }
949 den += T(STeffOut(m, r) * (one + totm - Qin(m, r)));
950 }
951 if (den == zero) continue;
952 if (qli) {
953 const T f = T(one / num_traits<T>::from_double(Nc[r] - 1.0));
954 totArvl(i, r) = T(tot - f * (Qin(i, r) - num / den));
955 } else {
956 const T f = T(num_traits<T>::from_int(2) / num_traits<T>::from_double(Nc[r]));
957 totArvl(i, r) = T(tot - f * Qin(i, r) + num / den);
958 }
959 }
960 }
961 }
962
963 // Interlocked flow (Franks 1999, Eq. 4.7)
964 // A request cannot queue behind work that its own submission caused, so the
965 // arrival-instant queue drops the interlocked share of every other chain. The
966 // own-class term is never removed. The matrix is empty for every model but the
967 // layers of SolverLN, where it comes from the interlock path tables.
968 if (!ILchain.empty()) {
969 for (std::size_t i = 0; i < M; ++i)
970 for (std::size_t c : nnz) {
971 T ilq = zero;
972 for (std::size_t c2 : nnz)
973 if (c2 != c) ilq += ILchain(c, c2) * Qin(i, c2);
974 if (ilq > zero) {
975 T adj = T(totArvl(i, c) - ilq);
976 if (adj < selfArvl(i, c)) adj = selfArvl(i, c);
977 totArvl(i, c) = adj;
978 }
979 }
980 }
981
982 Wout = Matrix<T>(M, K, zero);
983 for (std::size_t c : nnz) {
984 for (std::size_t i = 0; i < M; ++i) {
985 const SchedStrategy sc = schedfw[i];
986 // Source residence-time rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
987 if (sc == SchedStrategy::EXT) continue;
988 if (sc == SchedStrategy::INF) {
989 Wout(i, c) = STeffOut(i, c);
990 continue;
991 }
992 const double cs = L.stations[i].nservers;
993
994 if (sc == SchedStrategy::PS) {
995 T corr = zero;
996 if (linmethod) {
997 for (std::size_t s : ccl)
998 corr += num_traits<T>::from_double(Nc[s]) * gamma[c](i, s);
999 corr -= gamma[c](i, c);
1000 } else {
1001 corr = T(num_traits<T>::from_double(Ntl - 1.0) * gamma[c](i, c));
1002 }
1003 if (opt.multiserver == "suri") {
1004 // W = S (1 + Lm * suriFactor), against the arrival-instant
1005 // queue seen by class c -- see the note below.
1006 const T Lm = isopen[c] ? totArvlOpen(i, c)
1007 : T(totArvl(i, c) + corr);
1008 Wout(i, c) = T(STeffOut(i, c) * (one + Lm * suri[i]));
1009 continue;
1010 }
1011 if (opt.multiserver == "seidmann")
1012 Wout(i, c) = T(STeffOut(i, c) * num_traits<T>::from_double(cs - 1.0));
1013 if (isopen[c]) {
1014 // PASTA no-discount rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
1015 Wout(i, c) = T(Wout(i, c) + STeffOut(i, c) * (one + totArvlOpen(i, c)));
1016 } else {
1017 // The arrival-instant queue is the one seen BY CLASS c:
1018 // interpTot is a per-station total scaled by the GLOBAL
1019 // (Ntot-1)/Ntot, so it cannot drop the arriving job's own
1020 // chain and it charges a chain for jobs that never visit
1021 // this station. totArvl(i,c) does drop it. Identical when
1022 // the model has one chain -- see _kb/06-solver-catalog.md.
1023 Wout(i, c) = T(Wout(i, c) + STeffOut(i, c) * (one + totArvl(i, c) + corr));
1024 }
1025 continue;
1026 }
1027
1028 if (sc == SchedStrategy::DPS) {
1029 // Discriminatory sharing: the arriving class waits behind
1030 // each other class in proportion to the weight ratio.
1031 const std::vector<T>& w = L.stations[i].schedparam;
1032 if (w.size() != K)
1033 throw UnsupportedError(ErrorKind{"SchedStrategy_DPS"},
1034 "solver_amvald: the DPS station '" + L.stations[i].name +
1035 "' has no per-class weights");
1036 T acc = zero;
1037 if (cs > 1.0 && std::isfinite(cs))
1038 acc = T(STeffOut(i, c) * num_traits<T>::from_double(cs - 1.0));
1039 acc += T(STeffOut(i, c) * (one + selfArvl(i, c)));
1040 for (std::size_t s : nnz) {
1041 if (s == c) continue;
1042 if (w[s] == w[c])
1043 acc += T(STeffOut(i, c) * Qin(i, s));
1044 else
1045 acc += T(STeffOut(i, c) * Qin(i, s) * w[s] / w[c]);
1046 }
1047 Wout(i, c) = acc;
1048 continue;
1049 }
1050
1051 const bool fcfs_family = (sc == SchedStrategy::FCFS || sc == SchedStrategy::SIRO ||
1052 sc == SchedStrategy::LCFSPR);
1053 if (!fcfs_family && sc != SchedStrategy::HOL && sc != SchedStrategy::FCFSPRPRIO)
1054 throw UnsupportedError(ErrorKind{"SchedStrategy"}, std::string("solver_amvald: ") + lang::sched_to_text(sc) +
1055 " scheduling is not implemented in this port");
1056 if (STeffOut(i, c) <= zero) continue;
1057
1058 const std::vector<T>& Xarv = Xref.empty() ? Xin : Xref;
1059
1060 // Preemptive-resume priority (PRIOMVA), Chandy-Lakshmi [ChaL83] applied
1061 // where it was derived: a job in service IS preempted by a higher-priority
1062 // arrival. Two terms separate this arm from the HOL path below.
1063 // (a) no non-preemptive residual -- the lower-priority job found in
1064 // service is preempted, so it delays nobody;
1065 // (b) the tagged job's OWN service is interrupted too, so it is scaled
1066 // by 1/(1-sigma_{k-1}) as well as the queued work.
1067 // Together: E[T_k] = E[S_k]/(1-sigma_{k-1}) + <queued>/(1-sigma_{k-1}).
1068 // Taken BEFORE the Bk / multiserver machinery because the reference
1069 // restricts the arm to single-server stations and refuses the rest.
1070 // Port of solver_amvald_forward.m (FCFSPRPRIO arm).
1071 if (sc == SchedStrategy::FCFSPRPRIO) {
1072 if (cs > 1.0 && std::isfinite(cs))
1073 throw UnsupportedError(ErrorKind{"MultiServer"},
1074 "solver_amvald: FCFSPRPRIO with more than one server. The "
1075 "preemptive-resume priority arm (priomva) is implemented for "
1076 "single-server stations only; use SolverCTMC or SolverSSA for "
1077 "multiserver PRS.");
1078
1079 // higher-priority utilization seen at the arrival instant
1080 T uh_prs = zero;
1081 for (std::size_t h : hprio[c])
1082 uh_prs += T(d.Vchain(i, h) * STeffOut(i, h) * T(Xarv[h] + tau[c][h]));
1083 double vps = 1.0 - num_traits<T>::to_double(uh_prs);
1084 vps = std::max(opt.tol, std::min(vps, 1.0 - opt.tol));
1085 const T ps_prs = num_traits<T>::from_double(vps);
1086
1087 // work of EQUAL OR HIGHER priority already queued ahead
1088 T queued = T(STeffOut(i, c) * (isopen[c] ? Qin(i, c) : selfArvl(i, c)));
1089 for (std::size_t s : ehprio[c])
1090 if (s != c) queued += T(STeffOut(i, s) * Qin(i, s));
1091
1092 Wout(i, c) = T((STeffOut(i, c) + queued) / ps_prs);
1093 continue;
1094 }
1095 // Uchain_r rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
1096 auto Ur = [&](std::size_t k, std::size_t s) -> T {
1097 if (!(Xin[s] > zero)) return Uin(k, s);
1098 return T(Uin(k, s) / Xin[s] * (Xarv[s] + tau[c][s]));
1099 };
1100 // softmin and suri leave STeff above S/c, so the priority utilization and residual use the per-server time
1101 const bool per_server = cs > 1.0 && std::isfinite(cs) &&
1102 (opt.multiserver == "softmin" || opt.multiserver == "suri");
1103 auto STps = [&](std::size_t s) -> T {
1104 if (!per_server) return STeffOut(i, s);
1105 return T(STeffOut(i, s) / msterm[i] / num_traits<T>::from_double(cs));
1106 };
1107 // prioScaling: the fraction of the server left by the strictly
1108 // higher-priority classes, clamped into [tol, 1-tol].
1109 auto prio_scaling = [&](std::size_t r) -> T {
1110 if (sc != SchedStrategy::HOL) return one;
1111 T uh = zero;
1112 for (std::size_t h : hprio[r]) {
1113 // shadow: Sevcik's server at the current population; cl: Eager-Lipscomb,
1114 // the utilization seen at arrival, i.e. at population N - 1_r
1115 const T xh = opt.np_priority == "shadow" ? Xarv[h] : T(Xarv[h] + tau[r][h]);
1116 uh += T(d.Vchain(i, h) * STps(h) * xh);
1117 }
1118 double v = 1.0 - num_traits<T>::to_double(uh);
1119 v = std::max(opt.tol, std::min(v, 1.0 - opt.tol));
1121 };
1122 const T ps_r = prio_scaling(c);
1123
1124 // Work of EQUAL OR HIGHER priority queued ahead of the arriving job, and the
1125 // residual of a strictly lower-priority job found in service, which HOL does not
1126 // preempt. This backlog is disjoint from the 1/ps_r inflation, which counts only
1127 // the higher-priority work that overtakes the job while it waits;
1128 // see _kb/06-solver-catalog.md
1129 auto hol_ehprio_backlog = [&](const std::vector<T>& Bkw) -> T {
1130 T acc = zero;
1131 for (std::size_t s : ehprio[c])
1132 if (s != c) acc += T(STeffOut(i, s) * Qin(i, s) * Bkw[s]);
1133 return acc;
1134 };
1135 auto hol_np_residual = [&](const std::vector<T>& Bkw) -> T {
1136 if (opt.highvar == "hvmva") return zero; // hvmva already spans every class
1137 T acc = zero;
1138 for (std::size_t s : lprio[c])
1139 acc += T(d.Vchain(i, s) * STps(s) * (Xarv[s] + tau[c][s]) * STps(s) * Bkw[s]);
1140 return acc;
1141 };
1142
1143 // Bk backlog-reduction rationale (FCFS/SIRO/LCFSPR vs HOL): see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
1144 std::vector<T> Bk(K, one);
1145 if (cs > 1.0 && std::isfinite(cs)) {
1146 // all-servers-busy is a station property, so Bk reads the TOTAL load for every class;
1147 // a per-class rho_s^(c-1) vanishes with K classes and lets the station exceed its capacity.
1148 // HOL takes the FCFS factor itself except under softmin, so all-tied priorities reproduce FCFS
1149 const bool hol_softmin = sc == SchedStrategy::HOL && opt.multiserver == "softmin";
1150 T load = zero;
1151 for (std::size_t s : nnz) {
1152 const T dr = hol_softmin ? dcl[s] : ((s == c) ? dcl[c] : one);
1153 load += dr * Xin[s] * d.Vchain(i, s) * STeffOut(i, s);
1154 }
1155 // NOT Rolia's U^c (MOL as in Franks-Woodside MASCOTS'04 eq. 5): steeper at U=1, the fixed point
1156 // stops converging on a saturated station (see _kb/06-solver-catalog.md, Bk bullet)
1157 const bool light = num_traits<T>::to_double(load) < 0.75;
1158 T base = load;
1159 if (!light) {
1160 const unsigned e = static_cast<unsigned>(std::llround(cs) - (hol_softmin ? 0 : 1));
1161 base = num_pow_int(base, e);
1162 }
1163 for (std::size_t s : nnz)
1164 Bk[s] = base;
1165 }
1166
1167 // single-server-with-scaling branch rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
1168 if (cs == 1.0) {
1169 T w = zero;
1170 if (opt.highvar == "hvmva") {
1171 T usum = zero;
1172 for (std::size_t s : ccl) usum += Ur(i, s);
1173 w = T(STeffOut(i, c) * (one - usum));
1174 for (std::size_t s : ccl)
1175 w += T(STeffOut(i, s) / prio_scaling(s) * Ur(i, s) *
1176 (one + d.SCVchain(i, s)) / num_traits<T>::from_int(2));
1177 } else if (opt.highvar != "default") {
1178 throw UnsupportedError(ErrorKind{"Option"}, "solver_amvald: highvar '" + opt.highvar +
1179 "' is not implemented");
1180 } else {
1181 w = STeffOut(i, c);
1182 }
1183 if (sc == SchedStrategy::HOL) {
1184 // priority-branch charging rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
1185 const std::vector<T> ones(K, one);
1186 w += T((STeffOut(i, c) * (isopen[c] ? Qin(i, c) : selfArvl(i, c)) +
1187 hol_ehprio_backlog(ones) + hol_np_residual(ones)) / ps_r);
1188 } else {
1189 w += STeffOut(i, c) * (isopen[c] ? Qin(i, c) : selfArvl(i, c));
1190 for (std::size_t s : nnz)
1191 if (s != c) w += STeffOut(i, s) * Qin(i, s);
1192 }
1193 Wout(i, c) = w;
1194 continue;
1195 }
1196
1197 // Multiserver.
1198 if (opt.multiserver == "suri") {
1199 T Lm = isopen[c] ? T(deltaclass[c] * Qin(i, c)) : selfArvl(i, c);
1200 if (sc != SchedStrategy::HOL)
1201 for (std::size_t s : nnz)
1202 if (s != c) Lm += Qin(i, s);
1203 if (sc == SchedStrategy::HOL) {
1204 Lm = isopen[c] ? Qin(i, c) : selfArvl(i, c);
1205 const std::vector<T> ones(K, one);
1206 Wout(i, c) = T(STeffOut(i, c) +
1207 ((STeffOut(i, c) * Lm + hol_ehprio_backlog(ones)) * suri[i] +
1208 hol_np_residual(ones)) / ps_r);
1209 continue;
1210 }
1211 Wout(i, c) = T(STeffOut(i, c) / ps_r + STeffOut(i, c) * Lm * suri[i] / ps_r);
1212 continue;
1213 }
1214 if (opt.multiserver == "softmin") {
1215 // The own service is the full S (STeff/msterm). At HOL only the backlog sees softmin(n, c), discounted by Bk.
1216 // At FCFS, of the nB jobs found softmin(n,c)-1 hold other servers, so (nB+1-softmin)/nB of the backlog
1217 // queues; with one class this is S(1+nB)/softmin(n,c)
1218 if (sc == SchedStrategy::HOL) {
1219 Wout(i, c) = T(STps(c) * num_traits<T>::from_double(cs) +
1220 (STeffOut(i, c) * (isopen[c] ? Qin(i, c) : selfArvl(i, c)) * Bk[c] +
1221 hol_ehprio_backlog(Bk) + hol_np_residual(Bk)) / ps_r);
1222 continue;
1223 }
1224 const T selfQ = isopen[c] ? Qin(i, c) : selfArvl(i, c);
1225 T nB = selfQ;
1226 T wq = T(STeffOut(i, c) * selfQ);
1227 for (std::size_t s : nnz)
1228 if (s != c) {
1229 nB += Qin(i, s);
1230 wq += T(STeffOut(i, s) * Qin(i, s));
1231 }
1232 T w = T(STeffOut(i, c) / msterm[i]);
1233 if (nB > zero) {
1234 T qfrac = T(nB + one - one / msterm[i]);
1235 if (qfrac < zero) qfrac = zero;
1236 w += T(wq * qfrac / nB);
1237 }
1238 Wout(i, c) = w;
1239 continue;
1240 }
1241 // default / seidmann
1242 T w = T(STeffOut(i, c) * num_traits<T>::from_double(cs - 1.0));
1243 w += STeffOut(i, c);
1244 if (sc == SchedStrategy::HOL) {
1245 w += T((STeffOut(i, c) * (isopen[c] ? Qin(i, c) : selfArvl(i, c)) * Bk[c] +
1246 hol_ehprio_backlog(Bk) + hol_np_residual(Bk)) / ps_r);
1247 } else {
1248 w += STeffOut(i, c) *
1249 (isopen[c] ? T(deltaclass[c] * Qin(i, c)) : selfArvl(i, c)) * Bk[c];
1250 for (std::size_t s : nnz)
1251 if (s != c) w += STeffOut(i, s) * Bk[s] * Qin(i, s);
1252 }
1253 Wout(i, c) = w;
1254 }
1255 }
1256 };
1257
1258 // one inner fixed point at a given population vector
1259 auto inner_loop = [&](Matrix<T>& Q, std::vector<T>& X, Matrix<T>& U,
1260 const std::vector<double>& Nc, Matrix<T>& Wout, Matrix<T>& STeffOut) {
1261 int iter = 0;
1262 Matrix<T> Qprev = Q;
1263 while (true) {
1264 Qprev = Q;
1265 const std::vector<T> Xprev = X;
1266 const Matrix<T> Uprev = U;
1267 ++iter;
1268 forward(Qprev, Xprev, Uprev, Nc, Wout, STeffOut);
1269 ++totiter;
1271 double resid = 0.0;
1272 for (std::size_t i = 0; i < Q.rows(); ++i)
1273 for (std::size_t c = 0; c < Q.cols(); ++c)
1274 resid = std::max(resid, std::abs(num_traits<T>::to_double(Q(i, c)) -
1275 num_traits<T>::to_double(Qprev(i, c))));
1277 "AMVA sweep %d: queue-length residual %.3e",
1278 totiter, resid);
1279 }
1280 if (totiter >= max_totiter) break;
1281 // wall-clock budget (options.timeout): the sweep just taken is the
1282 // interim solution, as MATLAB's ~lineTimeoutExceeded loop guard
1283 if (line::util::timeout_exceeded()) break;
1284 for (std::size_t c : nnz) {
1285 T sw = zero;
1286 for (std::size_t i = 0; i < M; ++i) sw += Wout(i, c);
1287 if (sw == zero) {
1288 X[c] = zero;
1289 } else if (!isopen[c]) {
1290 T cyc = zero;
1291 for (std::size_t i = 0; i < M; ++i) cyc += d.Vchain(i, c) * Wout(i, c);
1292 if (cyc != zero)
1293 X[c] = T(omicron * num_traits<T>::from_double(Nc[c]) / cyc +
1294 (one - omicron) * Xprev[c]);
1295 }
1296 // an open chain's X is its arrival rate and stays put; only its
1297 // queue lengths and utilizations follow from the residence times
1298 for (std::size_t i = 0; i < M; ++i) {
1299 Q(i, c) = T(omicron * X[c] * d.Vchain(i, c) * Wout(i, c) +
1300 (one - omicron) * Qprev(i, c));
1301 U(i, c) = T(omicron * d.Vchain(i, c) * STeffOut(i, c) * X[c] +
1302 (one - omicron) * Uprev(i, c));
1303 }
1304 }
1305 if (iter >= 2) {
1306 double err = 0.0;
1307 for (std::size_t i = 0; i < M; ++i)
1308 for (std::size_t c = 0; c < K; ++c)
1309 err = std::max(err, std::fabs(num_traits<T>::to_double(Q(i, c) - Qprev(i, c))));
1310 if (err <= opt.iter_tol) break;
1311 }
1312 if (iter > inner_cap) break;
1313 }
1314 return Qprev;
1315 };
1316
1317 Matrix<T> QouterPrev = Qchain;
1318 int outer = 0;
1319 converged = false;
1320 while (true) {
1321 ++outer;
1322 QouterPrev = Qchain;
1323 const std::vector<T> XouterPrev = Xchain;
1324 // baseline the tau differences below are taken against; empty when no recursion runs
1325 if (linmethod) Xref = XouterPrev;
1326
1327 // Linearizer correction: solve at each reduced population N - e_s
1328 if (linmethod && std::isfinite(Nt) && Nt > 0.0) {
1329 for (std::size_t s = 0; s < K; ++s) {
1330 if (!std::isfinite(d.Nchain[s])) continue;
1331 std::vector<double> Ns = d.Nchain;
1332 Ns[s] -= 1.0;
1333 const T shrink = num_traits<T>::from_double((Nt - 1.0) / Nt);
1334 Matrix<T> Qs = Qchain;
1335 std::vector<T> Xs = Xchain;
1336 Matrix<T> Us = Uchain;
1337 for (std::size_t i = 0; i < M; ++i)
1338 for (std::size_t c = 0; c < K; ++c) {
1339 Qs(i, c) = T(Qs(i, c) * shrink);
1340 Us(i, c) = T(Us(i, c) * shrink);
1341 }
1342 for (std::size_t c = 0; c < K; ++c) Xs[c] = T(Xs[c] * shrink);
1343 Matrix<T> Ws, STs;
1344 const std::vector<T> Xs_in = Xs;
1345 const Matrix<T> Qs_prev = inner_loop(Qs, Xs, Us, Ns, Ws, STs);
1346 // tau(s,r) rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
1347 for (std::size_t c : nnz) tau[s][c] = T(Xs[c] - XouterPrev[c]);
1348 (void)Xs_in;
1349 // ONLY 'lin' TAKES THE PER-CLASS CORRECTION. 'qdlin' takes the
1350 // class-AGGREGATE one and stores it in column 0, leaving the
1351 // rest of the row zero, which is what the reference does:
1352 // solver_amvald.m allocates the (K,M,K) per-class array for
1353 // qdlin but writes `gamma(s,k) = sum_r Q_s(k,r)/(Nt-1) -
1354 // sum_r Q(k,r)/Nt` into it with two subscripts, and MATLAB
1355 // linear-indexes that to (s,k,1). Every reader below still
1356 // indexes gamma PER CLASS, so the correction that reaches the
1357 // residence time is N_0*gamma(r,i,0) - [r==0]*gamma(r,i,0). It
1358 // coincides with the queue-dependent AMVA form (Nt-1)*gamma_agg
1359 // iff K = 1, so a single-chain model is unaffected and lin and
1360 // qdlin stay bit-identical there. This port filled it per class
1361 // for both methods until 2026-09-04, which made C++ qdlin an
1362 // alias of C++ lin and put it at odds with MATLAB, the JAR and
1363 // native Python on every multichain model. Do not "restore" it
1364 // without re-baselining the AMVA goldens in all four codebases;
1365 // see _kb/06-solver-catalog.md.
1366 if (method == "qdlin") {
1367 for (std::size_t i = 0; i < M; ++i) {
1368 T qs = zero, qo = zero;
1369 for (std::size_t c = 0; c < K; ++c) {
1370 qs += Qs_prev(i, c);
1371 qo += QouterPrev(i, c);
1372 }
1373 // Nt = 1 leaves the reduced population empty and the
1374 // reference divides by zero there; native Python guards
1375 // it with a zero and this port follows Python.
1376 gamma[s](i, 0) =
1377 (Nt > 1.0) ? T(qs / num_traits<T>::from_double(Nt - 1.0) -
1379 : zero;
1380 }
1381 } else {
1382 for (std::size_t i = 0; i < M; ++i)
1383 for (std::size_t c : nnz)
1384 if (std::isfinite(d.Nchain[c]) && Ns[c] > 0.0)
1385 gamma[s](i, c) =
1386 T(Qs_prev(i, c) / num_traits<T>::from_double(Ns[c]) -
1387 QouterPrev(i, c) / num_traits<T>::from_double(d.Nchain[c]));
1388 }
1389 if (totiter >= max_totiter || line::util::timeout_exceeded()) break;
1390 }
1391 }
1392 if (totiter >= max_totiter) break;
1393
1394 Matrix<T> Wtmp, STtmp;
1395 const Matrix<T> Qprev = inner_loop(Qchain, Xchain, Uchain, d.Nchain, Wtmp, STtmp);
1396 Wchain = Wtmp;
1397 STeff = STtmp;
1398
1399 double err = 0.0;
1400 for (std::size_t i = 0; i < M; ++i)
1401 for (std::size_t c = 0; c < K; ++c)
1402 err = std::max(err, std::fabs(num_traits<T>::to_double(Qchain(i, c) - QouterPrev(i, c))));
1403 converged = err <= opt.iter_tol;
1404 if (outer >= 2 && converged) break;
1405 if (outer >= inner_cap || totiter > max_totiter) break;
1406 if (line::util::timeout_exceeded()) break;
1407 }
1408
1409 for (std::size_t i = 0; i < M; ++i)
1410 for (std::size_t c = 0; c < K; ++c) Tchain(i, c) = T(Xchain[c] * d.Vchain(i, c));
1411
1412 // renormalise utilizations past one, as the reference does
1413 for (std::size_t i = 0; i < M; ++i) {
1414 const SchedStrategy sc = L.stations[i].sched;
1415 if (!(sc == SchedStrategy::FCFS || sc == SchedStrategy::SIRO || sc == SchedStrategy::PS ||
1416 sc == SchedStrategy::LCFSPR || sc == SchedStrategy::DPS || sc == SchedStrategy::HOL))
1417 continue;
1418 T usum = zero;
1419 for (std::size_t c = 0; c < K; ++c) usum += Uchain(i, c);
1420 if (num_traits<T>::to_double(usum) <= 1.0) continue;
1421 T den = zero;
1422 for (std::size_t c = 0; c < K; ++c) den += d.Vchain(i, c) * STeff(i, c) * Xchain[c];
1423 if (den == zero) continue;
1424 for (std::size_t c = 0; c < K; ++c) {
1425 if (!(d.Vchain(i, c) * STeff(i, c) > zero)) continue;
1426 Uchain(i, c) = T(one * d.Vchain(i, c) * STeff(i, c) * Xchain[c] / den);
1427 }
1428 }
1429
1430 Matrix<T> Rchain(M, K, zero);
1431 for (std::size_t i = 0; i < M; ++i)
1432 for (std::size_t c = 0; c < K; ++c)
1433 if (Tchain(i, c) != zero) Rchain(i, c) = T(Qchain(i, c) / Tchain(i, c));
1434 for (std::size_t c = 0; c < K; ++c) {
1435 if (d.Nchain[c] != 0.0) continue;
1436 Xchain[c] = zero;
1437 for (std::size_t i = 0; i < M; ++i) {
1438 Uchain(i, c) = zero;
1439 Rchain(i, c) = zero;
1440 Tchain(i, c) = zero;
1441 }
1442 }
1443
1444 // THE CHAIN UTILIZATION MUST TRAVEL when a rate dependence is declared.
1445 // `sn_deaggregate_chain_results` recomputes U = T*S from the NOMINAL service
1446 // time when it is handed an empty Uchain, which throws away the lld, cd and
1447 // jd terms `STeff` carries: this call passed Matrix<T>() unconditionally
1448 // until 2026-09-13, so an open station with alpha = beta = eta = 0.8 reported
1449 // Util 0.500000 where MATLAB, the JAR and python report 0.625000, while its
1450 // queue length carried the scaling. U and Q then described different service
1451 // rates on one station (solver_amvald.m:260-264).
1452 bool declares_dependence = false;
1453 for (const auto& st : L.stations)
1454 if (!st.lldscaling.empty() || st.cdscaling || st.jdscaling) declares_dependence = true;
1456 L, d, Matrix<T>(), declares_dependence ? Uchain : Matrix<T>(), Rchain, Tchain, Xchain);
1457 MvaSolution<T> out;
1458 out.Q = cr.Q;
1459 out.U = cr.U;
1460 out.R = cr.R;
1461 out.Tp = cr.Tp;
1462 out.C = cr.C;
1463 out.X = cr.X;
1464
1465 // A station with limited class or joint dependence reports utilization as
1466 // T*S/peak from the declared peak rate scaling, matching the T*S/c
1467 // convention of an ordinary multiserver station (solver_amvald.m:255-291).
1468 //
1469 // THE PEAK IS A MODEL INPUT, NOT A DEFAULT. Without it this pass has no
1470 // normalizer, and returning the unnormalized column -- or, as it did before,
1471 // a column of zeros -- is worse than refusing: both read as a utilization.
1472 // SolverCTMC, solver_nc_conv and both SSA engines already refuse it by name
1473 // here, and MATLAB's getLimitedClassDependencePeak.m refuses it in the
1474 // model. This check sits ahead of the closed-model guard below because a
1475 // missing peak is a defect whether or not the pass would have run.
1476 for (std::size_t ist = 0; ist < M; ++ist) {
1477 if (L.stations[ist].cdscaling && L.stations[ist].cdscalingpeak.empty())
1478 throw InputError(
1479 "SolverMVA: station '" + L.stations[ist].name +
1480 "' declares class-dependent service without a peak rate. Utilization at a "
1481 "class-dependent station is reported as T*S/peak, so pass the peak to "
1482 "setClassDependence");
1483 if (L.stations[ist].jdscaling && L.stations[ist].jdscalingpeak.empty())
1484 throw InputError(
1485 "SolverMVA: station '" + L.stations[ist].name +
1486 "' declares joint-dependent service without a peak rate; pass the peak to "
1487 "setJointDependence");
1488 }
1489 bool anyOpen = false;
1490 for (const auto& c : L.classes)
1491 if (std::isinf(c.population)) anyOpen = true;
1492 if (!anyOpen) {
1493 const std::size_t Kcls = L.nclasses;
1494 for (std::size_t ist = 0; ist < M; ++ist) {
1495 const std::vector<T>* peak = nullptr;
1496 if (L.stations[ist].cdscaling)
1497 peak = &L.stations[ist].cdscalingpeak;
1498 else if (L.stations[ist].jdscaling)
1499 peak = &L.stations[ist].jdscalingpeak;
1500 if (peak == nullptr) continue;
1501 for (std::size_t k = 0; k < Kcls; ++k) {
1502 const double rate = num_traits<T>::to_double(L.rates(ist, k));
1503 const T bmax = k < peak->size() ? (*peak)[k] : zero;
1504 if (std::isfinite(rate) && rate > 0.0 && bmax > zero)
1505 out.U(ist, k) = T(out.Tp(ist, k) / L.rates(ist, k) / bmax);
1506 else
1507 out.U(ist, k) = zero;
1508 }
1509 }
1510 }
1511 out.method = method;
1512 out.iter = totiter;
1513 // through DETAIL, not STEP: SolverLN runs this analyzer once per layer per
1514 // iteration, inside its own run, so a step line here repeats hundreds of
1515 // times; detail() collapses repeats of the same shape
1516 {
1517 char buf[96];
1518 std::snprintf(buf, sizeof(buf), "AMVA finished after %d sweeps", totiter);
1519 line::util::LineConsole::detail(buf);
1520 }
1521 return out;
1522}
1523
1524// ---------------------------------------------------------------------------
1525// solver_amva: method resolution and the product-form fast paths
1526// ---------------------------------------------------------------------------
1527
1528/**
1529 * The @c amva.* spellings of solver_amva.m, mapped onto the bare method names.
1530 *
1531 * The reference accepts both, and a model or a test may use either, so the
1532 * alias table is part of the interface rather than a convenience: an
1533 * unrecognised name must reach the method switch and be refused there by its
1534 * own name, not silently resolved to `default`.
1535 */
1536inline std::string amva_method_alias(const std::string& m) {
1537 if (m == "amva.qli") return "qli";
1538 if (m == "amva.qd" || m == "amva.qdamva" || m == "qdamva") return "qd";
1539 if (m == "amva.aql") return "aql";
1540 if (m == "amva.qsa") return "qsa";
1541 if (m == "amva.qdaql") return "qdaql";
1542 if (m == "amva.tay") return "tay";
1543 if (m == "amva.scat") return "scat";
1544 if (m == "amva.lin") return "lin";
1545 if (m == "amva.qdlin") return "qdlin";
1546 if (m == "amva.fli") return "fli";
1547 if (m == "amva.bs") return "bs";
1548 if (m == "amva.ab") return "ab";
1549 if (m == "amva.schmidt") return "schmidt";
1550 if (m == "amva.schmidt-ext") return "schmidt-ext";
1551 if (m == "amva.lcp") return "lcp";
1552 if (m == "amva.chow") return "chow";
1553 if (m == "amva.pamb") return "pamb";
1554 if (m == "amva.pami") return "pami";
1555 if (m == "amva.pamt") return "pamt";
1556 if (m == "amva.clust") return "clust";
1557 if (m == "amva.dmlin") return "dmlin";
1558 if (m == "amva.priomva") return "priomva";
1559 if (m == "amva.marie") return "marie";
1560 return m;
1561}
1562
1563template <class T>
1565 const Matrix<T>& init_sol, bool& converged) {
1566 using qn::SchedStrategy;
1567 const T zero = num_traits<T>::from_int(0);
1568 const std::size_t M = L.nstations, C = L.nchains;
1569 opt.iter_max = std::min(opt.iter_max, 10000);
1570 converged = true;
1571
1572 std::string method = amva_method_alias(opt.method);
1573 if (method == "default" || method == "amva") {
1574 double Nsum = 0.0;
1575 bool anysmall = false;
1576 for (std::size_t c = 0; c < C; ++c) {
1577 Nsum += d.Nchain[c];
1578 if (d.Nchain[c] < 1.0) anysmall = true;
1579 }
1580 if (Nsum <= 2.0 || anysmall) {
1581 method = "qd";
1582 } else {
1583 bool anyfinite = false, allone = true;
1584 for (const auto& s : L.stations)
1585 if (std::isfinite(s.nservers)) {
1586 anyfinite = true;
1587 if (s.nservers != 1.0) allone = false;
1588 }
1589 // empty finite-server max rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
1590 method = (anyfinite && allone) ? "egflin" : "lin";
1591 }
1592 }
1593
1594 // The closed-population AMVA family (Bard-Schweitzer, SQNI, Tay, SCAT, AQL, QSA,
1595 // Bard LCP, JMT Chow, Hsieh-Lam PAM, clustering, Improved Linearizer,
1596 // Akyildiz-Bolch, Schmidt) lives ONLY in the product-form branch below. The same
1597 // predicate the report gates on decides here, so a name the report offers is a
1598 // name that runs and a name it withholds errors rather than falling through to
1599 // solver_amvald and returning the qd-family answer under a method the caller did
1600 // not ask for.
1601 {
1602 const std::string amva_reason = mva_closed_population_reason(L, method);
1603 if (!amva_reason.empty()) throw UnsupportedError(ErrorKind{"Model"}, amva_reason);
1604 }
1605
1606 // MATLAB's "trivial models" early exit tests sn_has_homogeneous_scheduling,
1607 // true when every station is a delay; see the note on that predicate.
1608 if (L.has_homogeneous_scheduling(SchedStrategy::INF)) {
1609 MvaOptions o2 = opt;
1610 o2.multiserver = "default";
1611 return solver_amvald(L, d, o2, method, converged, init_sol);
1612 }
1613
1614 // ab / schmidt / schmidt-ext ARE the class-dependent FCFS algorithms and live only in
1615 // the product-form branch below, so the het-FCFS exclusion must not divert them.
1616 const bool het_fcfs_own =
1617 (method == "ab" || method == "schmidt" || method == "schmidt-ext");
1618 const bool cond1 = L.has_product_form_not_het_fcfs() ||
1619 (het_fcfs_own && L.has_product_form_not_het_fcfs(false));
1620 bool cond2 = true; // ~sn_has_load_dependence: the pf kernels ignore lldscaling
1621 for (const auto& st : L.stations)
1622 if (!st.lldscaling.empty()) cond2 = false;
1623 // MATLAB keeps ONE mixed model in this branch (solver_amva.m:146): a strict
1624 // product-form network under 'lin', where pfqn_linearizermx solves the open classes
1625 // in closed form and inflates the closed demands by their utilization. Every other
1626 // open model goes to solver_amvald, the only path carrying the open corrections.
1627 const bool cond3 = !L.has_open_classes() || (L.has_product_form() && method == "lin");
1628 if (!(cond1 && cond2 && cond3)) return solver_amvald(L, d, opt, method, converged, init_sol);
1629
1630 // Interlocked flow (Franks 1999, Eq. 4.7): only solver_amvald carries the correction, so
1631 // an interlocked model goes there rather than to the product-form kernels below, which
1632 // have no interlock term and would drop it silently. Mirrors solver_amva.m and the JAR.
1633 if (!sn_interlock_chain<T>(L, opt.interlock).empty())
1634 return solver_amvald(L, d, opt, method, converged, init_sol);
1635
1637 if (pf.queue_stations.empty()) return solver_amvald(L, d, opt, method, converged, init_sol);
1638
1639 const std::size_t nq = pf.queue_stations.size(), nz = pf.delay_stations.size();
1640 // An open chain has no population: it takes pfqn's kOpenClass sentinel, which stands
1641 // in for MATLAB's Inf, and llround(Inf) is undefined behaviour rather than a marker.
1642 std::vector<int> N(C, 0);
1643 for (std::size_t c = 0; c < C; ++c)
1644 N[c] = std::isfinite(d.Nchain[c]) ? static_cast<int>(std::llround(d.Nchain[c]))
1646 // Nt is read only by the closed-only kernels, which no open model reaches, and an
1647 // exact field has no value for from_double(Inf); an open chain is left at zero.
1648 std::vector<T> Nt(C, zero);
1649 for (std::size_t c = 0; c < C; ++c)
1650 if (std::isfinite(d.Nchain[c])) Nt[c] = num_traits<T>::from_double(d.Nchain[c]);
1651
1652 // The scheduling of the queueing stations, in the api layer's enum.
1653 std::vector<pfqn::SchedStrategy> types;
1654 for (std::size_t a = 0; a < nq; ++a) {
1655 switch (L.stations[pf.queue_stations[a] - 1].sched) {
1656 case SchedStrategy::PS: types.push_back(pfqn::SchedStrategy::PS); break;
1657 case SchedStrategy::INF: types.push_back(pfqn::SchedStrategy::INF); break;
1658 default: types.push_back(pfqn::SchedStrategy::FCFS); break;
1659 }
1660 }
1661
1662 // Warm start, aligned to the queueing-station rows; a malformed seed is
1663 // dropped rather than repaired, as the reference does.
1664 Matrix<T> Q0;
1665 if (init_sol.rows() == L.nstations && init_sol.cols() == C) {
1666 Q0 = Matrix<T>(nq, C, zero);
1667 bool bad = false;
1668 for (std::size_t a = 0; a < nq && !bad; ++a)
1669 for (std::size_t c = 0; c < C; ++c) {
1670 Q0(a, c) = init_sol(pf.queue_stations[a] - 1, c);
1671 if (Q0(a, c) < zero) {
1672 bad = true;
1673 break;
1674 }
1675 }
1676 if (bad) Q0 = Matrix<T>();
1677 }
1678
1679 // Seidmann-scaling exemption rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
1680 const bool direct_ms = (method == "ab" || method == "schmidt" || method == "schmidt-ext");
1681 const bool seidmann = (opt.multiserver == "default" || opt.multiserver == "seidmann");
1682
1683 Matrix<T> Dm = pf.D, Zm = pf.Z;
1684 if (!direct_ms) {
1685 if (seidmann) {
1686 // move the (c-1)/c share of each multiserver demand into the first
1687 // delay station
1688 for (std::size_t a = 0; a < nq; ++a) {
1689 const double c = pf.S[a];
1690 if (!std::isfinite(c)) continue;
1691 for (std::size_t k = 0; k < C; ++k)
1692 Dm(a, k) = T(Dm(a, k) / num_traits<T>::from_double(c));
1693 if (Zm.rows() > 0)
1694 for (std::size_t k = 0; k < C; ++k)
1695 Zm(0, k) =
1696 T(Zm(0, k) + pf.D(a, k) * num_traits<T>::from_double((c - 1.0) / c));
1697 }
1698 } else if (opt.multiserver == "softmin") {
1699 return solver_amvald(L, d, opt, method, converged, init_sol);
1700 }
1701 // conway, krzesinski and erlang leave the demands alone: they carry the
1702 // multiplicity into the algorithm itself.
1703 }
1704
1705 // Think time per class, which is what the single-server api routines take.
1706 std::vector<T> Zsum(C, zero);
1707 for (std::size_t c = 0; c < C; ++c)
1708 for (std::size_t a = 0; a < Zm.rows(); ++a) Zsum[c] += Zm(a, c);
1709
1710 bool allone = true, anyinf = false;
1711 for (double s : pf.S) {
1712 if (!std::isfinite(s)) anyinf = true;
1713 else if (s != 1.0) allone = false;
1714 }
1715
1716 // The per-method solve fills these, over the QUEUEING stations only.
1717 Matrix<T> Qq(nq, C, zero), Uq(nq, C, zero), Qz(nz, C, zero);
1718 std::vector<T> X(C, zero);
1719 int iters = 0;
1720 bool have_delay_rows = false; // set by the methods that solve the delays too
1721
1722 if (method == "sqni") {
1723 // square-root approximation gate rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
1724 if (!(M == 2 && nq == 1 && nz == 1))
1725 throw UnsupportedError(ErrorKind{"Topology"},
1726 "solver_amva: method 'sqni' applies only to a model of one queueing station and "
1727 "one infinite server");
1728 if constexpr (!num_traits<T>::has_transcendental) {
1729 throw UnsupportedError(ErrorKind{"Arithmetic"},
1730 "solver_amva: method 'sqni' solves a quadratic and evaluates a square root, "
1731 "which exact arithmetic has no representation for; use the double or real "
1732 "backend");
1733 } else {
1734 std::vector<T> Lv(C, zero);
1735 for (std::size_t c = 0; c < C; ++c) Lv[c] = Dm(0, c);
1736 const pfqn::SqniResult<T> r = pfqn::pfqn_sqni(Nt, Lv, Zsum);
1737 for (std::size_t c = 0; c < C; ++c) {
1738 Qq(0, c) = r.Q[c];
1739 Uq(0, c) = r.U[c];
1740 X[c] = r.X[c];
1741 }
1742 iters = 1;
1743 }
1744 } else if (method == "bs") {
1745 std::vector<pfqn::AmvaSched> bstype;
1746 for (std::size_t a = 0; a < nq; ++a)
1747 bstype.push_back(L.stations[pf.queue_stations[a] - 1].sched == SchedStrategy::PS
1750 const pfqn::AmvaResult<T> r =
1751 pfqn::pfqn_bs(Dm, Nt, Zsum, bstype, opt.tol, static_cast<std::size_t>(opt.iter_max), Q0);
1752 Qq = r.QN;
1753 Uq = r.UN;
1754 X = r.XN;
1755 iters = static_cast<int>(r.iterations);
1756 } else if (method == "lcp" || method == "chow") {
1757 // Bard LCP and JMT-compatible Chow use the same full-population aggregate
1758 // queue estimate, so they take the same Seidmann treatment and scheduling
1759 // tags as 'bs'.
1760 std::vector<pfqn::AmvaSched> lctype;
1761 for (std::size_t a = 0; a < nq; ++a)
1762 lctype.push_back(L.stations[pf.queue_stations[a] - 1].sched == SchedStrategy::PS
1765 const pfqn::AmvaResult<T> r =
1766 (method == "lcp")
1767 ? pfqn::pfqn_lcp(Dm, Nt, Zsum, lctype, opt.tol,
1768 static_cast<std::size_t>(opt.iter_max), Q0)
1769 : pfqn::pfqn_chow(Dm, Nt, Zsum, lctype, opt.tol,
1770 static_cast<std::size_t>(opt.iter_max), Q0);
1771 Qq = r.QN;
1772 Uq = r.UN;
1773 X = r.XN;
1774 iters = static_cast<int>(r.iterations);
1775 } else if (method == "pamb" || method == "pami" || method == "pamt") {
1776 // Hsieh-Lam proportional approximations, noniterative
1777 const pfqn::PamVariant pv = (method == "pamb") ? pfqn::PamVariant::Basic
1778 : (method == "pami") ? pfqn::PamVariant::Improved
1780 const pfqn::AmvaResult<T> r = pfqn::pfqn_pam(Dm, Nt, Zsum, pv);
1781 Qq = r.QN;
1782 Uq = r.UN;
1783 X = r.XN;
1784 iters = 1;
1785 } else if (method == "clust") {
1786 // de Souza e Silva-Lavenberg-Muntz clustering approximation, with the
1787 // decomposition derived automatically from the PAMB utilizations.
1789 Dm, Nt, Zsum, std::vector<std::vector<std::size_t> >(),
1790 std::vector<std::vector<std::size_t> >(), pfqn::ClustInner::Linearizer, opt.tol,
1791 static_cast<std::size_t>(opt.iter_max));
1792 Qq = r.QN;
1793 Uq = r.UN;
1794 X = r.XN;
1795 iters = static_cast<int>(r.iterations);
1796 } else if (method == "dmlin") {
1797 // de Souza e Silva-Muntz Improved Linearizer: the Linearizer fixed point
1798 // with the Delta-terms pre-aggregated, so it agrees with 'lin' by
1799 // construction and only the cost differs.
1801 pfqn::pfqn_dmlin(Dm, N, Zm, types, opt.tol, opt.iter_max, Q0);
1802 Qq = r.Q;
1803 Uq = r.U;
1804 X = r.X;
1805 iters = r.totiter;
1806 } else if (method == "tay") {
1807 // Between 'bs' and 'aql', which is the reference's own branch order in
1808 // solver_amva.m. MATLAB raises here rather than approximating: the
1809 // elasticity equations are derived for single servers throughout, and
1810 // there is no multiserver correction to fall back on.
1811 if (L.has_multi_server())
1812 throw UnsupportedError(ErrorKind{"MultiServer"},
1813 "solver_amva: Tay's approximation is defined for single-server stations; use "
1814 "'default' or 'lin'");
1815 if constexpr (!num_traits<T>::has_transcendental) {
1816 throw UnsupportedError(ErrorKind{"Arithmetic"},
1817 "solver_amva: method 'tay' stops on a tolerance evaluated with transcendentals, "
1818 "which exact arithmetic has no representation for; use the double or real "
1819 "backend");
1820 } else {
1822 Dm, Nt, Zsum, opt.tol, static_cast<std::size_t>(opt.iter_max), Q0);
1823 Qq = r.QN;
1824 Uq = r.UN;
1825 X = r.XN;
1826 iters = static_cast<int>(r.iterations);
1827 }
1828 } else if (method == "scat") {
1829 // Neuse-Chandy SCAT: the Linearizer fixed point with one Delta refresh
1830 // instead of three. Unlike tay/aql/qsa this takes multiserver stations,
1831 // because they reach it already Seidmann-scaled, exactly as for 'bs'.
1833 pfqn::pfqn_scat(Dm, N, Zm, types, opt.tol, opt.iter_max, Q0);
1834 Qq = r.Q;
1835 Uq = r.U;
1836 X = r.X;
1837 iters = r.totiter;
1838 } else if (method == "aql") {
1839 // MATLAB raises here rather than approximating: the AQL recursion has
1840 // no multiserver correction at all.
1841 if (L.has_multi_server())
1842 throw UnsupportedError(ErrorKind{"MultiServer"},
1843 "solver_amva: AQL cannot handle multi-server stations; use 'default' or 'lin'");
1844 if constexpr (!num_traits<T>::has_transcendental) {
1845 throw UnsupportedError(ErrorKind{"Arithmetic"},
1846 "solver_amva: method 'aql' stops on a relative tolerance evaluated with "
1847 "transcendentals, which exact arithmetic has no representation for; use the "
1848 "double or real backend");
1849 } else {
1850 const pfqn::AmvaResult<T> r =
1851 pfqn::pfqn_aql(Dm, Nt, Zsum, opt.tol, static_cast<std::size_t>(opt.iter_max));
1852 Qq = r.QN;
1853 Uq = r.UN;
1854 X = r.XN;
1855 iters = static_cast<int>(r.iterations);
1856 }
1857 } else if (method == "qsa") {
1858 // MATLAB raises here rather than approximating: the QSA core carries an
1859 // aggregate queue length with no multiserver correction at all.
1860 if (L.has_multi_server())
1861 throw UnsupportedError(ErrorKind{"MultiServer"},
1862 "solver_amva: QSA cannot handle multi-server stations; use 'default' or 'lin'");
1863 if constexpr (!num_traits<T>::has_transcendental) {
1864 throw UnsupportedError(ErrorKind{"Arithmetic"},
1865 "solver_amva: method 'qsa' stops on a residual tolerance evaluated with "
1866 "transcendentals, which exact arithmetic has no representation for; use the "
1867 "double or real backend");
1868 } else {
1869 // Dm holds the queueing stations only, the delays already folded
1870 // into Zsum, so every row here is a queueing centre.
1872 Dm, Nt, Zsum, std::vector<pfqn::AmvaSched>(nq, pfqn::AmvaSched::PS), opt.tol,
1873 static_cast<std::size_t>(opt.iter_max));
1874 Qq = r.QN;
1875 Uq = r.UN;
1876 X = r.XN;
1877 iters = static_cast<int>(r.iterations);
1878 }
1879 } else if (direct_ms) {
1880 // The demands of the delays are stacked ON TOP of the queues, which is
1881 // the [Z0; L0] layout these three routines expect.
1882 Matrix<T> Dfull(nz + nq, C, zero), Vfull(nz + nq, C, num_traits<T>::from_int(1));
1883 std::vector<int> nsfull;
1884 std::vector<pfqn::SchedStrategy> schedfull;
1885 Matrix<int> Sfull(nz + nq, 1, 1);
1886 for (std::size_t a = 0; a < nz; ++a) {
1887 for (std::size_t c = 0; c < C; ++c) Dfull(a, c) = pf.Z(a, c);
1888 nsfull.push_back(1); // an infinite server is marked by its discipline
1889 schedfull.push_back(pfqn::SchedStrategy::INF);
1890 Sfull(a, 0) = 1;
1891 }
1892 for (std::size_t a = 0; a < nq; ++a) {
1893 for (std::size_t c = 0; c < C; ++c) {
1894 Dfull(nz + a, c) = pf.D(a, c);
1895 Vfull(nz + a, c) = d.Vchain(pf.queue_stations[a] - 1, c) > zero
1897 : zero;
1898 }
1899 const int c_i = std::isfinite(pf.S[a]) ? static_cast<int>(std::llround(pf.S[a])) : 1;
1900 nsfull.push_back(c_i);
1901 Sfull(nz + a, 0) = c_i;
1902 schedfull.push_back(types[a]);
1903 }
1904 if constexpr (!num_traits<T>::has_transcendental) {
1905 throw UnsupportedError(ErrorKind{"Arithmetic"},
1906 "solver_amva: the Akyildiz-Bolch and Schmidt multiserver methods use marginal "
1907 "weights with non-integer powers and floors, which exact arithmetic has no "
1908 "representation for; use the double or real backend");
1909 } else if (method == "ab") {
1911 Dfull, N, Vfull, nsfull, schedfull, false, pfqn::AbMarginalMethod::Ab);
1912 for (std::size_t a = 0; a < nq; ++a)
1913 for (std::size_t c = 0; c < C; ++c) {
1914 Qq(a, c) = r.QN(nz + a, c);
1915 Uq(a, c) = r.UN(nz + a, c);
1916 }
1917 for (std::size_t a = 0; a < nz; ++a)
1918 for (std::size_t c = 0; c < C; ++c) Qz(a, c) = r.QN(a, c);
1919 X = r.XN;
1920 iters = static_cast<int>(r.totiter);
1921 } else if (method == "schmidt") {
1922 const pfqn::SchmidtResult<T> r = pfqn::pfqn_schmidt(Dfull, N, Sfull, schedfull, Vfull);
1923 for (std::size_t a = 0; a < nq; ++a)
1924 for (std::size_t c = 0; c < C; ++c) Qq(a, c) = r.QN(nz + a, c);
1925 for (std::size_t a = 0; a < nz; ++a)
1926 for (std::size_t c = 0; c < C; ++c) Qz(a, c) = r.QN(a, c);
1927 X = r.XN;
1928 iters = 1;
1929 } else {
1930 // One predicate for the gate and the run, asked about the numbers THIS
1931 // arm passes: pfqn_schmidt_ext forms its alpha correction from the
1932 // network with one class-r customer tagged, and a chain holding no
1933 // customer has none to tag.
1934 {
1935 std::vector<double> sx_n(C, 0.0);
1936 for (std::size_t c = 0; c < C; ++c) sx_n[c] = d.Nchain[c];
1937 std::vector<bool> sx_fcfs;
1938 for (std::size_t a = 0; a < nq; ++a)
1939 sx_fcfs.push_back(L.stations[pf.queue_stations[a] - 1].sched ==
1940 SchedStrategy::FCFS);
1941 const std::string sx_reason =
1942 mva_schmidt_ext_reason(sx_n, sx_fcfs, "schmidt-ext");
1943 if (!sx_reason.empty()) throw UnsupportedError(ErrorKind{"Model"}, sx_reason);
1944 }
1945 const pfqn::SchmidtExtResult<T> r = pfqn::pfqn_schmidt_ext(Dfull, N, Sfull, schedfull);
1946 for (std::size_t a = 0; a < nq; ++a)
1947 for (std::size_t c = 0; c < C; ++c) Qq(a, c) = r.QN(nz + a, c);
1948 for (std::size_t a = 0; a < nz; ++a)
1949 for (std::size_t c = 0; c < C; ++c) Qz(a, c) = r.QN(a, c);
1950 X = r.XN;
1951 iters = 1;
1952 }
1953 have_delay_rows = true;
1954 // U = X D / c, which is what the reference recomputes for both Schmidt
1955 // variants rather than reading it back from the algorithm.
1956 for (std::size_t a = 0; a < nq; ++a) {
1957 const double c_i = std::isfinite(pf.S[a]) ? pf.S[a] : 1.0;
1958 for (std::size_t k = 0; k < C; ++k)
1959 Uq(a, k) = T(X[k] * pf.D(a, k) / num_traits<T>::from_double(c_i));
1960 }
1961 } else if (method == "lin" || method == "gflin" || method == "egflin") {
1962 // class- or joint-dependent models go to solver_amvald, which handles
1963 // them; the linearizer kernels do not (solver_amva.m:304-307)
1964 for (const auto& st : L.stations)
1965 if (st.cdscaling || st.jdscaling)
1966 return solver_amvald(L, d, opt, method, converged, init_sol);
1967 const pfqn::LinearizerMxMethod mx = method == "lin" ? pfqn::LinearizerMxMethod::Lin
1968 : method == "gflin" ? pfqn::LinearizerMxMethod::Gflin
1970 if (anyinf) {
1971 MvaOptions o2 = opt;
1972 if (o2.multiserver == "erlang") o2.multiserver = "default";
1973 return solver_amvald(L, d, o2, method, converged, init_sol);
1974 }
1975 if (allone || opt.multiserver == "krzesinski") {
1976 std::vector<int> ns;
1977 for (std::size_t a = 0; a < nq; ++a)
1978 ns.push_back(std::isfinite(pf.S[a]) ? static_cast<int>(std::llround(pf.S[a])) : 1);
1979 if (allone) ns.assign(nq, 1);
1981 pf.lambda, Dm, N, Zm, ns, types, opt.tol, opt.iter_max, mx, Q0);
1982 Qq = r.Q;
1983 Uq = r.U;
1984 X = r.X;
1985 iters = r.totiter;
1986 } else if (opt.multiserver == "conway") {
1987 if constexpr (!num_traits<T>::has_transcendental) {
1988 throw UnsupportedError(ErrorKind{"Arithmetic"},
1989 "solver_amva: the Conway multiserver correction evaluates transcendentals, "
1990 "which exact arithmetic has no representation for; use the double or real "
1991 "backend");
1992 } else {
1993 std::vector<int> ns;
1994 for (std::size_t a = 0; a < nq; ++a)
1995 ns.push_back(std::isfinite(pf.S[a]) ? static_cast<int>(std::llround(pf.S[a]))
1996 : 1);
1998 pfqn::pfqn_conwayms(pf.D, N, pf.Z, ns, types, opt.tol, opt.iter_max, Q0);
1999 Qq = r.Q;
2000 Uq = r.U;
2001 X = r.X;
2002 iters = r.totiter;
2003 }
2004 } else if (opt.multiserver == "default" || opt.multiserver == "softmin" ||
2005 opt.multiserver == "seidmann" || opt.multiserver == "suri" ||
2006 opt.multiserver == "erlang") {
2007 // 'erlang' names no algorithm of its own and is solved as 'default',
2008 // as solver_amva.m aliases it before calling in
2009 MvaOptions o2 = opt;
2010 if (o2.multiserver == "erlang") o2.multiserver = "default";
2011 MvaSolution<T> sol = solver_amvald(L, d, o2, method, converged, init_sol);
2012 // An unconverged amvald iterate can violate the closed populations
2013 // (het-FCFS multiserver layers oscillate); the reference then
2014 // re-solves with the Conway multiserver linearizer, which is stable
2015 // there. Population, not the flag alone, gates it: an exhausted
2016 // budget on a many-job layer is routine and leaves a feasible iterate.
2017 bool conserves = true;
2018 for (std::size_t c = 0; c < C && conserves; ++c) {
2019 const double Nc = d.Nchain[c];
2020 if (!std::isfinite(Nc) || Nc <= 0.0) continue;
2021 double qc = 0.0;
2022 for (std::size_t k : L.inchain[c])
2023 for (std::size_t i = 0; i < sol.Q.rows(); ++i) {
2024 const double v = num_traits<T>::to_double(sol.Q(i, k - 1));
2025 if (!std::isnan(v)) qc += v;
2026 }
2027 if (!std::isfinite(qc) || std::abs(qc - Nc) > 1e-3 * Nc) conserves = false;
2028 }
2029 if (converged || conserves) return sol;
2030 MvaOptions o3 = opt;
2031 o3.multiserver = "conway";
2032 bool conv2 = true;
2033 MvaSolution<T> again = solver_amva(L, d, o3, init_sol, conv2);
2034 again.iter += sol.iter;
2035 converged = conv2;
2036 return again;
2037 } else {
2038 throw UnsupportedError(ErrorKind{"Method"}, "solver_amva: unrecognized multiserver approximation '" +
2039 opt.multiserver +
2040 "'. Supported: default, softmin, seidmann, suri, conway, "
2041 "erlang, krzesinski.");
2042 }
2043 } else {
2044 // multiserver-rule reset rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
2045 MvaOptions o2 = opt;
2046 if (o2.multiserver == "conway" || o2.multiserver == "erlang" ||
2047 o2.multiserver == "krzesinski")
2048 o2.multiserver = "default";
2049 return solver_amvald(L, d, o2, method, converged, init_sol);
2050 }
2051
2052 Matrix<T> Q(M, C, zero), U(M, C, zero), Tp(M, C, zero), R(M, C, zero);
2053 for (std::size_t a = 0; a < nq; ++a)
2054 for (std::size_t c = 0; c < C; ++c) {
2055 Q(pf.queue_stations[a] - 1, c) = Qq(a, c);
2056 U(pf.queue_stations[a] - 1, c) = Uq(a, c);
2057 }
2058 // Delay stations: Q = X Z with the ORIGINAL think times, for every method.
2059 // Seidmann folds L(m-1)/m of each multiserver station into Z, but that
2060 // population is in service at the station and is given back to it just
2061 // below; charging Zm here too counted it twice and sum(Q) exceeded N.
2062 for (std::size_t a = 0; a < nz; ++a)
2063 for (std::size_t c = 0; c < C; ++c) {
2064 Q(pf.delay_stations[a] - 1, c) = T(X[c] * pf.Z(a, c));
2065 U(pf.delay_stations[a] - 1, c) = Q(pf.delay_stations[a] - 1, c);
2066 }
2067 (void)have_delay_rows; // the reference overwrites the solved delay rows too
2068 // Un-apply Seidmann back onto the originating queue. ab and schmidt never
2069 // had it applied, so they are exempt, which is what the reference tests.
2070 if (seidmann && !direct_ms) {
2071 for (std::size_t a = 0; a < nq; ++a) {
2072 const double c = pf.S[a];
2073 if (!std::isfinite(c) || c <= 1.0) continue;
2074 for (std::size_t k = 0; k < C; ++k)
2075 Q(pf.queue_stations[a] - 1, k) =
2076 T(Q(pf.queue_stations[a] - 1, k) +
2077 pf.D(a, k) * num_traits<T>::from_double((c - 1.0) / c) * X[k]);
2078 }
2079 }
2080 for (std::size_t i = 0; i < M; ++i)
2081 for (std::size_t c = 0; c < C; ++c) {
2082 Tp(i, c) = T(d.Vchain(i, c) * X[c]);
2083 if (Tp(i, c) != zero) R(i, c) = T(Q(i, c) / Tp(i, c));
2084 }
2085 // Cycle time excludes the think time actually spent at the delays, which is
2086 // the ORIGINAL Z summed over them; the Seidmann Zm disagreed with the station
2087 // residence times sum(R.*V) that Q now reports.
2088 std::vector<T> Cyc(C, zero);
2089 for (std::size_t c = 0; c < C; ++c) {
2090 if (!(X[c] > zero)) continue;
2091 T z = zero;
2092 for (std::size_t a = 0; a < nz; ++a) z += pf.Z(a, c);
2093 Cyc[c] = T(num_traits<T>::from_double(d.Nchain[c]) / X[c] - z);
2094 }
2095
2096 MvaSolution<T> out;
2097 out.method = method;
2098 out.iter = iters;
2099 if (L.has_class_switching()) {
2100 // de-aggregation input rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
2101 const ClassResults<T> cr =
2102 sn_deaggregate_chain_results(L, d, Matrix<T>(), Matrix<T>(), R, Tp, X);
2103 out.Q = cr.Q;
2104 out.U = cr.U;
2105 out.R = cr.R;
2106 out.Tp = cr.Tp;
2107 out.C = cr.C;
2108 out.X = cr.X;
2109 } else {
2110 out.Q = Q;
2111 out.U = U;
2112 out.R = R;
2113 out.Tp = Tp;
2114 out.X = X;
2115 out.C = Cyc;
2116 }
2117 return out;
2118}
2119
2120// ---------------------------------------------------------------------------
2121// solver_mvald: the exact load-dependent recursion
2122// ---------------------------------------------------------------------------
2123
2124namespace detail {
2125/**
2126 * Rate multiplier of finite station `i` at n = 1..ncol jobs: min(n,c) times the
2127 * limited load dependence, whose last column is held beyond its width (a
2128 * station declaring none contributes ones). MATLAB `mvald_rate_row`.
2129 */
2130template <class T>
2131std::vector<T> mvald_rate_row(const qn::NetworkStruct<T>& L, std::size_t i, std::size_t ncol) {
2132 const std::vector<T>& a = L.stations[i].lldscaling;
2133 const double c = L.stations[i].nservers;
2134 std::vector<T> row(ncol);
2135 for (std::size_t n = 0; n < ncol; ++n) {
2136 const double k = std::min(static_cast<double>(n + 1), c);
2137 const T base = num_traits<T>::from_double(k);
2138 row[n] = a.empty() ? base : T(base * (n < a.size() ? a[n] : a.back()));
2139 }
2140 return row;
2141}
2142} // namespace detail
2143
2144/**
2145 * Port of `solver_mvald.m`: exact MVA on a load-dependent model, through
2146 * `pfqn_mvaldmx`.
2147 *
2148 * The rate lattice `mu` is built per station: an infinite server gets the
2149 * linear ramp 1, 2, ..., Nt (which is what makes it a delay in a
2150 * load-dependent recursion), a station with `lldscaling` gets its lattice, and
2151 * everything else gets ones.
2152 *
2153 * THE UTILIZATION IS NOT the recursion's. Under load-dependent scaling the
2154 * reference replaces it with the carried load over the EFFECTIVE capacity
2155 * `max(nservers, max(lldscaling))`, the NC convention, rather than the
2156 * P(busy)-style estimator `pfqn_mvaldmx` returns; the two disagree wherever the
2157 * lattice exceeds the server count.
2158 */
2159template <class T>
2161 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
2163 const std::size_t M = L.nstations, C = L.nchains;
2164
2165 double Nt = 0.0;
2166 for (std::size_t c = 0; c < C; ++c)
2167 if (std::isfinite(d.Nchain[c])) Nt += d.Nchain[c];
2168 const std::size_t NT = static_cast<std::size_t>(std::llround(Nt));
2169
2170 // An open chain contributes its arrival rate and is marked OPEN_CLASS. The
2171 // rate is read at CHAIN level: STchain at an open chain's reference station
2172 // (its Source) is one over the SUM of the class arrival rates, which also
2173 // covers a chain whose classes arrive at several rates.
2174 std::vector<T> lambda(C, zero);
2175 std::vector<int> N(C, 0);
2176 std::vector<bool> openChain(C, false);
2177 std::size_t nOpenChains = 0;
2178 for (std::size_t c = 0; c < C; ++c) {
2179 if (std::isfinite(d.Nchain[c])) {
2180 N[c] = static_cast<int>(std::llround(d.Nchain[c]));
2181 continue;
2182 }
2183 N[c] = pfqn::OPEN_CLASS;
2184 openChain[c] = true;
2185 ++nOpenChains;
2186 const T st = d.STchain(d.refstatchain[c] - 1, c);
2187 if (st > zero) lambda[c] = T(one / st);
2188 }
2189
2190 Matrix<T> Qchain(M, C, zero), Uchain(M, C, zero);
2191 std::vector<T> Xchain(C, zero);
2192 if (nOpenChains == 0) {
2193 // PURELY CLOSED. Every station enters the recursion, an infinite server
2194 // as the load-dependent rate mu(n)=n, exact because n cannot then exceed
2195 // the closed population.
2196 if (NT == 0) throw UnsupportedError(ErrorKind{"Population"}, "solver_mvald: the model has no closed population");
2197 Matrix<T> mu(M, NT, one);
2198 for (std::size_t i = 0; i < M; ++i) {
2199 if (std::isinf(L.stations[i].nservers)) {
2200 for (std::size_t n = 0; n < NT; ++n)
2201 mu(i, n) = num_traits<T>::from_int(static_cast<long>(n) + 1);
2202 } else {
2203 // A finite station runs at min(n,c)*lld(n): the server count
2204 // and the declared limited load dependence multiply, as in
2205 // SolverCTMC, SolverSSA and sn_to_qrf_alpha. Reading the lld row
2206 // alone dropped c, so a 2-server queue beside a load-dependent
2207 // one was solved as a single server (MATLAB solver_mvald.m).
2208 const std::vector<T> row = detail::mvald_rate_row(L, i, NT);
2209 for (std::size_t n = 0; n < NT; ++n) mu(i, n) = row[n];
2210 }
2211 }
2212 Matrix<T> Dm(M, C, zero);
2213 for (std::size_t i = 0; i < M; ++i)
2214 for (std::size_t c = 0; c < C; ++c) Dm(i, c) = d.Lchain(i, c);
2215 const pfqn::MvaResult<T> pf = pfqn::pfqn_mvaldmx(lambda, Dm, N, Matrix<T>(), mu);
2216 Xchain = pf.XN;
2217 Qchain = pf.QN;
2218 Uchain = pf.UN;
2219 } else {
2220 // MIXED OR PURELY OPEN. Three kinds of row are not the same thing to
2221 // pfqn_mvaldmx and have to be separated before it is called; this is the
2222 // partition solver_ncld makes for the same recursion.
2223 // - THE SOURCE IS NOT A STATION. Its chain demand is the interarrival
2224 // time 1/lambda, so it carries offered load Lo=1 exactly and
2225 // pfqn_ldmx_ec then forms 1/(1-Lo/mu) = inf, poisoning every chain.
2226 // - A DELAY IS AN INFINITE SERVER FOR THE OPEN CHAINS TOO. mu(n)=n cut
2227 // at the closed population declares it saturated at NT jobs. It enters
2228 // as chain think time instead and its queue length is X*L, exact.
2229 // - A QUEUEING STATION KEEPS ITS WHOLE RATE ROW. pfqn_ldmx_ec reads the
2230 // limited-load-dependence level b off the row itself, so a row cut at
2231 // the closed population is read as a slower station, and with no closed
2232 // class at all it collapses to mu(1), a single fixed-rate server.
2233 std::vector<bool> sourceStation(M, false), delayStation(M, false);
2234 for (std::size_t c = 0; c < C; ++c)
2235 if (openChain[c]) sourceStation[static_cast<std::size_t>(d.refstatchain[c] - 1)] = true;
2236 std::vector<std::size_t> queueStations;
2237 for (std::size_t i = 0; i < M; ++i) {
2238 if (sourceStation[i]) continue;
2239 if (std::isinf(L.stations[i].nservers))
2240 delayStation[i] = true;
2241 else
2242 queueStations.push_back(i);
2243 }
2244 const std::size_t nq = queueStations.size();
2245
2246 Matrix<T> Z(1, C, zero);
2247 for (std::size_t c = 0; c < C; ++c) {
2248 T z = zero;
2249 for (std::size_t i = 0; i < M; ++i)
2250 if (delayStation[i]) z = T(z + d.Lchain(i, c));
2251 Z(0, c) = z;
2252 }
2253
2254 // The row must reach the level b where the rate saturates, pfqn_ldmx_ec
2255 // reads b off the row itself; with the server count folded in, b is at
2256 // least the lld width and at least c.
2257 std::size_t ncol = NT > 0 ? NT : 1;
2258 for (std::size_t i = 0; i < M; ++i) ncol = std::max(ncol, L.stations[i].lldscaling.size());
2259 for (std::size_t k = 0; k < nq; ++k)
2260 ncol = std::max(ncol, static_cast<std::size_t>(std::llround(L.stations[queueStations[k]].nservers)));
2261 Matrix<T> mu(nq, ncol, one);
2262 for (std::size_t k = 0; k < nq; ++k) {
2263 const std::vector<T> row = detail::mvald_rate_row(L, queueStations[k], ncol);
2264 for (std::size_t n = 0; n < ncol; ++n) mu(k, n) = row[n];
2265 }
2266 Matrix<T> Dq(nq, C, zero);
2267 for (std::size_t k = 0; k < nq; ++k)
2268 for (std::size_t c = 0; c < C; ++c) Dq(k, c) = d.Lchain(queueStations[k], c);
2269
2270 const pfqn::MvaResult<T> pf = pfqn::pfqn_mvaldmx(lambda, Dq, N, Z, mu);
2271 Xchain = pf.XN;
2272 for (std::size_t k = 0; k < nq; ++k)
2273 for (std::size_t c = 0; c < C; ++c) {
2274 Qchain(queueStations[k], c) = pf.QN(k, c);
2275 Uchain(queueStations[k], c) = pf.UN(k, c);
2276 }
2277 for (std::size_t i = 0; i < M; ++i)
2278 if (delayStation[i])
2279 for (std::size_t c = 0; c < C; ++c)
2280 // infinite server: X*L for a closed chain, lambda*L for an open one
2281 Qchain(i, c) = T(d.Lchain(i, c) * Xchain[c]);
2282 }
2283
2284 // Rchain IS THE PER-VISIT RESPONSE TIME, Qchain / Tchain, not the residence
2285 // time Qchain / Xchain. `sn_deaggregate_chain_results` rebuilds the class
2286 // queue length as `Rchain * Xchain * Vchain(i,c)/Vchain(refstat,c)`, so it
2287 // multiplies the visit ratio back IN; handing it a residence time counts
2288 // that ratio twice and the reported queue lengths then no longer sum to the
2289 // population. Invisible on every load-dependent model whose LD station has
2290 // the reference station's chain visits (the shipped examples all do), and
2291 // decisive on one that does not -- the closed delayed-hit retrieval cache,
2292 // whose fetch station is visited once per MISS. Every sibling analyzer here
2293 // (:300, :1046, :1690) already divides by Tchain; this line did not.
2294 // MATLAB's solver_mvald.m:45 carried the same divisor and is fixed with it;
2295 // Python's exact LD path already divided by Tchain and was right.
2296 Matrix<T> Tchain(M, C, zero), Rchain(M, C, zero);
2297 for (std::size_t i = 0; i < M; ++i)
2298 for (std::size_t c = 0; c < C; ++c) {
2299 Tchain(i, c) = T(Xchain[c] * d.Vchain(i, c));
2300 if (Tchain(i, c) > zero) Rchain(i, c) = T(Qchain(i, c) / Tchain(i, c));
2301 }
2302
2303 const ClassResults<T> cr =
2304 sn_deaggregate_chain_results(L, d, Matrix<T>(), Uchain, Rchain, Tchain, Xchain);
2305 MvaSolution<T> out;
2306 out.Q = cr.Q;
2307 out.U = cr.U;
2308 out.R = cr.R;
2309 out.Tp = cr.Tp;
2310 out.C = cr.C;
2311 out.X = cr.X;
2312 out.method = "exact";
2313 out.iter = 1;
2314
2315 // Busy-server fraction under load-dependent scaling (NC convention), at
2316 // EVERY finite station once any station declares limited load dependence:
2317 // the reference's lldscaling is then a matrix with a row of ones at a
2318 // station that declares none, so ceff = max(c, 1) = c there.
2319 bool anyLld = false;
2320 for (std::size_t i = 0; i < M; ++i)
2321 if (!L.stations[i].lldscaling.empty()) anyLld = true;
2322 for (std::size_t i = 0; i < M; ++i) {
2323 if (!anyLld || !std::isfinite(L.stations[i].nservers)) continue;
2324 double ceff = L.stations[i].nservers;
2325 for (const T& v : L.stations[i].lldscaling)
2326 ceff = std::max(ceff, num_traits<T>::to_double(v));
2327 for (std::size_t r = 0; r < L.nclasses; ++r) {
2328 if (L.disabled[i][r]) continue;
2329 const T st = L.rates(i, r) > zero ? T(one / L.rates(i, r)) : zero;
2330 if (st > zero) out.U(i, r) = T(out.Tp(i, r) * st / num_traits<T>::from_double(ceff));
2331 }
2332 }
2333 return out;
2334}
2335
2336// ---------------------------------------------------------------------------
2337// solver_mva_sum: the summation method
2338// ---------------------------------------------------------------------------
2339
2340/**
2341 * Port of `solver_mva_sum.m`: the SUM / ESUM summation method (Bolch et al.,
2342 * Secs. 9.2, 10.1.4.4 and 10.1.5).
2343 *
2344 * A closed model goes to `sum_closed`; an open or mixed one to `sum_closing`
2345 * with the reference's Kclosed = 5000. The SCV each station is given is the
2346 * ESUM discrimination: FCFS and SIRO are service-time sensitive and get the
2347 * chain SCV, while PS, LCFSPR and the infinite servers are insensitive and are
2348 * passed 1 -- handing them their real SCV would apply a correction that the
2349 * product form says does not exist.
2350 */
2351template <class T>
2353 using qn::SchedStrategy;
2354 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
2356 const std::size_t M = L.nstations, K = L.nchains;
2357
2358 if constexpr (!num_traits<T>::has_transcendental) {
2359 throw UnsupportedError(ErrorKind{"Arithmetic"},
2360 "solver_mva_sum: the summation method locates the root of its population constraint "
2361 "by bisection and evaluates the Erlang-C waiting probability, neither of which exact "
2362 "arithmetic has a representation for; use the double or real backend");
2363 } else {
2364 std::vector<std::size_t> rows;
2365 std::vector<sum::Servers> mi;
2366 for (std::size_t i = 0; i < M; ++i) {
2367 const SchedStrategy sc = L.stations[i].sched;
2368 if (sc == SchedStrategy::EXT) continue; // the external world is lambda
2369 if (sc == SchedStrategy::INF) {
2370 rows.push_back(i);
2371 mi.push_back(sum::Servers::inf());
2372 continue;
2373 }
2374 if (sc == SchedStrategy::PS || sc == SchedStrategy::LCFSPR ||
2375 sc == SchedStrategy::FCFS || sc == SchedStrategy::SIRO) {
2376 rows.push_back(i);
2377 const double c = L.stations[i].nservers;
2378 mi.push_back(std::isfinite(c) ? sum::Servers::of(static_cast<long>(std::llround(c)))
2379 : sum::Servers::inf());
2380 continue;
2381 }
2382 throw UnsupportedError(ErrorKind{"SchedStrategy"}, std::string("solver_mva_sum: the summation method does not "
2383 "support ") +
2384 lang::sched_to_text(sc) + " scheduling");
2385 }
2386
2387 const std::size_t Mr = rows.size();
2388 Matrix<T> Lm(Mr, K, zero), scv(Mr, K, one);
2389 for (std::size_t a = 0; a < Mr; ++a) {
2390 const std::size_t i = rows[a];
2391 const bool sensitive = L.stations[i].sched == SchedStrategy::FCFS ||
2392 L.stations[i].sched == SchedStrategy::SIRO;
2393 for (std::size_t c = 0; c < K; ++c) {
2394 Lm(a, c) = T(d.STchain(i, c) * d.Vchain(i, c));
2395 if (!sensitive) continue;
2396 const double v = num_traits<T>::to_double(d.SCVchain(i, c));
2397 if (std::isfinite(v) && v > 0.0) scv(a, c) = num_traits<T>::from_double(v);
2398 }
2399 }
2400
2401 std::vector<long> N(K, 0);
2402 std::vector<T> Z(K, zero);
2403 std::vector<std::size_t> ocl;
2404 for (std::size_t c = 0; c < K; ++c) {
2405 if (std::isfinite(d.Nchain[c])) N[c] = static_cast<long>(std::llround(d.Nchain[c]));
2406 else ocl.push_back(c);
2407 }
2408
2409 Matrix<T> Qrows, Urows;
2410 std::vector<T> Xchain;
2411 std::size_t iters = 0;
2412 if (ocl.empty()) {
2413 sum::SumOptions so;
2414 so.tol = opt.iter_tol;
2415 so.maxiter = static_cast<std::size_t>(opt.iter_max);
2416 const sum::SumClosedResult<T> r = sum::sum_closed(Lm, N, Z, mi, scv, so);
2417 Qrows = r.QN;
2418 Urows = r.UN;
2419 Xchain = r.XN;
2420 iters = r.it;
2421 } else {
2422 std::vector<T> lambda(K, zero), scva(K, one);
2423 for (std::size_t c : ocl) {
2424 const T st = d.STchain(d.refstatchain[c] - 1, c);
2425 // AN OPEN CHAIN WITH NO ARRIVAL RATE IS NOT A CHAIN OF RATE ZERO.
2426 // Leaving lambda[c] at zero makes `sum_closing` treat it as a CLOSED
2427 // chain of zero population, which is a different model solved
2428 // without complaint. The service time at the reference station is
2429 // where the arrival rate comes from, so a non-positive one means the
2430 // chain is unspecified, not idle.
2431 if (!(st > zero))
2432 throw InputError(
2433 "solver_mva_sum: open chain " + std::to_string(c + 1) +
2434 " has a non-positive service time at its reference station, so it carries no "
2435 "arrival rate; the summation method cannot place it");
2436 lambda[c] = T(one / st);
2437 const double v = num_traits<T>::to_double(d.SCVchain(d.refstatchain[c] - 1, c));
2438 if (std::isfinite(v) && v > 0.0) scva[c] = num_traits<T>::from_double(v);
2439 }
2441 co.sum.tol = opt.iter_tol;
2442 co.sum.maxiter = static_cast<std::size_t>(opt.iter_max);
2443 const sum::SumClosingResult<T> r = sum::sum_closing(lambda, scva, Lm, mi, scv, N, Z, co);
2444 Qrows = r.QN;
2445 Urows = r.UN;
2446 Xchain = r.XN;
2447 iters = r.it;
2448 }
2449
2450 Matrix<T> Qchain(M, K, zero), Uchain(M, K, zero), Tchain(M, K, zero), Rchain(M, K, zero);
2451 for (std::size_t a = 0; a < Mr; ++a)
2452 for (std::size_t c = 0; c < K; ++c) {
2453 Qchain(rows[a], c) = Qrows(a, c);
2454 Uchain(rows[a], c) = Urows(a, c);
2455 }
2456 for (std::size_t i = 0; i < M; ++i)
2457 for (std::size_t c = 0; c < K; ++c) {
2458 Tchain(i, c) = T(Xchain[c] * d.Vchain(i, c));
2459 if (Tchain(i, c) > zero) Rchain(i, c) = T(Qchain(i, c) / Tchain(i, c));
2460 }
2461 for (std::size_t c = 0; c < K; ++c) {
2462 if (d.Nchain[c] != 0.0) continue;
2463 Xchain[c] = zero;
2464 for (std::size_t i = 0; i < M; ++i) {
2465 Qchain(i, c) = zero;
2466 Uchain(i, c) = zero;
2467 Rchain(i, c) = zero;
2468 Tchain(i, c) = zero;
2469 }
2470 }
2471
2472 const ClassResults<T> cr =
2473 sn_deaggregate_chain_results(L, d, Matrix<T>(), Matrix<T>(), Rchain, Tchain, Xchain);
2474 MvaSolution<T> out;
2475 out.Q = cr.Q;
2476 out.U = cr.U;
2477 out.R = cr.R;
2478 out.Tp = cr.Tp;
2479 out.C = cr.C;
2480 out.X = cr.X;
2481 out.method = opt.method;
2482 out.iter = static_cast<int>(iters);
2483 return out;
2484 }
2485}
2486
2487// ---------------------------------------------------------------------------
2488// Blocking-after-service: the SQD handler
2489// ---------------------------------------------------------------------------
2490
2491/**
2492 * Port of `solver_sqd.m`: Smith queue decomposition for blocking-after-service.
2493 *
2494 * `npfqn_sqd` is single-chain by construction -- it solves ONE circulating
2495 * population -- so a multichain model is refused. The reference warns and
2496 * returns a matrix of NaN there; refusing by name is the same information
2497 * without a result that reads as solved.
2498 *
2499 * The unpacking is the one `npfqn_sqd.h` documents: the chain-aggregated demand
2500 * and visit columns, an infinite capacity at every delay, and `sn.rt` with its
2501 * stateful indexing.
2502 */
2503template <class T>
2505 using qn::SchedStrategy;
2506 // The effective-rate calibration evaluates exp, log and real powers, and the
2507 // M/M/1/K blocking probability a real power, so there is no exact-field
2508 // version of this method. Refuse at RUN time rather than at compile time,
2509 // as every other transcendental analyzer in this port does.
2510 if constexpr (!num_traits<T>::has_transcendental) {
2511 (void)L;
2512 (void)d;
2513 throw UnsupportedError(ErrorKind{"Arithmetic"},
2514 "solver_sqd: the blocking-after-service calibration evaluates exp, log and real "
2515 "powers, which exact rational arithmetic cannot represent");
2516 } else {
2517 const T zero = num_traits<T>::from_int(0);
2518 const std::size_t M = L.nstations;
2519 if (L.nchains != 1)
2520 throw UnsupportedError(ErrorKind{"MultiClass"},
2521 "solver_sqd: Smith queue decomposition supports single-chain closed networks only; "
2522 "this model has " + std::to_string(L.nchains) + " chains");
2523 // AND CLOSED, which the chain count alone does not establish. The automatic
2524 // route here is gated by `mva_is_bas_model`, which excludes open classes, but
2525 // the explicit `method == "sqd"` route is not: an open model reaches
2526 // npfqn_sqd with a population counting only the closed classes and gets a
2527 // silently wrong answer rather than a refusal.
2528 if (L.has_open_classes())
2529 throw UnsupportedError(
2530 "solver_sqd: Smith queue decomposition is defined for a CLOSED population; this model "
2531 "has an open class, whose jobs the fixed point cannot count");
2532
2533 std::vector<T> ST(M, zero), V(M, zero), cap(M, zero);
2534 std::vector<bool> isDelay(M, false);
2535 std::vector<std::size_t> s2sf(M, 0);
2536 const T inf = num_traits<T>::from_double(std::numeric_limits<double>::infinity());
2537 for (std::size_t i = 0; i < M; ++i) {
2538 ST[i] = d.STchain(i, 0);
2539 V[i] = d.Vchain(i, 0);
2540 isDelay[i] = (L.stations[i].sched == SchedStrategy::INF ||
2541 L.stations[i].sched == SchedStrategy::EXT);
2542 // a capacity above 1e14 is MATLAB's own "effectively unbounded" test
2543 const double c = L.cap.empty() ? std::numeric_limits<double>::infinity() : L.cap[i];
2544 cap[i] = (isDelay[i] || !(c <= 1e14)) ? inf : num_traits<T>::from_double(c);
2545 s2sf[i] = L.stateful_of_station(i + 1);
2546 }
2547
2549 const npfqn::SqdResult<T> r =
2550 npfqn::npfqn_sqd(ST, V, cap, isDelay, L.rt, s2sf, L.nclasses,
2551 static_cast<int>(std::llround(L.nclosedjobs())), sopt);
2552
2553 // Vchain is normalized to 1 at the reference station, so the per-station
2554 // throughput there IS the chain reference throughput.
2555 const std::size_t refstat = d.refstatchain.empty() ? 1 : d.refstatchain[0];
2556 Matrix<T> Tchain(M, 1, zero), Qchain(M, 1, zero), Uchain(M, 1, zero), Rchain(M, 1, zero);
2557 for (std::size_t i = 0; i < M; ++i) {
2558 Tchain(i, 0) = r.X[i];
2559 Qchain(i, 0) = r.Q[i];
2560 Uchain(i, 0) = r.U[i];
2561 Rchain(i, 0) = r.R[i];
2562 }
2563 std::vector<T> Xchain(1, r.X[refstat - 1]);
2564
2565 const ClassResults<T> cr =
2566 sn_deaggregate_chain_results(L, d, Qchain, Uchain, Rchain, Tchain, Xchain);
2567 MvaSolution<T> out;
2568 out.Q = cr.Q;
2569 out.U = cr.U;
2570 out.R = cr.R;
2571 out.Tp = cr.Tp;
2572 out.C = cr.C;
2573 out.X = cr.X;
2574 out.method = "sqd";
2575 out.lG = std::numeric_limits<double>::quiet_NaN();
2576 return out;
2577 }
2578}
2579
2580// ---------------------------------------------------------------------------
2581// Blocking-after-service: the MVABLO handler
2582// ---------------------------------------------------------------------------
2583
2584/**
2585 * Port of `mvablo_scope_reason.m`: why method 'mvablo' cannot solve L, as
2586 * {reason, kind} with kind the error kind of the refusal, or two empty strings
2587 * when it can. One predicate, read by the method gate and by solver_mvablo.
2588 *
2589 * Scope: a closed single-class network of single-server FCFS queues with
2590 * exponential service and finite capacities under Blocking-After-Service, plus
2591 * INF delays (a LINE extension). Every buffer that can bind must block its
2592 * feeders BAS-style, declared on itself or on a feeder, and no delay may feed one.
2593 */
2594template <class T>
2595std::pair<std::string, std::string> mvablo_scope_reason(const qn::NetworkStruct<T>& L) {
2596 using qn::SchedStrategy;
2597 const std::string alt = " Use SolverCTMC or SolverJMT instead.";
2598 for (const auto& c : L.classes)
2599 if (std::isinf(c.population))
2600 return {"MVABLO is defined for closed networks only; this model has an open class." + alt, "OpenClass"};
2601 if (L.nclasses != 1 || L.nchains != 1)
2602 return {"MVABLO supports a single closed class; this model has " + std::to_string(L.nclasses) +
2603 " classes (class switching included)." + alt, "MultiClass"};
2604 if (!(L.nclosedjobs() > 0.0)) return {"MVABLO requires a positive closed population." + alt, "ClosedClass"};
2605 for (const auto& n : L.nodes)
2606 if (n.nodetype == qn::NodeType::Fork || n.nodetype == qn::NodeType::Join)
2607 return {"MVABLO does not support fork-join." + alt, "Fork"};
2608 if (L.stateful_nodes.size() != L.nstations)
2609 return {"MVABLO supports networks whose stateful nodes are all stations (queues and delays)." + alt, "Node"};
2610 const std::size_t M = L.nstations;
2611 for (std::size_t i = 0; i < M; ++i) {
2612 const auto& st = L.stations[i];
2613 if (!st.lldscaling.empty() || st.cdscaling || st.jdscaling)
2614 return {"MVABLO does not support load-, class- or joint-dependent service." + alt, "LoadDependence"};
2615 }
2616 auto is_delay = [&](std::size_t i) { return L.stations[i].sched == SchedStrategy::INF; };
2617 for (std::size_t i = 0; i < M; ++i) {
2618 const auto& st = L.stations[i];
2619 if (!is_delay(i) && st.sched != SchedStrategy::FCFS) {
2620 std::string s = lang::sched_to_text(st.sched);
2621 for (char& ch : s) ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
2622 return {"MVABLO supports FCFS queues and INF delays; station " + st.name + " is " + s + "." + alt,
2623 "Scheduling"};
2624 }
2625 if (!is_delay(i) && st.nservers != 1.0)
2626 return {"MVABLO supports single-server queues; station " + st.name + " has " +
2627 std::to_string(static_cast<long>(st.nservers)) + " servers." + alt, "MultiServer"};
2628 if (L.service.size() <= i || L.service[i].empty() || L.service[i][0].type != lang::ProcessType::EXP)
2629 return {"MVABLO requires exponential service; station " + st.name + " is not exponential." + alt,
2630 "Distribution"};
2631 }
2632 const double N = L.nclosedjobs();
2633 const T zero = num_traits<T>::from_int(0);
2634 auto rt = [&](std::size_t j, std::size_t i) {
2635 return L.rt(L.stateful_of_station(j + 1) - 1, L.stateful_of_station(i + 1) - 1) > zero;
2636 };
2637 auto is_bas = [&](std::size_t i) {
2638 return L.droprule.size() > i && !L.droprule[i].empty() && L.droprule[i][0] == lang::DropStrategy::BAS;
2639 };
2640 for (std::size_t i = 0; i < M; ++i) {
2641 const double cap = L.cap.empty() ? std::numeric_limits<double>::infinity() : L.cap[i];
2642 if (is_delay(i) || std::isinf(cap) || cap >= N) continue;
2643 bool bas = is_bas(i);
2644 for (std::size_t j = 0; j < M && !bas; ++j) bas = is_bas(j) && rt(j, i);
2645 if (!bas)
2646 return {"MVABLO models Blocking-After-Service only; the finite buffer of station " +
2647 L.stations[i].name + " has no BAS drop rule." + alt, "FiniteCapacity"};
2648 for (std::size_t j = 0; j < M; ++j)
2649 if (is_delay(j) && rt(j, i))
2650 return {"MVABLO cannot block a delay: " + L.stations[j].name + " feeds the finite buffer of " +
2651 L.stations[i].name + "." + alt, "Delay"};
2652 }
2653 return {std::string(), std::string()};
2654}
2655
2656/**
2657 * Port of `solver_mvablo.m`. Results are the paper's: QLen is k_i of eq. (3) and
2658 * RespT the per-visit residence time t_i, blocking included. The paper counts a
2659 * blocked job at the station holding it, whereas LINE's CTMC/JMT/LDES count it at
2660 * the full destination; the blocking times are a calibration device that grows
2661 * with the population and are NOT used to move jobs across.
2662 *
2663 * `converged` carries pfqn_mvablo's flag: false when a population exhausted
2664 * iter_max passes without meeting every capacity, the paper's deadlock outcome.
2665 */
2666template <class T>
2668 const std::pair<std::string, std::string> why = mvablo_scope_reason(L);
2669 if (!why.first.empty()) throw UnsupportedError(ErrorKind{why.second}, "solver_mvablo: " + why.first);
2670 const T zero = num_traits<T>::from_int(0);
2671 const T one = num_traits<T>::from_int(1);
2672 const std::size_t M = L.nstations;
2673 std::vector<T> S(M, zero);
2674 std::vector<double> K(M, std::numeric_limits<double>::infinity());
2675 std::vector<bool> isdelay(M, false);
2676 Matrix<T> P(M, M, zero);
2677 for (std::size_t i = 0; i < M; ++i) {
2678 isdelay[i] = L.stations[i].sched == qn::SchedStrategy::INF;
2679 S[i] = T(one / L.service[i][0].rate());
2680 if (!isdelay[i] && !L.cap.empty()) K[i] = L.cap[i];
2681 for (std::size_t j = 0; j < M; ++j)
2682 P(i, j) = L.rt(L.stateful_of_station(i + 1) - 1, L.stateful_of_station(j + 1) - 1);
2683 }
2684 const long N = std::lround(L.nclosedjobs());
2685 const pfqn::MvabloResult<T> r = pfqn::pfqn_mvablo(N, S, P, K, isdelay, opt.tol, opt.iter_max);
2686 const std::size_t ref = L.classes[0].refstat - 1;
2687 MvaSolution<T> out;
2688 out.Q = Matrix<T>(M, 1, zero);
2689 out.U = Matrix<T>(M, 1, zero);
2690 out.R = Matrix<T>(M, 1, zero);
2691 out.Tp = Matrix<T>(M, 1, zero);
2692 for (std::size_t i = 0; i < M; ++i) {
2693 out.Q(i, 0) = r.Q[i];
2694 out.U(i, 0) = r.U[i];
2695 out.R(i, 0) = r.R[i];
2696 out.Tp(i, 0) = r.X[i];
2697 }
2698 out.X = {r.X[ref]};
2699 out.C = {T(num_traits<T>::from_int(N) / r.X[ref])};
2700 out.method = "mvablo";
2701 out.iter = r.iter;
2702 out.converged = r.converged;
2703 out.lG = std::numeric_limits<double>::quiet_NaN();
2704 return out;
2705}
2706
2707// ---------------------------------------------------------------------------
2708// Finite BAS buffers: the debeMVA handler
2709// ---------------------------------------------------------------------------
2710
2711/**
2712 * Port of `debemva_scope_reason.m`: why method 'debemva' cannot solve L, as
2713 * {reason, kind} with kind the error kind of the refusal, or two empty strings
2714 * when it can. One predicate, read by the method gate and by solver_debemva.
2715 *
2716 * Scope: a closed single-class network of single-server FCFS queues with
2717 * exponential service and finite capacities under Blocking-After-Service, plus
2718 * delays of any service distribution, which may feed a finite buffer but may
2719 * not have a binding capacity themselves. Every buffer that can bind must block
2720 * its feeders BAS-style, declared on itself or on a feeder.
2721 */
2722template <class T>
2723std::pair<std::string, std::string> debemva_scope_reason(const qn::NetworkStruct<T>& L) {
2724 using qn::SchedStrategy;
2725 const std::string alt = " Use SolverCTMC or SolverJMT instead.";
2726 for (const auto& c : L.classes)
2727 if (std::isinf(c.population))
2728 return {"debeMVA is defined for closed networks only; this model has an open class." + alt, "OpenClass"};
2729 if (L.nclasses != 1 || L.nchains != 1)
2730 return {"debeMVA supports a single closed class; this model has " + std::to_string(L.nclasses) +
2731 " classes (class switching included)." + alt, "MultiClass"};
2732 if (!(L.nclosedjobs() > 0.0)) return {"debeMVA requires a positive closed population." + alt, "ClosedClass"};
2733 for (const auto& n : L.nodes)
2734 if (n.nodetype == qn::NodeType::Fork || n.nodetype == qn::NodeType::Join)
2735 return {"debeMVA does not support fork-join." + alt, "Fork"};
2736 if (L.stateful_nodes.size() != L.nstations)
2737 return {"debeMVA supports networks whose stateful nodes are all stations (queues and delays)." + alt, "Node"};
2738 const std::size_t M = L.nstations;
2739 for (std::size_t i = 0; i < M; ++i) {
2740 const auto& st = L.stations[i];
2741 if (!st.lldscaling.empty() || st.cdscaling || st.jdscaling)
2742 return {"debeMVA does not support load-, class- or joint-dependent service." + alt, "LoadDependence"};
2743 }
2744 auto is_delay = [&](std::size_t i) { return L.stations[i].sched == SchedStrategy::INF; };
2745 for (std::size_t i = 0; i < M; ++i) {
2746 const auto& st = L.stations[i];
2747 if (!is_delay(i) && st.sched != SchedStrategy::FCFS) {
2748 std::string s = lang::sched_to_text(st.sched);
2749 for (char& ch : s) ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
2750 return {"debeMVA supports FCFS queues and INF delays; station " + st.name + " is " + s + "." + alt,
2751 "Scheduling"};
2752 }
2753 if (!is_delay(i) && st.nservers != 1.0)
2754 return {"debeMVA supports single-server queues; station " + st.name + " has " +
2755 std::to_string(static_cast<long>(st.nservers)) + " servers." + alt, "MultiServer"};
2756 if (!is_delay(i) &&
2757 (L.service.size() <= i || L.service[i].empty() || L.service[i][0].type != lang::ProcessType::EXP))
2758 return {"debeMVA requires exponential service at queues; station " + st.name + " is not exponential." +
2759 alt, "Distribution"};
2760 }
2761 const double N = L.nclosedjobs();
2762 const double inf = std::numeric_limits<double>::infinity();
2763 for (std::size_t i = 0; i < M; ++i) {
2764 const double cap = L.cap.empty() ? inf : L.cap[i];
2765 if (is_delay(i) && !std::isinf(cap) && cap < N)
2766 return {"debeMVA treats a delay as never full; station " + L.stations[i].name + " has capacity " +
2767 std::to_string(static_cast<long>(cap)) + " below the population." + alt, "FiniteCapacity"};
2768 }
2769 const T zero = num_traits<T>::from_int(0);
2770 auto rt = [&](std::size_t j, std::size_t i) {
2771 return L.rt(L.stateful_of_station(j + 1) - 1, L.stateful_of_station(i + 1) - 1) > zero;
2772 };
2773 auto is_bas = [&](std::size_t i) {
2774 return L.droprule.size() > i && !L.droprule[i].empty() && L.droprule[i][0] == lang::DropStrategy::BAS;
2775 };
2776 for (std::size_t i = 0; i < M; ++i) {
2777 const double cap = L.cap.empty() ? inf : L.cap[i];
2778 if (is_delay(i) || std::isinf(cap) || cap >= N) continue;
2779 bool bas = is_bas(i);
2780 for (std::size_t j = 0; j < M && !bas; ++j) bas = is_bas(j) && rt(j, i);
2781 if (!bas)
2782 return {"debeMVA models Blocking-After-Service only; the finite buffer of station " +
2783 L.stations[i].name + " has no BAS drop rule." + alt, "FiniteCapacity"};
2784 }
2785 return {std::string(), std::string()};
2786}
2787
2788/**
2789 * Port of `solver_debemva.m`. Results are the paper's: QLen is n_i after the
2790 * last pass and RespT the per-visit residence time t_i, blocking included; a
2791 * blocked job is counted at the station holding it, whereas LINE's
2792 * CTMC/JMT/LDES count it at the full destination. The capacity test is strict
2793 * (opt.tol is not used) and the pass budget per population is
2794 * max(opt.iter_max, 1e5). `converged` carries pfqn_debemva's flag.
2795 */
2796template <class T>
2798 const std::pair<std::string, std::string> why = debemva_scope_reason(L);
2799 if (!why.first.empty()) throw UnsupportedError(ErrorKind{why.second}, "solver_debemva: " + why.first);
2800 const T zero = num_traits<T>::from_int(0);
2801 const T one = num_traits<T>::from_int(1);
2802 const std::size_t M = L.nstations;
2803 std::vector<T> S(M, zero);
2804 std::vector<double> K(M, std::numeric_limits<double>::infinity());
2805 std::vector<bool> isdelay(M, false);
2806 Matrix<T> P(M, M, zero);
2807 for (std::size_t i = 0; i < M; ++i) {
2808 isdelay[i] = L.stations[i].sched == qn::SchedStrategy::INF;
2809 S[i] = T(one / L.rates(i, 0)); // mean service time, any distribution at a delay
2810 if (!isdelay[i] && !L.cap.empty()) K[i] = L.cap[i];
2811 for (std::size_t j = 0; j < M; ++j)
2812 P(i, j) = L.rt(L.stateful_of_station(i + 1) - 1, L.stateful_of_station(j + 1) - 1);
2813 }
2814 const long N = std::lround(L.nclosedjobs());
2815 const long budget = std::max<long>(opt.iter_max, 100000L);
2816 const pfqn::DebemvaResult<T> r = pfqn::pfqn_debemva(N, S, P, K, isdelay, 0.0, budget);
2817 // !converged stands for the reference's line_warning: a population exhausted
2818 // the pass budget without meeting every capacity.
2819 const std::size_t ref = L.classes[0].refstat - 1;
2820 MvaSolution<T> out;
2821 out.Q = Matrix<T>(M, 1, zero);
2822 out.U = Matrix<T>(M, 1, zero);
2823 out.R = Matrix<T>(M, 1, zero);
2824 out.Tp = Matrix<T>(M, 1, zero);
2825 for (std::size_t i = 0; i < M; ++i) {
2826 out.Q(i, 0) = r.Q[i];
2827 out.U(i, 0) = r.U[i];
2828 out.R(i, 0) = r.R[i];
2829 out.Tp(i, 0) = r.X[i];
2830 }
2831 out.X = {r.X[ref]};
2832 out.C = {T(num_traits<T>::from_int(N) / r.X[ref])};
2833 out.method = "debemva";
2834 out.iter = static_cast<int>(std::min<long>(r.iter, std::numeric_limits<int>::max()));
2835 out.converged = r.converged;
2836 out.lG = std::numeric_limits<double>::quiet_NaN();
2837 return out;
2838}
2839
2840// ---------------------------------------------------------------------------
2841// Open networks inside one finite capacity region: the OQNRC handler
2842// ---------------------------------------------------------------------------
2843
2844/** Scope of a model inside OQNRC: token pool of each class (0-based), tokens per pool, drop rule. */
2846 std::string reason, kind; ///< empty when the model is in scope
2847 std::vector<int> pool, Ncap;
2848 bool waitq = true;
2849};
2850
2851/**
2852 * Port of `oqnrc_scope_reason.m`: why method 'oqnrc' cannot solve L, with the
2853 * error kind of the refusal, or empty strings plus the token pools when it can.
2854 * One predicate, read by the method gate, `resolve_method` and solver_oqnrc.
2855 *
2856 * Scope (Buitenhek, van Houtum and Zijm 1997): an open network with exactly one
2857 * finite capacity region holding every station but the Source, capped by a
2858 * global job count, by per-class counts on every class, or by linear
2859 * constraints that partition the classes into unit-weight groups. Every class
2860 * uses the same drop rule, WAITQ or DROP. Stations are FCFS, PS or INF.
2861 */
2862template <class T>
2864 using qn::SchedStrategy;
2865 const std::string alt = " Use SolverCTMC, SolverLDES or SolverJMT instead.";
2866 OqnrcScope sc;
2867 auto refuse = [&](const std::string& why, const char* kind) {
2868 sc.reason = why + alt;
2869 sc.kind = kind;
2870 sc.pool.clear();
2871 sc.Ncap.clear();
2872 return sc;
2873 };
2874 const std::size_t K = L.nclasses, M = L.nstations;
2875 if (L.regions.empty()) return refuse("OQNRC needs a finite capacity region (addRegion) holding the inner system.", "Region");
2876 if (L.regions.size() != 1)
2877 return refuse("OQNRC supports a single finite capacity region; this model has " +
2878 std::to_string(L.regions.size()) + ".", "Region");
2879 for (const auto& c : L.classes)
2880 if (!std::isinf(c.population))
2881 return refuse("OQNRC is defined for open networks only; this model has a closed class.", "ClosedClass");
2882 for (const auto& n : L.nodes)
2883 if (n.nodetype == qn::NodeType::Fork || n.nodetype == qn::NodeType::Join)
2884 return refuse("OQNRC does not support fork-join.", "Fork");
2885 if (L.stateful_nodes.size() != M)
2886 return refuse("OQNRC supports networks whose stateful nodes are all stations (Source, queues and delays).",
2887 "Node");
2888 for (std::size_t i = 0; i < M; ++i) {
2889 const auto& st = L.stations[i];
2890 if (!st.lldscaling.empty() || st.cdscaling || st.jdscaling)
2891 return refuse("OQNRC does not support load-, class- or joint-dependent service.", "LoadDependence");
2892 }
2893 const auto& rg = L.regions[0];
2894 auto member = [&](std::size_t i) { return i < rg.members.size() && rg.members[i]; };
2895 long src = -1;
2896 for (std::size_t i = 0; i < M; ++i) {
2897 const auto& st = L.stations[i];
2898 if (st.nodetype == qn::NodeType::Source) {
2899 if (member(i)) return refuse("OQNRC cannot place the Source inside the region.", "Region");
2900 if (src < 0) src = static_cast<long>(i);
2901 continue;
2902 }
2903 if (st.sched != SchedStrategy::FCFS && st.sched != SchedStrategy::PS && st.sched != SchedStrategy::INF) {
2904 std::string s = lang::sched_to_text(st.sched);
2905 for (char& ch : s) ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
2906 return refuse("OQNRC supports FCFS, PS and INF stations; station " + st.name + " is " + s + ".",
2907 "Scheduling");
2908 }
2909 const double cp = L.cap.size() > i ? L.cap[i] : std::numeric_limits<double>::infinity();
2910 if (std::isfinite(cp) && cp >= 0 && st.sched != SchedStrategy::INF)
2911 return refuse("OQNRC models the region cap only; station " + st.name +
2912 " also has a finite buffer (setCapacity).", "FiniteCapacity");
2913 if (!member(i))
2914 return refuse("OQNRC needs the region to hold every station but the Source; station " + st.name +
2915 " is outside it.", "Region");
2916 }
2917 for (std::size_t i = 0; i < M && i < rg.maxmem.size(); ++i)
2918 if (member(i) && rg.maxmem[i] != -1)
2919 return refuse("OQNRC does not support a region memory budget (setGlobalMaxMemory).", "Region");
2920 bool allW = true, allD = true;
2921 for (std::size_t r = 0; r < K; ++r) {
2922 const lang::DropStrategy d = r < rg.rule.size() ? rg.rule[r] : lang::DropStrategy::DROP;
2923 allW = allW && d == lang::DropStrategy::WAITQ;
2924 allD = allD && d == lang::DropStrategy::DROP;
2925 }
2926 if (!allW && !allD)
2927 return refuse("OQNRC needs the same drop rule on every class of the region, either WAITQ (the paper's "
2928 "external queue) or DROP (loss).", "Region");
2929 sc.waitq = allW;
2930 std::size_t first = M;
2931 for (std::size_t i = 0; i < M && first == M; ++i)
2932 if (member(i)) first = i;
2933 if (first == M) return refuse("OQNRC needs the region to hold the inner stations.", "Region");
2934 auto capat = [&](std::size_t r) {
2935 return first < rg.cap.size() && r < rg.cap[first].size() ? rg.cap[first][r] : -1.0;
2936 };
2937 const double gcap = capat(K);
2938 bool unset = true, allpos = true;
2939 for (std::size_t r = 0; r < K; ++r) {
2940 unset = unset && capat(r) == -1;
2941 allpos = allpos && capat(r) > 0;
2942 }
2943 if (rg.lincon_A.rows() > 0) {
2944 if (gcap != -1 || !unset)
2945 return refuse("OQNRC supports linear constraints only without a global or per-class cap on the same "
2946 "region.", "Region");
2947 const std::size_t C = rg.lincon_A.rows();
2948 bool ok = rg.lincon_A.cols() == K && rg.lincon_b.size() >= C;
2949 sc.pool.assign(K, 0);
2950 sc.Ncap.assign(C, 0);
2951 for (std::size_t r = 0; ok && r < K; ++r) {
2952 double colsum = 0;
2953 for (std::size_t c = 0; c < C; ++c) {
2954 const double a = num_traits<T>::to_double(rg.lincon_A(c, r));
2955 ok = ok && (a == 0 || a == 1);
2956 colsum += a;
2957 if (a == 1) sc.pool[r] = static_cast<int>(c);
2958 }
2959 ok = ok && colsum == 1;
2960 }
2961 for (std::size_t c = 0; ok && c < C; ++c) {
2962 double rowsum = 0;
2963 for (std::size_t r = 0; r < K; ++r) rowsum += num_traits<T>::to_double(rg.lincon_A(c, r));
2964 const double b = num_traits<T>::to_double(rg.lincon_b[c]);
2965 ok = ok && rowsum > 0 && b >= 1 && b == std::rint(b);
2966 if (ok) sc.Ncap[c] = static_cast<int>(b);
2967 }
2968 if (!ok)
2969 return refuse("OQNRC supports linear constraints only as a partition of the classes into groups with "
2970 "unit weights and a positive integer cap per group (dedicated token pools).", "Region");
2971 } else if (gcap > 0 && unset) {
2972 sc.pool.assign(K, 0);
2973 sc.Ncap.assign(1, static_cast<int>(gcap));
2974 } else if (gcap == -1 && allpos) {
2975 sc.pool.assign(K, 0);
2976 sc.Ncap.assign(K, 0);
2977 for (std::size_t r = 0; r < K; ++r) {
2978 sc.pool[r] = static_cast<int>(r);
2979 sc.Ncap[r] = static_cast<int>(capat(r));
2980 }
2981 } else {
2982 return refuse("OQNRC needs either a global cap alone (setGlobalMaxJobs) or a per-class cap on every class "
2983 "(setClassMaxJobs), not both and not a partial set.", "Region");
2984 }
2985 for (std::size_t c = 0; c < L.nchains; ++c) {
2986 int p = -1;
2987 for (std::size_t r = 0; r < K; ++r)
2988 if (L.chains[c][r]) {
2989 if (p >= 0 && sc.pool[r] != p)
2990 return refuse("OQNRC needs class switching to stay within one token pool; a chain here switches "
2991 "between classes with separate caps.", "ClassSwitch");
2992 p = sc.pool[r];
2993 }
2994 }
2995 for (std::size_t g = 0; g < sc.Ncap.size(); ++g) {
2996 double lam = 0;
2997 for (std::size_t r = 0; r < K; ++r)
2998 if (src >= 0 && sc.pool[r] == static_cast<int>(g) && !L.disabled[src][r])
2999 lam += num_traits<T>::to_double(L.rates(static_cast<std::size_t>(src), r));
3000 if (!(lam > 0))
3001 return refuse("OQNRC needs a positive arrival rate into every token pool; pool " + std::to_string(g + 1) +
3002 " has none.", "Structure");
3003 }
3004 return sc;
3005}
3006
3007/** {reason, kind} of `oqnrc_scope`, two empty strings when 'oqnrc' can solve L. */
3008template <class T>
3009std::pair<std::string, std::string> oqnrc_scope_reason(const qn::NetworkStruct<T>& L) {
3010 const OqnrcScope sc = oqnrc_scope(L);
3011 return {sc.reason, sc.kind};
3012}
3013
3014/**
3015 * Port of `solver_oqnrc.m`. Station rows follow the LINE FCR convention: a WAITQ
3016 * arrival blocked at the region waits outside every station, so station QLen
3017 * excludes it. The region row (QNfcr, TNfcr, RNfcr, DropRateNfcr) carries the
3018 * jobs in the region plus those waiting to enter it, the carried throughput,
3019 * their ratio and the rate of lost arrivals (DROP).
3020 */
3021template <class T>
3023 const OqnrcScope sc = oqnrc_scope(L);
3024 if (!sc.reason.empty()) throw UnsupportedError(ErrorKind{sc.kind}, "solver_oqnrc: " + sc.reason);
3025 const std::size_t M = L.nstations, K = L.nclasses;
3026 auto td = [](const T& v) { return num_traits<T>::to_double(v); };
3027 auto fd = [](double v) { return num_traits<T>::from_double(v); };
3028 std::size_t src = M;
3029 std::vector<std::size_t> inner;
3030 for (std::size_t i = 0; i < M; ++i) {
3031 if (L.stations[i].nodetype == qn::NodeType::Source) {
3032 if (src == M) src = i;
3033 } else {
3034 inner.push_back(i);
3035 }
3036 }
3037 const std::size_t nin = inner.size();
3038 std::vector<double> lam(K, 0.0);
3039 for (std::size_t r = 0; r < K; ++r) lam[r] = L.disabled[src][r] ? 0.0 : td(L.rates(src, r));
3040 Matrix<double> A(nin, K, 0.0), S(nin, K, 0.0), SCV(nin, K, 1.0);
3041 const std::size_t srcSf = L.stateful_of_station(src + 1) - 1;
3042 for (std::size_t c = 0; c < L.nchains; ++c) {
3043 const Matrix<T>& Vc = L.visits[c];
3044 double vref = 0, lamc = 0;
3045 for (std::size_t r = 0; r < K; ++r)
3046 if (L.chains[c][r]) {
3047 vref += td(Vc(srcSf, r));
3048 lamc += lam[r];
3049 }
3050 if (vref <= 0) continue;
3051 for (std::size_t r = 0; r < K; ++r)
3052 if (L.chains[c][r])
3053 for (std::size_t k = 0; k < nin; ++k)
3054 A(k, r) = lamc * td(Vc(L.stateful_of_station(inner[k] + 1) - 1, r)) / vref;
3055 }
3056 std::vector<double> nservers(nin, 1.0);
3057 std::vector<bool> isps(nin, false);
3058 for (std::size_t k = 0; k < nin; ++k) {
3059 const std::size_t i = inner[k];
3060 for (std::size_t r = 0; r < K; ++r) {
3061 if (L.disabled[i][r]) continue;
3062 const double mu = td(L.rates(i, r));
3063 S(k, r) = mu > 0 && std::isfinite(mu) ? 1.0 / mu : 0.0;
3064 const double v = td(L.scv(i, r));
3065 SCV(k, r) = std::isfinite(v) ? v : 1.0;
3066 }
3067 const qn::SchedStrategy sch = L.stations[i].sched;
3068 nservers[k] = sch == qn::SchedStrategy::INF ? std::numeric_limits<double>::infinity() : L.stations[i].nservers;
3069 isps[k] = sch == qn::SchedStrategy::PS;
3070 }
3071 const pfqn::OqnrcResult res =
3072 pfqn::pfqn_oqnrc(lam, A, S, SCV, nservers, isps, sc.pool, sc.Ncap, sc.waitq, opt.tol, opt.iter_max);
3073 const T zero = num_traits<T>::from_int(0);
3074 MvaSolution<T> out;
3075 out.Q = Matrix<T>(M, K, zero);
3076 out.U = Matrix<T>(M, K, zero);
3077 out.R = Matrix<T>(M, K, zero);
3078 out.Tp = Matrix<T>(M, K, zero);
3079 for (std::size_t k = 0; k < nin; ++k)
3080 for (std::size_t r = 0; r < K; ++r) {
3081 out.Q(inner[k], r) = fd(res.Q(k, r));
3082 out.U(inner[k], r) = fd(res.U(k, r));
3083 out.R(inner[k], r) = fd(res.R(k, r));
3084 out.Tp(inner[k], r) = fd(res.T(k, r));
3085 }
3086 for (std::size_t r = 0; r < K; ++r) out.Tp(src, r) = fd(lam[r]);
3087 out.X.assign(L.nchains, zero);
3088 out.C.assign(L.nchains, zero);
3089 for (std::size_t c = 0; c < L.nchains; ++c) {
3090 double x = 0, qs = 0;
3091 for (std::size_t r = 0; r < K; ++r)
3092 if (L.chains[c][r]) {
3093 x += res.X[r];
3094 for (std::size_t k = 0; k < nin; ++k) qs += res.Q(k, r);
3095 }
3096 out.X[c] = fd(x);
3097 out.C[c] = fd(x > 0 ? qs / x : 0.0);
3098 }
3099 out.QNfcr.assign(K, zero);
3100 out.TNfcr.assign(K, zero);
3101 out.RNfcr.assign(K, zero);
3102 out.DropRateNfcr.assign(K, zero);
3103 for (std::size_t r = 0; r < K; ++r) {
3104 double qs = res.Qext[r];
3105 for (std::size_t k = 0; k < nin; ++k) qs += res.Q(k, r);
3106 out.QNfcr[r] = fd(qs);
3107 out.TNfcr[r] = fd(res.X[r]);
3108 out.RNfcr[r] = fd(res.X[r] > 0 ? qs / res.X[r] : 0.0);
3109 out.DropRateNfcr[r] = fd(lam[r] * res.Ploss[r]);
3110 }
3111 out.method = "oqnrc";
3112 out.iter = res.iter;
3113 out.converged = true;
3114 out.lG = std::numeric_limits<double>::quiet_NaN();
3115 return out;
3116}
3117
3118/**
3119 * Port of `isBasModel` in `solver_mva_analyzer.m`: a closed single-CHAIN model
3120 * with at least one blocking-after-service drop rule, which SQD handles and
3121 * neither exact MVA nor AMVA does. This is the DISPATCH test.
3122 */
3123template <class T>
3125 if (L.nchains != 1 || !(L.nclosedjobs() > 0.0) || L.droprule.empty()) return false;
3126 for (const auto& c : L.classes)
3127 if (std::isinf(c.population)) return false; // an open class present
3128 for (const auto& row : L.droprule)
3129 for (lang::DropStrategy s : row)
3130 if (s == lang::DropStrategy::BAS) return true;
3131 return false;
3132}
3133
3134/**
3135 * Port of `matlab/src/api/sn/sn_is_bas_model.m`: a closed single-CLASS model
3136 * with a BAS drop rule. This is the GATE test, and it is deliberately NARROWER
3137 * than mva_is_bas_model above: the reference keeps two predicates because SQD's
3138 * Smith decomposition models ONE circulating population, so a chain built from
3139 * several classes is dispatched to SQD but is NOT exempted from the
3140 * finite-capacity refusal. Collapsing the two would let a multiclass BAS model
3141 * past the gate on the strength of a decomposition that does not represent it.
3142 */
3143template <class T>
3145 if (L.nclasses != 1 || !(L.nclosedjobs() > 0.0) || L.droprule.empty()) return false;
3146 for (const auto& c : L.classes)
3147 if (std::isinf(c.population)) return false; // an open class present
3148 for (const auto& row : L.droprule)
3149 for (lang::DropStrategy s : row)
3150 if (s == lang::DropStrategy::BAS) return true;
3151 return false;
3152}
3153
3154/**
3155 * Port of `matlab/src/api/sn/sn_is_mm1k_loss.m`: a single-class open
3156 * Source-Queue-Sink system whose queue is a single-server exponential M/M/1/K
3157 * with tail drop. Both the MVA moment-based branch (qsys_mg1k_loss_mgs) and the
3158 * NC probability-based one (qsys_mm1k_loss) gate their finite-capacity loss
3159 * path on it, and it is the one shape whose finite buffer IS honoured here.
3160 */
3161template <class T>
3163 if (L.nclasses != 1 || L.nclosedjobs() != 0.0 || L.nodes.size() != 3) return false;
3164 std::size_t nsrc = 0, nq = 0, nsnk = 0;
3165 for (const qn::NodeDef& nd : L.nodes) {
3166 if (nd.nodetype == qn::NodeType::Source) ++nsrc;
3167 else if (nd.nodetype == qn::NodeType::Queue) ++nq;
3168 else if (nd.nodetype == qn::NodeType::Sink) ++nsnk;
3169 }
3170 if (nsrc != 1 || nq != 1 || nsnk != 1) return false;
3171 std::size_t qist = 0, sist = 0;
3172 for (std::size_t i = 0; i < L.stations.size(); ++i) {
3173 if (L.stations[i].nodetype == qn::NodeType::Queue) qist = i + 1;
3174 else if (L.stations[i].nodetype == qn::NodeType::Source) sist = i + 1;
3175 }
3176 if (qist == 0 || sist == 0) return false;
3177 if (L.stations[qist - 1].nservers != 1.0) return false;
3178 if (L.droprule.size() < qist || L.droprule[qist - 1].empty()) return false;
3179 if (L.droprule[qist - 1][0] != lang::DropStrategy::DROP) return false;
3180 if (L.cap.size() < qist) return false;
3181 if (!std::isfinite(L.cap[qist - 1]) || L.cap[qist - 1] <= 0.0) return false;
3182 const double scvs = num_traits<T>::to_double(L.scv(sist - 1, 0));
3183 const double scvq = num_traits<T>::to_double(L.scv(qist - 1, 0));
3184 if (std::fabs(scvs - 1.0) > 1e-6 || std::fabs(scvq - 1.0) > 1e-6) return false;
3185 // A DECLARED STATE DEPENDENCE IS NOT AN M/M/1/K: both closed forms read ONE
3186 // service rate, so a station carrying lldscaling, cdscaling or jdscaling would
3187 // be answered with the UNSCALED queue. Kept in step with
3188 // NetworkStruct::is_mm1k_loss, which states the same rule for the NC side.
3189 const qn::Station<T>& qst = L.stations[qist - 1];
3190 if (!qst.lldscaling.empty() || static_cast<bool>(qst.cdscaling) ||
3191 static_cast<bool>(qst.jdscaling))
3192 return false;
3193 return true;
3194}
3195
3196/**
3197 * Conservative form of the branch test in solver_amva: true when this model may be solved by
3198 * the product-form AMVA kernels rather than by solver_amvald. The mixed case is reported true
3199 * for every resolved method, while the branch itself takes it only for some, so a caller is
3200 * never told that solver_amvald will run when it might not.
3201 */
3202template <class T>
3204 bool has_ld = false;
3205 for (const auto& st : L.stations)
3206 if (!st.lldscaling.empty() || st.cdscaling || st.jdscaling) has_ld = true;
3207 return L.has_product_form_not_het_fcfs() && !has_ld &&
3208 (!L.has_open_classes() || L.has_product_form());
3209}
3210
3211/**
3212 * True when the MVA path this model already dispatches to carries a class-level interlock
3213 * matrix (Franks 1999, Eq. 4.7) itself, so that supplying one does not silently move the model
3214 * to a DIFFERENT algorithm.
3215 *
3216 * Only two kernels implement the correction: pfqn_mva (exact, closed single-server) and the
3217 * AMVA forward step of solver_amvald. A model that would otherwise be solved by exact
3218 * multiserver or mixed MVA, or by the product-form AMVA kernels, cannot take the matrix
3219 * without swapping its algorithm, and the swap is worth far more than the correction it
3220 * carries: inside SolverLN it can turn a converging Picard iteration into a limit cycle. A
3221 * caller holding a matrix such a model cannot carry must apply its own correction instead.
3222 */
3223template <class T>
3225 // A fork-join model is solved on its MMT/HT transformation, whose auxiliary classes the
3226 // class-indexed matrix does not cover and whose dispatch this test cannot see, so no path
3227 // of it carries the matrix.
3228 for (const auto& nd : L.nodes)
3229 if (nd.nodetype == qn::NodeType::Fork) return false;
3230 const std::string& method = opt.method;
3231 bool has_open = false, has_closed = false, integral = true, has_finite_server = false;
3232 double maxsrv = -1.0, Nsum = 0.0;
3233 for (const auto& c : L.classes) {
3234 if (std::isinf(c.population)) {
3235 has_open = true;
3236 } else {
3237 if (c.population > 0.0) has_closed = true;
3238 if (c.population != std::floor(c.population)) integral = false;
3239 }
3240 Nsum += c.population;
3241 }
3242 for (const auto& st : L.stations)
3243 if (std::isfinite(st.nservers)) {
3244 has_finite_server = true;
3245 maxsrv = std::max(maxsrv, st.nservers);
3246 }
3247 // pfqn_mva takes the matrix for a closed single-server model, and for nothing else
3248 const bool pfqn_mva_can_take_it = !has_open && integral && (maxsrv < 0.0 || maxsrv <= 1.0);
3249
3250 if (method == "exact" || method == "mva") return pfqn_mva_can_take_it;
3251 static const char* amva_methods[] = {
3252 "amva", "bs", "qd", "qli", "fli", "lin", "qdlin", "sqni",
3253 "gflin", "egflin", "ab", "schmidt", "schmidt-ext", "tay", "scat", "aql",
3254 "qsa", "lcp", "chow", "pamb", "pami", "pamt", "clust", "dmlin",
3255 "priomva"};
3256 for (const char* m : amva_methods)
3257 if (method == m) return !amva_uses_pf_kernels(L); // only solver_amvald carries it
3258 if (method == "default") {
3259 if (mva_is_bas_model(L)) return false; // solver_sqd has no interlock term
3260 const bool exact_mixed = has_open && has_closed && has_finite_server && maxsrv == 1.0 &&
3261 L.has_product_form() && integral;
3262 const bool exact_small = L.nchains <= 4 && Nsum <= 20.0 && L.has_product_form() &&
3264 if (exact_mixed || exact_small) return pfqn_mva_can_take_it;
3265 return !amva_uses_pf_kernels(L);
3266 }
3267 // mvac, sqd, sum, qna, rqna and rqt reach neither kernel
3268 return false;
3269}
3270
3271// ---------------------------------------------------------------------------
3272// solver_mva_analyzer: the `default` ladder
3273// ---------------------------------------------------------------------------
3274
3275/** Port of solver_mva_analyzer.m, `default` and the explicit method names. */
3276template <class T>
3278 const Matrix<T>& init_sol) {
3280 bool converged = true;
3281
3282 if (opt.method == "exact" || opt.method == "mva") return solver_mva(L, d, opt);
3283 if (opt.method == "sum" || opt.method == "esum") return solver_mva_sum(L, opt);
3284 if (opt.method == "sqd") return solver_sqd(L, d);
3285 if (opt.method == "mvablo") return solver_mvablo(L, opt);
3286 if (opt.method == "debemva") return solver_debemva(L, opt);
3287 if (opt.method == "oqnrc") return solver_oqnrc(L, opt);
3288 // `qna` is handled one level up, in mva_dispatch, purely so that
3289 // solver_qna.h need not include this header; reaching it here means the
3290 // analyzer was called directly, which no ported path does.
3291 if (opt.method == "qna")
3292 throw UnsupportedError(ErrorKind{"Method"},
3293 "solver_mva_analyzer: 'qna' is dispatched by mva_dispatch, not by the analyzer");
3294 if (opt.method == "rqt")
3295 throw UnsupportedError(ErrorKind{"Method"},
3296 "solver_mva_analyzer: 'rqt' is dispatched by mva_dispatch, not by the analyzer");
3297 if (opt.method == "rqna")
3298 throw UnsupportedError(ErrorKind{"Method"},
3299 "solver_mva_analyzer: 'rqna' is dispatched by mva_dispatch, not by the analyzer");
3300 if (opt.method != "default") {
3301 MvaOptions o = opt;
3302 return solver_amva(L, d, o, init_sol, converged);
3303 }
3304
3305 // BAS: neither exact MVA nor AMVA represents the blocked-server time, so the
3306 // reference sends it to SQD before every product-form test below.
3307 if (mva_is_bas_model(L)) return solver_sqd(L, d);
3308
3309 // Force AMVA for class- or joint-dependent models: exact MVA does not
3310 // support them (solver_mva_analyzer.m:63-67).
3311 for (const auto& st : L.stations)
3312 if (st.cdscaling || st.jdscaling) {
3313 MvaOptions o = opt;
3314 return solver_amva(L, d, o, init_sol, converged);
3315 }
3316
3317 // An interlock matrix that exact MVA cannot honour sends the model to AMVA, which
3318 // applies the same Eq. (4.7) correction to the arrival-instant queue length: pfqn_mva
3319 // carries it for closed single-server models only.
3320 bool il_needs_amva = false;
3321 if (!opt.interlock.empty()) {
3322 il_needs_amva = L.has_open_classes();
3323 for (const auto& st : L.stations)
3324 if (std::isfinite(st.nservers) && st.nservers > 1.0) il_needs_amva = true;
3325 }
3326
3327 // mixed open+closed exact-MVA gate rationale: see _kb/06-solver-catalog.md (cpp port notes: solver_mva.h)
3328 if (!il_needs_amva && L.has_open_classes()) {
3329 bool anyopen = false, anyclosed = false, integral = true;
3330 for (const auto& cl : L.classes) {
3331 if (std::isinf(cl.population)) {
3332 anyopen = true;
3333 continue;
3334 }
3335 if (cl.population > 0.0) anyclosed = true;
3336 if (cl.population != std::floor(cl.population)) integral = false;
3337 }
3338 bool anyfinite = false, allone = true;
3339 for (const auto& st : L.stations)
3340 if (std::isfinite(st.nservers)) {
3341 anyfinite = true;
3342 if (st.nservers != 1.0) allone = false;
3343 }
3344 if (anyopen && anyclosed && anyfinite && allone && integral && L.has_product_form())
3345 return solver_mva(L, d, opt);
3346 }
3347
3348 // An OPEN product-form network is a set of INDEPENDENT M/M/c queues
3349 // (Jackson), so the exact per-station Erlang-C answer costs no more than the
3350 // approximation and there is no population to iterate over. AMVA would apply
3351 // the Seidmann multiserver transform, which replaces the c servers by one
3352 // c-times-faster server plus a delay: on Source Exp(2) -> Queue(PS, c=3,
3353 // Exp(1)) -> Queue(PS, Exp(8)) that reports QLen = 2.0 at the first queue,
3354 // which is exactly the offered load a = lambda/mu, i.e. NO WAITING AT ALL,
3355 // against the exact M/M/3 value 2.888889. c = 1 is admitted here too: egflin is a
3356 // fixed point that only CONVERGES towards rho/(1-rho), leaving 3.5e-5 on a
3357 // two-station tandem and 1.1e-3 on a four-station one, against a free closed form.
3358 if (!il_needs_amva) {
3359 bool all_open = true, has_finite_server = false, has_lld = false;
3360 for (const auto& cl : L.classes)
3361 if (!std::isinf(cl.population)) all_open = false;
3362 for (const auto& st : L.stations) {
3363 if (std::isfinite(st.nservers) && st.nservers >= 1.0) has_finite_server = true;
3364 if (!st.lldscaling.empty()) has_lld = true;
3365 }
3366 // The STRICT predicate is conjoined because solver_mva refuses anything
3367 // sn_has_product_form rejects: the relaxed one is blind to blocking,
3368 // fork-join, state-dependent routing and to per-class FCFS means that
3369 // differ WITHIN a chain, so at c = 1 it admitted class-switching models
3370 // and LQN async layers that the exact routine then threw on.
3371 if (all_open && has_finite_server && !has_lld && L.has_product_form_not_het_fcfs() &&
3373 return solver_mva(L, d, opt);
3374 }
3375
3376 double Nsum = 0.0;
3377 for (std::size_t c = 0; c < L.nchains; ++c) Nsum += d.Nchain[c];
3378 if (!il_needs_amva && L.nchains <= 4 && Nsum <= 20.0 && L.has_product_form() &&
3380 return solver_mva(L, d, opt);
3381
3382 MvaOptions o = opt;
3383 return solver_amva(L, d, o, init_sol, converged);
3384}
3385
3386} // namespace mva
3387} // namespace line
3388
3389#endif // LINE_SOLVERS_MVA_SOLVER_MVA_H
InputError(const std::string &what)
Definition error.h:105
std::size_t cols() const
Definition matrix.h:90
std::size_t rows() const
Definition matrix.h:89
bool empty() const
Definition matrix.h:92
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
bool has_multi_class_heter_fcfs() const
std::size_t stateful_of_station(std::size_t st) const
std::size_t nof_stateful() const
std::vector< std::size_t > stateful_nodes
1-based node indices, ascending
std::vector< std::vector< Distrib< T > > > service
service[i][r], 0-based station and class; a disabled entry marks a pair never visited.
std::vector< std::vector< bool > > chains
(nchains x nclasses)
std::vector< bool > fjauxclass
sn.fjauxclass: (nclasses+1, 1-based) true where the class is an MMT AUXILIARY OPEN class,...
std::vector< std::vector< bool > > disabled
Matrix< T > rt
sn.rt and sn.rtnodes: the class-expanded routing.
std::vector< double > cap
sn.cap and sn.classcap: the total and per-class buffers.
std::vector< JobClass > classes
bool has_product_form_not_het_fcfs(bool check_means=true) const
Port of sn_has_product_form_not_het_fcfs: LCFS is excluded, and at FCFS the service must be exponenti...
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< std::vector< std::size_t > > inchain
1-based class indices per chain
std::vector< NodeDef > nodes
every node, in creation order
bool has_sd_routing() const
sn_has_sd_routing: RROBIN, WRROBIN, JSQ, SQ or SDR at some node.
bool sched_is_product_form() const
std::vector< std::vector< DropStrategy > > droprule
bool has_blocking() const
Some station can REFUSE a job: its own buffer BINDS, or a finite capacity region caps a set of statio...
std::vector< Matrix< T > > visits
(nchains) each (nstateful x nclasses)
bool has_homogeneous_scheduling(SchedStrategy strategy) const
Port of sn_has_homogeneous_scheduling: true when EVERY station uses strategy, the reference's length(...
double nclosedjobs() const
sn.nclosedjobs: the total population of the closed classes.
std::vector< std::pair< std::size_t, std::size_t > > fj
fj(f,j): the Join node j that closes the Fork node f, 1-based.
bool has_product_form() const
sn_has_product_form, conjunct for conjunct.
bool has_fractional_populations() const
std::vector< Region > regions
static void loop(const char *fmt,...)
Announce an iteration loop and reset its reporting budget.
static void iter(long k, const char *fmt,...)
Report iteration k of the current loop.
static bool owns_log()
True only inside the OUTERMOST open run; gates EMISSION.
The exception types the port throws.
Running progress log of a LINE solver run (the "solver console").
options.timeout: one wall-clock budget per top-level solve, on a per-THREAD deadline stack.
The option and result types every MVA analyzer shares.
bool sn_has_product_form(const qn::NetworkStruct< T > &sn)
Port of sn_has_product_form.
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
DropStrategy
Blocking and loss rules, with the values of MATLAB DropStrategy.
Definition lang_types.h:465
const char * sched_to_text(SchedStrategy s)
Definition lang_types.h:248
std::function< std::vector< T >(const std::vector< T > &)> CdScaling
A class-dependent scaling map, sn.cdscaling.
Definition lang_types.h:794
std::pair< std::string, std::string > mvablo_scope_reason(const qn::NetworkStruct< T > &L)
Port of mvablo_scope_reason.m: why method 'mvablo' cannot solve L, as {reason, kind}...
PfChainParams< T > sn_get_product_form_chain_params(const qn::NetworkStruct< T > &L, const ChainDemands< T > &d)
Port of sn_get_product_form_chain_params.
Definition sn_chain.h:351
MvaSolution< T > solver_oqnrc(const qn::NetworkStruct< T > &L, const MvaOptions &opt)
Port of solver_oqnrc.m.
MvaSolution< T > solver_mva(const qn::NetworkStruct< T > &L, const ChainDemands< T > &d, const MvaOptions &opt)
Port of solver_mva.m, closed and mixed product-form networks.
Definition solver_mva.h:161
MvaSolution< T > solver_mvablo(const qn::NetworkStruct< T > &L, const MvaOptions &opt)
Port of solver_mvablo.m.
MvaSolution< T > solver_amvald(const qn::NetworkStruct< T > &L, const ChainDemands< T > &d, const MvaOptions &opt, const std::string &method, bool &converged, const Matrix< T > &init_sol=Matrix< T >())
Port of solver_amvald.m together with solver_amvald_forward.m, restricted to the INF / PS / FCFS-fami...
Definition solver_mva.h:493
std::string mva_schmidt_ext_reason(const std::vector< double > &njobs, const std::vector< bool > &fcfs, const std::string &method)
The extended Schmidt method needs a customer of every class to tag.
Definition mva_types.h:233
bool sn_is_mm1k_loss(const qn::NetworkStruct< T > &L)
Port of matlab/src/api/sn/sn_is_mm1k_loss.m: a single-class open Source-Queue-Sink system whose queue...
bool amva_uses_pf_kernels(const qn::NetworkStruct< T > &L)
Conservative form of the branch test in solver_amva: true when this model may be solved by the produc...
std::string amva_method_alias(const std::string &m)
The amva.
OqnrcScope oqnrc_scope(const qn::NetworkStruct< T > &L)
Port of oqnrc_scope_reason.m: why method 'oqnrc' cannot solve L, with the error kind of the refusal,...
bool sn_is_bas_model(const qn::NetworkStruct< T > &L)
Port of matlab/src/api/sn/sn_is_bas_model.m: a closed single-CLASS model with a BAS drop rule.
Matrix< T > sn_interlock_chain(const qn::NetworkStruct< T > &L, const std::vector< std::vector< double > > &ILclass)
Aggregate a class-indexed interlock matrix to the chain basis the MVA analyzers work in.
Definition sn_chain.h:430
MvaSolution< T > solver_mva_sum(const qn::NetworkStruct< T > &L, const MvaOptions &opt)
Port of solver_mva_sum.m: the SUM / ESUM summation method (Bolch et al., Secs.
bool mva_is_bas_model(const qn::NetworkStruct< T > &L)
Port of isBasModel in solver_mva_analyzer.m: a closed single-CHAIN model with at least one blocking-a...
std::pair< std::string, std::string > debemva_scope_reason(const qn::NetworkStruct< T > &L)
Port of debemva_scope_reason.m: why method 'debemva' cannot solve L, as {reason, kind}...
ClassResults< T > sn_deaggregate_chain_results(const qn::NetworkStruct< T > &L, const ChainDemands< T > &d, const Matrix< T > &Qchain, const Matrix< T > &Uchain, const Matrix< T > &Rchain, const Matrix< T > &Tchain, const std::vector< T > &Xchain)
Port of sn_deaggregate_chain_results.
Definition sn_chain.h:227
MvaSolution< T > solver_sqd(const qn::NetworkStruct< T > &L, const ChainDemands< T > &d)
Port of solver_sqd.m: Smith queue decomposition for blocking-after-service.
std::string mva_closed_population_reason(const qn::NetworkStruct< T > &L, const std::string &method)
The closed-population AMVA family: an open chain, or a network outside strict product form,...
Definition mva_types.h:159
MvaSolution< T > solver_mvald(const qn::NetworkStruct< T > &L, const MvaOptions &opt)
Port of solver_mvald.m: exact MVA on a load-dependent model, through pfqn_mvaldmx.
MvaSolution< T > solver_mva_lcfsqn(const qn::NetworkStruct< T > &L, std::size_t lcfs_ist, std::size_t lcfspr_ist)
Port of solver_mva_lcfsqn.m: the closed two-station LCFS + LCFS-PR network.
Definition solver_mva.h:94
MvaSolution< T > solver_debemva(const qn::NetworkStruct< T > &L, const MvaOptions &opt)
Port of solver_debemva.m.
MvaSolution< T > solver_amva(const qn::NetworkStruct< T > &L, const ChainDemands< T > &d, MvaOptions opt, const Matrix< T > &init_sol, bool &converged)
bool mva_carries_interlock(const qn::NetworkStruct< T > &L, const MvaOptions &opt)
True when the MVA path this model already dispatches to carries a class-level interlock matrix (Frank...
std::pair< std::string, std::string > oqnrc_scope_reason(const qn::NetworkStruct< T > &L)
{reason, kind} of oqnrc_scope, two empty strings when 'oqnrc' can solve L.
MvaSolution< T > solver_mva_analyzer(const qn::NetworkStruct< T > &L, const MvaOptions &opt, const Matrix< T > &init_sol)
Port of solver_mva_analyzer.m, default and the explicit method names.
ChainDemands< T > sn_get_demands_chain(const qn::NetworkStruct< T > &L)
Port of sn_get_demands_chain.
Definition sn_chain.h:63
SqdResult< T > npfqn_sqd(const std::vector< T > &ST, const std::vector< T > &V, const std::vector< T > &cap, const std::vector< bool > &isDelay, const Matrix< T > &rt, const std::vector< std::size_t > &stationToStateful, std::size_t nclasses, int N, const SqdOptions< T > &opt)
Smith Queue Decomposition (SQD): approximate MVA for closed networks under Blocking-After-Service (ma...
Definition npfqn_sqd.h:432
SqniResult< T > pfqn_sqni(const std::vector< T > &N, const std::vector< T > &L, const std::vector< T > &Z)
Square-root non-iterative (SQNI) approximation for a single queueing station with per-class delay.
Definition pfqn_sqni.h:57
SchmidtExtResult< T > pfqn_schmidt_ext(const Matrix< T > &D, const std::vector< int > &N, const Matrix< int > &S, const std::vector< SchedStrategy > &sched)
Extended Schmidt MVA with queue-aware alpha corrections.
LinearizerResult< T > pfqn_scat(const Matrix< T > &L, const std::vector< int > &N, const Matrix< T > &Z, const std::vector< SchedStrategy > &type, double tol, int maxiter, const Matrix< T > &QN0)
Neuse-Chandy SCAT (Self-Correcting Approximation Technique) approximate MVA.
Definition pfqn_scat.h:71
AmvaResult< T > pfqn_clust(const Matrix< T > &L, const std::vector< T > &N, const std::vector< T > &Z, const std::vector< std::vector< std::size_t > > &subnets, const std::vector< std::vector< std::size_t > > &localclasses, ClustInner inner=ClustInner::Linearizer, double tol=1e-6, std::size_t maxiter=1000)
de Souza e Silva-Lavenberg-Muntz Clustering Approximation (CA).
Definition pfqn_clust.h:214
OqnrcResult pfqn_oqnrc(const std::vector< double > &lam, const Matrix< double > &A, const Matrix< double > &S, const Matrix< double > &SCV, const std::vector< double > &nservers, const std::vector< bool > &isps, const std::vector< int > &pool, const std::vector< int > &Ncap, bool waitq, double tol, int iter_max)
Runs OQNRC.
Definition pfqn_oqnrc.h:179
AmvaResult< T > pfqn_pam(const Matrix< T > &L, const std::vector< T > &N, const std::vector< T > &Z, PamVariant variant=PamVariant::Basic)
Hsieh-Lam Proportional Approximation Methods (PAMB / PAMI / PAMT).
Definition pfqn_pam.h:55
MvaResult< T > pfqn_mvams(const std::vector< T > &lambda, const Matrix< T > &L, const std::vector< int > &N, const Matrix< T > &Z, const std::vector< int > &mi, const std::vector< int > &S)
General-purpose exact MVA for mixed networks with multiserver stations.
Definition pfqn_mvams.h:893
constexpr int OPEN_CLASS
Marks an open (infinite-population) class in a population vector.
Definition pfqn_mvams.h:74
LinearizerMxMethod
Which Linearizer variant solves the closed subnetwork.
MvabloResult< T > pfqn_mvablo(long N, const std::vector< T > &S, const Matrix< T > &P, const std::vector< double > &K, std::vector< bool > isdelay, double tol=1e-4, int iter_max=1000)
Runs MVABLO.
Definition pfqn_mvablo.h:75
std::vector< T > pfqn_jdfun(const Matrix< T > &nvec, const std::vector< JdScaling< T > > &jdscaling, std::size_t classIdx)
AMVA joint-dependence function for non-product-form scaling.
Definition pfqn_jdfun.h:59
LinearizerResult< T > pfqn_conwayms(const Matrix< T > &L, const std::vector< int > &N, const Matrix< T > &Z, const std::vector< int > &nservers, const std::vector< SchedStrategy > &type, double tol, int maxiter, const Matrix< T > &QN0)
Conway's multiserver Linearizer for chain-dependent FCFS queues (Conway 1989, "Fast Approximate Solut...
LinearizerResult< T > pfqn_dmlin(const Matrix< T > &L, const std::vector< int > &N, const Matrix< T > &Z, const std::vector< SchedStrategy > &type, double tol, int maxiter, const Matrix< T > &QN0, int npasses=3)
de Souza e Silva-Muntz Improved Linearizer (IL).
Definition pfqn_dmlin.h:132
AmvaResult< T > pfqn_tay(const Matrix< T > &L, const std::vector< T > &N, const std::vector< T > &Z, double tol=1e-6, std::size_t maxiter=1000, const Matrix< T > &QN0=Matrix< T >())
Tay's arrival-instant approximate MVA.
Definition pfqn_tay.h:83
DebemvaResult< T > pfqn_debemva(long N, const std::vector< T > &S, const Matrix< T > &P, const std::vector< double > &K, std::vector< bool > isdelay, double tol=0.0, long iter_max=100000)
Runs debeMVA.
AmvaResult< T > pfqn_qsa(const Matrix< T > &L, const std::vector< T > &N, const std::vector< T > &Z, const std::vector< AmvaSched > &type, double tol=1e-10, std::size_t maxiter=100, int levels=3)
Queue-Shift Approximation (QSA) for closed product-form networks.
Definition pfqn_qsa.h:221
std::vector< T > pfqn_lldfun(const std::vector< T > &n, const Matrix< T > &lldscaling, const std::vector< double > &nservers)
AMVA-QD limited-load-dependence function.
Definition pfqn_lldfun.h:81
SchmidtResult< T > pfqn_schmidt(const Matrix< T > &D, const std::vector< int > &N, const Matrix< int > &S, const std::vector< SchedStrategy > &sched, const Matrix< T > &v)
Schmidt's MVA for closed networks with general scheduling disciplines and class-dependent multiserver...
AmvaResult< T > pfqn_chow(const Matrix< T > &L, const std::vector< T > &N, const std::vector< T > &Z, const std::vector< AmvaSched > &type, double tol=1e-6, std::size_t maxiter=1000, const Matrix< T > &QN0=Matrix< T >(), ChowVariant variant=ChowVariant::Forward)
JMT-compatible Chow approximate MVA.
Definition pfqn_chow.h:42
MvaResult< T > pfqn_mvaldmx(const std::vector< T > &lambda, const Matrix< T > &D, const std::vector< int > &N, const Matrix< T > &Z, const Matrix< T > &mu)
Exact MVA for mixed open/closed networks with limited load dependence.
Definition pfqn_mvams.h:577
constexpr int kOpenClass
Population sentinel marking an open class, standing in for MATLAB's Inf.
LinearizerResult< T > pfqn_linearizermx(const std::vector< T > &lambda, const Matrix< T > &L, const std::vector< int > &N, const Matrix< T > &Z, const std::vector< int > &nservers, const std::vector< SchedStrategy > &type, double tol, int maxiter, LinearizerMxMethod method, const Matrix< T > &QN0)
Linearizer for mixed open/closed queueing networks.
AmvaResult< T > pfqn_bs(const Matrix< T > &L, const std::vector< T > &N, const std::vector< T > &Z, const std::vector< AmvaSched > &type, double tol=1e-6, std::size_t maxiter=1000, const Matrix< T > &QN0=Matrix< T >())
Bard-Schweitzer approximate MVA.
Definition pfqn_bs.h:73
AbAmvaResult< T > pfqn_ab_amva(const Matrix< T > &S, const std::vector< int > &N, const Matrix< T > &v, const std::vector< int > &nservers, const std::vector< SchedStrategy > &sched, bool fcfsSchmidt, AbMarginalMethod method)
Akyildiz-Bolch approximate MVA for multi-server BCMP networks.
AmvaResult< T > pfqn_lcp(const Matrix< T > &L, const std::vector< T > &N, const std::vector< T > &Z, const std::vector< AmvaSched > &type, double tol=1e-6, std::size_t maxiter=1000, const Matrix< T > &QN0=Matrix< T >())
Bard Large Customer Population (LCP) approximate MVA.
Definition pfqn_lcp.h:57
AmvaResult< T > pfqn_aql(const Matrix< T > &L, const std::vector< T > &N, const std::vector< T > &Z, double tol=1e-7, std::size_t maxiter=1000)
Aggregate Queue Length (AQL) approximate MVA.
Definition pfqn_aql.h:51
PamVariant
Which of the three proportional approximations to run.
Definition pfqn_pam.h:46
std::vector< T > pfqn_cdfun(const Matrix< T > &nvec, const std::vector< CdScaling< T > > &cdscaling, std::size_t classIdx)
AMVA-QD class-dependence function.
Definition pfqn_cdfun.h:56
MvaResult< T > pfqn_mvams_ilock(const std::vector< T > &lambda, const Matrix< T > &L, const std::vector< int > &N, const Matrix< T > &Z, const std::vector< int > &mi, const std::vector< int > &S, const Matrix< T > &IL)
MVA entry point for models carrying the interlocked-flow correction.
Definition pfqn_mvams.h:993
LcfsMvaResult< T > pfqn_lcfsqn_mva(const std::vector< T > &alpha, const std::vector< T > &beta, const std::vector< int > &N)
Exact mean value analysis of the two-station multiclass LCFS network of Casale, QUESTA 2026 (station ...
@ Ab
the Akyildiz-Bolch weight function
SumClosedResult< T > sum_closed(const Matrix< T > &L, const std::vector< long > &N, const std::vector< T > &Z, const std::vector< Servers > &mi, const Matrix< T > &scv, const SumOptions &options=SumOptions())
Summation method (SUM) and its extension (ESUM) for closed queueing networks, including non-product-f...
Definition sum_closed.h:196
SumClosingResult< T > sum_closing(const std::vector< T > &lambda0, const std::vector< T > &scva, const Matrix< T > &L, const std::vector< Servers > &mi, const Matrix< T > &scv, const std::vector< long > &N, const std::vector< T > &Z, const ClosingOptions &options=ClosingOptions())
Closing method for open and mixed non-product-form queueing networks, solved with the summation metho...
Definition sum_closing.h:81
bool timeout_exceeded()
The checkpoint: true when the innermost budget has run out, marking it tripped.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
T num_pow_int(const T &base, unsigned e)
Integer power, valid in any field (no transcendental requirement).
Definition number.h:204
std::vector< T > ones(std::size_t n)
Column vector of ones, the ubiquitous e in MAP algebra.
Definition linalg.h:104
A queueing network and its refreshed NetworkStruct.
Smith Queue Decomposition (SQD): approximate MVA for closed networks under Blocking-After-Service (ma...
Akyildiz-Bolch approximate MVA for multi-server BCMP networks.
Aggregate Queue Length (AQL) approximate MVA.
Bard-Schweitzer approximate MVA.
AMVA-QD class-dependence function.
JMT-compatible Chow approximate MVA.
de Souza e Silva-Lavenberg-Muntz Clustering Approximation (CA).
Conway's multiserver Linearizer for chain-dependent FCFS queues (Conway 1989, "Fast Approximate Solut...
debeMVA: MVA-based approximation of closed networks with finite (BAS) buffers.
de Souza e Silva-Muntz Improved Linearizer (IL).
AMVA joint-dependence function for non-product-form scaling.
Exact mean value analysis of the two-station multiclass LCFS network of Casale, QUESTA 2026 (station ...
Bard Large Customer Population (LCP) approximate MVA.
Linearizer for mixed open/closed queueing networks.
AMVA-QD limited-load-dependence function.
MVABLO: approximate MVA for closed networks with Blocking-After-Service (BAS).
Exact Mean Value Analysis for mixed open/closed networks with multiserver stations.
OQNRC: approximate MVA for open queueing networks with restricted capacity.
Hsieh-Lam Proportional Approximation Methods (PAMB / PAMI / PAMT).
Queue-Shift Approximation (QSA) for closed product-form networks.
Neuse-Chandy SCAT (Self-Correcting Approximation Technique) approximate MVA.
Schmidt's MVA for closed networks with general scheduling disciplines and class-dependent multiserver...
Extended Schmidt MVA with queue-aware alpha corrections.
Square-root non-iterative (SQNI) approximation for a single queueing station with per-class delay.
Tay's arrival-instant approximate MVA.
Chain aggregation and de-aggregation.
Ports of the sn_has_* / sn_is_* predicate family of matlab/src/api/sn.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
The chain-level view of a layer, as sn_get_demands_chain returns it.
Definition sn_chain.h:46
std::vector< std::size_t > refstatchain
(C) 1-based reference station
Definition sn_chain.h:53
std::vector< double > Nchain
(C) population, infinite for an open chain
Definition sn_chain.h:51
Matrix< T > STchain
(M x C) mean service time
Definition sn_chain.h:48
Matrix< T > Lchain
(M x C) demand
Definition sn_chain.h:47
Matrix< T > Vchain
(M x C) visits
Definition sn_chain.h:49
Matrix< T > SCVchain
(M x C)
Definition sn_chain.h:52
Class-level results, as sn_deaggregate_chain_results returns them.
Definition sn_chain.h:204
std::vector< T > C
Definition sn_chain.h:206
std::vector< T > X
Definition sn_chain.h:206
The options SolverMVA reads.
Definition mva_types.h:32
std::string multiserver
Definition mva_types.h:37
Class-level results, the [Q,U,R,T,C,X] of the MATLAB analyzers.
Definition mva_types.h:97
std::vector< T > X
Definition mva_types.h:99
std::vector< T > QNfcr
Finite capacity region row (1 x K each), filled by solver_oqnrc alone and EMPTY otherwise: jobs in th...
Definition mva_types.h:132
double lG
log of the normalizing constant, the reference's lG.
Definition mva_types.h:119
std::vector< T > RNfcr
Definition mva_types.h:132
std::vector< T > DropRateNfcr
Definition mva_types.h:132
std::vector< T > C
Definition mva_types.h:99
std::optional< bool > converged
Whether the fixed point met its tolerance, or empty when the handler reports none.
Definition mva_types.h:110
std::vector< T > TNfcr
Definition mva_types.h:132
Scope of a model inside OQNRC: token pool of each class (0-based), tokens per pool,...
std::vector< int > Ncap
std::vector< int > pool
std::string kind
empty when the model is in scope
Product-form chain parameters, the split into queueing and delay stations.
Definition sn_chain.h:322
Matrix< T > D
(Mq x C) demands at queueing stations
Definition sn_chain.h:323
std::vector< T > lambda
(C) chain arrival rates, zero on a closed chain
Definition sn_chain.h:325
Matrix< T > Z
(Md x C) demands at delay stations
Definition sn_chain.h:324
std::vector< std::size_t > delay_stations
1-based
Definition sn_chain.h:329
std::vector< std::size_t > queue_stations
1-based
Definition sn_chain.h:328
std::vector< double > S
(Mq) server counts
Definition sn_chain.h:327
The four option switches of the reference, with its defaults.
Definition npfqn_sqd.h:114
Return value of npfqn_sqd, mirroring [X, Q, U, R].
Definition npfqn_sqd.h:105
std::vector< T > R
(M) per-station residence time
Definition npfqn_sqd.h:109
std::vector< T > Q
(M) per-station queue length
Definition npfqn_sqd.h:107
std::vector< T > U
(M) per-station utilization, capped at one
Definition npfqn_sqd.h:108
std::vector< T > X
(M) per-station throughput
Definition npfqn_sqd.h:106
Return value of pfqn_ab_amva, mirroring [QN,UN,RN,CN,XN,totiter].
Matrix< T > UN
(M x R) utilization
std::size_t totiter
iterations of the final core pass
std::vector< T > XN
(R) class throughput AT STATION 1
Matrix< T > QN
(M x R) mean queue length
std::vector< T > XN
(R) throughput
Definition pfqn_bs.h:49
Matrix< T > UN
(M x R) utilization
Definition pfqn_bs.h:51
std::size_t iterations
Definition pfqn_bs.h:53
Matrix< T > QN
(M x R) queue length
Definition pfqn_bs.h:50
Return value of pfqn_debemva, mirroring [X,Q,U,R,BT,z,theta,iter,converged]; vectors are (M).
std::vector< T > Q
mean number of jobs, blocked jobs at the source
std::vector< T > U
utilization X.*S, blocked time excluded
std::vector< T > X
throughput of each station
std::vector< T > R
mean residence time per visit, blocking time included
long iter
total number of passes over all populations
bool converged
false if a population exhausted iter_max passes
Matrix< T > Q
(2 x R) mean queue lengths
std::vector< T > T_
(R) per-class throughput
Matrix< T > U
(2 x R) utilizations
Return value of the Linearizer family, mirroring [Q,U,W,C,X,totiter].
Matrix< T > U
(M x R) utilization
std::vector< T > X
(R) per-class throughput
Matrix< T > Q
(M x R) mean queue length
int totiter
total inner iterations across all Core calls
std::vector< T > XN
(R) per-class throughput
Definition pfqn_mva.h:46
Matrix< T > QN
(M x R) mean queue length
Definition pfqn_mva.h:47
double lG
log of the normalizing constant
Definition pfqn_mva.h:51
Matrix< T > UN
(M x R) utilization
Definition pfqn_mva.h:48
Return value of pfqn_mvablo, mirroring [X,Q,U,R,BT,iter,converged]; vectors are (M).
Definition pfqn_mvablo.h:53
std::vector< T > Q
mean number of jobs, blocked jobs at the source
Definition pfqn_mvablo.h:55
int iter
total number of passes over all populations
Definition pfqn_mvablo.h:59
std::vector< T > X
throughput of each station
Definition pfqn_mvablo.h:54
std::vector< T > U
utilization X.*S, blocked time excluded
Definition pfqn_mvablo.h:56
bool converged
false if a population exhausted iter_max passes (deadlock)
Definition pfqn_mvablo.h:60
std::vector< T > R
mean residence time per visit, blocking time included
Definition pfqn_mvablo.h:57
Result of pfqn_oqnrc.
Definition pfqn_oqnrc.h:43
Matrix< double > Q
Definition pfqn_oqnrc.h:44
int iter
multi-pool fixed point iterations
Definition pfqn_oqnrc.h:48
std::vector< double > Ploss
loss probability of each class (DROP)
Definition pfqn_oqnrc.h:47
std::vector< double > X
carried throughput of each class
Definition pfqn_oqnrc.h:45
Matrix< double > U
Definition pfqn_oqnrc.h:44
Matrix< double > R
queue length, throughput, utilization, response time per visit
Definition pfqn_oqnrc.h:44
Matrix< double > T
Definition pfqn_oqnrc.h:44
std::vector< double > Qext
mean class-r arrivals waiting outside (WAITQ)
Definition pfqn_oqnrc.h:46
Return value of pfqn_schmidt_ext, mirroring [XN,QN,UN,CN].
Matrix< T > QN
(M x R) mean queue length
std::vector< T > XN
(R) per-class throughput
Return value of pfqn_schmidt, mirroring [XN,QN,UN,CN].
std::vector< T > XN
(R) per-class throughput
Matrix< T > QN
(M x R) mean queue length
Return value of pfqn_sqni, mirroring [Q, U, X] for the single station.
Definition pfqn_sqni.h:43
std::vector< T > X
Definition pfqn_sqni.h:46
std::vector< T > Q
Definition pfqn_sqni.h:44
std::vector< T > U
Definition pfqn_sqni.h:45
A node of the network.
One station of the network.
CdScaling< T > jdscaling
sn.jdscaling for this station: MATLAB's Station.ljdScaling, the JOINT dependence map eta_i(n),...
std::vector< T > lldscaling
sn.lldscaling for this station: the multiplier at population 1, 2, ... Empty when the station is not ...
CdScaling< T > cdscaling
sn.cdscaling for this station: the class-dependence map, empty when unset.
Closing controls; Kclosed is the population given to the open classes.
Definition sum_closing.h:62
static Servers of(long m)
Definition sum_closed.h:68
static Servers inf()
Definition sum_closed.h:74
Mirrors the [XN, QN, UN, RN, it] return list of the MATLAB function.
Definition sum_closed.h:84
Matrix< T > QN
(M x R) mean queue lengths
Definition sum_closed.h:86
Matrix< T > UN
(M x R) utilizations, per server at queueing stations
Definition sum_closed.h:87
std::size_t it
iterations of the outer loop
Definition sum_closed.h:89
std::vector< T > XN
(R) class throughputs
Definition sum_closed.h:85
Mirrors the [XN, QN, UN, RN, TN, it] return list of the MATLAB function.
Definition sum_closing.h:52
std::vector< T > XN
(R) class throughputs
Definition sum_closing.h:53
Matrix< T > QN
(M x R) queue lengths at the original stations
Definition sum_closing.h:54
Matrix< T > UN
(M x R) utilizations at the original stations
Definition sum_closing.h:55
Convergence controls, mirroring the trailing (tol, maxiter) arguments.
Definition sum_closed.h:93
std::size_t maxiter
Definition sum_closed.h:95
Summation method (SUM) and its extension (ESUM) for closed queueing networks, including non-product-f...
Closing method for open and mixed non-product-form queueing networks, solved with the summation metho...