LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_mva_runner.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_RUNNER_H
6#define LINE_SOLVERS_MVA_SOLVER_MVA_RUNNER_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * The SolverMVA class surface: `@@SolverMVA/runAnalyzer.m` and the gates around
12 * it.
13 *
14 * What sits here rather than in the dispatch is everything that happens BEFORE
15 * and AFTER one inner solve: the method whitelist, the structural gates, the
16 * conversions from response time to residence time and from throughput to
17 * arrival rate, and the metric filter. `mvaDispatch` is the callback; on a
18 * model without forks it runs exactly once.
19 *
20 * THE FILTER IS LOAD BEARING, not cosmetic. `@@NetworkSolver/getAvg` is not a
21 * getter: between the analyzer and the caller it zeroes a metric wherever the
22 * class has no visit, snaps anything below FineTol to zero, and masks the
23 * queue length and the utilization where the response time is below
24 * 10 FineTol. In a layered model every entry, task and call class is served by
25 * an Immediate distribution somewhere, whose response time is exactly 1e-8, so
26 * without the mask a layer reports the immediate classes' share of the
27 * population as real queue length.
28 */
29
30#include <algorithm>
31#include <cmath>
32#include <limits>
33#include <memory>
34#include <optional>
35#include <string>
36#include <vector>
37
41#include "line/util/lu.h"
56#include <set>
57
58namespace line {
59namespace mva {
60
61/** The metrics `getAvg` returns, after filtering. */
62template <class T>
63struct AvgResult {
64 Matrix<T> QN; ///< queue length
65 Matrix<T> UN; ///< utilization
66 Matrix<T> RN; ///< response time, per visit
67 Matrix<T> TN; ///< throughput
68 Matrix<T> AN; ///< arrival rate
69 Matrix<T> WN; ///< residence time, per job
70 std::vector<T> CN; ///< system response time per class
71 std::vector<T> XN; ///< system throughput per class
72 /** Finite capacity region row (1 x K each), filled by method 'oqnrc' alone, EMPTY otherwise. */
73 std::vector<T> QNfcr, TNfcr, RNfcr, DropRateNfcr;
74 std::string method; ///< the method asked for
75 std::string actualmethod;///< the algorithm that ran
76 /**
77 * The reference's own warning text, verbatim, empty when it did not warn.
78 *
79 * It belongs beside `actualmethod` because it is the same kind of thing: a
80 * statement about HOW the numbers were produced rather than a metric. It is
81 * carried, not thrown, because the answer is usable -- the SJN starvation
82 * cap leaves the population law exact and only the ACCURACY unwarranted,
83 * which is solver_nc_cdf.h:83's precedent, not solver_mam_retrial.h:437's.
84 * Dropping it silently is worse than a wrong number: the answer then looks
85 * authoritative exactly where the reference declines to stand behind it.
86 */
87 std::string warning;
88 /**
89 * (h) mean storage cost held by each cache list, K_j = sum_i sigma_i pi_ij,
90 * filled only by the NC cache branch on a model with item sizes; EMPTY
91 * otherwise. See ton21cache Sec. IX and [[09-ldes-and-cache]].
92 */
93 std::vector<T> listcost;
94 int iter = 0;
95 /**
96 * Whether the fixed point met its tolerance, empty when the handler reports
97 * none. Carried beside `iter` because the count alone cannot decide it on
98 * the AMVA route, where it aggregates the nested inner sweeps and reaches
99 * the cap on solves whose outer residual is exactly zero. A caller that
100 * reads the count as a convergence test raises false warnings; that is why
101 * the flag exists and why it has to reach the CLI envelope.
102 */
103 std::optional<bool> converged;
104 /**
105 * `@@SolverNC/getProbNormConstAggr`, i.e. the reference's
106 * `result.Prob.logNormConstAggr`, filled by the NC runner alone and EMPTY
107 * for every other solver.
108 *
109 * It sits here for `listcost`'s reason: it is a statement about the solve
110 * that only one solver can make, and the alternative -- calling
111 * `solver_nc_solve` a second time to recover it -- would solve the model
112 * twice for one number. Absent is not zero: log G = 0 is the constant of an
113 * empty network, so a caller must test the option rather than the value.
114 */
115 std::optional<double> lognormconst;
116 /**
117 * What the cache branches observed, EMPTY on a model with no Cache node and
118 * on every solver that does not analyze one. `getAvgCacheTable` and
119 * `getAvgItemTable` are built from it; see `solvers::CacheMetrics`.
120 */
122 /**
123 * The struct whose cache self-switch carries the CONVERGED hit/miss split,
124 * filled by the cacheqn branches and NULL for every other model.
125 *
126 * It has to travel with the result because the split is a SOLVER OUTPUT, not
127 * model structure: `link()` leaves the self-switch at the offered 1/2-1/2,
128 * and every quantity derived from a visit ratio -- ArvR, ResidT, and the
129 * node-level hit and miss throughputs -- is wrong by that ratio until the
130 * solve replaces it. The runner already uses this struct for the STATION
131 * table (see `refL` below); handing the caller the base struct instead makes
132 * `-a avg` and `-a node` disagree on one column of one model, which is the
133 * divergence `node_metrics` exists to avoid. Measured on cache_replc_routing:
134 * Cache/Router/Sink hit and miss read 1/1 off the base struct against 0.8/1.2.
135 */
136 std::shared_ptr<qn::NetworkStruct<T>> refreshed_struct;
137 /**
138 * `self.result.FJ`: the fork-join section metrics FJQLen, FJRespT and FJTput,
139 * filled by the solvers the fork-join fixed point drives (MVA, NC, Fluid) and
140 * EMPTY for every other solver and every model without a Fork/Join pair.
141 */
143 /**
144 * `self.result.LossN`: the loss-network inputs SolverNC keeps for
145 * `getAvgLinkTable`, EMPTY for every other solver and model.
146 */
148};
149
150/**
151 * Port of `SolverMVA.listValidMethods`.
152 *
153 * A LISTED NAME MUST ACTUALLY RUN. The reference records why: the bound family
154 * was delisted when it moved to SolverBA, because listing names that error made
155 * the list a false claim. `qdaql` is implemented in `solver_amva` and dispatched
156 * by no analyzer, so it stays off the list here too and the gate below refuses
157 * it.
158 */
159template <class T>
160std::vector<std::string> list_valid_methods(const qn::NetworkStruct<T>& L) {
161 // The names and their order are SolverMVA's row of the method registry
162 // (doc/line-methods.json); the gates below only drop names, and the
163 // per-name reasons after them drop more.
164 std::vector<std::string> m = ::line::method_registry::methods("MVA");
165 std::set<std::string> drop;
166
167 if (L.has_multi_server()) {
168 drop.insert({"aql", "amva.aql", "qsa", "amva.qsa", "tay", "amva.tay", "sqni"});
169 }
170
171 bool open = true, closed = false;
172 for (const qn::JobClass& c : L.classes) {
173 if (std::isfinite(c.population) && c.population > 0.0) {
174 closed = true;
175 open = false;
176 }
177 }
178 (void)closed;
179 bool has_bas = false;
180 for (const qn::Station<T>& st : L.stations)
181 for (int dr : st.droprule)
182 if (dr == static_cast<int>(lang::DropStrategy::BAS)) has_bas = true;
183 if (!(L.nclasses == 1 && !open && has_bas)) drop.insert("sqd");
184 if (!(sn_is_bas_model(L) && mvablo_scope_reason(L).first.empty())) drop.insert("mvablo");
185 if (!(sn_is_bas_model(L) && debemva_scope_reason(L).first.empty())) drop.insert("debemva");
186 if (!oqnrc_scope_reason(L).first.empty()) drop.insert("oqnrc");
187
188 bool any_open_class = false;
189 for (const qn::JobClass& c : L.classes)
190 if (std::isinf(c.population)) any_open_class = true;
191 if (any_open_class) drop.insert("mvac");
192
193 if (!(!any_open_class && sn_has_sjn(L))) {
194 drop.insert({"sjn.mva", "sjn.amva"});
195 }
196
197 bool classdep_routing = false;
198 if (open) {
199 drop.insert({"marie", "amva.marie"});
200 } else {
201 drop.insert({"qna", "rqna", "rqt"});
202 for (std::size_t r = 0; r + 1 < L.nclasses; ++r)
203 for (std::size_t i = 1; i <= L.nof_nodes() && !classdep_routing; ++i)
204 for (std::size_t j = 1; j <= L.nof_nodes(); ++j)
205 if (L.route_eff(r + 1, r + 1, i, j) != L.route_eff(r + 2, r + 2, i, j)) {
206 classdep_routing = true;
207 break;
208 }
209 if (classdep_routing) drop.insert({"marie", "amva.marie"});
210 }
211 bool has_prio = false;
212 for (const qn::Station<T>& st : L.stations)
213 if (st.sched == qn::SchedStrategy::FCFSPRPRIO) has_prio = true;
214 if (!has_prio) drop.insert({"priomva", "amva.priomva"});
215 if (!mva_mapqn_reason(L, "mapqn").empty()) drop.insert("amva.mapqn");
216
217 const std::set<std::string> qsys = {"mm1", "mmk", "mg1", "mgi1", "gm1", "gig1", "gim1", "gimc",
218 "gig1.kingman", "gigk", "gigk.kingman_approx",
219 "gig1.gelenbe", "gig1.heyman", "gig1.kimura", "gig1.allen",
220 "gig1.kobayashi", "gig1.klb", "gig1.marchal",
221 "gigk.whitt", "qed", "gig1.extremal", "gigk.diffusion"};
222 if (!(open && L.nstations == 2 && L.nclasses == 1)) {
223 drop.insert(qsys.begin(), qsys.end());
224 drop.insert({"erlanga", "mgisrgi"});
225 } else {
226 const std::size_t qi = detail::station_of_type(L, qn::NodeType::Queue);
227 if (!(qi != 0 && api::sn_patience_handles(L, qi - 1, 0).present)) {
228 drop.insert({"erlanga", "mgisrgi"});
229 } else if (!mva_erlanga_patience_reason(L).empty()) {
230 drop.insert("erlanga"); // Erlang A needs an exponential patience
231 }
232 }
233 // finite-source closed forms: offered only on the Delay + FCFS Queue cycle
234 // whose laws they read (SolverMVA.finiteSourceVariant)
235 for (const char* fs : {"mg1kk", "ddckk", "mmckk"})
236 if (mva_finite_source_variant(L, fs).empty()) drop.insert(fs);
237 {
238 std::vector<std::string> kept;
239 kept.reserve(m.size());
240 for (const std::string& name : m)
241 if (drop.count(name) == 0) kept.push_back(name);
242 m.swap(kept);
243 }
244
245 std::size_t n_inf = 0;
246 for (const qn::Station<T>& st : L.stations)
247 if (st.sched == qn::SchedStrategy::INF) ++n_inf;
248 // The schmidt-ext arm recurs on the CHAIN populations, so the gate asks about
249 // those and not about the class ones; see mva_schmidt_ext_reason. Built lazily
250 // and once: it is the only rule here that costs a chain aggregation, and every
251 // other name in the list would pay for it.
252 std::vector<double> sx_n;
253 std::vector<bool> sx_fcfs;
254 bool sx_ready = false;
255 std::vector<std::string> keep;
256 keep.reserve(m.size());
257 for (const std::string& name : m) {
258 if (!mva_closed_population_reason(L, name).empty()) continue;
259 if (!mva_single_class_open_reason(L, name).empty()) continue;
260 if (!mva_mvac_reason(L, name).empty()) continue;
261 if (!mva_mapqn_reason(L, name).empty()) continue;
262 if (!mva_breakdown_reason(L, name).empty()) continue;
263 if (qn::mva_base_method(name) == "schmidt-ext") {
264 if (!sx_ready) {
266 for (std::size_t c = 0; c < L.nchains; ++c) sx_n.push_back(cd.Nchain[c]);
267 for (const qn::Station<T>& st : L.stations)
268 if (st.sched != qn::SchedStrategy::INF && st.sched != qn::SchedStrategy::EXT)
269 sx_fcfs.push_back(st.sched == qn::SchedStrategy::FCFS);
270 sx_ready = true;
271 }
272 if (!mva_schmidt_ext_reason(sx_n, sx_fcfs, name).empty()) continue;
273 }
274 // pfqn_sqni is a closed form for ONE queueing station with a delay; listing
275 // it elsewhere named a method solver_amva refuses by name.
276 if (qn::mva_base_method(name) == "sqni" && !(L.nstations == 2 && n_inf == 1)) continue;
277 keep.push_back(name);
278 }
279 m.swap(keep);
280 return m;
281}
282
283/**
284 * Port of `runAnalyzerChecks`' method gate: a method the solver does not list
285 * is refused before any analyzer sees it.
286 */
287template <class T>
288void check_method(const qn::NetworkStruct<T>& L, const std::string& method) {
289 // SolverMVA.supportsMvablo runs ahead of the list, so the refusal names the construct
290 if (method == "mvablo") {
291 const std::pair<std::string, std::string> why = mvablo_scope_reason(L);
292 if (!why.first.empty()) throw UnsupportedError(ErrorKind{"Method"}, "SolverMVA: " + why.first);
293 }
294 if (method == "debemva") {
295 const std::pair<std::string, std::string> why = debemva_scope_reason(L);
296 if (!why.first.empty()) throw UnsupportedError(ErrorKind{"Method"}, "SolverMVA: " + why.first);
297 }
298 // SolverMVA.supportsOqnrc: the refusal names the construct and its kind
299 if (method == "oqnrc") {
300 const std::pair<std::string, std::string> why = oqnrc_scope_reason(L);
301 if (!why.first.empty()) throw UnsupportedError(ErrorKind{why.second}, "SolverMVA: " + why.first);
302 }
303 // 'erlanga' is dropped from the list on a non-exponential patience: name the law, not the list
304 if (method == "erlanga") {
305 const std::string why = mva_erlanga_patience_reason(L);
306 if (!why.empty()) throw UnsupportedError(ErrorKind{"Structure"}, "SolverMVA: " + why);
307 }
308 const std::vector<std::string> valid = list_valid_methods(L);
309 if (std::find(valid.begin(), valid.end(), method) != valid.end()) return;
310 // a registered name dropped for THIS model is not an unknown name: say so
311 const std::vector<std::string> all = ::line::method_registry::methods("MVA");
312 if (std::find(all.begin(), all.end(), method) != all.end())
313 throw UnsupportedError(ErrorKind{"Method"}, "SolverMVA: the '" + method +
314 "' method does not apply to this model. list_valid_methods names the methods that do.");
315 throw UnsupportedError(ErrorKind{"Method"}, "SolverMVA: the '" + method + "' method is unsupported by this solver");
316}
317
318/**
319 * Port of `SolverMVA.resolveMethod`: the feature-driven `default` -> `rqna`
320 * upgrade for a bursty single-class open network.
321 *
322 * The reference computes this ONLY to pick the method feature set
323 * (`getMethodFeatureSet`), never writing it back to options; `mva_dispatch`
324 * makes the same decision again on its own terminal branch. Without it the gate
325 * would read the base envelope, which declares neither MAP nor MMPP2, and would
326 * refuse the very models `solver_rqna` exists to solve.
327 */
328template <class T>
329std::string resolve_method(const qn::NetworkStruct<T>& L, const std::string& method) {
330 // an open network inside one finite capacity region resolves to OQNRC
331 if (method == "default" && !L.regions.empty() && oqnrc_scope_reason(L).first.empty())
332 return std::string("oqnrc");
333 if (method != "default" || L.nclasses != 1) return method;
334 // JobClass::population is a plain double, as mva_dispatch.h:854 reads it; a
335 // num_traits<T> round trip would throw on an infinite one at T = Rational.
336 for (std::size_t r = 0; r < L.nclasses; ++r)
337 if (std::isfinite(L.classes[r].population)) return method;
338 if (api::sn_has_bursty_arrival(L)) return std::string("rqna");
339 if (L.nstations == 2) {
340 // A single-class open station customers ABANDON is a different model,
341 // not a correction to a G/G/k one: the resolution has to happen here as
342 // well as in mva_dispatch, because the feature gate runs on the
343 // resolved name and Reneging is admitted for these two methods only.
344 const std::size_t qi = detail::station_of_type(L, qn::NodeType::Queue);
345 if (qi != 0) {
347 if (h.present) return h.isExponential ? std::string("erlanga") : std::string("mgisrgi");
348 }
349 }
350 return method;
351}
352
353namespace detail {
354
355/**
356 * The visit ratios summed over chains, at STATION level.
357 *
358 * `sn.visits` is indexed by stateful node and by chain; both conversions below
359 * need one (nstations x nclasses) matrix, which is what `cellsum` followed by
360 * the statefulToStation mapping produces in the reference.
361 */
362template <class T>
363Matrix<T> station_visits(const qn::NetworkStruct<T>& L) {
364 const T zero = num_traits<T>::from_int(0);
365 Matrix<T> V(L.nstations, L.nclasses, zero);
366 for (std::size_t c = 0; c < L.nchains; ++c)
367 for (std::size_t i = 0; i < L.nstations; ++i) {
368 const std::size_t sf = L.stateful_of_station(i + 1);
369 for (std::size_t k = 0; k < L.nclasses; ++k)
370 V(i, k) = T(V(i, k) + L.visits[c](sf - 1, k));
371 }
372 return V;
373}
374
375} // namespace detail
376
377/**
378 * Port of `sn_get_residt_from_respt`: the per-JOB residence time.
379 *
380 * `RN` is per visit; multiplying by this station's visits and dividing by the
381 * reference station's visits of the chain's reference class turns it into the
382 * time a job spends here per completion. A response time already below FineTol
383 * (an Immediate class) is passed through unscaled, since scaling noise is
384 * still noise.
385 */
386template <class T>
388 const T zero = num_traits<T>::from_int(0);
389 const std::size_t M = L.nstations, K = L.nclasses;
390 const Matrix<T> V = detail::station_visits(L);
391 Matrix<T> WN(M, K, zero);
392 for (std::size_t i = 0; i < M; ++i)
393 for (std::size_t k = 0; k < K; ++k) {
394 // A PLACE HAS NO SERVICE PROCESS, SO `disabled` IS NOT ABSENCE --
395 // the same caveat `refresh_capacity` already carries. The reference
396 // gates this loop on the metric HANDLE (`WH{ist,k}.disabled`), which
397 // a Place holding a class does have; `sn.disabled` is only a
398 // stand-in for it, and on an SPN it is true at every Place, which
399 // zeroed the whole ResidT column (`-s jmt` reported ResidT 0 beside
400 // RespT 0.35308 on spn_basic_closed while every other codebase
401 // reported both).
402 const bool is_place = L.stations[i].nodetype == qn::NodeType::Place;
403 if ((L.disabled[i][k] && !is_place) || !(RN(i, k) > zero)) continue;
405 WN(i, k) = RN(i, k);
406 continue;
407 }
408 std::size_t c = L.nchains;
409 for (std::size_t cc = 0; cc < L.nchains; ++cc)
410 if (L.chains[cc][k]) c = cc;
411 if (c == L.nchains) continue;
412 const std::size_t rs = L.classes[k].refstat;
413 T den = zero;
414 if (L.refclass[c] > 0) {
415 den = V(rs - 1, L.refclass[c] - 1);
416 } else {
417 for (std::size_t r : L.inchain[c]) den += V(rs - 1, r - 1);
418 }
419 if (den > zero) WN(i, k) = T(RN(i, k) * V(i, k) / den);
420 }
421 for (std::size_t i = 0; i < M; ++i)
422 for (std::size_t k = 0; k < K; ++k)
424 WN(i, k) = zero;
425 return WN;
426}
427
428/**
429 * A Join reports the PER-SIBLING waiting time, QLen over the SIBLING ARRIVAL
430 * RATE, and not QLen over its own firing rate.
431 *
432 * The two differ by exactly the fork degree: a Join fires once per parent job
433 * while it takes in one sibling per branch, so Little's law applied with the
434 * firing rate answers a question about parents with a queue length measured in
435 * siblings. On the closed two-branch fork-join with N=2 that is 1.44444 where
436 * the settled JMT convention is 0.72222.
437 *
438 * Called by every engine that folds sibling classes back (CTMC and SSA), after
439 * their own `Q/T` pass, so the override lands on the same table the caller
440 * reads. A model with no Join leaves the matrix untouched.
441 */
442template <class T>
444 Matrix<T>& RN) {
445 const T zero = num_traits<T>::from_int(0);
446 for (std::size_t nd = 0; nd < L.nodes.size(); ++nd) {
447 if (L.nodes[nd].nodetype != qn::NodeType::Join) continue;
448 const std::size_t ist = L.nodes[nd].station;
449 if (ist == 0 || ist > RN.rows()) continue;
450 for (std::size_t r = 0; r < RN.cols(); ++r)
451 if (AN(ist - 1, r) > zero) RN(ist - 1, r) = QN(ist - 1, r) / AN(ist - 1, r);
452 }
453}
454
455/**
456 * Port of `sn_get_arvr_from_tput`: the arrival rate each station sees, from the
457 * throughputs and the class-expanded routing `sn.rt`.
458 *
459 * A Source's row is zero, as the reference writes it (`AN(ist,:) = 0`); the
460 * caller's mask in `getAvg` zeroes it again, harmlessly.
461 *
462 * A NON-STATION STATEFUL NODE (Router, Cache) has no throughput of its own, so
463 * the throughput routed into it is found by solving the flow balance over all
464 * of them at once. The hit/miss split rides in the effective routing as a
465 * SELF-LOOP at the cache node (`set_route_effective(r, hitclass[r], ci, ci,
466 * hitprob)`), which is one more term of that system. The reference instead
467 * reads the solver-written `nodeparam{ind}.actualhitprob` and builds the hit
468 * and miss class throughputs of the Cache from the chain's reference throughput;
469 * this struct carries no such field, and the self-loop term is the same split
470 * expressed in the routing, so that is where it is taken from here.
471 *
472 * After the routing pass the reference applies two overrides, both ported: a
473 * fork-join model takes the NODE arrival rates of `sn_get_node_arvr_from_tput`
474 * at its stations, and a Petri net takes the token production rates of
475 * `sn_pn_firing_rates` at its Places. A sweep in node order,
476 * as this used to be, left a node at zero whenever its feeder came later: a
477 * Router ahead of the Cache zeroed both Delay stations of
478 * cache_replc_routing (ArvR 0 against the reference's 0.4 and 0.6), and a
479 * Router fed by a later-declared Router zeroed the Delay after it.
480 */
481template <class T>
483 const T zero = num_traits<T>::from_int(0);
484 const std::size_t M = L.nstations, R = L.nclasses;
485 const std::size_t S = L.nof_stateful();
486 Matrix<T> AN(M, R, zero);
487 if (L.rt.rows() != S * R) return AN; // no routing was refreshed
488 // The reference's `if ~isempty(TH) && ~isempty(TN)` guard: this overload is
489 // the one every analyzer calls with its own throughput table, so TN is what
490 // decides; the (L, TN, TH) overload below honours TH as well.
491 if (TN.rows() == 0) return AN;
492
493 // Throughput per stateful node: a station contributes its own, and any
494 // other stateful node inherits what the routing carries into it.
495 Matrix<T> TS(S, R, zero);
496 for (std::size_t sf = 0; sf < S; ++sf) {
497 const std::size_t nd = L.stateful_nodes[sf];
498 const std::size_t ist = L.nodes[nd - 1].station;
499 if (ist == 0) continue;
500 for (std::size_t r = 0; r < R; ++r) TS(sf, r) = TN(ist - 1, r);
501 }
502 // Every non-station stateful node (Router, Cache) takes the flow balance x_u = x_k*P_ku + x_u*P_uu, solved
503 // exactly: a sweep in node order left a Router fed by a later-declared Router at zero, and the Cache's hit/miss
504 // self-loop is just one more term of P_uu.
505 std::vector<std::size_t> ucols;
506 std::vector<bool> is_u(S * R, false);
507 for (std::size_t sf = 0; sf < S; ++sf) {
508 if (L.nodes[L.stateful_nodes[sf] - 1].station != 0) continue;
509 for (std::size_t k = 0; k < R; ++k) {
510 ucols.push_back(sf * R + k);
511 is_u[sf * R + k] = true;
512 }
513 }
514 if (!ucols.empty()) {
515 const std::size_t nU = ucols.size();
516 Matrix<T> At(nU, nU, zero); // (I - P_uu)^T
517 std::vector<T> b(nU, zero);
518 for (std::size_t j = 0; j < nU; ++j) {
519 T acc = zero;
520 for (std::size_t col = 0; col < S * R; ++col)
521 if (!is_u[col]) acc += T(TS(col / R, col % R) * L.rt(col, ucols[j]));
522 b[j] = acc;
523 for (std::size_t i = 0; i < nU; ++i)
524 At(j, i) = T((i == j ? num_traits<T>::from_int(1) : zero) - L.rt(ucols[i], ucols[j]));
525 }
526 const std::vector<T> xu = line::solve(At, b);
527 for (std::size_t j = 0; j < nU; ++j) TS(ucols[j] / R, ucols[j] % R) = xu[j];
528 }
529 for (std::size_t ist = 0; ist < M; ++ist) {
530 // MATLAB: a Source's row is zero
531 if (L.stations[ist].nodetype == qn::NodeType::Source) continue;
532 const std::size_t sf_i = L.stateful_of_station(ist + 1) - 1;
533 for (std::size_t k = 0; k < R; ++k) {
534 T acc = zero;
535 for (std::size_t sf2 = 0; sf2 < S; ++sf2)
536 for (std::size_t r = 0; r < R; ++r)
537 acc += T(TS(sf2, r) * L.rt(sf2 * R + r, sf_i * R + k));
538 AN(ist, k) = acc;
539 }
540 }
541
542 // MATLAB: `if any(sn.fj(:))` the station rows are overridden by the node
543 // arrival rates of sn_get_node_arvr_from_tput.
544 if (!L.fj.empty()) {
545 const Matrix<T> ANn = api::sn_get_node_arvr_from_tput(L, TN, AN);
546 for (std::size_t ist = 0; ist < M; ++ist) {
547 const std::size_t ind = L.station_to_node[ist];
548 if (ind == 0 || ind > ANn.rows()) continue;
549 for (std::size_t k = 0; k < R; ++k) AN(ist, k) = ANn(ind - 1, k);
550 }
551 }
552
553 // MATLAB: a Petri net's Place rows are the token production rates,
554 // AN(ist, k) = produced(:, pp, k)' * x, from sn_pn_firing_rates(sn, TN, true).
555 bool any_place = false;
556 for (std::size_t a = 0; a < L.nodes.size() && !any_place; ++a)
557 any_place = L.nodes[a].nodetype == qn::NodeType::Place;
558 if (any_place) {
559 const api::SnPnFiringRates fr = api::sn_pn_firing_rates(L, TN, true);
560 if (!fr.x.empty()) {
561 for (std::size_t pp = 0; pp < fr.place_nodes.size(); ++pp) {
562 const std::size_t ist = L.nodes[fr.place_nodes[pp] - 1].station;
563 if (ist == 0) continue;
564 for (std::size_t k = 0; k < R; ++k) {
565 double acc = 0.0;
566 for (std::size_t mm = 0; mm < fr.x.size(); ++mm) {
567 const std::size_t col = pp * fr.nclasses + k;
568 if (mm < fr.produced.size() && col < fr.produced[mm].size())
569 acc += fr.produced[mm][col] * fr.x[mm];
570 }
571 AN(ist - 1, k) = num_traits<T>::from_double(acc);
572 }
573 }
574 }
575 }
576 return AN;
577}
578
579/**
580 * Overwrite the routing-derived arrival rates with those an analyzer supplied (`MvaSolution::AN`, NaN = not set),
581 * as runAnalyzer.m does for the open retrieval analyzers: their fetches are booked to the read class, which sn.rt
582 * does not route from the Cache, so the routing pass alone leaves a fetch station fed by the Cache at zero.
583 */
584template <class T>
585void apply_analyzer_arvr(Matrix<T>& AN, const Matrix<T>& supplied) {
586 if (supplied.rows() != AN.rows() || supplied.cols() != AN.cols()) return;
587 for (std::size_t i = 0; i < AN.rows(); ++i)
588 for (std::size_t k = 0; k < AN.cols(); ++k)
589 if (!std::isnan(num_traits<T>::to_double(supplied(i, k)))) AN(i, k) = supplied(i, k);
590}
591
592/**
593 * The reference's full signature `sn_get_arvr_from_tput(sn, TN, TH)`: with an
594 * empty TN or TH the routing pass is skipped and AN is empty (`AN = []`), after
595 * which only the fork-join override can still fill it.
596 */
597template <class T>
599 const Matrix<T>& TH) {
600 if (TH.rows() == 0 || TN.rows() == 0) {
601 Matrix<T> AN;
602 if (!L.fj.empty()) {
603 const std::size_t M = L.nstations, R = L.nclasses;
604 const Matrix<T> ANn = api::sn_get_node_arvr_from_tput(L, TN, AN);
605 if (ANn.rows() > 0) {
606 AN = Matrix<T>(M, R, num_traits<T>::from_int(0));
607 for (std::size_t ist = 0; ist < M; ++ist) {
608 const std::size_t ind = L.station_to_node[ist];
609 if (ind == 0 || ind > ANn.rows()) continue;
610 for (std::size_t k = 0; k < R; ++k) AN(ist, k) = ANn(ind - 1, k);
611 }
612 }
613 }
614 return AN;
615 }
616 return sn_get_arvr_from_tput(L, TN);
617}
618
619/**
620 * Which metric is being filtered. `@@MNetwork/getAvgHandles.m` disables a metric
621 * handle per KIND, not per station, and `filterMetric` turns a disabled handle
622 * into a zero -- so the kind is what decides which rows survive:
623 *
624 * Q, R, W disabled at a Source and at a Sink
625 * U disabled at a Source, a Sink, a Fork AND A JOIN -- a Join is an
626 * infinite server whose "utilization" would just restate its queue
627 * length, and the reference declines to report it
628 * T, A never disabled by station kind, only by an undefined service
629 *
630 * Every kind is additionally disabled where the class has no service defined.
631 */
632enum class MetricKind { QLen, Util, RespT, ResidT, Tput, ArvR };
633
634/**
635 * Port of `filterMetric`: what `@@NetworkSolver/getAvg` does between the
636 * analyzer and the caller.
637 *
638 * `zero_mask` carries the RN < 10 FineTol test the queue length and the
639 * utilization take and the other metrics do not.
640 */
641template <class T>
643 const std::vector<std::vector<bool>>* zero_mask) {
644 const T zero = num_traits<T>::from_int(0);
645 const std::size_t M = L.nstations, K = L.nclasses;
646 // the fork-join, cache and spawn-fed exemptions from the reachability test
647 // below: those three constructs are exactly the ones whose visit equations
648 // do not describe how a job actually reaches a station (a Join is entered by
649 // the parent class, which has no routing visit there), so a metric the
650 // analyzer reports as positive is trusted over the visit ratio
651 // ... and the STOCHASTIC PETRI NET, the fourth such construct and for the
652 // same reason: where a token sits is the MARKING, and a Place is reached by
653 // a transition firing rather than by a routing visit, so `sn.visits` is
654 // identically zero over every Place. Without the exemption this loop erased
655 // the whole table an analyzer had just computed -- `spnlp2.upper` on a
656 // fork-join net reported four zeros in place of the token bounds, and
657 // `r.QN >= tokens` then failed against a row the bound had got right.
658 bool has_fj = false, has_cache = false, has_spn = false;
659 for (const qn::NodeDef& nd : L.nodes) {
660 if (nd.nodetype == qn::NodeType::Fork || nd.nodetype == qn::NodeType::Join) has_fj = true;
661 if (nd.nodetype == qn::NodeType::Cache) has_cache = true;
662 if (nd.nodetype == qn::NodeType::Transition) has_spn = true;
663 }
664 // The Tput/ArvR HANDLE is disabled iff `~isServiceDefined && ~isCacheClass`
665 // (getAvgHandles.m): a service-undefined pair keeps its throughput only when
666 // the class is a cache hit/miss class -- NOT for fork-join. The fork-join
667 // exemption belongs to the reachability test (part 2 below), not here.
668 std::vector<bool> is_cache_class(K, false);
669 for (const auto& kv : L.nodeparam) {
670 const qn::CacheParam<T>& cp = kv.second;
671 for (std::size_t r = 0; r < cp.hitclass.size(); ++r) {
672 if (cp.hitclass[r] != 0 && cp.hitclass[r] <= K) is_cache_class[cp.hitclass[r] - 1] = true;
673 if (r < cp.missclass.size() && cp.missclass[r] != 0 && cp.missclass[r] <= K)
674 is_cache_class[cp.missclass[r] - 1] = true;
675 }
676 }
677
678 Matrix<T> out(M, K, zero);
679 for (std::size_t i = 0; i < M; ++i) {
680 const qn::NodeType nt = L.stations[i].nodetype;
681 const bool src_or_sink = (nt == qn::NodeType::Source || nt == qn::NodeType::Sink);
682 bool kind_disabled = false;
683 switch (kind) {
684 case MetricKind::QLen:
687 kind_disabled = src_or_sink;
688 break;
689 case MetricKind::Util:
690 kind_disabled = src_or_sink || nt == qn::NodeType::Fork || nt == qn::NodeType::Join;
691 break;
692 case MetricKind::Tput:
693 case MetricKind::ArvR:
694 kind_disabled = false;
695 break;
696 }
697 if (kind_disabled) continue;
698 // `hasServiceTunnel`, the wrapper this port was missing. Every metric in
699 // `getAvgHandles.m` gates its service test on `if ~hasServiceTunnel(ist)`
700 // -- a station whose SERVER is a ServiceTunnel is never disabled for
701 // having no service law, only by the kind-specific rules just above
702 // (which already match, arm for arm).
703 //
704 // Those stations are Source, Fork, Join and an ORDINARY Place. A Place is
705 // the one that has to be decided rather than looked up: `installQueueServer`
706 // REPLACES the tunnel on a queueing Place, so `hasServiceTunnel` is false
707 // there, and this struct carries no queueing flag. It is recovered the way
708 // MATLAB defines it, PER STATION: an ordinary Place has a law for no class
709 // at all, a queueing one has a real server. Deciding it per class instead
710 // would keep a queueing Place's explicitly Disabled class, which MATLAB
711 // disables.
712 //
713 // The Place arm is what made a pure Petri net print an EMPTY AvgTable:
714 // a non-queueing Place has NaN rates, which is `disabled` here, so every
715 // metric was zeroed and the printer drops an all-zero row -- while MATLAB
716 // reports e.g. P1 QLen 0.25966 on spn_basic_open. Source and Join change
717 // little in practice (a Source's ungenerated class and a Join both compute
718 // 0 or are already kept), but they are MATLAB's rule and are encoded here
719 // rather than left to coincidence.
720 bool service_tunnel = (nt == qn::NodeType::Source || nt == qn::NodeType::Fork ||
721 nt == qn::NodeType::Join);
722 if (nt == qn::NodeType::Place) {
723 service_tunnel = true;
724 for (std::size_t k = 0; k < K && k < L.service[i].size(); ++k)
725 if (!L.service[i][k].disabled) { service_tunnel = false; break; }
726 }
727 for (std::size_t k = 0; k < K; ++k) {
728 if (!L.disabled[i][k] || service_tunnel) {
729 out(i, k) = metric(i, k);
730 } else if (is_cache_class[k] &&
731 (kind == MetricKind::Tput || kind == MetricKind::ArvR)) {
732 // a cache over-routing sends a hit/miss class through a station
733 // that never serves it (a pass-through); its Tput/ArvR handle is
734 // not disabled, so the reported flow is kept
735 out(i, k) = metric(i, k);
736 }
737 }
738 }
739 if (zero_mask)
740 for (std::size_t i = 0; i < M; ++i)
741 for (std::size_t k = 0; k < K; ++k)
742 if ((*zero_mask)[i][k]) out(i, k) = zero;
743 for (std::size_t i = 0; i < M; ++i)
744 for (std::size_t k = 0; k < K; ++k)
745 if (num_traits<T>::to_double(out(i, k)) < GlobalConstants::FineTol) out(i, k) = zero;
746 // a class with no visit at a station holds nothing there
747 for (std::size_t k = 0; k < K; ++k) {
748 std::size_t c = L.nchains;
749 for (std::size_t cc = 0; cc < L.nchains; ++cc)
750 if (L.chains[cc][k]) c = cc;
751 if (c == L.nchains) continue;
752 for (std::size_t i = 0; i < M; ++i) {
753 if (L.visits[c](L.stateful_of_station(i + 1) - 1, k) != zero) continue;
754 if ((has_fj || has_cache || has_spn) &&
756 continue;
757 out(i, k) = zero;
758 }
759 }
760 return out;
761}
762
763/**
764 * The saturated open-station rule of `@@NetworkSolver/getAvg.m:221-308`.
765 *
766 * A finite-server queueing station whose open-class offered load
767 * `rho = sum_r TN(i,r) / (c * lldpeak * rate(i,r))` reaches 1 is saturated:
768 * its utilization is reported normalized to a station total of 1.0 and the
769 * open classes' queue length and response time as Inf. Throughput is NOT
770 * rescaled -- the offered rate is what the reference reports.
771 *
772 * IT LIVES HERE, NEXT TO `filter_metric`, BECAUSE EVERY SOLVER OWES IT. The
773 * reference applies it once in `getAvg.m`, above the analyzer, so MVA, NC and
774 * MAM all report a saturated station the same way. Keeping a private copy in
775 * the MVA runner is what let SolverNC report `QLen 3.05, Util 61.8` and
776 * SolverMAM the clamped `QLen 9.99e7` for the very same station MVA called
777 * Inf (chaos seed 215).
778 *
779 * CALL IT AFTER `out.WN` IS ASSEMBLED. `getAvg.m` computes the residence times
780 * off `RNclass` BEFORE the Inf overwrite, so ResidT keeps the pre-saturation
781 * `RN*V` value and does not become Inf with the response time.
782 *
783 * THE THREE EXCLUSIONS ARE NOT OPTIONAL once the rule is universal, because
784 * each names a station whose queue is bounded at any offered load and whose
785 * exact answer would otherwise be overwritten with Inf:
786 * - a BINDING BUFFER (`cap`, `classcap`, or a finite capacity region), where
787 * the excess is blocked or lost and `rho` sits exactly on 1;
788 * - RENEGING, where the excess abandons instead of accumulating (the Erlang A
789 * queue length `qsys_erlanga` computes exactly);
790 * - LOAD DEPENDENCE, where the nominal rate understates the server and
791 * `lldpeak` is the peak multiplier the reference divides by.
792 *
793 * Skipped under exact arithmetic, where infinity is not representable.
794 */
795template <class T>
797 Matrix<T>& RN, const Matrix<T>& TN) {
798 if constexpr (!num_traits<T>::has_transcendental) {
799 (void)L; (void)QN; (void)UN; (void)RN; (void)TN;
800 return false;
801 } else {
802 const std::size_t M = L.nstations, K = L.nclasses;
803 bool any_open = false;
804 for (std::size_t r = 0; r < K; ++r)
805 if (std::isinf(L.classes[r].population)) any_open = true;
806 if (!any_open) return false;
807
808 const double dinf = std::numeric_limits<double>::infinity();
809 bool any_unstable = false;
810 for (std::size_t i = 0; i < M; ++i) {
811 const double c = num_traits<T>::to_double(L.stations[i].nservers);
812 const qn::NodeType nt = L.stations[i].nodetype;
813 const qn::SchedStrategy sch = L.stations[i].sched;
814 if (!std::isfinite(c) || c <= 0.0) continue; // delay / infinite server
815 if (nt == qn::NodeType::Source || nt == qn::NodeType::Sink) continue;
816 if (sch == qn::SchedStrategy::INF || sch == qn::SchedStrategy::EXT) continue;
817 // AN ORDER-INDEPENDENT STATION IS NOT JUDGED BY sn.rates (getAvg.m).
818 // Its rate is the whole function mu(n); sn.rates holds only the
819 // single-job rate mu([r]), so T/(c*rate) calls an OI M/M/3
820 // (mu(n) = min(|n|,3), one nominal server) saturated at a load of 2.
821 // Whoever solved the station decided its stability from mu itself
822 // (the analytical OI route reports Inf there; CTMC/LDES cap it with
823 // a buffer).
824 if (sch == qn::SchedStrategy::OI || sch == qn::SchedStrategy::PAS) continue;
825
826 bool bounded = (i < L.cap.size() && std::isfinite(L.cap[i]));
827 if (!bounded && i < L.classcap.size())
828 for (double cc : L.classcap[i])
829 if (std::isfinite(cc)) { bounded = true; break; }
830 if (!bounded)
831 for (const auto& rg : L.regions)
832 if (i < rg.members.size() && rg.members[i]) { bounded = true; break; }
833 if (bounded) continue;
834
835 bool reneges = false;
836 for (lang::ImpatienceType it : L.stations[i].impatience)
837 if (it == lang::ImpatienceType::RENEGING) { reneges = true; break; }
838 if (reneges) continue;
839
840 double lldpeak = 1.0;
841 for (const T& v : L.stations[i].lldscaling) {
842 const double d = num_traits<T>::to_double(v);
843 if (std::isfinite(d) && d > 0.0 && d > lldpeak) lldpeak = d;
844 }
845
846 std::vector<double> rho(K, 0.0);
847 double rho_open = 0.0, rho_tot = 0.0;
848 for (std::size_t r = 0; r < K; ++r) {
849 const double rate = num_traits<T>::to_double(L.rates(i, r));
850 const double tp = num_traits<T>::to_double(TN(i, r));
851 if (rate > 0.0 && tp > 0.0) rho[r] = tp / (c * lldpeak * rate);
852 rho_tot += rho[r];
853 if (std::isinf(L.classes[r].population)) rho_open += rho[r];
854 }
855 if (rho_open < 1.0 || rho_tot <= 0.0) continue;
856 any_unstable = true;
857 for (std::size_t r = 0; r < K; ++r) {
858 UN(i, r) = num_traits<T>::from_double(rho[r] / rho_tot);
859 if (std::isinf(L.classes[r].population) && rho[r] > 0.0) {
860 QN(i, r) = num_traits<T>::from_double(dinf);
861 RN(i, r) = num_traits<T>::from_double(dinf);
862 }
863 }
864 }
865 return any_unstable;
866 }
867}
868
869/** The warning `getAvg.m` raises when cap_unstable_open_stations() fires. */
870inline const char* unstable_open_warning() {
871 return "The model has unstable queues (utilization >= 1); station utilization is "
872 "reported capped at 1.0, queue length and response time as Inf.";
873}
874
875/**
876 * Port of `SolverMVA.supportsFiniteCapacity` (SolverMVA.m:158-186), the
877 * structural capacity gate SolverMVA.supportsModelMethod (SolverMVA.m:143-153)
878 * lays on top of the universal feature gate.
879 *
880 * WHY IT IS SEPARATE FROM `feature_gate`. Finite capacity has no
881 * LINE_QN_FEATURE_LIST enumerator: it is a NUMBER on a station, not a
882 * construct, so no declared feature set can express it. Without this check a
883 * model built with setCapacity is solved as if uncapacitated and returns a
884 * WRONG NUMBER instead of a refusal (BUG-39).
885 *
886 * WHY IT RUNS AFTER THE FEATURE GATE. The reference calls
887 * supportsModelMethod@@NetworkSolver first and only tests capacity `if bool`, so
888 * a model that fails both is refused by the FEATURE, whose message names the
889 * construct to remove. The order is therefore load-bearing, not incidental.
890 *
891 * THE TWO EXEMPTIONS.
892 * - A BAS model, because solver_mva_analyzer routes it to solver_sqd under
893 * `default` too, so the finite buffers ARE honoured on every MVA path. The
894 * predicate is the api/sn one (single CLASS), not the analyzer's dispatch
895 * test mva_is_bas_model (single CHAIN); see solver_mva.h.
896 * - A single-station M/M/1/K with tail drop under any method but `exact`,
897 * which the mg1k.mgs branch of solver_mva_qsys_analyzer solves. That branch
898 * is an approximation away from scv=1, so `exact` is NOT exempted and must
899 * refuse here. `method` is the RESOLVED method, which is what
900 * runAnalyzerChecks (NetworkSolver.m:184) passes on.
901 */
902template <class T>
903void mva_check_finite_capacity(const qn::NetworkStruct<T>& L, const std::string& method) {
904 if (sn_is_bas_model(L)) return;
905 if (method != "exact" && sn_is_mm1k_loss(L)) return;
906 // The isolated order-independent loss queue is solved EXACTLY (qsys_oi_loss
907 // through solver_mva_oi_analyzer) under 'default' and 'exact', the two names
908 // the OI route answers (SolverMVA.supportsFiniteCapacity).
909 if ((method == "default" || method == "exact") && qn::is_oi_loss(L)) return;
910 qn::check_binding_capacity("SolverMVA", L);
911}
912
913/**
914 * Port of `@@SolverMVA/runAnalyzer.m` for the `lang='matlab'` path: gate, solve,
915 * convert, filter.
916 *
917 * A model with a Fork is solved through the shared fork-join fixed point
918 * (fj_driver.h), which drives `mva_dispatch` as its inner solve on the
919 * transformed (auxiliary-expanded) model; a model without one runs the dispatch
920 * exactly once. The filtering below is common to both paths.
921 */
922template <class T>
924 const Matrix<T>& init_sol) {
925 // a non-Markovian reneging patience is refused by name for every method, ahead of the method list
926 {
927 const std::string patWhy = api::sn_patience_refusal(L);
928 if (!patWhy.empty()) throw UnsupportedError(ErrorKind{"Structure"}, "SolverMVA: " + patWhy);
929 }
930 // a closed chain whose (station,class) routing has several closed sets would be
931 // normalized over all of them at once; see sn_reducible_chain.h
932 {
933 const std::string redWhy = api::sn_reducible_chain_refusal(L);
934 if (!redWhy.empty()) throw UnsupportedError(ErrorKind{"Structure"}, "SolverMVA: " + redWhy);
935 }
936 // Port of SolverMVA.supportsBreakdown, read ahead of the method list so the
937 // refusal names the construct: a breakdown station is served by the M/G/1
938 // breakdown closed form alone, under 'default' or 'exact'.
939 {
940 const std::string bdWhy = mva_breakdown_reason(L, opt_in.method);
941 if (!bdWhy.empty()) throw UnsupportedError(ErrorKind{"Structure"}, "SolverMVA: " + bdWhy);
942 }
943 check_method(L, opt_in.method);
944 // A POLLING station is answered by the station-time analyzer alone; any
945 // other shape, method or discipline mix would reach the AMVA core, which
946 // has no polling arm and leaves the wait at zero. Port of
947 // SolverMVA.supportsPolling, read ahead of the feature gate as the
948 // reference's supportsModelMethod does.
949 {
950 const std::string pollWhy = polling_reason(L, opt_in.method);
951 if (!pollWhy.empty()) throw UnsupportedError(ErrorKind{"Structure"}, "SolverMVA: " + pollWhy);
952 }
953
954 // Finite Capacity Region: MVA does not enforce the aggregate per-region job
955 // limit and would otherwise silently return the unconstrained product-form
956 // answer. Port of `runAnalyzer.m:21-35`: method 'oqnrc' (or 'default'
957 // resolved to it) is the one exception, solved by solver_oqnrc below.
958 if (!L.regions.empty() && resolve_method(L, opt_in.method) != "oqnrc")
959 throw UnsupportedError(ErrorKind{"Region"},
960 "SolverMVA: this model uses a Finite Capacity Region (addRegion), which SolverMVA supports only "
961 "through method 'oqnrc' (an open network whose stations all sit in one region). Use SolverCTMC, "
962 "SolverSSA, SolverLDES or SolverJMT, or setCapacity for a single-station limit.");
963
964 // resolveMethod (SolverMVA.resolveMethod) computes the bursty default->rqna
965 // upgrade only for the feature gate; the reference never writes it back to
966 // options. The substitution itself lives in mva_dispatch's terminal
967 // ordinary-QN branch, so the structural special cases (e.g. a 3-node
968 // MAP/M/1, a G/M/1 the qsys analyzer solves) keep method='default' rather
969 // than being forced into rqna and refused.
970 // runAnalyzerChecks' universal feature gate, AFTER the method gate so the
971 // specific message wins wherever one exists. Gated on `L`, before fj_mmt
972 // rewrites the Fork into a Router that MVA does not declare.
973 // The resolved method is passed so that a `default` -> `rqna` refusal names
974 // rqna, which is NetworkSolver.m:184-190's second message form: rqna's set
975 // withdraws ClosedClass, and nothing the user typed mentions rqna.
976 const std::string rm = resolve_method(L, opt_in.method);
977 // The MODEL-aware overload, because one grant in getMethodFeatureSet reads
978 // the model: every method but 'exact' carries FiniteCapacity on a
979 // single-station M/M/1/K with tail drop, the shape mva_dispatch answers
980 // under any name. `mva_check_finite_capacity` below is the same rule as a
981 // structural refusal, and the two must agree.
982 qn::feature_gate("SolverMVA", qn::mva_feature_set(rm, L), L, opt_in.method, rm);
984 const MvaOptions& opt = opt_in;
985
987 std::string actualmethod, warning;
988 // The integrated cacheqn analyzer returns a refreshed struct whose routing
989 // carries the actual hit/miss probabilities; ArvR and ResidT are read from
990 // it. Empty for every other model, in which case the base struct is used.
991 std::shared_ptr<qn::NetworkStruct<T>> refreshed;
992 // What a cache branch measured; see AvgResult::cache. Left empty on the
993 // fork-join path, whose inner solves are of a TRANSFORMED network.
995 // SolverMVA.supportsExactness on the USER model: a fork-join has no product form, so 'exact' is refused
996 // before the transform below hides the fork from the inner solve. OI/PAS stations are exempt, as in the reference.
997 if (opt.method == "exact" && L.has_fork() && !L.has_product_form()) {
998 bool oi = false;
999 for (const qn::Station<T>& st : L.stations)
1000 if (st.sched == qn::SchedStrategy::OI || st.sched == qn::SchedStrategy::PAS) oi = true;
1001 if (!oi)
1002 throw UnsupportedError(ErrorKind{"Structure"},
1003 "SolverMVA: method 'exact' requires a product-form solution; use 'mva' for the "
1004 "approximation based on the exact MVA algorithm");
1005 }
1006 if (rm == "oqnrc") {
1007 s = solver_oqnrc(L, opt);
1008 actualmethod = "oqnrc";
1009 } else if (L.has_fork()) {
1010 // The transform turns the fork into a router, the join into a delay and
1011 // the branches into auxiliary open classes; the driver iterates the
1012 // auxiliary arrival rates to their fixed point and merges the auxiliary
1013 // columns back before returning. `mva_dispatch` sees a plain mixed
1014 // network, so its own fork checks never fire.
1015 FjMmt<T> tr = fj_fork_join_transform(L, opt.fork_join);
1016 std::vector<T> lam(tr.V.classes.size() + 1,
1018 MvaOptions inner = opt;
1019 inner.base_has_fork = true; // the transform removes the fork; see MvaOptions
1020 std::string am, wn, fjw;
1021 s = fj_fixed_point(L, tr, lam, opt, [&inner, &am, &wn](qn::NetworkStruct<T>& V) {
1022 const DispatchResult<T> d = mva_dispatch(V, inner, Matrix<T>());
1023 am = d.actualmethod;
1024 // the last inner solve is the one the returned metrics came from
1025 wn = d.warning;
1026 return d.sol;
1027 }, &fjw);
1028 actualmethod = am;
1029 warning = wn;
1030 if (!fjw.empty()) warning = warning.empty() ? fjw : warning + " " + fjw;
1031 } else {
1032 const DispatchResult<T> dr = mva_dispatch(L, opt, init_sol);
1033 s = dr.sol;
1034 actualmethod = dr.actualmethod;
1035 warning = dr.warning;
1036 refreshed = dr.refreshed_struct;
1037 cache = dr.cache;
1038 }
1039 // Values (not topology) for ArvR/ResidT come from the refreshed struct when
1040 // the cacheqn analyzer supplied one; filter_metric still keys on the base L
1041 // so its cache pass-through masking is unaffected by the ClassSwitch relabel.
1042 const qn::NetworkStruct<T>& refL = refreshed ? *refreshed : L;
1043
1044 const std::size_t M = L.nstations, K = L.nclasses;
1045 std::vector<std::vector<bool>> mask(M, std::vector<bool>(K, false));
1046 for (std::size_t i = 0; i < M; ++i)
1047 for (std::size_t k = 0; k < K; ++k)
1048 mask[i][k] = num_traits<T>::to_double(s.R(i, k)) < 10.0 * GlobalConstants::FineTol;
1049
1050 // `getAvg` zeroes the arrival rate at a Source explicitly: a Source is not
1051 // fed by anything, and the routing would otherwise report whatever the
1052 // stochastic complement carries back into it.
1053 std::vector<std::vector<bool>> srcmask(M, std::vector<bool>(K, false));
1054 for (std::size_t i = 0; i < M; ++i)
1055 if (L.stations[i].nodetype == qn::NodeType::Source)
1056 for (std::size_t k = 0; k < K; ++k) srcmask[i][k] = true;
1057
1058 AvgResult<T> out;
1059 // Carried, not consumed and dropped: the node table needs the same visits
1060 // the station table just used, or the two disagree on the cache columns.
1061 out.refreshed_struct = refreshed;
1062 // The cache answer a cache branch measured. Empty on every other model, and
1063 // on the fork-join path, whose inner solves are of a TRANSFORMED network.
1064 out.cache = cache;
1065 out.QN = filter_metric(L, s.Q, MetricKind::QLen, &mask);
1066 out.UN = filter_metric(L, s.U, MetricKind::Util, &mask);
1067 out.RN = filter_metric(L, s.R, MetricKind::RespT, nullptr);
1068 out.TN = filter_metric(L, s.Tp, MetricKind::Tput, nullptr);
1069 // Both ArvR and ResidT come from the refreshed struct when the cacheqn
1070 // analyzer supplied one: its cache self-switch is normalized at the ACTUAL
1071 // hit/miss split, so the visits back the carried rate without the over-route
1072 // inflation. filter_metric still keys on the base L for its topology masking.
1073 out.WN = filter_metric(L, sn_get_residt_from_respt(refL, out.RN), MetricKind::ResidT, nullptr);
1074 out.AN = filter_metric(L, sn_get_arvr_from_tput(refL, out.TN), MetricKind::ArvR, &srcmask);
1075 apply_analyzer_arvr(out.AN, s.AN);
1076
1077 // The saturated open-station rule, applied AFTER out.WN so the residence
1078 // times keep their pre-saturation value, exactly as getAvg.m orders it.
1079 if (cap_unstable_open_stations(L, out.QN, out.UN, out.RN, out.TN)) {
1080 if (!warning.empty()) warning += " ";
1081 warning += unstable_open_warning();
1082 }
1083
1084 out.CN = s.C;
1085 out.XN = s.X;
1086 out.method = opt.method;
1087 out.actualmethod = actualmethod;
1088 // Immediate feedback is APPROXIMATED, not refused: a fed-back job holds its
1089 // server, and mean-value analysis has no way to express that, so the visit
1090 // it makes is counted as an ordinary re-entry. The reference warns and
1091 // solves (`runAnalyzer.m:26-27`); refusing here would reject a model MATLAB
1092 // and the JAR both answer. Appended rather than assigned, so a warning the
1093 // dispatch already raised is not swallowed by this one.
1094 if (L.has_immediate_feedback()) {
1095 if (!warning.empty()) warning += " ";
1096 warning +=
1097 "SolverMVA does not handle immediate feedback (immfeed); the solver will treat "
1098 "self-loops as class-switching with re-queueing.";
1099 }
1100 // Verbatim: a user must be able to match it against the reference output.
1101 out.warning = warning;
1102 out.iter = s.iter;
1103 out.converged = s.converged;
1104 out.fj = s.fj; // fork-join section metrics, see getAvgFJ
1105 out.QNfcr = s.QNfcr; // region row, solver_oqnrc only
1106 out.TNfcr = s.TNfcr;
1107 out.RNfcr = s.RNfcr;
1108 out.DropRateNfcr = s.DropRateNfcr;
1109 return out;
1110}
1111
1112} // namespace mva
1113} // namespace line
1114
1115#endif // LINE_SOLVERS_MVA_SOLVER_MVA_RUNNER_H
What a solver observed about the Cache nodes of a model.
std::size_t cols() const
Definition matrix.h:90
std::size_t rows() const
Definition matrix.h:89
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
bool has_immediate_feedback() const
Whether immediate feedback is EFFECTIVE anywhere in the model.
std::size_t stateful_of_station(std::size_t st) const
std::size_t nof_nodes() 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< std::size_t > refclass
(nchains) 1-based class, 0 = none
std::vector< std::vector< bool > > disabled
Matrix< T > rt
sn.rt and sn.rtnodes: the class-expanded routing.
std::map< std::size_t, CacheParam< T > > nodeparam
Cache parameters by 1-based NODE index; only Cache nodes have an entry.
std::vector< double > cap
sn.cap and sn.classcap: the total and per-class buffers.
std::vector< JobClass > classes
std::vector< Station< T > > stations
stations[k-1] is the k-th station
Matrix< T > rates
(nstations x nclasses) service rates and SCVs, with a PARALLEL disabled flag instead of MATLAB's NaN ...
T route_eff(std::size_t r, std::size_t s, std::size_t i, std::size_t j) const
The routing actually in force: the expansion when there is one, else P.
std::vector< std::vector< std::size_t > > inchain
1-based class indices per chain
std::vector< NodeDef > nodes
every node, in creation order
std::vector< std::vector< double > > classcap
std::vector< Matrix< T > > visits
(nchains) each (nstateful x nclasses)
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.
std::vector< std::size_t > station_to_node
(nstations) 1-based node index
std::vector< Region > regions
The fork-join fixed point that drives one inner MVA solve.
The Heidelberger-Trivedi fork-join transform, options.config.fork_join='ht'.
The fork-join transform SolverMVA applies before solving a layer that contains a Fork.
The inputs of a loss network solved by SolverNC, kept beside the result.
LU factorization with partial pivoting, templated on the number type.
The method names of each solver, in listing order.
Port of @@SolverMVA/mvaDispatch.m: one inner solve, choosing the analyzer that fits the model.
The option and result types every MVA analyzer shares.
SnPnFiringRates sn_pn_firing_rates(const qn::NetworkStruct< T > &sn, const Matrix< T > &TN, bool tput_is_tokens)
Ports of matlab/src/api/sn/sn_pn_firing_rates.m and sn_pn_avg_rates.m.
PatienceHandles< T > sn_patience_handles(const qn::NetworkStruct< T > &sn, std::size_t ist, std::size_t r)
Build the patience handles of station ist (0-based), class r.
bool sn_has_bursty_arrival(const qn::NetworkStruct< T > &sn)
std::string sn_patience_refusal(const qn::NetworkStruct< T > &sn, std::size_t ist, std::size_t r)
Port of sn_patience_refusal.m: the by-name refusal of a reneging patience that is not a Markovian law...
Matrix< T > sn_get_node_arvr_from_tput(const qn::NetworkStruct< T > &sn, const Matrix< T > &TN, const Matrix< T > &AN)
Port of sn_get_node_arvr_from_tput.
std::string sn_reducible_chain_refusal(const qn::NetworkStruct< T > &sn)
The by-name refusal of the first closed chain whose (station,class) routing has more than one closed ...
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
NodeType
Node kinds, with the values of MATLAB NodeType.
Definition lang_types.h:345
ImpatienceType
Impatience kinds, with the values of MATLAB ImpatienceType.
Definition lang_types.h:483
std::vector< std::string > methods(const std::string &solver)
Every method name the solver can be asked for, in listing order.
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}...
Matrix< T > sn_get_residt_from_respt(const qn::NetworkStruct< T > &L, const Matrix< T > &RN)
Port of sn_get_residt_from_respt: the per-JOB residence time.
Matrix< T > filter_metric(const qn::NetworkStruct< T > &L, const Matrix< T > &metric, MetricKind kind, const std::vector< std::vector< bool > > *zero_mask)
Port of filterMetric: what @@NetworkSolver/getAvg does between the analyzer and the caller.
MvaSolution< T > solver_oqnrc(const qn::NetworkStruct< T > &L, const MvaOptions &opt)
Port of solver_oqnrc.m.
bool sn_has_sjn(const qn::NetworkStruct< T > &L)
True when the layer has an SJF station, the reference's any(sn.sched == SchedStrategy....
std::string mva_single_class_open_reason(const qn::NetworkStruct< T > &L, const std::string &method)
RQNA and RQT decompose an open network into GI/G/1 queues and build one uncertainty set per flow out ...
Definition mva_types.h:192
bool cap_unstable_open_stations(const qn::NetworkStruct< T > &L, Matrix< T > &QN, Matrix< T > &UN, Matrix< T > &RN, const Matrix< T > &TN)
The saturated open-station rule of @@NetworkSolver/getAvg.m:221-308.
std::string mva_finite_source_variant(const qn::NetworkStruct< T > &L, const std::string &method)
Port of SolverMVA.finiteSourceVariant(sn, method): the finite-source closed form solver_mva_finite_so...
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...
MetricKind
Which metric is being filtered.
std::string polling_reason(const qn::NetworkStruct< T > &L, const std::string &method)
Why SolverMVA cannot answer a model holding a POLLING station under method, or "" when it can (or the...
std::string resolve_method(const qn::NetworkStruct< T > &L, const std::string &method)
Port of SolverMVA.resolveMethod: the feature-driven default -> rqna upgrade for a bursty single-class...
std::vector< std::string > list_valid_methods(const qn::NetworkStruct< T > &L)
Port of SolverMVA.listValidMethods.
std::string mva_erlanga_patience_reason(const qn::NetworkStruct< T > &L)
Why method 'erlanga' cannot answer this model's patience, or "".
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.
std::string mva_mvac_reason(const qn::NetworkStruct< T > &L, const std::string &method)
MVAC is the exact chain recursion over single-server fixed-rate (SSFR) queues and infinite-server cen...
Definition mva_types.h:259
void apply_analyzer_arvr(Matrix< T > &AN, const Matrix< T > &supplied)
Overwrite the routing-derived arrival rates with those an analyzer supplied (MvaSolution::AN,...
const char * unstable_open_warning()
The warning getAvg.m raises when cap_unstable_open_stations() fires.
void mva_check_finite_capacity(const qn::NetworkStruct< T > &L, const std::string &method)
Port of SolverMVA.supportsFiniteCapacity (SolverMVA.m:158-186), the structural capacity gate SolverMV...
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}...
std::string mva_mapqn_reason(const qn::NetworkStruct< T > &L, const std::string &method)
The reason 'amva.mapqn' cannot solve L, or "" when it can (and "" for any other method).
FjMmt< T > fj_fork_join_transform(const qn::NetworkStruct< T > &L, const std::string &method)
options.config.fork_join -> the transform it names.
Definition fj_ht.h:389
std::string mva_breakdown_reason(const qn::NetworkStruct< T > &L, const std::string &method)
Port of SolverMVA.supportsBreakdown: a station with Queue.setBreakdown is served by one arm,...
MvaSolution< T > fj_fixed_point(const qn::NetworkStruct< T > &L, FjMmt< T > &tr, std::vector< T > &lam, const MvaOptions &opt, InnerSolve inner, std::string *warning=nullptr)
Drive the fork-join fixed point of a transformed model to convergence.
Definition fj_driver.h:512
void sn_apply_join_respt(const qn::NetworkStruct< T > &L, const Matrix< T > &QN, const Matrix< T > &AN, Matrix< T > &RN)
A Join reports the PER-SIBLING waiting time, QLen over the SIBLING ARRIVAL RATE, and not QLen over it...
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
Matrix< T > sn_get_arvr_from_tput(const qn::NetworkStruct< T > &L, const Matrix< T > &TN)
Port of sn_get_arvr_from_tput: the arrival rate each station sees, from the throughputs and the class...
void check_method(const qn::NetworkStruct< T > &L, const std::string &method)
Port of runAnalyzerChecks' method gate: a method the solver does not list is refused before any analy...
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.
AvgResult< T > solver_mva_run_analyzer(const qn::NetworkStruct< T > &L, const MvaOptions &opt_in, const Matrix< T > &init_sol)
Port of @@SolverMVA/runAnalyzer.m for the lang='matlab' path: gate, solve, convert,...
DispatchResult< T > mva_dispatch(const qn::NetworkStruct< T > &L, const MvaOptions &opt, const Matrix< T > &init_sol)
The ladder itself.
ChainDemands< T > sn_get_demands_chain(const qn::NetworkStruct< T > &L)
Port of sn_get_demands_chain.
Definition sn_chain.h:63
bool is_oi_loss(const NetworkStruct< T > &sn, std::size_t *qist=nullptr)
Port of sn_is_oi_loss.m: an open Source -> Queue -> Sink system (any number of classes,...
void check_binding_capacity(const std::string &solver, const NetworkStruct< T > &sn)
NetworkSolver.checkBindingCapacity (NetworkSolver.m:1172-1228): the shared structural gate for finite...
FeatureSet mva_feature_set(const std::string &raw_method)
SolverMVA.getFeatureSet, plus getMethodFeatureSet's per-method deltas.
void feature_gate(const std::string &solver, const FeatureSet &declared, const NetworkStruct< T > &sn, const std::string &requested_method="", const std::string &resolved_method="")
runAnalyzerChecks: refuse a model the solver does not declare, by name.
std::string mva_base_method(const std::string &method)
The method name with any leading "amva." alias stripped.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
std::vector< T > solve(const Matrix< T > &A, const std::vector< T > &b)
Convenience: solve Ax = b, leaving A and b untouched.
Definition lu.h:158
A queueing network and its refreshed NetworkStruct.
Chain aggregation and de-aggregation.
Port of matlab/src/api/sn/sn_has_bursty_arrival.m.
Ports of matlab/src/api/sn/sn_get_node_arvr_from_tput.m and sn_get_node_tput_from_tput....
Port of matlab/src/api/sn/sn_patience_handles.m.
Ports of matlab/src/api/sn/sn_pn_firing_rates.m and sn_pn_avg_rates.m.
Port of sn_reducible_chain_refusal.m: refusal of a closed chain whose (station,class) routing is redu...
The DECLARED side of the gate: one feature set per solver.
Closed networks with shortest-job-next (SJF) stations, ladder branch 0.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
The patience law of one station-class pair, in the forms the solvers consume.
bool present
Whether the pair declares reneging at all; everything below is unset when false.
bool isExponential
Whether the law is exponential, in which case the analysis is exact.
What sn_pn_firing_rates returns; x empty means "no answer", as in the reference.
std::vector< std::vector< double > > produced
produced[mode][place * nclasses + class], the reference's (mm, pp, k).
std::vector< double > x
firing rate per mode
std::vector< std::size_t > place_nodes
1-based Place node indices
std::size_t nclasses
the stride of the two tables above
The metrics getAvg returns, after filtering.
std::shared_ptr< qn::NetworkStruct< T > > refreshed_struct
The struct whose cache self-switch carries the CONVERGED hit/miss split, filled by the cacheqn branch...
Matrix< T > TN
throughput
solvers::LossnInfo lossn
self.result.LossN: the loss-network inputs SolverNC keeps for getAvgLinkTable, EMPTY for every other ...
Matrix< T > RN
response time, per visit
std::vector< T > RNfcr
std::string warning
The reference's own warning text, verbatim, empty when it did not warn.
Matrix< T > UN
utilization
solvers::FjMetrics< T > fj
self.result.FJ: the fork-join section metrics FJQLen, FJRespT and FJTput, filled by the solvers the f...
std::vector< T > listcost
(h) mean storage cost held by each cache list, K_j = sum_i sigma_i pi_ij, filled only by the NC cache...
std::optional< double > lognormconst
@@SolverNC/getProbNormConstAggr, i.e.
std::optional< bool > converged
Whether the fixed point met its tolerance, empty when the handler reports none.
std::vector< T > TNfcr
Matrix< T > WN
residence time, per job
std::string method
the method asked for
std::string actualmethod
the algorithm that ran
std::vector< T > DropRateNfcr
Matrix< T > QN
queue length
std::vector< T > CN
system response time per class
std::vector< T > XN
system throughput per class
solvers::CacheMetrics< T > cache
What the cache branches observed, EMPTY on a model with no Cache node and on every solver that does n...
std::vector< T > QNfcr
Finite capacity region row (1 x K each), filled by method 'oqnrc' alone, EMPTY otherwise.
Matrix< T > AN
arrival rate
The chain-level view of a layer, as sn_get_demands_chain returns it.
Definition sn_chain.h:46
std::vector< double > Nchain
(C) population, infinite for an open chain
Definition sn_chain.h:51
What the dispatch returns: the metrics plus the algorithm that produced them.
std::string actualmethod
The concrete algorithm, as the reference's actualmethod.
std::string warning
Non-empty when the analyzer that ran would have raised a reference line_warning and still returned a ...
solvers::CacheMetrics< T > cache
What a cache branch measured, EMPTY on every model without a Cache.
std::shared_ptr< qn::NetworkStruct< T > > refreshed_struct
Set only by the integrated cacheqn branch: the converged struct whose routing carries the actual hit/...
The transformed layer and the bookkeeping the fixed point needs to drive it and to merge its results ...
Definition fj_mmt.h:113
static constexpr double FineTol
Definition lang_types.h:823
The options SolverMVA reads.
Definition mva_types.h:32
bool base_has_fork
Whether the model this solve came from has a Fork, which the model handed to the analyzer no longer d...
Definition mva_types.h:66
std::string method
Definition mva_types.h:33
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
std::vector< T > RNfcr
Definition mva_types.h:132
Matrix< T > AN
Analyzer-supplied station arrival rates (M x K), NaN where the runner derives them from the routing; ...
Definition mva_types.h:127
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
solvers::FjMetrics< T > fj
Fork-join section metrics set by the fork-join fixed point (fj_driver.h); empty otherwise.
Definition mva_types.h:121
std::vector< T > TNfcr
Definition mva_types.h:132
The parameters of a Cache node, MATLAB's sn.nodeparam{ind} for a Cache.
std::vector< std::size_t > missclass
std::vector< std::size_t > hitclass
One job class of the network.
double population
infinite for an open class
A node of the network.
One station of the network.
std::vector< int > droprule
Per-class blocking rule as an INT, with 0 meaning "not set".
SchedStrategy sched
Every Cache node of the model, in node order; empty on a model with none.
self.result.FJ: one row per Fork/Join pair, one column per class.
Definition fj_metrics.h:43
self.result.LossN.
Definition lossn_info.h:39