LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_mam_basic.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_MAM_SOLVER_MAM_BASIC_H
6#define LINE_SOLVERS_MAM_SOLVER_MAM_BASIC_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * Port of `solver_mam_basic.m`, the `dec.source` analyzer and the default
12 * algorithm of SolverMAM.
13 *
14 * THE METHOD. Each queueing station is solved IN ISOLATION as a matrix-analytic
15 * queue, and the stations are coupled only through a fixed point on the
16 * per-chain throughput. The arrival stream a station sees is not derived from
17 * traffic equations: it is the chain's SOURCE process (or, for a closed chain,
18 * a Poisson surrogate at the current throughput iterate) rescaled to the visit
19 * rate of that station. That is what "dec.source" names, and it is why the
20 * method is cheap and why it is an approximation.
21 *
22 * THE FIXED POINT. `lambda(c)` is the chain arrival rate. Open chains have it
23 * fixed by their source. Closed chains start at the no-contention lower bound
24 * N/sum(D) and are then driven by an ITERATION-AVERAGED regula falsi towards
25 * QN = N; the averaging weight walks from the raw Newton step to a no-op as the
26 * iteration count approaches iter_max, which is what damps the oscillation a
27 * bare N/QN step shows on a saturated chain. A purely open or purely closed
28 * network backs off uniformly by 1/Umax when the busiest station saturates; a
29 * MIXED network instead backs off the CLOSED chains alone onto the capacity the
30 * open traffic leaves free, because scaling the open chains too would report a
31 * throughput below their own source rate.
32 *
33 * WHAT EACH STATION GETS. In branch order, as the reference writes them:
34 * INF delay: U = Q = T S, R = S
35 * PS U = T S / c and the M/M/1-PS-style Q = U/(1-Utot)
36 * FCFS / HOL / FCFSPRPRIO (all-distinct class priorities under HOL or
37 * FCFSPRPRIO take BUTools' MMAPPH1NPPR or MMAPPH1PRPR,
38 * api/mam/mmapph1prio.h; identical priorities are plain FCFS)
39 * open: PH/M/c (renewal arrival, exp service, exact), D/M/c, MAP/D/c,
40 * finite buffer (exact M/M/c/K, exact MMAP/G/1/K at one server,
41 * truncate-and-renormalize otherwise), RAP/RAP/1, MAP/MAP/1 for a
42 * correlated single-class service, else MMAP[K]/PH[K]/1 FCFS
43 * closed: the MMAP[K]/PH[K]/1 queue-length DISTRIBUTION truncated at the
44 * class population, which is what makes a closed chain's queue
45 * length respect its own population bound
46 *
47 * THE SURROGATE DELAY. A c-server station is solved as a single server of c
48 * times the speed and the missing T S (c-1)/c jobs are added back afterwards.
49 * The branches that are exact for c > 1 (PH/M/c, D/M/c, MAP/D/c, M/M/c/K) skip
50 * that correction, which is what `mapdcStations` records.
51 *
52 * THE SETUP / DELAY-OFF BRANCHES ARE WRITTEN, both of them, keyed on
53 * NetworkStruct::setupparam (which IS the reference's sn.hassetup). The open
54 * one collapses the station to one M/G/1-with-setup and splits the QBD's queue
55 * back by load share; the closed one is not a QBD at all but a cold-start race,
56 * charging the setup with the probability that the delay-off timer expired
57 * before the job's own think time did. SolverLN routes a setup-task layer
58 * here through `dec.poisson`.
59 *
60 * WHAT THIS PORT DOES NOT REACH, and why it is not a gap. The reference also
61 * carries a self-looping-class clamp and an ME/RAP branch.
62 * `lang/lang_types.h` has no SelfLoopingClass (JobClassType is OPEN or CLOSED)
63 * and no ME or RAP ProcessType, so no model the C++ layer can express reaches
64 * either. They are noted rather than written, because writing an unreachable
65 * branch is writing an untested one.
66 */
67
68#include <algorithm>
69#include <cmath>
70#include <limits>
71#include <iostream>
72#include <string>
73#include <vector>
74
102#include "line/util/error.h"
104#include "line/util/matrix.h"
105
106namespace line {
107namespace mam {
108
109using lang::GlobalConstants;
112
113namespace basic_detail {
114
115/**
116 * True for a process the MAM analyzer can read as a (D0,D1) pair as declared.
117 *
118 * ME AND RAP COUNT. The matrix-geometric algebra never needs D0 to be a
119 * generator -- R solves a quadratic in the blocks and the stationary vector
120 * follows from it -- so a rational arrival process is as solvable as a
121 * Markovian one, which is why `SolverMAM.getFeatureSet` lists both. They are
122 * also exactly what `sn_nonmarkov_toph`'s default two-moment fit produces, so
123 * excluding them would refuse the conversion the analyzer had just performed.
124 * The paths that DO need a generator -- the retrial solver -- test
125 * `is_markovian_map` on the pair itself and refuse there.
126 */
127inline bool is_markovian_type(ProcessType p) {
128 switch (p) {
129 case ProcessType::EXP:
130 case ProcessType::ERLANG:
131 case ProcessType::HYPEREXP:
132 case ProcessType::PH:
133 case ProcessType::APH:
134 case ProcessType::ME:
135 case ProcessType::RAP:
136 case ProcessType::MAP:
137 case ProcessType::MMAP:
138 case ProcessType::MPH:
139 case ProcessType::COXIAN:
140 case ProcessType::COX2:
141 case ProcessType::MMPP2:
142 case ProcessType::IMMEDIATE:
143 case ProcessType::DISABLED:
144 return true;
145 default:
146 return false;
147 }
148}
149
150/**
151 * True when station `i0` should be answered by MMAP[K]/G[K]/1.
152 *
153 * The generic mmapph1fcfs path reads the service law out of the PHASE-TYPE FIT:
154 * for a Uniform, Gamma, Pareto, Weibull, Lognormal or Det that fit matches the
155 * mean and, once the SCV exceeds one, nothing else. He (2001) needs only the
156 * TRANSFORM of the original law, which `lang::dist_lst` evaluates directly off
157 * `L.service`, so wherever a class declares one of those laws the exact analysis
158 * is available. A matrix-exponential service qualifies too, its transform being
159 * rational; a RAP does NOT, He's analysis assuming INDEPENDENT service times, so
160 * reading a correlated service through its marginal transform would discard
161 * exactly the autocorrelation the RAP was declared to carry. Mirrors MATLAB
162 * `mam_gk1_applicable`.
163 */
164template <class T>
165const lang::Distrib<T>& mam_declared_law(const lang::Distrib<T>& d) {
166 // sn_nonmarkov_toph has already replaced a Gamma or a Lognormal by its
167 // phase-type fit and retagged it PH/ME, keeping the original under
168 // `declared`. That original is the law whose transform this path reads.
169 return d.declared ? *d.declared : d;
170}
171
172template <class T>
173bool mam_gk1_applicable(const qn::NetworkStruct<T>& L, std::size_t i0, std::size_t K) {
174 for (std::size_t r = 0; r < K; ++r) {
175 const lang::ProcessType t = mam_declared_law(L.service[i0][r]).type;
181 return true;
182 }
183 }
184 return false;
185}
186
187/**
188 * Port of `mam_is_renewal_map`: D1 = (-D0 e) sigma to within tolerance, i.e.
189 * the phase after an arrival does not depend on the phase before it.
190 */
191template <class T>
192bool is_renewal_map(const Map<T>& m) {
193 const std::size_t n = m.D0.rows();
194 if (n == 1) return true;
195 double scale = 1.0;
196 for (std::size_t i = 0; i < n; ++i)
197 for (std::size_t j = 0; j < n; ++j)
198 scale = std::max(scale, std::fabs(num_traits<T>::to_double(m.D1(i, j))));
199 const double tol = 1e-9 * scale;
200 std::vector<double> exitrate(n, 0.0), sigma(n, 0.0);
201 double tot = 0.0;
202 for (std::size_t i = 0; i < n; ++i) {
203 for (std::size_t j = 0; j < n; ++j) exitrate[i] += num_traits<T>::to_double(m.D1(i, j));
204 tot += exitrate[i];
205 }
206 if (tot <= 0.0) return true;
207 // sigma from the first row with a positive exit rate.
208 std::size_t ref = n;
209 for (std::size_t i = 0; i < n; ++i)
210 if (exitrate[i] > tol) {
211 ref = i;
212 break;
213 }
214 if (ref == n) return true;
215 for (std::size_t j = 0; j < n; ++j)
216 sigma[j] = num_traits<T>::to_double(m.D1(ref, j)) / exitrate[ref];
217 for (std::size_t i = 0; i < n; ++i)
218 for (std::size_t j = 0; j < n; ++j)
219 if (std::fabs(num_traits<T>::to_double(m.D1(i, j)) - exitrate[i] * sigma[j]) > tol)
220 return false;
221 return true;
222}
223
224/**
225 * Port of `mam_corr_service_classes`: the classes whose MAP or MMPP2 service at
226 * station i0 (0-based) is NOT renewal, so successive service times are
227 * autocorrelated. MMAPPH1FCFS, MMAP[K]/G[K]/1 and the PH/c chain read only the
228 * marginal and would silently drop that. PHi is the (possibly 1/c-scaled) service
229 * MAP row; scaling does not change whether it is renewal.
230 */
231template <class T>
232std::vector<bool> corr_service_classes(const qn::NetworkStruct<T>& L, std::size_t i0,
233 const std::vector<Map<T>>& PHi,
234 const std::vector<bool>& known) {
235 const std::size_t K = L.nclasses;
236 std::vector<bool> corr(K, false);
237 for (std::size_t r = 0; r < K; ++r) {
238 const ProcessType pt = L.service[i0][r].type;
239 if (pt != ProcessType::MAP && pt != ProcessType::MMPP2) continue;
240 if (r >= PHi.size() || !known[r] || PHi[r].D0.rows() == 0) continue;
241 corr[r] = !is_renewal_map(PHi[r]);
242 }
243 return corr;
244}
245
246/** The class names flagged in `mask`, comma separated, for a warning. */
247template <class T>
248std::string class_names(const qn::NetworkStruct<T>& L, const std::vector<bool>& mask) {
249 std::string s;
250 for (std::size_t r = 0; r < mask.size(); ++r)
251 if (mask[r]) s += (s.empty() ? "" : ", ") + L.classes[r].name;
252 return s;
253}
254
255/**
256 * Port of `mam_warn_carried`: names what stays approximate at a station whose
257 * correlated MAP service is answered with its phase carried (qsys_mmapmap1).
258 * At c > 1 that runs on the single-fast-server surrogate; a class declaring a
259 * non-phase-type law next to a correlated one is read through its PH fit.
260 */
261template <class T>
262void warn_carried(const qn::NetworkStruct<T>& L, std::size_t i0, const std::vector<bool>& corr) {
263 const std::size_t K = L.nclasses;
264 const double ns = L.stations[i0].nservers;
265 const std::string name = L.stations[i0].name, corrNames = class_names(L, corr);
266 if (ns > 1.0 && K == 1)
267 std::cerr << "[LINE] Warning: Station " << name << " has a correlated MAP service (class "
268 << corrNames << ") at " << ns << " servers, and its exact MAP/MAP/c chain is "
269 << "too large. MAM carries the service phase on the single-fast-server "
270 << "surrogate, which is an approximation.\n";
271 else if (ns > 1.0)
272 std::cerr << "[LINE] Warning: Station " << name << " has a correlated MAP service (class "
273 << corrNames << ") at " << ns << " servers with " << K << " classes. No exact "
274 << "multiclass multiserver analysis exists, so MAM carries each class's service "
275 << "phase across its services on the single-fast-server surrogate, which is an "
276 << "approximation.\n";
277 std::vector<bool> fitted(K, false);
278 bool anyFitted = false;
279 for (std::size_t r = 0; r < K; ++r) {
280 const ProcessType pt = L.service[i0][r].type;
281 fitted[r] = !corr[r] &&
282 (pt == ProcessType::DET || pt == ProcessType::UNIFORM ||
283 pt == ProcessType::GAMMA || pt == ProcessType::PARETO ||
284 pt == ProcessType::WEIBULL || pt == ProcessType::LOGNORMAL ||
285 pt == ProcessType::LOGLOGISTIC || pt == ProcessType::MASSATORIGIN ||
286 pt == ProcessType::ME);
287 anyFitted = anyFitted || fitted[r];
288 }
289 if (anyFitted)
290 std::cerr << "[LINE] Warning: Station " << name << " mixes a correlated MAP service (class "
291 << corrNames << ") with the non-phase-type service of class "
292 << class_names(L, fitted) << ", which is read through its phase-type fit: "
293 << "MMAP[K]/G[K]/1 admits only independent service times.\n";
294}
295
296/**
297 * Port of `mam_source_feeds_station`: station `jst` is a Source whose whole
298 * output IS the whole arrival stream of station `ist` (both 1-based).
299 *
300 * The exact GI/M/c closed forms (`qsys_phmc`, `qsys_dmc`) take an INTER-ARRIVAL
301 * law and read it out of some station's service slot. That substitution is only
302 * legitimate when the arrivals at `ist` are, sample path for sample path, the
303 * epochs that station generates: `jst` must be a Source (so its process is an
304 * inter-arrival law and not a service law), all of its flow must reach `ist`
305 * directly, and nothing else may reach `ist`. Anywhere else in a network the
306 * input of a station is a DEPARTURE process, which is not the upstream
307 * station's service law and which only the decomposition produces.
308 *
309 * Both tests are written over `sn_rt_stations` rather than over `sn.rt`,
310 * because `sn.rt` is indexed by stateful node and a Router, Cache or stateful
311 * class switch between the Source and `ist` would otherwise read as a foreign
312 * feeder.
313 */
314template <class T>
315bool mam_source_feeds_station(const qn::NetworkStruct<T>& L, std::size_t jst, std::size_t ist) {
316 const std::size_t M = L.nstations, K = L.nclasses;
317 if (jst < 1 || jst > M || ist < 1 || ist > M || jst == ist) return false;
318 if (L.nodes[L.node_of_station(jst) - 1].nodetype != qn::NodeType::Source) return false;
319
320 const Matrix<T> rtst = api::sn_rt_stations(L).rtst;
321 if (rtst.rows() < M * K) return false;
322 const double tol = GlobalConstants::FineTol;
323
324 // All of the source's flow reaches `ist` directly.
325 double emitted = 0.0;
326 for (std::size_t r = 0; r < K; ++r) {
327 const std::size_t row = (jst - 1) * K + r;
328 double into = 0.0, total = 0.0;
329 for (std::size_t c = 0; c < K; ++c)
330 into += num_traits<T>::to_double(rtst(row, (ist - 1) * K + c));
331 for (std::size_t c = 0; c < rtst.cols(); ++c)
332 total += num_traits<T>::to_double(rtst(row, c));
333 if (std::fabs(into - total) > tol) return false;
334 emitted += total;
335 }
336 if (emitted <= tol) return false;
337
338 // Nothing else reaches `ist`.
339 for (std::size_t kst = 1; kst <= M; ++kst) {
340 if (kst == jst) continue;
341 double into = 0.0;
342 for (std::size_t r = 0; r < K; ++r)
343 for (std::size_t c = 0; c < K; ++c)
344 into += num_traits<T>::to_double(rtst((kst - 1) * K + r, (ist - 1) * K + c));
345 if (into > tol) return false;
346 }
347 return true;
348}
349
350/** True when (D0,D1) is a genuine Markovian pair, as `is_markovian_map` tests. */
351template <class T>
352bool is_markovian_map(const Map<T>& m) {
353 const std::size_t n = m.D0.rows();
354 double scale = 1.0;
355 for (std::size_t i = 0; i < n; ++i)
356 for (std::size_t j = 0; j < n; ++j) {
357 scale = std::max(scale, std::fabs(num_traits<T>::to_double(m.D0(i, j))));
358 scale = std::max(scale, std::fabs(num_traits<T>::to_double(m.D1(i, j))));
359 }
360 const double tol = 1e-9 * scale;
361 for (std::size_t i = 0; i < n; ++i) {
362 double rowsum = 0.0;
363 for (std::size_t j = 0; j < n; ++j) {
364 const double a = num_traits<T>::to_double(m.D0(i, j));
365 const double b = num_traits<T>::to_double(m.D1(i, j));
366 if (i != j && a < -tol) return false;
367 if (b < -tol) return false;
368 rowsum += a + b;
369 }
370 if (std::fabs(rowsum) > tol) return false;
371 }
372 return true;
373}
374
375/** The PH mixture `mam_svc_mixture` builds: alpha = [w_k sigma_k], T = blkdiag(S_k). */
376template <class T>
377qsys::ServiceLaw<T> svc_mixture(const Mmap<T>& arv, const std::vector<PhService<T>>& svc) {
378 const T zero = num_traits<T>::from_int(0);
379 const std::size_t K = svc.size();
380 Matrix<T> Q = arv.D0;
381 for (std::size_t k = 0; k < arv.classes(); ++k)
382 for (std::size_t i = 0; i < Q.rows(); ++i)
383 for (std::size_t j = 0; j < Q.cols(); ++j) Q(i, j) += arv.Dc[k](i, j);
384 const std::vector<T> theta = mc::ctmc_solve(Q);
385 std::vector<T> lam(K, zero);
386 T sumL = zero;
387 for (std::size_t k = 0; k < K && k < arv.classes(); ++k) {
388 const std::vector<T> t = vecmul(theta, arv.Dc[k]);
389 for (const T& v : t) lam[k] += v;
390 sumL += lam[k];
391 }
392 std::vector<T> w(K, T(num_traits<T>::from_int(1) / num_traits<T>::from_int((int)K)));
393 if (sumL > zero)
394 for (std::size_t k = 0; k < K; ++k) w[k] = T(lam[k] / sumL);
395
396 std::size_t ntot = 0;
397 for (const PhService<T>& s : svc) ntot += s.S.rows();
398 std::vector<T> alpha(ntot, zero);
399 Matrix<T> Tm(ntot, ntot, zero);
400 std::size_t off = 0;
401 for (std::size_t k = 0; k < K; ++k) {
402 for (std::size_t i = 0; i < svc[k].S.rows(); ++i) {
403 alpha[off + i] = T(w[k] * svc[k].sigma[i]);
404 for (std::size_t j = 0; j < svc[k].S.cols(); ++j) Tm(off + i, off + j) = svc[k].S(i, j);
405 }
406 off += svc[k].S.rows();
407 }
408 return qsys::ServiceLaw<T>::phase_type(alpha, Tm);
409}
410
411/**
412 * `cellsum(sn.visits)`: V(i,k), the visits summed over the chains, at STATION
413 * level.
414 *
415 * `sn.visits` is stateful-indexed, so the station index has to be mapped
416 * through `stateful_of_station` before the sum -- the two agree only when every
417 * stateful node is a station, which is not the case in a fork-join model. Every
418 * MAM analyzer needs it, so it lives here rather than being written out again in
419 * each; `mna_detail` and `solver_mam_basic_mmap` both call this one.
420 */
421template <class T>
422Matrix<T> station_visits(const qn::NetworkStruct<T>& L) {
423 Matrix<T> V(L.nstations, L.nclasses, num_traits<T>::from_int(0));
424 for (std::size_t c = 0; c < L.nchains; ++c)
425 for (std::size_t i = 0; i < L.nstations; ++i) {
426 const std::size_t sf = L.stateful_of_station(i + 1) - 1;
427 for (std::size_t k = 0; k < L.nclasses; ++k) V(i, k) += L.visits[c](sf, k);
428 }
429 return V;
430}
431
432/** The reference's terminal `X(isnan(X))=0` sweep over the metric matrices. */
433template <class T>
434void zero_nans(Matrix<T>& A) {
435 for (std::size_t i = 0; i < A.rows(); ++i)
436 for (std::size_t j = 0; j < A.cols(); ++j)
437 if (std::isnan(num_traits<T>::to_double(A(i, j)))) A(i, j) = num_traits<T>::from_int(0);
438}
439
440/** Output of `mam_truncate_renorm`. */
441template <class T>
442struct TruncRenorm {
443 T meanQ;
444 T lossProb;
445 std::vector<T> p;
446};
447
448/**
449 * Port of `mam_truncate_renorm`: solve the infinite-buffer MMAP[K]/PH[K]/1
450 * FCFS queue, truncate the AGGREGATE marginal at the buffer capacity and
451 * renormalize.
452 *
453 * Multi-class input is first aggregated to a single-class MMAP/PH/1, because
454 * `ncDistr` returns the PER-CLASS marginal P(N_k = n) while the truncation
455 * needs the joint P(N_total = n).
456 */
457template <class T>
458TruncRenorm<T> truncate_renorm(const Mmap<T>& arv, const std::vector<PhService<T>>& svc,
459 std::size_t capK) {
460 const T zero = num_traits<T>::from_int(0);
461 Mmap<T> call = arv;
462 std::vector<PhService<T>> scall = svc;
463 if (svc.size() > 1) {
464 const qsys::ServiceLaw<T> mix = svc_mixture(arv, svc);
465 Matrix<T> Dsum(arv.order(), arv.order(), zero);
466 for (std::size_t k = 0; k < arv.classes(); ++k)
467 for (std::size_t i = 0; i < Dsum.rows(); ++i)
468 for (std::size_t j = 0; j < Dsum.cols(); ++j) Dsum(i, j) += arv.Dc[k](i, j);
469 call.D0 = arv.D0;
470 call.D1 = Dsum;
471 call.Dc.assign(1, Dsum);
472 scall.assign(1, PhService<T>{mix.ph_alpha, mix.ph_T});
473 }
474 const std::vector<std::vector<T>> d = mmapph1fcfs_ncdistr(call, scall, capK + 1);
475 TruncRenorm<T> out;
476 out.p.assign(capK + 1, zero);
477 T mass = zero;
478 for (std::size_t n = 0; n <= capK; ++n) {
479 out.p[n] = num_abs(d[0][n]);
480 mass += out.p[n];
481 }
482 if (!(mass > zero)) {
483 out.p.assign(capK + 1, zero);
484 out.p[0] = num_traits<T>::from_int(1);
485 } else {
486 for (std::size_t n = 0; n <= capK; ++n) out.p[n] /= mass;
487 }
488 T m = zero;
489 for (std::size_t n = 0; n <= capK; ++n) m += num_traits<T>::from_int((int)n) * out.p[n];
490 if (m < zero) m = zero;
491 if (num_traits<T>::to_double(m) > static_cast<double>(capK))
492 m = num_traits<T>::from_int((int)capK);
493 out.meanQ = m;
494 out.lossProb = out.p[capK];
495 return out;
496}
497
498/**
499 * The setup / delay-off pair of a station, or false when it has none.
500 *
501 * Presence in `setupparam` IS the reference's `sn.hassetup(ist)`, and the
502 * reference reads ONE pair per station (`{end}`, the last class that declares
503 * one) rather than a pair per class.
504 */
505template <class T>
506bool station_setup_pair(const qn::NetworkStruct<T>& L, std::size_t ist, lang::Distrib<T>& setup,
507 lang::Distrib<T>& delayoff) {
508 typename std::map<std::size_t, qn::SetupDelayOffParam<T>>::const_iterator it =
509 L.setupparam.find(ist);
510 if (it == L.setupparam.end()) return false;
511 return it->second.last(setup, delayoff);
512}
513
514/**
515 * The open-class setup/delay-off queue, solver_mam_basic.m:507-547.
516 *
517 * `mu_k` is the per-class service RATE the phase representation already carries
518 * scaled by S/nservers, so rho_k is per-class utilization. The aggregate rate
519 * is defined by Lambda / sum(rho_k), which makes the surrogate's utilization
520 * agree with the station's by construction; the QBD then answers one scalar
521 * mean queue length, split back by load share.
522 */
523template <class T>
524void mam_setup_qbd(const qn::NetworkStruct<T>& L, std::size_t ist,
525 const std::vector<T>& aggrLambda,
526 const std::vector<std::vector<PhService<T>>>& svc, const Matrix<T>& S,
527 const std::vector<std::vector<T>>& rates, std::size_t R, double ns,
528 const lang::Distrib<T>& setup, const lang::Distrib<T>& delayoff,
529 std::vector<T>& Qret) {
530 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
531 const std::size_t i0 = ist - 1, K = L.nclasses;
532 for (std::size_t r = 0; r < K; ++r) Qret[r] = zero;
533 if constexpr (!num_traits<T>::has_transcendental) {
534 throw UnsupportedError(ErrorKind{"Arithmetic"},
535 "solver_mam_basic: a setup/delay-off station is solved by a QBD whose G matrix needs "
536 "a logarithm; rerun with --arith double or real");
537 } else {
538 const Map<T> su = lang::dist_to_map(setup), doff = lang::dist_to_map(delayoff);
539 const T alpharate = map_lambda(su), alphascv = map_scv(su);
540 const T betarate = map_lambda(doff), betascv = map_scv(doff);
541
542 std::vector<T> rho(K, zero);
543 T rho_total = zero;
544 for (std::size_t r = 0; r < K; ++r) {
545 if (L.disabled[i0][r]) continue;
546 // mean of the already-scaled service phase: sigma (-S)^-1 e
547 const Matrix<T>& Sr = svc[i0][r].S;
548 if (Sr.rows() == 0) continue;
549 Matrix<T> negS = Sr;
550 for (std::size_t a = 0; a < negS.rows(); ++a)
551 for (std::size_t b = 0; b < negS.cols(); ++b) negS(a, b) = -negS(a, b);
552 const Matrix<T> negSinv = inverse(negS);
553 T mean = zero;
554 for (std::size_t a = 0; a < negSinv.rows() && a < svc[i0][r].sigma.size(); ++a)
555 for (std::size_t b = 0; b < negSinv.cols(); ++b)
556 mean += svc[i0][r].sigma[a] * negSinv(a, b);
557 if (!(mean > zero)) continue;
558 std::size_t c = L.nchains;
559 for (std::size_t cc = 0; cc < L.nchains; ++cc)
560 if (L.chains[cc][r]) c = cc;
561 if (c == L.nchains) continue;
562 // rho = lambda / mu, and mu is 1/mean of the already-scaled phase
563 rho[r] = T(rates[c][r] * mean);
564 rho_total += rho[r];
565 }
566 if (!(rho_total > zero)) return;
567
568 T lam_total = zero;
569 for (std::size_t r = 0; r < K && r < aggrLambda.size(); ++r) lam_total += aggrLambda[r];
570 if (R == 1 && !aggrLambda.empty()) lam_total = aggrLambda[0];
571 if (!(lam_total > zero)) return;
572 const T aggrRate = T(lam_total / rho_total);
573 const T qtot =
574 mam::qbd_setupdelayoff(lam_total, aggrRate, alpharate, alphascv, betarate, betascv);
575 for (std::size_t r = 0; r < K; ++r)
576 if (rho[r] > zero) Qret[r] = T(qtot * rho[r] / rho_total);
577 (void)S;
578 (void)ns;
579 (void)one;
580 }
581}
582
583/**
584 * The closed-class setup/delay-off queue, solver_mam_basic.m.
585 *
586 * THE CLOSED VACATION QUEUE, SOLVED. What stood here was the per-instance
587 * cold-start race `R = p_cold*E[setup] + S`: it raced the delay-off against the
588 * per-instance idle time and carried NO queueing term, so it described a
589 * serverless instance pool rather than a single-server vacation queue and
590 * reported the SAME response time across a tenfold change in the setup mean
591 * (BUG-78). `qbd_setupdelayoff_closed` solves the finite level-dependent chain
592 * the simulator walks, and the aggregate response it returns is split back over
593 * the classes by R_k = W + S_k -- the decomposition the finite-capacity branch
594 * already uses, and an identity when the chain holds one class.
595 */
596template <class T>
597void mam_setup_closed(const qn::NetworkStruct<T>& L, std::size_t ist,
598 const std::vector<std::vector<PhService<T>>>& svc, const Matrix<T>& S,
599 const std::vector<std::vector<T>>& rates, const std::vector<T>& ztchain,
600 const Matrix<T>& V, double ns, const lang::Distrib<T>& setup,
601 const lang::Distrib<T>& delayoff, const Matrix<T>& QNprev,
602 std::vector<T>& Qret) {
603 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
604 const std::size_t i0 = ist - 1, K = L.nclasses;
605 for (std::size_t r = 0; r < K; ++r) Qret[r] = zero;
606 if constexpr (!num_traits<T>::has_transcendental) {
607 throw UnsupportedError(ErrorKind{"Arithmetic"},
608 "solver_mam_basic: the closed setup/delay-off chain fits a phase-type setup and "
609 "delay-off, which needs a square root; rerun with --arith double or real");
610 } else {
611 const Map<T> su = lang::dist_to_map(setup), doff = lang::dist_to_map(delayoff);
612 const T alpharate = map_lambda(su), alphascv = map_scv(su);
613 const T betarate = map_lambda(doff), betascv = map_scv(doff);
614 const T ft = num_traits<T>::from_double(GlobalConstants::FineTol);
615
616 for (std::size_t c = 0; c < L.nchains; ++c) {
617 T Nc = zero;
618 bool finiteNc = true, anyActive = false;
619 for (std::size_t r = 0; r < K; ++r) {
620 if (!L.chains[c][r]) continue;
621 if (!std::isfinite(L.classes[r].population)) { finiteNc = false; break; }
622 Nc += num_traits<T>::from_double(L.classes[r].population);
623 if (rates[c][r] > zero && std::isfinite(num_traits<T>::to_double(S(i0, r))))
624 anyActive = true;
625 }
626 if (!finiteNc || !anyActive || !(Nc > zero)) continue;
627
628 T vtot = zero;
629 for (std::size_t j = 0; j < K; ++j)
630 if (L.chains[c][j]) vtot += V(i0, j);
631 const T ZT = T(ztchain[c] / (vtot > ft ? vtot : ft));
632
633 // THE COMPLEMENTARY DELAY, not the think demand alone.
634 // lambda(n) = (Nc-n)/Z is exact only when everything away from this
635 // station is a pure delay; with other queues in the network the think
636 // demand OVERSTATES the arrival rate and saturates the station. Z is
637 // the mean time a customer currently spends away,
638 // (Nc - QN_here)/lambda_here at this iterate, floored at ZT so it can
639 // never be shorter than the think time it contains. On a Delay+Queue
640 // the two coincide at convergence.
641 T lamHere = zero, qnHere = zero, tnS = zero, tnTot = zero, svcAny = zero;
642 std::size_t svcAnyCount = 0;
643 for (std::size_t r = 0; r < K; ++r) {
644 if (!L.chains[c][r]) continue;
645 T lamK = rates[c][r];
646 if (!std::isfinite(num_traits<T>::to_double(lamK))) lamK = zero;
647 T sk = S(i0, r);
648 if (!std::isfinite(num_traits<T>::to_double(sk))) sk = zero;
649 lamHere += lamK;
650 if (i0 < QNprev.rows() && r < QNprev.cols() &&
651 std::isfinite(num_traits<T>::to_double(QNprev(i0, r))))
652 qnHere += QNprev(i0, r);
653 tnTot += lamK;
654 tnS += T(lamK * sk);
655 if (sk > zero) { svcAny += sk; ++svcAnyCount; }
656 }
657 T Zc = ZT;
658 if (lamHere > ft && T(Nc - qnHere) > zero) {
659 const T zalt = T(T(Nc - qnHere) / lamHere);
660 Zc = zalt > ZT ? zalt : ZT;
661 }
662 // One server serves the whole chain, so the vacation cycle is a
663 // property of the STATION: the chain is solved on the aggregate.
664 T Sbar = tnTot > ft ? T(tnS / tnTot)
665 : (svcAnyCount > 0
666 ? T(svcAny / num_traits<T>::from_int(
667 static_cast<long>(svcAnyCount)))
668 : zero);
669 if (!(Sbar > ft)) continue;
670 const mam::SetupDelayoffClosed<T> cr = mam::qbd_setupdelayoff_closed(
671 Nc, Zc, T(one / Sbar), alpharate, alphascv, betarate, betascv);
672 if (!std::isfinite(num_traits<T>::to_double(cr.QN)) || !(cr.XN > zero)) continue;
673 T Wq = T(T(cr.QN / cr.XN) - Sbar);
674 if (!(Wq > zero)) Wq = zero;
675 for (std::size_t r = 0; r < K; ++r) {
676 if (!L.chains[c][r]) continue;
677 if (L.disabled[i0][r]) continue;
678 // S/c, NOT S: the caller adds the surrogate-delay jobs
679 // TN*S*(c-1)/c back, so a full S here counts the service term
680 // (2c-1)/c times. The two together make S. At c=1 the division
681 // is the identity. Wq still comes from a SINGLE-SERVER chain, so
682 // a closed multiserver setup station is approximated, not solved.
683 const T cserv = (std::isfinite(ns) && ns >= 1.0)
684 ? num_traits<T>::from_double(ns)
685 : one;
686 if (rates[c][r] > zero && std::isfinite(num_traits<T>::to_double(S(i0, r))))
687 Qret[r] = T(rates[c][r] * T(Wq + T(S(i0, r) / cserv)));
688 }
689 }
690 (void)svc;
691 }
692}
693
694/**
695 * The marked arrival stream at station i0 (0-based) of the source decomposition:
696 * every chain's system arrivals thinned to the classes visiting i0, scaled to
697 * their visit rates, superposed, and permuted into class order. `rates[c][r]`
698 * returns the visit rate of class r of chain c at the station. Shared by the
699 * FCFS and LCFS-PR stations, which read the same stream.
700 */
701template <class T>
702Mmap<T> station_arrival(const qn::NetworkStruct<T>& L, const MamOptions& opt, std::size_t i0,
703 const std::vector<T>& lambda, const Matrix<T>& V,
704 const std::vector<Mmap<T>>& chainSysArrivals,
705 std::vector<std::vector<T>>& rates) {
706 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
707 const std::size_t K = L.nclasses, C = L.nchains;
708 // rates(ist,:) per chain: the visit rate of every class at this station.
709 rates.assign(C, std::vector<T>(K, zero));
710 for (std::size_t c = 0; c < C; ++c)
711 for (std::size_t r = 0; r < K; ++r) rates[c][r] = T(V(i0, r) * lambda[c]);
712
713 Mmap<T> aggr;
714 for (std::size_t c = 0; c < C; ++c) {
715 const std::vector<std::size_t>& ic = L.inchain[c];
716 T tot = zero;
717 for (std::size_t r : ic) tot += rates[c][r - 1];
718 Matrix<T> markProb(1, ic.size(), zero);
719 for (std::size_t j = 0; j < ic.size(); ++j)
720 markProb(0, j) = (tot > zero) ? T(rates[c][ic[j] - 1] / tot) : zero;
721 Mmap<T> cur = mmap_mark_probs(chainSysArrivals[c], markProb);
722 // Every arrival process the C++ lang layer can express is Markovian
723 // (there is no ME or RAP ProcessType), so mam_chain_arrival_is_markovian
724 // is unconditionally true and the normalization always applies.
725 cur = mmap_normalize(cur);
726 bool anypos = false;
727 for (std::size_t j = 0; j < ic.size(); ++j)
728 if (rates[c][ic[j] - 1] > zero) anypos = true;
729 if (anypos) {
730 std::vector<T> tgt(ic.size(), zero);
731 for (std::size_t j = 0; j < ic.size(); ++j)
732 tgt[j] = (rates[c][ic[j] - 1] > zero)
733 ? T(one / rates[c][ic[j] - 1])
734 : num_traits<T>::from_double(1.0 / GlobalConstants::Zero);
735 cur = mmap_scale_perclass(cur, tgt);
736 }
737 if (c == 0) {
738 // Chain 1 keeps its own per-class marks; lumping them into one gave
739 // the aggregate the wrong mark count. See _kb/06-solver-catalog.md.
740 aggr = cur;
741 } else {
742 aggr = mmap_super_safe(std::vector<Mmap<T>>{aggr, cur}, opt.space_max);
743 }
744 }
745
746 // The marks come out chain by chain and every reader below indexes them by
747 // CLASS, so permute them into class order.
748 {
749 std::vector<std::size_t> markorder;
750 for (std::size_t c = 0; c < C; ++c)
751 for (std::size_t r : L.inchain[c]) markorder.push_back(r);
752 if (markorder.size() == aggr.Dc.size() &&
753 !std::is_sorted(markorder.begin(), markorder.end())) {
754 std::vector<std::size_t> perm(markorder.size());
755 for (std::size_t j = 0; j < perm.size(); ++j) perm[j] = j;
756 std::stable_sort(perm.begin(), perm.end(),
757 [&markorder](std::size_t a, std::size_t b) {
758 return markorder[a] < markorder[b];
759 });
760 std::vector<Matrix<T>> reordered(perm.size());
761 for (std::size_t j = 0; j < perm.size(); ++j) reordered[j] = aggr.Dc[perm[j]];
762 aggr.Dc.swap(reordered);
763 }
764 }
765
766 return aggr;
767}
768
769/**
770 * Port of `mam_basic_lcfspr`: per-class means at the LCFS-PR station `ist`
771 * (1-based) from Takine's matrix product form, qsys_mmapgk1_lcfspr, fed by the
772 * same marked arrival stream as an FCFS station. The result is exact for the
773 * station in isolation, so no surrogate delay is added and the station is
774 * flagged exact, which exempts it from the response-time floor. An open or
775 * mixed model takes the means directly; an all-closed one truncates each
776 * class's marginal distribution at its population and renormalizes, as the
777 * FCFS branch does with MMAPPH1FCFS.
778 */
779template <class T>
780void solve_lcfspr_station(const qn::NetworkStruct<T>& L, const MamOptions& opt, std::size_t ist,
781 const std::vector<T>& lambda, const Matrix<T>& V, const Matrix<T>& S,
782 const std::vector<std::vector<bool>>& Sknown,
783 const std::vector<std::vector<Map<T>>>& PH,
784 const std::vector<std::vector<bool>>& PHset,
785 const std::vector<Mmap<T>>& chainSysArrivals, Matrix<T>& QN,
786 Matrix<T>& UN, Matrix<T>& RN, Matrix<T>& TN,
787 std::vector<bool>& exact_station, std::vector<bool>& car_warned) {
788 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
789 const std::size_t K = L.nclasses, C = L.nchains, i0 = ist - 1;
790 const std::string stname = L.stations[i0].name;
791 if (L.stations[i0].nservers != 1.0)
792 throw UnsupportedError(ErrorKind{"Structure"},
793 "solver_mam_basic: Station " + stname + " is LCFS-PR with " +
794 std::to_string(L.stations[i0].nservers) + " servers. The MAM analysis of LCFS-PR "
795 "(Takine 2002) is a single-server result; use SolverCTMC or SolverJMT.");
796 if (std::isfinite(sn::sn_get_buffer_size(L, ist)))
797 throw UnsupportedError(ErrorKind{"Structure"},
798 "solver_mam_basic: Station " + stname + " is LCFS-PR with a finite capacity, which "
799 "the MAM analysis of LCFS-PR does not cover; use SolverCTMC or SolverJMT.");
800 lang::Distrib<T> setup_dist, delayoff_dist;
801 if (station_setup_pair(L, ist, setup_dist, delayoff_dist))
802 throw UnsupportedError(ErrorKind{"Structure"},
803 "solver_mam_basic: Station " + stname + " is LCFS-PR with setup times, which the "
804 "MAM analysis of LCFS-PR does not cover; use SolverCTMC or SolverJMT.");
805
806 std::vector<std::vector<T>> rates;
807 const Mmap<T> aggr = station_arrival(L, opt, i0, lambda, V, chainSysArrivals, rates);
808 if (aggr.classes() != K)
809 throw UnsupportedError(ErrorKind{"Structure"},
810 "solver_mam_basic: The arrival process at station " + stname + " carries " +
811 std::to_string(aggr.classes()) + " marks for " + std::to_string(K) + " classes.");
812
813 std::vector<T> lamK(K, zero);
814 for (std::size_t r = 0; r < K; ++r) {
815 for (std::size_t c = 0; c < C; ++c)
816 if (L.chains[c][r]) {
817 lamK[r] = rates[c][r];
818 break;
819 }
820 if (!std::isfinite(num_traits<T>::to_double(lamK[r]))) lamK[r] = zero;
821 }
822
823 const std::vector<bool> corrSvc = corr_service_classes(L, i0, PH[i0], PHset[i0]);
824 if (std::find(corrSvc.begin(), corrSvc.end(), true) != corrSvc.end() && !car_warned[i0]) {
825 car_warned[i0] = true;
826 std::cerr << "[LINE] Warning: Station " << stname << " has a correlated MAP service (class "
827 << class_names(L, corrSvc) << ") under LCFS-PR. The matrix product form reads "
828 << "it through its renewal marginal, which discards the autocorrelation; "
829 << "SolverCTMC carries it exactly.\n";
830 }
831
832 // Service laws. A class that DECLARES a law with no exact phase-type form is
833 // read through that original law's transform, as in MMAP[K]/G[K]/1 FCFS;
834 // every other one through its phase-type representation, already scaled to S.
835 // Should S differ from the declared mean (an inflated S), the law enters as
836 // the transform of a*X, a = S / E[X], with mean S: the reference's
837 // struct('lst', @(s) base(a*s), 'moments', S).
838 typedef qsys::MmapGk1Service<T> Svc;
839 qsys::MmapGk1Transform<T> noLoadT;
840 noLoadT.lst = [](std::complex<double>) { return std::complex<double>(1.0, 0.0); };
841 noLoadT.moments = {zero, zero};
842 const Svc noLoad(noLoadT);
843 std::vector<Svc> laws;
844 for (std::size_t r = 0; r < K; ++r) {
845 const double Sr = num_traits<T>::to_double(S(i0, r));
846 if (!(lamK[r] > zero) || !Sknown[i0][r] || !std::isfinite(Sr) || Sr <= 0.0) {
847 laws.push_back(noLoad);
848 if (lamK[r] < zero) lamK[r] = zero;
849 continue;
850 }
851 const lang::Distrib<T>& decl = mam_declared_law(L.service[i0][r]);
852 const lang::ProcessType t = decl.type;
853 const bool nonPh =
859 if (nonPh) {
860 double dm = std::numeric_limits<double>::quiet_NaN();
861 try {
862 dm = num_traits<T>::to_double(lang::dist_moment(decl, 1u));
863 } catch (const std::exception&) {
864 }
865 if (std::isfinite(dm) && std::fabs(dm / Sr - 1.0) < 1e-9) {
866 laws.push_back(Svc(decl));
867 continue;
868 }
869 if (std::isfinite(dm) && dm > 0.0) {
870 const double a = Sr / dm;
871 qsys::MmapGk1Transform<T> scaled;
872 scaled.lst = [decl, a](std::complex<double> s) { return lang::dist_lst(decl, a * s); };
873 scaled.moments = {S(i0, r)};
874 laws.push_back(Svc(scaled));
875 continue;
876 }
877 }
878 if (!PHset[i0][r] || PH[i0][r].D0.rows() == 0)
879 laws.push_back(Svc(map_scale(lang::dist_to_map(L.service[i0][r]), S(i0, r))));
880 else
881 laws.push_back(Svc(PH[i0][r]));
882 }
883
884 T rho = zero;
885 for (std::size_t r = 0; r < K; ++r)
886 if (Sknown[i0][r]) rho += lamK[r] * S(i0, r);
887 std::vector<T> Qk(K, zero), Rk(K, zero);
888 bool anyOpen = false;
889 long nMax = 0;
890 for (std::size_t r = 0; r < K; ++r) {
891 const double n = L.classes[r].population;
892 if (std::isinf(n)) anyOpen = true;
893 else nMax = std::max(nMax, static_cast<long>(std::llround(n)));
894 }
895 if (num_traits<T>::to_double(rho) >= 1.0 - GlobalConstants::FineTol) {
896 // Saturated: the reference reports each class's whole population.
897 for (std::size_t r = 0; r < K; ++r) {
898 Qk[r] = num_traits<T>::from_double(L.classes[r].population);
899 if (lamK[r] > zero) Rk[r] = T(Qk[r] / lamK[r]);
900 }
901 } else {
902 std::vector<Matrix<T>> MM;
903 MM.push_back(aggr.D0);
904 Matrix<T> D1sum(aggr.D0.rows(), aggr.D0.cols(), zero);
905 for (std::size_t r = 0; r < K; ++r)
906 for (std::size_t a = 0; a < D1sum.rows(); ++a)
907 for (std::size_t b = 0; b < D1sum.cols(); ++b) D1sum(a, b) += aggr.Dc[r](a, b);
908 MM.push_back(D1sum);
909 for (std::size_t r = 0; r < K; ++r) MM.push_back(aggr.Dc[r]);
910 qsys::MmapGk1LcfsprOptions<T> lopt;
911 if (!anyOpen) lopt.nMax = nMax;
912 const qsys::MmapGk1LcfsprResult<T> res = qsys::qsys_mmapgk1_lcfspr(MM, laws, lopt);
913 for (std::size_t r = 0; r < K; ++r) {
914 if (anyOpen) {
915 Qk[r] = res.classMeanQueueLength[r];
916 Rk[r] = res.meanSojournTime[r];
917 continue;
918 }
919 if (!(lamK[r] > zero)) continue;
920 const std::size_t Nk = static_cast<std::size_t>(std::llround(L.classes[r].population));
921 std::vector<T> p(Nk + 1, zero);
922 T acc = zero;
923 for (std::size_t n = 0; n < Nk; ++n) {
924 p[n] = res.classQueueLengthDistr[r][n];
925 acc += p[n];
926 }
927 p[Nk] = num_abs(T(one - acc));
928 T mass = zero;
929 for (std::size_t n = 0; n <= Nk; ++n) mass += p[n];
930 T m = zero;
931 if (mass > zero)
932 for (std::size_t n = 0; n <= Nk; ++n)
933 m += num_traits<T>::from_int((int)n) * T(p[n] / mass);
934 if (m < zero) m = zero;
935 if (num_traits<T>::to_double(m) > static_cast<double>(Nk))
936 m = num_traits<T>::from_int((int)Nk);
937 Qk[r] = m;
938 Rk[r] = T(m / lamK[r]);
939 }
940 }
941 for (std::size_t r = 0; r < K; ++r) {
942 TN(i0, r) = lamK[r];
943 UN(i0, r) = Sknown[i0][r] ? T(TN(i0, r) * S(i0, r)) : zero;
944 QN(i0, r) = Qk[r];
945 RN(i0, r) = Rk[r];
946 }
947 exact_station[i0] = true;
948}
949
950/**
951 * One FCFS / HOL / FCFSPRPRIO station of the decomposition, the inner body of
952 * the reference's `case {SchedStrategy.FCFS, HOL, FCFSPRPRIO}` branch.
953 *
954 * The arrival stream reaching the station is assembled here, chain by chain, in
955 * the reference's order: mark the chain stream by the per-class visit shares,
956 * retarget the per-class mean inter-arrival times, then superpose across
957 * chains. Chain 1 is COLLAPSED to a single mark on the way in -- the reference
958 * writes `{aggr{1} aggr{2} aggr{2}}` after superposing with a zero-rate
959 * exponential -- so the number of marks reaching the queue solver is
960 * 1 + sum_{c>=2} |chain c|, not K. That equals K exactly when chain 1 holds one
961 * class; when it does not, MATLAB itself fails (the utilization line divides a
962 * 1 x R vector by a 1 x K one, and the queue solve requests K outputs from an
963 * R-class analyzer), so the mismatch is refused BY NAME here rather than
964 * answered with a silently different model.
965 */
966template <class T>
967void solve_fcfs_station(const qn::NetworkStruct<T>& L, const MamOptions& opt, std::size_t ist,
968 const std::vector<T>& lambda, const Matrix<T>& V, const Matrix<T>& S,
969 const std::vector<std::vector<bool>>& Sknown,
970 const std::vector<std::vector<Map<T>>>& PH,
971 const std::vector<std::vector<bool>>& PHset,
972 const std::vector<std::vector<PhService<T>>>& svc,
973 const std::vector<Mmap<T>>& chainSysArrivals,
974 const std::vector<T>& ztchain, Matrix<T>& QN, Matrix<T>& UN,
975 Matrix<T>& RN, Matrix<T>& TN, std::vector<bool>& exact_station,
976 std::vector<bool>& car_warned) {
977 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
978 const std::size_t M = L.nstations, K = L.nclasses, C = L.nchains;
979 const double ns = L.stations[ist - 1].nservers;
980 const std::size_t i0 = ist - 1;
981
982 // Distinct class priorities under HOL (FCFSPRPRIO) select BUTools' MMAPPH1NPPR
983 // (MMAPPH1PRPR), mmapph1prio.h; identical priorities fall through to FCFS.
984 const SchedStrategy sched_i = L.stations[i0].sched;
985 bool prio_distinct = false;
986 if (sched_i == SchedStrategy::HOL || sched_i == SchedStrategy::FCFSPRPRIO)
987 for (std::size_t r = 1; r < K; ++r)
988 if (L.classes[r].prio != L.classes[0].prio) prio_distinct = true;
989
990 std::vector<std::vector<T>> rates;
991 Mmap<T> aggr = station_arrival(L, opt, i0, lambda, V, chainSysArrivals, rates);
992
993 const std::size_t R = aggr.classes();
994 lang::Distrib<T> setup_dist, delayoff_dist;
995 const bool has_setup = station_setup_pair(L, ist, setup_dist, delayoff_dist);
996
997 /**
998 * WHO ACTUALLY NEEDS ONE MARK PER CLASS, which is not everyone.
999 *
1000 * The loop above superposes every chain, each contributing one mark per
1001 * class, and permutes the result into class order, so R is K on any model
1002 * whose chains partition the classes. It used to rewrite chain 1 as
1003 * `{aggr{1} aggr{2} aggr{2}}` -- ONE aggregate mark, whatever that chain
1004 * held -- which made R equal 1 + sum_{c>1}|inchain_c|, and the reference
1005 * carried the same defect until 2026-08-16.
1006 *
1007 * The setup/delay-off branches do not read the marking at all: the closed
1008 * one (solver_mam_basic.m:596-650) works from `rates`, `S` and the think
1009 * demand, and the open one takes the SCALAR aggregate rate. That is the
1010 * shape SolverLN sends here for a setup layer -- a single chain over the
1011 * client, entry and call classes -- and MATLAB solves it, so refusing it
1012 * was a WRONG REFUSAL and is what made lqn_setup unsolvable in this port.
1013 *
1014 * MMAPPH1FCFS and the finite-capacity analyzers do read it: each needs the
1015 * r-th mark to be the arrival stream of the r-th service law. There the
1016 * requirement stands, and it is enforced at those branches instead of here,
1017 * so a shape one branch cannot use no longer refuses the ones that can.
1018 */
1019 const std::string mark_refusal =
1020 std::string("solver_mam_basic: the assembled arrival stream at station '") +
1021 L.stations[i0].name + "' carries " + std::to_string(R) +
1022 " marked classes against the model's " + std::to_string(K) +
1023 "; the reference collapses chain 1 to a single mark, so this analyzer has no arrival "
1024 "stream to pair with each service law. A class-switching chain at an FCFS station is "
1025 "refused rather than solved with a mismatched marking";
1026
1027 const std::vector<T> aggrLambda = mmap_lambda(aggr);
1028 double aggrUtil = 0.0;
1029 for (std::size_t r = 0; r < K; ++r) {
1030 // A class this station never serves has a NaN rate in the reference and
1031 // its term is dropped by 'omitnan'; the flag replaces the sentinel here.
1032 if (L.disabled[i0][r]) continue;
1033 const double lam = num_traits<T>::to_double(aggrLambda[R == 1 ? 0 : r]);
1034 const double mu = num_traits<T>::to_double(L.rates(i0, r));
1035 const double den = GlobalConstants::FineTol + mu * ns;
1036 if (den > 0.0 && std::isfinite(den)) aggrUtil += lam / den;
1037 }
1038
1039 std::vector<T> Qret(K, zero);
1040 bool exact_here = false; // the reference's mapdcUsed
1041 T exactRespT = zero;
1042 bool finiteCapUsed = false;
1043 T finiteCapMeanQ = zero, finiteCapLossProb = zero;
1044 std::vector<T> finiteCapLossPerClass;
1045
1046 bool anyopen = false;
1047 for (std::size_t r = 0; r < K; ++r)
1048 if (std::isinf(L.classes[r].population)) anyopen = true;
1049
1050 if (prio_distinct && !car_warned[i0]) {
1051 const std::vector<bool> corrP = corr_service_classes(L, i0, PH[i0], PHset[i0]);
1052 if (std::find(corrP.begin(), corrP.end(), true) != corrP.end()) {
1053 car_warned[i0] = true;
1054 std::cerr << "[LINE] Warning: Station " << L.stations[i0].name
1055 << " has a correlated MAP service (class " << class_names(L, corrP)
1056 << ") under class priorities. The priority analysis reads it through its "
1057 << "renewal marginal, which discards the autocorrelation; SolverCTMC "
1058 << "carries it exactly.\n";
1059 }
1060 }
1061
1062 if (prio_distinct) {
1063 // solver_mam_basic.m:359-380. BUTools orders the marks LOWEST priority
1064 // first and LINE's lower classprio is the higher priority, so the
1065 // classes go in descending classprio; output j belongs to class iK[j].
1066 // Neither branch gates on utilization, as in the reference.
1067 if (R != K) throw UnsupportedError(ErrorKind{"ClassSwitch"}, mark_refusal);
1068 std::vector<std::size_t> iK(K);
1069 for (std::size_t r = 0; r < K; ++r) iK[r] = r;
1070 std::stable_sort(iK.begin(), iK.end(), [&L](std::size_t a, std::size_t b) {
1071 return L.classes[a].prio > L.classes[b].prio;
1072 });
1073 for (std::size_t j = 1; j < K; ++j)
1074 if (L.classes[iK[j]].prio == L.classes[iK[j - 1]].prio)
1075 throw UnsupportedError(ErrorKind{"Priority"},
1076 "solver_mam_basic: Solver MAM requires either identical priorities or all "
1077 "distinct priorities");
1078 Mmap<T> pa;
1079 pa.D0 = aggr.D0;
1080 pa.D1 = aggr.D1;
1081 std::vector<PhService<T>> sl;
1082 for (std::size_t j = 0; j < K; ++j) {
1083 pa.Dc.push_back(aggr.Dc[iK[j]]);
1084 sl.push_back(svc[i0][iK[j]]);
1085 }
1086 const std::vector<std::vector<T>> m = (sched_i == SchedStrategy::FCFSPRPRIO)
1087 ? mmapph1prpr_ncmoms(pa, sl, 1)
1088 : mmapph1nppr_ncmoms(pa, sl, 1);
1089 for (std::size_t j = 0; j < K; ++j) Qret[iK[j]] = m[j][0];
1090 } else if (!(aggrUtil < 1.0 - GlobalConstants::FineTol)) {
1091 for (std::size_t r = 0; r < K; ++r)
1092 Qret[r] = num_traits<T>::from_double(L.classes[r].population);
1093 } else if (anyopen) {
1094 bool isMapDc = (K == 1) && (L.service[i0][0].type == ProcessType::DET);
1095 // D/M/c: the DET law must be the inter-arrival law of the Source feeding
1096 // this queue. A DET station elsewhere carries a SERVICE law, and its
1097 // departures are not deterministic at all.
1098 bool isDMc = false;
1099 std::size_t dmcSource = 0;
1100 if (K == 1 && !isMapDc && L.service[i0][0].type == ProcessType::EXP) {
1101 for (std::size_t j = 1; j <= M; ++j)
1102 if (j != ist && L.service[j - 1][0].type == ProcessType::DET &&
1103 mam_source_feeds_station(L, j, ist)) {
1104 isDMc = true;
1105 dmcSource = j;
1106 break;
1107 }
1108 }
1109 bool isPhM1 = false;
1110 std::size_t phSource = 0;
1111 if (K == 1 && !isMapDc && !isDMc && L.service[i0][0].type == ProcessType::EXP &&
1112 std::isfinite(ns) && ns >= 1.0) {
1113 for (std::size_t j = 1; j <= M; ++j) {
1114 if (j == ist) continue;
1115 const ProcessType sp = L.service[j - 1][0].type;
1116 if (sp != ProcessType::EXP && sp != ProcessType::DET &&
1117 sp != ProcessType::IMMEDIATE && sp != ProcessType::DISABLED) {
1118 // qsys_phmc reads the arrival through its (pie, D0) marginal
1119 // alone, so the gate is RENEWAL and not merely
1120 // non-exponential: a correlated MAP would be answered as its
1121 // renewal marginal.
1122 if (!is_renewal_map(lang::dist_to_map(L.service[j - 1][0]))) continue;
1123 // ... and the law must BE the arrival stream here, not some
1124 // other station's service law.
1125 if (!mam_source_feeds_station(L, j, ist)) continue;
1126 isPhM1 = true;
1127 phSource = j;
1128 break;
1129 } else if (sp == ProcessType::EXP && ns > 1.0 && M == 2 &&
1130 L.nodes[L.node_of_station(j) - 1].nodetype == qn::NodeType::Source) {
1131 // M/M/c: the single-fast-server surrogate is inexact for
1132 // c > 1, so take the exact Erlang-C route instead.
1133 isPhM1 = true;
1134 phSource = j;
1135 break;
1136 }
1137 }
1138 }
1139 // An infinite-buffer closed form would silently discard sn.cap and
1140 // report a lossless queue, so a finite buffer takes precedence. The
1141 // gate is a buffer that can BIND, not a finite sn.cap: refreshCapacity
1142 // derives one from the chain population for every closed model.
1143 const bool isFiniteCap = std::isfinite(sn::sn_get_buffer_size(L, i0 + 1));
1144 if (isFiniteCap) {
1145 isPhM1 = false;
1146 isDMc = false;
1147 }
1148 // EACH CLOSED FORM IS A SURROGATE THAT MAY NOT APPLY, and the reference
1149 // says so by WRAPPING EACH CALL IN `try ... catch <flag> = false`
1150 // (solver_mam_basic.m:417-445): the gates above are structural (which
1151 // laws are present), while the surrogate's own stability is only known
1152 // once it is evaluated. The PH/M/c arm takes ANOTHER station's service
1153 // law as the arrival process, so its rho is the ratio of two service
1154 // rates and can exceed one on a perfectly stable network -- `oqn_basic`
1155 // (Source Exp(0.1) -> Delay HyperExp -> Queue1 Exp(1)) is exactly that,
1156 // and this port propagated `qsys_phmc: load rho must be strictly less
1157 // than 1` out of SolverMAM instead of answering with the generic
1158 // MMAPPH1FCFS path the reference falls back to. The catch is the GATE,
1159 // not a mask: a refused surrogate leaves `exact_here` false and the
1160 // model is still solved, by the analyzer the reference would use.
1161 if (isPhM1) {
1162 try {
1163 const T muQ = T(one / S(i0, 0));
1164 const Map<T> src = lang::dist_to_map(L.service[phSource - 1][0]);
1165 const qsys::PhMcResult<T> r = qsys::qsys_phmc(
1166 map_pie(src), src.D0, muQ, static_cast<unsigned>(std::llround(ns)));
1167 Qret[0] = r.meanQueueLength;
1168 exactRespT = r.meanSojournTime;
1169 exact_here = true;
1170 } catch (const std::exception&) {
1171 isPhM1 = false;
1172 }
1173 }
1174 if (!exact_here && isDMc) {
1175 try {
1176 const T muQ = T(one / S(i0, 0));
1177 const qsys::DmcResult<T> r = qsys::qsys_dmc(
1178 L.rates(dmcSource - 1, 0), muQ, static_cast<unsigned>(std::llround(ns)));
1179 Qret[0] = r.meanQueueLength;
1180 exactRespT = r.meanSojournTime;
1181 exact_here = true;
1182 } catch (const std::exception&) {
1183 isDMc = false;
1184 }
1185 }
1186 if (!exact_here && !isFiniteCap && isMapDc) {
1187 try {
1188 Map<T> arv;
1189 arv.D0 = aggr.D0;
1190 arv.D1 = aggr.D1;
1191 const qsys::MapDcResult<T> r =
1192 qsys::qsys_mapdc(arv, S(i0, 0), static_cast<unsigned>(std::llround(ns)));
1193 Qret[0] = r.meanQueueLength;
1194 exactRespT = r.meanSojournTime;
1195 exact_here = true;
1196 } catch (const std::exception&) {
1197 isMapDc = false;
1198 }
1199 }
1200 // MAP/M/c: the PH/M/c gate above refused this station because its
1201 // aggregate arrival stream is NOT renewal. The single-fast-server
1202 // surrogate the generic path would use ignores the arrival
1203 // correlation; the level-dependent QBD is exact. c = 1 already goes to
1204 // the exact MAP/MAP/1 path, so only c > 1 is claimed here.
1205 bool isMapMc = !exact_here && !isFiniteCap && (K == 1) && !isMapDc && !isDMc &&
1206 !isPhM1 && L.service[i0][0].type == ProcessType::EXP &&
1207 std::isfinite(ns) && ns > 1.0;
1208 if (isMapMc) {
1209 try {
1210 Map<T> arv;
1211 arv.D0 = aggr.D0;
1212 arv.D1 = aggr.D1;
1213 const T muQ = T(one / S(i0, 0));
1214 const qsys::MapMcResult<T> r =
1215 qsys::qsys_mapmc(arv, muQ, static_cast<unsigned>(std::llround(ns)));
1216 Qret[0] = r.meanQueueLength;
1217 exactRespT = r.meanSojournTime;
1218 exact_here = true;
1219 } catch (const std::exception&) {
1220 isMapMc = false;
1221 }
1222 }
1223 // Exact MAP/PH/c. The arms above cover c > 1 only for EXPONENTIAL
1224 // service; with a phase-type service law the generic path scales the
1225 // service by nservers and adds a surrogate delay, an approximation that
1226 // discards the service SHAPE. The service must be RENEWAL, since each
1227 // freed server restarts at alpha. DET goes to MAP/D/c above, and ME/RAP
1228 // have no phase-type configuration space at all.
1229 bool isMapPhc = false, isMapMapc = false;
1230 if (!exact_here && !isFiniteCap && K == 1 && std::isfinite(ns) && ns > 1.0) {
1231 const ProcessType st = L.service[i0][0].type;
1232 if (st != ProcessType::EXP && st != ProcessType::DET && st != ProcessType::ME &&
1233 st != ProcessType::RAP && st != ProcessType::IMMEDIATE &&
1234 st != ProcessType::DISABLED) {
1235 isMapPhc = is_renewal_map(lang::dist_to_map(L.service[i0][0]));
1236 // A CORRELATED service at c > 1: the multiset QBD over (current,
1237 // landing) pairs with the carried phase is exact, where the renewal
1238 // marginal would discard the autocorrelation.
1239 isMapMapc = !isMapPhc && Sknown[i0][0];
1240 }
1241 }
1242 if (isMapMapc) {
1243 try {
1244 Map<T> arv;
1245 arv.D0 = aggr.D0;
1246 arv.D1 = aggr.D1;
1247 const Map<T> svcTrue = map_scale(lang::dist_to_map(L.service[i0][0]), S(i0, 0));
1248 const qsys::MapPhcResult<T> r =
1249 qsys::qsys_mapmapc(arv, svcTrue, static_cast<unsigned>(std::llround(ns)),
1250 static_cast<std::size_t>(500), static_cast<std::size_t>(1));
1251 Qret[0] = r.meanQueueLength;
1252 exactRespT = r.meanSojournTime;
1253 exact_here = true;
1254 } catch (const std::exception&) {
1255 // Too many configurations for the level blocks: the station falls
1256 // to the carried-phase surrogate below, which says so by name.
1257 isMapMapc = false;
1258 }
1259 }
1260 if (isMapPhc) {
1261 try {
1262 Map<T> arv;
1263 arv.D0 = aggr.D0;
1264 arv.D1 = aggr.D1;
1265 const Map<T> svc0 = lang::dist_to_map(L.service[i0][0]);
1266 const qsys::MapPhcResult<T> r = qsys::qsys_mapphc(
1267 arv, map_pie(svc0), svc0.D0, static_cast<unsigned>(std::llround(ns)),
1268 static_cast<std::size_t>(500), static_cast<std::size_t>(1), std::vector<T>());
1269 Qret[0] = r.meanQueueLength;
1270 exactRespT = r.meanSojournTime;
1271 exact_here = true;
1272 } catch (const std::exception&) {
1273 isMapPhc = false;
1274 }
1275 }
1276 if (exact_here) {
1277 // one of the closed forms above answered the station
1278 } else if (isFiniteCap) {
1279 // The buffer analyzers split the loss by class, so each mark has to
1280 // be one class's stream; M/M/c/K is exempt, it uses the total rate.
1281 if (R != K && !(aggr.order() == 1)) throw UnsupportedError(ErrorKind{"ClassSwitch"}, mark_refusal);
1282 const std::size_t capK = static_cast<std::size_t>(std::llround(L.cap[i0]));
1283 // mam_detect_mmck: single-phase arrivals and one shared exponential
1284 // service rate across every active class.
1285 bool isMmck = (aggr.order() == 1);
1286 T muMmck = zero;
1287 if (isMmck) {
1288 bool any = false;
1289 double lo = 0.0, hi = 0.0;
1290 for (std::size_t r = 0; r < K; ++r) {
1291 if (L.disabled[i0][r]) continue;
1292 if (L.service[i0][r].type != ProcessType::EXP) {
1293 isMmck = false;
1294 break;
1295 }
1296 const double v = num_traits<T>::to_double(L.rates(i0, r));
1297 if (!(v > 0.0)) continue;
1298 if (!any) {
1299 lo = hi = v;
1300 any = true;
1301 muMmck = L.rates(i0, r);
1302 } else {
1303 lo = std::min(lo, v);
1304 hi = std::max(hi, v);
1305 }
1306 }
1307 if (!any) isMmck = false;
1308 if (isMmck && hi - lo > 1e-9 * std::max(1.0, hi)) isMmck = false;
1309 }
1310 if (isMmck) {
1311 T lamTot = zero;
1312 for (const T& v : aggrLambda) lamTot += v;
1313 const qsys::MmckResult<T> r =
1314 qsys::qsys_mmck(lamTot, muMmck, static_cast<unsigned>(std::llround(ns)),
1315 static_cast<unsigned>(capK));
1316 finiteCapMeanQ = r.meanQueueLength;
1317 finiteCapLossProb = r.lossProbability;
1318 } else if (ns == 1.0) {
1319 // Exact MMAP[K]/G/1/K: the embedded chain at departure epochs
1320 // resolves the buffer level jointly with the arrival phase, so
1321 // each class gets its own loss ratio.
1322 std::vector<PhService<T>> sl;
1323 for (std::size_t r = 0; r < K; ++r) sl.push_back(svc[i0][r]);
1324 const qsys::ServiceLaw<T> mix = svc_mixture(aggr, sl);
1325 const qsys::MmapG1kResult<T> r = qsys::qsys_mmapg1k(aggr.D0, aggr.Dc, mix, capK);
1326 finiteCapMeanQ = r.meanQueueLength;
1327 finiteCapLossProb = r.lossAggregate;
1328 finiteCapLossPerClass = r.lossRatio;
1329 } else {
1330 std::vector<PhService<T>> sl;
1331 for (std::size_t r = 0; r < K; ++r) sl.push_back(svc[i0][r]);
1332 const TruncRenorm<T> r = truncate_renorm(aggr, sl, capK);
1333 finiteCapMeanQ = r.meanQ;
1334 finiteCapLossProb = r.lossProb;
1335 }
1336 finiteCapUsed = true;
1337 exact_station[i0] = true;
1338 } else if (has_setup) {
1339 // OPEN SETUP / DELAY-OFF, solver_mam_basic.m:507-547. The station is
1340 // collapsed to ONE M/G/1 with setup: the aggregate arrival rate, and
1341 // an aggregate service rate chosen so the aggregate utilization is
1342 // exactly the sum of the per-class ones. The queue that QBD returns
1343 // is then split back over the classes by their share of the load.
1344 mam_setup_qbd(L, ist, aggrLambda, svc, S, rates, R, ns, setup_dist, delayoff_dist,
1345 Qret);
1346 } else {
1347 // MMAPPH1FCFS treats service as a renewal phase type, discarding
1348 // service autocorrelation. A single-class single-server station with
1349 // a genuinely correlated service takes the exact MAP/MAP/1 QBD,
1350 // which carries the service phase across departures.
1351 const bool corr =
1352 (K == 1) && (ns == 1.0) && PHset[i0][0] &&
1353 std::fabs(num_traits<T>::to_double(map_acf(PH[i0][0], std::vector<unsigned>{1})[0])) >
1355 // Classes whose MAP service is CORRELATED, which MMAPPH1FCFS and
1356 // MMAP[K]/G[K]/1 would read as i.i.d. and silently decorrelate.
1357 std::vector<bool> corrSvc(K, false);
1358 if (!corr) corrSvc = corr_service_classes(L, i0, PH[i0], PHset[i0]);
1359 const bool useCarried =
1360 std::find(corrSvc.begin(), corrSvc.end(), true) != corrSvc.end();
1361 if (useCarried && !car_warned[i0]) {
1362 car_warned[i0] = true;
1363 warn_carried(L, i0, corrSvc);
1364 }
1365 if (corr) {
1366 Map<T> arv;
1367 arv.D0 = aggr.D0;
1368 arv.D1 = aggr.Dc[0];
1369 const QbdMapMap1Result<T> r = qbd_mapmap1(arv, PH[i0][0]);
1370 Qret[0] = r.QN;
1371 } else if (useCarried) {
1372 // MMAP[K]/MAP[K]/1 with every correlated class's phase carried across
1373 // its own services: exact at one server; at c > 1 it runs on the
1374 // 1/c-scaled surrogate plus the surrogate delay, which warn_carried names.
1375 if (R != K) throw UnsupportedError(ErrorKind{"ClassSwitch"}, mark_refusal);
1376 std::vector<Map<T>> svcK(PH[i0].begin(), PH[i0].begin() + K);
1377 const qsys::MmapMap1Result<T> cr = qsys::qsys_mmapmap1(aggr, svcK, corrSvc);
1378 for (std::size_t r = 0; r < K; ++r) Qret[r] = cr.meanQueueLength[r];
1379 } else {
1380 // One arrival mark per service law, which is what the analyzer
1381 // pairs up; a collapsed marking has no such pairing.
1382 if (R != K) throw UnsupportedError(ErrorKind{"ClassSwitch"}, mark_refusal);
1383 // MMAP[K]/G[K]/1 whenever a class carries a service law that is
1384 // NOT phase type. mmapph1fcfs_ncmean below reads the PH FIT,
1385 // which matches the mean and, above SCV 1, nothing else; He's
1386 // transform analysis takes the ORIGINAL law, which L.service
1387 // still holds. The result is a /1, hence the single-server gate.
1388 bool gk_done = false;
1389 if (ns == 1.0 && mam_gk1_applicable(L, i0, K)) {
1390 try {
1391 std::vector<Matrix<T>> MM;
1392 MM.push_back(aggr.D0);
1393 Matrix<T> D1sum(aggr.D0.rows(), aggr.D0.cols(),
1394 num_traits<T>::from_int(0));
1395 for (std::size_t r = 0; r < K; ++r)
1396 for (std::size_t a = 0; a < D1sum.rows(); ++a)
1397 for (std::size_t b = 0; b < D1sum.cols(); ++b)
1398 D1sum(a, b) += aggr.Dc[r](a, b);
1399 MM.push_back(D1sum);
1400 for (std::size_t r = 0; r < K; ++r) MM.push_back(aggr.Dc[r]);
1401 std::vector<lang::Distrib<T>> laws;
1402 for (std::size_t r = 0; r < K; ++r)
1403 laws.push_back(mam_declared_law(L.service[i0][r]));
1404 const qsys::MmapGk1Result<T> gk = qsys::qsys_mmapgk1(
1405 MM, laws, std::vector<T>(), static_cast<std::size_t>(1), 1e-12,
1406 static_cast<std::size_t>(10000));
1407 for (std::size_t r = 0; r < K; ++r)
1408 Qret[r] = gk.lambdas[r] * gk.meanSojournTime[r];
1409 // NOT exact_here: that flag carries ONE scalar response
1410 // time for the whole station, which the single-class
1411 // arms above own. Here the answer is per class, and with
1412 // ns == 1 the generic tail computes RN = QN/TN and adds
1413 // no surrogate delay, which is exactly right.
1414 gk_done = true;
1415 } catch (const std::exception&) {
1416 gk_done = false;
1417 }
1418 }
1419 if (!gk_done) {
1420 std::vector<PhService<T>> sl;
1421 for (std::size_t r = 0; r < R; ++r) sl.push_back(svc[i0][r]);
1422 const std::vector<T> m = mmapph1fcfs_ncmean(aggr, sl);
1423 for (std::size_t r = 0; r < K; ++r) Qret[r] = m[r];
1424 }
1425 }
1426 }
1427 } else {
1428 // Every class closed. The queue-length DISTRIBUTION is truncated at each
1429 // class's own population, which is what stops the decomposition from
1430 // reporting more jobs than the chain owns.
1431 std::size_t maxLevel = 1;
1432 for (std::size_t r = 0; r < K; ++r)
1433 if (std::isfinite(L.classes[r].population))
1434 maxLevel += static_cast<std::size_t>(std::llround(L.classes[r].population));
1435 // "the station receives no arrivals" is a property of the AGGREGATE
1436 // stream. The reference passes {D0, Dc[0], ...} to map_lambda, which
1437 // reads only its second argument, so it tested CLASS 1 alone and a
1438 // station whose class 1 is disabled fell here however busy the rest was.
1439 const Map<T> probe = aggr.map();
1440 if (num_traits<T>::to_double(map_lambda(probe)) < GlobalConstants::FineTol) {
1441 for (std::size_t r = 0; r < K; ++r)
1442 Qret[r] = (L.rates(i0, 0) > zero)
1443 ? T(num_traits<T>::from_double(GlobalConstants::FineTol) /
1444 L.rates(i0, 0))
1445 : zero;
1446 } else if (has_setup) {
1447 // CLOSED SETUP / DELAY-OFF, solver_mam_basic.m:596-650. No QBD here:
1448 // a closed job returns after its own chain's think time, so what
1449 // matters is the race between that gap and the delay-off timer.
1450 // p_cold is the delay-off LST at 1/ZT, the probability the server
1451 // has already shut down when the job comes back, and the class holds
1452 // (expected setup paid + its own service) jobs by Little.
1453 mam_setup_closed(L, ist, svc, S, rates, ztchain, V, ns, setup_dist, delayoff_dist,
1454 QN, Qret);
1455 } else {
1456 // Same pairing requirement as the open branch above.
1457 if (R != K) throw UnsupportedError(ErrorKind{"ClassSwitch"}, mark_refusal);
1458 // The truncation needs each class's queue-length DISTRIBUTION, and the
1459 // carried-phase marks of one class have dependent counts, so only the mean
1460 // survives: a correlated service is read through its marginal, by name.
1461 const std::vector<bool> corrC = corr_service_classes(L, i0, PH[i0], PHset[i0]);
1462 if (std::find(corrC.begin(), corrC.end(), true) != corrC.end() && !car_warned[i0]) {
1463 car_warned[i0] = true;
1464 std::cerr << "[LINE] Warning: Station " << L.stations[i0].name
1465 << " has a correlated MAP service (class " << class_names(L, corrC)
1466 << ") in a closed chain. The closed decomposition reads it through "
1467 << "its renewal marginal, which discards the autocorrelation; method "
1468 << "'ldqbd' carries it exactly on a single-class Delay+Queue model, "
1469 << "and SolverCTMC on any model.\n";
1470 }
1471 std::vector<PhService<T>> sl;
1472 for (std::size_t r = 0; r < R; ++r) sl.push_back(svc[i0][r]);
1473 const std::vector<std::vector<T>> pd = mmapph1fcfs_ncdistr(aggr, sl, maxLevel);
1474 for (std::size_t r = 0; r < K; ++r) {
1475 const std::size_t Nk =
1476 static_cast<std::size_t>(std::llround(L.classes[r].population));
1477 std::vector<T> p(Nk + 1, zero);
1478 const std::vector<T>& src = pd[r];
1479 T acc = zero;
1480 for (std::size_t n = 0; n < Nk; ++n) {
1481 p[n] = num_abs(src[n]);
1482 acc += p[n];
1483 }
1484 // Truncating at N(k) folds the tail into that level, so the
1485 // complement must be taken over the TRUNCATED vector.
1486 p[Nk] = num_abs(T(one - acc));
1487 T mass = zero;
1488 for (std::size_t n = 0; n <= Nk; ++n) mass += p[n];
1489 T m = zero;
1490 if (mass > zero)
1491 for (std::size_t n = 0; n <= Nk; ++n)
1492 m += num_traits<T>::from_int((int)n) * T(p[n] / mass);
1493 if (m < zero) m = zero;
1494 if (num_traits<T>::to_double(m) > static_cast<double>(Nk))
1495 m = num_traits<T>::from_int((int)Nk);
1496 Qret[r] = m;
1497 }
1498 }
1499 }
1500
1501 // ---- write the station's metrics back --------------------------------
1502 if (finiteCapUsed) {
1503 // Under FCFS the wait in queue is common to every class, so per class
1504 // R_k = Wq + S_k with Wq recovered from the aggregate queue length.
1505 std::vector<T> inflow(K, zero), eff(K, zero);
1506 for (std::size_t r = 0; r < K; ++r) {
1507 std::size_t c = 0;
1508 for (std::size_t cc = 0; cc < C; ++cc)
1509 if (L.chains[cc][r]) {
1510 c = cc;
1511 break;
1512 }
1513 inflow[r] = rates[c][r];
1514 const T loss = finiteCapLossPerClass.empty() ? finiteCapLossProb
1515 : finiteCapLossPerClass[r];
1516 eff[r] = T(inflow[r] * T(one - loss));
1517 }
1518 T sumTN = zero;
1519 for (std::size_t r = 0; r < K; ++r) sumTN += eff[r];
1520 T Wq = zero;
1521 if (sumTN > zero) {
1522 T sw = zero;
1523 for (std::size_t r = 0; r < K; ++r)
1524 if (Sknown[i0][r]) sw += eff[r] * S(i0, r);
1525 const T w = T(T(finiteCapMeanQ / sumTN) - T(sw / sumTN));
1526 Wq = (w > zero) ? w : zero;
1527 }
1528 for (std::size_t r = 0; r < K; ++r) {
1529 TN(i0, r) = eff[r];
1530 UN(i0, r) = T(TN(i0, r) * S(i0, r) / num_traits<T>::from_double(ns));
1531 if (TN(i0, r) > zero) {
1532 RN(i0, r) = T(Wq + S(i0, r));
1533 QN(i0, r) = T(TN(i0, r) * RN(i0, r));
1534 } else {
1535 RN(i0, r) = zero;
1536 QN(i0, r) = zero;
1537 }
1538 }
1539 } else {
1540 for (std::size_t r = 0; r < K; ++r) {
1541 std::size_t c = 0;
1542 for (std::size_t cc = 0; cc < C; ++cc)
1543 if (L.chains[cc][r]) {
1544 c = cc;
1545 break;
1546 }
1547 TN(i0, r) = rates[c][r];
1548 UN(i0, r) = T(TN(i0, r) * S(i0, r) / num_traits<T>::from_double(ns));
1549 QN(i0, r) = Qret[r];
1550 if (exact_here) {
1551 RN(i0, r) = exactRespT;
1552 exact_station[i0] = true;
1553 } else {
1554 // Add back the jobs at the surrogate delay server the c-fold
1555 // service speedup removed.
1556 if (Sknown[i0][r] && std::isfinite(ns))
1557 QN(i0, r) = T(QN(i0, r) + TN(i0, r) * S(i0, r) *
1558 num_traits<T>::from_double((ns - 1.0) / ns));
1559 RN(i0, r) = (TN(i0, r) > zero) ? T(QN(i0, r) / TN(i0, r)) : zero;
1560 }
1561 }
1562 }
1563}
1564
1565} // namespace basic_detail
1566
1567/**
1568 * Port of `solver_mam_basic.m`.
1569 *
1570 * @param L the refreshed struct, with non-Markovian processes already gated
1571 * out by the runner
1572 * @param opt the MAM options; `space_max` is the arrival superposition budget
1573 */
1574template <class T>
1576 if constexpr (!num_traits<T>::has_transcendental) {
1577 throw UnsupportedError(ErrorKind{"Arithmetic"},
1578 "solver_mam_basic: the matrix-analytic station solves run tolerance-terminated "
1579 "iterations (the Riccati doubling behind MMAP[K]/PH[K]/1, the QBD cyclic reduction) "
1580 "and need transcendental arithmetic; rerun this model with --arith double or "
1581 "--arith real");
1582 } else {
1583 using namespace basic_detail;
1584 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
1585 const std::size_t I = L.nof_nodes(), M = L.nstations, K = L.nclasses, C = L.nchains;
1586 const double tol = opt.tol;
1587
1588 // ---- service times, visits and chain demands -------------------------
1589 Matrix<T> S(M, K, zero);
1590 std::vector<std::vector<bool>> Sknown(M, std::vector<bool>(K, false));
1591 for (std::size_t i = 0; i < M; ++i)
1592 for (std::size_t r = 0; r < K; ++r)
1593 if (!L.disabled[i][r] && L.rates(i, r) > zero) {
1594 S(i, r) = T(one / L.rates(i, r));
1595 Sknown[i][r] = true;
1596 }
1597 const Matrix<T> V = station_visits(L);
1599 // Think demand of each chain, the sum of its demand at the INFINITE-server
1600 // stations. The closed setup branch divides it by the chain's visits to get
1601 // the gap between two visits of one job, which is what the cold-start race
1602 // is against (solver_mam_basic.m:630).
1603 std::vector<T> ztchain(C, zero);
1604 for (std::size_t c = 0; c < C; ++c)
1605 for (std::size_t i = 0; i < M; ++i)
1606 if (std::isinf(L.stations[i].nservers)) ztchain[c] += dem.Lchain(i, c);
1607
1608 Matrix<T> QN(M, K, zero), UN(M, K, zero), RN(M, K, zero), TN(M, K, zero);
1609 std::vector<T> CN(K, zero), XN(K, zero);
1610 std::vector<bool> exact_station(M, false); // the reference's mapdcStations
1611 std::vector<bool> car_warned(M, false); // one carried-phase warning per station
1612
1613 // ---- per-station service phase-type pairs ----------------------------
1614 // Det is left alone (preserveDet), so the exact MAP/D/c branch can claim it.
1615 std::vector<std::vector<Map<T>>> PH(M, std::vector<Map<T>>(K));
1616 std::vector<std::vector<bool>> PHset(M, std::vector<bool>(K, false));
1617 std::vector<std::vector<PhService<T>>> svc(M, std::vector<PhService<T>>(K));
1618 for (std::size_t i = 0; i < M; ++i) {
1619 const SchedStrategy sc = L.stations[i].sched;
1620 if (!(sc == SchedStrategy::FCFS || sc == SchedStrategy::HOL ||
1621 sc == SchedStrategy::FCFSPRPRIO || sc == SchedStrategy::PS ||
1622 sc == SchedStrategy::LCFSPR))
1623 continue;
1624 for (std::size_t r = 0; r < K; ++r) {
1625 if (L.service[i][r].type == ProcessType::DET && opt.preserve_det_resolved()) continue;
1626 const double ns = L.stations[i].nservers;
1627 const T target = std::isfinite(ns) ? T(S(i, r) / num_traits<T>::from_double(ns))
1628 : S(i, r);
1629 if (L.disabled[i][r] || !Sknown[i][r] || !(target > zero)) {
1630 // The reference's `any(isnan(D0))` guard: a class this station
1631 // never serves gets an Immediate service rather than a NaN pair,
1632 // so it contributes nothing and cannot poison the phase-type
1633 // checks downstream.
1635 // MATLAB map_exponential takes a MEAN; the rate spelling gives mean 1e-8.
1636 PH[i][r] = map_exponential_mean(imm);
1637 PHset[i][r] = true;
1638 svc[i][r].sigma.assign(1, one);
1639 svc[i][r].S = Matrix<T>(1, 1, T(-imm));
1640 continue;
1641 }
1642 // ME and RAP are rescaled by the rate ALONE (solver_mam_basic.m:82-88):
1643 // map_scale finishes with map_normalize, whose clamp on the negative
1644 // entries is a repair for a MAP and destruction for a matrix
1645 // exponential, whose negative off-diagonals ARE the representation.
1646 const ProcessType pt = L.service[i][r].type;
1647 PH[i][r] = (pt == ProcessType::ME || pt == ProcessType::RAP)
1648 ? map_scale_rate(lang::dist_to_map(L.service[i][r]), target)
1649 : map_scale(lang::dist_to_map(L.service[i][r]), target);
1650 PHset[i][r] = true;
1651 svc[i][r].sigma = map_pie(PH[i][r]);
1652 svc[i][r].S = PH[i][r].D0;
1653 }
1654 }
1655
1656 // ---- chain classification and the open-chain arrival MMAPs -----------
1657 std::vector<bool> isopenchain(C, false), isclosedchain(C, false);
1658 std::vector<T> lambda(C, zero);
1659 std::vector<Mmap<T>> chainSysArrivals(C);
1660 for (std::size_t c = 0; c < C; ++c) {
1661 double tot = 0.0;
1662 bool inf = false;
1663 for (std::size_t r : L.inchain[c]) {
1664 const double n = L.classes[r - 1].population;
1665 if (std::isinf(n)) inf = true;
1666 else tot += n;
1667 }
1668 (void)tot;
1669 isopenchain[c] = inf;
1670 isclosedchain[c] = !inf;
1671 const std::size_t ist = L.classes[L.inchain[c][0] - 1].refstat;
1672 if (!inf) continue;
1673 // Open chain: the arrival stream is the superposition of the per-class
1674 // source processes, each marked as its own class.
1675 std::vector<Mmap<T>> parts;
1676 for (std::size_t r : L.inchain[c]) {
1677 Mmap<T> m;
1678 if (L.disabled[ist - 1][r - 1] || !(L.rates(ist - 1, r - 1) > zero)) {
1679 // No arrivals from this class: the reference substitutes
1680 // map_exponential(Inf), a zero-rate stream.
1681 m.D0 = Matrix<T>(1, 1, zero);
1682 m.D1 = Matrix<T>(1, 1, zero);
1683 m.Dc.assign(1, Matrix<T>(1, 1, zero));
1684 } else {
1685 const Map<T> src = lang::dist_to_map(L.service[ist - 1][r - 1]);
1686 m.D0 = src.D0;
1687 m.D1 = src.D1;
1688 m.Dc.assign(1, src.D1);
1689 lambda[c] += L.rates(ist - 1, r - 1);
1690 }
1691 parts.push_back(m);
1692 }
1693 chainSysArrivals[c] = parts[0];
1694 for (std::size_t p = 1; p < parts.size(); ++p)
1695 chainSysArrivals[c] = mmap_super_safe(
1696 std::vector<Mmap<T>>{chainSysArrivals[c], parts[p]}, opt.space_max);
1697 for (std::size_t r : L.inchain[c])
1698 TN(ist - 1, r - 1) = L.disabled[ist - 1][r - 1] ? zero : L.rates(ist - 1, r - 1);
1699 }
1700
1701 std::vector<bool> finite_srv(M, false);
1702 for (std::size_t i = 0; i < M; ++i) finite_srv[i] = std::isfinite(L.stations[i].nservers);
1703
1704 bool ismixed = false;
1705 {
1706 bool anyc = false, anyo = false;
1707 for (std::size_t c = 0; c < C; ++c) {
1708 anyc = anyc || isclosedchain[c];
1709 anyo = anyo || isopenchain[c];
1710 }
1711 ismixed = anyc && anyo;
1712 }
1713 const double Ulim = 1.0 - GlobalConstants::CoarseTol;
1714 // A non-mixed closed model keeps its iterate strictly inside the stability region
1715 // (solver_mam_basic.m, _kb/06-solver-catalog.md "Closed-model stability cap").
1716 bool closedCap = false;
1717 for (std::size_t c = 0; c < C; ++c) closedCap = closedCap || isclosedchain[c];
1718
1719 // Floor R at one full service time and restate Q = R*T; see _kb/06-solver-catalog.md (MAM closed-chain population)
1720 std::vector<std::size_t> all_classes(K);
1721 for (std::size_t r = 0; r < K; ++r) all_classes[r] = r + 1;
1722 auto resptime_floor = [&](const std::vector<std::size_t>& rlist) {
1723 for (std::size_t i = 0; i < M; ++i) {
1724 if (exact_station[i]) continue;
1725 for (std::size_t r : rlist) {
1726 const std::size_t k = r - 1;
1727 if (V(i, k) > zero) {
1728 if (!finite_srv[i]) {
1729 RN(i, k) = S(i, k);
1730 } else {
1731 const T byLittle = (TN(i, k) > zero) ? T(QN(i, k) / TN(i, k)) : zero;
1732 RN(i, k) = (S(i, k) > byLittle) ? S(i, k) : byLittle;
1733 }
1734 } else {
1735 RN(i, k) = zero;
1736 }
1737 QN(i, k) = T(RN(i, k) * TN(i, k));
1738 }
1739 }
1740 };
1741
1742 // ---- the throughput fixed point --------------------------------------
1743 Matrix<T> TN_1(M, K, zero);
1744 double delta = std::numeric_limits<double>::infinity();
1745 int it = 0;
1746 while (delta > tol && it <= opt.iter_max) {
1747 // Wall-clock budget (options.timeout): the last completed pass is the
1748 // interim solution, as the reference's `if it>0 && lineTimeoutExceeded`.
1749 if (it > 0 && util::timeout_exceeded()) break;
1750 ++it;
1751 TN_1 = TN;
1752 double Umax = 0.0;
1753 for (std::size_t i = 0; i < M; ++i) {
1754 if (!finite_srv[i]) continue;
1755 double s = 0.0;
1756 for (std::size_t r = 0; r < K; ++r) s += num_traits<T>::to_double(UN(i, r));
1757 if (s > Umax) Umax = s;
1758 }
1759 if (ismixed || Umax < 1.0) {
1760 for (std::size_t c = 0; c < C; ++c) {
1761 if (!isclosedchain[c]) continue;
1762 double Nc = 0.0;
1763 for (std::size_t r : L.inchain[c]) Nc += L.classes[r - 1].population;
1764 double QNc = 0.0;
1765 for (std::size_t i = 0; i < M; ++i)
1766 for (std::size_t r : L.inchain[c]) QNc += num_traits<T>::to_double(QN(i, r - 1));
1767 QNc = std::max(tol, QNc);
1768 T Dsum = zero;
1769 for (std::size_t i = 0; i < M; ++i) Dsum += dem.Lchain(i, c);
1770 if (it == 1) {
1771 lambda[c] = (Dsum > zero) ? T(num_traits<T>::from_double(Nc) / Dsum) : zero;
1772 } else {
1773 // Iteration-averaged regula falsi: the raw N/QN Newton step
1774 // is blended with a no-op, the no-op's weight growing to one
1775 // at iter_max.
1776 const double w = static_cast<double>(it) / opt.iter_max;
1777 const T step = T(num_traits<T>::from_double(Nc / QNc) * lambda[c]);
1778 lambda[c] = T(lambda[c] * num_traits<T>::from_double(w) +
1779 step * num_traits<T>::from_double(1.0 - w));
1780 }
1781 }
1782 }
1783 if (ismixed) {
1784 double theta = 1.0;
1785 bool binding = false;
1786 for (std::size_t i = 0; i < M; ++i) {
1787 if (!finite_srv[i]) continue;
1788 double Uopen = 0.0, Uclosed = 0.0;
1789 for (std::size_t c = 0; c < C; ++c) {
1790 const double u =
1792 if (isclosedchain[c]) Uclosed += u;
1793 else Uopen += u;
1794 }
1795 if (Uclosed > tol) {
1796 binding = true;
1797 theta = std::min(theta, (Ulim - Uopen) / Uclosed);
1798 }
1799 }
1800 if (binding && theta < 1.0)
1801 for (std::size_t c = 0; c < C; ++c)
1802 if (isclosedchain[c])
1803 lambda[c] = T(lambda[c] * num_traits<T>::from_double(std::max(0.0, theta)));
1804 } else if (closedCap) {
1805 // The first iterate N/L is a per-chain bound whose SUM can overload a shared station
1806 // while Umax still reads 0, 1/Umax lands on 1-2e-16, and on multi-class FCFS the
1807 // recomputed Umax rounds to 1.0 or 1-eps (a coin flip): cap the per-server
1808 // utilisation the iterate implies at Ulim instead.
1809 double Uimpl = 0.0;
1810 for (std::size_t i = 0; i < M; ++i) {
1811 if (!finite_srv[i]) continue;
1812 double u = 0.0;
1813 for (std::size_t c = 0; c < C; ++c)
1814 u += num_traits<T>::to_double(dem.Lchain(i, c)) * num_traits<T>::to_double(lambda[c]);
1815 Uimpl = std::max(Uimpl, u / L.stations[i].nservers);
1816 }
1817 if (Uimpl > Ulim)
1818 for (std::size_t c = 0; c < C; ++c)
1819 lambda[c] = T(lambda[c] * num_traits<T>::from_double(Ulim / Uimpl));
1820 } else if (Umax >= 1.0) {
1821 for (std::size_t c = 0; c < C; ++c)
1822 lambda[c] = T(lambda[c] / num_traits<T>::from_double(Umax));
1823 }
1824
1825 for (std::size_t c = 0; c < C; ++c) {
1826 if (isclosedchain[c]) {
1827 // Poisson surrogate at the current throughput iterate. An open
1828 // chain keeps its source MMAP, whose rate is re-imposed per
1829 // station by the per-class scaling below.
1830 chainSysArrivals[c] =
1831 mmap_exponential_vec(std::vector<T>(L.inchain[c].size(), lambda[c]), 1);
1832 }
1833 for (std::size_t i = 0; i < M; ++i)
1834 for (std::size_t r : L.inchain[c]) TN(i, r - 1) = T(V(i, r - 1) * lambda[c]);
1835 }
1836
1837 for (std::size_t ind = 1; ind <= I; ++ind) {
1838 const qn::NodeDef& nd = L.nodes[ind - 1];
1839 if (nd.station == 0) continue;
1840 const std::size_t ist = nd.station;
1841 if (nd.nodetype == qn::NodeType::Join) {
1842 for (std::size_t c = 0; c < C; ++c)
1843 for (std::size_t r : L.inchain[c]) {
1844 std::size_t fanin = 0;
1845 if (L.rtnodes.rows() > 0)
1846 for (std::size_t row = 0; row < L.rtnodes.rows(); ++row)
1847 if (L.rtnodes(row, (ind - 1) * K + (r - 1)) != zero) ++fanin;
1848 if (fanin == 0) fanin = 1;
1849 TN(ist - 1, r - 1) =
1850 T(lambda[c] * V(ist - 1, r - 1) / num_traits<T>::from_int((int)fanin));
1851 UN(ist - 1, r - 1) = zero;
1852 QN(ist - 1, r - 1) = zero;
1853 RN(ist - 1, r - 1) = zero;
1854 }
1855 continue;
1856 }
1857 const SchedStrategy sched = L.stations[ist - 1].sched;
1858 const double ns = L.stations[ist - 1].nservers;
1859 if (sched == SchedStrategy::INF) {
1860 for (std::size_t c = 0; c < C; ++c)
1861 for (std::size_t r : L.inchain[c]) {
1862 const std::size_t k = r - 1;
1863 if (!(V(ist - 1, k) > zero)) {
1864 TN(ist - 1, k) = UN(ist - 1, k) = QN(ist - 1, k) = RN(ist - 1, k) = zero;
1865 continue;
1866 }
1867 TN(ist - 1, k) = T(lambda[c] * V(ist - 1, k));
1868 // An infinite server reports U = QLen = T S: dividing by
1869 // Inf would annihilate it.
1870 UN(ist - 1, k) = T(S(ist - 1, k) * TN(ist - 1, k));
1871 QN(ist - 1, k) = T(TN(ist - 1, k) * S(ist - 1, k));
1872 RN(ist - 1, k) = (TN(ist - 1, k) > zero)
1873 ? T(QN(ist - 1, k) / TN(ist - 1, k))
1874 : zero;
1875 }
1876 } else if (sched == SchedStrategy::PS) {
1877 for (std::size_t c = 0; c < C; ++c) {
1878 for (std::size_t r : L.inchain[c]) {
1879 const std::size_t k = r - 1;
1880 if (!(V(ist - 1, k) > zero)) {
1881 TN(ist - 1, k) = UN(ist - 1, k) = zero;
1882 continue;
1883 }
1884 TN(ist - 1, k) = T(lambda[c] * V(ist - 1, k));
1885 UN(ist - 1, k) = T(S(ist - 1, k) * TN(ist - 1, k) /
1887 }
1888 double Uden = 0.0;
1889 for (std::size_t k = 0; k < K; ++k) Uden += num_traits<T>::to_double(UN(ist - 1, k));
1890 Uden = std::min(1.0 - GlobalConstants::FineTol, Uden);
1891 for (std::size_t r : L.inchain[c]) {
1892 const std::size_t k = r - 1;
1893 if (!(V(ist - 1, k) > zero)) {
1894 QN(ist - 1, k) = RN(ist - 1, k) = zero;
1895 continue;
1896 }
1897 QN(ist - 1, k) =
1898 T(UN(ist - 1, k) / num_traits<T>::from_double(1.0 - Uden));
1899 RN(ist - 1, k) = (TN(ist - 1, k) > zero)
1900 ? T(QN(ist - 1, k) / TN(ist - 1, k))
1901 : zero;
1902 }
1903 }
1904 } else if (sched == SchedStrategy::FCFS || sched == SchedStrategy::HOL ||
1905 sched == SchedStrategy::FCFSPRPRIO) {
1906 solve_fcfs_station(L, opt, ist, lambda, V, S, Sknown, PH, PHset, svc,
1907 chainSysArrivals, ztchain, QN, UN, RN, TN, exact_station,
1908 car_warned);
1909 } else if (sched == SchedStrategy::LCFSPR) {
1910 solve_lcfspr_station(L, opt, ist, lambda, V, S, Sknown, PH, PHset,
1911 chainSysArrivals, QN, UN, RN, TN, exact_station, car_warned);
1912 } else if (sched != SchedStrategy::EXT) {
1913 // The Source is skipped: it has no queue of its own, and the
1914 // dispatch overwrites its throughput with sn.rates afterwards.
1915 // The reference's switch has no default arm, so it skips every
1916 // other discipline SILENTLY; the featset gate in the runner
1917 // rejects them first, so reaching here is a defect and is named.
1918 throw UnsupportedError(ErrorKind{"SchedStrategy"},
1919 std::string("solver_mam_basic: station '") + L.stations[ist - 1].name +
1920 "' uses the " + lang::sched_to_text(sched) +
1921 " discipline, which the dec.source decomposition does not model (it solves "
1922 "INF, PS, FCFS, HOL and LCFS-PR stations only)");
1923 }
1924 }
1925
1926 // Calibrate the fixed point on the REPORTED QN; see _kb/06-solver-catalog.md (MAM closed-chain population)
1927 resptime_floor(all_classes);
1928
1929 delta = 0.0;
1930 for (std::size_t i = 0; i < M; ++i)
1931 for (std::size_t r = 0; r < K; ++r)
1932 delta = std::max(delta, std::fabs(num_traits<T>::to_double(TN(i, r)) -
1933 num_traits<T>::to_double(TN_1(i, r))));
1934 }
1935
1936 // ---- the two rescaling passes ----------------------------------------
1937 for (std::size_t i = 0; i < M; ++i)
1938 for (std::size_t r = 0; r < K; ++r) QN(i, r) = num_abs(QN(i, r));
1939 const Matrix<T> QN0 = QN; // fixed-point queue lengths before the population rescaling
1940 for (int pass = 0; pass < 2; ++pass) {
1941 for (std::size_t c = 0; c < C; ++c) {
1942 double Nc = 0.0;
1943 bool closed = true;
1944 for (std::size_t r : L.inchain[c]) {
1945 if (std::isinf(L.classes[r - 1].population)) closed = false;
1946 else Nc += L.classes[r - 1].population;
1947 }
1948 if (closed) {
1949 T QNc = zero;
1950 for (std::size_t i = 0; i < M; ++i)
1951 for (std::size_t r : L.inchain[c]) QNc += QN(i, r - 1);
1952 if (QNc > zero) {
1953 const T f = T(num_traits<T>::from_double(Nc) / QNc);
1954 for (std::size_t i = 0; i < M; ++i)
1955 for (std::size_t r : L.inchain[c]) QN(i, r - 1) *= f;
1956 }
1957 }
1958 resptime_floor(L.inchain[c]);
1959 if (closed && Nc == 0.0) {
1960 for (std::size_t i = 0; i < M; ++i)
1961 for (std::size_t r : L.inchain[c]) {
1962 QN(i, r - 1) = UN(i, r - 1) = RN(i, r - 1) = TN(i, r - 1) = zero;
1963 }
1964 for (std::size_t r : L.inchain[c]) CN[r - 1] = XN[r - 1] = zero;
1965 }
1966 }
1967 }
1968
1969 // Open classes at a PS station shared with closed chains take the mixed
1970 // product-form relation Q_r = U_r/(1-U_open)*(1+Q_closed). The in-loop
1971 // surrogate U_r/(1-U_tot) is that relation with Q_closed = U_c/(1-U_tot),
1972 // sound off the closed bottleneck but U_c/(1-Ulim) on it, so the open class
1973 // inherited R = D/(1-Ulim) (1000 on mqn_singleserver_ps against 142.28
1974 // exact). Q_closed is the fixed-point closed queue, with each closed chain's
1975 // population filled into its stations in increasing order of that queue, so
1976 // the bottleneck takes what the other stations leave of N. Mirrors
1977 // solver_mam_basic.m.
1978 if (ismixed) {
1979 std::vector<double> Qcl(M, 0.0);
1980 for (std::size_t c = 0; c < C; ++c) {
1981 if (!isclosedchain[c]) continue;
1982 std::vector<double> qc(M, 0.0);
1983 double Nc = 0.0;
1984 for (std::size_t r : L.inchain[c]) {
1985 const std::size_t k = r - 1;
1986 Nc += L.classes[k].population;
1987 for (std::size_t i = 0; i < M; ++i) {
1988 const double q = num_traits<T>::to_double(QN0(i, k));
1989 if (std::isnan(q) || !(V(i, k) > zero)) continue;
1990 qc[i] += q;
1991 }
1992 }
1993 std::vector<std::size_t> ord(M);
1994 for (std::size_t i = 0; i < M; ++i) ord[i] = i;
1995 std::stable_sort(ord.begin(), ord.end(),
1996 [&](std::size_t a, std::size_t b) { return qc[a] < qc[b]; });
1997 double left = Nc;
1998 for (std::size_t j = 0; j < M; ++j) {
1999 const double take = std::min(qc[ord[j]], std::max(0.0, left));
2000 Qcl[ord[j]] += take;
2001 left -= take;
2002 }
2003 }
2004 for (std::size_t i = 0; i < M; ++i) {
2005 if (L.stations[i].sched != SchedStrategy::PS) continue;
2006 double Uopen = 0.0;
2007 for (std::size_t c = 0; c < C; ++c)
2008 if (isopenchain[c])
2009 for (std::size_t r : L.inchain[c])
2010 Uopen += num_traits<T>::to_double(UN(i, r - 1));
2011 Uopen = std::min(1.0 - GlobalConstants::FineTol, Uopen);
2012 for (std::size_t c = 0; c < C; ++c) {
2013 if (!isopenchain[c]) continue;
2014 for (std::size_t r : L.inchain[c]) {
2015 const std::size_t k = r - 1;
2016 if (!(V(i, k) > zero)) continue;
2017 QN(i, k) = T(UN(i, k) * num_traits<T>::from_double((1.0 + Qcl[i]) / (1.0 - Uopen)));
2018 RN(i, k) = (TN(i, k) > zero) ? T(QN(i, k) / TN(i, k)) : zero;
2019 }
2020 }
2021 }
2022 }
2023
2024 for (std::size_t r = 0; r < K; ++r) {
2025 T s = zero;
2026 for (std::size_t i = 0; i < M; ++i) s += RN(i, r);
2027 CN[r] = s;
2028 }
2029 for (std::size_t c = 0; c < C; ++c)
2030 for (std::size_t r : L.inchain[c]) XN[r - 1] = TN(L.classes[r - 1].refstat - 1, r - 1);
2031
2033 out.Q = QN;
2034 out.U = UN;
2035 out.R = RN;
2036 out.Tp = TN;
2037 out.C = CN;
2038 out.X = XN;
2039 out.method = opt.method;
2040 out.iter = it + 2;
2041 return out;
2042 } // if constexpr has_transcendental
2043}
2044
2045} // namespace mam
2046} // namespace line
2047
2048#endif // LINE_SOLVERS_MAM_SOLVER_MAM_BASIC_H
Acyclic phase-type fitters from the first two moments.
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
std::size_t nof_nodes() const
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 > > disabled
std::vector< JobClass > classes
std::vector< Station< T > > stations
stations[k-1] is the k-th station
Matrix< T > rates
(nstations x nclasses) service rates and SCVs, with a PARALLEL disabled flag instead of MATLAB's NaN ...
std::vector< std::vector< std::size_t > > inchain
1-based class indices per chain
std::vector< NodeDef > nodes
every node, in creation order
Steady-state distribution of a continuous-time Markov chain.
What refreshProcessRepresentations and refreshLST compute FROM a distribution: the (D0,...
The exception types the port throws.
options.timeout: one wall-clock budget per top-level solve, on a per-THREAD deadline stack.
The option and result types SolverMAM shares with its analyzers.
Markovian arrival process descriptors: stationary vectors, rate, moments, autocorrelation and the ind...
MAP constructors and structural transformations.
Dense matrix and non-owning view.
The MMAP assembly primitives solver_mam_basic.m builds its per-station arrival stream from: mmap_expo...
Marked MAP (MMAP) algebra: per-class rates, class probabilities, superposition, normalization and sca...
The MMAP[K]/PH[K]/1 FCFS queue: per-class mean number in system and per-class queue-length distributi...
The MMAP[K]/PH[K]/1 priority queue, preemptive resume (mmapph1prpr_*) and non-preemptive (mmapph1nppr...
SnRtStations< T > sn_rt_stations(const qn::NetworkStruct< T > &sn)
mam::Map< T > dist_to_map(const Distrib< T > &d)
The (D0,D1) pair that reaches sn.proc.
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
T dist_lst(const Distrib< T > &d, const T &s)
sn.lst: the Laplace-Stieltjes transform E[exp(-sX)].
ProcessType
Distribution kinds, with the values of MATLAB ProcessType.
Definition lang_types.h:524
@ LOGLOGISTIC
Three reliability laws of Trivedi and Bobbio, "Reliability andAvailability Engineering" (2017),...
Definition lang_types.h:622
const char * sched_to_text(SchedStrategy s)
Definition lang_types.h:248
T dist_moment(const Distrib< T > &d, unsigned k)
The k-th raw moment.
double tot(const std::vector< double > &pops)
std::string name(const Element *el, const std::string &key="name")
std::vector< T > map_acf(const Map< T > &m, const std::vector< unsigned > &lags)
Autocorrelation coefficients of the inter-arrival times at the given lags,.
Definition map_moment.h:168
Mmap< T > mmap_normalize(const Mmap< T > &in)
Clamp negative off-diagonal and per-class entries to zero and rebuild D1 and the diagonal of D0 from ...
std::vector< T > mmapph1fcfs_ncmean(const Mmap< T > &arrival, const std::vector< PhService< T > > &svc)
Per-class mean number of customers in the system, BUTools' 'ncMoms', 1.
std::vector< T > mmap_lambda(const Mmap< T > &m)
Alias kept for parity with the MATLAB name.
Mmap< T > mmap_mark_probs(const Mmap< T > &in, const Matrix< T > &prob)
Re-mark an MMAP by a (K x R) probability matrix (mmap_mark.m): a type-k arrival is reported as class ...
Mmap< T > mmap_scale_perclass(const Mmap< T > &in, const std::vector< T > &M)
Retarget the per-class MEAN inter-arrival times (mmap_scale.m, vector form).
QbdMapMap1Result< T > qbd_mapmap1(const Map< T > &arrival, const Map< T > &service_in, const T &util, std::size_t max_levels)
MAP/MAP/1 queue (qbd_mapmap1.m).
T qbd_setupdelayoff(const T &lambda, const T &mu, const T &alpharate, const T &alphascv, const T &betarate, const T &betascv)
Mean queue length of the M/M/1 queue with setup delay and delay-off (qbd_setupdelayoff....
Mmap< T > mmap_exponential_vec(const std::vector< T > &lambda, std::size_t n=1)
Order-n MMAP with the given per-class arrival rates (mmap_exponential.m).
mva::MvaSolution< T > solver_mam_basic(const qn::NetworkStruct< T > &L, const MamOptions &opt)
Port of solver_mam_basic.m.
std::vector< std::vector< T > > mmapph1prpr_ncmoms(const Mmap< T > &arrival, const std::vector< PhService< T > > &svc, std::size_t n, const PrioQueueOptions &opt=PrioQueueOptions())
Per-class moments 1..n of the number of jobs, MMAP[K]/PH[K]/1 preemptive resume priority.
std::vector< std::vector< T > > mmapph1fcfs_ncdistr(const Mmap< T > &arrival, const std::vector< PhService< T > > &svc, std::size_t levels)
Per-class queue-length distribution, BUTools' 'ncDistr', n: P(N_k = 0..n-1).
Map< T > map_exponential_mean(const T &mean)
Poisson process with the given mean inter-arrival time (map_exponential.m).
Map< T > map_scale_rate(const Map< T > &in, const T &new_mean)
Rescale to a target mean WITHOUT the feasibility repair, for a matrix exponential.
Map< T > map_scale(const Map< T > &in, const T &new_mean)
Rescale time so that the mean inter-arrival time becomes new_mean.
std::vector< T > map_pie(const Map< T > &m)
Phase distribution seen by an arriving job, pie = pi D1 / (pi D1 e).
Definition map_moment.h:89
T map_scv(const Map< T > &m)
Squared coefficient of variation.
Definition map_moment.h:140
SetupDelayoffClosed< T > qbd_setupdelayoff_closed(const T &N, const T &Z, const T &mu, const T &alpharate, const T &alphascv, const T &betarate, const T &betascv)
Mean queue length and throughput of a FINITE-POPULATION queue with setup delay and delay-off,...
T map_lambda(const Map< T > &m)
Stationary arrival rate, lambda = pi D1 e.
Definition map_moment.h:79
std::vector< std::vector< T > > mmapph1nppr_ncmoms(const Mmap< T > &arrival, const std::vector< PhService< T > > &svc, std::size_t n, const PrioQueueOptions &opt=PrioQueueOptions())
Per-class moments 1..n of the number of jobs, MMAP[K]/PH[K]/1 non-preemptive priority.
Mmap< T > mmap_super_safe(const std::vector< Mmap< T > > &in, std::size_t maxorder)
Order-bounded superposition of several MMAPs (mmap_super_safe.m).
std::vector< T > ctmc_solve(const Matrix< T > &Qin, const std::string &linsolver=std::string())
Steady-state distribution of a continuous-time Markov chain.
Definition ctmc_solve.h:133
ChainDemands< T > sn_get_demands_chain(const qn::NetworkStruct< T > &L)
Port of sn_get_demands_chain.
Definition sn_chain.h:63
MapMcResult< T > qsys_mapmc(const mam::Map< T > &arrival, const T &mu, unsigned c, std::size_t dist_size)
MAP/M/c by the matrix-geometric solution.
Definition qsys_mapmc.h:104
MapPhcResult< T > qsys_mapmapc(const mam::Map< T > &arrival, const mam::Map< T > &service, unsigned c, std::size_t dist_size=500, std::size_t num_w_moms=3)
MAP/MAP/c FCFS with the service phase carried in start order, exactly.
MmapGk1Result< T > qsys_mmapgk1(const std::vector< Matrix< T > > &MMAP, const std::vector< MmapGk1Service< T > > &svc, const std::vector< T > &w_points, std::size_t num_w_moms, double tol, std::size_t iter_max, std::size_t quad_nodes)
MMAP[K]/G[K]/1 FCFS, per type.
MmckResult< T > qsys_mmck(const T &lambda, const T &mu, unsigned c, unsigned K)
Exact analysis of the M/M/c/K queue (truncated Erlang form).
Definition qsys_mmck.h:70
MapPhcResult< T > qsys_mapphc(const mam::Map< T > &arrival, const std::vector< T > &alpha, const Matrix< T > &S, unsigned c, std::size_t dist_size, std::size_t num_w_moms, const std::vector< T > &w_points)
MAP/PH/c FCFS, exactly.
MmapMap1Result< T > qsys_mmapmap1(const mam::Mmap< T > &arrival, const std::vector< mam::Map< T > > &svc, std::vector< bool > carry=std::vector< bool >())
MMAP[K]/MAP[K]/1 FCFS with per-class carried service phases, exactly.
MmapG1kResult< T > qsys_mmapg1k(const Matrix< T > &D0, const std::vector< Matrix< T > > &D1c, const ServiceLaw< T > &svc, std::size_t K, const T &tol, std::size_t nmaxCap)
MMAP[K]/G/1/K with tail drop.
MmapGk1LcfsprResult< T > qsys_mmapgk1_lcfspr(const std::vector< Matrix< T > > &MMAP, const std::vector< MmapGk1Service< T > > &svc, const MmapGk1LcfsprOptions< T > &opt)
MMAP[K]/G[K]/1 LCFS-PR, per type, by Takine's matrix product form.
DmcResult< T > qsys_dmc(const T &lambda, const T &mu, unsigned c, unsigned truncation, unsigned quadSteps)
D/M/c: deterministic interarrival times, exponential service.
Definition qsys_dmc.h:122
PhMcResult< T > qsys_phmc(const std::vector< T > &alpha, const Matrix< T > &Tm, const T &mu, unsigned c, unsigned maxIter, const T &tol)
Exact PH/M/c by Neuts' matrix-geometric method.
Definition qsys_phmc.h:97
MapDcResult< T > qsys_mapdc(const mam::Map< T > &arrival, const T &s, unsigned c, std::size_t dist_size, unsigned max_arrivals, std::size_t max_levels, const T &tol, std::size_t num_steps)
MAP/D/c by Crommelin's exact embedded lattice chain.
Definition qsys_mapdc.h:157
double sn_get_buffer_size(const qn::NetworkStruct< T > &sn, std::size_t ist)
Physical buffer size of a station, in jobs, the one in service included.
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_abs(const T &v)
Definition number.h:184
std::vector< T > vecmul(const std::vector< T > &v, const Matrix< T > &A)
Row vector times matrix, v A.
Definition linalg.h:50
Matrix< T > inverse(const Matrix< T > &A)
Inverse by LU with one factorization and n back substitutions.
Definition linalg.h:72
A queueing network and its refreshed NetworkStruct.
The MAP/MAP/1 queue solved as a quasi-birth-death process.
Mean queue length of an M/M/1 queue with a setup delay and a delayed-off period, solved as a QBD.
D/M/c: deterministic interarrival times, exponential service.
The MAP/D/c FCFS queue: c servers, deterministic service of length s, fed by a Markovian arrival proc...
The MAP/MAP/c FCFS queue whose service MAP is CARRIED in service-start order.
The MAP/M/c FCFS queue: c identical exponential servers of rate mu fed by a Markovian arrival process...
The MAP/PH/c FCFS queue, solved exactly.
Exact per-class throughput and loss ratio of an MMAP[K]/G/1/K tail-drop queue.
The MMAP[K]/G[K]/1 FCFS queue: K customer types with class-dependent GENERAL service,...
The MMAP[K]/G[K]/1 LCFS-PR queue: K customer types with class-dependent GENERAL service under preempt...
The MMAP[K]/MAP[K]/1 FCFS queue in which each class's service phase is CARRIED.
Exact analysis of the M/M/c/K queue (truncated Erlang form).
Exact PH/M/c by Neuts' matrix-geometric method.
Chain aggregation and de-aggregation.
Physical buffer size of a station, in jobs, the one in service included.
Port of matlab/src/api/sn/sn_rt_stations.m.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
static constexpr double Immediate
Rate of an Immediate distribution; its mean is 1/Immediate = 1e-8.
Definition lang_types.h:829
static constexpr double FineTol
Definition lang_types.h:823
static constexpr double CoarseTol
Definition lang_types.h:824
The options SolverMAM reads.
Definition mam_types.h:30
A MAP as the pair of matrices (D0, D1).
Definition map_moment.h:53
Matrix< T > D1
Definition map_moment.h:55
Matrix< T > D0
Definition map_moment.h:54
An MMAP: the underlying MAP plus the per-class arrival matrices.
Definition mmap_lambda.h:45
Matrix< T > D0
Definition mmap_lambda.h:46
Matrix< T > D1
Definition mmap_lambda.h:47
std::vector< Matrix< T > > Dc
per-class matrices, sum_c Dc = D1
Definition mmap_lambda.h:48
One class's phase-type service law, He's (sigma_k, S_k).
Definition mmapph1fcfs.h:72
The chain-level view of a layer, as sn_get_demands_chain returns it.
Definition sn_chain.h:46
Matrix< T > Lchain
(M x C) demand
Definition sn_chain.h:47
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 > C
Definition mva_types.h:99
A node of the network.
static ServiceLaw phase_type(const std::vector< T > &alpha, const Matrix< T > &Tmat)
Phase type (alpha, Tmat).