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 (the reference also lists FCFSPRPRIO, routed through BUTools'
37 * MMAPPH1PRPR; that analyzer is not ported, so an FCFSPRPRIO
38 * station reaches the station-ladder throw near the end of this
39 * file instead of a branch here -- the C++ SchedStrategy DOES
40 * have an FCFSPRPRIO enumerator, lang_types.h:144, only no MAM
41 * analyzer serves it)
42 * open: PH/M/c (renewal arrival, exp service, exact), D/M/c, MAP/D/c,
43 * finite buffer (exact M/M/c/K, exact MMAP/G/1/K at one server,
44 * truncate-and-renormalize otherwise), RAP/RAP/1, MAP/MAP/1 for a
45 * correlated single-class service, else MMAP[K]/PH[K]/1 FCFS
46 * closed: the MMAP[K]/PH[K]/1 queue-length DISTRIBUTION truncated at the
47 * class population, which is what makes a closed chain's queue
48 * length respect its own population bound
49 *
50 * THE SURROGATE DELAY. A c-server station is solved as a single server of c
51 * times the speed and the missing T S (c-1)/c jobs are added back afterwards.
52 * The branches that are exact for c > 1 (PH/M/c, D/M/c, MAP/D/c, M/M/c/K) skip
53 * that correction, which is what `mapdcStations` records.
54 *
55 * THE SETUP / DELAY-OFF BRANCHES ARE WRITTEN, both of them, keyed on
56 * NetworkStruct::setupparam (which IS the reference's sn.hassetup). The open
57 * one collapses the station to one M/G/1-with-setup and splits the QBD's queue
58 * back by load share; the closed one is not a QBD at all but a cold-start race,
59 * charging the setup with the probability that the delay-off timer expired
60 * before the job's own think time did. SolverLN routes a setup-task layer
61 * here through `dec.poisson`.
62 *
63 * WHAT THIS PORT DOES NOT REACH, and why it is not a gap. The reference also
64 * carries a self-looping-class clamp and an ME/RAP branch.
65 * `lang/lang_types.h` has no SelfLoopingClass (JobClassType is OPEN or CLOSED)
66 * and no ME or RAP ProcessType, so no model the C++ layer can express reaches
67 * either. They are noted rather than written, because writing an unreachable
68 * branch is writing an untested one.
69 */
70
71#include <algorithm>
72#include <cmath>
73#include <limits>
74#include <string>
75#include <vector>
76
99#include "line/util/error.h"
100#include "line/util/matrix.h"
101
102namespace line {
103namespace mam {
104
105using lang::GlobalConstants;
108
109namespace basic_detail {
110
111/**
112 * True for a process the MAM analyzer can read as a (D0,D1) pair as declared.
113 *
114 * ME AND RAP COUNT. The matrix-geometric algebra never needs D0 to be a
115 * generator -- R solves a quadratic in the blocks and the stationary vector
116 * follows from it -- so a rational arrival process is as solvable as a
117 * Markovian one, which is why `SolverMAM.getFeatureSet` lists both. They are
118 * also exactly what `sn_nonmarkov_toph`'s default two-moment fit produces, so
119 * excluding them would refuse the conversion the analyzer had just performed.
120 * The paths that DO need a generator -- the retrial solver -- test
121 * `is_markovian_map` on the pair itself and refuse there.
122 */
123inline bool is_markovian_type(ProcessType p) {
124 switch (p) {
125 case ProcessType::EXP:
126 case ProcessType::ERLANG:
127 case ProcessType::HYPEREXP:
128 case ProcessType::PH:
129 case ProcessType::APH:
130 case ProcessType::ME:
131 case ProcessType::RAP:
132 case ProcessType::MAP:
133 case ProcessType::MMAP:
134 case ProcessType::COXIAN:
135 case ProcessType::COX2:
136 case ProcessType::MMPP2:
137 case ProcessType::IMMEDIATE:
138 case ProcessType::DISABLED:
139 return true;
140 default:
141 return false;
142 }
143}
144
145/**
146 * True when station `i0` should be answered by MMAP[K]/G[K]/1.
147 *
148 * The generic mmapph1fcfs path reads the service law out of the PHASE-TYPE FIT:
149 * for a Uniform, Gamma, Pareto, Weibull, Lognormal or Det that fit matches the
150 * mean and, once the SCV exceeds one, nothing else. He (2001) needs only the
151 * TRANSFORM of the original law, which `lang::dist_lst` evaluates directly off
152 * `L.service`, so wherever a class declares one of those laws the exact analysis
153 * is available. A matrix-exponential service qualifies too, its transform being
154 * rational; a RAP does NOT, He's analysis assuming INDEPENDENT service times, so
155 * reading a correlated service through its marginal transform would discard
156 * exactly the autocorrelation the RAP was declared to carry. Mirrors MATLAB
157 * `mam_gk1_applicable`.
158 */
159template <class T>
160const lang::Distrib<T>& mam_declared_law(const lang::Distrib<T>& d) {
161 // sn_nonmarkov_toph has already replaced a Gamma or a Lognormal by its
162 // phase-type fit and retagged it PH/ME, keeping the original under
163 // `declared`. That original is the law whose transform this path reads.
164 return d.declared ? *d.declared : d;
165}
166
167template <class T>
168bool mam_gk1_applicable(const qn::NetworkStruct<T>& L, std::size_t i0, std::size_t K) {
169 for (std::size_t r = 0; r < K; ++r) {
170 const lang::ProcessType t = mam_declared_law(L.service[i0][r]).type;
175 return true;
176 }
177 }
178 return false;
179}
180
181/**
182 * Port of `mam_is_renewal_map`: D1 = (-D0 e) sigma to within tolerance, i.e.
183 * the phase after an arrival does not depend on the phase before it.
184 */
185template <class T>
186bool is_renewal_map(const Map<T>& m) {
187 const std::size_t n = m.D0.rows();
188 if (n == 1) return true;
189 double scale = 1.0;
190 for (std::size_t i = 0; i < n; ++i)
191 for (std::size_t j = 0; j < n; ++j)
192 scale = std::max(scale, std::fabs(num_traits<T>::to_double(m.D1(i, j))));
193 const double tol = 1e-9 * scale;
194 std::vector<double> exitrate(n, 0.0), sigma(n, 0.0);
195 double tot = 0.0;
196 for (std::size_t i = 0; i < n; ++i) {
197 for (std::size_t j = 0; j < n; ++j) exitrate[i] += num_traits<T>::to_double(m.D1(i, j));
198 tot += exitrate[i];
199 }
200 if (tot <= 0.0) return true;
201 // sigma from the first row with a positive exit rate.
202 std::size_t ref = n;
203 for (std::size_t i = 0; i < n; ++i)
204 if (exitrate[i] > tol) {
205 ref = i;
206 break;
207 }
208 if (ref == n) return true;
209 for (std::size_t j = 0; j < n; ++j)
210 sigma[j] = num_traits<T>::to_double(m.D1(ref, j)) / exitrate[ref];
211 for (std::size_t i = 0; i < n; ++i)
212 for (std::size_t j = 0; j < n; ++j)
213 if (std::fabs(num_traits<T>::to_double(m.D1(i, j)) - exitrate[i] * sigma[j]) > tol)
214 return false;
215 return true;
216}
217
218/** True when (D0,D1) is a genuine Markovian pair, as `is_markovian_map` tests. */
219template <class T>
220bool is_markovian_map(const Map<T>& m) {
221 const std::size_t n = m.D0.rows();
222 double scale = 1.0;
223 for (std::size_t i = 0; i < n; ++i)
224 for (std::size_t j = 0; j < n; ++j) {
225 scale = std::max(scale, std::fabs(num_traits<T>::to_double(m.D0(i, j))));
226 scale = std::max(scale, std::fabs(num_traits<T>::to_double(m.D1(i, j))));
227 }
228 const double tol = 1e-9 * scale;
229 for (std::size_t i = 0; i < n; ++i) {
230 double rowsum = 0.0;
231 for (std::size_t j = 0; j < n; ++j) {
232 const double a = num_traits<T>::to_double(m.D0(i, j));
233 const double b = num_traits<T>::to_double(m.D1(i, j));
234 if (i != j && a < -tol) return false;
235 if (b < -tol) return false;
236 rowsum += a + b;
237 }
238 if (std::fabs(rowsum) > tol) return false;
239 }
240 return true;
241}
242
243/** The PH mixture `mam_svc_mixture` builds: alpha = [w_k sigma_k], T = blkdiag(S_k). */
244template <class T>
245qsys::ServiceLaw<T> svc_mixture(const Mmap<T>& arv, const std::vector<PhService<T>>& svc) {
246 const T zero = num_traits<T>::from_int(0);
247 const std::size_t K = svc.size();
248 Matrix<T> Q = arv.D0;
249 for (std::size_t k = 0; k < arv.classes(); ++k)
250 for (std::size_t i = 0; i < Q.rows(); ++i)
251 for (std::size_t j = 0; j < Q.cols(); ++j) Q(i, j) += arv.Dc[k](i, j);
252 const std::vector<T> theta = mc::ctmc_solve(Q);
253 std::vector<T> lam(K, zero);
254 T sumL = zero;
255 for (std::size_t k = 0; k < K && k < arv.classes(); ++k) {
256 const std::vector<T> t = vecmul(theta, arv.Dc[k]);
257 for (const T& v : t) lam[k] += v;
258 sumL += lam[k];
259 }
260 std::vector<T> w(K, T(num_traits<T>::from_int(1) / num_traits<T>::from_int((int)K)));
261 if (sumL > zero)
262 for (std::size_t k = 0; k < K; ++k) w[k] = T(lam[k] / sumL);
263
264 std::size_t ntot = 0;
265 for (const PhService<T>& s : svc) ntot += s.S.rows();
266 std::vector<T> alpha(ntot, zero);
267 Matrix<T> Tm(ntot, ntot, zero);
268 std::size_t off = 0;
269 for (std::size_t k = 0; k < K; ++k) {
270 for (std::size_t i = 0; i < svc[k].S.rows(); ++i) {
271 alpha[off + i] = T(w[k] * svc[k].sigma[i]);
272 for (std::size_t j = 0; j < svc[k].S.cols(); ++j) Tm(off + i, off + j) = svc[k].S(i, j);
273 }
274 off += svc[k].S.rows();
275 }
276 return qsys::ServiceLaw<T>::phase_type(alpha, Tm);
277}
278
279/**
280 * `cellsum(sn.visits)`: V(i,k), the visits summed over the chains, at STATION
281 * level.
282 *
283 * `sn.visits` is stateful-indexed, so the station index has to be mapped
284 * through `stateful_of_station` before the sum -- the two agree only when every
285 * stateful node is a station, which is not the case in a fork-join model. Every
286 * MAM analyzer needs it, so it lives here rather than being written out again in
287 * each; `mna_detail` and `solver_mam_basic_mmap` both call this one.
288 */
289template <class T>
290Matrix<T> station_visits(const qn::NetworkStruct<T>& L) {
291 Matrix<T> V(L.nstations, L.nclasses, num_traits<T>::from_int(0));
292 for (std::size_t c = 0; c < L.nchains; ++c)
293 for (std::size_t i = 0; i < L.nstations; ++i) {
294 const std::size_t sf = L.stateful_of_station(i + 1) - 1;
295 for (std::size_t k = 0; k < L.nclasses; ++k) V(i, k) += L.visits[c](sf, k);
296 }
297 return V;
298}
299
300/** The reference's terminal `X(isnan(X))=0` sweep over the metric matrices. */
301template <class T>
302void zero_nans(Matrix<T>& A) {
303 for (std::size_t i = 0; i < A.rows(); ++i)
304 for (std::size_t j = 0; j < A.cols(); ++j)
305 if (std::isnan(num_traits<T>::to_double(A(i, j)))) A(i, j) = num_traits<T>::from_int(0);
306}
307
308/** Output of `mam_truncate_renorm`. */
309template <class T>
310struct TruncRenorm {
311 T meanQ;
312 T lossProb;
313 std::vector<T> p;
314};
315
316/**
317 * Port of `mam_truncate_renorm`: solve the infinite-buffer MMAP[K]/PH[K]/1
318 * FCFS queue, truncate the AGGREGATE marginal at the buffer capacity and
319 * renormalize.
320 *
321 * Multi-class input is first aggregated to a single-class MMAP/PH/1, because
322 * `ncDistr` returns the PER-CLASS marginal P(N_k = n) while the truncation
323 * needs the joint P(N_total = n).
324 */
325template <class T>
326TruncRenorm<T> truncate_renorm(const Mmap<T>& arv, const std::vector<PhService<T>>& svc,
327 std::size_t capK) {
328 const T zero = num_traits<T>::from_int(0);
329 Mmap<T> call = arv;
330 std::vector<PhService<T>> scall = svc;
331 if (svc.size() > 1) {
332 const qsys::ServiceLaw<T> mix = svc_mixture(arv, svc);
333 Matrix<T> Dsum(arv.order(), arv.order(), zero);
334 for (std::size_t k = 0; k < arv.classes(); ++k)
335 for (std::size_t i = 0; i < Dsum.rows(); ++i)
336 for (std::size_t j = 0; j < Dsum.cols(); ++j) Dsum(i, j) += arv.Dc[k](i, j);
337 call.D0 = arv.D0;
338 call.D1 = Dsum;
339 call.Dc.assign(1, Dsum);
340 scall.assign(1, PhService<T>{mix.ph_alpha, mix.ph_T});
341 }
342 const std::vector<std::vector<T>> d = mmapph1fcfs_ncdistr(call, scall, capK + 1);
343 TruncRenorm<T> out;
344 out.p.assign(capK + 1, zero);
345 T mass = zero;
346 for (std::size_t n = 0; n <= capK; ++n) {
347 out.p[n] = num_abs(d[0][n]);
348 mass += out.p[n];
349 }
350 if (!(mass > zero)) {
351 out.p.assign(capK + 1, zero);
352 out.p[0] = num_traits<T>::from_int(1);
353 } else {
354 for (std::size_t n = 0; n <= capK; ++n) out.p[n] /= mass;
355 }
356 T m = zero;
357 for (std::size_t n = 0; n <= capK; ++n) m += num_traits<T>::from_int((int)n) * out.p[n];
358 if (m < zero) m = zero;
359 if (num_traits<T>::to_double(m) > static_cast<double>(capK))
360 m = num_traits<T>::from_int((int)capK);
361 out.meanQ = m;
362 out.lossProb = out.p[capK];
363 return out;
364}
365
366/**
367 * One FCFS / HOL station of the decomposition, the inner body of
368 * the reference's `case {SchedStrategy.FCFS, HOL, FCFSPRPRIO}` branch. The C++
369 * SchedStrategy enumerator for FCFSPRPRIO exists (lang_types.h:144); what is
370 * missing is a MAM analyzer for it (BUTools' MMAPPH1PRPR is not ported), so
371 * only FCFS and HOL are dispatched here and an FCFSPRPRIO station falls to the
372 * station-ladder throw instead.
373 *
374 * The arrival stream reaching the station is assembled here, chain by chain, in
375 * the reference's order: mark the chain stream by the per-class visit shares,
376 * retarget the per-class mean inter-arrival times, then superpose across
377 * chains. Chain 1 is COLLAPSED to a single mark on the way in -- the reference
378 * writes `{aggr{1} aggr{2} aggr{2}}` after superposing with a zero-rate
379 * exponential -- so the number of marks reaching the queue solver is
380 * 1 + sum_{c>=2} |chain c|, not K. That equals K exactly when chain 1 holds one
381 * class; when it does not, MATLAB itself fails (the utilization line divides a
382 * 1 x R vector by a 1 x K one, and the queue solve requests K outputs from an
383 * R-class analyzer), so the mismatch is refused BY NAME here rather than
384 * answered with a silently different model.
385 */
386/**
387 * The setup / delay-off pair of a station, or false when it has none.
388 *
389 * Presence in `setupparam` IS the reference's `sn.hassetup(ist)`, and the
390 * reference reads ONE pair per station (`{end}`, the last class that declares
391 * one) rather than a pair per class.
392 */
393template <class T>
394bool station_setup_pair(const qn::NetworkStruct<T>& L, std::size_t ist, lang::Distrib<T>& setup,
395 lang::Distrib<T>& delayoff) {
396 typename std::map<std::size_t, qn::SetupDelayOffParam<T>>::const_iterator it =
397 L.setupparam.find(ist);
398 if (it == L.setupparam.end()) return false;
399 return it->second.last(setup, delayoff);
400}
401
402/**
403 * The open-class setup/delay-off queue, solver_mam_basic.m:507-547.
404 *
405 * `mu_k` is the per-class service RATE the phase representation already carries
406 * scaled by S/nservers, so rho_k is per-class utilization. The aggregate rate
407 * is defined by Lambda / sum(rho_k), which makes the surrogate's utilization
408 * agree with the station's by construction; the QBD then answers one scalar
409 * mean queue length, split back by load share.
410 */
411template <class T>
412void mam_setup_qbd(const qn::NetworkStruct<T>& L, std::size_t ist,
413 const std::vector<T>& aggrLambda,
414 const std::vector<std::vector<PhService<T>>>& svc, const Matrix<T>& S,
415 const std::vector<std::vector<T>>& rates, std::size_t R, double ns,
416 const lang::Distrib<T>& setup, const lang::Distrib<T>& delayoff,
417 std::vector<T>& Qret) {
418 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
419 const std::size_t i0 = ist - 1, K = L.nclasses;
420 for (std::size_t r = 0; r < K; ++r) Qret[r] = zero;
421 if constexpr (!num_traits<T>::has_transcendental) {
422 throw UnsupportedError(
423 "solver_mam_basic: a setup/delay-off station is solved by a QBD whose G matrix needs "
424 "a logarithm; rerun with --arith double or real");
425 } else {
426 const Map<T> su = lang::dist_to_map(setup), doff = lang::dist_to_map(delayoff);
427 const T alpharate = map_lambda(su), alphascv = map_scv(su);
428 const T betarate = map_lambda(doff), betascv = map_scv(doff);
429
430 std::vector<T> rho(K, zero);
431 T rho_total = zero;
432 for (std::size_t r = 0; r < K; ++r) {
433 if (L.disabled[i0][r]) continue;
434 // mean of the already-scaled service phase: sigma (-S)^-1 e
435 const Matrix<T>& Sr = svc[i0][r].S;
436 if (Sr.rows() == 0) continue;
437 Matrix<T> negS = Sr;
438 for (std::size_t a = 0; a < negS.rows(); ++a)
439 for (std::size_t b = 0; b < negS.cols(); ++b) negS(a, b) = -negS(a, b);
440 const Matrix<T> negSinv = inverse(negS);
441 T mean = zero;
442 for (std::size_t a = 0; a < negSinv.rows() && a < svc[i0][r].sigma.size(); ++a)
443 for (std::size_t b = 0; b < negSinv.cols(); ++b)
444 mean += svc[i0][r].sigma[a] * negSinv(a, b);
445 if (!(mean > zero)) continue;
446 std::size_t c = L.nchains;
447 for (std::size_t cc = 0; cc < L.nchains; ++cc)
448 if (L.chains[cc][r]) c = cc;
449 if (c == L.nchains) continue;
450 // rho = lambda / mu, and mu is 1/mean of the already-scaled phase
451 rho[r] = T(rates[c][r] * mean);
452 rho_total += rho[r];
453 }
454 if (!(rho_total > zero)) return;
455
456 T lam_total = zero;
457 for (std::size_t r = 0; r < K && r < aggrLambda.size(); ++r) lam_total += aggrLambda[r];
458 if (R == 1 && !aggrLambda.empty()) lam_total = aggrLambda[0];
459 if (!(lam_total > zero)) return;
460 const T aggrRate = T(lam_total / rho_total);
461 const T qtot =
462 mam::qbd_setupdelayoff(lam_total, aggrRate, alpharate, alphascv, betarate, betascv);
463 for (std::size_t r = 0; r < K; ++r)
464 if (rho[r] > zero) Qret[r] = T(qtot * rho[r] / rho_total);
465 (void)S;
466 (void)ns;
467 (void)one;
468 }
469}
470
471/**
472 * The closed-class setup/delay-off queue, solver_mam_basic.m.
473 *
474 * THE CLOSED VACATION QUEUE, SOLVED. What stood here was the per-instance
475 * cold-start race `R = p_cold*E[setup] + S`: it raced the delay-off against the
476 * per-instance idle time and carried NO queueing term, so it described a
477 * serverless instance pool rather than a single-server vacation queue and
478 * reported the SAME response time across a tenfold change in the setup mean
479 * (BUG-78). `qbd_setupdelayoff_closed` solves the finite level-dependent chain
480 * the simulator walks, and the aggregate response it returns is split back over
481 * the classes by R_k = W + S_k -- the decomposition the finite-capacity branch
482 * already uses, and an identity when the chain holds one class.
483 */
484template <class T>
485void mam_setup_closed(const qn::NetworkStruct<T>& L, std::size_t ist,
486 const std::vector<std::vector<PhService<T>>>& svc, const Matrix<T>& S,
487 const std::vector<std::vector<T>>& rates, const std::vector<T>& ztchain,
488 const Matrix<T>& V, double ns, const lang::Distrib<T>& setup,
489 const lang::Distrib<T>& delayoff, const Matrix<T>& QNprev,
490 std::vector<T>& Qret) {
491 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
492 const std::size_t i0 = ist - 1, K = L.nclasses;
493 for (std::size_t r = 0; r < K; ++r) Qret[r] = zero;
494 if constexpr (!num_traits<T>::has_transcendental) {
495 throw UnsupportedError(
496 "solver_mam_basic: the closed setup/delay-off chain fits a phase-type setup and "
497 "delay-off, which needs a square root; rerun with --arith double or real");
498 } else {
499 const Map<T> su = lang::dist_to_map(setup), doff = lang::dist_to_map(delayoff);
500 const T alpharate = map_lambda(su), alphascv = map_scv(su);
501 const T betarate = map_lambda(doff), betascv = map_scv(doff);
502 const T ft = num_traits<T>::from_double(GlobalConstants::FineTol);
503
504 for (std::size_t c = 0; c < L.nchains; ++c) {
505 T Nc = zero;
506 bool finiteNc = true, anyActive = false;
507 for (std::size_t r = 0; r < K; ++r) {
508 if (!L.chains[c][r]) continue;
509 if (!std::isfinite(L.classes[r].population)) { finiteNc = false; break; }
510 Nc += num_traits<T>::from_double(L.classes[r].population);
511 if (rates[c][r] > zero && std::isfinite(num_traits<T>::to_double(S(i0, r))))
512 anyActive = true;
513 }
514 if (!finiteNc || !anyActive || !(Nc > zero)) continue;
515
516 T vtot = zero;
517 for (std::size_t j = 0; j < K; ++j)
518 if (L.chains[c][j]) vtot += V(i0, j);
519 const T ZT = T(ztchain[c] / (vtot > ft ? vtot : ft));
520
521 // THE COMPLEMENTARY DELAY, not the think demand alone.
522 // lambda(n) = (Nc-n)/Z is exact only when everything away from this
523 // station is a pure delay; with other queues in the network the think
524 // demand OVERSTATES the arrival rate and saturates the station. Z is
525 // the mean time a customer currently spends away,
526 // (Nc - QN_here)/lambda_here at this iterate, floored at ZT so it can
527 // never be shorter than the think time it contains. On a Delay+Queue
528 // the two coincide at convergence.
529 T lamHere = zero, qnHere = zero, tnS = zero, tnTot = zero, svcAny = zero;
530 std::size_t svcAnyCount = 0;
531 for (std::size_t r = 0; r < K; ++r) {
532 if (!L.chains[c][r]) continue;
533 T lamK = rates[c][r];
534 if (!std::isfinite(num_traits<T>::to_double(lamK))) lamK = zero;
535 T sk = S(i0, r);
536 if (!std::isfinite(num_traits<T>::to_double(sk))) sk = zero;
537 lamHere += lamK;
538 if (i0 < QNprev.rows() && r < QNprev.cols() &&
539 std::isfinite(num_traits<T>::to_double(QNprev(i0, r))))
540 qnHere += QNprev(i0, r);
541 tnTot += lamK;
542 tnS += T(lamK * sk);
543 if (sk > zero) { svcAny += sk; ++svcAnyCount; }
544 }
545 T Zc = ZT;
546 if (lamHere > ft && T(Nc - qnHere) > zero) {
547 const T zalt = T(T(Nc - qnHere) / lamHere);
548 Zc = zalt > ZT ? zalt : ZT;
549 }
550 // One server serves the whole chain, so the vacation cycle is a
551 // property of the STATION: the chain is solved on the aggregate.
552 T Sbar = tnTot > ft ? T(tnS / tnTot)
553 : (svcAnyCount > 0
554 ? T(svcAny / num_traits<T>::from_int(
555 static_cast<long>(svcAnyCount)))
556 : zero);
557 if (!(Sbar > ft)) continue;
558 const mam::SetupDelayoffClosed<T> cr = mam::qbd_setupdelayoff_closed(
559 Nc, Zc, T(one / Sbar), alpharate, alphascv, betarate, betascv);
560 if (!std::isfinite(num_traits<T>::to_double(cr.QN)) || !(cr.XN > zero)) continue;
561 T Wq = T(T(cr.QN / cr.XN) - Sbar);
562 if (!(Wq > zero)) Wq = zero;
563 for (std::size_t r = 0; r < K; ++r) {
564 if (!L.chains[c][r]) continue;
565 if (L.disabled[i0][r]) continue;
566 // S/c, NOT S: the caller adds the surrogate-delay jobs
567 // TN*S*(c-1)/c back, so a full S here counts the service term
568 // (2c-1)/c times. The two together make S. At c=1 the division
569 // is the identity. Wq still comes from a SINGLE-SERVER chain, so
570 // a closed multiserver setup station is approximated, not solved.
571 const T cserv = (std::isfinite(ns) && ns >= 1.0)
572 ? num_traits<T>::from_double(ns)
573 : one;
574 if (rates[c][r] > zero && std::isfinite(num_traits<T>::to_double(S(i0, r))))
575 Qret[r] = T(rates[c][r] * T(Wq + T(S(i0, r) / cserv)));
576 }
577 }
578 (void)svc;
579 }
580}
581
582template <class T>
583void solve_fcfs_station(const qn::NetworkStruct<T>& L, const MamOptions& opt, std::size_t ist,
584 const std::vector<T>& lambda, const Matrix<T>& V, const Matrix<T>& S,
585 const std::vector<std::vector<bool>>& Sknown,
586 const std::vector<std::vector<Map<T>>>& PH,
587 const std::vector<std::vector<bool>>& PHset,
588 const std::vector<std::vector<PhService<T>>>& svc,
589 const std::vector<Mmap<T>>& chainSysArrivals,
590 const std::vector<T>& ztchain, Matrix<T>& QN, Matrix<T>& UN,
591 Matrix<T>& RN, Matrix<T>& TN, std::vector<bool>& exact_station) {
592 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
593 const std::size_t M = L.nstations, K = L.nclasses, C = L.nchains;
594 const double ns = L.stations[ist - 1].nservers;
595 const std::size_t i0 = ist - 1;
596
597 // The reference also routes FCFSPRPRIO here, through BUTools' MMAPPH1PRPR,
598 // which is not ported; this function is only ever called for FCFS or HOL
599 // (see the dispatch below), so that arm is unreachable, not because the
600 // C++ SchedStrategy lacks the enumerator (it does not, lang_types.h:144).
601 if (L.stations[i0].sched == SchedStrategy::HOL && K > 1) {
602 bool distinct = false;
603 for (std::size_t r = 1; r < K; ++r)
604 if (L.classes[r].prio != L.classes[0].prio) distinct = true;
605 if (distinct)
606 throw UnsupportedError(
607 std::string("solver_mam_basic: station '") + L.stations[i0].name +
608 "' has non-identical class priorities under " +
609 lang::sched_to_text(L.stations[i0].sched) +
610 ", which the reference solves with BUTools' MMAPPH1NPPR; the priority analyzer "
611 "is not ported to C++");
612 }
613
614 // rates(ist,:) per chain: the visit rate of every class at this station.
615 std::vector<std::vector<T>> rates(C, std::vector<T>(K, zero));
616 for (std::size_t c = 0; c < C; ++c)
617 for (std::size_t r = 0; r < K; ++r) rates[c][r] = T(V(i0, r) * lambda[c]);
618
619 Mmap<T> aggr;
620 for (std::size_t c = 0; c < C; ++c) {
621 const std::vector<std::size_t>& ic = L.inchain[c];
622 T tot = zero;
623 for (std::size_t r : ic) tot += rates[c][r - 1];
624 Matrix<T> markProb(1, ic.size(), zero);
625 for (std::size_t j = 0; j < ic.size(); ++j)
626 markProb(0, j) = (tot > zero) ? T(rates[c][ic[j] - 1] / tot) : zero;
627 Mmap<T> cur = mmap_mark_probs(chainSysArrivals[c], markProb);
628 // Every arrival process the C++ lang layer can express is Markovian
629 // (there is no ME or RAP ProcessType), so mam_chain_arrival_is_markovian
630 // is unconditionally true and the normalization always applies.
631 cur = mmap_normalize(cur);
632 bool anypos = false;
633 for (std::size_t j = 0; j < ic.size(); ++j)
634 if (rates[c][ic[j] - 1] > zero) anypos = true;
635 if (anypos) {
636 std::vector<T> tgt(ic.size(), zero);
637 for (std::size_t j = 0; j < ic.size(); ++j)
638 tgt[j] = (rates[c][ic[j] - 1] > zero)
639 ? T(one / rates[c][ic[j] - 1])
640 : num_traits<T>::from_double(1.0 / GlobalConstants::Zero);
641 cur = mmap_scale_perclass(cur, tgt);
642 }
643 if (c == 0) {
644 // Chain 1 keeps its own per-class marks; lumping them into one gave
645 // the aggregate the wrong mark count. See _kb/06-solver-catalog.md.
646 aggr = cur;
647 } else {
648 aggr = mmap_super_safe(std::vector<Mmap<T>>{aggr, cur}, opt.space_max);
649 }
650 }
651
652 // The marks come out chain by chain and every reader below indexes them by
653 // CLASS, so permute them into class order.
654 {
655 std::vector<std::size_t> markorder;
656 for (std::size_t c = 0; c < C; ++c)
657 for (std::size_t r : L.inchain[c]) markorder.push_back(r);
658 if (markorder.size() == aggr.Dc.size() &&
659 !std::is_sorted(markorder.begin(), markorder.end())) {
660 std::vector<std::size_t> perm(markorder.size());
661 for (std::size_t j = 0; j < perm.size(); ++j) perm[j] = j;
662 std::stable_sort(perm.begin(), perm.end(),
663 [&markorder](std::size_t a, std::size_t b) {
664 return markorder[a] < markorder[b];
665 });
666 std::vector<Matrix<T>> reordered(perm.size());
667 for (std::size_t j = 0; j < perm.size(); ++j) reordered[j] = aggr.Dc[perm[j]];
668 aggr.Dc.swap(reordered);
669 }
670 }
671
672 const std::size_t R = aggr.classes();
673 lang::Distrib<T> setup_dist, delayoff_dist;
674 const bool has_setup = station_setup_pair(L, ist, setup_dist, delayoff_dist);
675
676 /**
677 * WHO ACTUALLY NEEDS ONE MARK PER CLASS, which is not everyone.
678 *
679 * The loop above superposes every chain, each contributing one mark per
680 * class, and permutes the result into class order, so R is K on any model
681 * whose chains partition the classes. It used to rewrite chain 1 as
682 * `{aggr{1} aggr{2} aggr{2}}` -- ONE aggregate mark, whatever that chain
683 * held -- which made R equal 1 + sum_{c>1}|inchain_c|, and the reference
684 * carried the same defect until 2026-08-16.
685 *
686 * The setup/delay-off branches do not read the marking at all: the closed
687 * one (solver_mam_basic.m:596-650) works from `rates`, `S` and the think
688 * demand, and the open one takes the SCALAR aggregate rate. That is the
689 * shape SolverLN sends here for a setup layer -- a single chain over the
690 * client, entry and call classes -- and MATLAB solves it, so refusing it
691 * was a WRONG REFUSAL and is what made lqn_setup unsolvable in this port.
692 *
693 * MMAPPH1FCFS and the finite-capacity analyzers do read it: each needs the
694 * r-th mark to be the arrival stream of the r-th service law. There the
695 * requirement stands, and it is enforced at those branches instead of here,
696 * so a shape one branch cannot use no longer refuses the ones that can.
697 */
698 const std::string mark_refusal =
699 std::string("solver_mam_basic: the assembled arrival stream at station '") +
700 L.stations[i0].name + "' carries " + std::to_string(R) +
701 " marked classes against the model's " + std::to_string(K) +
702 "; the reference collapses chain 1 to a single mark, so this analyzer has no arrival "
703 "stream to pair with each service law. A class-switching chain at an FCFS station is "
704 "refused rather than solved with a mismatched marking";
705
706 const std::vector<T> aggrLambda = mmap_lambda(aggr);
707 double aggrUtil = 0.0;
708 for (std::size_t r = 0; r < K; ++r) {
709 // A class this station never serves has a NaN rate in the reference and
710 // its term is dropped by 'omitnan'; the flag replaces the sentinel here.
711 if (L.disabled[i0][r]) continue;
712 const double lam = num_traits<T>::to_double(aggrLambda[R == 1 ? 0 : r]);
713 const double mu = num_traits<T>::to_double(L.rates(i0, r));
714 const double den = GlobalConstants::FineTol + mu * ns;
715 if (den > 0.0 && std::isfinite(den)) aggrUtil += lam / den;
716 }
717
718 std::vector<T> Qret(K, zero);
719 bool exact_here = false; // the reference's mapdcUsed
720 T exactRespT = zero;
721 bool finiteCapUsed = false;
722 T finiteCapMeanQ = zero, finiteCapLossProb = zero;
723 std::vector<T> finiteCapLossPerClass;
724
725 bool anyopen = false;
726 for (std::size_t r = 0; r < K; ++r)
727 if (std::isinf(L.classes[r].population)) anyopen = true;
728
729 if (!(aggrUtil < 1.0 - GlobalConstants::FineTol)) {
730 for (std::size_t r = 0; r < K; ++r)
731 Qret[r] = num_traits<T>::from_double(L.classes[r].population);
732 } else if (anyopen) {
733 bool isMapDc = (K == 1) && (L.service[i0][0].type == ProcessType::DET);
734 bool isDMc = false;
735 std::size_t dmcSource = 0;
736 if (K == 1 && !isMapDc && L.service[i0][0].type == ProcessType::EXP) {
737 for (std::size_t j = 1; j <= M; ++j)
738 if (j != ist && L.service[j - 1][0].type == ProcessType::DET) {
739 isDMc = true;
740 dmcSource = j;
741 break;
742 }
743 }
744 bool isPhM1 = false;
745 std::size_t phSource = 0;
746 if (K == 1 && !isMapDc && !isDMc && L.service[i0][0].type == ProcessType::EXP &&
747 std::isfinite(ns) && ns >= 1.0) {
748 for (std::size_t j = 1; j <= M; ++j) {
749 if (j == ist) continue;
750 const ProcessType sp = L.service[j - 1][0].type;
751 if (sp != ProcessType::EXP && sp != ProcessType::DET &&
752 sp != ProcessType::IMMEDIATE && sp != ProcessType::DISABLED) {
753 // qsys_phmc reads the arrival through its (pie, D0) marginal
754 // alone, so the gate is RENEWAL and not merely
755 // non-exponential: a correlated MAP would be answered as its
756 // renewal marginal.
757 if (!is_renewal_map(lang::dist_to_map(L.service[j - 1][0]))) continue;
758 isPhM1 = true;
759 phSource = j;
760 break;
761 } else if (sp == ProcessType::EXP && ns > 1.0 && M == 2 &&
762 L.nodes[L.node_of_station(j) - 1].nodetype == qn::NodeType::Source) {
763 // M/M/c: the single-fast-server surrogate is inexact for
764 // c > 1, so take the exact Erlang-C route instead.
765 isPhM1 = true;
766 phSource = j;
767 break;
768 }
769 }
770 }
771 // An infinite-buffer closed form would silently discard sn.cap and
772 // report a lossless queue, so a finite buffer takes precedence. The
773 // gate is a buffer that can BIND, not a finite sn.cap: refreshCapacity
774 // derives one from the chain population for every closed model.
775 const bool isFiniteCap = std::isfinite(sn::sn_get_buffer_size(L, i0 + 1));
776 if (isFiniteCap) {
777 isPhM1 = false;
778 isDMc = false;
779 }
780 // EACH CLOSED FORM IS A SURROGATE THAT MAY NOT APPLY, and the reference
781 // says so by WRAPPING EACH CALL IN `try ... catch <flag> = false`
782 // (solver_mam_basic.m:417-445): the gates above are structural (which
783 // laws are present), while the surrogate's own stability is only known
784 // once it is evaluated. The PH/M/c arm takes ANOTHER station's service
785 // law as the arrival process, so its rho is the ratio of two service
786 // rates and can exceed one on a perfectly stable network -- `oqn_basic`
787 // (Source Exp(0.1) -> Delay HyperExp -> Queue1 Exp(1)) is exactly that,
788 // and this port propagated `qsys_phmc: load rho must be strictly less
789 // than 1` out of SolverMAM instead of answering with the generic
790 // MMAPPH1FCFS path the reference falls back to. The catch is the GATE,
791 // not a mask: a refused surrogate leaves `exact_here` false and the
792 // model is still solved, by the analyzer the reference would use.
793 if (isPhM1) {
794 try {
795 const T muQ = T(one / S(i0, 0));
796 const Map<T> src = lang::dist_to_map(L.service[phSource - 1][0]);
797 const qsys::PhMcResult<T> r = qsys::qsys_phmc(
798 map_pie(src), src.D0, muQ, static_cast<unsigned>(std::llround(ns)));
799 Qret[0] = r.meanQueueLength;
800 exactRespT = r.meanSojournTime;
801 exact_here = true;
802 } catch (const std::exception&) {
803 isPhM1 = false;
804 }
805 }
806 if (!exact_here && isDMc) {
807 try {
808 const T muQ = T(one / S(i0, 0));
809 const qsys::DmcResult<T> r = qsys::qsys_dmc(
810 L.rates(dmcSource - 1, 0), muQ, static_cast<unsigned>(std::llround(ns)));
811 Qret[0] = r.meanQueueLength;
812 exactRespT = r.meanSojournTime;
813 exact_here = true;
814 } catch (const std::exception&) {
815 isDMc = false;
816 }
817 }
818 if (!exact_here && !isFiniteCap && isMapDc) {
819 try {
820 Map<T> arv;
821 arv.D0 = aggr.D0;
822 arv.D1 = aggr.D1;
823 const qsys::MapDcResult<T> r =
824 qsys::qsys_mapdc(arv, S(i0, 0), static_cast<unsigned>(std::llround(ns)));
825 Qret[0] = r.meanQueueLength;
826 exactRespT = r.meanSojournTime;
827 exact_here = true;
828 } catch (const std::exception&) {
829 isMapDc = false;
830 }
831 }
832 // MAP/M/c: the PH/M/c gate above refused this station because its
833 // aggregate arrival stream is NOT renewal. The single-fast-server
834 // surrogate the generic path would use ignores the arrival
835 // correlation; the level-dependent QBD is exact. c = 1 already goes to
836 // the exact MAP/MAP/1 path, so only c > 1 is claimed here.
837 bool isMapMc = !exact_here && !isFiniteCap && (K == 1) && !isMapDc && !isDMc &&
838 !isPhM1 && L.service[i0][0].type == ProcessType::EXP &&
839 std::isfinite(ns) && ns > 1.0;
840 if (isMapMc) {
841 try {
842 Map<T> arv;
843 arv.D0 = aggr.D0;
844 arv.D1 = aggr.D1;
845 const T muQ = T(one / S(i0, 0));
846 const qsys::MapMcResult<T> r =
847 qsys::qsys_mapmc(arv, muQ, static_cast<unsigned>(std::llround(ns)));
848 Qret[0] = r.meanQueueLength;
849 exactRespT = r.meanSojournTime;
850 exact_here = true;
851 } catch (const std::exception&) {
852 isMapMc = false;
853 }
854 }
855 // Exact MAP/PH/c. The arms above cover c > 1 only for EXPONENTIAL
856 // service; with a phase-type service law the generic path scales the
857 // service by nservers and adds a surrogate delay, an approximation that
858 // discards the service SHAPE. The service must be RENEWAL, since each
859 // freed server restarts at alpha. DET goes to MAP/D/c above, and ME/RAP
860 // have no phase-type configuration space at all.
861 bool isMapPhc = false;
862 if (!exact_here && !isFiniteCap && K == 1 && std::isfinite(ns) && ns > 1.0) {
863 const ProcessType st = L.service[i0][0].type;
864 if (st != ProcessType::EXP && st != ProcessType::DET && st != ProcessType::ME &&
865 st != ProcessType::RAP && st != ProcessType::IMMEDIATE &&
866 st != ProcessType::DISABLED) {
867 isMapPhc = is_renewal_map(lang::dist_to_map(L.service[i0][0]));
868 }
869 }
870 if (isMapPhc) {
871 try {
872 Map<T> arv;
873 arv.D0 = aggr.D0;
874 arv.D1 = aggr.D1;
875 const Map<T> svc0 = lang::dist_to_map(L.service[i0][0]);
876 const qsys::MapPhcResult<T> r = qsys::qsys_mapphc(
877 arv, map_pie(svc0), svc0.D0, static_cast<unsigned>(std::llround(ns)),
878 static_cast<std::size_t>(500), static_cast<std::size_t>(1), std::vector<T>());
879 Qret[0] = r.meanQueueLength;
880 exactRespT = r.meanSojournTime;
881 exact_here = true;
882 } catch (const std::exception&) {
883 isMapPhc = false;
884 }
885 }
886 if (exact_here) {
887 // one of the closed forms above answered the station
888 } else if (isFiniteCap) {
889 // The buffer analyzers split the loss by class, so each mark has to
890 // be one class's stream; M/M/c/K is exempt, it uses the total rate.
891 if (R != K && !(aggr.order() == 1)) throw UnsupportedError(mark_refusal);
892 const std::size_t capK = static_cast<std::size_t>(std::llround(L.cap[i0]));
893 // mam_detect_mmck: single-phase arrivals and one shared exponential
894 // service rate across every active class.
895 bool isMmck = (aggr.order() == 1);
896 T muMmck = zero;
897 if (isMmck) {
898 bool any = false;
899 double lo = 0.0, hi = 0.0;
900 for (std::size_t r = 0; r < K; ++r) {
901 if (L.disabled[i0][r]) continue;
902 if (L.service[i0][r].type != ProcessType::EXP) {
903 isMmck = false;
904 break;
905 }
906 const double v = num_traits<T>::to_double(L.rates(i0, r));
907 if (!(v > 0.0)) continue;
908 if (!any) {
909 lo = hi = v;
910 any = true;
911 muMmck = L.rates(i0, r);
912 } else {
913 lo = std::min(lo, v);
914 hi = std::max(hi, v);
915 }
916 }
917 if (!any) isMmck = false;
918 if (isMmck && hi - lo > 1e-9 * std::max(1.0, hi)) isMmck = false;
919 }
920 if (isMmck) {
921 T lamTot = zero;
922 for (const T& v : aggrLambda) lamTot += v;
923 const qsys::MmckResult<T> r =
924 qsys::qsys_mmck(lamTot, muMmck, static_cast<unsigned>(std::llround(ns)),
925 static_cast<unsigned>(capK));
926 finiteCapMeanQ = r.meanQueueLength;
927 finiteCapLossProb = r.lossProbability;
928 } else if (ns == 1.0) {
929 // Exact MMAP[K]/G/1/K: the embedded chain at departure epochs
930 // resolves the buffer level jointly with the arrival phase, so
931 // each class gets its own loss ratio.
932 std::vector<PhService<T>> sl;
933 for (std::size_t r = 0; r < K; ++r) sl.push_back(svc[i0][r]);
934 const qsys::ServiceLaw<T> mix = svc_mixture(aggr, sl);
935 const qsys::MmapG1kResult<T> r = qsys::qsys_mmapg1k(aggr.D0, aggr.Dc, mix, capK);
936 finiteCapMeanQ = r.meanQueueLength;
937 finiteCapLossProb = r.lossAggregate;
938 finiteCapLossPerClass = r.lossRatio;
939 } else {
940 std::vector<PhService<T>> sl;
941 for (std::size_t r = 0; r < K; ++r) sl.push_back(svc[i0][r]);
942 const TruncRenorm<T> r = truncate_renorm(aggr, sl, capK);
943 finiteCapMeanQ = r.meanQ;
944 finiteCapLossProb = r.lossProb;
945 }
946 finiteCapUsed = true;
947 exact_station[i0] = true;
948 } else if (has_setup) {
949 // OPEN SETUP / DELAY-OFF, solver_mam_basic.m:507-547. The station is
950 // collapsed to ONE M/G/1 with setup: the aggregate arrival rate, and
951 // an aggregate service rate chosen so the aggregate utilization is
952 // exactly the sum of the per-class ones. The queue that QBD returns
953 // is then split back over the classes by their share of the load.
954 mam_setup_qbd(L, ist, aggrLambda, svc, S, rates, R, ns, setup_dist, delayoff_dist,
955 Qret);
956 } else {
957 // MMAPPH1FCFS treats service as a renewal phase type, discarding
958 // service autocorrelation. A single-class single-server station with
959 // a genuinely correlated service takes the exact MAP/MAP/1 QBD,
960 // which carries the service phase across departures.
961 const bool corr =
962 (K == 1) && (ns == 1.0) && PHset[i0][0] &&
963 std::fabs(num_traits<T>::to_double(map_acf(PH[i0][0], std::vector<unsigned>{1})[0])) >
965 if (corr) {
966 Map<T> arv;
967 arv.D0 = aggr.D0;
968 arv.D1 = aggr.Dc[0];
969 const QbdMapMap1Result<T> r = qbd_mapmap1(arv, PH[i0][0]);
970 Qret[0] = r.QN;
971 } else {
972 // One arrival mark per service law, which is what the analyzer
973 // pairs up; a collapsed marking has no such pairing.
974 if (R != K) throw UnsupportedError(mark_refusal);
975 // MMAP[K]/G[K]/1 whenever a class carries a service law that is
976 // NOT phase type. mmapph1fcfs_ncmean below reads the PH FIT,
977 // which matches the mean and, above SCV 1, nothing else; He's
978 // transform analysis takes the ORIGINAL law, which L.service
979 // still holds. The result is a /1, hence the single-server gate.
980 bool gk_done = false;
981 if (ns == 1.0 && mam_gk1_applicable(L, i0, K)) {
982 try {
983 std::vector<Matrix<T>> MM;
984 MM.push_back(aggr.D0);
985 Matrix<T> D1sum(aggr.D0.rows(), aggr.D0.cols(),
986 num_traits<T>::from_int(0));
987 for (std::size_t r = 0; r < K; ++r)
988 for (std::size_t a = 0; a < D1sum.rows(); ++a)
989 for (std::size_t b = 0; b < D1sum.cols(); ++b)
990 D1sum(a, b) += aggr.Dc[r](a, b);
991 MM.push_back(D1sum);
992 for (std::size_t r = 0; r < K; ++r) MM.push_back(aggr.Dc[r]);
993 std::vector<lang::Distrib<T>> laws;
994 for (std::size_t r = 0; r < K; ++r)
995 laws.push_back(mam_declared_law(L.service[i0][r]));
996 const qsys::MmapGk1Result<T> gk = qsys::qsys_mmapgk1(
997 MM, laws, std::vector<T>(), static_cast<std::size_t>(1), 1e-12,
998 static_cast<std::size_t>(10000));
999 for (std::size_t r = 0; r < K; ++r)
1000 Qret[r] = gk.lambdas[r] * gk.meanSojournTime[r];
1001 // NOT exact_here: that flag carries ONE scalar response
1002 // time for the whole station, which the single-class
1003 // arms above own. Here the answer is per class, and with
1004 // ns == 1 the generic tail computes RN = QN/TN and adds
1005 // no surrogate delay, which is exactly right.
1006 gk_done = true;
1007 } catch (const std::exception&) {
1008 gk_done = false;
1009 }
1010 }
1011 if (!gk_done) {
1012 std::vector<PhService<T>> sl;
1013 for (std::size_t r = 0; r < R; ++r) sl.push_back(svc[i0][r]);
1014 const std::vector<T> m = mmapph1fcfs_ncmean(aggr, sl);
1015 for (std::size_t r = 0; r < K; ++r) Qret[r] = m[r];
1016 }
1017 }
1018 }
1019 } else {
1020 // Every class closed. The queue-length DISTRIBUTION is truncated at each
1021 // class's own population, which is what stops the decomposition from
1022 // reporting more jobs than the chain owns.
1023 std::size_t maxLevel = 1;
1024 for (std::size_t r = 0; r < K; ++r)
1025 if (std::isfinite(L.classes[r].population))
1026 maxLevel += static_cast<std::size_t>(std::llround(L.classes[r].population));
1027 // "the station receives no arrivals" is a property of the AGGREGATE
1028 // stream. The reference passes {D0, Dc[0], ...} to map_lambda, which
1029 // reads only its second argument, so it tested CLASS 1 alone and a
1030 // station whose class 1 is disabled fell here however busy the rest was.
1031 const Map<T> probe = aggr.map();
1032 if (num_traits<T>::to_double(map_lambda(probe)) < GlobalConstants::FineTol) {
1033 for (std::size_t r = 0; r < K; ++r)
1034 Qret[r] = (L.rates(i0, 0) > zero)
1035 ? T(num_traits<T>::from_double(GlobalConstants::FineTol) /
1036 L.rates(i0, 0))
1037 : zero;
1038 } else if (has_setup) {
1039 // CLOSED SETUP / DELAY-OFF, solver_mam_basic.m:596-650. No QBD here:
1040 // a closed job returns after its own chain's think time, so what
1041 // matters is the race between that gap and the delay-off timer.
1042 // p_cold is the delay-off LST at 1/ZT, the probability the server
1043 // has already shut down when the job comes back, and the class holds
1044 // (expected setup paid + its own service) jobs by Little.
1045 mam_setup_closed(L, ist, svc, S, rates, ztchain, V, ns, setup_dist, delayoff_dist,
1046 QN, Qret);
1047 } else {
1048 // Same pairing requirement as the open branch above.
1049 if (R != K) throw UnsupportedError(mark_refusal);
1050 std::vector<PhService<T>> sl;
1051 for (std::size_t r = 0; r < R; ++r) sl.push_back(svc[i0][r]);
1052 const std::vector<std::vector<T>> pd = mmapph1fcfs_ncdistr(aggr, sl, maxLevel);
1053 for (std::size_t r = 0; r < K; ++r) {
1054 const std::size_t Nk =
1055 static_cast<std::size_t>(std::llround(L.classes[r].population));
1056 std::vector<T> p(Nk + 1, zero);
1057 const std::vector<T>& src = pd[r];
1058 T acc = zero;
1059 for (std::size_t n = 0; n < Nk; ++n) {
1060 p[n] = num_abs(src[n]);
1061 acc += p[n];
1062 }
1063 // Truncating at N(k) folds the tail into that level, so the
1064 // complement must be taken over the TRUNCATED vector.
1065 p[Nk] = num_abs(T(one - acc));
1066 T mass = zero;
1067 for (std::size_t n = 0; n <= Nk; ++n) mass += p[n];
1068 T m = zero;
1069 if (mass > zero)
1070 for (std::size_t n = 0; n <= Nk; ++n)
1071 m += num_traits<T>::from_int((int)n) * T(p[n] / mass);
1072 if (m < zero) m = zero;
1073 if (num_traits<T>::to_double(m) > static_cast<double>(Nk))
1074 m = num_traits<T>::from_int((int)Nk);
1075 Qret[r] = m;
1076 }
1077 }
1078 }
1079
1080 // ---- write the station's metrics back --------------------------------
1081 if (finiteCapUsed) {
1082 // Under FCFS the wait in queue is common to every class, so per class
1083 // R_k = Wq + S_k with Wq recovered from the aggregate queue length.
1084 std::vector<T> inflow(K, zero), eff(K, zero);
1085 for (std::size_t r = 0; r < K; ++r) {
1086 std::size_t c = 0;
1087 for (std::size_t cc = 0; cc < C; ++cc)
1088 if (L.chains[cc][r]) {
1089 c = cc;
1090 break;
1091 }
1092 inflow[r] = rates[c][r];
1093 const T loss = finiteCapLossPerClass.empty() ? finiteCapLossProb
1094 : finiteCapLossPerClass[r];
1095 eff[r] = T(inflow[r] * T(one - loss));
1096 }
1097 T sumTN = zero;
1098 for (std::size_t r = 0; r < K; ++r) sumTN += eff[r];
1099 T Wq = zero;
1100 if (sumTN > zero) {
1101 T sw = zero;
1102 for (std::size_t r = 0; r < K; ++r)
1103 if (Sknown[i0][r]) sw += eff[r] * S(i0, r);
1104 const T w = T(T(finiteCapMeanQ / sumTN) - T(sw / sumTN));
1105 Wq = (w > zero) ? w : zero;
1106 }
1107 for (std::size_t r = 0; r < K; ++r) {
1108 TN(i0, r) = eff[r];
1109 UN(i0, r) = T(TN(i0, r) * S(i0, r) / num_traits<T>::from_double(ns));
1110 if (TN(i0, r) > zero) {
1111 RN(i0, r) = T(Wq + S(i0, r));
1112 QN(i0, r) = T(TN(i0, r) * RN(i0, r));
1113 } else {
1114 RN(i0, r) = zero;
1115 QN(i0, r) = zero;
1116 }
1117 }
1118 } else {
1119 for (std::size_t r = 0; r < K; ++r) {
1120 std::size_t c = 0;
1121 for (std::size_t cc = 0; cc < C; ++cc)
1122 if (L.chains[cc][r]) {
1123 c = cc;
1124 break;
1125 }
1126 TN(i0, r) = rates[c][r];
1127 UN(i0, r) = T(TN(i0, r) * S(i0, r) / num_traits<T>::from_double(ns));
1128 QN(i0, r) = Qret[r];
1129 if (exact_here) {
1130 RN(i0, r) = exactRespT;
1131 exact_station[i0] = true;
1132 } else {
1133 // Add back the jobs at the surrogate delay server the c-fold
1134 // service speedup removed.
1135 if (Sknown[i0][r] && std::isfinite(ns))
1136 QN(i0, r) = T(QN(i0, r) + TN(i0, r) * S(i0, r) *
1137 num_traits<T>::from_double((ns - 1.0) / ns));
1138 RN(i0, r) = (TN(i0, r) > zero) ? T(QN(i0, r) / TN(i0, r)) : zero;
1139 }
1140 }
1141 }
1142}
1143
1144} // namespace basic_detail
1145
1146/**
1147 * Port of `solver_mam_basic.m`.
1148 *
1149 * @param L the refreshed struct, with non-Markovian processes already gated
1150 * out by the runner
1151 * @param opt the MAM options; `space_max` is the arrival superposition budget
1152 */
1153template <class T>
1155 if constexpr (!num_traits<T>::has_transcendental) {
1156 throw UnsupportedError(
1157 "solver_mam_basic: the matrix-analytic station solves run tolerance-terminated "
1158 "iterations (the Riccati doubling behind MMAP[K]/PH[K]/1, the QBD cyclic reduction) "
1159 "and need transcendental arithmetic; rerun this model with --arith double or "
1160 "--arith real");
1161 } else {
1162 using namespace basic_detail;
1163 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
1164 const std::size_t I = L.nof_nodes(), M = L.nstations, K = L.nclasses, C = L.nchains;
1165 const double tol = opt.tol;
1166
1167 // ---- service times, visits and chain demands -------------------------
1168 Matrix<T> S(M, K, zero);
1169 std::vector<std::vector<bool>> Sknown(M, std::vector<bool>(K, false));
1170 for (std::size_t i = 0; i < M; ++i)
1171 for (std::size_t r = 0; r < K; ++r)
1172 if (!L.disabled[i][r] && L.rates(i, r) > zero) {
1173 S(i, r) = T(one / L.rates(i, r));
1174 Sknown[i][r] = true;
1175 }
1176 const Matrix<T> V = station_visits(L);
1178 // Think demand of each chain, the sum of its demand at the INFINITE-server
1179 // stations. The closed setup branch divides it by the chain's visits to get
1180 // the gap between two visits of one job, which is what the cold-start race
1181 // is against (solver_mam_basic.m:630).
1182 std::vector<T> ztchain(C, zero);
1183 for (std::size_t c = 0; c < C; ++c)
1184 for (std::size_t i = 0; i < M; ++i)
1185 if (std::isinf(L.stations[i].nservers)) ztchain[c] += dem.Lchain(i, c);
1186
1187 Matrix<T> QN(M, K, zero), UN(M, K, zero), RN(M, K, zero), TN(M, K, zero);
1188 std::vector<T> CN(K, zero), XN(K, zero);
1189 std::vector<bool> exact_station(M, false); // the reference's mapdcStations
1190
1191 // ---- per-station service phase-type pairs ----------------------------
1192 // Det is left alone (preserveDet), so the exact MAP/D/c branch can claim it.
1193 std::vector<std::vector<Map<T>>> PH(M, std::vector<Map<T>>(K));
1194 std::vector<std::vector<bool>> PHset(M, std::vector<bool>(K, false));
1195 std::vector<std::vector<PhService<T>>> svc(M, std::vector<PhService<T>>(K));
1196 for (std::size_t i = 0; i < M; ++i) {
1197 const SchedStrategy sc = L.stations[i].sched;
1198 if (!(sc == SchedStrategy::FCFS || sc == SchedStrategy::HOL ||
1199 sc == SchedStrategy::PS))
1200 continue;
1201 for (std::size_t r = 0; r < K; ++r) {
1202 if (L.service[i][r].type == ProcessType::DET && opt.preserve_det) continue;
1203 const double ns = L.stations[i].nservers;
1204 const T target = std::isfinite(ns) ? T(S(i, r) / num_traits<T>::from_double(ns))
1205 : S(i, r);
1206 if (L.disabled[i][r] || !Sknown[i][r] || !(target > zero)) {
1207 // The reference's `any(isnan(D0))` guard: a class this station
1208 // never serves gets an Immediate service rather than a NaN pair,
1209 // so it contributes nothing and cannot poison the phase-type
1210 // checks downstream.
1212 // MATLAB map_exponential takes a MEAN; the rate spelling gives mean 1e-8.
1213 PH[i][r] = map_exponential_mean(imm);
1214 PHset[i][r] = true;
1215 svc[i][r].sigma.assign(1, one);
1216 svc[i][r].S = Matrix<T>(1, 1, T(-imm));
1217 continue;
1218 }
1219 // ME and RAP are rescaled by the rate ALONE (solver_mam_basic.m:82-88):
1220 // map_scale finishes with map_normalize, whose clamp on the negative
1221 // entries is a repair for a MAP and destruction for a matrix
1222 // exponential, whose negative off-diagonals ARE the representation.
1223 const ProcessType pt = L.service[i][r].type;
1224 PH[i][r] = (pt == ProcessType::ME || pt == ProcessType::RAP)
1225 ? map_scale_rate(lang::dist_to_map(L.service[i][r]), target)
1226 : map_scale(lang::dist_to_map(L.service[i][r]), target);
1227 PHset[i][r] = true;
1228 svc[i][r].sigma = map_pie(PH[i][r]);
1229 svc[i][r].S = PH[i][r].D0;
1230 }
1231 }
1232
1233 // ---- chain classification and the open-chain arrival MMAPs -----------
1234 std::vector<bool> isopenchain(C, false), isclosedchain(C, false);
1235 std::vector<T> lambda(C, zero);
1236 std::vector<Mmap<T>> chainSysArrivals(C);
1237 for (std::size_t c = 0; c < C; ++c) {
1238 double tot = 0.0;
1239 bool inf = false;
1240 for (std::size_t r : L.inchain[c]) {
1241 const double n = L.classes[r - 1].population;
1242 if (std::isinf(n)) inf = true;
1243 else tot += n;
1244 }
1245 (void)tot;
1246 isopenchain[c] = inf;
1247 isclosedchain[c] = !inf;
1248 const std::size_t ist = L.classes[L.inchain[c][0] - 1].refstat;
1249 if (!inf) continue;
1250 // Open chain: the arrival stream is the superposition of the per-class
1251 // source processes, each marked as its own class.
1252 std::vector<Mmap<T>> parts;
1253 for (std::size_t r : L.inchain[c]) {
1254 Mmap<T> m;
1255 if (L.disabled[ist - 1][r - 1] || !(L.rates(ist - 1, r - 1) > zero)) {
1256 // No arrivals from this class: the reference substitutes
1257 // map_exponential(Inf), a zero-rate stream.
1258 m.D0 = Matrix<T>(1, 1, zero);
1259 m.D1 = Matrix<T>(1, 1, zero);
1260 m.Dc.assign(1, Matrix<T>(1, 1, zero));
1261 } else {
1262 const Map<T> src = lang::dist_to_map(L.service[ist - 1][r - 1]);
1263 m.D0 = src.D0;
1264 m.D1 = src.D1;
1265 m.Dc.assign(1, src.D1);
1266 lambda[c] += L.rates(ist - 1, r - 1);
1267 }
1268 parts.push_back(m);
1269 }
1270 chainSysArrivals[c] = parts[0];
1271 for (std::size_t p = 1; p < parts.size(); ++p)
1272 chainSysArrivals[c] = mmap_super_safe(
1273 std::vector<Mmap<T>>{chainSysArrivals[c], parts[p]}, opt.space_max);
1274 for (std::size_t r : L.inchain[c])
1275 TN(ist - 1, r - 1) = L.disabled[ist - 1][r - 1] ? zero : L.rates(ist - 1, r - 1);
1276 }
1277
1278 std::vector<bool> finite_srv(M, false);
1279 for (std::size_t i = 0; i < M; ++i) finite_srv[i] = std::isfinite(L.stations[i].nservers);
1280
1281 bool ismixed = false;
1282 {
1283 bool anyc = false, anyo = false;
1284 for (std::size_t c = 0; c < C; ++c) {
1285 anyc = anyc || isclosedchain[c];
1286 anyo = anyo || isopenchain[c];
1287 }
1288 ismixed = anyc && anyo;
1289 }
1290 const double Ulim = 1.0 - GlobalConstants::CoarseTol;
1291
1292 // Floor R at one full service time and restate Q = R*T; see _kb/06-solver-catalog.md (MAM closed-chain population)
1293 std::vector<std::size_t> all_classes(K);
1294 for (std::size_t r = 0; r < K; ++r) all_classes[r] = r + 1;
1295 auto resptime_floor = [&](const std::vector<std::size_t>& rlist) {
1296 for (std::size_t i = 0; i < M; ++i) {
1297 if (exact_station[i]) continue;
1298 for (std::size_t r : rlist) {
1299 const std::size_t k = r - 1;
1300 if (V(i, k) > zero) {
1301 if (!finite_srv[i]) {
1302 RN(i, k) = S(i, k);
1303 } else {
1304 const T byLittle = (TN(i, k) > zero) ? T(QN(i, k) / TN(i, k)) : zero;
1305 RN(i, k) = (S(i, k) > byLittle) ? S(i, k) : byLittle;
1306 }
1307 } else {
1308 RN(i, k) = zero;
1309 }
1310 QN(i, k) = T(RN(i, k) * TN(i, k));
1311 }
1312 }
1313 };
1314
1315 // ---- the throughput fixed point --------------------------------------
1316 Matrix<T> TN_1(M, K, zero);
1317 double delta = std::numeric_limits<double>::infinity();
1318 int it = 0;
1319 while (delta > tol && it <= opt.iter_max) {
1320 ++it;
1321 TN_1 = TN;
1322 double Umax = 0.0;
1323 for (std::size_t i = 0; i < M; ++i) {
1324 if (!finite_srv[i]) continue;
1325 double s = 0.0;
1326 for (std::size_t r = 0; r < K; ++r) s += num_traits<T>::to_double(UN(i, r));
1327 if (s > Umax) Umax = s;
1328 }
1329 if (ismixed || Umax < 1.0) {
1330 for (std::size_t c = 0; c < C; ++c) {
1331 if (!isclosedchain[c]) continue;
1332 double Nc = 0.0;
1333 for (std::size_t r : L.inchain[c]) Nc += L.classes[r - 1].population;
1334 double QNc = 0.0;
1335 for (std::size_t i = 0; i < M; ++i)
1336 for (std::size_t r : L.inchain[c]) QNc += num_traits<T>::to_double(QN(i, r - 1));
1337 QNc = std::max(tol, QNc);
1338 T Dsum = zero;
1339 for (std::size_t i = 0; i < M; ++i) Dsum += dem.Lchain(i, c);
1340 if (it == 1) {
1341 lambda[c] = (Dsum > zero) ? T(num_traits<T>::from_double(Nc) / Dsum) : zero;
1342 } else {
1343 // Iteration-averaged regula falsi: the raw N/QN Newton step
1344 // is blended with a no-op, the no-op's weight growing to one
1345 // at iter_max.
1346 const double w = static_cast<double>(it) / opt.iter_max;
1347 const T step = T(num_traits<T>::from_double(Nc / QNc) * lambda[c]);
1348 lambda[c] = T(lambda[c] * num_traits<T>::from_double(w) +
1349 step * num_traits<T>::from_double(1.0 - w));
1350 }
1351 }
1352 }
1353 if (ismixed) {
1354 double theta = 1.0;
1355 bool binding = false;
1356 for (std::size_t i = 0; i < M; ++i) {
1357 if (!finite_srv[i]) continue;
1358 double Uopen = 0.0, Uclosed = 0.0;
1359 for (std::size_t c = 0; c < C; ++c) {
1360 const double u =
1362 if (isclosedchain[c]) Uclosed += u;
1363 else Uopen += u;
1364 }
1365 if (Uclosed > tol) {
1366 binding = true;
1367 theta = std::min(theta, (Ulim - Uopen) / Uclosed);
1368 }
1369 }
1370 if (binding && theta < 1.0)
1371 for (std::size_t c = 0; c < C; ++c)
1372 if (isclosedchain[c])
1373 lambda[c] = T(lambda[c] * num_traits<T>::from_double(std::max(0.0, theta)));
1374 } else if (Umax >= 1.0) {
1375 for (std::size_t c = 0; c < C; ++c)
1376 lambda[c] = T(lambda[c] / num_traits<T>::from_double(Umax));
1377 }
1378
1379 for (std::size_t c = 0; c < C; ++c) {
1380 if (isclosedchain[c]) {
1381 // Poisson surrogate at the current throughput iterate. An open
1382 // chain keeps its source MMAP, whose rate is re-imposed per
1383 // station by the per-class scaling below.
1384 chainSysArrivals[c] =
1385 mmap_exponential_vec(std::vector<T>(L.inchain[c].size(), lambda[c]), 1);
1386 }
1387 for (std::size_t i = 0; i < M; ++i)
1388 for (std::size_t r : L.inchain[c]) TN(i, r - 1) = T(V(i, r - 1) * lambda[c]);
1389 }
1390
1391 for (std::size_t ind = 1; ind <= I; ++ind) {
1392 const qn::NodeDef& nd = L.nodes[ind - 1];
1393 if (nd.station == 0) continue;
1394 const std::size_t ist = nd.station;
1395 if (nd.nodetype == qn::NodeType::Join) {
1396 for (std::size_t c = 0; c < C; ++c)
1397 for (std::size_t r : L.inchain[c]) {
1398 std::size_t fanin = 0;
1399 if (L.rtnodes.rows() > 0)
1400 for (std::size_t row = 0; row < L.rtnodes.rows(); ++row)
1401 if (L.rtnodes(row, (ind - 1) * K + (r - 1)) != zero) ++fanin;
1402 if (fanin == 0) fanin = 1;
1403 TN(ist - 1, r - 1) =
1404 T(lambda[c] * V(ist - 1, r - 1) / num_traits<T>::from_int((int)fanin));
1405 UN(ist - 1, r - 1) = zero;
1406 QN(ist - 1, r - 1) = zero;
1407 RN(ist - 1, r - 1) = zero;
1408 }
1409 continue;
1410 }
1411 const SchedStrategy sched = L.stations[ist - 1].sched;
1412 const double ns = L.stations[ist - 1].nservers;
1413 if (sched == SchedStrategy::INF) {
1414 for (std::size_t c = 0; c < C; ++c)
1415 for (std::size_t r : L.inchain[c]) {
1416 const std::size_t k = r - 1;
1417 if (!(V(ist - 1, k) > zero)) {
1418 TN(ist - 1, k) = UN(ist - 1, k) = QN(ist - 1, k) = RN(ist - 1, k) = zero;
1419 continue;
1420 }
1421 TN(ist - 1, k) = T(lambda[c] * V(ist - 1, k));
1422 // An infinite server reports U = QLen = T S: dividing by
1423 // Inf would annihilate it.
1424 UN(ist - 1, k) = T(S(ist - 1, k) * TN(ist - 1, k));
1425 QN(ist - 1, k) = T(TN(ist - 1, k) * S(ist - 1, k));
1426 RN(ist - 1, k) = (TN(ist - 1, k) > zero)
1427 ? T(QN(ist - 1, k) / TN(ist - 1, k))
1428 : zero;
1429 }
1430 } else if (sched == SchedStrategy::PS) {
1431 for (std::size_t c = 0; c < C; ++c) {
1432 for (std::size_t r : L.inchain[c]) {
1433 const std::size_t k = r - 1;
1434 if (!(V(ist - 1, k) > zero)) {
1435 TN(ist - 1, k) = UN(ist - 1, k) = zero;
1436 continue;
1437 }
1438 TN(ist - 1, k) = T(lambda[c] * V(ist - 1, k));
1439 UN(ist - 1, k) = T(S(ist - 1, k) * TN(ist - 1, k) /
1441 }
1442 double Uden = 0.0;
1443 for (std::size_t k = 0; k < K; ++k) Uden += num_traits<T>::to_double(UN(ist - 1, k));
1444 Uden = std::min(1.0 - GlobalConstants::FineTol, Uden);
1445 for (std::size_t r : L.inchain[c]) {
1446 const std::size_t k = r - 1;
1447 if (!(V(ist - 1, k) > zero)) {
1448 QN(ist - 1, k) = RN(ist - 1, k) = zero;
1449 continue;
1450 }
1451 QN(ist - 1, k) =
1452 T(UN(ist - 1, k) / num_traits<T>::from_double(1.0 - Uden));
1453 RN(ist - 1, k) = (TN(ist - 1, k) > zero)
1454 ? T(QN(ist - 1, k) / TN(ist - 1, k))
1455 : zero;
1456 }
1457 }
1458 } else if (sched == SchedStrategy::FCFS || sched == SchedStrategy::HOL) {
1459 solve_fcfs_station(L, opt, ist, lambda, V, S, Sknown, PH, PHset, svc,
1460 chainSysArrivals, ztchain, QN, UN, RN, TN, exact_station);
1461 } else if (sched != SchedStrategy::EXT) {
1462 // The Source is skipped: it has no queue of its own, and the
1463 // dispatch overwrites its throughput with sn.rates afterwards.
1464 // The reference's switch has no default arm, so it skips every
1465 // other discipline SILENTLY; the featset gate in the runner
1466 // rejects them first, so reaching here is a defect and is named.
1467 throw UnsupportedError(
1468 std::string("solver_mam_basic: station '") + L.stations[ist - 1].name +
1469 "' uses the " + lang::sched_to_text(sched) +
1470 " discipline, which the dec.source decomposition does not model (it solves "
1471 "INF, PS, FCFS and HOL stations only)");
1472 }
1473 }
1474
1475 // Calibrate the fixed point on the REPORTED QN; see _kb/06-solver-catalog.md (MAM closed-chain population)
1476 resptime_floor(all_classes);
1477
1478 delta = 0.0;
1479 for (std::size_t i = 0; i < M; ++i)
1480 for (std::size_t r = 0; r < K; ++r)
1481 delta = std::max(delta, std::fabs(num_traits<T>::to_double(TN(i, r)) -
1482 num_traits<T>::to_double(TN_1(i, r))));
1483 }
1484
1485 // ---- the two rescaling passes ----------------------------------------
1486 for (std::size_t i = 0; i < M; ++i)
1487 for (std::size_t r = 0; r < K; ++r) QN(i, r) = num_abs(QN(i, r));
1488 for (int pass = 0; pass < 2; ++pass) {
1489 for (std::size_t c = 0; c < C; ++c) {
1490 double Nc = 0.0;
1491 bool closed = true;
1492 for (std::size_t r : L.inchain[c]) {
1493 if (std::isinf(L.classes[r - 1].population)) closed = false;
1494 else Nc += L.classes[r - 1].population;
1495 }
1496 if (closed) {
1497 T QNc = zero;
1498 for (std::size_t i = 0; i < M; ++i)
1499 for (std::size_t r : L.inchain[c]) QNc += QN(i, r - 1);
1500 if (QNc > zero) {
1501 const T f = T(num_traits<T>::from_double(Nc) / QNc);
1502 for (std::size_t i = 0; i < M; ++i)
1503 for (std::size_t r : L.inchain[c]) QN(i, r - 1) *= f;
1504 }
1505 }
1506 resptime_floor(L.inchain[c]);
1507 if (closed && Nc == 0.0) {
1508 for (std::size_t i = 0; i < M; ++i)
1509 for (std::size_t r : L.inchain[c]) {
1510 QN(i, r - 1) = UN(i, r - 1) = RN(i, r - 1) = TN(i, r - 1) = zero;
1511 }
1512 for (std::size_t r : L.inchain[c]) CN[r - 1] = XN[r - 1] = zero;
1513 }
1514 }
1515 }
1516
1517 for (std::size_t r = 0; r < K; ++r) {
1518 T s = zero;
1519 for (std::size_t i = 0; i < M; ++i) s += RN(i, r);
1520 CN[r] = s;
1521 }
1522 for (std::size_t c = 0; c < C; ++c)
1523 for (std::size_t r : L.inchain[c]) XN[r - 1] = TN(L.classes[r - 1].refstat - 1, r - 1);
1524
1526 out.Q = QN;
1527 out.U = UN;
1528 out.R = RN;
1529 out.Tp = TN;
1530 out.C = CN;
1531 out.X = XN;
1532 out.method = opt.method;
1533 out.iter = it + 2;
1534 return out;
1535 } // if constexpr has_transcendental
1536}
1537
1538} // namespace mam
1539} // namespace line
1540
1541#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:51
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.
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...
mam::Map< T > dist_to_map(const Distrib< T > &d)
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:181
ProcessType
Distribution kinds, with the values of MATLAB ProcessType.
Definition lang_types.h:483
const char * sched_to_text(SchedStrategy s)
Definition lang_types.h:230
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 > > 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
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)
Steady-state distribution of a continuous-time Markov chain.
Definition ctmc_solve.h:122
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:120
MmapGk1Result< T > qsys_mmapgk1(const std::vector< Matrix< T > > &MMAP, const std::vector< lang::Distrib< T > > &svc, const std::vector< T > &w_points, std::size_t num_w_moms, double tol, std::size_t iter_max)
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:63
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.
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)
MAP/D/c by Crommelin's exact embedded lattice chain.
Definition qsys_mapdc.h:153
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.
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
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.
T num_abs(const T &v)
Definition number.h:172
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/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,...
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.
static constexpr double Immediate
Rate of an Immediate distribution; its mean is 1/Immediate = 1e-8.
Definition lang_types.h:674
static constexpr double FineTol
Definition lang_types.h:668
static constexpr double CoarseTol
Definition lang_types.h:669
The options SolverMAM reads.
Definition mam_types.h:29
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:71
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:96
std::vector< T > X
Definition mva_types.h:98
std::vector< T > C
Definition mva_types.h:98
A node of the network.
static ServiceLaw phase_type(const std::vector< T > &alpha, const Matrix< T > &Tmat)
Phase type (alpha, Tmat).