LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
mam_dispatch.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_MAM_DISPATCH_H
6#define LINE_SOLVERS_MAM_MAM_DISPATCH_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * Port of `solver_mam_analyzer.m`: one inner solve, choosing the analyzer that
12 * fits the model and the requested method.
13 *
14 * THE ORDER IS THE CONTRACT, exactly as in `mva_dispatch.h`. The reference's
15 * sequence, top to bottom:
16 *
17 * -1 discrete-time (slotted) models -> solver_mam_dt <- ported
18 * 0 exact MAP/MAP/1 fast path, tried before any method dispatch <- ported
19 * 1 method 'dec.mmap' -> solver_mam <- ported
20 * 2 method 'default' / 'dec.source':
21 * 2a homogeneous Fork-Join -> solver_mam_fj ("qiu") <- ported
22 * 2b any other Fork-Join, open -> solver_mam_basic_mmap <- ported
23 * 2c BMAP/PH/N/N bufferless retrial -> solver_mam_retrial <- ported
24 * 2d reneging (MAP/M/s+G) -> solver_mam_reneging <- ported
25 * 2e single-class closed Delay+Queue -> solver_mam_ldqbd <- ported
26 * 2f otherwise -> solver_mam_basic <- ported
27 * 3 method 'dec.poisson' -> solver_mam_basic with space_max = 1 <- ported
28 * 4 method 'mna' -> solver_mna_open / solver_mna_closed <- ported
29 * 5 method 'ldqbd' -> solver_mam_ldqbd <- ported
30 * 5b method 'bgchain' -> solver_mam_bgchain <- ported
31 * 6 methods 'inap' / 'inaprc' / 'inapinf' -> moved to SolverAG (ag_dispatch.h)
32 * 6b method 'exact' -> removed from the reference (SolverMAM.m:39-40:
33 * "'exact' method removed - autocat moved to line-legacy.git"); not in
34 * list_valid_methods either, so unreachable through solver_mam_solve
35 * 6c methods 'sync.faster' / 'sync.slower' -> solver_mam_sync <- ported
36 * 7 method 'dec.source.mmap' -> solver_mam_basic_mmap <- ported
37 *
38 * 2a IS DOUBLE ONLY. The FJ_codes engine behind it needs an ordered real Schur
39 * factorization and two Bartels-Stewart Sylvester solves, i.e. LAPACK, so
40 * `solver_mam_fj` refuses at Rational and Real AFTER running the reference's two
41 * validation steps -- a model outside the homogeneous class is still named as
42 * such at every arithmetic.
43 *
44 * WHAT IS NOT PORTED IS REFUSED BY NAME and never allowed to fall through to
45 * `solver_mam_basic`. A fork-join model or a level-dependent closed model solved
46 * as an ordinary open decomposition returns numbers that are simply not the
47 * model's. The rule extends ONE step past the reference at 2b: a CLOSED
48 * fork-join model, which the reference itself lets fall through to
49 * `solver_mam_basic`, is refused here for exactly that reason; see the branch.
50 *
51 * AFTER the analyzer, the reference overwrites the throughput of every EXT
52 * (Source) station with `sn.rates`, and zeroes every NaN across its six metrics
53 * (the four matrices Q, U, R, Tp and the two vectors C, X). Both are reproduced
54 * in `finish_dispatch`, which every branch below step 0 returns through. Step 0
55 * bypasses it, as the reference's own early return does; see `finish_dispatch`.
56 * The C++ sweep tests `!isfinite` rather than NaN alone, so it also zeroes an
57 * infinity the reference would keep -- deliberate, because the `disabled` flags
58 * this port carries mean a non-finite entry here is a division artefact and
59 * never a modelled infinity.
60 */
61
62#include <limits>
63#include <cmath>
64#include <string>
65#include <vector>
66
84#include "line/util/error.h"
85
86namespace line {
87namespace mam {
88
89namespace dispatch_detail {
90
91/** Is there any Fork node? A Join alone cannot occur without one. */
92template <class T>
93bool has_fork(const qn::NetworkStruct<T>& L) {
94 return L.has_fork();
95}
96
97/**
98 * The reference's `sn_has_fork_join`, which is `any(sn.fj(:) > 0)` and NOT a
99 * scan for Fork nodes: it is the branch-2b gate, and a Fork whose Join the
100 * model never declared leaves `fj` empty and fails it.
101 */
102template <class T>
103bool has_fork_join(const qn::NetworkStruct<T>& L) {
104 return !L.fj.empty();
105}
106
107/**
108 * `sn_is_closed_model`, which is `all(isfinite(sn.njobs))`. NetworkStruct
109 * carries `is_open_model` but no counterpart, and the mna branch needs both:
110 * the reference's own else is the mixed-model refusal, so "not open" is not the
111 * same test as "closed". The empty-class guard mirrors `is_open_model`, where
112 * MATLAB's `all([])` would answer true for both.
113 */
114template <class T>
115bool is_closed_model(const qn::NetworkStruct<T>& L) {
116 for (const qn::JobClass& c : L.classes)
117 if (!std::isfinite(c.population)) return false;
118 return !L.classes.empty();
119}
120
121/** The reference's `isClosedDelayQueue`: one class, two stations, one INF one FCFS. */
122template <class T>
123bool is_closed_delay_queue(const qn::NetworkStruct<T>& L) {
124 if (L.nclasses != 1 || L.nstations != 2) return false;
125 if (!std::isfinite(L.classes[0].population)) return false;
126 std::size_t ndelay = 0, nqueue = 0;
127 for (const qn::Station<T>& st : L.stations) {
128 if (st.sched == lang::SchedStrategy::INF) ++ndelay;
129 else if (st.sched == lang::SchedStrategy::FCFS) ++nqueue;
130 }
131 return ndelay == 1 && nqueue == 1;
132}
133
134/**
135 * Whether a setup/delay-off station, if there is one, is inside the exact
136 * regime of `solver_mam_ldqbd`: one server, exponential service, no load
137 * dependence. True when the model declares no setup at all.
138 */
139template <class T>
140bool ldqbd_setup_ok(const qn::NetworkStruct<T>& L) {
141 if (L.setupparam.empty()) return true;
142 for (typename std::map<std::size_t, qn::SetupDelayOffParam<T>>::const_iterator it =
143 L.setupparam.begin();
144 it != L.setupparam.end(); ++it) {
145 const std::size_t ist = it->first;
146 if (ist == 0 || ist > L.stations.size()) return false;
147 lang::Distrib<T> su, doff;
148 if (!it->second.last(su, doff) || doff.disabled) continue; // not actually declared
149 const qn::Station<T>& st = L.stations[ist - 1];
150 if (st.nservers > 1) return false;
151 // NETWORK-WIDE, as the MATLAB reference's sn_has_load_dependence: the
152 // exact chain assumes a plain delay away from this station, so a
153 // load-dependent station ANYWHERE takes the model out of the regime, not
154 // only a load-dependent setup station. Reading st.lldscaling alone
155 // admitted a load-dependent Delay that MATLAB and the JAR refuse.
156 if (api::sn_has_load_dependence(L)) return false;
157 if (L.service.size() < ist || L.service[ist - 1].empty()) return false;
158 if (lang::dist_to_map(L.service[ist - 1][0]).D0.rows() != 1) return false;
159 }
160 return true;
161}
162
163/**
164 * The reference's `mnaApplies`: whether the closed MNA analyzer covers this
165 * model. The round-robin split is carried by the open traffic equations only, a
166 * self-looping class has no inter-station flow to decompose, and a station whose
167 * discipline the flow sweep does not update would keep a zero queue length. Any
168 * of those routes `default` to dec.source instead.
169 */
170template <class T>
171bool mna_applies(const qn::NetworkStruct<T>& L) {
172 // solver_mna_closed drives its bisection over CLASSES but stores the throughput in
173 // the CHAIN-indexed lambda, and renormalizes chain c's queue lengths with the
174 // class-indexed njobs(c). Both are only correct when each chain holds exactly one
175 // class, and the analyzer refuses otherwise by name -- so the DEFAULT has to stop
176 // here rather than propagate that refusal (cqn_twoclass_hyperl, 1 chain over 2
177 // classes, died at MAM under lang='cpp' while MATLAB answered dec.source).
178 if (L.nchains != L.nclasses) return false;
179
180 for (const qn::NodeDef& nd : L.nodes)
181 for (std::size_t r = 0; r < nd.routing.size(); ++r)
182 if (nd.routing[r] == lang::RoutingStrategy::RROBIN) return false;
183
184 for (const qn::Station<T>& st : L.stations) {
185 if (st.sched != lang::SchedStrategy::INF && st.sched != lang::SchedStrategy::PS &&
186 st.sched != lang::SchedStrategy::FCFS && st.sched != lang::SchedStrategy::EXT)
187 return false;
188 // The PS branch of solver_mna_closed forms U = S*T and the geometric bound
189 // from it WITHOUT dividing by the number of servers, so a multiserver PS
190 // station is misrepresented; dec.source is exact on the non-queueing regime
191 // (c >> N) that shape usually stands for.
192 if (st.sched == lang::SchedStrategy::PS && st.nservers > 1) return false;
193 // A multiclass FCFS station makes the flow sweep superpose one MMAP per class
194 // and then solve MMAPPH1FCFS at level sum(N)+1: measured against an exact CTMC
195 // that costs 12-61s where dec.source costs 0.03s and is not more accurate
196 // (mean relative error 0.11-0.38 against 0.04-0.19). The single-class case is
197 // both cheap and better, so keep only that one.
198 if (st.sched == lang::SchedStrategy::FCFS && L.nclasses > 1) return false;
199 }
200
201 const Matrix<T> V = basic_detail::station_visits(L);
202 for (std::size_t k = 0; k < L.nclasses; ++k) {
203 if (!std::isfinite(L.classes[k].population)) continue;
204 std::size_t seen = 0, at = 0;
205 for (std::size_t i = 0; i < L.nstations; ++i)
206 if (num_traits<T>::to_double(V(i, k)) > 1e-8) {
207 ++seen;
208 at = i;
209 }
210 if (seen == 1 && L.stations[at].sched != lang::SchedStrategy::INF &&
211 L.stations[at].sched != lang::SchedStrategy::EXT)
212 return false;
213 }
214 return true;
215}
216
217/**
218 * The reference's `mnaConserves`: whether the closed MNA outer bisection closed on
219 * N. `solver_mna_closed` rescales each chain onto its population as a last step, so
220 * a diverged bisection still returns queue lengths that sum to N and the failure is
221 * invisible in Q. R and Tp are NOT rescaled, so Little's law over the whole network,
222 * sum_i Tp(i,k)*R(i,k) = N_k, still reads the raw iterate: a converged run lands
223 * within 5e-4 of N and a diverged one is orders of magnitude out, or negative.
224 */
225template <class T, class Sol>
226bool mna_conserves(const qn::NetworkStruct<T>& L, const Sol& sol) {
227 for (std::size_t i = 0; i < L.nstations; ++i)
228 for (std::size_t k = 0; k < L.nclasses; ++k)
229 if (!std::isfinite(num_traits<T>::to_double(sol.Q(i, k))) ||
230 !std::isfinite(num_traits<T>::to_double(sol.R(i, k))) ||
231 !std::isfinite(num_traits<T>::to_double(sol.Tp(i, k))))
232 return false;
233
234 for (std::size_t k = 0; k < L.nclasses; ++k) {
235 const double nk = L.classes[k].population;
236 if (!std::isfinite(nk) || nk <= 0) continue;
237 double npred = 0;
238 for (std::size_t i = 0; i < L.nstations; ++i)
239 npred += num_traits<T>::to_double(sol.Tp(i, k)) * num_traits<T>::to_double(sol.R(i, k));
240 if (std::fabs(npred - nk) > 0.01 * nk) return false;
241 }
242 return true;
243}
244
245/**
246 * The reference's `bgchainApplies`: no class priorities, no fork-join, and at
247 * least one station visited by the closed classes, which is what the background
248 * chain is built over.
249 */
250template <class T>
251bool bgchain_applies(const qn::NetworkStruct<T>& L, const MamOptions& opt) {
252 bool prio_sched = false;
253 for (const qn::Station<T>& st : L.stations)
254 if (st.sched == lang::SchedStrategy::HOL || st.sched == lang::SchedStrategy::FCFSPRPRIO)
255 prio_sched = true;
256 if (prio_sched)
257 for (std::size_t k = 1; k < L.nclasses; ++k)
258 if (L.classes[k].prio != L.classes[0].prio) return false;
259
260 // An LCFS-PR station: the background chain serves every non-PS queue in
261 // arrival order, so it is left to dec.source and its matrix product form.
262 for (const qn::Station<T>& st : L.stations)
263 if (st.sched == lang::SchedStrategy::LCFSPR) return false;
264
265 if (has_fork_join(L)) return false;
266
267 const mva::ChainDemands<T> dem = mva::sn_get_demands_chain(L);
268 bool visited = false;
269 for (std::size_t c = 0; c < L.nchains && !visited; ++c) {
270 if (!std::isfinite(num_traits<T>::to_double(dem.Nchain[c])) ||
271 num_traits<T>::to_double(dem.Nchain[c]) <= 0.0)
272 continue;
273 for (std::size_t i = 0; i < L.nstations; ++i)
274 if (num_traits<T>::to_double(dem.Vchain(i, c)) > 1e-14) {
275 visited = true;
276 break;
277 }
278 }
279 if (!visited) return false;
280
281 // The background chain enumerates the closed population vector over the
282 // stations the closed classes visit, so a large closed population makes
283 // mam_bgchain_ctmc refuse the model outright. That refusal is right when the
284 // user asked for bgchain by name and wrong as a default, which must land on
285 // a method that answers: size the chain first and leave those models to
286 // dec.source. The limit is the one mam_bgchain_ctmc enforces.
287 const double states_max = (opt.bgstates_max > 0) ? static_cast<double>(opt.bgstates_max) : 20000.0;
288 return bgchain_states(L, opt) <= states_max;
289}
290
291/**
292 * The reference's `bgchainClosedExact`: whether the background chain represents
293 * this closed model's service laws exactly.
294 *
295 * A station that is not PS or INF must satisfy BOTH conditions below, because the
296 * background chain makes two separate first-moment substitutions there.
297 *
298 * 1 mam_bgchain_ctmc builds its generator from the MEAN service time alone.
299 * That is exact at a PS or INF station, which is insensitive to the service
300 * law beyond its first moment, and exact under any discipline when the law
301 * IS exponential. Measured on a closed Delay+FCFS cycle with Erlang-3
302 * service, the mean-only chain reads 2.8% off SolverCTMC.
303 * 2 The capacity a station's closed jobs hold is split over the background
304 * classes in proportion to their COUNTS, which is service in random order.
305 * That is exact under PS, and exact under FCFS only when the classes are
306 * served at the SAME rate -- an FCFS station with class-dependent rates
307 * reads 25.2% off SolverCTMC on a two-chain closed cycle, against 3.5e-16
308 * when the two rates are made equal.
309 *
310 * solver_mna_closed carries the phase-type representation instead, so neither
311 * surrogate may be chosen as the DEFAULT. Asking for bgchain by name still gets
312 * it, with both approximations documented in solver_mam_bgchain.
313 */
314template <class T>
315bool bgchain_closed_exact(const qn::NetworkStruct<T>& L) {
316 for (std::size_t i = 0; i < L.nstations; ++i) {
317 const lang::SchedStrategy sc = L.stations[i].sched;
320 continue;
321 double rate_here = std::numeric_limits<double>::quiet_NaN();
322 for (std::size_t r = 0; r < L.nclasses; ++r) {
323 const double rate = num_traits<T>::to_double(L.rates(i, r));
324 if (!std::isfinite(rate) || rate <= 0.0) continue;
325 if (L.service[i][r].type != lang::ProcessType::EXP) return false;
326 if (std::isnan(rate_here)) {
327 rate_here = rate;
328 } else if (std::fabs(rate - rate_here) > 1e-3 * rate_here) {
329 return false;
330 }
331 }
332 }
333 return true;
334}
335
336/**
337 * Is any station a Cache, a Place or a Transition, i.e. outside the MAM envelope?
338 * A Place or a Transition is inside it under 'default' and 'ispn', which route a
339 * stochastic Petri net to solver_mam_ispn.
340 */
341template <class T>
342void reject_unsupported_nodes(const qn::NetworkStruct<T>& L, const std::string& method = "") {
343 const bool spn_ok = method == "default" || method == "ispn";
344 for (const qn::NodeDef& nd : L.nodes) {
345 switch (nd.nodetype) {
346 case qn::NodeType::Cache:
347 throw UnsupportedError(ErrorKind{"Cache"},
348 "SolverMAM: Cache nodes are outside the MAM feature set; use SolverMVA, "
349 "SolverNC, SolverCTMC or SolverLDES");
350 case qn::NodeType::Place:
351 case qn::NodeType::Transition:
352 if (spn_ok) break;
353 throw UnsupportedError(ErrorKind{"Place"},
354 "SolverMAM: stochastic Petri net models are outside the MAM feature set; "
355 "use SolverCTMC, SolverSSA or SolverLDES");
356 default:
357 break;
358 }
359 }
360 // A BMAP SERVICE is a BULK SERVER (one firing completes several jobs). No
361 // MAM analyzer reads the batch blocks: every route took the BMAP as the MAP
362 // of its firing epochs, one job per firing, and answered a saturated queue.
363 for (std::size_t i = 0; i < L.nstations; ++i) {
364 if (L.stations[i].nodetype == qn::NodeType::Source) continue;
365 for (std::size_t r = 0; r < L.nclasses; ++r)
366 if (!L.service[i][r].disabled &&
367 (L.service[i][r].type == lang::ProcessType::BMAP ||
368 L.service[i][r].type == lang::ProcessType::BMMAPT))
369 throw UnsupportedError(ErrorKind{"BMAP"},
370 "SolverMAM: station '" + L.stations[i].name + "' serves class '" +
371 L.classes[r].name + "' with a batch (BMAP) process, i.e. a bulk server "
372 "whose firing completes several jobs; MAM has no bulk-server analysis. "
373 "Use SolverLDES");
374 }
375 // A Source emitting BMAP BATCHES (more than one batch block). Every route,
376 // the retrial one included (solver_mam_retrial.h passes dist_to_map's
377 // aggregate {D0, D1} to the engine), reads it as the MAP of the batch
378 // epochs and counts one job per batch: Tput 0.6 for a 1.02 jobs/s source.
379 // MATLAB, JAR and Python still admit the BMAP/PH/N/N retrial route, whose
380 // engine there receives the batch blocks; this layer does not wire them.
381 for (std::size_t i = 0; i < L.nstations; ++i) {
382 if (L.stations[i].nodetype != qn::NodeType::Source) continue;
383 for (std::size_t r = 0; r < L.nclasses; ++r)
384 if (!L.service[i][r].disabled && lang::process_is_batch(L.service[i][r].type) &&
385 L.service[i][r].Dmark.size() > 1)
386 throw UnsupportedError(ErrorKind{"BMAP"},
387 "SolverMAM: source '" + L.stations[i].name + "' emits class '" +
388 L.classes[r].name + "' as batches (BMAP); SolverMAM would count one job "
389 "per batch. Use SolverMVA (M^X/G/1, 'mxg1') or SolverLDES");
390 }
391}
392
393} // namespace dispatch_detail
394
395
396/**
397 * What `solver_mam_analyzer.m` does AFTER whichever analyzer ran: pin the
398 * throughput of every EXT (Source) station to its declared rate, and zero every
399 * non-finite entry.
400 *
401 * Factored out because THREE branches return early and must still take this
402 * tail: 2a (`qiu`), 2c (`retrial`) and the 2e `ldqbd` preference on `default`.
403 * The reference has no early return at any of them -- its `case` bodies fall
404 * through to the tail -- so routing them here is what keeps the C++ ladder
405 * equivalent rather than an optimization.
406 *
407 * THE ONE EARLY RETURN THAT DOES NOT COME HERE is the exact MAP/MAP/1 fast
408 * path, and it matches the reference: `solver_mam_analyzer.m` lines 10-17
409 * return before the tail as well. It is not an omission -- that analyzer sets
410 * the Source throughput itself (`solver_mam_mapmap1_exact.h`, `Tp(src,0) =
411 * lambda`), so there is nothing for the tail to pin.
412 *
413 * 'censor' takes the tail WITHOUT the pin, as the reference skips `TN = sn.rates`
414 * for that method: its Source row is SolverCTMC's extraction over the truncated
415 * chain, which is what makes it agree with SolverCTMC at the same cutoff.
416 */
417template <class T>
419 bool pin_source = true) {
421 const T zero = num_traits<T>::from_int(0);
422 if (pin_source)
423 for (std::size_t i = 0; i < L.nstations; ++i)
424 if (L.stations[i].sched == SchedStrategy::EXT)
425 for (std::size_t r = 0; r < L.nclasses; ++r)
426 out.sol.Tp(i, r) = L.disabled[i][r] ? zero : L.rates(i, r);
427 // The reference's terminal NaN sweep. The C++ layer carries `disabled`
428 // flags rather than NaN sentinels, so nothing here should be non-finite;
429 // the sweep stays because a division by a zero iterate can still produce
430 // one at double, and reporting NaN would be worse than reporting zero.
431 Matrix<T>* mats[4] = {&out.sol.Q, &out.sol.U, &out.sol.R, &out.sol.Tp};
432 for (Matrix<T>* m : mats)
433 for (std::size_t i = 0; i < m->rows(); ++i)
434 for (std::size_t j = 0; j < m->cols(); ++j)
435 if (!std::isfinite(num_traits<T>::to_double((*m)(i, j)))) (*m)(i, j) = zero;
436 for (T& v : out.sol.C)
437 if (!std::isfinite(num_traits<T>::to_double(v))) v = zero;
438 for (T& v : out.sol.X)
439 if (!std::isfinite(num_traits<T>::to_double(v))) v = zero;
440 return out;
441}
442
443/** The ladder. */
444template <class T>
447 MamOptions opt = opt_in;
448 MamSolution<T> out;
449
450 dispatch_detail::reject_unsupported_nodes(L, opt.method);
451
452 // -2. a stochastic Petri net, which 'default' and 'ispn' route to the
453 // matrix-geometric iSPN analyzer, as solver_mam_analyzer.m does. No queueing
454 // analyzer below reads a Place, so the net leaves the ladder here.
455 if (ispn_has_place(L) || opt.method == "ispn") {
456 const std::string why = ispn_refusal(L, opt.method);
457 if (!why.empty()) throw UnsupportedError(ErrorKind{"Structure"}, why);
458 out = solver_mam_ispn(L, opt);
459 return finish_dispatch(L, out);
460 }
461
462 // -1. the discrete-time (slotted) path, ahead of EVERYTHING. It has to run
463 // before any phase-type conversion: by the time a law reaches `proc` a
464 // Geometric has already been fitted to a CONTINUOUS MAP and the lattice is
465 // no longer visible, so the test reads procid/rates/scv instead.
466 if constexpr (num_traits<T>::has_transcendental) {
468 dtopt.timescale = opt.timescale;
469 dtopt.slotted = opt.slotted;
470 dtopt.slotlength = opt.slotlength;
471 double slot = 1.0;
473 if (api::sn_is_discrete_time(L, dtopt, &slot, &dtinfo)) {
474 out = solver_mam_dt(L, opt, slot);
475 out.sol.method = opt.method;
476 return out;
477 }
478 }
479
480 // 0. the exact MAP/MAP/1 fast path, ahead of any method dispatch. A station
481 // that powers down is NOT an M/M/1 whatever its shape looks like: the setup
482 // is extra work the QBD below does not carry, so it must not be taken here.
483 if (L.setupparam.empty()) {
485 if (ex.ok) {
486 out.sol = ex.sol;
487 out.sol.method = opt.method;
488 out.actualmethod = "exact.mapmap1";
489 return out;
490 }
491 }
492
493 const std::string& method = opt.method;
494
495 if (method == "dec.mmap") {
496 out.sol = solver_mam_decmmap(L, opt);
497 out.actualmethod = "dec.mmap";
498 return finish_dispatch(L, out);
499 }
500
501 if (method == "default" || method == "dec.source" || method == "dec.poisson") {
502 if (method == "dec.poisson") opt.space_max = 1;
503 if (method != "dec.poisson") {
504 if constexpr (!num_traits<T>::has_transcendental) {
505 if (dispatch_detail::has_fork(L) || dispatch_detail::has_fork_join(L))
506 throw UnsupportedError(ErrorKind{"Arithmetic"},
507 "SolverMAM: model '" + L.name +
508 "' forks, and every fork-join route here first classifies the branches by "
509 "fitting a phase-type to each, which is transcendental and has no exact "
510 "counterpart; use --arith double or real");
511 } else {
512 // 2a: `fj_is_homogeneous` -- one fork-join pair, K identical open
513 // FCFS/PS branches -- is the ONLY class FJ_codes is defined on, and
514 // most fork-join models fail it, in which case 2b takes them. See
515 // solver_mam_fj.h for why no other FJ approximation in this tree may
516 // be substituted under this method name.
517 // THE PREDICATE IS NOT ARITHMETIC-NEUTRAL. mam_fj_is_homogeneous
518 // compares branches by fitting a PH to each (dist_to_map ->
519 // aph_fit), which static_asserts on transcendental arithmetic, so
520 // calling it unconditionally made the WHOLE MAM dispatch
521 // uninstantiable at Rational -- a model with no Fork at all stopped
522 // compiling. It is therefore reached only from the exact-capable
523 // branch below, and exact arithmetic refuses a forking model BY
524 // NAME rather than skipping the gate and answering it as ordinary.
525 const MamFjInfo fjinfo = mam_fj_is_homogeneous(L);
526 if (fjinfo.ok) {
527 out.sol = solver_mam_fj(L, opt);
528 out.actualmethod = "qiu";
529 return finish_dispatch(L, out);
530 }
531 // 2b: every other OPEN fork-join model, which the reference sends to
532 // the MMAP decomposition.
533 if (dispatch_detail::has_fork_join(L) && L.is_open_model()) {
534 out.sol = solver_mam_basic_mmap(L, opt);
535 out.actualmethod = "dec.source.mmap";
536 return finish_dispatch(L, out);
537 }
538 // DELIBERATE DEVIATION, and the only one in this ladder. A CLOSED
539 // fork-join model passes both reference gates and falls through to
540 // solver_mam_basic, whose dec.source decomposition has no Join
541 // synchronization at all: it zeroes the Join's own metrics and
542 // charges no waiting for the slowest sibling branch, so the response
543 // times it reports are the branches' and not the model's, with
544 // nothing in the output to say so. Refused by name instead.
545 //
546 // SANCTIONED (2026-07-28), not provisional: the refusal is preferred
547 // over bit-parity with MATLAB because the alternative here is a
548 // SILENTLY WRONG answer, not a less accurate one. Do not "restore
549 // parity" by deleting this without reopening that decision.
550 if (dispatch_detail::has_fork(L))
551 throw UnsupportedError(ErrorKind{"Fork"},
552 "SolverMAM: model '" + L.name +
553 "' carries a Fork but is not an open fork-join network, and "
554 "solver_mam_analyzer.m has no branch for it: it falls through to "
555 "solver_mam_basic, whose dec.source decomposition never charges the "
556 "synchronization delay at the Join, so the response times would be those of "
557 "the branches alone. Call method 'dec.source.mmap', which routes the model to "
558 "the MMAP decomposition's closed wrapper and does charge the join, or use "
559 "SolverMVA, SolverNC, SolverJMT or SolverLDES");
560 }
561
562 // 2c: the BMAP/PH/N/N bufferless retrial queue of Dudin et al. A
563 // station is claimed only when it declares an orbit or is
564 // bufferless AND carries a RETRIAL drop rule, exactly as
565 // qsys_is_retrial.m requires; nothing is inferred from capacity
566 // alone, which would claim finite buffers that are not orbits.
567 // The DETECTION is arithmetic-neutral (it reads retrialparam and
568 // the drop rule), but the ANALYZER fits a phase-type to the arrival
569 // and service processes at solver_mam_retrial.h:360, so the orbit
570 // route is transcendental even though qsys_bmapphnn_retrial itself
571 // is exact. Refuse the orbit BY NAME under an exact type rather
572 // than fall through to 2e/2f, which would answer it as an ordinary
573 // waiting line -- the very substitution wiring this branch removed.
574 const MamRetrialInfo retinfo = mam_retrial_detect(L);
575 if (retinfo.ok) {
576 if constexpr (!num_traits<T>::has_transcendental) {
577 throw UnsupportedError(ErrorKind{"Arithmetic"},
578 "SolverMAM: model '" + L.name +
579 "' declares a retrial orbit, whose analyzer fits a phase-type to the "
580 "arrival and service processes and has no exact counterpart; use --arith "
581 "double or real");
582 } else {
583 out.sol = solver_mam_retrial(L, opt);
584 out.actualmethod = "retrial";
585 return finish_dispatch(L, out);
586 }
587 }
588 // An orbit OUTSIDE that shape (a non-exponential retrial delay or
589 // orbit abandonment, a finite attempt cap, several classes...) must
590 // not fall through to 2e/2f either: they read no retrial field and
591 // would answer it as an ordinary waiting line.
592 for (std::size_t i = 1; i <= L.nstations; ++i)
593 if (retrial_detail::has_retrial_proc(L, i))
594 throw UnsupportedError(ErrorKind{"Retrial"},
595 "SolverMAM: model '" + L.name + "' declares a retrial orbit outside the "
596 "BMAP/PH/N/N bufferless shape the retrial analyzer solves (" + retinfo.why +
597 "). Use SolverLDES for any retrial law, or SolverCTMC/SolverSSA for an "
598 "exponential retrial delay with unlimited attempts and no orbit abandonment.");
599 // 2d: reneging (`mam_has_reneging_patience`) reaches the same
600 // analyzer's OTHER route, the MAP/M/s+G fluid queue of
601 // solver_mam_reneging.h. A declared reneging OUTSIDE that shape (or a
602 // non-Markovian patience) must not fall through to 2e/2f, which read
603 // no patience and would answer it as an ordinary waiting line;
604 // check_model_method refuses it ahead of the dispatch with the same
605 // sentence, which is raised again here for a direct caller.
606 if (mam_declares_reneging(L)) {
607 const std::string renWhy = mam_reneging_default_refusal(L);
608 if (!renWhy.empty()) throw UnsupportedError(ErrorKind{"Reneging"}, renWhy);
610 out.actualmethod = "reneging";
611 return finish_dispatch(L, out);
612 }
613 //
614 // 2e: the level-dependent QBD is EXACT for this shape, and the
615 // reference prefers it over dec.source on 'default'. The OPEN
616 // Source+Queue regime of solver_mam_ldqbd is deliberately NOT
617 // claimed here: it truncates at options.cutoff, so it is not
618 // unconditionally better than dec.source and stays opt-in through
619 // method='ldqbd', exactly as the reference's isClosedDelayQueue
620 // comment states.
621 // A closed setup task IS a Delay+Queue tandem by shape, and ldqbd
622 // now models it exactly -- but only at a single server with
623 // exponential service and no load dependence, which is what
624 // qbd_setupdelayoff_closed covers. Outside that it refuses by name,
625 // so the shape test has to exclude those or the default would reach
626 // the refusal instead of falling through to the decomposition.
627 if (method == "default" && dispatch_detail::ldqbd_setup_ok(L) &&
628 dispatch_detail::is_closed_delay_queue(L)) {
629 out.sol = solver_mam_ldqbd(L, opt).sol;
630 out.actualmethod = "ldqbd";
631 return finish_dispatch(L, out);
632 }
633
634 // 2e-bis: a closed model is the degenerate case of the background chain.
635 // With no open work to take a share of the servers the chain is the EXACT
636 // closed CTMC at chain granularity, so it dominates the mna fixed point
637 // wherever its state space fits. bgchain_applies sizes that state space
638 // and bgchain_closed_exact checks the chain is built from a service law it
639 // represents exactly.
640 // bgchain DROPS setup/delay-off: it would answer with the
641 // always-warm chain and nothing would say so. Only solver_mam_basic
642 // and solver_mam_ldqbd read it, so a setup model must not reach here.
643 if (method == "default" && dispatch_detail::is_closed_model(L) &&
644 L.setupparam.empty() &&
645 dispatch_detail::bgchain_applies(L, opt) &&
646 dispatch_detail::bgchain_closed_exact(L)) {
647 out.sol = solver_mam_bgchain(L, opt);
648 out.actualmethod = "bgchain";
649 return finish_dispatch(L, out);
650 }
651
652 // 2f: a closed model has no arrival stream for dec.source to build its
653 // Poisson surrogate from -- it replaces each closed chain by a source at
654 // the current throughput iterate and never enforces the population, so
655 // the answer neither conserves N nor separates the classes. MNA closes
656 // the same traffic equations by bisecting the per-class throughput
657 // against N.
658 // mna DROPS setup/delay-off for the same reason as bgchain.
659 if (method == "default" && dispatch_detail::is_closed_model(L) &&
660 L.setupparam.empty() &&
661 dispatch_detail::mna_applies(L)) {
662 out.sol = solver_mna_closed(L, opt);
663 out.actualmethod = "mna";
664 if (!dispatch_detail::mna_conserves(L, out.sol)) {
665 // The outer bisection did not close on the population: the last
666 // step rescales each chain onto N regardless, so the failure is
667 // invisible in Q alone and only Little's law on the unrescaled R
668 // and Tp still shows it.
669 out.sol = solver_mam_basic(L, opt);
670 out.actualmethod = "dec.source";
671 }
672 return finish_dispatch(L, out);
673 }
674
675 // 2g: mixed. The closed classes are solved exactly as a background chain
676 // and the open ones as QBDs driven by it, which is 4-5 significant
677 // digits against CTMC where dec.source is 10-24% out.
678 // The mixed branch drops setup/delay-off exactly as the closed one
679 // does, so it takes the same guard.
680 if (method == "default" && !L.is_open_model() && L.setupparam.empty() &&
681 !dispatch_detail::is_closed_model(L) && dispatch_detail::bgchain_applies(L, opt)) {
682 out.sol = solver_mam_bgchain(L, opt);
683 out.actualmethod = "bgchain";
684 return finish_dispatch(L, out);
685 }
686 }
687 out.sol = solver_mam_basic(L, opt);
688 out.actualmethod = (method == "default") ? "dec.source" : method;
689 } else if (method == "mna") {
690 // The two analyzers are disjoint by population regime, so unlike the
691 // fork-join and retrial branches this pair carries no order hazard; the
692 // reference's open-then-closed sequence is kept anyway.
693 if (L.is_open_model()) {
694 out.sol = solver_mna_open(L, opt);
695 } else if (dispatch_detail::is_closed_model(L)) {
696 out.sol = solver_mna_closed(L, opt);
697 } else {
698 // The reference's own line_error. `SolverMAM.supportsModelMethod`
699 // already rejects a mixed model one level up, in
700 // runner_detail::check_model_method, so this is reachable only by
701 // calling mam_dispatch directly; it is transcribed rather than
702 // dropped because that caller exists.
703 throw UnsupportedError(ErrorKind{"MixedNetwork"},
704 "SolverMAM: the mna method in SolverMAM does not support mixed models");
705 }
706 out.actualmethod = "mna";
707 } else if (method == "bgchain") {
708 // Mixed networks: the closed classes are a background modulating chain,
709 // the open classes are QBDs driven by it. With several closed chains an
710 // outer iteration tags one chain at a time and aggregates the rest, so
711 // the background chain always carries two classes.
712 out.sol = solver_mam_bgchain(L, opt);
713 out.actualmethod = "bgchain";
714 } else if (method == "ldqbd") {
715 out.sol = solver_mam_ldqbd(L, opt).sol;
716 out.actualmethod = "ldqbd";
717 } else if (method == "censor") {
718 // The network CTMC read as connected LDQBDs and solved by successive
719 // censoring (solver_mam_censor.m); the Source throughput is the chain's.
720 out.sol = solver_mam_censor(L, opt).sol;
721 out.actualmethod = "censor";
722 return finish_dispatch(L, out, false);
723 } else if (method == "inap" || method == "inaprc" || method == "inapinf"
724 || method == "exact") {
725 // The RCAT methods moved to SolverAG. Name them rather than reporting an
726 // unknown method, so a caller carrying an old options.method is told
727 // where they went.
728 throw UnsupportedError(ErrorKind{"Method"},
729 "SolverMAM: the '" + method + "' method moved to SolverAG: RCAT decomposes the "
730 "model into cooperating agents rather than decomposing traffic, and no MAM "
731 "algorithm shares its machinery. Solve it with -s ag, or call "
732 "line::ag::solver_ag directly");
733 } else if (method == "retrial") {
734 // The BMAP/PH/N/N retrial analyzer BY NAME, which branch 2c also
735 // resolves to from 'default' on a retrial topology. The reference
736 // advertises the name (SolverMAM.m) and dispatches it
737 // (solver_mam_analyzer.m 'case retrial'), so it must be reachable here
738 // and must refuse off that topology rather than answer a waiting line.
739 {
740 // The predicate `check_model_method` and `auto_family_refusal` ask,
741 // so the method the report offers and the method that runs are the
742 // same set, with the same sentence when they are not.
743 const std::string retrialWhy = mam_retrial_refusal(L);
744 if (!retrialWhy.empty()) throw UnsupportedError(ErrorKind{"Retrial"}, retrialWhy);
745 if constexpr (!num_traits<T>::has_transcendental) {
746 throw UnsupportedError(ErrorKind{"Arithmetic"},
747 "SolverMAM: the retrial analyzer fits a phase-type to the arrival and "
748 "service processes and has no exact counterpart; use --arith double or real");
749 } else {
750 out.sol = solver_mam_retrial(L, opt);
751 out.actualmethod = "retrial";
752 }
753 }
754 } else if (method == "sync.faster" || method == "sync.slower") {
755 // Synchronous approximation of an M/G/c/K station with dual bounds; the
756 // shape is mam_sync_refusal's, which the gate and solver_mam_sync ask.
757 const std::string syncWhy = mam_sync_refusal(L, opt.sync_phases);
758 if (!syncWhy.empty()) throw UnsupportedError(ErrorKind{"Structure"}, "SolverMAM: " + syncWhy);
759 if constexpr (!num_traits<T>::has_transcendental) {
760 throw UnsupportedError(ErrorKind{"Arithmetic"},
761 "SolverMAM: the sync methods uniformize the service law, whose coefficients need "
762 "exp; use --arith double or real");
763 } else {
764 out.sol = solver_mam_sync(L, opt);
765 out.actualmethod = method;
766 }
767 } else if (method == "dec.source.mmap") {
768 // solver_mam_basic_mmap.m: the inner MMAP decomposition for an open
769 // model, the throughput bisection around it for a closed one. Unlike
770 // branch 2b this is reachable BY NAME on a model with no fork at all,
771 // which is what the reference's own dispatcher allows.
772 out.sol = solver_mam_basic_mmap(L, opt);
773 out.actualmethod = "dec.source.mmap";
774 } else {
775 throw UnsupportedError(ErrorKind{"Method"}, "SolverMAM: unknown method '" + method + "'");
776 }
777
778 return finish_dispatch(L, out);
779}
780
781} // namespace mam
782} // namespace line
783
784#endif // LINE_SOLVERS_MAM_MAM_DISPATCH_H
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
std::map< std::size_t, SetupDelayOffParam< T > > setupparam
Setup / delay-off, keyed by 1-based STATION index.
std::vector< std::vector< bool > > disabled
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 ...
bool is_open_model() const
sn_is_open_model: EVERY class is open, which is not has_open_classes.
The exception types the port throws.
The option and result types SolverMAM shares with its analyzers.
bool sn_has_load_dependence(const qn::NetworkStruct< T > &sn)
size(sn.lldscaling,2)>0: some station carries a limited-load scaling row.
bool sn_is_discrete_time(const qn::NetworkStruct< T > &sn, const DiscreteTimeOptions &options, double *slot_length, DiscreteTimeInfo *info)
True when every law of sn is lattice-valued on slot_length.
mam::Map< T > dist_to_map(const Distrib< T > &d)
The (D0,D1) pair that reaches sn.proc.
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
bool process_is_batch(ProcessType p)
True when an EVENT of this process releases (or, as a service process, completes) a BATCH of jobs who...
Definition lang_types.h:771
@ BMMAPT
BMMAPT crosses the BATCH axis with the two above: a block is indexed by segment, mark and batch size,...
Definition lang_types.h:613
MamSolution< T > & finish_dispatch(const qn::NetworkStruct< T > &L, MamSolution< T > &out, bool pin_source=true)
What solver_mam_analyzer.m does AFTER whichever analyzer ran: pin the throughput of every EXT (Source...
mva::MvaSolution< T > solver_mna_open(const qn::NetworkStruct< T > &L, const MamOptions &opt, const MnaConfig &cfg=MnaConfig())
Port of solver_mna_open.m.
Definition solver_mna.h:379
double bgchain_states(const qn::NetworkStruct< T > &L, const MamOptions &opt)
Number of states of the background-chain CTMC solver_mam_bgchain would build on this model,...
mva::MvaSolution< T > solver_mam_bgchain(const qn::NetworkStruct< T > &L, const MamOptions &opt)
Port of solver_mam_bgchain.m.
MamSolution< T > mam_dispatch(const qn::NetworkStruct< T > &L, const MamOptions &opt_in)
The ladder.
bool mam_declares_reneging(const qn::NetworkStruct< T > &L)
True when some station-class pair declares RENEGING, with or without a patience law this analyzer can...
mva::MvaSolution< T > solver_mam_basic_mmap(const qn::NetworkStruct< T > &L, const MamOptions &opt)
Port of solver_mam_basic_mmap.m, the top-level dispatcher of the MMAP fork-join decomposition: an ope...
MamRenegingInfo mam_reneging_detect(const qn::NetworkStruct< T > &L)
Port of mam_reneging_applicable.m: is this the MAP/M/s+G shape?
mva::MvaSolution< T > solver_mam_fj(const qn::NetworkStruct< T > &L, const MamOptions &opt, std::vector< std::vector< T > > *percentiles_out)
Port of solver_mam_fj.m.
mva::MvaSolution< T > solver_mam_sync(const qn::NetworkStruct< T > &L, const MamOptions &opt)
Port of solver_mam_sync.m: fills Q, U, R, T, C, X from qsys_mgck_sync.
bool ispn_has_place(const qn::NetworkStruct< T > &L)
True when the model holds a Place node, i.e.
LdqbdSolution< T > solver_mam_ldqbd(const qn::NetworkStruct< T > &L, const MamOptions &opt)
Port of solver_mam_ldqbd.m.
MamCensorResult< T > solver_mam_censor(const qn::NetworkStruct< T > &L, const MamOptions &opt)
Port of solver_mam_censor.m.
mva::MvaSolution< T > solver_mam_basic(const qn::NetworkStruct< T > &L, const MamOptions &opt)
Port of solver_mam_basic.m.
MamFjInfo mam_fj_is_homogeneous(const qn::NetworkStruct< T > &L)
Port of fj_is_homogeneous.m.
MamSolution< T > solver_mam_dt(const qn::NetworkStruct< T > &sn, const MamOptions &opt, double slot_length)
Discrete-time analysis of sn, returning the same metric tuple as every other MAM analyzer.
mva::MvaSolution< T > solver_mna_closed(const qn::NetworkStruct< T > &L, const MamOptions &opt)
Port of solver_mna_closed.m.
Definition solver_mna.h:656
MamRetrialInfo mam_retrial_detect(const qn::NetworkStruct< T > &L)
Port of qsys_is_retrial.m, plus the reneging gate of solver_mam_retrial.m.
MapMap1Exact< T > solver_mam_mapmap1_exact(const qn::NetworkStruct< T > &L)
std::string mam_sync_refusal(const qn::NetworkStruct< T > &L, std::size_t nph, MamSyncParams< T > *par=nullptr)
mam_sync_applicable.m: why the sync methods cannot answer this model, or "" when they can,...
mva::MvaSolution< T > solver_mam_decmmap(const qn::NetworkStruct< T > &L, const MamOptions &opt)
Port of solver_mam.m.
std::string mam_reneging_default_refusal(const qn::NetworkStruct< T > &L)
The sentence supportsModelMethod('default') refuses a declared reneging with when the model is not th...
mva::MvaSolution< T > solver_mam_retrial(const qn::NetworkStruct< T > &L, const MamOptions &opt, const MamRetrialConfig &cfg=MamRetrialConfig())
Port of solver_mam_retrial.m.
std::string ispn_refusal(const qn::NetworkStruct< T > &L, const std::string &method)
Why the iSPN route cannot take this model under METHOD, or "" when it can or when the model is not a ...
mva::MvaSolution< T > solver_mam_reneging(const qn::NetworkStruct< T > &L, const MamOptions &opt, const MamRenegingInfo &info)
The reneging route of solver_mam_retrial.m.
MamSolution< T > solver_mam_ispn(const qn::NetworkStruct< T > &L, const MamOptions &opt)
The analyzer.
std::string mam_retrial_refusal(const qn::NetworkStruct< T > &L)
The 'retrial' method's applicability as one sentence; empty when applicable.
ChainDemands< T > sn_get_demands_chain(const qn::NetworkStruct< T > &L)
Port of sn_get_demands_chain.
Definition sn_chain.h:63
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
Port of matlab/src/api/sn/sn_is_discrete_time.m.
Ports of the sn_has_* / sn_is_* predicate family of matlab/src/api/sn.
Port of solver_mam_basic.m, the dec.source analyzer and the default algorithm of SolverMAM.
Port of solver_mam_basic_mmap.m, solver_mam_basic_mmap_inner.m and solver_mam_basic_mmap_closed....
Port of solver_mam_bgchain.m and its three helpers: the analyzer that treats the CLOSED classes as a ...
Port of solver_mam_censor.m: the 'censor' method of SolverMAM.
Port of solver_mam.m, the dec.mmap method: the per-class departure-process decomposition.
Port of solver_mam_dt.m: discrete-time (slotted) analysis of an open network whose interarrival and s...
Port of solver_mam_fj.m, the fork-join route of SolverMAM.
The 'ispn' method of SolverMAM: steady state of a stochastic Petri net with exactly one unbounded pla...
Port of solver_mam_ldqbd.m: the level-dependent QBD analyzer for a single-class network of one infini...
Port of solver_mam_mapmap1_exact.m: the exact fast path SolverMAM tries BEFORE anything else,...
Port of solver_mam_retrial.m, the customer-impatience analyzer of SolverMAM.
The 'sync.faster' and 'sync.slower' methods of SolverMAM: the synchronous approximation of an M/G/c/K...
Port of solver_mna_open.m and solver_mna_closed.m, the two analyzers behind SolverMAM's mna method.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
Which laws the model carries, and why it was refused when it was.
How the caller may override the automatic decision.
bool slotted
options.config.slotted: true asks for the discrete time scale.
std::string timescale
"auto", "discrete" or "continuous".
double slotlength
Slot length in model time units: the lattice unit, never a rescale of a law.
What fj_is_homogeneous.m returns: the fork-join pair, or why there is none.
The options SolverMAM reads.
Definition mam_types.h:30
What qsys_is_retrial.m returns: the station it found, or why it found none.
std::string why
the reference's errorMsg, empty when ok
What the MAM dispatch returns: the metrics plus the algorithm that ran.
Definition mam_types.h:211
std::string actualmethod
The concrete algorithm, as the reference's actualmethod.
Definition mam_types.h:214
mva::MvaSolution< T > sol
Definition mam_types.h:212
Result of the fast path; ok false means the model is not in its regime.