LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
ssa_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_SSA_SSA_DISPATCH_H
6#define LINE_SOLVERS_SSA_SSA_DISPATCH_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * The SolverSSA entry surface: a port of `@@SolverSSA/runAnalyzer.m`'s method
12 * whitelist, of `solver_ssa_analyzer.m`'s eligibility gate (`isNrmEligible` and
13 * the per-feature `*NrmOK` predicates) and of `solver_ssa_analyzer_nrm.m`'s own
14 * scheduling validation.
15 *
16 * EVERY METHOD THE REFERENCE OFFERS IS REACHED FROM HERE. `SolverSSA.m` line 55
17 * lists `default`, `ssa`, `serial`, `para`/`parallel` and `nrm`; the JAR's
18 * `SolverSSA.listValidMethods` and native Python's list the same set. All five
19 * resolve to one of the three ported engines: the NRM of `solver_ssa_nrm.h`,
20 * the event-driven engine of `solver_ssa_serial.h`, and the replica mean of
21 * `solver_ssa_parallel.h`. `para`/`parallel` prefers the NRM whenever the model
22 * is eligible and replicates the serial engine otherwise, exactly as the
23 * reference does; `ssa` is the reference's alias for `serial`, NOT for the NRM;
24 * `default` is the reference's ladder -- the NRM when eligible, the serial
25 * engine otherwise -- as `solver_ssa` sets out below.
26 * `solver_ssa` returns the metric table alone, so a caller who needs the sample
27 * path, the per-replica tables or their standard errors calls the engine's own
28 * entry. The mlmc method uses the dedicated finite-horizon
29 * solver_ssa_get_tran_reward getter; the metric analyzer refuses them.
30 * The tstep method (`ssa_tstep.h`, Wang-Song-Hong WSC 2023) is a fixed-step
31 * approximation of its own: it answers the metric table only, records no
32 * sample path and carries no batch-means CI.
33 *
34 * WITHIN `nrm` THERE ARE TWO ENGINES, and both are reached from here. The
35 * reference picks between them on `options.config.state_space_gen`
36 * (`solver_ssa_analyzer_nrm.m` lines 52-68): `none` and `default` take the
37 * plain engine of `solver_ssa_nrm.m`, which integrates the metrics along the
38 * sample path, and any other value takes the tabulating engine of
39 * `solver_ssa_nrm_space.m`, which records the distinct states visited and forms
40 * the means as `pi * A`. `SsaOptions::state_space_gen` is that switch, and the
41 * eligibility gate below runs before it, exactly as the reference's does: it is
42 * the NRM's gate, not one engine's. The space engine then applies its OWN
43 * further refusals (an open model, a phase-type service, a space above the cap),
44 * each by name, in `NrmSpaceEngine::check`.
45 *
46 * WHY THE GATE IS SO LONG, AND WHAT IT IS FOR. It is `isNrmEligible`
47 * (`solver_ssa_analyzer.m` lines 365-386) and it answers ONE question: can the
48 * NRM run this model? Under `method='nrm'` a no is a refusal BY NAME, because a
49 * caller who spelled out the estimator asked for that estimator; under
50 * `default` and `parallel` the same no is a fallback to the serial engine, as
51 * the reference's is. The two share a body (`raise`), so they cannot drift.
52 *
53 * WHAT THE GATE MEANS SINCE THE FALLBACK WAS RESTORED. It is the NRM's reach and
54 * NOT SolverSSA's: everything it rejects, the serial engine runs (a Fork, a
55 * BLOCKING region rule, global dependence), so a rejection under `default`
56 * costs the caller the NRM's SPEED and not the answer. Under `method='nrm'` it
57 * is still a refusal by name, because an estimator that was asked for by name
58 * must be the one that runs. What the NRM lacks falls in two groups:
59 *
60 * NOT REPRESENTABLE the struct has no field at all, so a model using the
61 * feature cannot be built (SelfLoopingClass --
62 * `JobClassType` is OPEN or CLOSED only). RROBIN, WRROBIN,
63 * JSQ and SQ are NOT here: the NRM resolves all four at
64 * firing time (`resolve_state_dependent_dest`).
65 * REFUSED IN EVERY CODEBASE'S NRM Fork/Join, the blocking region rules
66 * BAS / BBS / RSRD, a true-BAS station (`ssa_check_bas`),
67 * and global (Whittle) dependence; the
68 * reference's `isNrmEligible` excludes the same set.
69 * Reneging, balking and retrial orbits are refused by
70 * `ssa_check_impatience`, and G-network signals
71 * (`issignal` and friends) downstream, by the engines that
72 * would have to simulate them.
73 *
74 * The sub-engines that have LEFT the refusal list, all in `solver_ssa_nrm.h`
75 * unless named: the *PRIO shares on 2026-08-15; the stochastic Petri net path
76 * on 2026-09-13 (`solver_ssa_nrm_spn.h`, which still refuses the four firing
77 * laws `spn_nrm_supported` names); and on 2026-09-24 class- and joint-dependent
78 * scaling (`cdfac`), finite capacity regions under DROP and WAITQ
79 * (`fcr_outcome` / `fcr_release_cascade`), PAS / OI (`pas_rate` /
80 * `pas_depart`), POLLING (`PollCtrl` and one switchover reaction per station)
81 * and the Cache (`cache_fire`, drawing each READ from `after_event_cache`). The
82 * tabulating engine of `solver_ssa_nrm_space.h` does not carry those five and
83 * refuses them itself, by name.
84 *
85 * Nothing falls through silently: a model with a construct the reaction table
86 * does not model would run to completion and return numbers that are simply
87 * not the model's, which is why the gate stays even where the serial engine can
88 * answer.
89 */
90
91#include <algorithm>
92#include <cmath>
93#include <string>
94#include <vector>
95
109#include "line/util/error.h"
112
113namespace line {
114namespace ssa {
115
116namespace detail {
117
118/**
119 * The scheduling whitelist of `solver_ssa_analyzer_nrm.m` lines 15-26,
120 * restricted to what this port's rate laws cover.
121 *
122 * The three priority-weighted shares PSPRIO / DPSPRIO / GPSPRIO joined the
123 * whitelist on 2026-08-15, and PAS / OI and POLLING on 2026-09-24, when their
124 * sub-engines (the pass-and-swap list and the polling controller) were ported.
125 *
126 * `raise` is what makes this both the REFUSAL and the ELIGIBILITY test, as the
127 * reference's single `isNrmEligible` is: `raise=true` names the offending
128 * station and throws, `raise=false` answers false. One body, so the message a
129 * caller of `method='nrm'` reads and the predicate `default` and `parallel`
130 * branch on can never disagree.
131 */
132/**
133 * The polling-extension guard of `solver_ssa_analyzer_nrm.m`: refuses with
134 * LINE:unsupported:<name> when a POLLING station carries a table, a
135 * load-dependent order or a visit timer (`sn_polling_extension`).
136 */
137template <class T>
138bool ssa_check_pollext(const qn::NetworkStruct<T>& sn, bool raise = true) {
139 const std::string pext = api::sn_polling_extension(sn);
140 if (pext.empty()) return true;
141 if (!raise) return false;
142 throw UnsupportedError(ErrorKind{pext},
143 "The NRM method has no form for the " + pext +
144 " polling extension; use options.method='serial'.");
145}
146
147template <class T>
148bool ssa_check_scheduling(const qn::NetworkStruct<T>& sn, bool raise = true) {
150 for (std::size_t i = 0; i < sn.nstations; ++i) {
151 const SchedStrategy s = sn.stations[i].sched;
152 switch (s) {
169 // Pass-and-swap and order-independent: served since 2026-09-24 through
170 // the ordered-list sub-engine (`pas_rate` / `pas_depart`).
173 // Polling: served since 2026-09-24 through the controller sub-engine
174 // (`PollCtrl`, one switchover reaction per polling station).
176 continue;
177 default:
178 if (!raise) return false;
179 throw UnsupportedError(ErrorKind{"SchedStrategy"}, "SolverSSA(method='nrm'): the scheduling policy '" +
180 std::string(lang::sched_to_text(s)) + "' at station '" +
181 sn.stations[i].name +
182 "' is not supported by the NRM in any codebase");
183 }
184 }
185 // A polling table, load-dependent order or visit timer has no reaction
186 // form: the NRM's polling controller is the plain cyclic one. Folded into
187 // the scheduling test, as ssa_nrm_guards.m folds `pollext` into `sched`,
188 // so `default` falls back to the serial engine the same way.
189 return ssa_check_pollext(sn, raise);
190}
191
192/**
193 * Node kinds the NRM reaction grid cannot express in this port.
194 *
195 * A Place and a Transition are NOT among them since 2026-09-13:
196 * `solver_ssa_nrm_spn.h` ports the reference's SPN builder and run loop, so a
197 * net carrying them is routed to that engine instead of refused. What it can
198 * and cannot read is `spn_nrm_supported`, asked separately below, because the
199 * reference asks it separately too -- its four conditions are about the FIRING
200 * LAWS of the net, not about the presence of a node kind.
201 */
202template <class T>
203bool ssa_check_nodes(const qn::NetworkStruct<T>& sn, bool raise = true) {
204 for (const qn::NodeDef& nd : sn.nodes) {
205 switch (nd.nodetype) {
206 // Cache: served since 2026-09-24 through the cache-read reaction
207 // (`NrmEngine::cache_fire`).
208 case qn::NodeType::Fork:
209 case qn::NodeType::Join:
210 if (!raise) return false;
211 throw UnsupportedError(ErrorKind{"Fork"}, "SolverSSA(method='nrm'): node '" + nd.name +
212 "' makes this a fork-join model, which the NRM does not "
213 "handle in any codebase (isNrmEligible excludes it); the "
214 "reference falls back to the serial engine, whose own "
215 "fork handler (sn.fjsync / State.afterFJEvent) is not "
216 "ported either");
217 default:
218 break;
219 }
220 }
221 return true;
222}
223
224/**
225 * Routing strategies this port resolves, plus what the model layer itself
226 * cannot represent.
227 *
228 * RROBIN, WRROBIN, JSQ and SQ are resolved AT FIRING TIME by the NRM engine
229 * (`build_state_dependent_dest` / `resolve_state_dependent_dest`) from the
230 * declared out-arcs and the live population, which is what the reference does
231 * and what makes a round-robin dispatcher a dispatcher rather than a coin.
232 * `refresh_routing` still expands them into a probability split, because a
233 * matrix solver has nothing else to read; the engine ignores that split for
234 * these nodes and walks the arcs itself.
235 *
236 * SDR is the one that stays refused: its routing is a function the struct does
237 * not carry, so there is nothing here to evaluate.
238 */
239template <class T>
240bool ssa_check_routing(const qn::NetworkStruct<T>& sn, bool raise = true) {
241 for (const qn::NodeDef& nd : sn.nodes)
242 for (std::size_t r = 0; r < nd.routing.size(); ++r) {
243 const qn::RoutingStrategy rs = nd.routing[r];
244 if (rs == qn::RoutingStrategy::PROB || rs == qn::RoutingStrategy::RAND ||
245 rs == qn::RoutingStrategy::DISABLED || rs == qn::RoutingStrategy::RROBIN ||
246 rs == qn::RoutingStrategy::WRROBIN || rs == qn::RoutingStrategy::JSQ ||
247 rs == qn::RoutingStrategy::SQ)
248 continue;
249 if (!raise) return false;
250 throw UnsupportedError(ErrorKind{"RoutingStrategy"},
251 "SolverSSA(method='nrm'): node '" + nd.name + "' routes class '" +
252 sn.classes[r].name + "' by '" + std::string(lang::routing_to_text(rs)) +
253 "'. Its destination is a function the C++ NetworkStruct does not carry, so "
254 "there is nothing to resolve at firing time");
255 }
256 return true;
257}
258
259/**
260 * `phaseNrmOK` (solver_ssa_analyzer.m lines 407-...): where a non-exponential
261 * service process may sit.
262 *
263 * The INF / PS family expands exactly, because every job present is in service
264 * and the class share splits across the phases in the ratio kir/nir. The
265 * non-preemptive buffered family expands through the auxiliary in-service
266 * multiset. EXT is deliberately excluded and the reason is worth repeating: a
267 * phase-type ARRIVAL process is not a service law, and expanding it fires one
268 * arrival per PHASE instead of one per RENEWAL, so an Erlang-2 source doubles
269 * lambda. LCFSPR is excluded because preempt-resume would have to remember the
270 * preempted job's phase.
271 */
272template <class T>
273bool ssa_check_phases(const qn::NetworkStruct<T>& sn, bool raise = true) {
275 for (std::size_t i = 0; i < sn.nstations; ++i) {
276 const SchedStrategy s = sn.stations[i].sched;
277 const bool exact = s == SchedStrategy::INF || s == SchedStrategy::PS ||
283 // A MAP/MMPP2 service at FCFS chains its draws through a memory phase (and, with c > 1,
284 // the landing phase of each draw, `ctmc_mapc`), which the in-service multiset has no
285 // column for: the NRM would restart every draw from the entry law.
286 if (s == SchedStrategy::FCFS)
287 for (std::size_t r = 0; r < sn.nclasses; ++r) {
288 if (sn.disabled[i][r]) continue;
289 const lang::ProcessType pt = sn.service[i][r].type;
290 if (pt != lang::ProcessType::MAP && pt != lang::ProcessType::MMPP2) continue;
291 if (!raise) return false;
292 throw UnsupportedError(ErrorKind{"MAP"},
293 "SolverSSA(method='nrm'): class '" + sn.classes[r].name + "' has MAP service "
294 "at FCFS station '" + sn.stations[i].name + "', whose draws are chained "
295 "through a memory phase the NRM does not carry; ask for 'default', which "
296 "falls back to the serial engine");
297 }
298 if (exact) continue;
299 for (std::size_t r = 0; r < sn.nclasses; ++r) {
300 if (sn.disabled[i][r]) continue;
301 const lang::ProcessType pt = sn.service[i][r].type;
304 continue;
305 if (!raise) return false;
306 throw UnsupportedError(ErrorKind{"NonExponential"},
307 "SolverSSA(method='nrm'): class '" + sn.classes[r].name + "' has non-exponential "
308 "service at station '" + sn.stations[i].name + "', whose '" +
309 std::string(lang::sched_to_text(s)) +
310 "' discipline the NRM phase expansion does not cover; ask for 'default', which "
311 "falls back to the serial engine as the reference does");
312 }
313 }
314 return true;
315}
316
317/**
318 * Global (Whittle) dependence, refused because the NRM does not SCALE by it.
319 *
320 * Class- and joint-dependent scaling are served since 2026-09-24: `cdfac` in
321 * `solver_ssa_nrm.h` evaluates eta_i(n) .* beta_{i,r}(n) on the station's
322 * per-class population at firing time, as the reference does, and utilization
323 * is normalized by the declared peaks. The reference's gate (`ssa_nrm_guards.gd`)
324 * excludes only the global handle, and so does this one.
325 */
326template <class T>
327bool ssa_check_cdscaling(const qn::NetworkStruct<T>& sn, bool raise = true) {
328 // The NRM's propensities receive the per-station population slice, not the
329 // whole population matrix a global handle reads.
330 if (sn.gdscaling) {
331 if (!raise) return false;
332 throw UnsupportedError(ErrorKind{"GlobalDependence"},
333 "SolverSSA(method='nrm'): the model declares a global dependence "
334 "(setGlobalDependence). The NRM builds its propensities from the per-station "
335 "population slice and never sees the whole population matrix the handle reads, so "
336 "the sample path would run at the unscaled rates; ask for method='serial', which "
337 "applies it");
338 }
339 return true;
340}
341
342/**
343 * Finite capacity regions: served since 2026-09-24, under DROP and WAITQ.
344 *
345 * `solver_ssa_nrm.h` ports `fcrPrecompute` / `fcrRefusingRegion` /
346 * `fcrReleaseCascade`: an admission gate on every arrival into a region and a
347 * head-of-line release cascade from a per-region FIFO after every firing. What
348 * stays refused is a BLOCKING region rule (BAS, BBS, RSRD), which no codebase's
349 * NRM carries.
350 */
351template <class T>
352bool ssa_check_regions(const qn::NetworkStruct<T>& sn, bool raise = true) {
353 for (const typename qn::NetworkStruct<T>::Region& rg : sn.regions)
354 for (std::size_t r = 0; r < rg.rule.size(); ++r) {
355 const qn::DropStrategy d = rg.rule[r];
356 if (d != qn::DropStrategy::BAS && d != qn::DropStrategy::BBS &&
357 d != qn::DropStrategy::RSRD)
358 continue;
359 if (!raise) return false;
360 throw UnsupportedError(ErrorKind{"Region"},
361 "SolverSSA(method='nrm'): finite capacity region '" + rg.name +
362 "' declares a blocking rule for class '" + sn.classes[r].name +
363 "'. The NRM region gate implements DROP and WAITQ only, as the reference's does");
364 }
365 return true;
366}
367
368/**
369 * True Blocking-After-Service, `ssa_nrm_guards.bas`: refused by the NRM in every codebase.
370 *
371 * A completion at a BAS station whose destination is full is HELD: the job stays
372 * on the server, counted in the station's held-job block (`sn.isbasblocking`, one
373 * counter per target code, BUG-110), and transfers once room frees. The NRM's
374 * reactions see per-class counts only, so it cannot hold a completed job, and on
375 * the BUG-110 model it lets the upstream Delay keep serving: X Tput 1.218 against
376 * the exact 0.834. `default` and `parallel` therefore take the serial engine,
377 * which carries the block. An explicit `nrm` is refused by name, because this
378 * port's NRM has no fallback arm for it.
379 */
380template <class T>
381bool ssa_check_bas(const qn::NetworkStruct<T>& sn, bool raise = true) {
382 for (std::size_t ind = 0; ind < sn.isbasblocking.size(); ++ind) {
383 if (!sn.isbasblocking[ind]) continue;
384 if (!raise) return false;
385 throw UnsupportedError(ErrorKind{"BAS"},
386 "SolverSSA(method='nrm'): node '" + sn.nodes[ind].name + "' blocks after service "
387 "(BAS). The NRM has no held-job counter for a completed job waiting for room "
388 "downstream; use method='serial'");
389 }
390 return true;
391}
392
393/**
394 * Synchronous calls (REPLY signals), `ssa_nrm_guards.reply`: refused by the NRM in every codebase.
395 *
396 * A calling job leaves its caller and keeps the server there until the reply returns. The
397 * serial engine carries that hold in the reply block of the local row (`after_event`), while
398 * the NRM's reactions see per-class counts only and have no held-server counter, so the caller
399 * would free its server at once. `default` and `parallel` therefore take the serial engine,
400 * and an explicit `nrm` falls back to it with a warning, as the reference does.
401 */
402template <class T>
403bool ssa_check_reply(const qn::NetworkStruct<T>& sn, bool raise = true) {
404 for (std::size_t ind = 0; ind < sn.replyblock.size(); ++ind)
405 for (std::size_t k = 0; k < sn.replyblock[ind].size(); ++k) {
406 if (!sn.replyblock[ind][k]) continue;
407 if (!raise) return false;
408 throw UnsupportedError(ErrorKind{"SyncCall"},
409 "SolverSSA(method='nrm'): class '" + sn.classes[k].name + "' makes a synchronous "
410 "call (REPLY signal) from node '" + sn.nodes[ind].name + "'. The NRM has no "
411 "held-server counter for a pending reply; use method='serial'");
412 }
413 return true;
414}
415
416/**
417 * Reneging, balking and retrial orbits: refused by the NRM, whose reactions are per-class
418 * service completions and arrivals with no abandonment, balking or retry channel, so the
419 * model would be answered without them. The serial engine fires all three through
420 * `after_event`, which is where `default` and `parallel` send such a model.
421 */
422template <class T>
423bool ssa_check_impatience(const qn::NetworkStruct<T>& sn, bool raise = true) {
424 // A law the serial engine refuses too is reported as such, not as a pointer to 'serial'.
425 const std::string both = qn::state_impatience_unsupported(sn, "SolverSSA");
426 if (!both.empty()) {
427 if (!raise) return false;
428 throw UnsupportedError(ErrorKind{"Impatience"}, both);
429 }
430 for (std::size_t i = 0; i < sn.stations.size(); ++i) {
431 const qn::Station<T>& st = sn.stations[i];
432 bool any = qn::station_has_reneging(sn, i + 1);
433 for (std::size_t r = 0; r < st.balking.size(); ++r)
434 any = any || st.balking[r].strategy != lang::BalkingStrategy::NONE;
435 const auto rit = sn.retrialparam.find(i + 1);
436 if (rit != sn.retrialparam.end())
437 for (std::size_t r = 0; r < rit->second.retrial_proc.size(); ++r)
438 any = any || !rit->second.retrial_proc[r].disabled;
439 if (!any) continue;
440 if (!raise) return false;
441 throw UnsupportedError(ErrorKind{"Impatience"},
442 "SolverSSA(method='nrm'): station '" + st.name + "' declares reneging, balking or a "
443 "retrial orbit. The NRM has no reaction for any of them; use method='serial'");
444 }
445 return true;
446}
447
448/**
449 * `isNrmEligible` (`solver_ssa_analyzer.m` lines 365-386): can the NRM run this
450 * model at all?
451 *
452 * It is the SAME tests the refusal above takes, asked with `raise=false`,
453 * so the predicate cannot drift from the message. It is deliberately the C++
454 * NRM's reach and not the reference's: this port's NRM covers less, and a
455 * `default` that consulted MATLAB's wider predicate would send a model to a
456 * refusal the serial engine can actually answer.
457 */
458template <class T>
459bool ssa_nrm_eligible(const qn::NetworkStruct<T>& sn) {
460 // Immediate feedback keeps the fed-back job on the server it just used, which
461 // the serial engine expresses through `after_event`'s `no_promote` arc. The
462 // NRM has no such arc: its reactions see per-class counts, not which job holds
463 // the server, so a self-loop there is a class switch with re-queueing. An
464 // explicit `method='nrm'` still RUNS the model with that approximation,
465 // warning in as many words (`ssa_nrm_supports`, the GATE, deliberately does
466 // not test this); this only keeps `default` and `parallel` from PREFERRING an
467 // approximation over the exact serial engine.
468 if (sn.has_immediate_feedback()) return false;
469 return ssa_check_nodes(sn, false) && ssa_check_scheduling(sn, false) &&
470 ssa_check_routing(sn, false) && ssa_check_phases(sn, false) &&
471 ssa_check_cdscaling(sn, false) && ssa_check_regions(sn, false) &&
472 ssa_check_bas(sn, false) && ssa_check_reply(sn, false) && ssa_check_impatience(sn, false) &&
473 spn_nrm_supported(sn, false);
474}
475
476/**
477 * The same tests as a SENTENCE, so a report can say why `nrm` is withheld.
478 *
479 * `ssa_nrm_eligible` above answers the dispatch's question (may I PREFER the
480 * NRM?) and nothing answered the gate's (may I OFFER it?), so `ssa.nrm` was
481 * reported runnable on every model and an explicit request then raised. The
482 * catch is the ADAPTER between those two callers and not error suppression: the
483 * checks already carry the exact wording a user should see, and re-deriving it
484 * here is how the message and the predicate drift apart.
485 */
486template <class T>
487std::string ssa_nrm_supports(const qn::NetworkStruct<T>& sn) {
488 try {
489 ssa_check_nodes(sn, true);
490 ssa_check_scheduling(sn, true);
491 ssa_check_routing(sn, true);
492 ssa_check_phases(sn, true);
493 ssa_check_cdscaling(sn, true);
494 ssa_check_regions(sn, true);
495 ssa_check_bas(sn, true);
496 ssa_check_reply(sn, true);
497 ssa_check_impatience(sn, true);
498 spn_nrm_supported(sn, true);
499 } catch (const UnsupportedError& e) {
500 return e.what();
501 }
502 return "";
503}
504
505/**
506 * The tabulating engine's knobs from the caller's.
507 *
508 * `state_max` keeps its own default because `SsaOptions` carries no cap: a
509 * caller who wants a different one calls `solver_ssa_nrm_space_analyzer`
510 * directly, which is also where the tabulated path and the propensity table
511 * survive rather than being reduced to the metrics.
512 */
513inline SsaNrmSpaceOptions ssa_space_options(const SsaOptions& o) {
514 SsaNrmSpaceOptions s;
515 static_cast<SsaOptions&>(s) = o;
516 return s;
517}
518
519/**
520 * The serial and replicated engines' knobs from the caller's.
521 *
522 * `state_max`, `nreplicas` and `eventcache` keep their
523 * own defaults for the same reason `state_max` does above: `SsaOptions` has no
524 * field for them, and `nreplicas = 8` is `SolverOptions('SSA')`'s own default
525 * rather than a number chosen here. A caller who wants a different R calls
526 * `solver_ssa_parallel` directly, which is also where the R per-replica tables
527 * and their standard errors survive rather than being reduced to the mean.
528 */
529inline SsaSerialOptions ssa_serial_options(const SsaOptions& o) {
530 SsaSerialOptions s;
531 static_cast<SsaOptions&>(s) = o;
532 return s;
533}
534
535inline SsaParallelOptions ssa_parallel_options(const SsaOptions& o) {
536 SsaParallelOptions p;
537 static_cast<SsaOptions&>(p) = o;
538 return p;
539}
540
541/**
542 * One serial run, keeping the cache write-back the metric table does not carry.
543 *
544 * Written once because `solver_ssa` reaches the serial engine from two arms
545 * (the `default` fallback and the named method), and a caller that got its
546 * cache shares from one arm and not the other would report the offered split
547 * for the same model under a different spelling of the same request.
548 */
549template <class T>
550SsaSolution ssa_serial_avg(const qn::NetworkStruct<T>& sn, const SsaOptions& opt,
551 std::vector<SsaCacheRatio>* cache) {
552 SsaSerialSolution<T> s = solver_ssa_serial_analyzer(sn, ssa_serial_options(opt));
553 if (cache) *cache = s.cache;
554 return s.avg;
555}
556
557/**
558 * `@@SolverSSA/runAnalyzer.m:227`: a Place counts TOKENS, an engine counts
559 * FIRING EVENTS, and the two are the same number only where every arc has
560 * multiplicity one and no immediate transition moves the tokens.
561 *
562 * WHAT THE ENGINES HAND OVER. Every SPN engine accumulates a Place's
563 * throughput as the summed propensity of the TIMED modes consuming from it, so
564 * an arc of weight 2 counts one departure where two tokens left, and an
565 * IMMEDIATE consumer counts none at all -- a firing that takes zero time is not
566 * a timed event and no engine, here or in the reference, ever sees it as one.
567 * A Place drained only by an immediate transition therefore arrives here with
568 * TN = 0, which then makes RespT 0 and leaves the neighbouring Place's ArvR 0
569 * once the caller derives it from this table.
570 *
571 * `sn_pn_avg_rates` is the reference's repair and recovers the missing rates
572 * from the flow-balance equations, which is why it runs at the SOLVER level and
573 * on the ORIGINAL struct: both engines fold a fork-join tagging back before
574 * returning, so the table is already in the caller's own coordinates here, as
575 * it is after `solver_tr_fjtag_analyzer`'s lift in the reference. A model with
576 * no Place, or one whose firing rates cannot be recovered, is returned
577 * untouched.
578 *
579 * AN IS LEFT TO THE CALLER, exactly as `[TN,~,RN] = sn_pn_avg_rates(...)` leaves
580 * it in the reference: `SsaSolution` carries no arrival-rate table, and every
581 * consumer derives one with `sn_get_arvr_from_tput` from the TN repaired here.
582 */
583template <class T>
584SsaSolution ssa_pn_token_rates(const qn::NetworkStruct<T>& sn, const SsaSolution& in) {
585 bool has_place = false;
586 for (std::size_t a = 0; a < sn.nodes.size() && !has_place; ++a)
587 if (sn.nodes[a].nodetype == qn::NodeType::Place) has_place = true;
588 if (!has_place || in.TN.rows() == 0) return in;
589
590 const std::size_t M = in.TN.rows(), K = in.TN.cols();
591 Matrix<T> QN(M, K), TN(M, K), RN(M, K);
592 for (std::size_t i = 0; i < M; ++i)
593 for (std::size_t k = 0; k < K; ++k) {
594 QN(i, k) = num_traits<T>::from_double(in.QN(i, k));
595 TN(i, k) = num_traits<T>::from_double(in.TN(i, k));
596 RN(i, k) = num_traits<T>::from_double(in.RN(i, k));
597 }
598 const api::SnPnAvgRates<T> pn = api::sn_pn_avg_rates(sn, QN, TN, Matrix<T>(), RN);
599
600 SsaSolution out = in;
601 for (std::size_t i = 0; i < M; ++i)
602 for (std::size_t k = 0; k < K; ++k) {
603 out.TN(i, k) = num_traits<T>::to_double(pn.TN(i, k));
604 out.RN(i, k) = num_traits<T>::to_double(pn.RN(i, k));
605 }
606 return out;
607}
608
609} // namespace detail
610
611/**
612 * Port of `SolverSSA.listValidMethods`.
613 *
614 * Six names for three engines, because the reference spells the same engine
615 * more than one way: 'ssa' and 'serial' are the serial trajectory, 'para' and
616 * 'parallel' the replicated one, 'nrm' the next-reaction method, and 'default'
617 * is the ladder `solver_ssa` walks -- the NRM when it can run the model and the
618 * serial engine when it cannot. The reward method mlmc is
619 * dispatched by solver_ssa_get_tran_reward; solver_ssa below refuses them.
620 * The time-stepped approximation tstep is dispatched by solver_ssa_engine.
621 */
622inline std::vector<std::string> list_valid_methods() {
623 // the names and their order are this solver's row of the method registry (doc/line-methods.json)
624 return ::line::method_registry::methods("SSA");
625}
626
627/**
628 * `solver_ssa_analyzer_nrm.m`: run the NRM and return the metric table.
629 *
630 * The reference's post-processing (`QN(isnan(QN)) = 0` and the rest) is inside
631 * the engine already: it never produces a NaN, because every division is
632 * guarded at the point it is taken.
633 */
634template <class T>
636 std::vector<SsaCacheRatio>* cache = nullptr) {
637 // `if constexpr`, not a run-time test: the engine reaches `dist_to_map`,
638 // whose APH fit static_asserts on transcendental arithmetic, so a Rational
639 // instantiation would fail to COMPILE rather than refuse. The gate has to
640 // keep the body from being instantiated at all.
641 if constexpr (!std::is_same<T, double>::value) {
642 (void)sn;
643 (void)opt;
644 (void)cache;
645 throw UnsupportedError(ErrorKind{"Arithmetic"},
646 "solver_ssa_nrm: an SSA sample path is generated from exponential clocks, which are "
647 "logarithms of uniform draws; there is no exact value to compute and a wider float "
648 "carries no information the Monte Carlo error does not swamp. Rerun with --arith "
649 "double");
650 } else {
651 detail::ssa_check_nodes(sn);
652 detail::ssa_check_scheduling(sn);
653 detail::ssa_check_routing(sn);
654 detail::ssa_check_phases(sn);
655 detail::ssa_check_cdscaling(sn);
656 detail::ssa_check_regions(sn);
657 detail::ssa_check_bas(sn);
658 detail::ssa_check_reply(sn);
659 detail::ssa_check_impatience(sn);
660 detail::spn_nrm_supported(sn);
661 // `solver_ssa_nrm.m:174`: a net carrying a Transition is a STOCHASTIC
662 // PETRI NET and goes to the SPN builder and run loop, which reads a
663 // marking of tokens rather than a grid of jobs in service. The branch is
664 // taken before the space/plain switch below because the tabulating
665 // engine tabulates the queueing state vector, which an SPN does not
666 // have; the reference branches at the same point and for the same
667 // reason.
668 for (const qn::NodeDef& nd : sn.nodes)
669 if (nd.nodetype == qn::NodeType::Transition) {
671 return spn.run();
672 }
673 // The reference's engine switch, taken AFTER the gate above because the
674 // gate is the NRM's and not one engine's.
675 if (opt.state_space_gen != "none" && opt.state_space_gen != "default")
676 return solver_ssa_nrm_space_analyzer(sn, detail::ssa_space_options(opt)).avg;
677 NrmEngine<T> eng(sn, opt);
678 SsaSolution out = eng.run();
679 if (cache) *cache = eng.cache();
680 return out;
681 }
682}
683
684/**
685 * `solver_ssa_analyzer.m`: choose the method.
686 *
687 * The ladder is the reference's, in its order:
688 *
689 * `default` the NRM when it is eligible, ELSE the serial engine, and only a
690 * model neither engine runs is refused -- by the NRM's message,
691 * which names the missing sub-engine.
692 * `nrm` the NRM alone, reached by naming the estimator: a model it
693 * cannot run is refused rather than silently answered by the
694 * other engine, because a caller who spelled out an estimator
695 * asked for that estimator's variance as well as its mean.
696 * `ssa` the reference's alias for `serial` (line 128), not for the NRM.
697 * `serial` one run of the event-driven engine.
698 * `para` the NRM when eligible (the reference prefers one fast run over
699 * `parallel` R replicated ones, lines 143-157), else the replica mean of
700 * `nreplicas` independent serial runs.
701 *
702 * `default`'s FALLBACK IS THE REFERENCE'S (lines 66-78) and was restored on
703 * 2026-07-31, when the serial engine gained fork-join and the finite capacity
704 * regions. It had been held back while the serial engine covered less than the
705 * NRM gate rejects, on the ground that a second failure further downstream is
706 * less informative than the NRM's own message. That ground is gone for every
707 * construct the serial engine now runs, and where it still holds -- a model
708 * NEITHER engine covers -- the NRM's message is what the caller reads, because
709 * `serial_can_run` is asked BEFORE the fallback is taken rather than after it
710 * has failed.
711 *
712 * `cache`, when given, receives the serial engine's cache write-back -- the
713 * realized hit and miss shares of every Cache node, which are a SOLVER RESULT
714 * and the only thing that tells a node table apart from the 1/2-1/2 `link()`
715 * offers. It is an out-parameter rather than a field of `SsaSolution` because
716 * that struct is the metric table the three engines share, and only two of them
717 * have a cache to report, the serial engine and (since 2026-09-24) the NRM; the
718 * parallel engine averages replicas that carry none.
719 */
720template <class T>
722 std::vector<SsaCacheRatio>* cache) {
723 // Resolve the warmup discard once, so every engine below (NRM, its SPN and
724 // tabulating variants, serial, replicated) reads the same fraction, as
725 // `solver_ssa_analyzer.m` does. `SsaOptions` carries no timespan: every run
726 // reaching here is a steady-state one.
727 SsaOptions opt = opt_in;
728 opt.warmupfrac = ssa_resolve_warmupfrac(sn, opt_in.warmupfrac);
729 // A FLUID PETRI NET HAS ONE ENGINE, the NRM Petri runner (`ssa_fluid_refusal`), so it is sent there under
730 // every method that can reach it and refused by name under the rest, before any arm below can pick the
731 // serial engine.
732 if (sn.has_fluid_places()) {
733 const api::SnFluidVerdict fv = detail::ssa_fluid_refusal(sn, opt.method);
734 if (!fv.ok) throw UnsupportedError(ErrorKind{"Structure"}, fv.reason);
735 opt.method = "nrm";
737 }
738 // A fed-back job keeps its server, which the reference encodes in
739 // `State.afterEvent`'s immfeed self-loop, and only the SERIAL engine has that
740 // arc -- here as in the reference. `solver_ssa_analyzer_nrm.m:29` warns in as
741 // many words that the NRM "does not model immediate feedback (immfeed);
742 // self-loops are treated as class-switching with re-queueing" and then runs,
743 // so the name stays offerable and only the approximation is announced.
744 // `ssa_nrm_eligible` excludes immediate feedback, so `default` and `parallel`
745 // reach the exact serial engine and only an EXPLICIT `nrm` warns.
746 if (sn.has_immediate_feedback()) {
747 const std::string& mm = opt.method;
748 const bool runs_nrm =
749 mm == "nrm" || ((mm == "default" || mm == "para" || mm == "pana" || mm == "parallel") &&
750 detail::ssa_nrm_eligible(sn));
751 if (runs_nrm)
752 std::cerr << "[LINE] Warning: SolverSSA(method=nrm) does not model immediate feedback "
753 "(immfeed); self-loops are treated as class-switching with re-queueing. "
754 "Use method='serial' for immediate feedback."
755 << std::endl;
756 }
757 const std::string& m = opt.method;
759 // `solver_ssa_analyzer.m`'s 'tstep' arm: its own engine, no sample path, no batch-means CI; the
760 // Immediate-station balance `solver_ssa` applies afterwards is the reference's, too.
761 if constexpr (!std::is_same<T, double>::value) {
762 throw UnsupportedError(ErrorKind{"Arithmetic"},
763 "SolverSSA(method='tstep') draws binomial and Poisson variates; rerun with --arith double");
764 } else {
766 }
767 }
768 if (m == "default") {
769 // The reference's ladder: the NRM when it can run the model, the serial
770 // engine when it cannot, and the NRM's own refusal -- which names the
771 // sub-engine that is missing -- when neither can. Asking
772 // `serial_can_run` first is what keeps that message: falling through to
773 // the serial engine and letting IT fail would report whichever guard it
774 // hit, about a model the caller never asked it to run.
775 if (detail::ssa_nrm_eligible(sn)) return solver_ssa_nrm_analyzer(sn, opt, cache);
776 if (serial_detail::serial_can_run(sn))
777 return detail::ssa_serial_avg(sn, opt, cache);
778 return solver_ssa_nrm_analyzer(sn, opt, cache); // raises, by name
779 }
780 if (m == "nrm") {
781 // `solver_ssa_analyzer.m`'s explicit 'nrm' arm: a synchronous call falls back to the
782 // serial engine with a warning rather than refusing, in every codebase.
783 if (!detail::ssa_check_reply(sn, false)) {
784 std::cerr << "[LINE] Warning: SolverSSA: NRM does not support synchronous calls "
785 "(REPLY signals); falling back to the serial method."
786 << std::endl;
787 return detail::ssa_serial_avg(sn, opt, cache);
788 }
790 }
791 if (m == "ssa" || m == "serial") return detail::ssa_serial_avg(sn, opt, cache);
792 if (m == "para" || m == "pana" || m == "parallel") {
793 // The reference's own preference, `solver_ssa_analyzer.m` lines 143-157:
794 // an NRM-eligible model runs once on the NRM rather than R times here.
795 if (detail::ssa_nrm_eligible(sn)) return solver_ssa_nrm_analyzer(sn, opt, cache);
796 return solver_ssa_parallel_analyzer(sn, detail::ssa_parallel_options(opt)).avg;
797 }
798 throw UnsupportedError(ErrorKind{"Method"}, "SolverSSA: '" + m +
799 "' is not a valid method; the reference offers 'default', 'ssa', "
800 "'serial', 'para', 'parallel', 'nrm' and 'tstep', all of which this "
801 "port implements");
802}
803
804/**
805 * `@@SolverSSA/runAnalyzer` itself: the engine the method selects, then the
806 * result assembly the reference does before it hands the table to a caller.
807 *
808 * Only one step of that assembly belongs here rather than to the caller. A
809 * Place is measured in TOKENS and every engine counts FIRING EVENTS, so
810 * `ssa_pn_token_rates` rewrites the Place rows of TN and RN exactly where
811 * `runAnalyzer.m:227` does; the arrival rates and residence times each consumer
812 * still derives for itself, as before. A model with no Place is untouched, so
813 * this costs an ordinary queueing network one scan of the node list.
814 */
815template <class T>
817 const std::vector<SsaCacheRatio>& cache);
818template <class T>
819SsaSolution ssa_imm_tput_balance(const qn::NetworkStruct<T>& sn, const SsaSolution& in);
820
821template <class T>
823 std::vector<SsaCacheRatio>* cache = nullptr) {
824 if(opt.method=="mlmc")
825 throw UnsupportedError(ErrorKind{"Analysis"}, "SSA MLMC estimates finite-horizon rewards; use solver_ssa_get_tran_reward");
826 // The Immediate-station balance needs the measured cache split even when the caller does not ask for it.
827 std::vector<SsaCacheRatio> local;
828 std::vector<SsaCacheRatio>* cr = cache ? cache : &local;
829 // `solver_ssa_analyzer.m:25`: a non-Markovian law (Gamma, Lognormal,
830 // Weibull, LogLogistic, MassAtOrigin, ...) is replaced by a fitted
831 // phase-type before the path is drawn, and a GENUINE one (`phfit = 'ph'`),
832 // since the sample path walks the phases. Without it the engine read the
833 // refresh-time placeholder, which above SCV 1 is an exponential of the same
834 // mean: M/Lognormal/1 at SCV 5/3 came out as M/M/1 (1.296 against 1.527).
835 if constexpr (std::is_same<T, double>::value) {
836 if (api::sn_has_nonmarkov(sn, false)) {
837 qn::NetworkStruct<T> converted = sn;
840 api::sn_nonmarkov_toph(converted, no);
841 const SsaSolution raw = solver_ssa_engine(converted, opt, cr);
842 return detail::ssa_pn_token_rates(
843 converted, ssa_imm_tput_balance(sn_with_ssa_cache_split<T>(converted, *cr), raw));
844 }
845 }
846 const SsaSolution raw = solver_ssa_engine(sn, opt, cr);
847 // solver_ssa_analyzer.m / solver_ssa_analyzer_nrm.m apply ssa_imm_tput_balance before runAnalyzer's token rates.
848 return detail::ssa_pn_token_rates(sn, ssa_imm_tput_balance(sn_with_ssa_cache_split<T>(sn, *cr), raw));
849}
850
851/**
852 * `CacheMetrics` from the serial engine's cache write-back.
853 *
854 * The shares are matched to their Cache node BY INDEX, not by position: the
855 * base struct walks every Cache the model declares while the engine reports
856 * only the nodes it simulated, so pairing the two off in order would write one
857 * cache's measurement onto another on any model holding more than one.
858 *
859 * `residt` becomes `latency` unchanged, NaN included. The reference warns that
860 * retrieval latency is not implemented and reports NaN in every codebase, so
861 * carrying the NaN IS parity; dropping the field would report "not computed"
862 * about a quantity the engine did state.
863 */
864template <class T>
866 const std::vector<SsaCacheRatio>& cache) {
868 sn, std::vector<T>(), std::vector<T>(), std::vector<T>(), std::vector<T>(), Matrix<T>(),
869 Matrix<T>(), std::vector<T>());
870 for (std::size_t c = 0; c < out.caches.size(); ++c) {
871 for (std::size_t j = 0; j < cache.size(); ++j) {
872 if (cache[j].node != out.caches[c].node) continue;
874 m.hitprob.clear();
875 m.missprob.clear();
876 m.delayedprob.clear();
877 m.latency.clear();
878 for (std::size_t r = 0; r < cache[j].hitprob.size(); ++r)
879 m.hitprob.push_back(num_traits<T>::from_double(cache[j].hitprob[r]));
880 for (std::size_t r = 0; r < cache[j].missprob.size(); ++r)
881 m.missprob.push_back(num_traits<T>::from_double(cache[j].missprob[r]));
882 for (std::size_t r = 0; r < cache[j].delayedprob.size(); ++r)
883 m.delayedprob.push_back(num_traits<T>::from_double(cache[j].delayedprob[r]));
884 for (std::size_t r = 0; r < cache[j].residt.size(); ++r)
885 m.latency.push_back(num_traits<T>::from_double(cache[j].residt[r]));
886 break;
887 }
888 }
889 return out;
890}
891
892/**
893 * The struct with the cache split the SIMULATION MEASURED, visits rebuilt.
894 *
895 * A cache splits the read stream into a hit stream and a miss stream, and that
896 * split IS routing: the visit ratios of everything downstream depend on it. The
897 * base struct carries only what `link()` offered, an even share over the hit and
898 * miss classes, because the split is a RESULT and cannot be known before the
899 * solve. Anything derived from visits after the solve therefore has to be taken
900 * on the rewritten struct, not on the base one -- `sn_get_residt_from_respt`
901 * reported ResidT = RespT/2 for both classes of tut06_cache_lru_zipf (0.1 and
902 * 0.5 against the reference's 0.16475 and 0.17625), which is the even split
903 * showing through, not a residence time.
904 *
905 * The rewrite is the one `da_cacheqn` performs between passes, with the measured
906 * shares in place of the analytical ones: the cache row of `rtnodes` is cleared
907 * and the hit and miss mass sent to every connected successor, after which
908 * `da_recompute_visits_from_rtnodes` rebuilds `visits` and `nodevisits`. A share
909 * the engine left undefined (NaN, a class that does not read this cache) leaves
910 * that row alone rather than zeroing a routing the model does have.
911 */
912template <class T>
914 const std::vector<SsaCacheRatio>& cache) {
915 if (cache.empty()) return base;
917 const std::size_t I = sn.nodes.size(), K = sn.nclasses;
918 if (I == 0 || K == 0 || sn.rtnodes.rows() < I * K) return base;
919 const T zero = num_traits<T>::from_int(0);
920 // The connectivity is read BEFORE any row is rewritten, as in `da_cacheqn`:
921 // a cache's own read self-switch is not a downstream node.
922 std::vector<std::vector<bool> > conn(I, std::vector<bool>(I, false));
923 for (std::size_t a = 0; a < I; ++a)
924 for (std::size_t b = 0; b < I; ++b) {
925 if (a == b) continue;
926 for (std::size_t r = 0; r < K && !conn[a][b]; ++r)
927 for (std::size_t s = 0; s < K && !conn[a][b]; ++s)
928 if (sn.rtnodes(a * K + r, b * K + s) > zero) conn[a][b] = true;
929 }
930 bool rewrote = false;
931 for (std::size_t j = 0; j < cache.size(); ++j) {
932 const std::size_t ind = cache[j].node; // 1-based node index
933 if (ind == 0 || ind > I) continue;
934 typename std::map<std::size_t, qn::CacheParam<T> >::const_iterator ci =
935 sn.nodeparam.find(ind);
936 if (ci == sn.nodeparam.end()) continue;
937 const std::size_t nd = ind - 1;
938 for (std::size_t r = 0; r < K; ++r) {
939 if (ci->second.hitclass.size() <= r || ci->second.missclass.size() <= r) continue;
940 const std::size_t hc = ci->second.hitclass[r], mc = ci->second.missclass[r];
941 if (hc == 0 || mc == 0 || hc > K || mc > K) continue;
942 if (cache[j].hitprob.size() <= r || cache[j].missprob.size() <= r) continue;
943 const double hp = cache[j].hitprob[r], mp = cache[j].missprob[r];
944 if (!(hp == hp) || !(mp == mp)) continue; // NaN: the engine measured none
945 for (std::size_t col = 0; col < I * K; ++col) sn.rtnodes(nd * K + r, col) = zero;
946 for (std::size_t jnd = 0; jnd < I; ++jnd) {
947 if (!conn[nd][jnd]) continue;
948 sn.rtnodes(nd * K + r, jnd * K + (hc - 1)) = num_traits<T>::from_double(hp);
949 sn.rtnodes(nd * K + r, jnd * K + (mc - 1)) = num_traits<T>::from_double(mp);
950 }
951 rewrote = true;
952 }
953 }
954 if (!rewrote) return base;
955 sn.da_recompute_visits_from_rtnodes();
956 return sn;
957}
958
959/**
960 * Port of `ssa_imm_tput_balance.m`: the throughput of every station-class pair
961 * whose service is Immediate, taken from flow balance rather than from the
962 * sample path.
963 *
964 * Such a station holds a job for zero time, so its departure rate IS its
965 * arrival rate in every sample path. Every engine here estimates TN as the time
966 * integral of the departure rate, which at an Immediate station integrates the
967 * encoding rate `GlobalConstants::Immediate` over ~1e-8 sojourns: each visit
968 * contributes rate*dt ~ Exp(1) instead of one departure, a unit-variance number
969 * uncorrelated with the timed flows that fix the rate. On tut06_cache_lru_zipf
970 * that left Client Tput 2.71334 against the ArvR 2.86586 its feeders imply.
971 *
972 * TN there is replaced by the arrival rate of `sn_get_arvr_from_tput`, the same
973 * flow balance that reports the ArvR column, taken on the struct carrying the
974 * MEASURED cache split (`sn_with_ssa_cache_split`), and swept until a chain of
975 * Immediate stations settles (at most nstations sweeps, to FineTol). Sources
976 * are excluded, timed stations are untouched, and XN = TN(refstat),
977 * RN = QN/TN at the replaced pairs and CN = N/XN follow. Skipped under JSQ/SQ
978 * routing, whose split is state dependent and absent from `rt`.
979 */
980template <class T>
982 const std::size_t M = sn.nstations, R = sn.nclasses;
983 if (in.TN.rows() != M || in.TN.cols() != R) return in;
984 std::vector<std::vector<bool> > imm(M, std::vector<bool>(R, false));
985 bool any_imm = false;
986 for (std::size_t ist = 0; ist < M; ++ist) {
987 if (sn.stations[ist].nodetype == qn::NodeType::Source) continue;
988 for (std::size_t r = 0; r < R; ++r)
989 if (sn.service[ist][r].type == lang::ProcessType::IMMEDIATE) imm[ist][r] = any_imm = true;
990 }
991 if (!any_imm) return in;
992 for (const qn::NodeDef& nd : sn.nodes)
993 for (std::size_t r = 0; r < nd.routing.size(); ++r)
994 if (nd.routing[r] == qn::RoutingStrategy::JSQ || nd.routing[r] == qn::RoutingStrategy::SQ) return in;
995
996 SsaSolution out = in;
997 Matrix<T> TN(M, R);
998 for (std::size_t i = 0; i < M; ++i)
999 for (std::size_t r = 0; r < R; ++r) TN(i, r) = num_traits<T>::from_double(in.TN(i, r));
1000 for (std::size_t sweep = 0; sweep < M; ++sweep) {
1001 const Matrix<T> AN = mva::sn_get_arvr_from_tput(sn, TN, TN);
1002 if (AN.rows() != M || AN.cols() != R) break;
1003 double gap = 0.0;
1004 for (std::size_t i = 0; i < M; ++i)
1005 for (std::size_t r = 0; r < R; ++r)
1006 if (imm[i][r])
1007 gap = std::max(gap, std::fabs(num_traits<T>::to_double(AN(i, r)) -
1008 num_traits<T>::to_double(TN(i, r))));
1009 if (gap <= lang::GlobalConstants::FineTol) break;
1010 for (std::size_t i = 0; i < M; ++i)
1011 for (std::size_t r = 0; r < R; ++r)
1012 if (imm[i][r]) TN(i, r) = AN(i, r);
1013 }
1014 for (std::size_t i = 0; i < M; ++i)
1015 for (std::size_t r = 0; r < R; ++r) out.TN(i, r) = num_traits<T>::to_double(TN(i, r));
1016 for (std::size_t r = 0; r < R; ++r) {
1017 const std::size_t rs = sn.classes[r].refstat;
1018 if (rs > 0 && rs <= M && r < out.XN.size()) out.XN[r] = out.TN(rs - 1, r);
1019 for (std::size_t i = 0; i < M; ++i)
1020 if (imm[i][r]) out.RN(i, r) = out.TN(i, r) > 0.0 ? out.QN(i, r) / out.TN(i, r) : 0.0;
1021 if (r < out.XN.size() && r < out.CN.size() && out.XN[r] > 0.0)
1022 out.CN[r] = sn.classes[r].population / out.XN[r];
1023 }
1024 return out;
1025}
1026
1027} // namespace ssa
1028} // namespace line
1029
1030#endif // LINE_SOLVERS_SSA_SSA_DISPATCH_H
What a solver observed about the Cache nodes of a model.
std::size_t cols() const
Definition matrix.h:90
std::size_t rows() const
Definition matrix.h:89
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
The NRM engine: the reaction network built from sn, and the sample path.
const std::vector< SsaCacheRatio > & cache() const
The cache write-back of the last run(), one entry per Cache node.
SsaSolution run()
Run opt.samples firings and return the time-averaged metrics.
The SPN Next-Reaction-Method engine, solver_ssa_nrm_spn of the reference.
The exception types the port throws.
The method names of each solver, in listing order.
bool sn_has_nonmarkov(const qn::NetworkStruct< T > &sn, bool preserve_det=false)
Whether any law in the struct would be replaced, so a caller can skip copying the struct when there i...
SnPnAvgRates< T > sn_pn_avg_rates(const qn::NetworkStruct< T > &sn, const Matrix< T > &QN, const Matrix< T > &TN, const Matrix< T > &AN, const Matrix< T > &RN)
Port of sn_pn_avg_rates: rewrite the place rows of TN, AN and RN so that they agree with the recovere...
std::string sn_polling_extension(const qn::NetworkStruct< T > &sn)
@ Ph
Bernstein density fit: a genuine phase-type, shape-carrying.
void sn_nonmarkov_toph(qn::NetworkStruct< T > &sn, const NonmarkovOptions &opts=NonmarkovOptions())
Replace every non-Markovian service and firing law by a Markovian surrogate.
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
DropStrategy
Blocking and loss rules, with the values of MATLAB DropStrategy.
Definition lang_types.h:465
RoutingStrategy
Routing strategies, with the values of MATLAB RoutingStrategy.
Definition lang_types.h:430
ProcessType
Distribution kinds, with the values of MATLAB ProcessType.
Definition lang_types.h:524
const char * sched_to_text(SchedStrategy s)
Definition lang_types.h:248
const char * routing_to_text(RoutingStrategy r)
Definition lang_types.h:443
bool in(const std::string &s, std::initializer_list< const char * > set)
Matrix< T > sn_get_arvr_from_tput(const qn::NetworkStruct< T > &L, const Matrix< T > &TN)
Port of sn_get_arvr_from_tput: the arrival rate each station sees, from the throughputs and the class...
std::string state_impatience_unsupported(const NetworkStruct< T > &sn, const std::string &solver)
Port of solver_ctmc_state_supports.m: the impatience laws the state machinery cannot serve,...
bool ssa_method_is_tstep(const std::string &method)
True when method names SSA's time-stepped approximation, bare or family-qualified,...
bool station_has_reneging(const NetworkStruct< T > &sn, std::size_t ist)
True when station ist declares exponential reneging for some class.
CacheMetrics< T > cache_metrics_of(const qn::NetworkStruct< T > &sn, const std::vector< T > &hitprob, const std::vector< T > &missprob, const std::vector< T > &delayedprob, const std::vector< T > &latency, const Matrix< T > &hitproblist, const Matrix< T > &itemprob, const std::vector< T > &listcost)
Assemble CacheMetrics from what a cache analyzer returned.
SsaSerialSolution< T > solver_ssa_serial_analyzer(const qn::NetworkStruct< T > &sn_in, const SsaSerialOptions &opt)
Port of solver_ssa_analyzer_serial.m plus the fork-join wrapper @@SolverSSA/runAnalyzer....
SsaSolution solver_ssa_nrm_analyzer(const qn::NetworkStruct< T > &sn, const SsaOptions &opt, std::vector< SsaCacheRatio > *cache=nullptr)
solver_ssa_analyzer_nrm.m: run the NRM and return the metric table.
SsaParallelSolution< T > solver_ssa_parallel_analyzer(const qn::NetworkStruct< T > &sn, const SsaParallelOptions &opt)
solver_ssa_analyzer_parallel.m: run R replicas of the serial engine and combine their estimates.
SsaNrmSpaceSolution< T > solver_ssa_nrm_space_analyzer(const qn::NetworkStruct< T > &sn, const SsaNrmSpaceOptions &opt)
Port of the else branch of solver_ssa_analyzer_nrm.m, the one state_space_gen selects: the means as p...
std::vector< std::string > list_valid_methods()
Port of SolverSSA.listValidMethods.
SsaSolution solver_ssa_analyzer_tstep(const qn::NetworkStruct< double > &sn, const SsaOptions &opt, TstepInfo *info=nullptr)
solver_ssa_analyzer_tstep.m.
Definition ssa_tstep.h:164
SsaSolution solver_ssa_engine(const qn::NetworkStruct< T > &sn, const SsaOptions &opt_in, std::vector< SsaCacheRatio > *cache)
solver_ssa_analyzer.m: choose the method.
SsaSolution solver_ssa(const qn::NetworkStruct< T > &sn, const SsaOptions &opt, std::vector< SsaCacheRatio > *cache=nullptr)
SsaSolution ssa_imm_tput_balance(const qn::NetworkStruct< T > &sn, const SsaSolution &in)
Port of ssa_imm_tput_balance.m: the throughput of every station-class pair whose service is Immediate...
qn::NetworkStruct< T > sn_with_ssa_cache_split(const qn::NetworkStruct< T > &base, const std::vector< SsaCacheRatio > &cache)
@@SolverSSA/runAnalyzer itself: the engine the method selects, then the result assembly the reference...
solvers::CacheMetrics< T > cache_metrics_of_ssa(const qn::NetworkStruct< T > &sn, const std::vector< SsaCacheRatio > &cache)
CacheMetrics from the serial engine's cache write-back.
double ssa_resolve_warmupfrac(const Struct &sn, double warmupfrac, bool steady=true)
ssa_warmupfrac.m: the effective warmup (initial-transient) discard fraction.
Definition ssa_types.h:139
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
Replace every non-Markovian service and firing law by a Markovian surrogate.
Ports of matlab/src/api/sn/sn_pn_firing_rates.m and sn_pn_avg_rates.m.
Port of matlab/src/api/sn/sn_polling_extension.m.
The SolverMVA class surface: @@SolverMVA/runAnalyzer.m and the gates around it.
SolverSSA, the nrm method: a port of solver_ssa_nrm.m and its analyzer solver_ssa_analyzer_nrm....
SolverSSA, the EXPLICIT STATE SPACE variant of the Next Reaction Method: a port of solver_ssa_nrm_spa...
SolverSSA on a STOCHASTIC PETRI NET: the port of solver_ssa_nrm_spn, the sub-engine solver_ssa_nrm....
SolverSSA, the para / parallel method: a port of solver_ssa_analyzer_parallel.m.
SolverSSA, the serial method: a port of solver_ssa_reachability.m, of the run loop of solver_ssa....
Port of solver_ssa_analyzer_tstep.m and ssa_tstep_refusal.m: SolverSSA method tstep,...
Controls, results and the random source of SolverSSA.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
options.config.nonmkv and friends.
PhFit phfit
which surrogate family
The verdict of sn_fluid_refusal: ok when no rule is broken, else the reason.
static constexpr double FineTol
Definition lang_types.h:823
A node of the network.
std::vector< RoutingStrategy > routing
sn.routing, per class.
Every Cache node of the model, in node order; empty on a model with none.
std::vector< CacheNodeMetrics< T > > caches
One Cache node's measured behaviour.
std::vector< T > hitprob
(K) TRUE hit fraction, EMPTY = not computed
std::vector< T > delayedprob
(K) delayed-hit fraction, EMPTY off a retrieval system
std::vector< T > latency
(K) expected latency per read request (hits wait 0), EMPTY = not computed
Controls, defaulting to SolverOptions('SSA') in the reference.
Definition ssa_types.h:71
double warmupfrac
options.config.warmupfrac: the leading fraction of the path discarded before the means are taken.
Definition ssa_types.h:96
What the analyzer returns, in the same shape as the MVA and fluid results.
Definition ssa_types.h:154
std::vector< double > XN
Definition ssa_types.h:156
std::vector< double > CN
Definition ssa_types.h:156
Matrix< double > RN
Definition ssa_types.h:155
Matrix< double > TN
Definition ssa_types.h:155
Matrix< double > QN
Definition ssa_types.h:155