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