LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
network_struct.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_LANG_QN_NETWORK_STRUCT_H
6#define LINE_LANG_QN_NETWORK_STRUCT_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * A queueing network and its refreshed NetworkStruct.
12 *
13 * SCOPE. This is the `sn` of `matlab/src/lang/@@MNetwork/refreshStruct.m`, held
14 * together with the model it was refreshed from, because every consumer of a
15 * struct in this port also mutates the model and re-derives it (SolverLN
16 * re-parameterises service processes between outer iterations, the fork-join
17 * transform rewrites routing). MATLAB does the same through the `sn` its
18 * Network caches.
19 *
20 * Fields are filled in as the solvers that read them are ported; a model
21 * needing an unported field is refused where the field would be read.
22 *
23 * NODES vs STATIONS vs STATEFUL NODES. There are three nested index spaces,
24 * exactly as `sn` has, and they stopped coinciding the moment fork/join
25 * arrived:
26 *
27 * nodes everything routing passes through: the stations, plus a Fork, its
28 * output Routers, a Join, a Sink
29 * stateful the nodes that hold jobs: every node except the Fork
30 * stations the nodes that serve jobs, including a Join (which serves at rate
31 * Inf) and a Source (whose service process is the arrival process)
32 *
33 * Routing (`P`, and the `rtnodes` derived from it) lives at NODE level; `rt` is
34 * its stochastic complement over the stateful nodes, which is what eliminates
35 * the Fork; `visits` is indexed by stateful node and `nodevisits` by node.
36 *
37 * ClassSwitch NODES ARE MATERIALISED, as `@MNetwork/link.m:225-329` does it:
38 * `link()` inserts one `CS_<i>_to_<j>` per ordered pair of linked nodes whose
39 * routing switches class, folds the switching probability into the first leg
40 * and leaves every surviving route SAME-CLASS. The stochastic complement in
41 * `rt` removes them again, since they are not stateful, so `rt` is unchanged by
42 * their presence; `rtnodes` and `nnodes` carry the extra hop, which is what the
43 * node table reports and what the JSIM export needs (`jmt_writer.h` can only
44 * emit a ClassSwitch for a node whose type IS ClassSwitch). Keeping the switch
45 * on the edge instead makes JMT silently simulate the UNSWITCHED model.
46 *
47 * ARITHMETIC. Rates, service times, routing probabilities and visits are T.
48 * Populations and server counts are `double`, since they are counts that may
49 * be infinite (a delay station, an open class).
50 */
51
53#include <algorithm>
54#include <cmath>
55#include <complex>
56#include <functional>
57#include <limits>
58#include <map>
59#include <string>
60#include <vector>
61
71#include "line/num/number.h"
72#include "line/util/error.h"
73#include "line/util/matrix.h"
74
75namespace line {
76namespace qn {
77
78using lang::CdScaling;
79using lang::GdScaling;
80using lang::Distrib;
82using lang::GlobalConstants;
85using lang::NodeType;
90
91/** One fork firing synchronization: `sn.fjsync{k}`. */
92template <class T>
93struct FjSync {
94 std::size_t fork = 0; ///< 1-based Fork node
95 std::size_t join = 0; ///< 1-based Join node that closes it
96 std::size_t cls = 0; ///< 1-based ORIGINAL class being forked
97 std::size_t tag = 0; ///< 1-based tag this entry allocates
98 std::vector<std::size_t> branchheads; ///< 1-based node per branch
99 std::vector<std::size_t> auxclasses; ///< the tag's auxiliary class per branch
100 /** (B x T) every auxiliary class of this (fork, class), for the tag scan. */
101 std::vector<std::vector<std::size_t>> auxall;
102 std::size_t weight = 1; ///< tasksPerLink: siblings emitted per branch
103 /**
104 * Per-branch tasksPerLink, EMPTY when every branch carries `weight`.
105 *
106 * A fork may send a different number of tasks down each link
107 * (`Fork.setTasksPerLink(class, n, dest)`), and the count is what sizes the
108 * auxiliary class capacity and the join's required count, so it cannot be
109 * collapsed to the node-wide mean. It stays empty in the uniform case so
110 * that a plain fork carries exactly the shape it always did; the two paths
111 * emit the same interleaved order there, so this is a shape convention and
112 * not a behavioural fork.
113 */
114 std::vector<std::size_t> weightlink;
116};
117
118/**
119 * `sn.nodeparam{j}.fj`: what a Join node needs to fire on identity.
120 *
121 * `auxmatrix[r]` is the (B x T) matrix of auxiliary sibling classes minted for
122 * original class r -- row b is branch b, column t is tag t -- and `required[r][b]`
123 * is how many siblings of branch b a firing consumes (`tasksPerLink` under the
124 * only join strategy the exact implementation accepts). It lives here rather
125 * than in `fj_tag.h` because `NetworkStruct` carries it and the event layer reads
126 * it; `fj_tag.h` is what FILLS it.
127 */
129 std::size_t fork = 0;
130 std::vector<std::size_t> origclasses;
131 std::map<std::size_t, std::vector<std::vector<std::size_t>>> auxmatrix;
132 std::map<std::size_t, std::vector<std::size_t>> required;
133 /**
134 * QUORUM joins (JoinStrategy.PARTIAL), keyed by original class: the join
135 * fires on the first `quorum[r]` of a tag's siblings, whichever branches
136 * they come from, and discards the stragglers as they arrive. Absent for a
137 * standard join. The Join row then carries `debtwidth` leading counters,
138 * one per tag of each quorum class from `debtoff[r]`: the stragglers of a
139 * fired tag still on the branches (python fjtag `quorum`/`debtoff`).
140 */
141 std::map<std::size_t, std::size_t> quorum;
142 std::map<std::size_t, std::size_t> debtoff;
143 std::size_t debtwidth = 0;
144};
145
146/**
147 * Variable forking levels, the twin of MATLAB `sn.nodeparam{f}.fanOutLink` /
148 * `.fanOutProb` / `.fanOutDist`.
149 *
150 * All three are (nnodes x nclasses) and indexed by DESTINATION NODE rather than
151 * by link ordinal, because the link order is an artefact of `connmatrix`
152 * traversal and renumbers whenever the model is relinked.
153 *
154 * `fan_out_link(k,r)`: expected tasks sent to destination k for class r, zero
155 * on a link class r does not take. `fan_out_prob(k,r)`: probability the branch
156 * fires at all, so the SIBLING COUNT is random even when each link carries a
157 * fixed number. `fan_out_dist[k][r]`: the jobs-per-link distribution, with an
158 * unset (DISABLED) entry meaning degenerate at `fan_out_link(k,r)`.
159 *
160 * This is a per-node BLOCK keyed by node index -- the shape `joindecl` already
161 * uses, and the shape MATLAB's `nodeparam{f}` has -- rather than three fields on
162 * `NodeDef`, because `NodeDef` is not templated on the arithmetic and a
163 * `Matrix<T>` cannot live there. A fork with no override has no entry at all,
164 * which is how a consumer tells the classic case from the variable one without
165 * inspecting a single number.
166 */
167template <class T>
168struct ForkParam {
171 std::vector<std::vector<lang::Distrib<T> > > fan_out_dist;
172};
173
174/**
175 * A node of the network.
176 *
177 * `station` is the 1-based station index when the node serves jobs and 0 when
178 * it does not (a Fork, a Router, a ClassSwitch, a Sink). `stateful` is false
179 * for the nodes that hold no jobs and are eliminated by the stochastic
180 * complement that builds rt.
181 */
182struct NodeDef {
183 std::string name;
184 NodeType nodetype = NodeType::Queue;
185 /**
186 * Declared as a Queue although its INF discipline makes `nodetype` Delay (`Network::add_queue`). MATLAB keeps
187 * the node's CLASS apart from sn.nodetype, and the TikZ exporter and linemodel_save read the class: such a node
188 * is drawn as a buffer with an infinite server and saved with type "Queue". Not part of the reference sn.
189 */
190 bool queue_object = false;
191 bool stateful = true;
192 std::size_t station = 0;
193 /**
194 * `sn.routing`, per class. PROB means the routing block P carries the
195 * probabilities as given; RAND and RROBIN mean the refresh spreads them
196 * uniformly over the nodes this one is connected to, which is the routing
197 * MATRIX of a round-robin dispatcher (its determinism lives in the higher
198 * moments, see refresh_routing). Anything else is state dependent, and the
199 * refresh refuses it by name: a state-dependent strategy silently treated
200 * as PROB returns a product-form answer for a model that has none.
201 */
202 std::vector<RoutingStrategy> routing;
203 /**
204 * The per-destination weights of a WRROBIN dispatcher, per class: a map
205 * from 1-based destination NODE index to its weight.
206 *
207 * MATLAB and the JAR keep these on the node object and the native Python
208 * struct calls the field `sn.routingweights`; this port carries them here
209 * so a WRROBIN model round-trips through model.json without loss. The
210 * refresh still refuses WRROBIN by name, because spreading the weights into
211 * a routing MATRIX would answer a state-independent model instead.
212 */
213 std::vector<std::map<std::size_t, double>> routing_weights;
214 /**
215 * The scalar parameter of a parameterized dispatcher, per class: the d of
216 * a power-of-d (SQ) choice. Zero means the strategy takes none. Carried for
217 * the same reason as `routing_weights`.
218 */
219 std::vector<int> routing_param;
220 /**
221 * `Fork.output.tasksPerLink` == MATLAB `sn.nodeparam{f}.fanOut`: how many
222 * tasks a fork emits per outgoing link. It scales both the MMT auxiliary
223 * arrival rate and the synchronisation delay; the default 1 leaves a plain
224 * fork unchanged.
225 *
226 * For a fork whose degree is RANDOM this is the MEAN, so a consumer that
227 * only knows this field gets E[tasks per link] rather than a number the
228 * fork never emits.
229 */
230 double tasks_per_link = 1.0;
231
232 /**
233 * A Logger node's trace configuration, MATLAB's `Logger` properties and
234 * `sn.nodeparam{ind}` for a Logger.
235 *
236 * The defaults are `Logger.m`'s constructor: timestamp, job id and job
237 * class are recorded, the wall-clock start time, the logger name and the
238 * two inter-departure columns are not. They are carried on the node rather
239 * than derived because a Logger with no file name exports to JMT as a
240 * LogTunnel that writes nowhere -- the solver runs, and the trace the user
241 * asked for is silently absent.
242 */
243 struct LoggerParam {
244 std::string file_name; ///< base name, no directory
245 std::string file_path; ///< directory, MATLAB's model.getLogPath
246 bool start_time = false;
247 bool logger_name = false;
248 bool timestamp = true;
249 bool job_id = true;
250 bool job_class = true;
251 bool time_same_class = false;
252 bool time_any_class = false;
253 };
255};
256
257/**
258 * The parameters of a Transition node: MATLAB `sn.nodeparam{ind}` for an SPN
259 * transition, as `refreshPetriNetNodes.m` writes them.
260 *
261 * A transition has MODES, not classes, but its ARCS carry a class: MATLAB's
262 * `enablingConditions{m}` is an (nnodes x nclasses) matrix, so one mode can
263 * require two tokens of Class1 at a place while another requires one of Class2
264 * at the same place. Each mode carries its own enabling and inhibiting
265 * conditions over the input places, its firing effect, and its own firing
266 * process -- which is why State.fromMarginal treats a Transition's state as
267 * per-mode and cannot reuse the per-class station encoding.
268 *
269 * THE CLASS DIMENSION IS NOT DECORATION. Collapsing the arcs onto the place lets
270 * a token of one class satisfy another class's pre-arc -- a DIFFERENT net, not
271 * an approximation of this one. Every consumer therefore reads a (node, class)
272 * pair, and the few that are genuinely class-blind (the MDD level aggregation,
273 * the S-invariants) say so by refusing a multiclass net rather than by summing
274 * it.
275 */
276template <class T>
278 std::size_t nmodes = 0;
279 std::vector<std::string> modenames;
280 /** enabling[m](p,r): class-r tokens of place p (0-based node) mode m needs. */
281 std::vector<Matrix<T>> enabling;
282 /** inhibiting[m](p,r): class-r tokens of p that BLOCK mode m (Inf = never). */
283 std::vector<Matrix<T>> inhibiting;
284 /** firing[m](p,r): class-r tokens mode m moves to/from place p when it fires. */
285 std::vector<Matrix<T>> firing;
286
287 /**
288 * The arcs of one mode summed over classes, for a consumer that is class
289 * blind BECAUSE THE NET IS SINGLE CLASS.
290 *
291 * `is_multiclass()` is what makes that safe, and a caller that cannot honour
292 * the class dimension must test it and refuse: the sum of a multiclass net's
293 * arcs describes a net whose tokens are interchangeable, which is not this
294 * one.
295 *
296 * A NON-FINITE ENTRY IS SKIPPED, and a row of nothing but non-finite entries
297 * stays non-finite: on an enabling arc Inf is JMT's "any number of tokens"
298 * and on an inhibiting one it is the ABSENCE of the arc, so adding it in
299 * would turn either into a row that no marking satisfies.
300 */
301 static std::vector<T> arc_total(const std::vector<Matrix<T>>& a, std::size_t m) {
302 std::vector<T> v;
303 if (m >= a.size()) return v;
304 v.assign(a[m].rows(), num_traits<T>::from_int(0));
305 for (std::size_t p = 0; p < a[m].rows(); ++p) {
306 double s = 0.0;
307 bool any = false;
308 for (std::size_t r = 0; r < a[m].cols(); ++r) {
309 const double x = num_traits<T>::to_double(a[m](p, r));
310 if (!std::isfinite(x)) continue;
311 s += x;
312 any = true;
313 }
314 v[p] = any || a[m].cols() == 0
316 : num_traits<T>::from_double(std::numeric_limits<double>::infinity());
317 }
318 return v;
319 }
320
321 /**
322 * The inhibiting THRESHOLD of one mode per place, class blind.
323 *
324 * A threshold is not a count and does not add up: the mode is blocked as
325 * soon as ANY class reaches its own bound, so the class-blind reduction is
326 * the smallest finite threshold, and Inf where no class declares one.
327 */
328 static std::vector<T> inhibit_total(const std::vector<Matrix<T>>& a, std::size_t m) {
329 std::vector<T> v;
330 if (m >= a.size()) return v;
331 const double inf = std::numeric_limits<double>::infinity();
332 v.assign(a[m].rows(), num_traits<T>::from_double(inf));
333 for (std::size_t p = 0; p < a[m].rows(); ++p) {
334 double best = inf;
335 for (std::size_t r = 0; r < a[m].cols(); ++r) {
336 const double x = num_traits<T>::to_double(a[m](p, r));
337 if (std::isfinite(x) && x < best) best = x;
338 }
339 v[p] = num_traits<T>::from_double(best);
340 }
341 return v;
342 }
343
344 /** True when any mode's arcs touch more than one class. */
345 bool is_multiclass() const {
346 const std::vector<Matrix<T>>* all[3] = {&enabling, &inhibiting, &firing};
347 for (int w = 0; w < 3; ++w)
348 for (std::size_t m = 0; m < all[w]->size(); ++m) {
349 std::size_t touched = 0;
350 for (std::size_t r = 0; r < (*all[w])[m].cols(); ++r) {
351 bool any = false;
352 for (std::size_t p = 0; p < (*all[w])[m].rows() && !any; ++p) {
353 const double v = num_traits<T>::to_double((*all[w])[m](p, r));
354 // An inhibiting Inf is the ABSENCE of an arc, not one.
355 any = w == 1 ? (std::isfinite(v) && v > 0.0) : v > 0.0;
356 }
357 if (any) ++touched;
358 }
359 if (touched > 1) return true;
360 }
361 return false;
362 }
363
364 /** The one class every arc of every mode touches, 1-based; 0 when none does. */
365 std::size_t single_class() const {
366 const std::vector<Matrix<T>>* all[3] = {&enabling, &inhibiting, &firing};
367 for (int w = 0; w < 3; ++w)
368 for (std::size_t m = 0; m < all[w]->size(); ++m)
369 for (std::size_t r = 0; r < (*all[w])[m].cols(); ++r)
370 for (std::size_t p = 0; p < (*all[w])[m].rows(); ++p) {
371 const double v = num_traits<T>::to_double((*all[w])[m](p, r));
372 if (w == 1 ? (std::isfinite(v) && v > 0.0) : v > 0.0) return r + 1;
373 }
374 return 0;
375 }
376 std::vector<double> nmodeservers; ///< servers per mode, may be infinite
377 std::vector<double> firingprio; ///< firing priority per mode
378 std::vector<T> fireweight; ///< weight among simultaneously enabled modes
379 std::vector<lang::TimingStrategy> timing; ///< immediate or timed
380 std::vector<lang::Distrib<T>> firingproc; ///< firing distribution per mode
381 std::vector<std::size_t> firingphases; ///< phase count per mode, 0 when non-Markovian
382 /**
383 * Marking-dependent firing-rate multiplier g_m(marking); an empty entry is
384 * the unit multiplier. Transition.setFiringRateDependence. The argument is the
385 * (nnodes x nclasses) marking flattened node-major, entry (i-1)*K + (r-1) for
386 * 1-based node i and class r, as MATLAB's g(M); single-class, it is node-indexed.
387 */
388 std::vector<std::function<T(const std::vector<T>&)>> firingdep;
389
390 /** One fluid arc of a mode: `node` is the 1-based fluid place, `value` a rate or an impulse. */
391 struct FluidArc {
392 std::size_t node = 0;
393 double value = 0.0;
394 };
395 /** A fluid guard: the mode is enabled only while level(node) >= thr (sgn = +1) or <= thr (sgn = -1). */
396 struct FluidGuard {
397 std::size_t node = 0;
398 int sgn = 1;
399 double thr = 0.0;
400 };
401 /** A fluid rate dependence: the firing rate is multiplied by fun(level(node)). */
402 struct FluidDep {
403 std::size_t node = 0;
404 std::function<double(double)> fun;
405 };
406 /**
407 * A marking-dependent fluid flow (`setFluidFlowDependence`): the flow of the mode on fluid place `node` is
408 * multiplied by fun(M). M is the (nnodes x nclasses) marking flattened row-major, entry (i-1)*nclasses + (r-1)
409 * for 1-based node i and class r, holding the token places `read` and 0 in every other row. `read` names the
410 * mode's input places unless `read_given`; the builder resolves it at `get_struct()`, as refreshPetriNetNodes.
411 */
413 std::size_t node = 0;
414 std::function<double(const std::vector<double>&)> fun;
415 std::vector<std::size_t> read;
416 bool read_given = false;
417 };
418 /**
419 * FSPN arcs per mode, MATLAB `sn.transparam{ind}.fluidrate/fluidguard/fluidimpulse/fluiddep`. A reader that
420 * builds the per-mode vectors itself (pnml, jsim) may leave these shorter than `nmodes`, so read them through
421 * the accessors below, which answer an empty list for a mode that declares nothing.
422 */
423 std::vector<std::vector<FluidArc>> fluidrate;
424 std::vector<std::vector<FluidGuard>> fluidguard;
425 std::vector<std::vector<FluidArc>> fluidimpulse;
426 std::vector<std::vector<FluidDep>> fluiddep;
427 std::vector<std::vector<FluidFlowDep>> fluidflowdep;
428
429 const std::vector<FluidArc>& fluid_rates(std::size_t m) const {
430 static const std::vector<FluidArc> none;
431 return m < fluidrate.size() ? fluidrate[m] : none;
432 }
433 const std::vector<FluidGuard>& fluid_guards(std::size_t m) const {
434 static const std::vector<FluidGuard> none;
435 return m < fluidguard.size() ? fluidguard[m] : none;
436 }
437 const std::vector<FluidArc>& fluid_impulses(std::size_t m) const {
438 static const std::vector<FluidArc> none;
439 return m < fluidimpulse.size() ? fluidimpulse[m] : none;
440 }
441 const std::vector<FluidDep>& fluid_deps(std::size_t m) const {
442 static const std::vector<FluidDep> none;
443 return m < fluiddep.size() ? fluiddep[m] : none;
444 }
445 const std::vector<FluidFlowDep>& fluid_flow_deps(std::size_t m) const {
446 static const std::vector<FluidFlowDep> none;
447 return m < fluidflowdep.size() ? fluidflowdep[m] : none;
448 }
449 /** `Transition.hasFluidArcs`: any mode declares a fluid rate, guard, impulse, rate or flow dependence. */
450 bool has_fluid_arcs() const {
451 for (std::size_t m = 0; m < nmodes; ++m)
452 if (!fluid_rates(m).empty() || !fluid_guards(m).empty() || !fluid_impulses(m).empty() ||
453 !fluid_deps(m).empty() || !fluid_flow_deps(m).empty())
454 return true;
455 return false;
456 }
457};
458
459/**
460 * The parameters of a retrial station: MATLAB `sn.retrialProc` and friends.
461 *
462 * A retrial station has NO waiting line. An arrival that finds every server
463 * busy joins an ORBIT and re-attempts at the retrial rate, so its state is an
464 * (in-service, orbit) split rather than an ordered buffer -- State.fromMarginal
465 * enumerates that split, and the freed server is NOT filled on a completion.
466 */
467template <class T>
469 /** retrial_proc[r] is the class-r retrial process; empty = not a retrial class. */
470 std::vector<lang::Distrib<T>> retrial_proc;
471 std::vector<T> retrial_rate; ///< mu_r, the per-class orbit retry rate
472 std::vector<int> max_attempts; ///< 0 = unbounded
473 /** MATLAB `sn.retrialPolicy`: 1 = LINEAR (per-job clocks), 2 = CONSTANT (one clock per orbit). */
474 std::vector<int> policy;
475 /** MATLAB `sn.orbitMaxJobs`: -1 = unbounded. The capacity already bounds service plus orbit. */
476 std::vector<int> max_orbit;
477};
478
479/**
480 * Setup and delay-off of a station that powers down when it falls idle.
481 *
482 * MATLAB `Queue.setDelayOff(class, setupTime, delayoffTime)`, which
483 * refreshLocalVars copies into `sn.nodeparam{node}{class}`. The server starts
484 * a delay-off timer when it empties and shuts down when the timer expires; the
485 * next arrival to a shut-down server pays the setup time before service.
486 *
487 * Stored per class because the reference stores it per class, but every
488 * consumer reads ONE pair per station -- `solver_mam_basic.m` takes the LAST
489 * class's, so `last()` below is what a solver should call rather than picking
490 * a class itself.
491 */
492template <class T>
494 std::vector<lang::Distrib<T>> setup; ///< per class, disabled = not declared
495 std::vector<lang::Distrib<T>> delayoff; ///< per class
496 /** The pair the solvers use: the last class that declares one. */
497 bool last(lang::Distrib<T>& su, lang::Distrib<T>& doff) const {
498 for (std::size_t r = setup.size(); r > 0; --r)
499 if (!setup[r - 1].disabled) {
500 su = setup[r - 1];
501 doff = r - 1 < delayoff.size() ? delayoff[r - 1] : lang::Distrib<T>::disabled_dist();
502 return true;
503 }
504 return false;
505 }
506};
507
508/**
509 * Server breakdown and repair of a station whose server fails and is repaired.
510 *
511 * MATLAB `Queue.setBreakdown(failure, repair, downService)`, which
512 * `refreshStruct` spreads over `sn.hasbreakdown` (per NODE),
513 * `sn.breakdownMu` / `sn.repairMu` / `sn.breakdownProc` / `sn.repairProc` (per
514 * STATION) and `sn.downServiceRates` (per station and class). They are one
515 * feature and are kept as one record here, keyed by station, for the same
516 * reason `SetupDelayOffParam` is: presence IS the flag.
517 *
518 * WHAT A BREAKDOWN IS, and what it is not. The server alternates up and down on
519 * independent clocks. A job IN SERVICE when the server goes down is NOT evicted
520 * and does not restart: it holds its residual work across the outage, so the
521 * outage is a pure interruption. `down_service_rates(r)` is a DEGRADED server,
522 * not a stopped one -- a positive rate there means class r keeps being served
523 * while the server is down, more slowly. Zero means no service at all, which is
524 * the ordinary reading of "broken".
525 *
526 * THE DEGRADED SERVICE MUST BE EXPONENTIAL, and the reference refuses anything
527 * else by name: a phase-type degraded service would need its own phase block in
528 * the joint chain, which no codebase builds. Only the RATE is stored for that
529 * reason -- there is no distribution left to carry.
530 */
531template <class T>
533 lang::Distrib<T> failure; ///< time to failure of an up server
534 lang::Distrib<T> repair; ///< time to repair of a down server
535 T failure_rate = num_traits<T>::from_int(0); ///< `sn.breakdownMu`: 1 / mean failure time
536 T repair_rate = num_traits<T>::from_int(0); ///< `sn.repairMu`: 1 / mean repair time
537 /** `sn.downServiceRates(ist, :)`: per class, 0 = no service while down. */
538 std::vector<T> down_service_rates;
539
540 T down_rate_of(std::size_t cls_1based) const {
541 if (cls_1based == 0 || cls_1based > down_service_rates.size())
542 return num_traits<T>::from_int(0);
543 return down_service_rates[cls_1based - 1];
544 }
545};
546
547/**
548 * The parameters of a Cache node, MATLAB's `sn.nodeparam{ind}` for a Cache.
549 *
550 * `itemcap` is the capacity of each of the `h` cache lists (a single-level
551 * cache has one entry). `nitems` is the item population `n`.
552 *
553 * `pread[v]` is the read distribution of class v over the n items; an EMPTY row
554 * is MATLAB's `NaN` placeholder, "class v does not read this cache", and leaves
555 * that class's rates at zero. `accost[v][k]` is the ((h+1) x (h+1)) list-to-list
556 * routing matrix of class v on item k; an EMPTY `accost` selects the reference
557 * default, the linear cache in which an item moves from list l to l+1 on a hit.
558 * These two match `da::CacheParam` exactly, so `da_cache_isolate` consumes them
559 * without a conversion.
560 *
561 * `hitclass` and `missclass` are the 1-based classes a job of class r switches
562 * into on a hit and on a miss, 0 meaning the transition is disabled.
563 */
564template <class T>
566 std::size_t nitems = 0;
567 std::vector<int> itemcap;
568 /**
569 * Item read by each per-item class of a cache network (MATLAB
570 * `Cache.setItemReadClasses`, `sn.nodeparam{i}.classitem`), 1-based, 0 where
571 * the class is not one. Stored rather than inferred from a one-hot pread,
572 * which is ambiguous against a genuine single-item popularity.
573 */
574 std::vector<std::size_t> classitem;
575 /**
576 * Per-item storage cost (size) and per-list cap on the total cost of the
577 * resident items (ton21cache Sec. IX). BOTH EMPTY = unconstrained, the
578 * classic model. `costcapglobal` records that the caps came from a single
579 * cache-wide value.
580 */
581 std::vector<int> itemsize;
582 std::vector<int> costcap;
583 bool costcapglobal = false;
584 std::vector<std::vector<T>> pread; ///< (u) x (n), empty row = NaN
585 /**
586 * The popularity LAW each class declared, beside the pmf it expands to.
587 *
588 * Every solver reads `pread`, which is why the pmf is what the reader
589 * materializes. The law is kept because JMT's Cache section takes a
590 * PARAMETRIC popularity -- a Zipf exponent or a uniform range -- and
591 * cannot be given a pmf; without this, exporting a Zipf cache would have to
592 * either guess the exponent back out of the pmf or drop the popularity.
593 * `type` is NONE when the pmf was supplied directly.
594 */
595 struct Popularity {
597 double s = 0.0; ///< Zipf exponent
598 std::size_t n = 0; ///< support size of a Zipf or a DiscreteSampler
599 };
600 std::vector<Popularity> preadkind; ///< per class, parallel to `pread`
602 std::vector<std::size_t> hitclass, missclass;
603 std::vector<std::vector<Matrix<T>>> accost; ///< (u) x (n) of (h+1)x(h+1), or empty
604 /** q-LRU admission probability; 1 admits every miss (plain LRU). */
606 /**
607 * Delayed-hit retrieval system (Cache.setRetrievalSystem). Zero capacity =
608 * none. `retrieval_queues[r]` are the 1-based retrieval-station node indices
609 * a read of class r (0-based key) circulates on a miss; `retrieval_classes`
610 * is (nitems x nclasses), item i of read class r -> the per-item retrieval
611 * class (1-based), 0 where none. Built by set_retrieval_system.
612 */
614 std::map<std::size_t, std::vector<std::size_t>> retrieval_queues; ///< read class(0-based)->nodes
615 std::vector<std::vector<std::size_t>> retrieval_classes; ///< (nitems x nclasses), 1-based
616 /**
617 * The DECLARED initial contents of the cache, as the reference dumps the
618 * node's state row: the per-class job counts, then the list contents, then
619 * the retrieval bitmap. Empty means the cache starts empty, which is what
620 * `initDefault` builds; a warm cache is not derivable from anything else.
621 */
622 std::vector<T> initstate;
623 /**
624 * Truncation level of block B: how many secondary requests may be merged
625 * onto the in-flight fetches of this cache at once. -1 is UNBOUNDED, which
626 * is what a sample path needs and what `State.afterEventCache` calls the
627 * `isSimulation` branch; a non-negative value is the enumeration bound an
628 * exact solver generates its local state space under.
629 */
631};
632
633/**
634 * Port of `State.cacheRetrievalClassMap`: the canonical order of a cache's
635 * retrieval classes, which is the column order of block B.
636 *
637 * Block B keys the merged requests by RETRIEVAL CLASS rather than by item so
638 * that the originating class, hence its hit class, is recoverable when the
639 * fetch completes and the merged requests are released as delayed hits.
640 */
641template <class T>
642void cache_retrieval_class_map(const CacheParam<T>& cp, std::vector<std::size_t>& rc_list,
643 std::vector<std::size_t>& rc_items,
644 std::vector<std::size_t>& rc_orig) {
645 rc_list.clear();
646 rc_items.clear();
647 rc_orig.clear();
648 for (std::size_t k = 0; k < cp.retrieval_classes.size(); ++k)
649 for (std::size_t c = 0; c < cp.retrieval_classes[k].size(); ++c)
650 if (cp.retrieval_classes[k][c] != 0) {
651 rc_list.push_back(cp.retrieval_classes[k][c]);
652 rc_items.push_back(k + 1);
653 rc_orig.push_back(c + 1);
654 }
655 // The reference sorts by the retrieval class index and carries the two
656 // parallel arrays along; a plain index sort reproduces that permutation.
657 std::vector<std::size_t> ord(rc_list.size());
658 for (std::size_t i = 0; i < ord.size(); ++i) ord[i] = i;
659 std::stable_sort(ord.begin(), ord.end(),
660 [&](std::size_t a, std::size_t b) { return rc_list[a] < rc_list[b]; });
661 std::vector<std::size_t> l(rc_list.size()), it(rc_list.size()), oc(rc_list.size());
662 for (std::size_t i = 0; i < ord.size(); ++i) {
663 l[i] = rc_list[ord[i]];
664 it[i] = rc_items[ord[i]];
665 oc[i] = rc_orig[ord[i]];
666 }
667 rc_list.swap(l);
668 rc_items.swap(it);
669 rc_orig.swap(oc);
670}
671
672/** One station of the network. */
673template <class T>
674struct Station {
675 std::string name;
676 NodeType nodetype = NodeType::Queue;
677 SchedStrategy sched = SchedStrategy::FCFS;
678 double nservers = 1.0; ///< may be infinite (a Delay, or an inf-scheduled task)
679 bool attr_ishost = false;
680 std::size_t attr_idx = 0; ///< LQN element this station stands for
681
682 /**
683 * `sn.schedparam`, per class: the DPS / GPS weight, or the SEPT / LEPT rank.
684 * Empty means the discipline takes no parameter; the refresh fills it with
685 * ones for DPS and GPS, which is MATLAB's default weight.
686 */
687 std::vector<T> schedparam;
688 /**
689 * Station capacity in Kendall's K, as `setCapacity` sets it. Infinite means
690 * unbounded; `sn.cap` is derived from it and from the class capacities.
691 */
692 double cap = std::numeric_limits<double>::infinity();
693 /** Per-class buffer from `setChainCapacity`; infinite where unset. */
694 std::vector<double> classcap;
695 /**
696 * Node-level immediate feedback, per class; empty when the station sets
697 * none. Only a Queue carries it in the reference, which is also the only
698 * node the JSON writer emits it for.
699 */
700 std::vector<bool> immfeed;
701 /**
702 * Per-class blocking rule as an INT, with 0 meaning "not set".
703 *
704 * The sentinel is MATLAB's: DropStrategy has no member with value 0, so a
705 * zero entry is what an unset rule looks like there, and the refresh
706 * derives those from the capacity. It matters that the two are
707 * distinguishable, because an EXPLICIT WAITQ for an open class at a finite
708 * buffer is rejected while the derived one is not.
709 */
710 std::vector<int> droprule;
711 /**
712 * `sn.lldscaling` for this station: the multiplier at population 1, 2, ...
713 * Empty when the station is not load dependent.
714 */
715 std::vector<T> lldscaling;
716 /** `sn.cdscaling` for this station: the class-dependence map, empty when unset. */
718 /**
719 * `sn.cdscalingpeak` for this station: the DECLARED peak rate scaling per
720 * class, empty when the station is not class dependent.
721 *
722 * It is not derivable from `cdscaling`: finding max_n beta_r(n) would mean
723 * sweeping the whole population lattice, and the reference does not. It is
724 * what utilization at a class-dependent station is normalized by, so that
725 * U = T*S/peak keeps the T*S/c convention of an ordinary multiserver
726 * station; without it a beta emulating two servers reports twice the true
727 * utilization. MATLAB's `setClassDependence` requires it.
728 */
729 std::vector<T> cdscalingpeak;
730 /**
731 * `sn.jdscaling` for this station: MATLAB's `Station.ljdScaling`, the JOINT
732 * dependence map eta_i(n), empty when unset.
733 *
734 * It has the same signature as `cdscaling` and is folded into it
735 * multiplicatively wherever a rate is scaled, exactly as
736 * `State.afterEventInit` does. It is kept as a SEPARATE field rather than
737 * pre-multiplied into `cdscaling` because the two carry different modelling
738 * claims: a `cdscaling` beta_r(n) keeps the product form (it is the
739 * class-dependent rate lattice `pfqn_cdfun` evaluates), while an eta_i(n)
740 * does not, and `pfqn_mvajd` / `pfqn_ncjd` are selected on that distinction.
741 */
743 /**
744 * `sn.jdscalingpeak` for this station: the declared peak joint-dependent
745 * scaling per class. `setJointDependence` makes it mandatory for the same
746 * reason `setClassDependence` does -- utilization is reported as T*S/peak.
747 */
748 std::vector<T> jdscalingpeak;
749
750 /**
751 * `sn.nodeparam{ind}.svcRateFun` for a PAS / OI station: the TOTAL service
752 * rate as a function of the ordered microstate, a 1-based list of class
753 * indices in queue order.
754 *
755 * A pass-and-swap or order-independent queue is parameterized by mu(c) as a
756 * whole; there is no per-class service distribution, and MATLAB's
757 * `setServiceRateFunction` rejects one. The refresh still derives a
758 * representative per-class rate mu([r]) so the ordinary rate machinery
759 * stays consistent, exactly as `Queue.setServiceRateFunction` does.
760 */
761 std::function<T(const std::vector<std::size_t>&)> svc_rate_fun;
762
763 /**
764 * Polling parameters for a POLLING station, MATLAB's `pollingType`,
765 * `switchoverTime` and `pollingPar` on the Queue.
766 *
767 * `polling_type[r]` is the discipline of class r's buffer (the reference
768 * assumes it is identical across buffers), `switchover[r]` its switchover
769 * distribution, and `polling_par` the K of a K-limited discipline. Empty
770 * `polling_type` means the station is not a polling station.
771 */
772 std::vector<lang::PollingType> polling_type;
773 std::vector<Distrib<T>> switchover;
774 int polling_par = 0;
775 /**
776 * The polling extensions (`Queue.setPollingTable`, `setPollingOrder`,
777 * `setPollingTimer`). `polling_table` is the visit sequence (1-based
778 * classes, empty = the cyclic ring) and `polling_table_sw[p]` the walk out
779 * of table position p+1 (disabled = the class switchover of that entry).
780 * `polling_order_class`/`polling_order_threshold` are the THRESHOLD
781 * priority class (1-based) and its L. `polling_timer[r]` is the visit
782 * timer of class r+1 (disabled = none).
783 */
784 std::vector<std::size_t> polling_table;
785 std::vector<Distrib<T>> polling_table_sw;
787 std::size_t polling_order_class = 0;
791 std::vector<Distrib<T>> polling_timer;
792 /**
793 * `Queue.setSwitchover(fromClass, toClass, distrib)`: the walk the server
794 * takes when it turns from serving class r to serving class s, MATLAB's
795 * (K x K) `switchoverTime` cell. Empty means none declared at all;
796 * otherwise it is (K x K) and an undeclared pair is DISABLED, so it is not
797 * serialized. MATLAB fills its cell with Immediate and writes all K^2
798 * entries instead; nothing reads either, and the sparse form is the one
799 * that round-trips a document unchanged.
800 *
801 * IT IS CARRIED, NOT CONSUMED, and that is parity rather than an omission.
802 * No solver in any codebase reads a pairwise switchover: the MVA polling
803 * analyzer and the state machinery reach `switchover` above through the
804 * polling buffers, and `writeJSIM` warns and DROPS the pairwise times on an
805 * ordinary Server because JMT's `Server` has no switchover of its own. What
806 * the field buys is that the model can be declared, serialized and read
807 * back unchanged -- which is what `switchover_basic` exercises.
808 */
809 std::vector<std::vector<Distrib<T>>> switchover_pair;
810 /**
811 * `Queue.setQuantum(class, distrib)`: the per-class time slice of a
812 * round-robin (SchedStrategy::RR) station (Haverkort 1998, Sect. 6.4). On
813 * expiry the job in service is preempted (resume, its service phase kept)
814 * and rejoins the queue tail; a fresh quantum starts at every entry into
815 * service. Empty means none declared; an undeclared class is DISABLED.
816 * `rr_info` (rr_info.h) reads it to size the quantum-phase block of the
817 * local variables.
818 */
819 std::vector<Distrib<T>> quantum;
820 /**
821 * `sn.nodeparam{ind}.swapGraph`: which class a departing job promotes the
822 * jobs behind it into. All zero is the ORDER-INDEPENDENT case, where no
823 * swapping happens and the station is product-form; a nonzero entry makes
824 * it a genuine pass-and-swap station, which the OI analyzer refuses.
825 */
827
828 // ---- impatience, balking and heterogeneous servers ---------------------
829 //
830 // These are declared per class on the station, as the reference declares
831 // them, and they are all OPTIONAL: an empty vector means the station
832 // declares none, which is not the same as declaring a disabled one.
833 // `used_lang_features` emits Reneging / Balking / HeteroServers from them,
834 // so a solver that does not implement one refuses the model by name
835 // instead of solving a station without it.
836
837 /**
838 * `Queue.setPatience(class, dist)`: the abandonment timer of a WAITING job,
839 * with `impatience[r]` naming which rule it is. A disabled entry is a class
840 * that declares none.
841 */
842 std::vector<Distrib<T>> patience;
843 std::vector<lang::ImpatienceType> impatience;
844 /**
845 * `Queue.setOrbitImpatience(class, dist)`: abandonment from the RETRIAL
846 * ORBIT, which is a different population from the waiting line above -- a
847 * job that gave up retrying never occupied a buffer slot.
848 */
849 std::vector<Distrib<T>> orbit_impatience;
850 /** `Queue.setBatchRejectProbability`: per-class rejection of a whole batch. */
851 std::vector<T> batch_reject;
852 /**
853 * `Queue.setOrbitPersistence(class, p, q)`, MATLAB `sn.orbitJoinProb` and
854 * `sn.orbitPersistProb`: a fresh arrival that finds every server busy joins
855 * the retrial orbit with probability `orbit_join[r]` and is lost otherwise;
856 * an orbiting job whose retrial finds every server busy returns to the
857 * orbit with probability `orbit_persist[r]` and leaves the system otherwise.
858 * A missing entry is the persistent default 1.
859 */
860 std::vector<T> orbit_join;
861 std::vector<T> orbit_persist;
862 /**
863 * `Queue.setOrbitalSearch(class, theta)`, MATLAB `sn.orbitSearchProb`: on a
864 * service completion at a retrial station the freed server takes a class-r
865 * orbiting job with probability `orbit_search[r]` (sum over r <= 1). A
866 * missing entry is the default 0.
867 */
868 std::vector<T> orbit_search;
869
870 /** `orbit_join[r]` with the default 1 for a missing slot (0-based r). */
871 T orbit_join_of(std::size_t r) const {
872 return r < orbit_join.size() ? orbit_join[r] : num_traits<T>::from_int(1);
873 }
874 /** `orbit_persist[r]` with the default 1 for a missing slot (0-based r). */
875 T orbit_persist_of(std::size_t r) const {
876 return r < orbit_persist.size() ? orbit_persist[r] : num_traits<T>::from_int(1);
877 }
878 /** `orbit_search[r]` with the default 0 for a missing slot (0-based r). */
879 T orbit_search_of(std::size_t r) const {
880 return r < orbit_search.size() ? orbit_search[r] : num_traits<T>::from_int(0);
881 }
882
883 /**
884 * One balking threshold: with `min_jobs <= n <= max_jobs` at the station,
885 * an arriving job of the class refuses to join with `probability`.
886 * `max_jobs = -1` is the wire's spelling of an unbounded upper end.
887 */
889 double min_jobs = 0.0;
890 double max_jobs = -1.0;
892 };
893 /** Per class; `strategy == NONE` is a class that declares no balking. */
898 std::vector<BalkingParam> balking;
899
900 /**
901 * A heterogeneous server pool: `count` servers that serve only
902 * `compatible` classes, each with its own service law.
903 *
904 * The station's own `service` row stays the class-level default and is what
905 * every homogeneous consumer reads; `server_types` is the refinement, and
906 * `hetero_policy` says how the pools are picked among.
907 */
908 struct ServerType {
909 std::string name;
910 double count = 1.0;
911 std::vector<bool> compatible; ///< per class; empty = every class
912 std::vector<Distrib<T>> service; ///< per class
913 };
914 std::vector<ServerType> server_types;
916
917 /**
918 * `Queue.setServerParallelism(class, n)`: the servers a job seizes for the
919 * whole of its service, JMT's job parallelism. Per class, empty or all ones
920 * when every job seizes one server.
921 */
922 std::vector<std::size_t> server_parallelism;
923
924 /**
925 * `Source.setArrivalBatch(class, dist)`: the batch-size law released at
926 * each arrival epoch. It does NOT space the epochs -- the arrival process
927 * in `service` does -- so the two are separate and both are needed.
928 */
929 std::vector<Distrib<T>> arrival_batch;
930 /** `Source.markedClasses`: the 1-based class of each mark of an MMAP arrival. */
931 std::vector<std::size_t> marked_classes;
932 /** `Place.departureDiscipline`, per class. */
933 std::vector<lang::DepartureDiscipline> departure_discipline;
934 /**
935 * `Place.setFluid` (MATLAB `sn.fluid`): the place holds a continuous LEVEL rather than tokens, the fluid
936 * place of a Fluid Stochastic Petri Net (Horton, Kulkarni, Nicol and Trivedi, 1998). Tokens never enter it:
937 * timed modes pump it at a constant rate while enabled, any mode may move it by an impulse when it fires,
938 * and its level gates modes through guards. `fluidcap` is the level ceiling (`sn.fluidcap`, Inf when
939 * unbounded) and `fluidinit` the level at time zero (`sn.fluidinit`).
940 */
941 bool fluid = false;
942 double fluidcap = std::numeric_limits<double>::infinity();
943 double fluidinit = 0.0;
944};
945
946/** One job class of the network. */
947struct JobClass {
948 std::string name;
949 JobClassType type = JobClassType::CLOSED;
950 double population = 0.0; ///< infinite for an open class
951 std::size_t refstat = 1; ///< 1-based reference station
952 /**
953 * Whether passage through the reference station is a COMPLETION.
954 *
955 * TRUE BY DEFAULT, as in `JobClass.m:34`, `JobClass.java:108` and the native
956 * Python `classes.py:37` -- every other codebase constructs a class that
957 * completes, and nothing on the model.json wire carries the flag, so a
958 * `false` default here made the SAME model mean different things in this port
959 * than in the three it is a port of. The visible consequence was that every
960 * response-time law refused: `solver_ctmc_cdf_respt` needs one completing
961 * class in the tagged chain to have an event to end the passage at, so
962 * `getCdfRespT` on an ordinary two-station model reported that no class
963 * completes. The paths that need a NON-completing class -- an auxiliary
964 * fork-join sibling, an LN pseudo-class -- set it to false explicitly, and
965 * did so already.
966 */
967 bool completes = true;
968 bool is_ref_class = false; ///< marks the chain's reference class
969 int attr_kind = -1; ///< LayeredNetworkElement of the element it stands for
970 std::size_t attr_idx = 0; ///< index of that element
971 int prio = 0;
972 /**
973 * Class-level immediate feedback, ORed with the station's own setting into
974 * `sn.immfeed`. It is the class-wide spelling of the same property, and the
975 * JSON wire carries it as a bare `"immediateFeedback": true` on the class
976 * where the node-level form is a per-class map on the node.
977 */
978 bool immfeed = false;
979 /**
980 * `sn.classdeadline(r)`: the soft deadline EDD and EDF order by, and the
981 * tardiness JMT reports. Infinite where the class declares none, which is
982 * `NetworkStruct.m:17`'s "Inf = no deadline" sentinel.
983 */
984 double deadline = std::numeric_limits<double>::infinity();
985 /**
986 * `sn.classspawn(r)`: the 1-based class injected at the SAME station on
987 * every completion of this class, 0 where none. MATLAB stores -1 for none;
988 * the 0 here is this port's usual absent-index sentinel.
989 */
990 std::size_t spawn = 0;
991 /**
992 * A `SelfLoopingClass`: a closed class that perpetually cycles at its
993 * reference station. It carries no state beyond `ClosedClass`, so it is
994 * built as one; the marker exists so the writer does not silently downgrade
995 * the wire type to `Closed` and so `getUsedLangFeatures` can name it.
996 */
997 bool self_looping = false;
998};
999
1000/**
1001 * CTMC bookkeeping of a heterogeneous-server station, written by `ctmc::ctmc_pools`
1002 * on the solver's private copy of the struct (MATLAB `sn.nodeparam{ind}.ctmcpool`).
1003 *
1004 * The class-r service law there is a block-diagonal phase-type law with one block
1005 * per compatible pool, in ascending pool order, so the phase of a job in service
1006 * names its pool. All indices below are 1-based pools and classes, as in MATLAB.
1007 */
1008template <class T>
1009struct CtmcPool {
1010 std::size_t ntypes = 0;
1011 std::vector<double> count; ///< servers per pool
1012 std::vector<std::vector<bool>> compat; ///< compat[t-1][r-1]
1014 std::vector<std::vector<std::size_t>> pools; ///< pools[r-1]: compatible pools of r, ascending
1015 std::vector<std::vector<std::size_t>> off, len; ///< offset and length of block k of class r
1016 std::vector<std::vector<std::vector<T>>> alpha; ///< entry vector of block k of class r
1017 std::vector<std::vector<std::vector<T>>> exit; ///< exit rates of block k of class r
1018 std::vector<std::vector<Matrix<T>>> D0; ///< D0 of block k of class r
1019 std::vector<std::vector<double>> fsfrate; ///< fsfrate[t-1][r-1] = 1/mean (FSF)
1020 std::vector<std::size_t> alfsorder; ///< pools by ascending class count (ALFS)
1021 bool rotate = false; ///< ALIS/FAIRNESS order is part of the state
1022 std::vector<std::vector<std::size_t>> perms; ///< every pool order, identity first
1023 /** 1-based index of `order` in `perms`, 0 when absent. */
1024 std::size_t perm_index(const std::vector<std::size_t>& order) const {
1025 for (std::size_t p = 0; p < perms.size(); ++p)
1026 if (perms[p] == order) return p + 1;
1027 return 0;
1028 }
1029};
1030
1031/**
1032 * CTMC pair form of a MAP service at an FCFS station, written by `ctmc::ctmc_mapc` on the
1033 * solver's private copy of the struct (MATLAB `sn.ctmcmapc{ist,r}`). JMT and both LDES
1034 * engines chain ONE sampler per (station, class) in service-start order, so with
1035 * V = (-D0)^-1 D1 a busy server is a pair (i,j): current phase i, landing phase j drawn at
1036 * the start. The class memory variable holds the 1-based landing of the most recently
1037 * STARTED draw; a start from h enters pair (h,j) w.p. V(h,j) and sets it to j.
1038 *
1039 * A SINGLE server keeps the original law instead (`single`, no pairs), as the reference
1040 * does: the memory is the phase the last completion left the MAP in, a start enters it,
1041 * and while the class is in service the memory tracks the phase of that one job.
1042 */
1043template <class T>
1044struct CtmcMapc {
1045 std::size_t p = 0; ///< phases of the original MAP
1046 bool single = false; ///< c = 1: carried phase, no pairs
1047 std::vector<std::pair<std::size_t, std::size_t>> pairs; ///< 0-based (i,j), i-major, V(i,j) > 0
1048 Matrix<T> V; ///< landing law (-D0)^-1 D1
1049 std::vector<T> done; ///< completion rate D1(i,j)/V(i,j)
1050};
1051
1052/**
1053 * Refuses RENEGING on a class of finite population (`LINE:input:Model`; MATLAB `closedRenegingRefusal.m`, one
1054 * sentence for `set_patience`, the JSON reader that calls it, and `refresh_struct`). A renege REMOVES the waiting
1055 * job from the network, which a closed class cannot do: on Delay -> FCFS, N=4, Exp(0.5) patience, CTMC dropped the
1056 * transition while SSA, JMT and LDES destroyed jobs until the one in service was left (_kb/06, "Reneging is
1057 * open-class only"). `input`, not `unsupported`: no solver can help, so AUTO must not fall back.
1058 *
1059 * @param classname the class
1060 * @param where "" or ` at queue "<name>"`
1061 */
1062[[noreturn]] inline void closed_reneging_refusal(const std::string& classname, const std::string& where) {
1063 throw InputError(ErrorKind{"Model"},
1064 "Class \"" + classname + "\" is closed, but reneging" + where +
1065 " removes a waiting job from the network, which would change a closed population. Reneging "
1066 "is defined for open classes only; model the abandonment as a routing (e.g. a probabilistic "
1067 "exit back to the reference station) or use an open class.");
1068}
1069
1070/**
1071 * A network plus its refreshed NetworkStruct.
1072 *
1073 * The two halves are one object because every caller that mutates the model
1074 * (service processes, class populations, routing probabilities) re-derives the
1075 * struct, exactly as MATLAB's Network does through its cached `sn`. The refresh
1076 * entry points mirror the MATLAB ones and have the same granularity, which
1077 * matters for cost: `refresh_rates` is called on every outer iteration of
1078 * SolverLN for every layer, `refresh_chains` only where the routing changed.
1079 */
1080template <class T>
1082public:
1083 std::string name;
1084 /**
1085 * `Network.setLogPath` / `getLogPath`: the directory every Logger writes
1086 * into, and the `logPath` attribute of an exported JMT model.
1087 *
1088 * Model-level rather than per-Logger because that is where the reference
1089 * keeps it -- `Logger`'s constructor REFUSES when it is unset -- and
1090 * because the JSIM header carries one such path for the whole model.
1091 */
1092 std::string log_path;
1093 std::vector<NodeDef> nodes; ///< every node, in creation order
1094 std::vector<Station<T>> stations; ///< stations[k-1] is the k-th station
1095 std::vector<std::size_t> station_to_node; ///< (nstations) 1-based node index
1096 std::vector<std::size_t> stateful_nodes; ///< 1-based node indices, ascending
1097 std::vector<JobClass> classes;
1098 /** service[i][r], 0-based station and class; a disabled entry marks a pair never visited. */
1099 std::vector<std::vector<Distrib<T>>> service;
1100
1101 /**
1102 * Does (station i, class r) have a service law an analyzer may convert?
1103 * 0-based, and the ONLY correct precondition for `dist_to_map(service[i][r])`.
1104 *
1105 * `disabled` alone is not enough, and the gap is not hypothetical. It is the
1106 * twin of MATLAB's NaN-in-`sn.rates` sentinel, so it answers "does the class
1107 * visit this station". A JOIN is visited -- `refreshRates` gives it
1108 * `rates = Inf`, `scv = 0` -- and yet it has NO service law:
1109 * `refreshProcessRepresentations` hands it a `Coxian(NaN,NaN)`, which every
1110 * MATLAB analyzer then skips through a SECOND and separate `any(isnan(D0))`
1111 * guard. Rational has no NaN, so the C++ twin of that Coxian is a DISABLED
1112 * `Distrib`, and a guard that tests only `disabled[i][r] || rates <= 0` sails
1113 * past a Join (Inf > 0) straight into `dist_to_map`, which throws
1114 * "the distribution is disabled" with no station named. `fj_basic_open`
1115 * failed exactly this way under `-s mam`.
1116 *
1117 * So: `disabled[i][r]` is about the VISIT, `service[i][r].disabled` is about
1118 * the LAW, and a station can be visited without having one.
1119 */
1120 bool has_service_law(std::size_t i, std::size_t r) const {
1121 return !disabled[i][r] && !service[i][r].disabled;
1122 }
1123
1124 /**
1125 * Is station `i` (0-based) a QUEUEING PLACE, i.e. a Place with an embedded
1126 * queue? `Place.isQueueing()` in MATLAB.
1127 *
1128 * KEYED ON THE SERVICE LAW, not on the discipline, because that is the
1129 * reference's own rule: `Place.queueing` is raised by `setService` and by
1130 * nothing else, so a place constructed with a discipline and never given a
1131 * law is an ordinary place. The reverse cannot happen -- an ordinary place
1132 * carries a `ServiceTunnel` and no law -- so the two tests agree wherever
1133 * both are defined, and only this one survives the JSON round trip, where a
1134 * `queueing` flag would have to be carried separately and kept in step.
1135 */
1136 bool is_queueing_place(std::size_t i) const {
1137 if (i >= stations.size() || stations[i].nodetype != NodeType::Place) return false;
1138 for (std::size_t r = 0; r < service[i].size(); ++r)
1139 if (!service[i][r].disabled) return true;
1140 return false;
1141 }
1142
1143 /** Is 1-based node `ind` a FLUID place (`Place.setFluid`, MATLAB `sn.fluid(ind)`)? */
1144 bool is_fluid_node(std::size_t ind) const {
1145 if (ind == 0 || ind > nodes.size()) return false;
1146 const std::size_t st = nodes[ind - 1].station;
1147 return st > 0 && st <= stations.size() && stations[st - 1].nodetype == NodeType::Place &&
1148 stations[st - 1].fluid;
1149 }
1150 /** `sn_has_fluid_places`: does the net hold a fluid place, or a transition declaring a fluid arc? */
1151 bool has_fluid_places() const {
1152 for (const auto& s : stations)
1153 if (s.nodetype == NodeType::Place && s.fluid) return true;
1154 for (const auto& tp : transparam)
1155 if (tp.second.has_fluid_arcs()) return true;
1156 return false;
1157 }
1158 /** P[(r,s)] is an (nnodes x nnodes) block; absent means all zero. */
1159 std::map<std::pair<std::size_t, std::size_t>, Matrix<T>> P;
1160 /**
1161 * The routing after refresh_routing() has expanded the non-PROB strategies
1162 * and folded the class switches in. EMPTY when the expansion is the
1163 * identity, which is the case for every model whose routing is given as
1164 * probabilities and has no ClassSwitch node -- and then route_eff() reads P
1165 * directly, so the two representations never drift apart.
1166 */
1167 std::map<std::pair<std::size_t, std::size_t>, Matrix<T>> Peff;
1168 /**
1169 * Krzesinski (1987) product-form state-dependent routing, in 0-based
1170 * STATION indices; empty unless a node declares it with
1171 * `set_state_dep_routing`. Branch index 1 denotes the complement M-V and is
1172 * unused. `sdr_nodes` is the same structure in 0-based NODE indices.
1173 *
1174 * The routing is state dependent yet keeps a product form of its own, so
1175 * `sn_has_sd_routing` is true for it while the normalizing-constant solver
1176 * still accepts it. See _kb/16-state-dependent-routing.md
1177 */
1179 /** Node-indexed twin of `sdr`. */
1181 /** fj(f,j): the Join node j that closes the Fork node f, 1-based. */
1182 std::vector<std::pair<std::size_t, std::size_t>> fj;
1183 /**
1184 * `sn.isfjaugmented`: this struct came out of `fj_tag`, so its Fork nodes are
1185 * STATEFUL and its Join nodes carry a per-class sibling count instead of the
1186 * ordinary buffer/server split.
1187 *
1188 * It is a flag and not an inference from `fj` being non-empty, because the
1189 * un-augmented struct of the SAME model also has `fj` populated: what
1190 * distinguishes them is the auxiliary class block, and the event layer must
1191 * not take the Join branch before it exists.
1192 */
1193 bool isfjaugmented = false;
1194 /**
1195 * `sn.fjclassmap`: the ORIGINAL class of each auxiliary sibling class,
1196 * 0 for an original class. Empty unless `isfjaugmented`.
1197 */
1198 std::vector<std::size_t> fjclassmap;
1199 /**
1200 * `sn.fjauxclass`: (nclasses+1, 1-based) true where the class is an MMT
1201 * AUXILIARY OPEN class, i.e. one `fj_mmt` added to carry parallelism at rate
1202 * (fanout-1)*forkLambda. Such a class has infinite njobs but its arrivals come
1203 * from the finite closed population, so a finite-population correction still
1204 * applies to it. Empty on every struct the user's own model produces, and on
1205 * the H-T arm, whose auxiliary classes are CLOSED and need no such marker.
1206 * Distinct from `fjclassmap`/`isfjaugmented`, which describe the CTMC tag
1207 * augmentation.
1208 */
1209 std::vector<bool> fjauxclass;
1210 /**
1211 * `sn.nodeparam{j}.fj` for each Join node: the tag matrix and the required
1212 * sibling multiplicity `after_event_join` fires on. Declared as an opaque
1213 * map here and defined in `fj_tag.h`, which owns its layout.
1214 */
1215 std::map<std::size_t, FjJoinParam> fjjoinparam;
1216
1217 // ---- the Source/Sink pair, when the model has open classes -------------
1218 std::size_t sourceIdx = 0; ///< 1-based station index of the Source, 0 = none
1219 std::size_t sinkNode = 0; ///< 1-based NODE index of the Sink, 0 = none (it is not a station)
1220
1221 /** Cache parameters by 1-based NODE index; only Cache nodes have an entry. */
1222 std::map<std::size_t, CacheParam<T>> nodeparam;
1223 /**
1224 * Heterogeneous server pools rewritten for the CTMC, by 1-based NODE index.
1225 * Empty except on the private copy `ctmc::ctmc_pools` returns; the rotating
1226 * ALIS/FAIRNESS pool order, when present, is the single local variable
1227 * (`nvars` column 2R+1) and holds a 1-based index into `perms`.
1228 */
1229 std::map<std::size_t, CtmcPool<T>> ctmcpool;
1230 /**
1231 * MAP services in CTMC pair form, keyed by (1-based station, 1-based class). Empty except
1232 * on the private copy `ctmc::ctmc_mapc` returns; see `CtmcMapc`.
1233 */
1234 std::map<std::pair<std::size_t, std::size_t>, CtmcMapc<T>> ctmcmapc;
1235
1236 /**
1237 * The DECLARED initial state of a stateful node, by 1-based node index.
1238 *
1239 * `initmarking` is a Place's token count per class, which is the initial
1240 * marking of an SPN and is not derivable from anything else -- an SPN with
1241 * no tokens anywhere is a dead net, so dropping it changes the answer to
1242 * "nothing ever fires". `stateprior` and `statespace` are the pair MATLAB
1243 * writes together (`StatefulNode.statePrior` over `StatefulNode.space`):
1244 * the prior is a distribution over the ROWS of that space, so neither is
1245 * meaningful without the other and the reader refuses a lone one.
1246 */
1247 std::map<std::size_t, std::vector<T>> initmarking;
1248 std::map<std::size_t, std::vector<T>> stateprior;
1249 std::map<std::size_t, Matrix<T>> statespace;
1250
1251 /**
1252 * The DECLARED join rule of a Join node, by 1-based node index.
1253 *
1254 * STD waits for every sibling; PARTIAL fires on `quorum` of them. The
1255 * quorum is what `FjJoinParam::required` holds once the fork-join tagging
1256 * has run, but that runs on the augmented struct: this is the declaration
1257 * as the model.json carries it, so the two do not replace each other.
1258 */
1259 struct JoinDecl {
1261 double quorum = 0.0; ///< 0 = every sibling
1262 };
1263 std::map<std::size_t, JoinDecl> joindecl;
1264
1265 /** Variable forking levels, by 1-based Fork node; absent on a plain fork. */
1266 std::map<std::size_t, ForkParam<T> > forkparam;
1267
1268 /** The fork's override block, or null when it declares none. */
1269 const ForkParam<T>* fork_param_of(std::size_t node) const {
1270 const typename std::map<std::size_t, ForkParam<T> >::const_iterator it =
1271 forkparam.find(node);
1272 return it == forkparam.end() ? static_cast<const ForkParam<T>*>(0) : &it->second;
1273 }
1274
1275 /**
1276 * `sn.reward`: the user-declared reward functions, MATLAB's
1277 * `model.setReward(name, fn)`.
1278 *
1279 * `fn` is evaluated on the AGGREGATE state row -- the per-(station, class)
1280 * job counts in `(ist-1)*K + k` order, which is what
1281 * `ctmc_state_space_aggr` builds -- and not on the detailed state. That is
1282 * the reference's `RewardState` contract, and it is what makes a reward
1283 * portable across disciplines: the caller writes `state[q]` for a queue
1284 * length without having to know whether the buffer stores class tags or
1285 * per-class counts.
1286 */
1287 struct Reward {
1288 std::string name;
1289 std::function<T(const std::vector<T>&)> fn;
1290 /**
1291 * The DECLARATIVE form the reward was built from, when it was: the
1292 * template name (QLen, Util, Blocking), the 1-based node it is declared
1293 * at, and the 1-based class it covers (0 = every class).
1294 *
1295 * A lambda cannot be written back out, so a reward built from one has
1296 * an empty `kind` and the writer omits it -- which is what
1297 * `linemodel_save` does, with a warning, rather than emitting a
1298 * definition that would be wrong on reload.
1299 */
1300 std::string kind;
1301 std::size_t node = 0;
1302 std::size_t cls = 0;
1303 };
1304 std::vector<Reward> reward;
1305
1306 /**
1307 * FINITE CAPACITY REGIONS, MATLAB's `refreshRegions` output.
1308 *
1309 * A region caps the jobs (and the memory) held ACROSS a set of stations,
1310 * which no per-station capacity can express: three stations each able to
1311 * hold 5 jobs but at most 6 between them is a region, not three caps.
1312 *
1313 * `cap(i,r)` is the class-r bound at station i, `cap(i,K)` the station's
1314 * global bound, and -1 means unbounded -- the reference's sentinel, kept
1315 * rather than translated to infinity because it is compared with `~= -1`
1316 * to test MEMBERSHIP as well as boundedness.
1317 *
1318 * `rule(r)` decides what an arrival that would violate the region does:
1319 * DROP loses it, WAITQ parks it outside every station's own queue, which is
1320 * why the CTMC needs a separate waiting-room state per region and not just
1321 * a filter on the enumerated space.
1322 */
1323 struct Region {
1324 /** The region's declared name, as the wire carries it; a generated one otherwise. */
1325 std::string name;
1326 std::vector<std::vector<double>> cap; ///< (nstations x nclasses+1), -1 = unbounded
1327 std::vector<double> maxmem; ///< per member station, -1 = unbounded
1328 std::vector<bool> members; ///< membership, independent of the caps
1329 std::vector<DropStrategy> rule; ///< per class
1330 std::vector<T> weight, size; ///< per class; size is the memory footprint
1331 Matrix<T> lincon_A; ///< optional linear constraint A n <= b
1332 std::vector<T> lincon_b;
1333 };
1334 std::vector<Region> regions;
1335 /** Transition (SPN) parameters, keyed by 1-based node index. */
1336 std::map<std::size_t, TransitionParam<T>> transparam;
1337 /** Retrial parameters, keyed by 1-based STATION index. */
1338 std::map<std::size_t, RetrialParam<T>> retrialparam;
1339 /**
1340 * Setup / delay-off, keyed by 1-based STATION index.
1341 *
1342 * Presence IS MATLAB's `sn.hassetup(ist)`: the reference sets that flag
1343 * from `~isempty(station.setupTime)`, so a station appears here exactly
1344 * when it is a setup task's server.
1345 */
1346 std::map<std::size_t, SetupDelayOffParam<T>> setupparam;
1347 /**
1348 * Server breakdown / repair, keyed by 1-based STATION index.
1349 *
1350 * Presence IS MATLAB's `sn.hasbreakdown(node)`, which the reference sets
1351 * from `~isempty(node.breakdownFailure) && ~isempty(node.breakdownRepair)`
1352 * -- BOTH, since a server that fails and is never repaired is a different
1353 * model and the reference declines to infer one.
1354 */
1355 std::map<std::size_t, BreakdownParam<T>> breakdownparam;
1356
1357 /** `sn.hasbreakdown(ind)`: does the NODE's server break down? */
1358 bool has_breakdown_node(std::size_t ind) const {
1359 if (ind == 0 || ind > nodes.size()) return false;
1360 const std::size_t ist = nodes[ind - 1].station;
1361 return ist != 0 && breakdownparam.find(ist) != breakdownparam.end();
1362 }
1363 /** Any station at all, the guard every solver gate needs first. */
1364 bool has_breakdown() const { return !breakdownparam.empty(); }
1365 /**
1366 * The class-switch matrix of a ClassSwitch node, by 1-based NODE index.
1367 *
1368 * (nclasses x nclasses), row-stochastic. It is applied on the way OUT of
1369 * the node, exactly as MATLAB's ClassSwitch does, and the node is not
1370 * stateful, so the stochastic complement folds it into the edges around it.
1371 */
1372 std::map<std::size_t, Matrix<T>> csmatrix;
1373
1374 // ---- refreshed struct -------------------------------------------------
1375 std::size_t nstations = 0, nclasses = 0, nchains = 0;
1376 /**
1377 * `sn.gdscaling`: the network-level globally state-dependent (Whittle)
1378 * rate scaling phi(n). Its argument is the FULL (nstations x nclasses)
1379 * population matrix in row-major order, NOT one station's slice, so unlike
1380 * `Station::jdscaling` it lives on the struct rather than on a station.
1381 * Empty when the model declares none. See `set_global_dependence`.
1382 */
1384 /**
1385 * `sn.gdscalingpeak`: the declared (nstations x nclasses) peak of
1386 * `gdscaling`, row-major, used to report Util = T*S/peak.
1387 */
1388 std::vector<T> gdscalingpeak;
1389 /**
1390 * `sn.gdscalingcutoff`: the per-slot OPEN-class truncation used when
1391 * `gdscaling` is materialized onto the JSON wire (closed classes are
1392 * tabulated up to their own population). Solving ignores it entirely.
1393 */
1395 /**
1396 * (nstations x nclasses) service rates and SCVs, with a PARALLEL disabled
1397 * flag instead of MATLAB's NaN sentinel.
1398 *
1399 * MATLAB writes NaN into sn.rates for a (station, class) pair the class
1400 * never visits, and every consumer tests isnan. Rational has no NaN -- it
1401 * is a field, not a floating-point format -- so the marker has to be
1402 * carried out of band or the exact instantiation could not represent a
1403 * disabled pair at all. The flag is the marker; rates and scv hold zero
1404 * there, and no consumer may read them without consulting `disabled`.
1405 */
1407 std::vector<std::vector<bool>> disabled;
1408
1409 /**
1410 * `sn.immfeed`: (nstations x nclasses) IMMEDIATE FEEDBACK, the reference's
1411 * `refreshStruct` field.
1412 *
1413 * A job of class r completing at station i is fed straight back into
1414 * service, HOLDING THE SERVER, instead of being routed out and re-queued.
1415 * The flag is the OR of the station's own setting (Queue only) and the
1416 * class-level one, exactly as MATLAB `@@MNetwork/refreshStruct.m` computes
1417 * it, so either spelling reaches the same matrix.
1418 *
1419 * IT IS NOT A `Feature`, deliberately. `feature_name` is byte-for-byte the
1420 * MATLAB registry field name, and the reference has no such entry: MVA and
1421 * NC WARN that they approximate it as class-switching with re-queueing,
1422 * while CTMC and SSA implement the sample-path semantics. Making it a
1423 * feature would invent a name no other codebase carries and would turn the
1424 * reference's warning into a refusal.
1425 */
1426 std::vector<std::vector<bool>> immfeed;
1427 std::vector<std::vector<bool>> chains; ///< (nchains x nclasses)
1428 std::vector<std::vector<bool>> csmask; ///< (nclasses x nclasses) class r can switch into s, diagonal set
1429 std::vector<std::vector<std::size_t>> inchain;///< 1-based class indices per chain
1430 std::vector<std::size_t> refclass; ///< (nchains) 1-based class, 0 = none
1431 std::vector<Matrix<T>> visits; ///< (nchains) each (nstateful x nclasses)
1432 std::vector<Matrix<T>> nodevisits; ///< (nchains) each (nnodes x nclasses)
1433
1434 /**
1435 * `sn.cap` and `sn.classcap`: the total and per-class buffers.
1436 *
1437 * Derived by refresh_capacity() from the station capacities and the chain
1438 * populations, exactly as MATLAB's refreshCapacity does, so a station with
1439 * no explicit capacity still carries the population bound of the chains
1440 * that reach it.
1441 */
1442 std::vector<double> cap;
1443 std::vector<std::vector<double>> classcap;
1444 std::vector<std::vector<DropStrategy>> droprule;
1445
1446 /**
1447 * `sn.rt` and `sn.rtnodes`: the class-expanded routing.
1448 *
1449 * rt is (nstateful*nclasses) square over the STATEFUL nodes -- the
1450 * stochastic complement that removes Fork, ClassSwitch and Router nodes --
1451 * and rtnodes is (nnodes*nclasses) square over every node. Row (i-1)*K + r
1452 * is node i in class r, which is MATLAB's ordering.
1453 */
1455
1456 /**
1457 * `sn.nvars`, (nnodes x 3R+1): the LOCAL VARIABLE columns each node appends
1458 * to its state, beyond the buffer and the servers. Layout, verbatim from
1459 * refreshLocalVars:
1460 *
1461 * 1 .. R modulating phase, one per class with a MAP/MMPP2 process
1462 * R+1 .. 2R routing variable, one per class routed round-robin
1463 * 2R+1 the SHARED node block: cache width, or the BAS held-job
1464 * block (one counter per target code, `bas_ncols` wide,
1465 * BUG-110), or the breakdown status, or the polling
1466 * controller. They share one slot and are therefore
1467 * mutually exclusive -- refreshLocalVars rejects the
1468 * combinations rather than widening the state.
1469 * 2R+1+r the REPLY blocked-server counter for calling class r
1470 *
1471 * The trailing sum(nvars(ind,:)) columns are what every state slicer must
1472 * take clear of before reading the server block.
1473 */
1474 std::vector<std::vector<std::size_t>> nvars;
1475
1476 /**
1477 * `sn.isbasblocking`, per NODE: true where the node is the BLOCKING
1478 * (upstream) side of a true-BAS relation and therefore carries the held-job
1479 * block in `nvars` column 2R+1: one counter per target code
1480 * (`bas_marker_codes`), how many completed jobs wait here for room at that
1481 * destination. It was a single {0,1} marker before BUG-110, which could not
1482 * hold a second completed job at a multi-server station.
1483 *
1484 * TRUE BAS is not a drop rule, it is a HELD JOB. Under blocking after
1485 * service the job that finished at this station cannot leave because its
1486 * destination is full; it stays at the server, occupying it, until room
1487 * frees. That needs a state bit -- "the front job here is completed and
1488 * waiting" -- which no queue length can express, and it is what separates
1489 * BAS from DROP (where the arrival is lost) and from WAITQ (where the
1490 * arrival waits at the region gate instead).
1491 *
1492 * IT IS KEYED ON THE NODE, NOT ON THE DROP RULE, and the distinction is
1493 * load-bearing. BAS may be DECLARED on either side: upstream, on the station
1494 * that will hold the job, or on the full destination (the JMT/LDES
1495 * convention). Both resolve to the same blocking station, because the held
1496 * job sits upstream either way, so keying enumeration on the station's own
1497 * `droprule` misses every destination-declared model.
1498 */
1499 std::vector<bool> isbasblocking;
1500 /**
1501 * `sn.isbasdestination`, (nstations x nclasses): true where a refusal at
1502 * this station must BLOCK an upstream BAS station rather than drop the job.
1503 *
1504 * `arrival_is_lost` needs it because it sees only the station where the
1505 * refusal happens. Under the upstream declaration form that station carries
1506 * no BAS rule of its own, so without this mask an open class refused there
1507 * would be declared lost, the become-blocked edge would never fire, and the
1508 * blocking station would behave as if its destination were unbounded.
1509 */
1510 std::vector<std::vector<bool>> isbasdestination;
1511
1512 /**
1513 * The pass-and-swap / order-independent parameters of a PAS station, keyed
1514 * by station index (Dorsman and Gardner 2024, Sect. 2).
1515 *
1516 * `svc_rate_fun` is the total service rate mu(c) of an ordered list of
1517 * class indices; the rate of the token at position p is the INCREMENT
1518 * mu(c1..cp) - mu(c1..c_{p-1}), which is what makes the station
1519 * order-independent. `swap_graph` is the (R x R) adjacency saying which
1520 * class may take another's place. An OI station is the special case of an
1521 * empty swap graph.
1522 */
1523 struct PasParam {
1524 std::function<T(const std::vector<std::size_t>&)> svc_rate_fun;
1525 std::vector<std::vector<bool>> swap_graph;
1526 };
1527 std::map<std::size_t, PasParam> pasparam;
1528
1529 /**
1530 * `sn.replyblock` (nnodes x nclasses) and `sn.syncreply` (nclasses).
1531 *
1532 * A SYNCHRONOUS call: a job of a calling class leaves this station for the
1533 * callee but KEEPS its server, released only when the matching REPLY class
1534 * arrives back. `replyblock` marks the (node, calling class) pairs that
1535 * hold such a server, and `syncreply[r]` is the 1-based reply class the
1536 * calling class r expects (0 = none). A CTMC has no job identity to key on
1537 * as LDES does, so the state carries COUNTS of held servers.
1538 */
1539 std::vector<std::vector<bool>> replyblock;
1540 std::vector<std::size_t> syncreply;
1541
1542 /**
1543 * The polling controller of a POLLING station, keyed by station index.
1544 *
1545 * `switchover[r]` is the walk OUT of buffer r: the leg charged to the
1546 * buffer the server LEAVES, i.e. from r to the next POLLED buffer in cyclic
1547 * order (Takagi's r_i, `Queue.setSwitchover(class_r, d)`). The controller
1548 * indexes its states by DESTINATION, so `polling_info` shifts it once onto
1549 * the polled buffer that follows r. An Immediate switchover is NOT represented as
1550 * a state: taking its ~1e8 rate literally would make the generator stiff
1551 * and add a spurious state per buffer, so `pollingNext` folds it into the
1552 * enclosing transition instead.
1553 */
1556 std::size_t pk = 1; ///< the K of K-LIMITED
1557 std::vector<lang::Distrib<T>> switchover;
1558 /// The extensions, as the Station fields of the same names.
1559 std::vector<std::size_t> table;
1560 std::vector<lang::Distrib<T>> table_sw;
1562 std::size_t order_class = 0;
1565 bool timer_preempt = false;
1566 std::vector<lang::Distrib<T>> timer;
1567 };
1568 std::map<std::size_t, PollingParam> pollingparam;
1569
1570 /**
1571 * The polling controller of station `ist`, from whichever API declared it.
1572 *
1573 * TWO APIS WRITE THE SAME CONTROLLER. `set_polling` fills `pollingparam`;
1574 * `Queue.setPollingType` / `Queue.setSwitchover` -- the MATLAB-faithful pair
1575 * the JSON reader also uses -- fill `Station::polling_type`, `switchover`
1576 * and `polling_par`. Reading only the first left a station built the second
1577 * way with NO controller at all, which is not a degraded model but an
1578 * unrepresentable one: the state handlers then index an empty `polled`.
1579 *
1580 * A POLLING station that declares neither still HAS a controller, exactly as
1581 * `State.pollingInfo` builds one: EXHAUSTIVE service, every switchover
1582 * immediate. That is a discipline, not an absence.
1583 */
1584 PollingParam effective_polling(std::size_t ist) const {
1585 PollingParam pp;
1586 if (ist == 0 || ist > stations.size()) return pp;
1587 const typename std::map<std::size_t, PollingParam>::const_iterator it =
1588 pollingparam.find(ist);
1589 const Station<T>& st = stations[ist - 1];
1590 if (it != pollingparam.end()) {
1591 pp = it->second;
1592 } else {
1593 if (!st.polling_type.empty()) {
1594 pp.ptype = st.polling_type[0];
1596 pp.pk = static_cast<std::size_t>(st.polling_par);
1597 }
1598 pp.switchover = st.switchover;
1599 }
1600 // The extensions are written only to the Station, by either API.
1601 pp.table = st.polling_table;
1602 pp.table_sw = st.polling_table_sw;
1603 pp.order = st.polling_order;
1608 pp.timer = st.polling_timer;
1609 return pp;
1610 }
1611
1612 /**
1613 * The switchover law of leg `l` (1-based) of station `ist`'s controller, as
1614 * `State.pollingInfo` resolves it, or nullptr when the leg is immediate.
1615 * Legs are indexed by the position (or, under a load-dependent order, the
1616 * class) the server ARRIVES at: under a table, the leg into position l is
1617 * the walk out of position l-1 (its table switchover, else the class
1618 * switchover of that entry); in cyclic order, the class switchover of the
1619 * previous polled class; under a load-dependent order, the walk OUT of
1620 * class l. Shared by polling_info and the controller width.
1621 */
1622 const lang::Distrib<T>* polling_leg(std::size_t ist, const PollingParam& pp,
1623 std::size_t l) const {
1624 const std::vector<bool> polled = polling_polled(ist);
1625 const std::size_t R = polled.size();
1626 std::size_t src = 0;
1627 const lang::Distrib<T>* d = nullptr;
1629 if (l > R || !polled[l - 1]) return nullptr;
1630 src = l;
1631 } else if (!pp.table.empty()) {
1632 const std::size_t M = pp.table.size();
1633 const std::size_t pr = (l + M - 2) % M + 1;
1634 if (pr <= pp.table_sw.size() && !pp.table_sw[pr - 1].disabled)
1635 d = &pp.table_sw[pr - 1];
1636 else
1637 src = pp.table[pr - 1];
1638 } else {
1639 if (l > R || !polled[l - 1]) return nullptr;
1640 std::vector<std::size_t> pl;
1641 for (std::size_t r = 1; r <= R; ++r)
1642 if (polled[r - 1]) pl.push_back(r);
1643 std::size_t jj = 0;
1644 while (pl[jj] != l) ++jj;
1645 src = pl[(jj + pl.size() - 1) % pl.size()];
1646 }
1647 if (d == nullptr) {
1648 if (src == 0 || src > pp.switchover.size()) return nullptr;
1649 d = &pp.switchover[src - 1];
1650 }
1651 if (d->disabled || d->type == ProcessType::IMMEDIATE) return nullptr;
1652 if (lang::process_is_markovian(d->type) && d->D0.rows() == 0) return nullptr;
1653 return d;
1654 }
1655
1656 /** Number of controller legs: the table length, else R. */
1657 std::size_t polling_nlegs(const PollingParam& pp) const {
1658 if (pp.order == lang::PollingOrder::CYCLIC && !pp.table.empty()) return pp.table.size();
1659 return nclasses;
1660 }
1661
1662 /**
1663 * The controller width, `pinfo.width`: [pos, swk, ctr, src, tht, trt_1..R]
1664 * with each column materialized only when the configuration needs it.
1665 */
1666 std::size_t polling_width(std::size_t ist) const {
1667 const PollingParam pp = effective_polling(ist);
1668 const std::size_t L = polling_nlegs(pp);
1669 const bool ld = pp.order != lang::PollingOrder::CYCLIC;
1670 bool anysw = false;
1671 std::vector<const lang::Distrib<T>*> legs(L, nullptr);
1672 for (std::size_t l = 1; l <= L; ++l) {
1673 legs[l - 1] = polling_leg(ist, pp, l);
1674 anysw = anysw || legs[l - 1] != nullptr;
1675 }
1676 bool repeats = false;
1677 if (!ld && !pp.table.empty()) {
1678 std::vector<std::size_t> u = pp.table;
1679 std::sort(u.begin(), u.end());
1680 repeats = std::unique(u.begin(), u.end()) != u.end();
1681 }
1682 bool distinct = false;
1683 if (ld) {
1684 const lang::Distrib<T>* first = nullptr;
1685 for (std::size_t l = 0; l < L && !distinct; ++l) {
1686 if (legs[l] == nullptr) continue;
1687 if (first == nullptr) { first = legs[l]; continue; }
1688 distinct = polling_leg_differs(*first, *legs[l]);
1689 }
1690 }
1691 std::size_t w = 0;
1692 if (anysw || repeats) w += 1;
1693 if (anysw) w += 1;
1694 if (pp.ptype != lang::PollingType::EXHAUSTIVE) w += 1;
1695 if (distinct) w += 1;
1696 if (pp.timer_scope != lang::PollingTimer::NONE) w += 1;
1698 const std::vector<bool> polled = polling_polled(ist);
1699 for (bool b : polled) w += b ? 1 : 0;
1700 }
1701 return w;
1702 }
1703
1704 /** True when two timed legs are not the same law (`distinctLaws`). */
1707 if (a.D0.rows() != b.D0.rows() || a.D0.cols() != b.D0.cols()) return true;
1708 for (std::size_t i = 0; i < a.D0.rows(); ++i)
1709 for (std::size_t j = 0; j < a.D0.cols(); ++j)
1710 if (a.D0(i, j) != b.D0(i, j) || a.D1(i, j) != b.D1(i, j)) return true;
1711 return false;
1712 }
1713
1714 /**
1715 * The buffers a polling server at station `ist` actually visits, as
1716 * `State.pollingInfo` builds `pinfo.polled`: a class whose service is
1717 * disabled here can never hold a job, so it is dropped from the cyclic
1718 * order. Shared by `polling_info` and `refresh_local_vars`, which must
1719 * agree on it: the controller WIDTH is derived from the switchovers of the
1720 * polled buffers only, and sizing nvars over every class reserved pos/swk
1721 * columns for a non-immediate switchover declared on a disabled class that
1722 * `polling_info` (and MATLAB) never materialize.
1723 */
1724 std::vector<bool> polling_polled(std::size_t ist) const {
1725 const std::size_t R = nclasses;
1726 std::vector<bool> polled(R, true);
1727 for (std::size_t r = 1; r <= R; ++r)
1728 if ((ist - 1 < disabled.size() && r - 1 < disabled[ist - 1].size() &&
1729 disabled[ist - 1][r - 1]) ||
1730 phases_of(ist, r) == 0)
1731 polled[r - 1] = false;
1732 return polled;
1733 }
1734
1735 /**
1736 * True when some POLLED buffer of station `ist` declares a non-immediate
1737 * switchover, i.e. when the controller materializes its pos and swk
1738 * columns (`pinfo.wpos`/`pinfo.wswk`). Every polled buffer is the source of
1739 * exactly one leg of the cycle, so this is `any(pinfo.hasSw)`.
1740 */
1741 bool polling_has_timed_switchover(std::size_t ist, const PollingParam& pp) const {
1742 const std::vector<bool> polled = polling_polled(ist);
1743 for (std::size_t r = 0; r < polled.size() && r < pp.switchover.size(); ++r) {
1744 if (!polled[r]) continue;
1745 const lang::Distrib<T>& d = pp.switchover[r];
1746 // A non-Markovian leg is timed whether or not it carries a D0 (a
1747 // Det from the builder has none): polling_info sizes it as one
1748 // placeholder phase, and the two must agree on the width.
1749 if (!d.disabled && d.type != ProcessType::IMMEDIATE &&
1750 (d.D0.rows() > 0 || !lang::process_is_markovian(d.type)))
1751 return true;
1752 }
1753 return false;
1754 }
1755
1756 /**
1757 * The G-network signal declaration, per CLASS. `issignal` is the gate: the
1758 * remaining vectors are only read where it is true.
1759 *
1760 * `signaltarget` is the 1-based class a NEGATIVE signal may remove, or 0
1761 * for the classic untargeted Gelenbe customer, which is eligible against
1762 * every non-signal class. `signalremdist` is the batch-size pmf indexed by
1763 * batch size 0,1,2,...; an empty entry means "remove exactly one".
1764 */
1765 std::vector<bool> issignal;
1766 std::vector<lang::SignalType> signaltype;
1767 std::vector<std::size_t> signaltarget;
1768 std::vector<lang::RemovalPolicy> signalrempolicy;
1769 std::vector<std::vector<T>> signalremdist;
1770
1771 /** Total local-variable width of node `ind` (1-based). */
1772 std::size_t nvars_of(std::size_t ind) const {
1773 // A node index is 1-BASED, so 0 means "no node" and must return 0. The
1774 // old guard `nvars.size() < ind` is vacuously false at ind == 0 because
1775 // both sides are unsigned, and the loop below then indexed nvars[-1]:
1776 // heap corruption, surfacing as a SIGABRT far from here.
1777 if (ind == 0 || ind > nvars.size()) return 0;
1778 std::size_t w = 0;
1779 for (std::size_t j = 0; j < nvars[ind - 1].size(); ++j) w += nvars[ind - 1][j];
1780 return w;
1781 }
1782
1783 std::size_t nof_stations() const { return stations.size(); }
1784 std::size_t nof_classes() const { return classes.size(); }
1785 std::size_t nof_nodes() const { return nodes.size(); }
1786 std::size_t nof_stateful() const { return stateful_nodes.size(); }
1787
1788 /** `sn.njobs`: the population of each class, infinite for an open one. */
1789 std::vector<double> njobs() const {
1790 std::vector<double> v;
1791 v.reserve(classes.size());
1792 for (const JobClass& c : classes) v.push_back(c.population);
1793 return v;
1794 }
1795
1796 /** `sn.nclosedjobs`: the total population of the closed classes. */
1797 double nclosedjobs() const { return total_jobs(); }
1798
1799 // -----------------------------------------------------------------------
1800 // MATLAB-SHAPED VIEWS of the fields this port derives instead of storing.
1801 //
1802 // Each accessor below assembles one whole `sn` field in MATLAB's layout and
1803 // values (refreshStruct.m, refreshProcessPhases.m,
1804 // refreshProcessRepresentations.m, refreshProcessTypes.m, refreshLST.m), so
1805 // the NetworkStruct contract (sn_contract.h) can place the field on it. They
1806 // are computed on demand from the stored records, as the per-element
1807 // accessors (`phases_of`, `procid(i,r)`, `stateful_index`...) already are,
1808 // and are never stored beside them. Indices are 1-based and NaN marks "none",
1809 // as in MATLAB. They are views for the contract and for parity checks; the
1810 // engines keep reading the per-element accessors, and two of those differ
1811 // from the MATLAB field on purpose -- see `phases()` and `phasessz()`.
1812 // -----------------------------------------------------------------------
1813
1814 /** `sn.nregions`: the number of finite capacity regions. */
1815 std::size_t nregions() const { return regions.size(); }
1816
1817 /** `sn.nodeToStateful` (1 x N): the stateful index of each node, NaN when it is not stateful. */
1818 std::vector<double> node_to_stateful() const {
1819 std::vector<double> v(nodes.size(), std::nan(""));
1820 for (std::size_t k = 0; k < stateful_nodes.size(); ++k)
1821 if (stateful_nodes[k] >= 1 && stateful_nodes[k] <= nodes.size())
1822 v[stateful_nodes[k] - 1] = static_cast<double>(k + 1);
1823 return v;
1824 }
1825
1826 /** `sn.stationToStateful` (1 x M): the stateful index of each station. */
1827 std::vector<double> station_to_stateful() const {
1828 const std::vector<double> nsf = node_to_stateful();
1829 std::vector<double> v(nstations, std::nan(""));
1830 for (std::size_t ist = 1; ist <= nstations && ist <= station_to_node.size(); ++ist) {
1831 const std::size_t nd = station_to_node[ist - 1];
1832 if (nd >= 1 && nd <= nsf.size()) v[ist - 1] = nsf[nd - 1];
1833 }
1834 return v;
1835 }
1836
1837 /** `sn.statefulToStation` (1 x S): the station index of each stateful node, NaN when it is not a station. */
1838 std::vector<double> stateful_to_station() const {
1839 std::vector<double> v(stateful_nodes.size(), std::nan(""));
1840 for (std::size_t k = 0; k < stateful_nodes.size(); ++k) {
1841 const std::size_t nd = stateful_nodes[k];
1842 if (nd >= 1 && nd <= nodes.size() && nodes[nd - 1].station != 0)
1843 v[k] = static_cast<double>(nodes[nd - 1].station);
1844 }
1845 return v;
1846 }
1847
1848 /**
1849 * `sn.connmatrix` (N x N): 1 where some class routes node i to node j with
1850 * positive probability. MATLAB records each such arc through `addLink` as
1851 * `link` installs P; this port keeps P itself, so the arcs are read off it,
1852 * the same class-independent topology `refresh_routing` builds for the
1853 * RAND/RROBIN spreads. The Sink -> Source arcs are left out: they are the
1854 * open-chain closure `apply_sink_closure` writes into P, which the reference
1855 * adds after link.m has recorded its links, so they never reach its matrix.
1856 */
1858 const std::size_t I = nodes.size();
1859 const T zero = num_traits<T>::from_int(0);
1860 Matrix<double> c(I, I, 0.0);
1861 for (const auto& kv : P) {
1862 const Matrix<T>& B = kv.second;
1863 if (B.rows() < I || B.cols() < I) continue; // get_route reads such a block as zero
1864 for (std::size_t a = 0; a < I; ++a)
1865 for (std::size_t b = 0; b < I; ++b)
1866 if (B(a, b) > zero &&
1867 !(nodes[a].nodetype == NodeType::Sink && nodes[b].nodetype == NodeType::Source))
1868 c(a, b) = 1.0;
1869 }
1870 return c;
1871 }
1872
1873 /**
1874 * `sn.isstatedep` (N x 3): column 1 the input section (never set by the
1875 * reference), column 2 state-dependent service (a Cache), column 3
1876 * state-dependent routing (RROBIN, WRROBIN, JSQ, SQ, SDR for some class).
1877 */
1879 const std::size_t I = nodes.size();
1880 Matrix<double> m(I, 3, 0.0);
1881 for (std::size_t ind = 0; ind < I; ++ind) {
1882 if (nodes[ind].nodetype == NodeType::Cache) m(ind, 1) = 1.0;
1883 for (RoutingStrategy rs : nodes[ind].routing)
1884 if (rs == RoutingStrategy::RROBIN || rs == RoutingStrategy::WRROBIN || rs == RoutingStrategy::JSQ ||
1885 rs == RoutingStrategy::SQ || rs == RoutingStrategy::SDR)
1886 m(ind, 2) = 1.0;
1887 }
1888 return m;
1889 }
1890
1891 /** `sn.hasbreakdown` (N x 1): 1 where the node's server is subject to breakdowns. */
1892 std::vector<double> hasbreakdown() const {
1893 std::vector<double> v(nodes.size(), 0.0);
1894 for (std::size_t ind = 1; ind <= nodes.size(); ++ind)
1895 if (has_breakdown_node(ind)) v[ind - 1] = 1.0;
1896 return v;
1897 }
1898
1899 /** `sn.iscatastrophe` (K x 1): true where class r is a catastrophe signal. */
1900 std::vector<bool> iscatastrophe() const {
1901 std::vector<bool> v(nclasses, false);
1902 for (std::size_t r = 0; r < nclasses && r < signaltype.size(); ++r)
1903 v[r] = r < issignal.size() && issignal[r] && signaltype[r] == lang::SignalType::CATASTROPHE;
1904 return v;
1905 }
1906
1907 /**
1908 * `sn.procid` (M x K): the ProcessType id of each (station, class) pair, as
1909 * `refreshProcessTypes.m` writes it: a Join serves IMMEDIATE (its server is a
1910 * ServiceTunnel the reference names so), an ordinary Place is NaN (a
1911 * ServiceTunnel the reference leaves unset), every other pair the type of its
1912 * law. The ids are this port's enum values, which are MATLAB's.
1913 */
1915 Matrix<double> m(nstations, nclasses, std::nan(""));
1916 for (std::size_t i = 0; i < nstations && i < service.size(); ++i)
1917 for (std::size_t r = 0; r < nclasses && r < service[i].size(); ++r) {
1918 if (stations[i].nodetype == NodeType::Join)
1919 m(i, r) = static_cast<double>(static_cast<int>(ProcessType::IMMEDIATE));
1920 else if (stations[i].nodetype == NodeType::Place && !is_queueing_place(i))
1921 continue;
1922 else
1923 m(i, r) = static_cast<double>(static_cast<int>(service[i][r].type));
1924 }
1925 return m;
1926 }
1927
1928 private:
1929 /** Is (0-based i, r) a pair whose law MATLAB's getServiceRates has no arm for (an empty `sn.proc` entry)? */
1930 bool proc_is_empty(std::size_t i, std::size_t r) const {
1931 const Distrib<T>& d = service[i][r];
1932 if (d.disabled) return stations[i].nodetype == NodeType::Place && !is_queueing_place(i);
1933 return d.is_prior();
1934 }
1935 /** Is (0-based i, r) a pair whose `sn.proc` entry is MATLAB's disabled `{NaN, NaN}`? */
1936 bool proc_is_nan(std::size_t i, std::size_t r) const {
1937 return service[i][r].disabled && !proc_is_empty(i, r);
1938 }
1939 /** The (D0, D1, D_k...) of `sn.proc{i}{r}` after refreshProcessRepresentations' Erlang conversion. */
1940 std::vector<Matrix<T>> proc_blocks(std::size_t i, std::size_t r) const {
1941 const Distrib<T>& d = service[i][r];
1942 std::vector<Matrix<T>> b;
1943 if (d.has_map()) {
1944 b.push_back(d.D0);
1945 b.push_back(d.D1);
1946 for (const Matrix<T>& Dk : d.Dmark) b.push_back(Dk);
1947 } else {
1948 const mam::Map<T> m = lang::dist_to_map(d);
1949 b.push_back(m.D0);
1950 b.push_back(m.D1);
1951 }
1952 return b;
1953 }
1954
1955 public:
1956 /**
1957 * `sn.phases` (M x K), as refreshProcessRepresentations.m leaves it: 0 for a
1958 * disabled pair, 1 for an empty entry (an ordinary Place, a Prior) and for an
1959 * NHPP (and an NNPP), the order of the representation otherwise -- which for a
1960 * non-Markovian law is the order of its Erlang conversion (`dist_to_map`).
1961 * `phases_of(i, r)` answers 1 for such a law instead, because this port
1962 * converts it only when a solver asks (sn_nonmarkov_toph.h); the two agree on
1963 * every Markovian law.
1964 */
1967 for (std::size_t i = 0; i < nstations && i < service.size(); ++i)
1968 for (std::size_t r = 0; r < nclasses && r < service[i].size(); ++r) {
1969 const Distrib<T>& d = service[i][r];
1970 if (proc_is_empty(i, r) || d.type == ProcessType::NHPP || d.type == ProcessType::NNPP)
1971 m(i, r) = 1.0;
1972 else if (!d.disabled)
1973 m(i, r) = static_cast<double>(proc_blocks(i, r)[0].rows());
1974 }
1975 return m;
1976 }
1977
1978 /**
1979 * `sn.phasessz` (M x K) = max(phases, 1), with MATLAB's two exceptions: a
1980 * Join keeps its 0 and a non-carrier mark of a marked arrival is 1. The
1981 * engines size their state rows with `phasessz_of`, which gives a Join 1 and
1982 * is built on `phases_of` (see `phases()`).
1983 */
1985 Matrix<double> m = phases();
1986 for (std::size_t i = 0; i < m.rows(); ++i)
1987 for (std::size_t r = 0; r < m.cols(); ++r) {
1988 if (stations[i].nodetype != NodeType::Join && m(i, r) < 1.0) m(i, r) = 1.0;
1989 if (markidx_of(i + 1, r + 1) > 1) m(i, r) = 1.0;
1990 }
1991 return m;
1992 }
1993
1994 /** `sn.phaseshift` (M x K+1) = [0, cumsum(phasessz, 2)]. */
1996 const Matrix<double> sz = phasessz();
1997 Matrix<double> m(sz.rows(), sz.cols() + 1, 0.0);
1998 for (std::size_t i = 0; i < sz.rows(); ++i)
1999 for (std::size_t r = 0; r < sz.cols(); ++r) m(i, r + 1) = m(i, r) + sz(i, r);
2000 return m;
2001 }
2002
2003 /**
2004 * `sn.mu` (M x K cells): the total outgoing rate of each phase, MATLAB's
2005 * getServiceRates/getSourceRates. NaN for a disabled pair, empty for an
2006 * empty entry, the time-average rate for an NHPP, 1/mean for a DMAP (the
2007 * per-slot event rate), `Distrib::mu_vec` otherwise.
2008 */
2009 std::vector<std::vector<std::vector<double>>> mu() const { return rate_cells(true); }
2010
2011 /** `sn.phi` (M x K cells): the completion probability of each phase; 1 where `mu` is a single rate. */
2012 std::vector<std::vector<std::vector<double>>> phi() const { return rate_cells(false); }
2013
2014 /**
2015 * `sn.pie` (M x K cells): the phase an arriving job enters, `map_pie` of
2016 * `sn.proc{i}{r}` (the Erlang conversion for a non-Markovian law, the
2017 * time-average nominal for MAPt/PHt). NaN for a disabled or empty entry and
2018 * for an NHPP or an NNPP, whose rate function has no phase.
2019 */
2020 std::vector<std::vector<std::vector<double>>> pie() const {
2021 std::vector<std::vector<std::vector<double>>> out(nstations, std::vector<std::vector<double>>(nclasses));
2022 for (std::size_t i = 0; i < nstations && i < service.size(); ++i)
2023 for (std::size_t r = 0; r < nclasses && r < service[i].size(); ++r) {
2024 const Distrib<T>& d = service[i][r];
2025 if (d.disabled || d.is_prior() || d.type == ProcessType::NHPP ||
2026 d.type == ProcessType::NNPP) {
2027 out[i][r] = {std::nan("")};
2028 continue;
2029 }
2030 const std::vector<Matrix<T>> b = proc_blocks(i, r);
2031 mam::Map<T> m;
2032 m.D0 = b[0];
2033 m.D1 = b[1];
2034 for (const T& x : mam::map_pie(m)) out[i][r].push_back(num_traits<T>::to_double(x));
2035 }
2036 return out;
2037 }
2038
2039 /**
2040 * `sn.isph` (M x K): true where `sn.proc{i}{r}` with `sn.pie{i}{r}` admits a
2041 * phase-type reading (`sn_is_phasetype`); a disabled or empty entry is
2042 * uninspectable and reads true, as in the reference.
2043 */
2046 const auto pies = pie();
2047 for (std::size_t i = 0; i < nstations && i < service.size(); ++i)
2048 for (std::size_t r = 0; r < nclasses && r < service[i].size(); ++r) {
2049 const Distrib<T>& d = service[i][r];
2050 if (d.disabled || d.is_prior() || d.type == ProcessType::NHPP ||
2051 d.type == ProcessType::NNPP)
2052 continue;
2053 std::vector<T> p;
2054 for (double x : pies[i][r]) p.push_back(num_traits<T>::from_double(x));
2055 m(i, r) = api::sn_is_phasetype(proc_blocks(i, r), p) ? 1.0 : 0.0;
2056 }
2057 return m;
2058 }
2059
2060 /** One LST handle: E[exp(-sX)] at a complex argument. */
2061 using LstHandle = std::function<std::complex<double>(const std::complex<double>&)>;
2062
2063 /**
2064 * `sn.lst` (M x K handles), refreshLST.m: the Laplace-Stieltjes transform of
2065 * each law, admitting a complex argument (`lang::dist_lst`). EMPTY at a Fork,
2066 * a Join and a disabled Source class, as the reference leaves them; a
2067 * disabled class at any other station answers NaN, which is what the
2068 * reference's handle on a Disabled law returns. Under exact arithmetic a
2069 * handle accepts only a real argument and evaluates the exact transform.
2070 */
2071 std::vector<std::vector<LstHandle>> lst() const {
2072 std::vector<std::vector<LstHandle>> out(nstations, std::vector<LstHandle>(nclasses));
2073 for (std::size_t i = 0; i < nstations && i < service.size(); ++i)
2074 for (std::size_t r = 0; r < nclasses && r < service[i].size(); ++r) {
2075 const NodeType nt = stations[i].nodetype;
2076 const Distrib<T>& d = service[i][r];
2077 if (nt == NodeType::Fork || nt == NodeType::Join) continue;
2078 if (d.disabled) {
2079 if (nt != NodeType::Source)
2080 out[i][r] = [](const std::complex<double>&) { return std::complex<double>(std::nan(""), 0.0); };
2081 continue;
2082 }
2083 out[i][r] = [d](const std::complex<double>& s) -> std::complex<double> {
2084 if constexpr (num_traits<T>::has_transcendental) {
2085 return lang::dist_lst(d, s);
2086 } else {
2087 if (s.imag() != 0.0)
2088 throw UnsupportedError(ErrorKind{"Arithmetic"},
2089 "sn.lst: a complex argument needs transcendental arithmetic; solve in double");
2090 return std::complex<double>(
2092 }
2093 };
2094 }
2095 return out;
2096 }
2097
2098 private:
2099 std::vector<std::vector<std::vector<double>>> rate_cells(bool want_mu) const {
2100 std::vector<std::vector<std::vector<double>>> out(nstations, std::vector<std::vector<double>>(nclasses));
2101 for (std::size_t i = 0; i < nstations && i < service.size(); ++i)
2102 for (std::size_t r = 0; r < nclasses && r < service[i].size(); ++r) {
2103 const Distrib<T>& d = service[i][r];
2104 if (proc_is_empty(i, r)) continue;
2105 if (d.disabled) {
2106 out[i][r] = {std::nan("")};
2107 } else if (d.type == ProcessType::NHPP || d.type == ProcessType::NNPP ||
2108 d.type == ProcessType::DMAP) {
2109 out[i][r] = {want_mu ? num_traits<T>::to_double(d.rate()) : 1.0};
2110 } else {
2111 for (const T& x : want_mu ? d.mu_vec() : d.phi_vec())
2112 out[i][r].push_back(num_traits<T>::to_double(x));
2113 }
2114 }
2115 return out;
2116 }
2117
2118 public:
2119
2120 /** `sn.procid(i,r)`: the process type of a (station, class) pair. */
2121 ProcessType procid(std::size_t ist, std::size_t r) const {
2122 return service[ist - 1][r - 1].type;
2123 }
2124
2125 /**
2126 * `sn.phases(i,r)`: the order of the process representation.
2127 *
2128 * A PLACE HOLDS TOKENS IN ONE PHASE, and that is not cosmetic. MATLAB's
2129 * `refreshProcessRepresentations` decides the count from what `ph{ist}{r}`
2130 * turned out to be, and it has TWO ways of having no service:
2131 * - `isempty(ph{ist}{r})` -> `phases = 1`, its "fluid fails otherwise" arm
2132 * - a process that is all NaN -> `phases = 0`
2133 * A non-queueing Place carries a `ServiceTunnel`, so its entry is EMPTY and
2134 * it gets 1; a Join is handed an explicit `Coxian(NaN,NaN)` and gets 0.
2135 * C++ spells both "no service" as a disabled `Distrib`, whose `phases()` is
2136 * 0, so a Place must be answered 1 explicitly: with 0 phases
2137 * `from_marginal_node_first` builds no row and every closed SPN is refused.
2138 *
2139 * A QUEUEING Place is untouched: it has a real server and a real law, so it
2140 * is not disabled and answers from its representation as before.
2141 */
2142 std::size_t phases_of(std::size_t ist, std::size_t r) const {
2143 const Distrib<T>& d = service[ist - 1][r - 1];
2144 if (d.disabled && stations[ist - 1].nodetype == NodeType::Place) return 1;
2145 return d.phases();
2146 }
2147 /**
2148 * `sn.phasessz(i,r) = max(sn.phases(i,r),1)`: THE WIDTH of class r's phase
2149 * block in a state row, as opposed to `phases_of`, which is its CONTENT.
2150 *
2151 * The two differ exactly where a class is disabled at a station, and the
2152 * reference keeps the column anyway: a disabled process is stored as a
2153 * `1 x 1 NaN`, never as an empty, so `length(sn.proc{ist}{r}{1})` is 1 and
2154 * `State.fromMarginal` emits one always-zero column for it. A Source
2155 * serving one of six classes therefore writes `[Inf 1 0 0 0 0 0]`. A narrow
2156 * row is self-consistent but misdecodes a MATLAB-exported `model.json`.
2157 *
2158 * Use this wherever a WIDTH or an OFFSET is computed -- `row_layout`,
2159 * `to_marginal`, every `from_marginal*` builder -- and `phases_of` wherever
2160 * the question is whether the class has a process at all, or how many real
2161 * phases it has to iterate over.
2162 */
2163 /**
2164 * The number of QUANTUM phases class r carries at round-robin station ist:
2165 * the order of a renewal phase-type quantum (Exp, Erlang, HyperExp, PH,
2166 * APH, Coxian, Cox2), and 1 for any other law, which `State.rrInfo` sizes
2167 * as one placeholder phase and the state-space handlers refuse. A class
2168 * with no quantum raises LINE:input:Model, as `refreshLocalVars.m` does:
2169 * the slice sizes the state and has no meaningful default.
2170 */
2171 std::size_t rr_quantum_phases(std::size_t ist, std::size_t r) const {
2172 const Station<T>& st = stations[ist - 1];
2173 if (st.quantum.size() < r || st.quantum[r - 1].disabled)
2174 throw InputError(ErrorKind{"Model"}, "Round-robin station " + st.name + " has no quantum for class " +
2175 classes[r - 1].name + "; set it with setQuantum.");
2176 const Distrib<T>& d = st.quantum[r - 1];
2177 switch (d.type) {
2178 case ProcessType::EXP:
2179 case ProcessType::ERLANG:
2180 case ProcessType::HYPEREXP:
2181 case ProcessType::PH:
2182 case ProcessType::APH:
2183 case ProcessType::COXIAN:
2184 case ProcessType::COX2:
2185 return d.D0.rows() > 0 ? d.D0.rows() : 1;
2186 default:
2187 return 1;
2188 }
2189 }
2190 std::size_t phasessz_of(std::size_t ist, std::size_t r) const {
2191 // A NON-CARRIER MARK OWNS NO PHASE BLOCK. Every mark of a marked
2192 // arrival shares ONE modulating chain, and `set_marked_arrival` binds
2193 // the same `Distrib` to each marked class, so asking each of them for
2194 // its own width would lay K independent copies of the chain into the
2195 // state row -- K independent streams, at K times the offered load.
2196 // The chain lives in the CARRIER's block (mark 1) and a later mark
2197 // contributes one always-zero column, which is MATLAB's
2198 // `sn.phasessz(sn.markidx > 1) = 1`.
2199 if (markidx_of(ist, r) > 1) return 1;
2200 const std::size_t p = phases_of(ist, r);
2201 return p > 0 ? p : 1;
2202 }
2203 /**
2204 * `sn.markidx(i,r)`: the 1-based MARK that class r carries in station i's
2205 * marked arrival process, or 0 when the class carries no mark.
2206 *
2207 * DERIVED from `stations[i-1].marked_classes` rather than stored beside it,
2208 * since that vector already IS the binding -- mark k names class
2209 * `marked_classes[k-1]` -- and a second copy could disagree with it after a
2210 * class removal.
2211 */
2212 std::size_t markidx_of(std::size_t ist, std::size_t r) const {
2213 if (ist == 0 || ist > stations.size()) return 0;
2214 const std::vector<std::size_t>& mc = stations[ist - 1].marked_classes;
2215 for (std::size_t k = 0; k < mc.size(); ++k)
2216 if (mc[k] == r) return k + 1;
2217 return 0;
2218 }
2219 /**
2220 * The CARRIER of station i's marked arrival: the class of mark 1, whose
2221 * phase block holds the one modulating chain every mark shares. 0 when the
2222 * station has no marked process.
2223 */
2224 std::size_t mark_carrier_of(std::size_t ist) const {
2225 if (ist == 0 || ist > stations.size()) return 0;
2226 const std::vector<std::size_t>& mc = stations[ist - 1].marked_classes;
2227 return mc.empty() ? 0 : mc[0];
2228 }
2229 bool has_fork() const {
2230 for (const NodeDef& n : nodes)
2231 if (n.nodetype == NodeType::Fork) return true;
2232 return false;
2233 }
2234 /**
2235 * MATLAB's `any(sn.isstatedep(:,3))` NARROWED TO THE ONE STRATEGY THIS PORT
2236 * EVALUATES PER STATE: Krzesinski's SDR.
2237 *
2238 * RROBIN, WRROBIN, JSQ and SQ are state dependent too and `sn_has_sd_routing`
2239 * reports them. Round-robin carries its pointer in the state instead, and a
2240 * generator asking "must I re-evaluate the routing at every state?" asks
2241 * `has_rtfun_routing`, which adds JSQ and SQ to SDR.
2242 */
2243 bool has_sdr_routing() const {
2244 for (const NodeDef& n : nodes)
2245 for (RoutingStrategy rs : n.routing)
2246 if (rs == RoutingStrategy::SDR) return true;
2247 return false;
2248 }
2249 /**
2250 * True when some routing must be re-read at every state from `rt_state`: SDR, and the JSQ and SQ(d)
2251 * dispatchers, whose split is a function of the queue lengths the departing job sees (`sub_jsq` /
2252 * `sub_sq` of refreshRoutingMatrix.m). Round-robin is not here: its pointer is a state coordinate.
2253 */
2254 bool has_rtfun_routing() const {
2255 for (const NodeDef& n : nodes)
2256 for (RoutingStrategy rs : n.routing)
2257 if (rs == RoutingStrategy::SDR || rs == RoutingStrategy::JSQ || rs == RoutingStrategy::SQ)
2258 return true;
2259 return false;
2260 }
2261 /**
2262 * ROUND-ROBIN DISPATCH, the state that makes it deterministic.
2263 *
2264 * A round-robin dispatcher is not a coin: which link the next job takes is
2265 * decided by a POINTER the node carries between departures, and without it
2266 * `refresh_routing`'s uniform expansion answers a random-routing model under
2267 * a dispatcher's name. The pointer lives in the node's local-variable block,
2268 * one column per class that routes RROBIN or WRROBIN
2269 * (`refresh_local_vars` allocates it as `nvars[ind-1][R+r-1]`).
2270 *
2271 * RROBIN stores the DESTINATION NODE INDEX in its slot; WRROBIN stores a
2272 * POSITION in the weighted cycle, because a repeated outlink must advance
2273 * once per repetition and a destination value could not tell the copies
2274 * apart. Both are the reference's encodings (`refreshLocalVars.m:318-355`,
2275 * `afterEventStation.m:632-658`, `afterEventRouter.m:22-52`).
2276 */
2277 std::vector<std::size_t> rr_outlinks(std::size_t ind, std::size_t r) const {
2278 std::vector<std::size_t> out;
2279 const T zero = num_traits<T>::from_int(0);
2280 const std::size_t K = classes.size(), I = nodes.size();
2281 for (std::size_t j = 1; j <= I; ++j) {
2282 bool linked = false;
2283 for (std::size_t s = 1; s <= K && !linked; ++s)
2284 if (get_route(r, s, ind, j) > zero) linked = true;
2285 if (linked) out.push_back(j);
2286 }
2287 return out;
2288 }
2289
2290 /** The WRROBIN cycle: each outlink repeated by its weight, weight 0 once. */
2291 std::vector<std::size_t> rr_weighted_outlinks(std::size_t ind, std::size_t r) const {
2292 const std::vector<std::size_t> ol = rr_outlinks(ind, r);
2293 const std::map<std::size_t, double>* w =
2294 (ind <= nodes.size() && nodes[ind - 1].routing_weights.size() >= r)
2295 ? &nodes[ind - 1].routing_weights[r - 1]
2296 : NULL;
2297 std::vector<std::size_t> cycle;
2298 for (std::size_t d = 0; d < ol.size(); ++d) {
2299 long reps = 1;
2300 if (w != NULL) {
2301 const std::map<std::size_t, double>::const_iterator it = w->find(ol[d]);
2302 if (it != w->end() && it->second > 0.0)
2303 reps = std::lround(it->second) < 1 ? 1 : std::lround(it->second);
2304 }
2305 for (long q = 0; q < reps; ++q) cycle.push_back(ol[d]);
2306 }
2307 return cycle;
2308 }
2309
2310 /** The pair form of class r (1-based) at station ist (1-based), or null when there is none. */
2311 const CtmcMapc<T>* mapc_of(std::size_t ist, std::size_t r) const {
2312 if (ctmcmapc.empty()) return nullptr;
2313 const auto it = ctmcmapc.find(std::make_pair(ist, r));
2314 return it == ctmcmapc.end() ? nullptr : &it->second;
2315 }
2316
2317 /** 0-based column of class r's MAP memory inside node ind's local-variable block. */
2318 std::size_t map_var_slot(std::size_t ind, std::size_t r) const {
2319 std::size_t slot = 0;
2320 for (std::size_t j = 0; j + 1 < r && j < nvars[ind - 1].size(); ++j) slot += nvars[ind - 1][j];
2321 return slot;
2322 }
2323
2324 /**
2325 * 1-BASED index of the pointer of (ind, r) INSIDE the node's local-variable
2326 * block, or 0 when that pair does not dispatch round-robin.
2327 *
2328 * `sum(nvars(ind, 1:(R+class)))`, which counts over the phase columns first:
2329 * the reference indexes `space_var` with exactly that, and reading the
2330 * pointer as "the r-th trailing column" instead is wrong the moment a class
2331 * carries a modulating phase or only some classes dispatch.
2332 */
2333 std::size_t rr_var_slot(std::size_t ind, std::size_t r) const {
2334 const std::size_t R = classes.size();
2335 if (ind == 0 || ind > nodes.size() || r == 0 || r > R) return 0;
2336 const std::vector<RoutingStrategy>& rt_i = nodes[ind - 1].routing;
2337 if (rt_i.size() < r) return 0;
2338 if (rt_i[r - 1] != RoutingStrategy::RROBIN && rt_i[r - 1] != RoutingStrategy::WRROBIN)
2339 return 0;
2340 if (nvars.size() < ind) return 0;
2341 std::size_t slot = 0;
2342 for (std::size_t j = 0; j < R + r && j < nvars[ind - 1].size(); ++j)
2343 slot += nvars[ind - 1][j];
2344 return slot;
2345 }
2346
2347 /**
2348 * The destination node the pointer in VARROW names, or 0 when (ind, r) does
2349 * not dispatch round-robin or the pointer is out of range.
2350 *
2351 * @param varrow the node's local-variable columns, as `after_event` slices them
2352 */
2353 std::size_t rr_dest(std::size_t ind, std::size_t r, const std::vector<T>& varrow) const {
2354 const std::size_t slot = rr_var_slot(ind, r);
2355 if (slot == 0 || slot > varrow.size()) return 0;
2356 const long v = std::lround(num_traits<T>::to_double(varrow[slot - 1]));
2357 if (nodes[ind - 1].routing[r - 1] == RoutingStrategy::RROBIN)
2358 return v > 0 ? static_cast<std::size_t>(v) : 0;
2359 const std::vector<std::size_t> cycle = rr_weighted_outlinks(ind, r);
2360 if (v < 1 || static_cast<std::size_t>(v) > cycle.size()) return 0;
2361 return cycle[static_cast<std::size_t>(v) - 1];
2362 }
2363
2364 /**
2365 * Advance the pointer of (ind, r) in VARROW by one position, cyclically.
2366 *
2367 * A no-op where the pair does not dispatch round-robin, so a caller can run
2368 * it unconditionally on every departure.
2369 */
2370 void rr_advance(std::size_t ind, std::size_t r, std::vector<T>& varrow) const {
2371 const std::size_t slot = rr_var_slot(ind, r);
2372 if (slot == 0 || slot > varrow.size()) return;
2373 if (nodes[ind - 1].routing[r - 1] == RoutingStrategy::RROBIN) {
2374 const std::vector<std::size_t> ol = rr_outlinks(ind, r);
2375 if (ol.empty()) return;
2376 const long cur = std::lround(num_traits<T>::to_double(varrow[slot - 1]));
2377 std::size_t idx = ol.size(); // "not found" -> restart at the first
2378 for (std::size_t d = 0; d < ol.size(); ++d)
2379 if (static_cast<long>(ol[d]) == cur) { idx = d; break; }
2380 const std::size_t nxt = (idx + 1 < ol.size()) ? idx + 1 : 0;
2381 varrow[slot - 1] = num_traits<T>::from_int(static_cast<long>(ol[nxt]));
2382 return;
2383 }
2384 const std::vector<std::size_t> cycle = rr_weighted_outlinks(ind, r);
2385 if (cycle.empty()) return;
2386 const long pos = std::lround(num_traits<T>::to_double(varrow[slot - 1]));
2387 const long nxt = (pos < 1 || static_cast<std::size_t>(pos) >= cycle.size()) ? 1 : pos + 1;
2388 varrow[slot - 1] = num_traits<T>::from_int(nxt);
2389 }
2390
2391 /** Whether ANY (node, class) pair dispatches round-robin. */
2392 bool has_rr_routing() const {
2393 for (const NodeDef& n : nodes)
2394 for (RoutingStrategy rs : n.routing)
2395 if (rs == RoutingStrategy::RROBIN || rs == RoutingStrategy::WRROBIN) return true;
2396 return false;
2397 }
2398
2399 /**
2400 * Whether immediate feedback is EFFECTIVE anywhere in the model.
2401 *
2402 * A DECLARATION ALONE IS NOT ENOUGH. `Queue.setImmediateFeedback` marks a
2403 * station and `JobClass.setImmediateFeedback` marks a class -- and the class
2404 * spelling marks EVERY station, since `immfeed` is the OR of the two -- so a
2405 * model with no self-loop at all can carry a full `immfeed` matrix while the
2406 * feature changes nothing. Reading the raw matrix made every solver that
2407 * consults it warn, or refuse, on a plain M/M/1 that merely mentioned the flag.
2408 *
2409 * Immediate feedback is effective at (station i, class r) when `immfeed[i][r]`
2410 * holds AND the routing table has a self-loop INTO (i, r) from some class s at
2411 * the same station, which is the only way a job can come back to the server it
2412 * just left. A class switch on the way round is folded into `rt` by
2413 * `refresh_routing`, so the incoming class s need not be r.
2414 *
2415 * Solvers that HANDLE immediate feedback look at the SYNCHRONIZATION instead;
2416 * see `qn::immfeed_self_loop`, which applies the same test per sync.
2417 */
2419 bool declared = false;
2420 for (const std::vector<bool>& row : immfeed) {
2421 for (bool b : row)
2422 if (b) {
2423 declared = true;
2424 break;
2425 }
2426 if (declared) break;
2427 }
2428 if (!declared) return false;
2429 // Without a routing table there is nothing to qualify the declaration
2430 // with, so report it as declared rather than silently dropping it.
2431 if (rt.rows() == 0 || rt.cols() == 0) return true;
2432 const std::size_t R = nclasses;
2433 for (std::size_t ist = 1; ist <= immfeed.size(); ++ist) {
2434 const std::size_t ind = node_of_station(ist);
2435 if (ind == 0 || ind > nodes.size()) continue;
2436 const std::size_t isf = stateful_index(ind);
2437 if (isf == 0) continue;
2438 for (std::size_t r = 1; r <= immfeed[ist - 1].size() && r <= R; ++r) {
2439 if (!immfeed[ist - 1][r - 1]) continue;
2440 const std::size_t col = (isf - 1) * R + (r - 1);
2441 if (col >= rt.cols()) continue;
2442 for (std::size_t sc = 0; sc < R; ++sc) {
2443 const std::size_t row = (isf - 1) * R + sc;
2444 if (row < rt.rows() &&
2445 num_traits<T>::to_double(rt(row, col)) > 0)
2446 return true;
2447 }
2448 }
2449 }
2450 return false;
2451 }
2452 /** 1-based node index of station `st`, 0 when the map has no entry. */
2453 std::size_t node_of_station(std::size_t st) const {
2454 // A Layer built by the LQN path can carry fewer map entries than
2455 // stations; returning 0 says "no node" rather than reading past the end.
2456 if (st == 0 || st > station_to_node.size()) return 0;
2457 return station_to_node[st - 1];
2458 }
2459 /** 1-based stateful index of node `ind`, 0 when the node is not stateful. */
2460 std::size_t stateful_index(std::size_t ind) const {
2461 for (std::size_t k = 0; k < stateful_nodes.size(); ++k)
2462 if (stateful_nodes[k] == ind) return k + 1;
2463 return 0;
2464 }
2465
2466 std::size_t stateful_of_station(std::size_t st) const {
2467 const std::size_t nd = station_to_node[st - 1];
2468 for (std::size_t k = 0; k < stateful_nodes.size(); ++k)
2469 if (stateful_nodes[k] == nd) return k + 1;
2470 throw InputError("network: a station is not a stateful node");
2471 }
2472
2473 /** Add a station, which is also a node, and grow the service table. */
2474 std::size_t add_station(const Station<T>& st) {
2475 stations.push_back(st);
2476 service.emplace_back(classes.size(), Distrib<T>::disabled_dist());
2477 NodeDef nd;
2478 nd.name = st.name;
2479 nd.nodetype = st.nodetype;
2480 nd.stateful = true;
2481 nd.station = stations.size();
2482 nodes.push_back(nd);
2483 station_to_node.push_back(nodes.size());
2484 stateful_nodes.push_back(nodes.size());
2485 grow_routing();
2486 return stations.size();
2487 }
2488
2489 /** Add a non-station node (a Fork, a Router). Returns its 1-based index. */
2490 std::size_t add_node(const std::string& nm, NodeType ty, bool stateful) {
2491 NodeDef nd;
2492 nd.name = nm;
2493 nd.nodetype = ty;
2494 nd.stateful = stateful;
2495 nd.station = 0;
2496 nodes.push_back(nd);
2497 if (stateful) stateful_nodes.push_back(nodes.size());
2498 grow_routing();
2499 return nodes.size();
2500 }
2501
2502 /** Add a class and grow the service table. */
2503 std::size_t add_class(const JobClass& cl) {
2504 classes.push_back(cl);
2505 for (auto& row : service) row.emplace_back(Distrib<T>::disabled_dist());
2506 return classes.size();
2507 }
2508
2509 void set_service(std::size_t station, std::size_t cls, const Distrib<T>& d) {
2510 service[station - 1][cls - 1] = d;
2511 }
2512
2513 /** P{r,s}(i,j) = p, with 1-based NODE and class indices. */
2514 void set_route(std::size_t r, std::size_t s, std::size_t i, std::size_t j, const T& p) {
2515 auto key = std::make_pair(r, s);
2516 auto it = P.find(key);
2517 if (it == P.end())
2518 it = P.emplace(key, Matrix<T>(nodes.size(), nodes.size(), num_traits<T>::from_int(0)))
2519 .first;
2520 if (it->second.rows() != nodes.size()) grow_block(it->second);
2521 it->second(i - 1, j - 1) = p;
2522 }
2523
2524 /**
2525 * Write into the routing the consumers actually read.
2526 *
2527 * The Sink -> Source closure is derived by the refresh, not given by the
2528 * user, so it belongs in the effective routing; writing it into P alone
2529 * would make it invisible on any model whose routing was expanded.
2530 */
2531 void set_route_effective(std::size_t r, std::size_t s, std::size_t i, std::size_t j,
2532 const T& p) {
2533 if (Peff.empty()) {
2534 set_route(r, s, i, j, p);
2535 return;
2536 }
2537 auto key = std::make_pair(r, s);
2538 auto it = Peff.find(key);
2539 if (it == Peff.end())
2540 it = Peff.emplace(key, Matrix<T>(nodes.size(), nodes.size(), num_traits<T>::from_int(0)))
2541 .first;
2542 if (it->second.rows() != nodes.size()) {
2543 Matrix<T> g(nodes.size(), nodes.size(), num_traits<T>::from_int(0));
2544 for (std::size_t a = 0; a < it->second.rows(); ++a)
2545 for (std::size_t b = 0; b < it->second.cols(); ++b) g(a, b) = it->second(a, b);
2546 it->second = g;
2547 }
2548 it->second(i - 1, j - 1) = p;
2549 }
2550
2551 /**
2552 * P{r,s}(i,j), AS THE USER SET IT.
2553 *
2554 * Every consumer of the routing reads route_eff() instead, which is this
2555 * matrix once refresh_routing() has expanded the strategies that are not
2556 * literal probabilities. The two agree on a model whose routing is entirely
2557 * PROB, which is every model the LN layer builder produces.
2558 */
2559 T get_route(std::size_t r, std::size_t s, std::size_t i, std::size_t j) const {
2560 auto it = P.find(std::make_pair(r, s));
2561 if (it == P.end() || it->second.rows() < nodes.size()) return num_traits<T>::from_int(0);
2562 return it->second(i - 1, j - 1);
2563 }
2564
2565 /** The routing actually in force: the expansion when there is one, else P. */
2566 T route_eff(std::size_t r, std::size_t s, std::size_t i, std::size_t j) const {
2567 if (Peff.empty()) return get_route(r, s, i, j);
2568 auto it = Peff.find(std::make_pair(r, s));
2569 if (it == Peff.end() || it->second.rows() < nodes.size()) return num_traits<T>::from_int(0);
2570 return it->second(i - 1, j - 1);
2571 }
2572
2573 // -----------------------------------------------------------------------
2574 // Refresh
2575 // -----------------------------------------------------------------------
2576
2577 /**
2578 * The whole chain, in MATLAB's refreshStruct order.
2579 *
2580 * The order is load bearing: the routing expansion must precede the chains
2581 * (they are read off the class-switch structure of the routing), the chains
2582 * must precede the capacities (a station's buffer is bounded by the
2583 * population of the chains that reach it), and the visits must precede
2584 * nothing but must follow the sink closure, which needs the chains.
2585 */
2588 // A struct built any other way than through set_patience (direct field writes) is caught here.
2590 line::util::LineConsole::compile_detail("refreshing service and arrival processes");
2592 refresh_rates();
2594 // BEFORE the routing table: a round-robin Router must be STATEFUL, or
2595 // the stochastic complement that builds `rt` erases it and the pointer
2596 // has nowhere to live.
2598 line::util::LineConsole::compile_detail("computing the routing table");
2600 line::util::LineConsole::compile_detail("computing the chains and the visit ratios");
2603 "found %s over %s",
2604 line::util::LineConsole::plural(static_cast<long>(this->nchains), "chain", "chains").c_str(),
2605 line::util::LineConsole::plural(static_cast<long>(this->classes.size()), "class", "classes").c_str());
2607 refresh_rt();
2608 line::util::LineConsole::compile_detail("refreshing node parameters and state-dependent routing");
2611 // Needs the visit ratios, so it runs after refresh_chains.
2613 }
2614
2615 /** Refuses RENEGING declared for a class of finite population at any station (`closed_reneging_refusal`). */
2617 for (std::size_t i = 0; i < stations.size(); ++i)
2618 for (std::size_t r = 0; r < stations[i].impatience.size() && r < classes.size(); ++r)
2619 if (stations[i].impatience[r] == lang::ImpatienceType::RENEGING &&
2620 std::isfinite(classes[r].population))
2621 closed_reneging_refusal(classes[r].name, " at queue \"" + stations[i].name + "\"");
2622 }
2623
2624 /**
2625 * True when node `ind` (1-based) holds a server across a synchronous call
2626 * whose reply class is `r` (1-based), i.e. `r` returns here to release a
2627 * server rather than to be served by one.
2628 */
2629 bool holds_reply_for(std::size_t ind, std::size_t r) const {
2630 if (ind == 0 || ind > replyblock.size()) return false;
2631 for (std::size_t k = 0; k < syncreply.size(); ++k)
2632 if (syncreply[k] == r && k < replyblock[ind - 1].size() && replyblock[ind - 1][k])
2633 return true;
2634 return false;
2635 }
2636
2637 /**
2638 * Whether a job of class `r` (0-based) can LEAVE node `ind` (1-based) again.
2639 *
2640 * True for anything that is not a service station, and for a station that
2641 * serves `r`, declares heterogeneous server types (its per-class process is
2642 * disabled by construction there) or holds a server across a synchronous
2643 * call whose reply class is `r`. False only for the flow sink itself, which
2644 * is what stops the walk in `reached_node_classes` -- the same three
2645 * exemptions the guard applies, kept in one place so the walk and the
2646 * verdict cannot drift apart.
2647 */
2648 bool serves_class(std::size_t ind, std::size_t r) const {
2649 if (ind == 0 || ind > nodes.size()) return true;
2650 const NodeType nt = nodes[ind - 1].nodetype;
2651 if (nt != NodeType::Queue && nt != NodeType::Delay) return true;
2652 const std::size_t sti = nodes[ind - 1].station;
2653 if (sti == 0 || sti > stations.size()) return true;
2654 if (!stations[sti - 1].server_types.empty()) return true;
2655 if (procid(sti, r + 1) != ProcessType::DISABLED) return true;
2656 return holds_reply_for(ind, r + 1);
2657 }
2658
2659 /**
2660 * The (node, class) pairs a job can actually ARRIVE at, 0-based on both axes.
2661 *
2662 * A forward walk of `rtnodes` from the feed points. See
2663 * `check_service_reachable` for why the evidence is the UNMASKED routing
2664 * kernel rather than `nodevisits`, and for the three rules -- absorbing
2665 * Sink, Source expanded only as a seed, unservable pair reached but not
2666 * expanded -- that keep the walk from over-approximating.
2667 *
2668 * Returns an empty vector when `rtnodes` is not the expected (N*K) square,
2669 * which leaves the caller checking nothing, exactly as before.
2670 */
2671 std::vector<std::vector<bool>> reached_node_classes() const {
2672 const std::size_t N = nodes.size(), K = nclasses;
2673 std::vector<std::vector<bool>> reached;
2674 if (N == 0 || K == 0) return reached;
2675 if (rtnodes.rows() < N * K || rtnodes.cols() < N * K) return reached;
2676 reached.assign(N, std::vector<bool>(K, false));
2677 std::vector<std::vector<bool>> seed(N, std::vector<bool>(K, false));
2678 for (std::size_t i = 0; i < stations.size(); ++i) {
2679 if (stations[i].nodetype != NodeType::Source) continue;
2680 const std::size_t ind = node_of_station(i + 1);
2681 if (ind == 0 || ind > N) continue;
2682 for (std::size_t r = 0; r < K; ++r)
2683 if (procid(i + 1, r + 1) != ProcessType::DISABLED) seed[ind - 1][r] = true;
2684 }
2685 for (std::size_t r = 0; r < K && r < classes.size(); ++r) {
2686 const double pop = classes[r].population;
2687 if (!std::isfinite(pop) || pop <= 0.0) continue;
2688 const std::size_t ind = node_of_station(classes[r].refstat);
2689 if (ind == 0 || ind > N) continue;
2690 seed[ind - 1][r] = true;
2691 }
2692 std::vector<std::pair<std::size_t, std::size_t>> stack;
2693 for (std::size_t i = 0; i < N; ++i)
2694 for (std::size_t r = 0; r < K; ++r)
2695 if (seed[i][r]) {
2696 reached[i][r] = true;
2697 stack.push_back(std::make_pair(i, r));
2698 }
2699 while (!stack.empty()) {
2700 const std::size_t i = stack.back().first;
2701 const std::size_t r = stack.back().second;
2702 stack.pop_back();
2703 const NodeType nt = nodes[i].nodetype;
2704 if (nt == NodeType::Sink) continue;
2705 if (nt == NodeType::Source && !seed[i][r]) continue;
2706 if (!serves_class(i + 1, r)) continue;
2707 const std::size_t row = i * K + r;
2708 for (std::size_t col = 0; col < N * K; ++col) {
2709 if (num_traits<T>::to_double(rtnodes(row, col)) <=
2711 continue;
2712 const std::size_t j = col / K, sIdx = col % K;
2713 if (!reached[j][sIdx]) {
2714 reached[j][sIdx] = true;
2715 stack.push_back(std::make_pair(j, sIdx));
2716 }
2717 }
2718 }
2719 return reached;
2720 }
2721
2722 /**
2723 * Refuses a class that is ROUTED TO a station which cannot serve it.
2724 *
2725 * The reference's `sanitize` disables the OUTGOING routing of a class a
2726 * station cannot serve, which is what keeps it out of that station's visit
2727 * ratios -- but nothing stopped the class being routed IN, and a class that
2728 * arrives where it cannot be served is a flow sink: it enters and never
2729 * leaves. The station-level guard next to it cannot see this, because it
2730 * asks whether the station serves ANY class, not whether it serves the
2731 * classes that reach it.
2732 *
2733 * Unguarded, such a model gets a different silent wrong answer from each of
2734 * MVA, CTMC and SSA.
2735 *
2736 * READS `rtnodes`, WALKED FORWARD FROM THE FEED POINTS. Do not route this
2737 * guard through `nodevisits` or `visits`: both carry the `served` mask,
2738 * which zeroes exactly the (station, class) cell a flow sink shows up in,
2739 * so a masked visit vector cannot answer this question. See
2740 * _kb/07-cross-language-parity.md.
2741 *
2742 * `rtnodes` on its own over-approximates -- it says where a class WOULD go
2743 * if one existed -- and the WALK is what removes the slack. It starts only
2744 * at (Source, class) pairs whose arrival process is not DISABLED, and at the
2745 * reference station of each closed class with a positive population, so the
2746 * disabled-arrival row a class-switching Source carries is never entered.
2747 * Three rules keep it honest: a Sink is ABSORBING (`rtnodes` wraps it back
2748 * to the Source to close the kernel, and following that wrap re-enters every
2749 * Source row, including the disabled ones the seeding just excluded); a
2750 * Source is expanded ONLY AS A SEED, for the same reason; and an unservable
2751 * (station, class) is REACHED BUT NOT EXPANDED, since nothing leaves it --
2752 * that is the whole complaint -- so nothing downstream of it is evidence of
2753 * anything.
2754 *
2755 * A chain no job can enter has no seed, so its rows are never walked.
2756 */
2757 /**
2758 * A signal spends no time at the queue it reaches: it acts on arrival and leaves, so an unset slot is
2759 * Immediate. Left Disabled, the routed-without-service check demanded a service no solver reads.
2760 * MATLAB sanitize, the JAR and python fill the same slot.
2761 */
2763 for (std::size_t i = 0; i < nstations; ++i) {
2764 const NodeType nt = stations[i].nodetype;
2765 if (nt != NodeType::Queue && nt != NodeType::Delay) continue;
2766 for (std::size_t r = 0; r < classes.size() && r < issignal.size(); ++r)
2767 if (issignal[r] && procid(i + 1, r + 1) == ProcessType::DISABLED)
2768 set_service(i + 1, r + 1, Distrib<T>::immediate());
2769 }
2770 }
2771
2773 if (nclasses == 0) return;
2774 // Same exemption as the reference's sanitize checks: a station of a
2775 // cache, Petri-net or fork-join model legitimately carries no per-class
2776 // service.
2777 for (std::size_t ind = 0; ind < nodes.size(); ++ind) {
2778 const NodeType nt = nodes[ind].nodetype;
2779 if (nt == NodeType::Cache || nt == NodeType::Place ||
2780 nt == NodeType::Transition || nt == NodeType::Fork ||
2781 nt == NodeType::Join)
2782 return;
2783 }
2784 const std::size_t K = nclasses;
2785 const std::vector<std::vector<bool>> reached = reached_node_classes();
2786 if (reached.empty()) return;
2787 for (std::size_t i = 0; i < nstations; ++i) {
2788 const NodeType nt = stations[i].nodetype;
2789 if (nt != NodeType::Queue && nt != NodeType::Delay) continue;
2790 // A heterogeneous pool carries its service on the server types, so
2791 // the per-class process is legitimately disabled there. Skipped in
2792 // all four codebases.
2793 if (!stations[i].server_types.empty()) continue;
2794 const std::size_t ind = node_of_station(i + 1);
2795 if (ind == 0) continue;
2796 for (std::size_t r = 0; r < K; ++r) {
2797 if (procid(i + 1, r + 1) != ProcessType::DISABLED) continue;
2798 // A SYNCHRONOUS REPLY is not served by the station it returns
2799 // to: it releases the server that station held across the call,
2800 // which is the whole content of set_sync_reply. Its Disabled
2801 // service there is the marker of the feature, not a flow sink.
2802 if (holds_reply_for(ind, r + 1)) continue;
2803 if (ind - 1 >= reached.size() || r >= reached[ind - 1].size()) continue;
2804 if (!reached[ind - 1][r]) continue;
2805 const std::string kind = (nt == NodeType::Delay) ? "Delay" : "Queue";
2806 throw InputError(kind + " '" + stations[i].name +
2807 "' has no service configured for job class '" +
2808 classes[r].name +
2809 "', but the class is routed to it. Jobs would arrive and "
2810 "never leave. Configure a service for that class, or route "
2811 "it elsewhere.");
2812 }
2813 }
2814 }
2815
2816 /**
2817 * Port of the `sn.immfeed` block of `@@MNetwork/refreshStruct.m`.
2818 *
2819 * The station's own per-class setting OR the class-level one, which is the
2820 * reference's `stationHas || classHas`. Sized here rather than in
2821 * `refresh_rates` because it is a property of the model's topology and not
2822 * of the service processes, so it must not be cleared when only the rates
2823 * are re-derived (SolverLN calls `refresh_rates` per layer, per iteration).
2824 */
2826 const std::size_t M = stations.size(), R = classes.size();
2827 immfeed.assign(M, std::vector<bool>(R, false));
2828 for (std::size_t i = 0; i < M; ++i)
2829 for (std::size_t r = 0; r < R; ++r) {
2830 const bool station_has =
2831 r < stations[i].immfeed.size() && stations[i].immfeed[r];
2832 immfeed[i][r] = station_has || classes[r].immfeed;
2833 }
2834 }
2835
2836 /**
2837 * Make node `ind` stateful, keeping `stateful_nodes` ascending. Idempotent.
2838 *
2839 * Used by the fork-join transforms: the Router they put where a Fork stood
2840 * is a `Router` OBJECT in the reference, hence a `StatefulNode`, and it has
2841 * to stay one here. Its chain block is deliberately NOT stochastic -- an
2842 * auxiliary class keeps the OTHER fork's full fan-out, so that row sums to
2843 * the fan-out -- and on such a block the stochastic complement is not
2844 * visit-preserving, so complementing the node away moves every downstream
2845 * visit ratio off the reference's.
2846 */
2847 void promote_stateful(std::size_t ind) {
2848 if (ind == 0 || ind > nodes.size() || nodes[ind - 1].stateful) return;
2849 nodes[ind - 1].stateful = true;
2850 stateful_nodes.insert(std::lower_bound(stateful_nodes.begin(), stateful_nodes.end(), ind),
2851 ind);
2852 }
2853
2854 /**
2855 * A Router that DISPATCHES (round-robin, JSQ or SQ(d)) holds state, so it must
2856 * survive the stochastic complement that removes the stateless nodes: a
2857 * pointer for round-robin, and for JSQ/SQ a departure the generator can flag
2858 * as state dependent, which a complemented-away node would not have.
2859 *
2860 * The reference makes EVERY Router stateful (`refreshStruct.m:155`); this
2861 * port promotes only the dispatching ones, because a PROB or RAND Router
2862 * genuinely holds nothing and complementing it away is both correct and
2863 * cheaper -- it keeps the state space of every existing model unchanged.
2864 * The promotion happens at refresh rather than at `add_router`, since
2865 * `set_routing` is called after the node exists.
2866 */
2868 for (std::size_t ind = 1; ind <= nodes.size(); ++ind) {
2869 NodeDef& nd = nodes[ind - 1];
2870 if (nd.stateful || nd.nodetype != NodeType::Router) continue;
2871 bool dispatch = false;
2872 for (std::size_t r = 0; r < nd.routing.size(); ++r)
2873 if (nd.routing[r] == RoutingStrategy::RROBIN ||
2874 nd.routing[r] == RoutingStrategy::WRROBIN ||
2875 nd.routing[r] == RoutingStrategy::JSQ || nd.routing[r] == RoutingStrategy::SQ)
2876 dispatch = true;
2877 if (!dispatch) continue;
2878 nd.stateful = true;
2879 stateful_nodes.insert(
2880 std::lower_bound(stateful_nodes.begin(), stateful_nodes.end(), ind), ind);
2881 }
2882 }
2883
2884 /**
2885 * Port of MNetwork.refreshLocalVars: the per-node local-variable widths.
2886 *
2887 * A column is reserved only where the model actually needs one, because the
2888 * width is part of the state encoding -- a spurious column widens every
2889 * state row and makes it unmatchable against the enumerated space.
2890 */
2892 const std::size_t R = classes.size();
2893 // One entry per class, 0 = none, as MATLAB's -ones(nclasses,1): a class added after the last binding
2894 // (LQN2QN's Ph2End destructors) or a model with no binding at all would otherwise leave it short
2895 syncreply.resize(R, 0);
2897 nvars.assign(nodes.size(), std::vector<std::size_t>(3 * R + 1, 0));
2898 for (std::size_t ind = 1; ind <= nodes.size(); ++ind) {
2899 const std::size_t ist = nodes[ind - 1].station;
2900 // A Markov-modulated process restarts from the phase it was left
2901 // in, so that phase has to survive in the state between services.
2902 if (ist != 0)
2903 for (std::size_t r = 1; r <= R; ++r) {
2904 const ProcessType pt = procid(ist, r);
2905 if (pt == ProcessType::MAP || pt == ProcessType::MMPP2)
2906 nvars[ind - 1][r - 1] += 1;
2907 }
2908 // Round-robin routing is stateful: the pointer to the next outgoing
2909 // link is what makes it deterministic rather than random.
2910 const std::vector<RoutingStrategy>& rt_i = nodes[ind - 1].routing;
2911 for (std::size_t r = 1; r <= R && r <= rt_i.size(); ++r)
2912 if (rt_i[r - 1] == RoutingStrategy::RROBIN ||
2913 rt_i[r - 1] == RoutingStrategy::WRROBIN)
2914 nvars[ind - 1][R + r - 1] += 1;
2915 // The shared node block. A Cache stores its list contents here;
2916 // the BAS marker, the breakdown status and the polling controller
2917 // claim the same column, which is why the reference rejects those
2918 // combinations instead of widening the state.
2919 // The polling controller shares the node block with the cache,
2920 // the BAS marker and the breakdown status, which is why those
2921 // combinations are rejected rather than the state widened.
2922 // The SAME resolution polling_info reads, or its offset misses nvars.
2923 if (ist != 0 && stations[ist - 1].sched == SchedStrategy::POLLING) {
2924 // Over the POLLED buffers only, as `State.pollingInfo`: a
2925 // switchover declared on a class disabled here is never walked.
2926 nvars[ind - 1][2 * R] = polling_width(ist);
2927 }
2928 // ROUND ROBIN: the node block holds m(r,k,q), the class-r jobs in
2929 // service in service phase k and quantum phase q, in the order of
2930 // `rr_info` (rr_info.h). Redundant with the server counts when
2931 // every quantum is exponential, but kept so the layout does not
2932 // depend on the quantum law, as in `refreshLocalVars.m`.
2933 if (ist != 0 && stations[ist - 1].sched == SchedStrategy::RR) {
2934 std::size_t w = 0;
2935 for (std::size_t r = 1; r <= R; ++r) w += phasessz_of(ist, r) * rr_quantum_phases(ist, r);
2936 nvars[ind - 1][2 * R] = w;
2937 }
2938 // The REPLY block: one counter column per (node, calling class).
2939 for (std::size_t r = 1; r <= R; ++r)
2940 if (replyblock.size() >= ind && replyblock[ind - 1].size() >= r &&
2941 replyblock[ind - 1][r - 1])
2942 nvars[ind - 1][2 * R + r] = 1;
2943 // The SERVER STATUS of a station that breaks down (1 = up, 0 = down),
2944 // `refreshLocalVars.m`. It takes the shared node block, so a polling
2945 // controller there is refused as the reference refuses it; the BAS
2946 // marker is refused by `refresh_bas_blocking`. The status must be
2947 // the TRAILING column, which is where the DEP, PHASE, FAILURE and
2948 // REPAIR handlers read it, so a reply block (whose counters trail
2949 // the node block in this port) is refused too.
2950 if (ist != 0 && breakdownparam.find(ist) != breakdownparam.end()) {
2951 if (stations[ist - 1].sched == SchedStrategy::POLLING)
2952 throw UnsupportedError(ErrorKind{"Breakdown"},
2953 "Server breakdowns are not supported at a polling station (" +
2954 nodes[ind - 1].name +
2955 "): the polling controller and the breakdown status share one "
2956 "local-state column.");
2957 if (stations[ist - 1].sched == SchedStrategy::RR)
2958 throw UnsupportedError(ErrorKind{"SchedStrategy_RR"},
2959 "Server breakdowns are not supported at a round-robin station (" +
2960 nodes[ind - 1].name +
2961 "): the quantum phases of the jobs in service and the breakdown status "
2962 "share one local-state column.");
2963 for (std::size_t r = 1; r <= R; ++r)
2964 if (replyblock.size() >= ind && replyblock[ind - 1].size() >= r &&
2965 replyblock[ind - 1][r - 1])
2966 throw UnsupportedError(ErrorKind{"Breakdown"},
2967 "Server breakdowns are not supported at station '" +
2968 nodes[ind - 1].name +
2969 "', which also holds servers for a synchronous reply: the reply "
2970 "counters would trail the breakdown status the service handlers read");
2971 nvars[ind - 1][2 * R] = 1;
2972 }
2973 const typename std::map<std::size_t, CacheParam<T>>::const_iterator ci =
2974 nodeparam.find(ind);
2975 if (ci != nodeparam.end()) {
2976 // Contents, plus block A (a per-item occupancy bitmap) and block
2977 // B (a per-retrieval-class count of merged secondary requests)
2978 // when a delayed-hit retrieval system is attached.
2979 std::size_t w = 0;
2980 for (std::size_t u = 0; u < ci->second.itemcap.size(); ++u)
2981 if (ci->second.itemcap[u] > 0)
2982 w += static_cast<std::size_t>(ci->second.itemcap[u]);
2983 if (ci->second.retrieval_capacity > 0) {
2984 w += ci->second.nitems;
2985 std::vector<std::size_t> rcl, rci, rco;
2986 cache_retrieval_class_map(ci->second, rcl, rci, rco);
2987 w += rcl.size();
2988 }
2989 nvars[ind - 1][2 * R] = w;
2990 }
2991 }
2993 }
2994
2995 /**
2996 * `sn.replyblock`, DERIVED from `sn.syncreply` and the routing.
2997 *
2998 * Port of `refreshLocalVars.m:340-386`. A server is held wherever the REPLY
2999 * class can arrive: every node that is a station, is not the Source, and is
3000 * not an infinite server -- an INF station has a server per job, so holding
3001 * one is immaterial and needs no state. Every such station must be FCFS,
3002 * because a held server is encoded as a per-class COUNTER, which is exact
3003 * only where the servers are interchangeable.
3004 *
3005 * Derived rather than declared because the model layer carries only the
3006 * class-to-class binding (`JobClass.setReplySignalClass`), and a caller
3007 * naming the nodes itself would silently disagree with the reference on any
3008 * model whose routing sends the reply somewhere it did not think of.
3009 */
3011 const std::size_t R = classes.size(), N = nodes.size();
3012 bool any = false;
3013 for (std::size_t r = 0; r < R && r < syncreply.size(); ++r)
3014 if (syncreply[r] >= 1 && syncreply[r] <= R) any = true;
3015 if (!any) return;
3016 replyblock.assign(N, std::vector<bool>(R, false));
3017 for (std::size_t r = 1; r <= R; ++r) {
3018 if (r > syncreply.size()) break;
3019 const std::size_t s = syncreply[r - 1];
3020 if (s < 1 || s > R) continue;
3021 for (std::size_t ind = 1; ind <= N; ++ind) {
3022 const std::size_t ist = nodes[ind - 1].station;
3023 if (ist == 0 || nodes[ind - 1].nodetype == lang::NodeType::Source) continue;
3024 if (stations[ist - 1].sched == SchedStrategy::INF) continue;
3025 bool arrives_here = false;
3026 for (std::size_t i = 1; i <= N && !arrives_here; ++i)
3027 for (std::size_t q = 1; q <= R; ++q)
3028 if (rtnodes.rows() >= N * R &&
3030 rtnodes((i - 1) * R + q - 1, (ind - 1) * R + s - 1)) > 0) {
3031 arrives_here = true;
3032 break;
3033 }
3034 if (!arrives_here) continue;
3035 if (stations[ist - 1].sched != SchedStrategy::FCFS)
3036 throw InputError(
3037 "network '" + name +
3038 "': synchronous calls (REPLY signals) are supported only at FCFS "
3039 "stations, but '" +
3040 nodes[ind - 1].name +
3041 "' uses another discipline. A held server is encoded as a per-class "
3042 "counter, which is exact only where servers are interchangeable (FCFS) "
3043 "or unlimited (INF); the other disciplines are not yet encoded rather than "
3044 "infeasible. Set this station to FCFS or INF, or simulate the layered model "
3045 "directly with SolverLDES.");
3046 replyblock[ind - 1][r - 1] = true;
3047 }
3048 }
3049 }
3050
3051 /**
3052 * The nodes directly downstream of `ind`, walking THROUGH stateless nodes
3053 * and stopping at the first station on each path.
3054 *
3055 * `downstreamStations` in `refreshLocalVars.m`. A blocked job is held for its
3056 * IMMEDIATE destination, so the walk stops at the first station: a Router or
3057 * ClassSwitch in between is a routing decision, not a place to wait.
3058 *
3059 * The reference reads `sn.connmatrix`; this port has no such field and reads
3060 * `rtnodes` instead, which is the same graph after the refresh has resolved
3061 * the routing strategies. The two differ only on a link the model declares
3062 * and then routes zero mass over, and such a link cannot fill a destination,
3063 * so it cannot block anything either.
3064 */
3065 std::vector<std::size_t> downstream_stations(std::size_t ind) const {
3066 const std::size_t R = classes.size();
3067 const std::size_t N = nodes.size();
3068 std::vector<std::size_t> out;
3069 if (rtnodes.rows() < N * R) return out;
3070 std::vector<bool> seen(N + 1, false);
3071 std::vector<std::size_t> frontier(1, ind);
3072 seen[ind] = true;
3073 while (!frontier.empty()) {
3074 const std::size_t i = frontier.back();
3075 frontier.pop_back();
3076 for (std::size_t j = 1; j <= N; ++j) {
3077 if (seen[j]) continue;
3078 bool linked = false;
3079 for (std::size_t r = 0; r < R && !linked; ++r)
3080 for (std::size_t s = 0; s < R && !linked; ++s)
3082 rtnodes((i - 1) * R + r, (j - 1) * R + s)) > 0)
3083 linked = true;
3084 if (!linked) continue;
3085 seen[j] = true;
3086 if (nodes[j - 1].station != 0) {
3087 out.push_back(j); // a station terminates this path
3088 } else {
3089 frontier.push_back(j); // walk through the stateless node
3090 }
3091 }
3092 }
3093 return out;
3094 }
3095
3096 /**
3097 * Port of `refreshLocalVars`' true-BAS block and its `declaresBlockedMarker`
3098 * helper: which nodes carry the blocked marker, and where a refusal blocks.
3099 */
3101 const std::size_t R = classes.size();
3102 const std::size_t N = nodes.size();
3103 isbasblocking.assign(N, false);
3104 isbasdestination.assign(stations.size(), std::vector<bool>(R, false));
3105 if (droprule.empty()) return;
3106 for (std::size_t ind = 1; ind <= N; ++ind) {
3107 std::vector<std::vector<bool>> destmask;
3108 if (!bas_declares(ind, destmask)) continue;
3109 for (std::size_t j = 0; j < destmask.size(); ++j)
3110 for (std::size_t r = 0; r < R; ++r)
3111 if (destmask[j][r]) isbasdestination[j][r] = true;
3112 const std::size_t ist = nodes[ind - 1].station;
3113 // The marker shares nvars column 2R+1 with the cache contents, the
3114 // breakdown status and the polling controller, so the reference
3115 // rejects the combinations rather than widening the state.
3116 if (breakdownparam.find(ist) != breakdownparam.end())
3117 throw UnsupportedError(ErrorKind{"Breakdown"},
3118 "station '" + nodes[ind - 1].name +
3119 "' combines server breakdowns with true-BAS blocking: the breakdown status "
3120 "and the BAS blocked marker share one local-state column. Remove the BAS drop "
3121 "rule or the breakdown");
3122 if (stations[ist - 1].sched == SchedStrategy::POLLING)
3123 throw UnsupportedError(ErrorKind{"SchedStrategy_POLLING"},
3124 "true BAS blocking is not supported at the polling station '" +
3125 nodes[ind - 1].name +
3126 "': the polling controller and the BAS blocked marker share one local-state "
3127 "column. Use a non-polling discipline at the blocking station, or remove the "
3128 "BAS drop rule");
3129 if (stations[ist - 1].sched == SchedStrategy::RR)
3130 throw UnsupportedError(ErrorKind{"SchedStrategy_RR"},
3131 "True BAS blocking is not supported at a round-robin station (" +
3132 nodes[ind - 1].name +
3133 "): the quantum phases of the jobs in service and the BAS blocked marker "
3134 "share one local-state column.");
3135 for (std::size_t r = 1; r <= R; ++r)
3136 if (replyblock.size() >= ind && replyblock[ind - 1].size() >= r &&
3137 replyblock[ind - 1][r - 1])
3138 throw UnsupportedError(ErrorKind{"SyncCall"},
3139 "true BAS blocking is not supported at station '" + nodes[ind - 1].name +
3140 "', which also holds servers for a synchronous reply: fromMarginal appends "
3141 "the reply counters AFTER the blocked marker, so the marker would no "
3142 "longer be the trailing column the departure handler reads");
3143 isbasblocking[ind - 1] = true;
3144 // One held-job counter per target code (BUG-110), at least one column.
3145 nvars[ind - 1][2 * R] = bas_ncols(bas_marker_codes(ind));
3146 }
3147 }
3148
3149 /**
3150 * `declaresBlockedMarker` for node `ind` (1-based): true when it is the
3151 * BLOCKING side of a true-BAS relation. `destmask` (nstations x nclasses)
3152 * marks the (destination station, class) pairs whose refusals block `ind`.
3153 */
3154 bool bas_declares(std::size_t ind, std::vector<std::vector<bool>>& destmask) const {
3155 const std::size_t R = classes.size();
3156 destmask.assign(stations.size(), std::vector<bool>(R, false));
3157 if (droprule.empty() || ind == 0 || ind > nodes.size()) return false;
3158 const std::size_t ist = nodes[ind - 1].station;
3159 if (ist == 0) return false;
3160 const NodeType nt = nodes[ind - 1].nodetype;
3161 if (nt == NodeType::Source || nt == NodeType::Cache) return false;
3162 const std::vector<std::size_t> dests = downstream_stations(ind);
3163 bool declares = false;
3164 for (std::size_t r = 1; r <= R; ++r) {
3165 const bool here_bas = droprule.size() >= ist && droprule[ist - 1].size() >= r &&
3166 droprule[ist - 1][r - 1] == DropStrategy::BAS;
3167 for (std::size_t d = 0; d < dests.size(); ++d) {
3168 const std::size_t jst = nodes[dests[d] - 1].station;
3169 if (jst == 0 || nodes[dests[d] - 1].nodetype == NodeType::Source) continue;
3170 // The destination must be able to FILL. An unbounded queue
3171 // never refuses, so nothing upstream of it can ever block,
3172 // and reserving the marker would widen the state for nothing.
3173 //
3174 // THE DECLARED CAPACITY, not the refreshed `cap`. The refresh
3175 // clamps an unbounded station to the total closed population,
3176 // which is finite, so reading `cap` here would find every
3177 // destination in a closed model "able to fill" and reserve a
3178 // marker on every upstream station. The reference reads
3179 // `dnode.cap`, the value the user set.
3180 const double dcap = stations[jst - 1].cap;
3181 if (!std::isfinite(dcap) || !(dcap > 0)) continue;
3182 const bool there_bas =
3183 droprule.size() >= jst && droprule[jst - 1].size() >= r &&
3184 droprule[jst - 1][r - 1] == DropStrategy::BAS;
3185 if (!here_bas && !there_bas) continue;
3186 // Do NOT stop at the first hit: every such destination has to
3187 // be recorded, since a refusal at ANY of them must block here
3188 // rather than drop.
3189 declares = true;
3190 destmask[jst - 1][r - 1] = true;
3191 }
3192 }
3193 return declares;
3194 }
3195
3196 /**
3197 * TRUE-BAS HELD-JOB CODES (BUG-110). A blocking station carries, in its
3198 * trailing node block, one held-job COUNTER per target code
3199 * `1 + (r-1) + R*((s-1) + R*(jst-1))` (1-based r, s, jst): a completed
3200 * class-r job waiting to enter station jst as class s. A single {0,1}
3201 * marker could hold only one job, so a multi-server station (a Delay)
3202 * with several completions towards full destinations lost mass, and the
3203 * held job was released into whichever destination freed first.
3204 */
3205 std::size_t bas_code(std::size_t r, std::size_t jst, std::size_t s) const {
3206 const std::size_t R = classes.size();
3207 return 1 + (r - 1) + R * ((s - 1) + R * (jst - 1));
3208 }
3209 /** Inverse of bas_code: 1-based (r, jst, s) for a code >= 1. */
3210 void bas_decode(std::size_t code, std::size_t& r, std::size_t& jst, std::size_t& s) const {
3211 const std::size_t R = classes.size();
3212 std::size_t c = code - 1;
3213 r = c % R + 1;
3214 c /= R;
3215 s = c % R + 1;
3216 jst = c / R + 1;
3217 }
3218 /**
3219 * Sorted held-job codes of the blocking node `ind`: one per (r, jst, s) the
3220 * routing sends from class r at ind to class s at jst with positive mass,
3221 * where a refusal of s at jst blocks ind. A destination whose capacity
3222 * holds the whole closed population never refuses and is left out.
3223 */
3224 std::vector<std::size_t> bas_marker_codes(std::size_t ind) const {
3225 std::vector<std::size_t> codes;
3226 std::vector<std::vector<bool>> destmask;
3227 if (!bas_declares(ind, destmask)) return codes;
3228 const std::size_t R = classes.size();
3229 const std::size_t isf = stateful_index(ind);
3230 if (isf == 0) return codes;
3231 const std::vector<double> nj = njobs();
3232 double total = 0.0;
3233 for (std::size_t r = 0; r < nj.size(); ++r) total += nj[r];
3234 for (std::size_t jst = 1; jst <= stations.size(); ++jst) {
3235 const std::size_t jsf = stateful_index(node_of_station(jst));
3236 if (jsf == 0) continue;
3237 if (jst <= cap.size() && std::isfinite(total) && cap[jst - 1] >= total) continue;
3238 for (std::size_t s = 1; s <= R; ++s) {
3239 if (!destmask[jst - 1][s - 1]) continue;
3240 for (std::size_t r = 1; r <= R; ++r) {
3241 const std::size_t i = (isf - 1) * R + (r - 1), j = (jsf - 1) * R + (s - 1);
3242 if (i < rt.rows() && j < rt.cols() && num_traits<T>::to_double(rt(i, j)) > 0)
3243 codes.push_back(bas_code(r, jst, s));
3244 }
3245 }
3246 }
3247 std::sort(codes.begin(), codes.end());
3248 codes.erase(std::unique(codes.begin(), codes.end()), codes.end());
3249 return codes;
3250 }
3251 /** Width of the held-job block: one counter per code, at least one column. */
3252 static std::size_t bas_ncols(const std::vector<std::size_t>& codes) {
3253 return codes.empty() ? 1 : codes.size();
3254 }
3255 /** A non-INF station with at most one server holds at most one job in total. */
3256 bool bas_single_server(std::size_t ist) const {
3257 if (ist == 0 || ist > stations.size()) return false;
3258 if (stations[ist - 1].sched == SchedStrategy::INF) return false;
3259 return stations[ist - 1].nservers <= 1;
3260 }
3261
3262 /**
3263 * Port of MNetwork.refreshScheduling's schedparam half.
3264 *
3265 * DPS and GPS take a per-class weight, defaulting to 1; SEPT and LEPT take
3266 * the rank of the class's mean service time among the distinct means, which
3267 * is what the reference computes here rather than at the solver.
3268 *
3269 * EVERY OTHER DISCIPLINE DEFAULTS TO 1, NOT 0. Measured against MATLAB
3270 * R2025a: FCFS, PS, LPS, SIRO, LCFS, HOL and SJF all report schedparam 1
3271 * per class on a two-class model, and only SEPT/LEPT differ. Defaulting to
3272 * zero here made every consumer that normalizes by the weight total divide
3273 * 0/0: a load-dependent PS station reported Util exactly 0 against the
3274 * reference's 0.400822578299582, and `ctmc_signal_busy` shares the pattern.
3275 */
3277 const T one = num_traits<T>::from_int(1);
3278 for (std::size_t i = 0; i < stations.size(); ++i) {
3279 Station<T>& st = stations[i];
3280 if (st.sched == SchedStrategy::DPS || st.sched == SchedStrategy::GPS) {
3281 if (st.schedparam.size() != classes.size())
3282 st.schedparam.assign(classes.size(), one);
3283 continue;
3284 }
3285 if (st.sched == SchedStrategy::SEPT || st.sched == SchedStrategy::LEPT) {
3286 if (st.schedparam.size() == classes.size()) continue;
3287 std::vector<double> means;
3288 for (std::size_t r = 0; r < classes.size(); ++r)
3289 means.push_back(num_traits<T>::to_double(service[i][r].mean));
3290 std::vector<double> sorted = means;
3291 std::sort(sorted.begin(), sorted.end());
3292 sorted.erase(std::unique(sorted.begin(), sorted.end()), sorted.end());
3293 if (st.sched == SchedStrategy::LEPT)
3294 std::reverse(sorted.begin(), sorted.end());
3295 st.schedparam.assign(classes.size(), num_traits<T>::from_int(0));
3296 for (std::size_t r = 0; r < classes.size(); ++r)
3297 for (std::size_t k = 0; k < sorted.size(); ++k)
3298 if (sorted[k] == means[r])
3299 st.schedparam[r] = num_traits<T>::from_int(static_cast<long>(k) + 1);
3300 continue;
3301 }
3302 if (st.schedparam.empty()) st.schedparam.assign(classes.size(), one);
3303 }
3304 }
3305
3306 /**
3307 * Port of the part of MNetwork.refreshRoutingMatrix this port reaches: the
3308 * expansion of a routing STRATEGY into the probabilities `rt` is built from.
3309 *
3310 * PROB is already probabilities and is copied through. RAND and RROBIN
3311 * spread the mass uniformly over the nodes the user connected this one to,
3312 * which is what MATLAB's `RoutingStrategy.RAND` means once `link` has
3313 * recorded the connections, and what `getRoutingMatrix.m:117` does for both
3314 * in the same branch: a round-robin pointer visits every outgoing link
3315 * equally often, so the ROUTING PROBABILITIES it induces are uniform and
3316 * only the higher moments of the split are deterministic. Recovering that
3317 * determinism is the consumer's job -- `npfqn_traffic_split_rr` gives QNA
3318 * and MNA the split degree, and a solver that needs the pointer itself must
3319 * carry it in the state. A solver that does neither must not declare
3320 * `RoutingStrategy_RROBIN` in its feature set, or it answers a random-
3321 * routing model under a round-robin name.
3322 * A ClassSwitch node's outgoing mass is multiplied by its
3323 * class-switch matrix, so a job leaving it in class r continues as class s
3324 * with probability C(r,s) -- the node itself is not stateful, and the
3325 * stochastic complement folds it into the edges around it.
3326 *
3327 * WRROBIN spreads by its weights, and JSQ, SQ and SDR uniformly: for those
3328 * three the expansion is a PLACEHOLDER whose support is right and whose
3329 * values are not, and a solver that declares them re-reads the row at every
3330 * state from `rt_state`. Any other strategy (FIRING, say) is REFUSED by
3331 * name: silently treating one as PROB returns a product-form answer for a
3332 * model that does not have one.
3333 */
3335 const T zero = num_traits<T>::from_int(0);
3336 const std::size_t K = classes.size(), I = nodes.size();
3337 Peff.clear();
3338 bool trivial = true;
3339 for (const NodeDef& nd : nodes)
3340 for (RoutingStrategy rs : nd.routing)
3341 if (rs != RoutingStrategy::PROB && rs != RoutingStrategy::DISABLED) trivial = false;
3342 // A (node, class) PAIR THE CALLER NEVER ROUTED IS NOT TRIVIAL EITHER,
3343 // because the reference FILLS it -- see the unrouted branch below. This
3344 // port has no DISABLED strategy to key on (every pair defaults to PROB),
3345 // so the condition is the one MATLAB's DISABLED case IS: no outgoing
3346 // mass for this class at this node, at a node that has connections.
3347
3348 bool has_cs = false;
3349 for (const NodeDef& nd : nodes)
3350 if (nd.nodetype == NodeType::ClassSwitch) has_cs = true;
3351 // A Cache node is an implicit class switch: its read class routes on to
3352 // the hit and miss classes, so the routing is never trivial.
3353 const bool has_cache = !nodeparam.empty();
3354 if (trivial && !has_cs && !has_cache) return; // P is already the effective routing
3355
3356 for (const auto& kv : P) Peff[kv.first] = kv.second;
3357 // The class-INDEPENDENT topology (`sn.connmatrix`), built once from the arcs P holds. Probing
3358 // get_route over every class pair per (node, class, destination) was I^2 K^3 lookups, which
3359 // never finished on a flattened LQN (25 nodes, 146 classes: ~2e9 map finds).
3360 std::vector<char> conn(I * I, 0);
3361 for (const auto& kv : P) {
3362 const Matrix<T>& M = kv.second;
3363 if (M.rows() < I || M.cols() < I) continue; // get_route reads such a block as zero
3364 for (std::size_t a = 0; a < I; ++a)
3365 for (std::size_t b = 0; b < I; ++b)
3366 if (M(a, b) > zero) conn[a * I + b] = 1;
3367 }
3368 auto eff_at = [&](std::size_t r, std::size_t s) -> Matrix<T>& {
3369 auto key = std::make_pair(r, s);
3370 auto it = Peff.find(key);
3371 if (it == Peff.end())
3372 it = Peff.emplace(key, Matrix<T>(I, I, zero)).first;
3373 if (it->second.rows() != I) {
3374 Matrix<T> g(I, I, zero);
3375 for (std::size_t a = 0; a < it->second.rows(); ++a)
3376 for (std::size_t b = 0; b < it->second.cols(); ++b) g(a, b) = it->second(a, b);
3377 it->second = g;
3378 }
3379 return it->second;
3380 };
3381
3382 for (std::size_t i = 1; i <= I; ++i) {
3383 const NodeDef& nd = nodes[i - 1];
3384 for (std::size_t r = 1; r <= K; ++r) {
3385 const RoutingStrategy rs =
3386 nd.routing.size() >= r ? nd.routing[r - 1] : RoutingStrategy::PROB;
3387 if (rs == RoutingStrategy::PROB || rs == RoutingStrategy::DISABLED) continue;
3388 if (rs != RoutingStrategy::RAND && rs != RoutingStrategy::RROBIN &&
3389 rs != RoutingStrategy::JSQ && rs != RoutingStrategy::SQ &&
3390 rs != RoutingStrategy::WRROBIN && rs != RoutingStrategy::SDR)
3391 throw UnsupportedError(ErrorKind{"RoutingStrategy"}, std::string("network: routing strategy '") +
3392 routing_to_text(rs) + "' at node '" + nd.name +
3393 "' has no routing-matrix expansion in this port");
3394 // THE DESTINATIONS ARE THE NODE'S CONNECTIONS, NOT THIS CLASS'S
3395 // OWN ARCS. `getRoutingMatrix.m:117-135` enumerates `sn.connmatrix`
3396 // -- a class-INDEPENDENT topology -- and routes same-class over
3397 // it, which is what makes a class that declared no arc at a node
3398 // it nevertheless reaches get a routing at all. Reading the
3399 // class's own entries instead left such a row EMPTY, and an empty
3400 // row is not a visit: on `gallery_erlerl1`, where Class1 declares
3401 // Source->Queue and Class2 declares Queue->Sink, the Queue came
3402 // out unvisited by Class1 and every metric of the model was zero.
3403 // The `served` mask in `refresh_visits` is what keeps the fill
3404 // honest -- it drops the (station, class) pairs with no service.
3405 //
3406 // A CLOSED CLASS IS NOT ROUTED INTO A SINK, and not out of a
3407 // Source at all, which is the same branch's rule: a sink would
3408 // absorb a job the population must conserve.
3409 const bool open_class = !std::isfinite(
3410 num_traits<T>::to_double(classes[r - 1].population));
3411 const bool from_source = nd.nodetype == NodeType::Source;
3412 const bool from_sink = nd.nodetype == NodeType::Sink;
3413 if (!open_class && (from_source || from_sink)) continue;
3414 std::vector<std::pair<std::size_t, std::size_t>> dest; // (node, class)
3415 for (std::size_t j = 1; j <= I; ++j) {
3416 if (!open_class && nodes[j - 1].nodetype == NodeType::Sink) continue;
3417 if (conn[(i - 1) * I + (j - 1)]) dest.emplace_back(j, r);
3418 }
3419 if (dest.empty()) continue;
3420 // WRROBIN SPREADS BY ITS WEIGHTS, everything else uniformly.
3421 // That is `getRoutingMatrix.m`'s split and it keeps the FIRST
3422 // MOMENT right for a weighted dispatcher, which a uniform
3423 // expansion would not.
3424 std::vector<T> share(dest.size(),
3426 num_traits<T>::from_int(static_cast<long>(dest.size()))));
3427 if (rs == RoutingStrategy::WRROBIN) {
3428 const std::map<std::size_t, double>* w =
3429 nd.routing_weights.size() >= r ? &nd.routing_weights[r - 1] : NULL;
3430 double total = 0.0;
3431 std::vector<double> raw(dest.size(), 0.0);
3432 if (w != NULL)
3433 for (std::size_t d = 0; d < dest.size(); ++d) {
3434 const std::map<std::size_t, double>::const_iterator it =
3435 w->find(dest[d].first);
3436 raw[d] = (it == w->end()) ? 0.0 : it->second;
3437 total += raw[d];
3438 }
3439 if (total > 0.0)
3440 for (std::size_t d = 0; d < dest.size(); ++d)
3441 share[d] = num_traits<T>::from_double(raw[d] / total);
3442 }
3443 // Clear row i of every (r,s) block that exists: an absent block already reads as zero,
3444 // and materialising all K^2 of them only to zero one row is K^2 I^2 of memory
3445 for (std::size_t s = 1; s <= K; ++s) {
3446 if (Peff.find(std::make_pair(r, s)) == Peff.end()) continue;
3447 Matrix<T>& B = eff_at(r, s);
3448 for (std::size_t j = 1; j <= I; ++j) B(i - 1, j - 1) = zero;
3449 }
3450 for (std::size_t d = 0; d < dest.size(); ++d)
3451 eff_at(r, dest[d].second)(i - 1, dest[d].first - 1) = share[d];
3452 }
3453 }
3454
3455 // ClassSwitch: split the outgoing mass across the class-switch matrix.
3456 for (const auto& kv : csmatrix) {
3457 const std::size_t cs = kv.first;
3458 const Matrix<T>& C = kv.second;
3459 if (C.rows() != K || C.cols() != K)
3460 throw InputError("network: the class-switch matrix of node '" +
3461 nodes[cs - 1].name + "' is not (nclasses x nclasses)");
3462 // WHERE A SWITCHED JOB GOES IS THE ARRIVAL CLASS'S ROUTING, NOT THE
3463 // DEPARTURE CLASS'S. `getRoutingMatrix.m`'s StatelessClassSwitcher
3464 // block sets rtnodes(r, (j-1)*K+s) = Pcs(r,s) * Pij(s,s): the
3465 // destination distribution is read off the DIAGONAL, i.e. from the
3466 // row class s routes on with, and only the mass is Pcs(r,s).
3467 // Reading class r's own outgoing row instead is the same matrix
3468 // only when every class of the chain leaves the switch the same
3469 // way. Where they do not -- `Delay -> CS1 -> Queue -> CS2 -> Delay`
3470 // with each class Disabled at the station it does not visit, so
3471 // each class is routed on one arc of the cycle only -- class r has
3472 // NO outgoing arc at the switch it enters, the whole block comes
3473 // out zero, and the two classes then fall into separate chains with
3474 // empty visits. The state space collapses to its initial state and
3475 // the CTMC, NC and MVA answers are an empty table, not an error.
3476 std::vector<std::vector<T>> diag(K, std::vector<T>(I, zero));
3477 for (std::size_t s = 1; s <= K; ++s) {
3478 if (!Peff.empty() && Peff.find(std::make_pair(s, s)) == Peff.end()) continue;
3479 for (std::size_t j = 1; j <= I; ++j)
3480 diag[s - 1][j - 1] =
3481 Peff.empty() ? get_route(s, s, cs, j) : eff_at(s, s)(cs - 1, j - 1);
3482 }
3483 // Zero row cs only in blocks that exist: an absent block reads as zero, and eff_at on all K^2 pairs materialised them
3484 for (std::size_t r = 1; r <= K; ++r)
3485 for (std::size_t s = 1; s <= K; ++s) {
3486 if (Peff.find(std::make_pair(r, s)) == Peff.end()) continue;
3487 Matrix<T>& B = eff_at(r, s);
3488 for (std::size_t j = 1; j <= I; ++j) B(cs - 1, j - 1) = zero;
3489 }
3490 for (std::size_t r = 1; r <= K; ++r)
3491 for (std::size_t s = 1; s <= K; ++s) {
3492 if (!(C(r - 1, s - 1) > zero)) continue;
3493 Matrix<T>& B = eff_at(r, s);
3494 for (std::size_t j = 1; j <= I; ++j)
3495 if (diag[s - 1][j - 1] > zero)
3496 B(cs - 1, j - 1) = T(diag[s - 1][j - 1] * C(r - 1, s - 1));
3497 }
3498 }
3499
3500 // Cache: the read (input) class self-switches at the cache node to the
3501 // hit and the miss class, which then follow their own routing. The
3502 // reference leaves the split unresolved (NaN) in the base struct and the
3503 // solver decides it; for the visit equations that back the offered
3504 // arrival rate and residence time it resolves to a uniform 1/2 - 1/2,
3505 // which is what makes ArvR the OFFERED rate (Tput is the carried one the
3506 // cacheqn decomposition produces). A half of the read mass reaching each
3507 // of hit/miss is a same-node class switch, hence a self-loop edge.
3508 const T half = T(num_traits<T>::from_int(1) / num_traits<T>::from_int(2));
3509 for (const auto& kv : nodeparam) {
3510 const std::size_t ci = kv.first; // 1-based cache node
3511 const CacheParam<T>& cp = kv.second;
3512 for (std::size_t r = 0; r < cp.hitclass.size() && r < K; ++r) {
3513 if (cp.hitclass[r] == 0) continue;
3514 // clear the read class's own outgoing routing at the cache
3515 for (std::size_t s = 1; s <= K; ++s) {
3516 Matrix<T>& B = eff_at(r + 1, s);
3517 for (std::size_t j = 1; j <= I; ++j) B(ci - 1, j - 1) = zero;
3518 }
3519 eff_at(r + 1, cp.hitclass[r])(ci - 1, ci - 1) = half;
3520 if (r < cp.missclass.size() && cp.missclass[r] != 0)
3521 eff_at(r + 1, cp.missclass[r])(ci - 1, ci - 1) = half;
3522 }
3523 }
3524 }
3525
3526 /**
3527 * The number of siblings the fork-join pair ending at Join node `joinNode`
3528 * (1-based) emits per parent job: the matched Fork's out-degree times its
3529 * tasksPerLink, with the Join's in-degree as the fallback when no Fork is
3530 * matched. Port of `matlab/src/api/fj/sn_join_siblings.m`.
3531 *
3532 * Read off the DECLARED routing `P` rather than off `rtnodes`, because
3533 * `refresh_capacity` asks this question and runs BEFORE `refresh_rt`. The
3534 * two differ only on a declared link that carries no mass, which forks no
3535 * sibling either.
3536 */
3537 std::size_t join_siblings(std::size_t joinNode, std::size_t r = 0) const {
3538 const std::size_t I = nodes.size();
3539 if (joinNode == 0 || joinNode > I) return 0;
3540 std::size_t forkNode = 0;
3541 for (std::size_t a = 0; a < fj.size(); ++a)
3542 if (fj[a].second == joinNode) {
3543 forkNode = fj[a].first;
3544 break;
3545 }
3546 const T zero = num_traits<T>::from_int(0);
3547 std::vector<bool> seen(I + 1, false);
3548 std::size_t deg = 0;
3549 for (typename std::map<std::pair<std::size_t, std::size_t>, Matrix<T> >::const_iterator
3550 it = P.begin();
3551 it != P.end(); ++it) {
3552 if (it->second.rows() < I || it->second.cols() < I) continue;
3553 for (std::size_t b = 1; b <= I; ++b) {
3554 if (seen[b]) continue;
3555 const T v = (forkNode != 0) ? it->second(forkNode - 1, b - 1)
3556 : it->second(b - 1, joinNode - 1);
3557 if (v > zero) {
3558 seen[b] = true;
3559 ++deg;
3560 }
3561 }
3562 }
3563 if (forkNode == 0 || forkNode > I) return deg;
3564
3565 // THE COUNT IS PER LINK when the fork carries a VARIABLE FORKING LEVEL.
3566 // `fan_out_link(d,r)` is the expected tasks towards destination d for
3567 // class r (the DISTRIBUTION case stores its mean there) and
3568 // `fan_out_prob(d,r)` whether the branch fires at all, so the expected
3569 // sibling count is sum_d fan_out_prob(d,r)*fan_out_link(d,r). A fork
3570 // with no override has no `forkparam` entry, which is how the classic
3571 // out-degree times `tasks_per_link` case is told apart.
3572 const ForkParam<T>* fp = fork_param_of(forkNode);
3573 if (fp != 0 && fp->fan_out_link.rows() > 0) {
3574 const Matrix<T>& fol = fp->fan_out_link;
3575 const bool haveProb = fp->fan_out_prob.rows() == fol.rows() &&
3576 fp->fan_out_prob.cols() == fol.cols();
3577 const std::size_t lo = (r != 0 && r <= fol.cols()) ? r - 1 : 0;
3578 const std::size_t hi = (r != 0 && r <= fol.cols()) ? r - 1 : fol.cols() - 1;
3579 double best = 0.0;
3580 for (std::size_t c = lo; c <= hi && c < fol.cols(); ++c) {
3581 double acc = 0.0;
3582 for (std::size_t d = 0; d < fol.rows(); ++d) {
3583 const double link = num_traits<T>::to_double(fol(d, c));
3584 if (!(link > 0.0)) continue;
3585 acc += link * (haveProb ? num_traits<T>::to_double(fp->fan_out_prob(d, c))
3586 : 1.0);
3587 }
3588 if (acc > best) best = acc;
3589 }
3590 if (best > 0.0) return static_cast<std::size_t>(best + 0.5);
3591 }
3592
3593 double w = nodes[forkNode - 1].tasks_per_link;
3594 if (!(w >= 1.0)) w = 1.0;
3595 return deg * static_cast<std::size_t>(w + 0.5);
3596 }
3597
3598 /**
3599 * The 1-based Join nodes that fire on a STRICT quorum, i.e. on FEWER
3600 * siblings than are forked. A model holding one is not
3601 * population-conserving at the sibling level: the join releases the parent
3602 * at the k-th of n siblings and the n-k stragglers stay in their branches,
3603 * so the parent forks again while they are still in flight.
3604 */
3605 std::vector<std::size_t> quorum_joins() const {
3606 std::vector<std::size_t> out;
3607 for (typename std::map<std::size_t, JoinDecl>::const_iterator it = joindecl.begin();
3608 it != joindecl.end(); ++it) {
3609 if (it->second.strategy != lang::JoinStrategy::PARTIAL) continue;
3610 if (it->second.quorum <= 0.0) continue;
3611 const std::size_t n = join_siblings(it->first);
3612 const std::size_t k = static_cast<std::size_t>(it->second.quorum + 0.5);
3613 if (n == 0 || k < n) out.push_back(it->first);
3614 }
3615 return out;
3616 }
3617
3618 /**
3619 * Port of MNetwork.refreshCapacity.
3620 *
3621 * `classcap(i,r)` is the population of r's CHAIN, cut down by any explicit
3622 * per-class or per-station buffer, and 0 where the class does not visit the
3623 * station; `cap(i)` is the explicit station buffer when there is one, and
3624 * otherwise the smaller of the chain and class sums.
3625 *
3626 * `chaincap` IS K COLUMNS WIDE, NOT nchains, exactly as the reference sizes
3627 * it (`chaincap = Inf*ones(M,K)`). The last class of a chain wins the write,
3628 * so a chain with a class disabled at station i can leave chaincap(i,c) at
3629 * 0; under class switching, where nchains < K, the untouched columns stay
3630 * Inf and carry the sum, which is what stops that 0 from capping a station
3631 * that holds the whole chain population at nothing.
3632 *
3633 * The derived drop rule follows the reference exactly, including that WAITQ
3634 * means "never consulted" at an unbounded station and "unsettled" for a
3635 * closed class at a bounded one: only an OPEN class at a real finite buffer
3636 * gets DROP.
3637 *
3638 * A PLACE IS EXEMPT FROM THE ZEROING. `disabled` is this port's marker for
3639 * the reference's `isnan(sn.rates(i,r))`, and a Place holds a marking
3640 * rather than serving, so it has no service process and every class reads
3641 * as disabled there. Zeroing it leaves a token container that cannot hold a
3642 * token: `cap` and `classcap` both come out 0, JMT is handed a Storage
3643 * section of capacity 0, and the net is dead on arrival. `refreshCapacity.m`
3644 * carries the same `~= NodeType.Place` guard on its `isnan` test.
3645 */
3647 const std::size_t M = stations.size(), K = classes.size();
3648 const double inf = std::numeric_limits<double>::infinity();
3649 cap.assign(M, 0.0);
3650 classcap.assign(M, std::vector<double>(K, inf));
3651 droprule.assign(M, std::vector<DropStrategy>(K, DropStrategy::WAITQ));
3652 std::vector<std::vector<double>> chaincap(M, std::vector<double>(std::max(nchains, K), inf));
3653
3654 // A class routed into a QUORUM Join is not population-conserving: the
3655 // stragglers of an already-fired parent are still in their branches
3656 // when it forks again, and nothing bounds that backlog, so a branch
3657 // station holds no more than the class population only under a STANDARD
3658 // join. Capping it at the chain population makes the engine drop a
3659 // closed job. see _kb/05-solvers-overview.md
3660 std::vector<char> quorum_class(K + 1, 0);
3661 {
3662 const std::vector<std::size_t> qj = quorum_joins();
3663 const T zero = num_traits<T>::from_int(0);
3664 for (std::size_t x = 0; x < qj.size(); ++x)
3665 for (typename std::map<std::pair<std::size_t, std::size_t>,
3666 Matrix<T> >::const_iterator it = P.begin();
3667 it != P.end(); ++it) {
3668 if (it->second.rows() < nodes.size() || qj[x] > nodes.size()) continue;
3669 for (std::size_t a = 1; a <= nodes.size(); ++a)
3670 if (it->second(a - 1, qj[x] - 1) > zero) {
3671 if (it->first.first <= K) quorum_class[it->first.first] = 1;
3672 if (it->first.second <= K) quorum_class[it->first.second] = 1;
3673 }
3674 }
3675 }
3676
3677 // A fork with tasksPerLink = w > 1 puts w tasks of the SAME parent on one
3678 // link, so a branch station can hold w jobs per circulating parent and the
3679 // chain population is no longer its bound. The multiplier is the PRODUCT
3680 // over the forks, because a fork nested in another's branch multiplies
3681 // again; that is an upper bound for forks in series, where a cap that never
3682 // binds costs nothing, and exact for the single-fork case. Without it this
3683 // engine drops a closed job at a branch station.
3684 double fork_task_factor = 1.0;
3685 for (std::size_t i = 0; i < nodes.size(); ++i) {
3686 if (nodes[i].nodetype != NodeType::Fork) continue;
3687 const double w = nodes[i].tasks_per_link;
3688 if (w >= 1.0 && std::isfinite(w)) fork_task_factor *= std::floor(w + 0.5);
3689 }
3690
3691 for (std::size_t c = 0; c < nchains; ++c) {
3692 double chain_cap = 0.0;
3693 bool open = false;
3694 bool quorum = false;
3695 for (std::size_t r : inchain[c]) {
3696 if (std::isinf(classes[r - 1].population)) open = true;
3697 else chain_cap += classes[r - 1].population;
3698 if (r <= K && quorum_class[r]) quorum = true;
3699 }
3700 // A chain holding a spawn TARGET gains a job on every trigger completion, so it is not population-conserving
3701 // either (refreshCapacity.m spawnFedChain); capping it at its population makes the engine drop phase-2 jobs
3702 bool spawn_fed = false;
3703 for (std::size_t q = 0; q < K && !spawn_fed; ++q)
3704 for (std::size_t r : inchain[c])
3705 if (classes[q].spawn == r) spawn_fed = true;
3706 chain_cap *= fork_task_factor;
3707 if (open || quorum || spawn_fed) chain_cap = inf;
3708 for (std::size_t r : inchain[c])
3709 for (std::size_t i = 0; i < M; ++i) {
3710 const Station<T>& st = stations[i];
3711 const bool user_rule = st.droprule.size() >= r && st.droprule[r - 1] != 0;
3712 if (st.nodetype != NodeType::Source) {
3713 const bool cap_finite = st.cap >= 0.0 && !std::isinf(st.cap);
3714 const bool classcap_finite = st.classcap.size() >= r &&
3715 st.classcap[r - 1] > 0.0 &&
3716 !std::isinf(st.classcap[r - 1]);
3717 if (user_rule &&
3718 st.droprule[r - 1] == static_cast<int>(DropStrategy::WAITQ) &&
3719 std::isinf(classes[r - 1].population) &&
3720 (cap_finite || classcap_finite))
3721 throw UnsupportedError(ErrorKind{"FiniteCapacity"},
3722 "station '" + st.name + "' declares setDropRule(WAITQ) for the "
3723 "open class '" + classes[r - 1].name + "' at a finite capacity: "
3724 "LINE does not implement waiting-room blocking for an open "
3725 "arrival at a plain finite buffer. Use DropStrategy.DROP for a "
3726 "loss station, or BAS / BBS / RSRD for blocking between "
3727 "stations");
3728 if (user_rule) {
3729 droprule[i][r - 1] = static_cast<DropStrategy>(st.droprule[r - 1]);
3730 } else if (std::isinf(st.cap)) {
3731 droprule[i][r - 1] = DropStrategy::WAITQ;
3732 } else if (!std::isinf(classes[r - 1].population)) {
3733 droprule[i][r - 1] = DropStrategy::WAITQ;
3734 } else {
3735 droprule[i][r - 1] = DropStrategy::DROP;
3736 }
3737 }
3738 // A Place has no service process, so `disabled` is not absence.
3739 if (disabled[i][r - 1] && st.nodetype != NodeType::Place) {
3740 classcap[i][r - 1] = 0.0;
3741 chaincap[i][c] = 0.0;
3742 continue;
3743 }
3744 chaincap[i][c] = chain_cap;
3745 classcap[i][r - 1] = chain_cap;
3746 if (st.classcap.size() >= r && st.classcap[r - 1] >= 0.0)
3747 classcap[i][r - 1] = std::min(classcap[i][r - 1], st.classcap[r - 1]);
3748 if (st.cap >= 0.0) classcap[i][r - 1] = std::min(classcap[i][r - 1], st.cap);
3749 }
3750 }
3751 for (std::size_t i = 0; i < M; ++i) {
3752 if (stations[i].cap >= 0.0 && !std::isinf(stations[i].cap)) {
3753 cap[i] = stations[i].cap;
3754 continue;
3755 }
3756 double sc = 0.0, scl = 0.0;
3757 for (std::size_t c = 0; c < chaincap[i].size(); ++c) sc += chaincap[i][c];
3758 for (std::size_t r = 0; r < K; ++r) scl += classcap[i][r];
3759 cap[i] = std::min(sc, scl);
3760 }
3761 }
3762
3763 /**
3764 * `sn.rt` and `sn.rtnodes`: the class-expanded routing matrices.
3765 *
3766 * rtnodes is the routing over every node; rt is its stochastic complement
3767 * over the stateful ones, which is the same construction the per-chain
3768 * visits use -- but over ALL classes at once rather than one chain at a
3769 * time, because that is what `sn.rt` means and what solver_qna reads.
3770 */
3771 void refresh_rt() {
3772 const T zero = num_traits<T>::from_int(0);
3773 const std::size_t K = classes.size(), I = nodes.size();
3774 std::vector<std::size_t> all(K);
3775 for (std::size_t r = 0; r < K; ++r) all[r] = r + 1;
3776 rtnodes = Matrix<T>(I * K, I * K, zero);
3777 // route_eff over every entry is (I*K)^2 map finds; the blocks that exist hold every nonzero
3778 for_each_route_block([&](std::size_t r, std::size_t s, const Matrix<T>& M) {
3779 for (std::size_t a = 0; a < I; ++a)
3780 for (std::size_t b = 0; b < I; ++b) rtnodes(a * K + r - 1, b * K + s - 1) = M(a, b);
3781 });
3782 rt = station_routing(all);
3783 }
3784
3785 /**
3786 * Re-resolve the cache read self-switch from the offered 1/2-1/2 to the
3787 * ACTUAL hit/miss probabilities the cacheqn decomposition converged on, then
3788 * recompute `rt` and the visits. The runner reads ArvR and ResidT off the
3789 * result, matching MATLAB whose `sn.visits` carry the actual
3790 * (setResultHitProb) split, not the offered one. Served metrics are
3791 * unaffected: they come from the analyzer's own over-routed inner solve.
3792 * `hitprob`/`missprob` are (ncaches x nclasses), indexed by cache order and
3793 * input class, exactly as `da_cacheqn` returns them.
3794 */
3795 void refresh_cacheqn_actual_visits(const Matrix<T>& hitprob, const Matrix<T>& missprob) {
3796 const T zero = num_traits<T>::from_int(0);
3797 const std::size_t K = classes.size();
3798 std::size_t cidx = 0;
3799 for (const auto& kv : nodeparam) {
3800 const std::size_t ci = kv.first; // 1-based cache node
3801 const CacheParam<T>& cp = kv.second;
3802 for (std::size_t r = 0; r < cp.hitclass.size() && r < K; ++r) {
3803 if (cp.hitclass[r] == 0) continue;
3804 set_route_effective(r + 1, cp.hitclass[r], ci, ci, hitprob(cidx, r));
3805 if (r < cp.missclass.size() && cp.missclass[r] != 0)
3806 set_route_effective(r + 1, cp.missclass[r], ci, ci, missprob(cidx, r));
3807 }
3808 ++cidx;
3809 }
3810 refresh_rt();
3811 const bool fork = has_fork();
3812 visits.assign(nchains, Matrix<T>(stateful_nodes.size(), nclasses, zero));
3813 nodevisits.assign(nchains, Matrix<T>(nodes.size(), nclasses, zero));
3814 for (std::size_t c = 0; c < nchains; ++c) {
3815 visits[c] = chain_visits(c, stateful_nodes, true, fork);
3816 nodevisits[c] = chain_visits(c, all_nodes(), false, fork);
3817 }
3818 }
3819
3820 /**
3821 * Port of MNetwork.refreshRates: lower each service process onto a rate and
3822 * an SCV. A disabled (station, class) pair becomes NaN, which is the marker
3823 * every downstream consumer keys on to mean "this class never visits here".
3824 */
3826 nstations = stations.size();
3827 nclasses = classes.size();
3828 const T zero = num_traits<T>::from_int(0);
3830 scv = Matrix<T>(nstations, nclasses, zero);
3831 disabled.assign(nstations, std::vector<bool>(nclasses, true));
3832 for (std::size_t i = 0; i < nstations; ++i)
3833 for (std::size_t r = 0; r < nclasses; ++r) {
3834 // Join infinite-rate rationale: see _kb/04-networkstruct.md (cpp port notes)
3835 if (stations[i].nodetype == NodeType::Join) {
3836 disabled[i][r] = false;
3838 std::numeric_limits<double>::infinity());
3839 scv(i, r) = zero;
3840 continue;
3841 }
3842 const Distrib<T>& d = service[i][r];
3843 if (d.disabled) continue;
3844 disabled[i][r] = false;
3845 // A MARKED class receives ONLY ITS MARK'S stream, so its rate is
3846 // the mark's, not the shared process's. `set_marked_arrival`
3847 // binds one `Distrib` to every marked class, so `d.rate()` is
3848 // `1/mean` of the AGGREGATE and reports the whole stream K times
3849 // over -- 2.5 apiece on `cache_mmap_rr_env` against 1.9 and 0.6.
3850 const std::size_t mk = markidx_of(i + 1, r + 1);
3851 if (mk > 0 && mk <= d.Dmark.size()) {
3852 const std::pair<T, T> ms = mark_marginal_moments(d, mk);
3853 rates(i, r) = num_traits<T>::to_double(ms.first) > 0
3854 ? T(num_traits<T>::from_int(1) / ms.first)
3856 scv(i, r) = ms.second;
3857 continue;
3858 }
3859 rates(i, r) = d.rate();
3860 scv(i, r) = d.scv;
3861 }
3862 }
3863
3864 /**
3865 * Mean and SCV of ONE MARK'S MARGINAL MAP, `MarkedMAP.toMAPs(k)`.
3866 *
3867 * The marginal moves the OTHER marks' arrivals into the hidden part:
3868 * `D0' = D0 + (D1 - D1k)`, `D1' = D1k` (`MarkedMAP.m:130-140`,
3869 * `refreshRates.m:56-63`). It is what a consumer that sees only class k
3870 * experiences, and it is NOT the aggregate restricted -- an arrival of
3871 * another mark still moves the shared chain, it just is not an arrival here.
3872 *
3873 * `D0' + D1' = D0 + D1`, so the marginal keeps the aggregate's phase
3874 * generator and its rate reduces to `pi D1k e`; only the SCV needs the
3875 * second moment, which is why this goes through `map_scv` rather than
3876 * stopping at the rate.
3877 */
3878 std::pair<T, T> mark_marginal_moments(const Distrib<T>& d, std::size_t mk) const {
3879 mam::Map<T> m;
3880 m.D0 = d.D0;
3881 m.D1 = d.Dmark[mk - 1];
3882 for (std::size_t a = 0; a < m.D0.rows(); ++a)
3883 for (std::size_t b = 0; b < m.D0.cols(); ++b)
3884 m.D0(a, b) += T(d.D1(a, b) - m.D1(a, b));
3885 return std::make_pair(mam::map_mean(m), mam::map_scv(m));
3886 }
3887
3888 /**
3889 * Port of MNetwork.refreshChains followed by sn_refresh_visits.
3890 *
3891 * The class-switch mask is (r == s) or "some link carries r into s", which
3892 * is what link() records in csMatrix and what refreshChains then re-derives
3893 * from `rt`; the chains are the connected components of that mask read as
3894 * an undirected graph. MATLAB orders the chains by `sortrows(...,'descend')`
3895 * on the indicator rows, which for disjoint components is the same as
3896 * ordering by their smallest class index, and that is what is done here.
3897 */
3899 refresh_rates();
3900 const T zero = num_traits<T>::from_int(0);
3901 const std::size_t K = nclasses;
3902
3903 // class-switch mask rationale: see _kb/04-networkstruct.md (cpp port notes)
3904 std::vector<std::vector<bool>> cs(K, std::vector<bool>(K, false));
3905 for (std::size_t r = 0; r < K; ++r) cs[r][r] = true;
3906 for (const auto& kv : (Peff.empty() ? P : Peff)) {
3907 bool any = false;
3908 for (std::size_t a = 0; a < kv.second.rows() && !any; ++a)
3909 for (std::size_t b = 0; b < kv.second.cols() && !any; ++b)
3910 if (kv.second(a, b) > zero) any = true;
3911 if (any) cs[kv.first.first - 1][kv.first.second - 1] = true;
3912 }
3913 // A ClassSwitch NODE couples classes too, and once `link()` synthesizes
3914 // one the coupling lives ONLY here: the rewrite folds `P{r,s}(i,j)` into
3915 // a same-class pair of legs, so the r != s block that used to carry it
3916 // is gone from P. `link.m` accumulates the same thing --
3917 // `csMatrix = csMatrix | nodes{ind}.server.csMatrix > 0` -- and without
3918 // it every switched class falls into its own chain.
3919 for (const auto& kv : csmatrix) {
3920 const Matrix<T>& C = kv.second;
3921 for (std::size_t r = 0; r < K && r < C.rows(); ++r)
3922 for (std::size_t s = 0; s < K && s < C.cols(); ++s)
3923 if (C(r, s) > zero) cs[r][s] = true;
3924 }
3925 // A Cache node couples each input class with the classes it switches to
3926 // on a hit and a miss; that coupling lives in nodeparam, not in P, so it
3927 // must be added here or the read/hit/miss classes fall into separate
3928 // chains and the switched (open) classes get no arrivals.
3929 for (const auto& kv : nodeparam) {
3930 const CacheParam<T>& cp = kv.second;
3931 for (std::size_t r = 0; r < cp.hitclass.size() && r < K; ++r) {
3932 if (cp.hitclass[r] != 0) cs[r][cp.hitclass[r] - 1] = true;
3933 if (r < cp.missclass.size() && cp.missclass[r] != 0)
3934 cs[r][cp.missclass[r] - 1] = true;
3935 }
3936 // A RETRIEVAL class is also a class the cache switches the read
3937 // class into on a miss -- it just lives in `retrieval_classes`
3938 // rather than in `missclass`, because there is one per ITEM. The
3939 // coupling above missed them, so on a closed delayed-hit model each
3940 // retrieval class formed its own singleton chain: 4 chains where
3941 // MATLAB has 1, with zero visits at the fetch station and the whole
3942 // population parked at the delay. The rule in the comment above
3943 // applies to them unchanged.
3944 for (const std::vector<std::size_t>& row : cp.retrieval_classes)
3945 for (std::size_t r = 0; r < row.size() && r < K; ++r)
3946 if (row[r] != 0) cs[r][row[r] - 1] = true;
3947 }
3948 csmask = cs;
3949 std::vector<std::size_t> comp(K, K);
3950 std::size_t ncomp = 0;
3951 for (std::size_t r = 0; r < K; ++r) {
3952 if (comp[r] != K) continue;
3953 std::vector<std::size_t> stack{r};
3954 comp[r] = ncomp;
3955 while (!stack.empty()) {
3956 const std::size_t v = stack.back();
3957 stack.pop_back();
3958 for (std::size_t w = 0; w < K; ++w)
3959 if (comp[w] == K && (cs[v][w] || cs[w][v])) {
3960 comp[w] = ncomp;
3961 stack.push_back(w);
3962 }
3963 }
3964 ++ncomp;
3965 }
3966 // components are already discovered in order of their smallest member,
3967 // which is the order sortrows(...,'descend') produces
3968 nchains = ncomp;
3969 chains.assign(nchains, std::vector<bool>(K, false));
3970 inchain.assign(nchains, {});
3971 for (std::size_t r = 0; r < K; ++r) {
3972 chains[comp[r]][r] = true;
3973 inchain[comp[r]].push_back(r + 1);
3974 }
3975
3976 // ---- reference class per chain -------------------------------------
3977 refclass.assign(nchains, 0);
3978 for (std::size_t c = 0; c < nchains; ++c)
3979 for (std::size_t k : inchain[c])
3980 if (classes[k - 1].is_ref_class) refclass[c] = k;
3981
3982 for (std::size_t c = 0; c < nchains; ++c) {
3983 const std::size_t rs = classes[inchain[c][0] - 1].refstat;
3984 for (std::size_t k : inchain[c])
3985 if (classes[k - 1].refstat != rs)
3986 throw InputError("network '" + name + "': classes within a chain have different "
3987 "reference stations");
3988 }
3989
3991
3992 // ---- visits, at stateful-node and at node level ---------------------
3993 const bool fork = has_fork();
3994 visits.assign(nchains, Matrix<T>(stateful_nodes.size(), nclasses, zero));
3995 nodevisits.assign(nchains, Matrix<T>(nodes.size(), nclasses, zero));
3996 for (std::size_t c = 0; c < nchains; ++c) {
3997 visits[c] = chain_visits(c, stateful_nodes, true, fork);
3998 nodevisits[c] = chain_visits(c, all_nodes(), false, fork);
3999 }
4000 }
4001
4002 /**
4003 * Route every open chain from the Sink back into the Source, as the tail of
4004 * MATLAB's getRoutingMatrix does before it takes the stochastic complement.
4005 *
4006 * WHY IT IS NOT OPTIONAL. `visits` is the stationary vector of the chain's
4007 * routing DTMC. An open chain that ends at the Sink has no such vector --
4008 * the Sink is absorbing, so the solve returns the point mass there and
4009 * every station comes out with zero visits. The closing arc turns the open
4010 * chain into a recurrent one whose stationary vector, renormalised by the
4011 * Source, is the visit count PER ARRIVAL, which is what the chain demands
4012 * are built from.
4013 *
4014 * The destination class is drawn in proportion to the ARRIVAL RATES of the
4015 * chain's classes, so a job leaving the Sink re-enters as the class the
4016 * Source would have generated. A chain whose arrivals are all disabled has
4017 * no such proportion, and the reference falls back to the uniform choice
4018 * rather than dividing by zero -- those chains carry no traffic and only
4019 * need to stay well posed.
4020 *
4021 * The arcs are rebuilt on every refresh, and the previous ones cleared
4022 * first: the rates move between passes of the fork-join fixed point, and a
4023 * stale arc would leave two closures with different weights in place.
4024 */
4026 if (sourceIdx == 0 || sinkNode == 0) return;
4027 const T zero = num_traits<T>::from_int(0);
4028 const T one = num_traits<T>::from_int(1);
4029 const std::size_t src = station_to_node[sourceIdx - 1];
4030 // closure-clearing rationale: see _kb/04-networkstruct.md (cpp port notes)
4031 for (auto& kv : P) {
4032 if (kv.second.rows() < nodes.size()) continue;
4033 kv.second(sinkNode - 1, src - 1) = zero;
4034 }
4035 for (auto& kv : Peff) {
4036 if (kv.second.rows() < nodes.size()) continue;
4037 kv.second(sinkNode - 1, src - 1) = zero;
4038 }
4039 for (std::size_t c = 0; c < nchains; ++c) {
4040 bool open = false;
4041 for (std::size_t k : inchain[c])
4042 if (std::isinf(classes[k - 1].population)) open = true;
4043 if (!open) continue;
4044 T tot = zero;
4045 for (std::size_t k : inchain[c])
4046 if (!disabled[sourceIdx - 1][k - 1]) tot += rates(sourceIdx - 1, k - 1);
4047 const T uniform =
4048 T(one / num_traits<T>::from_int(static_cast<long>(inchain[c].size())));
4049 for (std::size_t s : inchain[c]) {
4050 T p = uniform;
4051 if (tot > zero) {
4052 const T ar =
4053 disabled[sourceIdx - 1][s - 1] ? zero : rates(sourceIdx - 1, s - 1);
4054 p = T(ar / tot);
4055 }
4056 if (!(p > zero)) continue;
4057 for (std::size_t r : inchain[c]) set_route_effective(r, s, sinkNode, src, p);
4058 }
4059 }
4060 }
4061
4062 /** Every node index, 1-based, for the node-level visit computation. */
4063 std::vector<std::size_t> all_nodes() const {
4064 std::vector<std::size_t> v(nodes.size());
4065 for (std::size_t i = 0; i < nodes.size(); ++i) v[i] = i + 1;
4066 return v;
4067 }
4068
4069 /**
4070 * Port of the per-chain body of sn_refresh_visits, over an arbitrary node
4071 * subset -- the stateful nodes for `visits`, all nodes for `nodevisits`.
4072 *
4073 * The FORK CORRECTIONS are the reference's, and they are blunt on purpose.
4074 * A Fork row sums to its fan-out rather than to one, so the rows are
4075 * renormalised before the DTMC solve; afterwards, rather than trusting the
4076 * resulting stationary vector, a population-preserving SPN argument sets
4077 * EVERY visited entry to 1 (and a Join entry to its in-degree, one per
4078 * incoming branch). Reproduced exactly: the corrected visits are what the
4079 * chain demands are built from, so an "improved" version would disagree
4080 * with every other codebase.
4081 */
4082 /**
4083 * sn_refresh_visits.m chainSeeds: the positions refpos*nIC+x, in a chain block over `sel`, of the chain
4084 * classes holding jobs at the reference station: a populated closed class, or an open class with a
4085 * positive, finite rate at its source.
4086 */
4087 std::vector<std::size_t> chain_seeds(std::size_t c, const std::vector<std::size_t>& sel) const {
4088 const std::vector<std::size_t>& ic = inchain[c];
4089 const std::size_t refst = classes[ic[0] - 1].refstat; // 1-based
4090 const std::size_t refnode = station_to_node[refst - 1];
4091 std::vector<std::size_t> seeds;
4092 std::size_t refpos = sel.size();
4093 for (std::size_t a = 0; a < sel.size(); ++a)
4094 if (sel[a] == refnode) refpos = a;
4095 if (refpos == sel.size()) return seeds;
4096 for (std::size_t x = 0; x < ic.size(); ++x) {
4097 const JobClass& jc = classes[ic[x] - 1];
4098 bool held;
4099 if (std::isfinite(jc.population)) {
4100 held = jc.population > 0;
4101 } else {
4102 const bool dis = refst - 1 < disabled.size() && ic[x] - 1 < disabled[refst - 1].size() &&
4103 disabled[refst - 1][ic[x] - 1];
4104 const double rate = (refst - 1 < rates.rows() && ic[x] - 1 < rates.cols())
4105 ? num_traits<T>::to_double(rates(refst - 1, ic[x] - 1)) : 0.0;
4106 held = !dis && std::isfinite(rate) && rate > 0;
4107 }
4108 if (held) seeds.push_back(refpos * ic.size() + x);
4109 }
4110 return seeds;
4111 }
4112
4113 /**
4114 * sn_refresh_visits.m retrievalEdges: extra [from, to] chain-block positions for a retrieval cache, which
4115 * switches a read class into a per-item retrieval class INSIDE the node. The routing does not carry that
4116 * switch, so without these edges the retrieval classes, and the stations only they visit, look unreachable.
4117 */
4118 std::vector<std::pair<std::size_t, std::size_t>> chain_retrieval_edges(const std::vector<std::size_t>& ic,
4119 const std::vector<std::size_t>& sel) const {
4120 std::vector<std::pair<std::size_t, std::size_t>> edges;
4121 const std::size_t nIC = ic.size();
4122 for (const auto& kv : nodeparam) {
4123 const std::vector<std::vector<std::size_t>>& rc = kv.second.retrieval_classes;
4124 if (rc.empty()) continue;
4125 std::size_t pos = sel.size();
4126 for (std::size_t a = 0; a < sel.size(); ++a)
4127 if (sel[a] == kv.first) pos = a;
4128 if (pos == sel.size()) continue;
4129 for (std::size_t x = 0; x < nIC; ++x)
4130 for (const std::vector<std::size_t>& row : rc) {
4131 if (ic[x] - 1 >= row.size() || row[ic[x] - 1] == 0) continue;
4132 for (std::size_t y = 0; y < nIC; ++y)
4133 if (ic[y] == row[ic[x] - 1]) edges.emplace_back(pos * nIC + x, pos * nIC + y);
4134 }
4135 }
4136 return edges;
4137 }
4138
4139 /** sn_refresh_visits.m chainReachable: states reachable from the seeds along nonzero entries and the
4140 * extra `edges`; all states when there is no seed. A NaN entry counts as an edge, as `~= 0` does in the
4141 * reference. */
4142 static std::vector<bool> chain_reachable(const Matrix<T>& P, const std::vector<std::size_t>& seeds,
4143 const std::vector<std::pair<std::size_t, std::size_t>>& edges) {
4144 const std::size_t n = P.rows();
4145 if (seeds.empty()) return std::vector<bool>(n, true);
4146 std::vector<std::vector<std::size_t>> extra(n);
4147 for (const std::pair<std::size_t, std::size_t>& e : edges)
4148 if (e.first < n && e.second < n) extra[e.first].push_back(e.second);
4149 std::vector<bool> reach(n, false);
4150 std::vector<std::size_t> frontier;
4151 for (std::size_t sd : seeds)
4152 if (sd < n && !reach[sd]) {
4153 reach[sd] = true;
4154 frontier.push_back(sd);
4155 }
4156 while (!frontier.empty()) {
4157 std::vector<std::size_t> nxt;
4158 for (std::size_t row : frontier) {
4159 for (std::size_t col = 0; col < n; ++col) {
4160 const double v = num_traits<T>::to_double(P(row, col));
4161 if (!reach[col] && v != 0.0) {
4162 reach[col] = true;
4163 nxt.push_back(col);
4164 }
4165 }
4166 for (std::size_t col : extra[row])
4167 if (!reach[col]) {
4168 reach[col] = true;
4169 nxt.push_back(col);
4170 }
4171 }
4172 frontier.swap(nxt);
4173 }
4174 return reach;
4175 }
4176
4177 Matrix<T> chain_visits(std::size_t c, const std::vector<std::size_t>& sel, bool complement,
4178 bool fork) const {
4179 const T zero = num_traits<T>::from_int(0);
4180 const std::vector<std::size_t>& ic = inchain[c];
4181 const std::size_t nIC = ic.size();
4182 const std::size_t dim = sel.size() * nIC;
4183 Matrix<T> Pc(dim, dim, zero);
4184 if (complement) {
4185 const Matrix<T> rt = station_routing(ic);
4186 Pc = rt;
4187 } else {
4188 // Block-wise over the routing map: route_eff per entry was dim^2 map finds per chain
4189 std::vector<std::size_t> cpos(nclasses + 1, nIC);
4190 for (std::size_t x = 0; x < nIC; ++x) cpos[ic[x]] = x;
4191 for_each_route_block([&](std::size_t r, std::size_t s, const Matrix<T>& M) {
4192 if (r > nclasses || s > nclasses) return;
4193 const std::size_t x = cpos[r], y = cpos[s];
4194 if (x == nIC || y == nIC) return;
4195 for (std::size_t a = 0; a < sel.size(); ++a)
4196 for (std::size_t b = 0; b < sel.size(); ++b)
4197 Pc(a * nIC + x, b * nIC + y) = M(sel[a] - 1, sel[b] - 1);
4198 });
4199 }
4200
4201 // THE `served` MASK of sn_refresh_visits.m, ON BOTH CHAINS.
4202 // `getRoutingMatrix` leaves a JMT-oriented UNIFORM FILL on (station,
4203 // class) pairs the class has no service at, and those states are not
4204 // reachable: a class with no service law cannot be served there. Left
4205 // in, they leak mass between what are otherwise separate recurrent
4206 // branches -- on cs_transient_class that moved Queue1 from 0.1875 to
4207 // 0.22917 and Queue2 from 0.3125 to 0.27083, against an absorption of
4208 // 0.375/0.625 halved over each two-station cycle.
4209 //
4210 // It matters MORE on the node chain, which the reference used to leave
4211 // untouched: at station level an unserved (station,class) is a dead end,
4212 // while the node kernel keeps the class-switch nodes between the
4213 // stations, so the disabled states close into a whole spurious CYCLE. A
4214 // materialised LQN replica is exactly that -- replica 2's stations still
4215 // carry replica 1's classes in rtnodes -- and the reducible solve then
4216 // splits the mass between the real chain and the phantom one, giving
4217 // every node of replica 2 a visit in replica 1's classes.
4218 //
4219 // A Place, a Transition and a station declaring heterogeneous server
4220 // types are EXEMPT, exactly as the reference exempts them: all three
4221 // carry NaN station rates by construction, so the test would read as
4222 // "not served" for a station that plainly is.
4223 std::vector<bool> served(dim, true);
4224 {
4225 for (std::size_t a = 0; a < sel.size(); ++a) {
4226 const std::size_t sti = nodes[sel[a] - 1].station;
4227 if (sti == 0 || sti > stations.size()) continue;
4228 const NodeType nt = stations[sti - 1].nodetype;
4229 if (nt == NodeType::Place || nt == NodeType::Transition) continue;
4230 if (!stations[sti - 1].server_types.empty()) continue;
4231 if (sti > disabled.size()) continue;
4232 // The reference tests `isnan(sn.rates(...))`; THIS PORT'S MARKER
4233 // IS `disabled`. refresh_rates leaves a disabled pair's rate at
4234 // 0 rather than NaN (its comment says otherwise and is stale),
4235 // so an isnan test here would never fire and the mask would be
4236 // silently inert. `disabled` is what every other consumer keys
4237 // on and it carries exactly MATLAB's meaning.
4238 for (std::size_t x = 0; x < nIC; ++x)
4239 if (ic[x] <= disabled[sti - 1].size() && disabled[sti - 1][ic[x] - 1])
4240 served[a * nIC + x] = false;
4241 }
4242 for (std::size_t row = 0; row < dim; ++row)
4243 if (!served[row])
4244 for (std::size_t col = 0; col < dim; ++col) Pc(row, col) = zero;
4245 for (std::size_t col = 0; col < dim; ++col)
4246 if (!served[col])
4247 for (std::size_t row = 0; row < dim; ++row) Pc(row, col) = zero;
4248 }
4249
4250 // keep only states a chain job can reach: an unreachable pass-through row whose successor is dropped
4251 // would otherwise leak mass out of the solved block (sn_refresh_visits.m chainReachable)
4252 const std::vector<bool> reach = chain_reachable(Pc, chain_seeds(c, sel), chain_retrieval_edges(ic, sel));
4253 std::vector<std::size_t> visited;
4254 std::vector<T> rowsum(dim, zero);
4255 for (std::size_t row = 0; row < dim; ++row) {
4256 T s = zero;
4257 for (std::size_t col = 0; col < dim; ++col) s += Pc(row, col);
4258 rowsum[row] = s;
4259 if (s > zero && reach[row]) visited.push_back(row);
4260 }
4261 bool oversum = false;
4262 if (fork) {
4263 for (std::size_t row = 0; row < dim; ++row) {
4264 if (num_traits<T>::to_double(rowsum[row]) > 1.0 + GlobalConstants::FineTol)
4265 oversum = true;
4267 for (std::size_t col = 0; col < dim; ++col)
4268 Pc(row, col) = T(Pc(row, col) / rowsum[row]);
4269 }
4270 }
4271
4272 // Detect a genuinely reducible chain up front, so its DISABLED-routing
4273 // fillers and the reducible solver apply ONLY here -- every irreducible
4274 // chain, i.e. the whole existing test surface, stays on the exact
4275 // dtmc_solve path below. In MATLAB the singular normalization solve
4276 // returns NaN here, tripping the same fallback; this reproduces that
4277 // without changing the shared solver.
4278 //
4279 // "Genuinely reducible" is more than one recurrent class AND all of them
4280 // inside ONE weak component, which is the shape MATLAB's solve actually
4281 // fails on. `ctmc_solve` (MATLAB's, the JAR's and this port's alike)
4282 // SPLITS ON WEAK COMPONENTS first, solves each on its own and
4283 // renormalizes the union, so a chain whose recurrent classes sit in
4284 // SEPARATE weak components has an answer there, and an exact one: each
4285 // component gets equal weight.
4286 //
4287 // A delayed-hit retrieval cache is exactly that second shape. Its
4288 // per-item fetch cycle (cache -> retrieval station -> cache, in that
4289 // item's retrieval class) shares no state with the read class's own
4290 // loop, because the class switch that feeds it happens INSIDE the cache
4291 // node rather than on a routing arc. Calling that reducible sends it to
4292 // `dtmc_solve_reducible`, which hands the read loop all the mass and
4293 // leaves every retrieval station with ZERO visits -- and a station with
4294 // no visits is given no capacity by `space_capacity_c`, so the CTMC then
4295 // enumerates a state space with no in-flight fetch in it at all and
4296 // reports NaN hit/miss shares. Measured on retrieval_simple before this
4297 // qualifier: 12 states where MATLAB, the JAR and native Python have 144.
4298 bool reducible = false;
4299 if (!fork && !visited.empty()) {
4300 Matrix<T> Pv0(visited.size(), visited.size(), zero);
4301 for (std::size_t a = 0; a < visited.size(); ++a)
4302 for (std::size_t b = 0; b < visited.size(); ++b) Pv0(a, b) = Pc(visited[a], visited[b]);
4303 const mc::SccResult scc = mc::stronglyconncomp(Pv0);
4304 std::size_t nrec = 0;
4305 for (bool rc : scc.recurrent)
4306 if (rc) ++nrec;
4307 reducible = (nrec > 1) && mc::detail::weak_components(Pv0).size() == 1;
4308 }
4309 if (reducible) {
4310 // DISABLED-routing filler (getRoutingMatrix.m DISABLED case): a
4311 // (node,class) with no outgoing routing at a physically connected node
4312 // routes SAME-CLASS to each neighbour at 1/nconn. These 0-visit
4313 // transient states give the reducible solver the multiple transient
4314 // SCCs MATLAB has, so it weights the recurrent classes correctly
4315 // (11:13) instead of the single-transient absorption split (3:5).
4316 std::vector<std::size_t> nconn(sel.size(), 0);
4317 std::vector<std::vector<bool>> conn(sel.size(), std::vector<bool>(sel.size(), false));
4318 for (std::size_t a = 0; a < sel.size(); ++a)
4319 for (std::size_t b = 0; b < sel.size(); ++b) {
4320 bool cbit = false;
4321 for (std::size_t x = 0; x < nIC && !cbit; ++x)
4322 for (std::size_t y = 0; y < nIC && !cbit; ++y)
4323 if (Pc(a * nIC + x, b * nIC + y) > zero) cbit = true;
4324 conn[a][b] = cbit;
4325 if (cbit) ++nconn[a];
4326 }
4327 for (std::size_t a = 0; a < sel.size(); ++a) {
4328 if (nconn[a] == 0) continue;
4329 for (std::size_t x = 0; x < nIC; ++x) {
4330 T outsum = zero;
4331 for (std::size_t col = 0; col < dim; ++col) outsum += Pc(a * nIC + x, col);
4332 if (outsum > zero) continue; // class already routes onward here
4333 const T p = num_traits<T>::from_int(1) /
4334 num_traits<T>::from_int(static_cast<long>(nconn[a]));
4335 for (std::size_t b = 0; b < sel.size(); ++b)
4336 if (conn[a][b]) Pc(a * nIC + x, b * nIC + x) = p;
4337 }
4338 }
4339 // AND THE FILLER IS MASKED AGAIN, which is the whole point of the
4340 // mask. The reference's order is: getRoutingMatrix lays the fill
4341 // down, THEN `served` zeroes those rows and columns -- so an
4342 // unserved state never carries fill in the matrix that is solved.
4343 // Synthesising the fill here and stopping would restore exactly what
4344 // the mask was ported to remove: on cs_transient_class the two
4345 // recurrent branches came out 11:13 (0.22917 / 0.27083) instead of
4346 // the absorption split 3:5 (0.1875 / 0.3125) that MATLAB, Java and
4347 // Python all report and that the routing implies.
4348 for (std::size_t row = 0; row < dim; ++row)
4349 if (!served[row])
4350 for (std::size_t col = 0; col < dim; ++col) Pc(row, col) = zero;
4351 for (std::size_t col = 0; col < dim; ++col)
4352 if (!served[col])
4353 for (std::size_t row = 0; row < dim; ++row) Pc(row, col) = zero;
4354 visited.clear();
4355 for (std::size_t row = 0; row < dim; ++row) {
4356 T s = zero;
4357 for (std::size_t col = 0; col < dim; ++col) s += Pc(row, col);
4358 if (s > zero && reach[row]) visited.push_back(row);
4359 }
4360 }
4361
4362 std::vector<T> alpha(dim, zero);
4363 if (!visited.empty()) {
4364 Matrix<T> Pv(visited.size(), visited.size(), zero);
4365 for (std::size_t a = 0; a < visited.size(); ++a)
4366 for (std::size_t b = 0; b < visited.size(); ++b)
4367 Pv(a, b) = Pc(visited[a], visited[b]);
4368 std::vector<T> av;
4369 bool ok = false;
4370 if (!reducible) {
4371 try {
4372 av = mc::dtmc_solve(Pv);
4373 ok = true;
4374 bool allzero = true, hasnan = false;
4375 for (const T& x : av) {
4376 if (x != zero) allzero = false;
4377 if (num_traits<T>::to_double(x) != num_traits<T>::to_double(x)) hasnan = true;
4378 }
4379 if (allzero || hasnan) ok = false;
4380 } catch (const Error&) {
4381 ok = false;
4382 }
4383 }
4384 if (!ok) {
4385 // DTMC solver order: see _kb/04-networkstruct.md (cpp port notes) and _kb/11-conventions-and-gotchas.md
4387 }
4388 for (std::size_t a = 0; a < visited.size(); ++a) alpha[visited[a]] = av[a];
4389
4390 // A TRANSIENT STATE HAS VISIT RATIO EXACTLY ZERO, and saying so by
4391 // the graph rather than by a tolerance is what keeps this port on
4392 // the reference's answer. `pi P = pi` puts all of its mass on the
4393 // recurrent classes, so a state whose SCC has an edge leaving it
4394 // carries none; whether the LU lands on 0 or on an eps residue is a
4395 // pivot-order accident, and MATLAB's backslash happens to land on 0
4396 // where this LU lands on 3e-17.
4397 //
4398 // That accident is not cosmetic downstream. RN is QN/TN, so a class
4399 // with an eps visit at a station reads 0/0 -- NaN in the reference,
4400 // which the H-T order statistic DROPS, and the station's full
4401 // residence time here, which it COUNTS. On the two-span H-T model
4402 // that handed Delay1 and the other fork's auxiliary delay a
4403 // residence time of 2 each for classes that never reach either, and
4404 // `ri` came out 5.747 against the reference's 1.747 -- exactly the
4405 // 2 + 2 those two rows contribute.
4406 {
4407 const mc::SccResult scc = mc::stronglyconncomp(Pv);
4408 for (std::size_t a = 0; a < visited.size(); ++a)
4409 if (!scc.recurrent[scc.scc[a] - 1]) alpha[visited[a]] = zero;
4410 }
4411 }
4412
4413 if (fork && oversum) {
4414 for (std::size_t idx = 0; idx < dim; ++idx) {
4415 if (!(num_traits<T>::to_double(alpha[idx]) > GlobalConstants::FineTol)) continue;
4416 const std::size_t nd = sel[idx / nIC];
4417 if (!complement && nodes[nd - 1].nodetype == NodeType::Join) {
4418 // a Join is entered once per incoming branch. The reference
4419 // counts POSITIVE ROWS of rtnodes in column (nd,r), i.e.
4420 // (source node, source class) PAIRS over every class -- two
4421 // classes entering the Join as r from the same predecessor
4422 // are two branches, so neither the break nor the restriction
4423 // to the chain's own classes belongs here.
4424 const std::size_t r = ic[idx % nIC];
4425 std::size_t nsrc = 0;
4426 for (std::size_t src = 1; src <= nodes.size(); ++src)
4427 for (std::size_t q = 1; q <= nclasses; ++q)
4428 if (num_traits<T>::to_double(route_eff(q, r, src, nd)) >
4430 ++nsrc;
4431 alpha[idx] = num_traits<T>::from_int(static_cast<long>(nsrc));
4432 } else {
4433 alpha[idx] = num_traits<T>::from_int(1);
4434 }
4435 }
4436 }
4437
4438 Matrix<T> out(sel.size(), nclasses, zero);
4439 for (std::size_t a = 0; a < sel.size(); ++a)
4440 for (std::size_t x = 0; x < nIC; ++x) out(a, ic[x] - 1) = alpha[a * nIC + x];
4441
4442 // normalise by the total visits of the chain at its reference node
4443 const std::size_t rstat = classes[ic[0] - 1].refstat;
4444 const std::size_t refnode = station_to_node[rstat - 1];
4445 std::size_t refrow = sel.size();
4446 for (std::size_t a = 0; a < sel.size(); ++a)
4447 if (sel[a] == refnode) refrow = a;
4448 if (refrow < sel.size()) {
4449 T norm = zero;
4450 for (std::size_t x = 0; x < nIC; ++x) norm += out(refrow, ic[x] - 1);
4452 for (std::size_t a = 0; a < sel.size(); ++a)
4453 for (std::size_t x = 0; x < nIC; ++x)
4454 out(a, ic[x] - 1) = T(out(a, ic[x] - 1) / norm);
4455 }
4456 for (std::size_t a = 0; a < sel.size(); ++a)
4457 for (std::size_t x = 0; x < nIC; ++x)
4458 if (out(a, ic[x] - 1) < zero) out(a, ic[x] - 1) = T(-out(a, ic[x] - 1));
4459 return out;
4460 }
4461
4462 /**
4463 * The visit ratios of one chain from an already-formed chain routing block
4464 * `Pc` (dim = sel.size() * nIC), the no-fork body of sn_refresh_visits: solve
4465 * the embedded DTMC over the visited states and normalise by the total visits
4466 * at the reference node. NaN entries (a Cache class switch can leave one) are
4467 * given the row's residual probability spread uniformly, as the reference
4468 * does. Fork models keep the route_eff path (`chain_visits`); this is used by
4469 * the cacheqn driver, which rewrites `rtnodes` directly and has no fork.
4470 */
4471 Matrix<T> visits_from_block(const Matrix<T>& Pc_in, const std::vector<std::size_t>& sel,
4472 const std::vector<std::size_t>& ic, std::size_t refnode) const {
4473 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
4474 const std::size_t nIC = ic.size();
4475 const std::size_t dim = Pc_in.rows();
4476 Matrix<T> Pc = Pc_in;
4477 // NaN handling: distribute the row's residual mass over the NaN columns.
4478 for (std::size_t row = 0; row < dim; ++row) {
4479 T nonnan = zero;
4480 std::size_t nnan = 0;
4481 for (std::size_t col = 0; col < dim; ++col) {
4482 const double v = num_traits<T>::to_double(Pc(row, col));
4483 if (v != v) ++nnan;
4484 else nonnan = T(nonnan + Pc(row, col));
4485 }
4486 if (nnan == 0) continue;
4487 const double rem = 1.0 - num_traits<T>::to_double(nonnan);
4488 const T fill = (rem > 0.0) ? num_traits<T>::from_double(rem / double(nnan)) : zero;
4489 for (std::size_t col = 0; col < dim; ++col) {
4490 const double v = num_traits<T>::to_double(Pc(row, col));
4491 if (v != v) Pc(row, col) = fill;
4492 }
4493 }
4494 // THE `served` MASK of sn_refresh_visits.m, as in `chain_visits` (which
4495 // documents the marker and the three exemptions). The cacheqn driver
4496 // needs it more than anyone: da_cacheqn sends the hit and miss mass to
4497 // EVERY node the cache connects to, so with two successors the read row
4498 // sums to 2 and is a stochastic row again only once the (station, class)
4499 // pairs with no service law are cut out. Without the mask the solve
4500 // renormalises the over-sum instead and halves the flow of each branch:
4501 // on a cache feeding HitQueue and MissQueue at hit probability 1/2 the
4502 // served classes came out at throughput 1/4 each instead of 1/2.
4503 {
4504 std::vector<bool> served(dim, true);
4505 for (std::size_t a = 0; a < sel.size(); ++a) {
4506 const std::size_t sti = nodes[sel[a] - 1].station;
4507 if (sti == 0 || sti > stations.size()) continue;
4508 const NodeType nt = stations[sti - 1].nodetype;
4509 if (nt == NodeType::Place || nt == NodeType::Transition) continue;
4510 if (!stations[sti - 1].server_types.empty()) continue;
4511 if (sti > disabled.size()) continue;
4512 for (std::size_t x = 0; x < nIC; ++x)
4513 if (ic[x] <= disabled[sti - 1].size() && disabled[sti - 1][ic[x] - 1])
4514 served[a * nIC + x] = false;
4515 }
4516 for (std::size_t row = 0; row < dim; ++row)
4517 if (!served[row])
4518 for (std::size_t col = 0; col < dim; ++col) Pc(row, col) = zero;
4519 for (std::size_t col = 0; col < dim; ++col)
4520 if (!served[col])
4521 for (std::size_t row = 0; row < dim; ++row) Pc(row, col) = zero;
4522 }
4523 std::size_t chain = nchains;
4524 for (std::size_t c = 0; c < nchains; ++c)
4525 if (inchain[c] == ic) chain = c;
4526 const std::vector<bool> reach =
4527 chain_reachable(Pc, chain < nchains ? chain_seeds(chain, sel) : std::vector<std::size_t>(),
4528 chain_retrieval_edges(ic, sel));
4529 std::vector<std::size_t> visited;
4530 for (std::size_t row = 0; row < dim; ++row) {
4531 T s = zero;
4532 for (std::size_t col = 0; col < dim; ++col) s += Pc(row, col);
4533 if (s > zero && reach[row]) visited.push_back(row);
4534 }
4535 std::vector<T> alpha(dim, zero);
4536 if (!visited.empty()) {
4537 Matrix<T> Pv(visited.size(), visited.size(), zero);
4538 for (std::size_t a = 0; a < visited.size(); ++a)
4539 for (std::size_t b = 0; b < visited.size(); ++b) Pv(a, b) = Pc(visited[a], visited[b]);
4540 std::vector<T> av;
4541 bool ok = false;
4542 try {
4543 av = mc::dtmc_solve(Pv);
4544 ok = true;
4545 bool allzero = true, hasnan = false;
4546 for (const T& x : av) {
4547 if (x != zero) allzero = false;
4548 if (num_traits<T>::to_double(x) != num_traits<T>::to_double(x)) hasnan = true;
4549 }
4550 if (allzero || hasnan) ok = false;
4551 } catch (const Error&) {
4552 ok = false;
4553 }
4555 for (std::size_t a = 0; a < visited.size(); ++a) alpha[visited[a]] = av[a];
4556 }
4557 Matrix<T> out(sel.size(), nclasses, zero);
4558 for (std::size_t a = 0; a < sel.size(); ++a)
4559 for (std::size_t x = 0; x < nIC; ++x) out(a, ic[x] - 1) = alpha[a * nIC + x];
4560 std::size_t refrow = sel.size();
4561 for (std::size_t a = 0; a < sel.size(); ++a)
4562 if (sel[a] == refnode) refrow = a;
4563 if (refrow < sel.size()) {
4564 T norm = zero;
4565 for (std::size_t x = 0; x < nIC; ++x) norm += out(refrow, ic[x] - 1);
4567 for (std::size_t a = 0; a < sel.size(); ++a)
4568 for (std::size_t x = 0; x < nIC; ++x)
4569 out(a, ic[x] - 1) = T(out(a, ic[x] - 1) / norm);
4570 }
4571 for (std::size_t a = 0; a < sel.size(); ++a)
4572 for (std::size_t x = 0; x < nIC; ++x)
4573 if (out(a, ic[x] - 1) < zero) out(a, ic[x] - 1) = T(-out(a, ic[x] - 1));
4574 return out;
4575 }
4576
4577 /**
4578 * Recompute `rt`, `visits` and `nodevisits` after the caller has rewritten
4579 * `rtnodes` in place -- the cacheqn driver's per-sweep refresh. `rt` is the
4580 * stochastic complement of `rtnodes` over the stateful (node, class) rows;
4581 * the per-chain visits then read directly off `rt` (stateful) and `rtnodes`
4582 * (all nodes), with the chains held FIXED (the reference does not recompute
4583 * them inside the sweep). No-fork only; a fork keeps the refresh path.
4584 */
4586 const T zero = num_traits<T>::from_int(0);
4587 const std::size_t K = nclasses, I = nodes.size(), M = stateful_nodes.size();
4588 for (const NodeDef& nd : nodes)
4589 if (nd.nodetype == NodeType::Fork)
4590 throw UnsupportedError(ErrorKind{"Fork"}, "da_recompute_visits_from_rtnodes: fork models keep the "
4591 "route_eff visit path");
4592 std::vector<std::size_t> keep;
4593 keep.reserve(M * K);
4594 for (std::size_t p = 0; p < M; ++p) {
4595 const std::size_t base = (stateful_nodes[p] - 1) * K;
4596 for (std::size_t r = 0; r < K; ++r) keep.push_back(base + r);
4597 }
4598 rt = mc::dtmc_stochcomp(rtnodes, keep);
4599
4600 std::vector<std::size_t> allnodes(I);
4601 for (std::size_t a = 0; a < I; ++a) allnodes[a] = a + 1;
4602 visits.assign(nchains, Matrix<T>(M, K, zero));
4603 nodevisits.assign(nchains, Matrix<T>(I, K, zero));
4604 for (std::size_t c = 0; c < nchains; ++c) {
4605 const std::vector<std::size_t>& ic = inchain[c];
4606 const std::size_t nIC = ic.size();
4607 // stateful visits from rt (ordered by stateful position)
4608 Matrix<T> Ps(M * nIC, M * nIC, zero);
4609 for (std::size_t a = 0; a < M; ++a)
4610 for (std::size_t x = 0; x < nIC; ++x)
4611 for (std::size_t b = 0; b < M; ++b)
4612 for (std::size_t y = 0; y < nIC; ++y)
4613 Ps(a * nIC + x, b * nIC + y) = rt(a * K + (ic[x] - 1), b * K + (ic[y] - 1));
4614 const std::size_t rstat = classes[ic[0] - 1].refstat;
4615 const std::size_t refnode = station_to_node[rstat - 1];
4616 // sel for the stateful block is the stateful node list; its "refnode"
4617 // position must be matched by node index, so pass stateful_nodes.
4618 visits[c] = visits_from_block(Ps, stateful_nodes, ic, refnode);
4619 // node visits from rtnodes (ordered by node)
4620 Matrix<T> Pn(I * nIC, I * nIC, zero);
4621 for (std::size_t a = 0; a < I; ++a)
4622 for (std::size_t x = 0; x < nIC; ++x)
4623 for (std::size_t b = 0; b < I; ++b)
4624 for (std::size_t y = 0; y < nIC; ++y)
4625 Pn(a * nIC + x, b * nIC + y) =
4626 rtnodes(a * K + (ic[x] - 1), b * K + (ic[y] - 1));
4627 nodevisits[c] = visits_from_block(Pn, allnodes, ic, refnode);
4628 }
4629 }
4630
4631 /**
4632 * The chain-restricted routing over the STATEFUL nodes: the node-level
4633 * routing with the non-stateful nodes eliminated by a stochastic
4634 * complement, S = P11 + P12 (I - P22)^-1 P21. That is MATLAB's
4635 * dtmc_stochcomp, and it is what removes a Fork (and, there, the auto-added
4636 * ClassSwitch nodes) from the visit equations.
4637 */
4638 Matrix<T> station_routing(const std::vector<std::size_t>& ic) const {
4639 const T zero = num_traits<T>::from_int(0);
4640 const std::size_t nIC = ic.size();
4641 const std::size_t I = nodes.size();
4642 Matrix<T> full(I * nIC, I * nIC, zero);
4643 std::vector<std::size_t> pos(classes.size() + 1, 0); // class -> 1-based position in ic
4644 for (std::size_t x = 0; x < nIC; ++x) pos[ic[x]] = x + 1;
4645 for_each_route_block([&](std::size_t r, std::size_t s, const Matrix<T>& M) {
4646 if (r >= pos.size() || s >= pos.size() || pos[r] == 0 || pos[s] == 0) return;
4647 const std::size_t x = pos[r] - 1, y = pos[s] - 1;
4648 for (std::size_t a = 0; a < I; ++a)
4649 for (std::size_t b = 0; b < I; ++b) full(a * nIC + x, b * nIC + y) = M(a, b);
4650 });
4651 return stoch_comp_stateful(full, nIC);
4652 }
4653
4654 /**
4655 * Visit every (r, s) block of the routing in force, the one route_eff reads: Peff when the
4656 * expansion ran, else P. A block smaller than nnodes reads as zero there, so it is skipped.
4657 */
4658 template <class F>
4659 void for_each_route_block(F f) const {
4660 const std::map<std::pair<std::size_t, std::size_t>, Matrix<T>>& src = Peff.empty() ? P : Peff;
4661 for (const auto& kv : src)
4662 if (kv.second.rows() >= nodes.size() && kv.second.cols() >= nodes.size())
4663 f(kv.first.first, kv.first.second, kv.second);
4664 }
4665
4666 /**
4667 * The stochastic complement of a NODE-level routing block over the stateful
4668 * nodes, S = P11 + P12 (I - P22)^-1 P21.
4669 *
4670 * Split out of `station_routing` because the STATE-DEPENDENT routing table
4671 * (`rt_state`, state.h) is the same complement of a block whose SDR rows
4672 * have been re-evaluated at one state: the two must eliminate the stateless
4673 * nodes identically, or the per-state table and `rt` would disagree on a
4674 * model that merely has a Router in it.
4675 *
4676 * @param full node-major (nnodes * nIC) square block
4677 * @param nIC number of classes carried per node in that block
4678 */
4679 Matrix<T> stoch_comp_stateful(const Matrix<T>& full, std::size_t nIC) const {
4680 const T zero = num_traits<T>::from_int(0);
4681 const T one = num_traits<T>::from_int(1);
4682 const std::size_t I = nodes.size();
4683 std::vector<std::size_t> keep, drop;
4684 for (std::size_t a = 0; a < I; ++a) {
4685 const bool st = nodes[a].stateful;
4686 for (std::size_t x = 0; x < nIC; ++x) (st ? keep : drop).push_back(a * nIC + x);
4687 }
4688 if (drop.empty()) return full;
4689 // Only the stateless states a stateful one can reach enter S = P11 + P12 X, and that set is
4690 // closed under P22, so its own sub-system gives X exactly. On a flattened LQN nearly every
4691 // (node, class) pair is unreachable, and eliminating them all was cubic in nnodes*nclasses.
4692 {
4693 std::vector<char> isdrop(full.rows(), 0), seen(full.rows(), 0);
4694 for (std::size_t d : drop) isdrop[d] = 1;
4695 std::vector<std::size_t> stack;
4696 for (std::size_t k : keep)
4697 for (std::size_t d : drop)
4698 if (!seen[d] && full(k, d) != zero) { seen[d] = 1; stack.push_back(d); }
4699 while (!stack.empty()) {
4700 const std::size_t u = stack.back();
4701 stack.pop_back();
4702 for (std::size_t d : drop)
4703 if (!seen[d] && full(u, d) != zero) { seen[d] = 1; stack.push_back(d); }
4704 }
4705 std::vector<std::size_t> reach;
4706 for (std::size_t d : drop)
4707 if (seen[d]) reach.push_back(d);
4708 drop.swap(reach);
4709 }
4710 if (drop.empty()) {
4711 Matrix<T> S(keep.size(), keep.size(), zero);
4712 for (std::size_t a = 0; a < keep.size(); ++a)
4713 for (std::size_t b = 0; b < keep.size(); ++b) S(a, b) = full(keep[a], keep[b]);
4714 return S;
4715 }
4716
4717 const std::size_t nk = keep.size(), nd = drop.size();
4718 Matrix<T> P11(nk, nk, zero), P12(nk, nd, zero), P21(nd, nk, zero), A(nd, nd, zero);
4719 for (std::size_t a = 0; a < nk; ++a) {
4720 for (std::size_t b = 0; b < nk; ++b) P11(a, b) = full(keep[a], keep[b]);
4721 for (std::size_t b = 0; b < nd; ++b) P12(a, b) = full(keep[a], drop[b]);
4722 }
4723 for (std::size_t a = 0; a < nd; ++a) {
4724 for (std::size_t b = 0; b < nk; ++b) P21(a, b) = full(drop[a], keep[b]);
4725 for (std::size_t b = 0; b < nd; ++b)
4726 A(a, b) = T((a == b ? one : zero) - full(drop[a], drop[b]));
4727 }
4728 // X = A^-1 P21 by Gaussian elimination with partial pivoting
4729 Matrix<T> X = P21;
4730 std::vector<std::size_t> piv(nd);
4731 for (std::size_t i = 0; i < nd; ++i) piv[i] = i;
4732 for (std::size_t col = 0; col < nd; ++col) {
4733 std::size_t best = col;
4734 double bv = std::fabs(num_traits<T>::to_double(A(col, col)));
4735 for (std::size_t r2 = col + 1; r2 < nd; ++r2) {
4736 const double v = std::fabs(num_traits<T>::to_double(A(r2, col)));
4737 if (v > bv) { bv = v; best = r2; }
4738 }
4739 if (best != col) {
4740 for (std::size_t b = 0; b < nd; ++b) std::swap(A(col, b), A(best, b));
4741 for (std::size_t b = 0; b < nk; ++b) std::swap(X(col, b), X(best, b));
4742 }
4743 if (A(col, col) == zero)
4744 throw NumericError(ErrorKind{"Singular"}, "network: the stochastic complement is singular");
4745 // The update touches only the pivot row's nonzero columns; a zero one would change nothing
4746 std::vector<std::size_t> nzA, nzX;
4747 for (std::size_t b = 0; b < nd; ++b)
4748 if (A(col, b) != zero) nzA.push_back(b);
4749 for (std::size_t b = 0; b < nk; ++b)
4750 if (X(col, b) != zero) nzX.push_back(b);
4751 for (std::size_t r2 = 0; r2 < nd; ++r2) {
4752 if (r2 == col) continue;
4753 const T f = T(A(r2, col) / A(col, col));
4754 if (f == zero) continue;
4755 for (std::size_t b : nzA) A(r2, b) = T(A(r2, b) - f * A(col, b));
4756 for (std::size_t b : nzX) X(r2, b) = T(X(r2, b) - f * X(col, b));
4757 }
4758 }
4759 for (std::size_t r2 = 0; r2 < nd; ++r2)
4760 for (std::size_t b = 0; b < nk; ++b) X(r2, b) = T(X(r2, b) / A(r2, r2));
4761
4762 // Same summation order as the dense product, with the zero terms of P12 skipped
4763 Matrix<T> S = P11;
4764 std::vector<T> acc(nk, zero);
4765 for (std::size_t a = 0; a < nk; ++a) {
4766 std::fill(acc.begin(), acc.end(), zero);
4767 for (std::size_t m = 0; m < nd; ++m) {
4768 const T w = P12(a, m);
4769 if (w == zero) continue;
4770 for (std::size_t b = 0; b < nk; ++b) acc[b] += w * X(m, b);
4771 }
4772 for (std::size_t b = 0; b < nk; ++b) S(a, b) = T(S(a, b) + acc[b]);
4773 }
4774 return S;
4775 }
4776
4777 // ---- predicates, ports of the sn_has_* family -------------------------
4778
4779 bool has_open_classes() const {
4780 for (const JobClass& c : classes)
4781 if (std::isinf(c.population)) return true;
4782 return false;
4783 }
4784
4785 /**
4786 * `sn_is_open_model`: EVERY class is open, which is not `has_open_classes`.
4787 * A mixed model passes that predicate and fails this one, and an analyzer
4788 * that confuses the two hands a closed chain to a solver with no level for
4789 * its population. An empty class list is not an open model either.
4790 */
4791 bool is_open_model() const {
4792 for (const JobClass& c : classes)
4793 if (!std::isinf(c.population)) return false;
4794 return !classes.empty();
4795 }
4796
4797 bool has_multi_server() const {
4798 for (const Station<T>& s : stations)
4799 if (std::isfinite(s.nservers) && s.nservers > 1.0) return true;
4800 return false;
4801 }
4802
4804 for (const JobClass& c : classes)
4805 if (std::isfinite(c.population) && c.population != std::floor(c.population + 0.5))
4806 return true;
4807 return false;
4808 }
4809
4810 bool has_class_switching() const { return nclasses != nchains; }
4811
4812 bool has_priorities() const {
4813 for (const JobClass& c : classes)
4814 if (c.prio > 0) return true;
4815 return false;
4816 }
4817
4818 /**
4819 * Whether the classes carry more than one priority level.
4820 *
4821 * NOT `has_priorities()`, which asks whether any priority is nonzero: a
4822 * model whose classes all sit at level 1 has priorities by that test and
4823 * nothing to distinguish, and the reference's warning below keys on the
4824 * distinction rather than on the magnitude.
4825 */
4827 if (classes.empty()) return false;
4828 for (const JobClass& c : classes)
4829 if (c.prio != classes.front().prio) return true;
4830 return false;
4831 }
4832
4833 /**
4834 * Whether some station runs a discipline that READS the class priorities.
4835 *
4836 * The list is exactly the `*PRIO` family. Priority-awareness is a property
4837 * of the DECLARED policy and is never inferred from the data: a base policy
4838 * is not upgraded because the classes it was handed carry unequal
4839 * priorities. `afterEventStation` did infer it once, and plain LCFS with
4840 * distinct priorities then behaved as none of the three policies involved.
4841 */
4843 for (const Station<T>& s : stations) {
4844 switch (s.sched) {
4845 case SchedStrategy::HOL:
4846 case SchedStrategy::PSPRIO:
4847 case SchedStrategy::DPSPRIO:
4848 case SchedStrategy::GPSPRIO:
4849 case SchedStrategy::LCFSPRIO:
4850 case SchedStrategy::LCFSPRPRIO:
4851 case SchedStrategy::LCFSPIPRIO:
4852 case SchedStrategy::FCFSPRPRIO:
4853 case SchedStrategy::FCFSPIPRIO:
4854 case SchedStrategy::SRPTPRIO:
4855 return true;
4856 default:
4857 break;
4858 }
4859 }
4860 return false;
4861 }
4862
4863 /** Priorities were declared and no station will read them. */
4864 bool priorities_ignored() const {
4866 }
4867
4868 /**
4869 * Port of sn_has_homogeneous_scheduling: true when EVERY station uses
4870 * `strategy`, the reference's `length(findstring(sn.sched, strategy)) ==
4871 * sn.nstations` (the count of stations whose discipline is `strategy`
4872 * equals the station count), as the JAR and Python ports evaluate it and
4873 * as solver_amva's "trivial models" dispatch reads it. This port used to
4874 * reduce it to `nstations == 1`; it now follows the reference.
4875 */
4877 std::size_t count = 0;
4878 for (std::size_t i = 0; i < nstations && i < stations.size(); ++i)
4879 if (stations[i].sched == strategy) ++count;
4880 return count == nstations;
4881 }
4882
4884 bool bad = false;
4885 for (std::size_t i = 0; i < nstations; ++i) {
4886 if (stations[i].sched != SchedStrategy::FCFS) continue;
4887 bool any = false;
4889 for (std::size_t r = 0; r < nclasses; ++r) {
4890 if (disabled[i][r]) continue; // MATLAB drops the NaN entries here
4891 if (!any) {
4892 lo = hi = rates(i, r);
4893 any = true;
4894 } else {
4895 if (rates(i, r) < lo) lo = rates(i, r);
4896 if (rates(i, r) > hi) hi = rates(i, r);
4897 }
4898 }
4899 // Relative FineTol, not hi > lo: a one-ulp spread in LN layer rates flipped exact MVA vs AMVA
4900 if (any && num_traits<T>::to_double(hi - lo) >
4902 bad = true;
4903 }
4904 return bad;
4905 }
4906
4908 for (const Station<T>& s : stations)
4909 if (!(s.sched == SchedStrategy::INF || s.sched == SchedStrategy::PS ||
4910 s.sched == SchedStrategy::FCFS || s.sched == SchedStrategy::LCFSPR ||
4911 s.sched == SchedStrategy::LCFS || s.sched == SchedStrategy::EXT))
4912 return false;
4913 return true;
4914 }
4915
4916 /**
4917 * BCMP type 1 asks the FCFS service to be exponential. `has_multi_class_heter_fcfs`
4918 * compares the class MEANS only, so a class-homogeneous Erlang, hyper-exponential or
4919 * deterministic FCFS station used to pass this gate and be dispatched to exact MVA,
4920 * which reads the means alone and returns the exponential answer with no warning.
4921 */
4923 for (std::size_t i = 0; i < nstations; ++i) {
4924 if (stations[i].sched != SchedStrategy::FCFS) continue;
4925 for (std::size_t r = 0; r < nclasses; ++r) {
4926 const double v = num_traits<T>::to_double(scv(i, r));
4927 if (std::isinf(v) || !(v > 0.0)) continue;
4928 if (!(v > 1.0 - GlobalConstants::FineTol && v < 1.0 + GlobalConstants::FineTol))
4929 return false;
4930 }
4931 }
4932 return true;
4933 }
4934
4935 /**
4936 * Kendall's K of station IST (1-based), +inf when unbounded. Implementation of
4937 * api/sn/sn_get_buffer_size.h, which delegates here so the solvers' member calls and
4938 * the api free function cannot drift; the traps are documented on that header.
4939 */
4940 double buffer_size(std::size_t ist) const {
4941 double k = std::numeric_limits<double>::infinity();
4942 if (cap[ist - 1] >= 0.0) k = std::min(k, cap[ist - 1]);
4943 double ccap = 0.0;
4944 bool anyServed = false;
4945 for (std::size_t r = 0; r < nclasses; ++r)
4946 if (classcap[ist - 1][r] > 0.0) {
4947 ccap += classcap[ist - 1][r];
4948 anyServed = true;
4949 }
4950 if (anyServed) k = std::min(k, ccap);
4951 // Only the classes served here count, as in the reference: with none (every chain
4952 // reaching the station has population 0, e.g. a chain parked by sn_zero_capacity)
4953 // nothing can arrive, and summing every class instead read the zero cap as blocking.
4954 double reachable = 0.0;
4955 for (std::size_t r = 0; r < nclasses; ++r)
4956 if (classcap[ist - 1][r] > 0.0) reachable += classes[r].population;
4957 return (k >= reachable) ? std::numeric_limits<double>::infinity() : k;
4958 }
4959
4960 /** Implementation of api::sn_is_mm1k_loss; that free function delegates here. */
4961 bool is_mm1k_loss() const {
4962 if (nclasses != 1 || nodes.size() != 3) return false;
4963 for (std::size_t k = 0; k < classes.size(); ++k)
4964 if (std::isfinite(classes[k].population)) return false; // nclosedjobs ~= 0
4965 std::size_t nq = 0, nsrc = 0, nsink = 0, qnode = 0, snode = 0;
4966 for (std::size_t a = 0; a < nodes.size(); ++a) {
4967 switch (nodes[a].nodetype) {
4968 case NodeType::Queue: ++nq; qnode = a + 1; break;
4969 case NodeType::Source: ++nsrc; snode = a + 1; break;
4970 case NodeType::Sink: ++nsink; break;
4971 default: return false;
4972 }
4973 }
4974 if (nq != 1 || nsrc != 1 || nsink != 1) return false;
4975 const std::size_t qist = nodes[qnode - 1].station;
4976 const std::size_t sist = nodes[snode - 1].station;
4977 if (qist == 0 || sist == 0) return false;
4978 if (stations[qist - 1].nservers != 1.0) return false;
4979 if (droprule.size() < qist || droprule[qist - 1].empty() ||
4980 droprule[qist - 1][0] != DropStrategy::DROP)
4981 return false;
4982 if (!(qist <= cap.size()) || !std::isfinite(cap[qist - 1]) || !(cap[qist - 1] > 0.0))
4983 return false;
4984 if (std::fabs(num_traits<T>::to_double(scv(sist - 1, 0)) - 1.0) > 1e-6) return false;
4985 if (std::fabs(num_traits<T>::to_double(scv(qist - 1, 0)) - 1.0) > 1e-6) return false;
4986 // A DECLARED STATE DEPENDENCE IS NOT AN M/M/1/K. Both closed forms this
4987 // predicate gates read ONE service rate -- `qsys_mm1k_loss` a scalar mu,
4988 // `qsys_mg1k_loss_mgs` the first two moments of one service law -- so a
4989 // station carrying lldscaling, cdscaling or jdscaling would be answered with
4990 // the UNSCALED queue: a wrong number, not a coarse one, and silent.
4991 const qn::Station<T>& qst = stations[qist - 1];
4992 if (!qst.lldscaling.empty() || static_cast<bool>(qst.cdscaling) ||
4993 static_cast<bool>(qst.jdscaling))
4994 return false;
4995 return true;
4996 }
4997
4998 /**
4999 * Some station can REFUSE a job: its own buffer BINDS, or a finite capacity region
5000 * caps a set of stations jointly. Implementation of api::sn_has_blocking, which
5001 * delegates here; the rule and its two exemptions are documented on that function.
5002 */
5003 bool has_blocking() const {
5004 if (!regions.empty()) return true;
5005 for (std::size_t a = 0; a < nodes.size(); ++a)
5006 if (nodes[a].nodetype == NodeType::Cache) return false;
5007 if (is_mm1k_loss()) return false;
5008 for (std::size_t ist = 1; ist <= stations.size(); ++ist)
5009 if (std::isfinite(buffer_size(ist))) return true;
5010 return false;
5011 }
5012
5013 /** `sn_has_sd_routing`: RROBIN, WRROBIN, JSQ, SQ or SDR at some node. */
5014 bool has_sd_routing() const {
5015 for (const NodeDef& n : nodes)
5016 for (RoutingStrategy rs : n.routing)
5017 if (rs == RoutingStrategy::RROBIN || rs == RoutingStrategy::WRROBIN ||
5018 rs == RoutingStrategy::JSQ || rs == RoutingStrategy::SQ || rs == RoutingStrategy::SDR)
5019 return true;
5020 return false;
5021 }
5022
5023 /**
5024 * `sn_has_product_form`, conjunct for conjunct. A surviving Fork/Join pair (`fj`, which the
5025 * MMT and H-T transforms clear) and state-dependent routing are not product form: without
5026 * them the exact NC and MVA gates offered 'exact' on a fork-join model the reference refuses.
5027 */
5028 bool has_product_form() const {
5029 // BCMP asks for infinite buffers: without this conjunct a BAS-blocked station or
5030 // any binding finite buffer read as product form, though its truncation couples
5031 // the station occupancies.
5033 fj.empty() && !has_sd_routing() && !has_blocking() && has_exponential_fcfs();
5034 }
5035
5036 /**
5037 * Port of sn_has_product_form_not_het_fcfs: LCFS is excluded, and at FCFS the service
5038 * must be exponential AND class-independent, which is what BCMP type 1 asks for. With
5039 * unequal per-class means the product-form solve returns a wait proportional to each
5040 * class's own demand where FCFS makes every class wait behind the same queue. The mean
5041 * comparison is between CHAIN service times (visit-weighted over the classes that
5042 * actually visit the station): a class that never visits cannot break product form,
5043 * and within-chain heterogeneity is invisible to both the product-form and the qd
5044 * branch, which deaggregate a chain result proportionally to each class's own demand,
5045 * so only between-chain heterogeneity warrants the divert. LN layers carry seeded
5046 * rates for classes with zero visits, which a raw per-class comparison mistakes for
5047 * heterogeneity.
5048 *
5049 * CHECK_MEANS drops the mean test; pass false only for an algorithm
5050 * that models class-dependent FCFS itself (ab, schmidt, schmidt-ext).
5051 */
5052 bool has_product_form_not_het_fcfs(bool check_means = true) const {
5053 for (const Station<T>& s : stations)
5054 if (!(s.sched == SchedStrategy::INF || s.sched == SchedStrategy::PS ||
5055 s.sched == SchedStrategy::FCFS || s.sched == SchedStrategy::LCFSPR ||
5056 s.sched == SchedStrategy::EXT))
5057 return false;
5058 if (has_priorities()) return false;
5059 for (std::size_t i = 0; i < nstations; ++i) {
5060 if (stations[i].sched != SchedStrategy::FCFS) continue;
5061 for (std::size_t r = 0; r < nclasses; ++r) {
5062 if (disabled[i][r]) continue;
5063 const double v = num_traits<T>::to_double(scv(i, r));
5064 if (!std::isinf(v) && v > 0.0 &&
5065 !(v > 1.0 - GlobalConstants::FineTol && v < 1.0 + GlobalConstants::FineTol))
5066 return false;
5067 }
5068 if (!check_means || visits.empty()) continue;
5069 const std::size_t isf = stateful_of_station(i + 1) - 1;
5070 double stmin = 0.0, stmax = 0.0;
5071 bool anyserved = false;
5072 for (std::size_t c = 0; c < nchains && c < visits.size(); ++c) {
5073 double num = 0.0, den = 0.0;
5074 for (std::size_t r = 0; r < nclasses; ++r) {
5075 if (!chains.empty() && !chains[c][r]) continue;
5076 if (disabled[i][r]) continue;
5077 const double w = num_traits<T>::to_double(visits[c](isf, r));
5078 const double rate = num_traits<T>::to_double(rates(i, r));
5079 if (w > GlobalConstants::Zero && std::isfinite(rate) && rate > 0.0) {
5080 num += w / rate;
5081 den += w;
5082 }
5083 }
5084 if (den > 0.0) {
5085 const double st = num / den;
5086 if (!anyserved) {
5087 stmin = stmax = st;
5088 anyserved = true;
5089 } else {
5090 stmin = std::min(stmin, st);
5091 stmax = std::max(stmax, st);
5092 }
5093 }
5094 }
5095 if (anyserved && stmax - stmin > GlobalConstants::CoarseTol * stmax) return false;
5096 }
5097 return true;
5098 }
5099
5100 /** Grow every routing block to the current node count. */
5102 for (auto& kv : P) grow_block(kv.second);
5103 }
5104 void grow_block(Matrix<T>& B) const {
5105 if (B.rows() == nodes.size()) return;
5106 Matrix<T> g(nodes.size(), nodes.size(), num_traits<T>::from_int(0));
5107 for (std::size_t a = 0; a < B.rows(); ++a)
5108 for (std::size_t b = 0; b < B.cols(); ++b) g(a, b) = B(a, b);
5109 B = g;
5110 }
5111
5112 /** Total population, as MATLAB's getNumberOfJobs summed. */
5113 double total_jobs() const {
5114 double s = 0.0;
5115 for (const JobClass& c : classes)
5116 if (std::isfinite(c.population)) s += c.population;
5117 return s;
5118 }
5119};
5120
5121/**
5122 * The swap graph of a PAS / OI station, with the defaults `refreshLocalVars.m`
5123 * installs applied.
5124 *
5125 * MATLAB fills `sn.nodeparam{ind}.swapGraph` at refresh time and NEVER leaves it
5126 * empty: an OI station always gets `zeros(R,R)`, a PAS station with no explicit
5127 * graph gets the complete compatibility graph `ones(R,R) - eye(R)`, and an
5128 * explicit graph is taken as given. The builder here stores the raw user graph,
5129 * so the defaulting has to happen on read; doing it here rather than in the
5130 * builder keeps it independent of whether the classes were added before or
5131 * after `set_service_rate_function`.
5132 *
5133 * @param sn the struct
5134 * @param ist 1-based station index
5135 */
5136template <class T>
5138 const Station<T>& st = sn.stations[ist - 1];
5139 const std::size_t R = sn.nclasses;
5140 const T zero = num_traits<T>::from_int(0);
5141 if (st.sched == SchedStrategy::OI) return Matrix<T>(R, R, zero);
5142 if (!st.swap_graph.empty()) return st.swap_graph;
5143 if (st.sched != SchedStrategy::PAS) return Matrix<T>(R, R, zero);
5145 for (std::size_t r = 0; r < R; ++r) g(r, r) = zero;
5146 return g;
5147}
5148
5149/** True when the station's materialized swap graph is entirely zero. */
5150template <class T>
5151bool station_swap_graph_is_zero(const NetworkStruct<T>& sn, std::size_t ist) {
5152 const Matrix<T> g = station_swap_graph(sn, ist);
5153 const T zero = num_traits<T>::from_int(0);
5154 for (std::size_t a = 0; a < g.rows(); ++a)
5155 for (std::size_t b = 0; b < g.cols(); ++b)
5156 if (g(a, b) != zero) return false;
5157 return true;
5158}
5159
5160/**
5161 * Port of `sn_is_oi_loss.m`: an open Source -> Queue -> Sink system (any number
5162 * of classes, each visiting the queue once) whose queue is an order-independent
5163 * station (OI, or PAS with an all-zero swap graph, with a service-rate function)
5164 * holding a finite total capacity or a finite per-class capacity for some class,
5165 * with arrivals beyond it lost (DROP, or the WAITQ default of a class-cap-only
5166 * station, which a Source-fed queue cannot honour and every state-space solver
5167 * drops). This is the regime of `qsys_oi_loss` (Berezner, Krzesinski 1996): the
5168 * loss queue is exact only in isolation, since truncation destroys
5169 * quasi-reversibility.
5170 *
5171 * Lives here rather than in api/sn for the reason `is_mm1k_loss` does: the
5172 * feature sets in lang/qn read it, and `api::sn_is_oi_loss` forwards to it.
5173 *
5174 * @param sn the refreshed struct
5175 * @param qist when non-null, receives the queue's 1-based station index (0 when false)
5176 */
5177template <class T>
5178bool is_oi_loss(const NetworkStruct<T>& sn, std::size_t* qist = nullptr) {
5179 if (qist) *qist = 0;
5180 for (const JobClass& c : sn.classes)
5181 if (std::isfinite(c.population)) return false;
5182 if (sn.nodes.size() != 3) return false;
5183 std::size_t nq = 0, nsrc = 0, nsink = 0, qnode = 0, snode = 0;
5184 for (std::size_t a = 0; a < sn.nodes.size(); ++a) {
5185 switch (sn.nodes[a].nodetype) {
5186 case NodeType::Queue: ++nq; qnode = a + 1; break;
5187 case NodeType::Source: ++nsrc; snode = a + 1; break;
5188 case NodeType::Sink: ++nsink; break;
5189 default: return false;
5190 }
5191 }
5192 if (nq != 1 || nsrc != 1 || nsink != 1) return false;
5193 const std::size_t q = sn.nodes[qnode - 1].station;
5194 const std::size_t src = sn.nodes[snode - 1].station;
5195 if (q == 0 || src == 0) return false;
5196 const Station<T>& st = sn.stations[q - 1];
5197 if (st.sched != SchedStrategy::OI && st.sched != SchedStrategy::PAS) return false;
5198 if (!st.svc_rate_fun) return false;
5199 if (!station_swap_graph_is_zero(sn, q)) return false;
5200 bool finite = q <= sn.cap.size() && std::isfinite(sn.cap[q - 1]);
5201 if (!finite && q <= sn.classcap.size())
5202 for (double cc : sn.classcap[q - 1])
5203 if (std::isfinite(cc)) finite = true;
5204 if (!finite) return false;
5205 // the reference tests sn.lldscaling/cdscaling/jdscaling as whole-model fields
5206 for (const Station<T>& s : sn.stations)
5207 if (!s.lldscaling.empty() || static_cast<bool>(s.cdscaling) ||
5208 static_cast<bool>(s.jdscaling))
5209 return false;
5210 const T zero = num_traits<T>::from_int(0);
5211 for (std::size_t r = 0; r < sn.nclasses; ++r) {
5212 if (!(sn.rates(src - 1, r) > zero)) continue;
5213 if (q <= sn.droprule.size() && r < sn.droprule[q - 1].size()) {
5214 const DropStrategy d = sn.droprule[q - 1][r];
5215 if (d != DropStrategy::DROP && d != DropStrategy::WAITQ) return false;
5216 }
5217 std::size_t chain = 0;
5218 for (std::size_t c = 0; c < sn.nchains; ++c)
5219 if (sn.chains[c][r]) chain = c + 1;
5220 if (chain == 0 || chain > sn.visits.size()) return false;
5221 const double vs =
5222 num_traits<T>::to_double(sn.visits[chain - 1](sn.stateful_of_station(src) - 1, r));
5223 const double vq =
5224 num_traits<T>::to_double(sn.visits[chain - 1](sn.stateful_of_station(q) - 1, r));
5225 if (!(vs > 0.0) || std::fabs(vq / vs - 1.0) > 1e-9)
5226 return false; // feedback or bypass: not a single-visit loss queue
5227 }
5228 if (qist) *qist = q;
5229 return true;
5230}
5231
5232} // namespace qn
5233} // namespace line
5234
5235#endif // LINE_LANG_QN_NETWORK_STRUCT_H
Base error for the multiprecision C++ port.
Definition error.h:73
InputError(const std::string &what)
Definition error.h:105
std::size_t cols() const
Definition matrix.h:90
std::size_t rows() const
Definition matrix.h:89
NumericError(const std::string &what)
Definition error.h:112
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
void set_route(std::size_t r, std::size_t s, std::size_t i, std::size_t j, const T &p)
P{r,s}(i,j) = p, with 1-based NODE and class indices.
std::size_t sourceIdx
1-based station index of the Source, 0 = none
Matrix< double > phases() const
sn.phases (M x K), as refreshProcessRepresentations.m leaves it: 0 for a disabled pair,...
bool has_multi_class_heter_fcfs() const
bool has_distinct_priorities() const
Whether the classes carry more than one priority level.
std::size_t nvars_of(std::size_t ind) const
Total local-variable width of node ind (1-based).
pfqn::SdrStruct sdr_nodes
Node-indexed twin of sdr.
std::size_t add_class(const JobClass &cl)
Add a class and grow the service table.
T get_route(std::size_t r, std::size_t s, std::size_t i, std::size_t j) const
P{r,s}(i,j), AS THE USER SET IT.
std::vector< Matrix< T > > nodevisits
(nchains) each (nnodes x nclasses)
void refresh_rates()
Port of MNetwork.refreshRates: lower each service process onto a rate and an SCV.
std::vector< double > node_to_stateful() const
sn.nodeToStateful (1 x N): the stateful index of each node, NaN when it is not stateful.
bool has_fluid_places() const
sn_has_fluid_places: does the net hold a fluid place, or a transition declaring a fluid arc?
std::function< std::complex< double >(const std::complex< double > &)> LstHandle
One LST handle: E[exp(-sX)] at a complex argument.
std::vector< std::size_t > chain_seeds(std::size_t c, const std::vector< std::size_t > &sel) const
Port of the per-chain body of sn_refresh_visits, over an arbitrary node subset – the stateful nodes f...
Matrix< T > chain_visits(std::size_t c, const std::vector< std::size_t > &sel, bool complement, bool fork) const
std::size_t stateful_index(std::size_t ind) const
1-based stateful index of node ind, 0 when the node is not stateful.
void refresh_cacheqn_actual_visits(const Matrix< T > &hitprob, const Matrix< T > &missprob)
Re-resolve the cache read self-switch from the offered 1/2-1/2 to the ACTUAL hit/miss probabilities t...
std::vector< std::vector< std::vector< double > > > pie() const
sn.pie (M x K cells): the phase an arriving job enters, map_pie of sn.proc{i}{r} (the Erlang conversi...
bool has_immediate_feedback() const
Whether immediate feedback is EFFECTIVE anywhere in the model.
std::vector< lang::RemovalPolicy > signalrempolicy
bool has_rtfun_routing() const
True when some routing must be re-read at every state from rt_state: SDR, and the JSQ and SQ(d) dispa...
std::vector< std::vector< bool > > immfeed
sn.immfeed: (nstations x nclasses) IMMEDIATE FEEDBACK, the reference's refreshStruct field.
const ForkParam< T > * fork_param_of(std::size_t node) const
The fork's override block, or null when it declares none.
std::size_t stateful_of_station(std::size_t st) const
std::vector< std::size_t > downstream_stations(std::size_t ind) const
The nodes directly downstream of ind, walking THROUGH stateless nodes and stopping at the first stati...
std::size_t nof_nodes() const
std::size_t polling_width(std::size_t ist) const
The controller width, pinfo.width: [pos, swk, ctr, src, tht, trt_1..R] with each column materialized ...
std::size_t nof_stateful() const
std::size_t polling_nlegs(const PollingParam &pp) const
Number of controller legs: the table length, else R.
bool has_rr_routing() const
Whether ANY (node, class) pair dispatches round-robin.
Matrix< double > phaseshift() const
sn.phaseshift (M x K+1) = [0, cumsum(phasessz, 2)].
std::map< std::pair< std::size_t, std::size_t >, Matrix< T > > P
P[(r,s)] is an (nnodes x nnodes) block; absent means all zero.
std::size_t phases_of(std::size_t ist, std::size_t r) const
sn.phases(i,r): the order of the process representation.
std::map< std::size_t, TransitionParam< T > > transparam
Transition (SPN) parameters, keyed by 1-based node index.
void check_closed_reneging() const
Refuses RENEGING declared for a class of finite population at any station (closed_reneging_refusal).
std::size_t mark_carrier_of(std::size_t ist) const
The CARRIER of station i's marked arrival: the class of mark 1, whose phase block holds the one modul...
std::vector< std::vector< bool > > replyblock
sn.replyblock (nnodes x nclasses) and sn.syncreply (nclasses).
std::vector< std::size_t > all_nodes() const
Every node index, 1-based, for the node-level visit computation.
bool bas_declares(std::size_t ind, std::vector< std::vector< bool > > &destmask) const
declaresBlockedMarker for node ind (1-based): true when it is the BLOCKING side of a true-BAS relatio...
std::vector< std::vector< bool > > isbasdestination
sn.isbasdestination, (nstations x nclasses): true where a refusal at this station must BLOCK an upstr...
bool is_mm1k_loss() const
Implementation of api::sn_is_mm1k_loss; that free function delegates here.
void for_each_route_block(F f) const
Visit every (r, s) block of the routing in force, the one route_eff reads: Peff when the expansion ra...
bool has_sdr_routing() const
MATLAB's any(sn.isstatedep(:,3)) NARROWED TO THE ONE STRATEGY THIS PORT EVALUATES PER STATE: Krzesins...
std::vector< Reward > reward
std::vector< std::size_t > stateful_nodes
1-based node indices, ascending
Matrix< double > phasessz() const
sn.phasessz (M x K) = max(phases, 1), with MATLAB's two exceptions: a Join keeps its 0 and a non-carr...
bool sched_has_priority_aware() const
Whether some station runs a discipline that READS the class priorities.
const lang::Distrib< T > * polling_leg(std::size_t ist, const PollingParam &pp, std::size_t l) const
The switchover law of leg l (1-based) of station ist's controller, as State.pollingInfo resolves it,...
std::vector< bool > iscatastrophe() const
sn.iscatastrophe (K x 1): true where class r is a catastrophe signal.
bool holds_reply_for(std::size_t ind, std::size_t r) const
True when node ind (1-based) holds a server across a synchronous call whose reply class is r (1-based...
void refresh_replyblock()
sn.replyblock, DERIVED from sn.syncreply and the routing.
std::vector< std::vector< Distrib< T > > > service
service[i][r], 0-based station and class; a disabled entry marks a pair never visited.
void refresh_chains()
Port of MNetwork.refreshChains followed by sn_refresh_visits.
std::vector< std::vector< bool > > csmask
(nclasses x nclasses) class r can switch into s, diagonal set
void refresh_capacity()
Port of MNetwork.refreshCapacity.
std::vector< std::vector< bool > > chains
(nchains x nclasses)
void apply_sink_closure()
Route every open chain from the Sink back into the Source, as the tail of MATLAB's getRoutingMatrix d...
std::vector< std::size_t > refclass
(nchains) 1-based class, 0 = none
std::vector< bool > polling_polled(std::size_t ist) const
The buffers a polling server at station ist actually visits, as State.pollingInfo builds pinfo....
int gdscalingcutoff
sn.gdscalingcutoff: the per-slot OPEN-class truncation used when gdscaling is materialized onto the J...
std::map< std::size_t, SetupDelayOffParam< T > > setupparam
Setup / delay-off, keyed by 1-based STATION index.
std::map< std::size_t, BreakdownParam< T > > breakdownparam
Server breakdown / repair, keyed by 1-based STATION index.
bool has_exponential_fcfs() const
BCMP type 1 asks the FCFS service to be exponential.
void check_service_reachable() const
bool has_breakdown() const
Any station at all, the guard every solver gate needs first.
static bool polling_leg_differs(const lang::Distrib< T > &a, const lang::Distrib< T > &b)
True when two timed legs are not the same law (distinctLaws).
GdScaling< T > gdscaling
sn.gdscaling: the network-level globally state-dependent (Whittle) rate scaling phi(n).
std::vector< bool > fjauxclass
sn.fjauxclass: (nclasses+1, 1-based) true where the class is an MMT AUXILIARY OPEN class,...
std::vector< std::vector< std::size_t > > nvars
sn.nvars, (nnodes x 3R+1): the LOCAL VARIABLE columns each node appends to its state,...
bool has_service_law(std::size_t i, std::size_t r) const
Does (station i, class r) have a service law an analyzer may convert?
std::vector< std::vector< bool > > disabled
Matrix< T > visits_from_block(const Matrix< T > &Pc_in, const std::vector< std::size_t > &sel, const std::vector< std::size_t > &ic, std::size_t refnode) const
The visit ratios of one chain from an already-formed chain routing block Pc (dim = sel....
pfqn::SdrStruct sdr
Krzesinski (1987) product-form state-dependent routing, in 0-based STATION indices; empty unless a no...
std::vector< std::vector< bool > > reached_node_classes() const
The (node, class) pairs a job can actually ARRIVE at, 0-based on both axes.
void refresh_sched_param()
Port of MNetwork.refreshScheduling's schedparam half.
std::map< std::size_t, FjJoinParam > fjjoinparam
sn.nodeparam{j}.fj for each Join node: the tag matrix and the required sibling multiplicity after_eve...
std::vector< std::vector< LstHandle > > lst() const
sn.lst (M x K handles), refreshLST.m: the Laplace-Stieltjes transform of each law,...
bool serves_class(std::size_t ind, std::size_t r) const
Whether a job of class r (0-based) can LEAVE node ind (1-based) again.
double total_jobs() const
Total population, as MATLAB's getNumberOfJobs summed.
Matrix< T > rt
sn.rt and sn.rtnodes: the class-expanded routing.
void fill_signal_services()
Refuses a class that is ROUTED TO a station which cannot serve it.
const CtmcMapc< T > * mapc_of(std::size_t ist, std::size_t r) const
The pair form of class r (1-based) at station ist (1-based), or null when there is none.
std::map< std::size_t, RetrialParam< T > > retrialparam
Retrial parameters, keyed by 1-based STATION index.
void promote_stateful(std::size_t ind)
Make node ind stateful, keeping stateful_nodes ascending.
std::vector< bool > issignal
The G-network signal declaration, per CLASS.
void grow_routing()
Grow every routing block to the current node count.
std::map< std::size_t, CacheParam< T > > nodeparam
Cache parameters by 1-based NODE index; only Cache nodes have an entry.
Matrix< double > procid() const
sn.procid (M x K): the ProcessType id of each (station, class) pair, as refreshProcessTypes....
void grow_block(Matrix< T > &B) const
std::size_t map_var_slot(std::size_t ind, std::size_t r) const
0-based column of class r's MAP memory inside node ind's local-variable block.
std::size_t add_node(const std::string &nm, NodeType ty, bool stateful)
Add a non-station node (a Fork, a Router).
std::map< std::size_t, PasParam > pasparam
static std::size_t bas_ncols(const std::vector< std::size_t > &codes)
Width of the held-job block: one counter per code, at least one column.
std::vector< double > cap
sn.cap and sn.classcap: the total and per-class buffers.
std::map< std::pair< std::size_t, std::size_t >, CtmcMapc< T > > ctmcmapc
MAP services in CTMC pair form, keyed by (1-based station, 1-based class).
std::vector< JobClass > classes
void rr_advance(std::size_t ind, std::size_t r, std::vector< T > &varrow) const
Advance the pointer of (ind, r) in VARROW by one position, cyclically.
std::vector< bool > isbasblocking
sn.isbasblocking, per NODE: true where the node is the BLOCKING (upstream) side of a true-BAS relatio...
bool has_product_form_not_het_fcfs(bool check_means=true) const
Port of sn_has_product_form_not_het_fcfs: LCFS is excluded, and at FCFS the service must be exponenti...
std::size_t sinkNode
1-based NODE index of the Sink, 0 = none (it is not a station)
std::size_t nregions() const
sn.nregions: the number of finite capacity regions.
Matrix< double > isph() const
sn.isph (M x K): true where sn.proc{i}{r} with sn.pie{i}{r} admits a phase-type reading (sn_is_phaset...
std::vector< std::vector< std::vector< double > > > mu() const
sn.mu (M x K cells): the total outgoing rate of each phase, MATLAB's getServiceRates/getSourceRates.
Matrix< double > connmatrix() const
sn.connmatrix (N x N): 1 where some class routes node i to node j with positive probability.
std::map< std::size_t, JoinDecl > joindecl
std::vector< std::size_t > signaltarget
std::vector< std::vector< std::vector< double > > > phi() const
sn.phi (M x K cells): the completion probability of each phase; 1 where mu is a single rate.
void bas_decode(std::size_t code, std::size_t &r, std::size_t &jst, std::size_t &s) const
Inverse of bas_code: 1-based (r, jst, s) for a code >= 1.
void refresh_local_vars()
Port of MNetwork.refreshLocalVars: the per-node local-variable widths.
ProcessType procid(std::size_t ist, std::size_t r) const
sn.procid(i,r): the process type of a (station, class) pair.
std::size_t rr_dest(std::size_t ind, std::size_t r, const std::vector< T > &varrow) const
The destination node the pointer in VARROW names, or 0 when (ind, r) does not dispatch round-robin or...
PollingParam effective_polling(std::size_t ist) const
The polling controller of station ist, from whichever API declared it.
std::vector< T > gdscalingpeak
sn.gdscalingpeak: the declared (nstations x nclasses) peak of gdscaling, row-major,...
std::size_t rr_var_slot(std::size_t ind, std::size_t r) const
1-BASED index of the pointer of (ind, r) INSIDE the node's local-variable block, or 0 when that pair ...
void refresh_bas_blocking()
Port of refreshLocalVars' true-BAS block and its declaresBlockedMarker helper: which nodes carry the ...
std::vector< Station< T > > stations
stations[k-1] is the k-th station
std::vector< std::size_t > rr_outlinks(std::size_t ind, std::size_t r) const
ROUND-ROBIN DISPATCH, the state that makes it deterministic.
Matrix< T > rates
(nstations x nclasses) service rates and SCVs, with a PARALLEL disabled flag instead of MATLAB's NaN ...
void refresh_struct()
The whole chain, in MATLAB's refreshStruct order.
T route_eff(std::size_t r, std::size_t s, std::size_t i, std::size_t j) const
The routing actually in force: the expansion when there is one, else P.
bool is_queueing_place(std::size_t i) const
Is station i (0-based) a QUEUEING PLACE, i.e.
void set_service(std::size_t station, std::size_t cls, const Distrib< T > &d)
std::vector< std::size_t > syncreply
std::map< std::pair< std::size_t, std::size_t >, Matrix< T > > Peff
The routing after refresh_routing() has expanded the non-PROB strategies and folded the class switche...
std::vector< std::vector< std::size_t > > inchain
1-based class indices per chain
Matrix< double > isstatedep() const
sn.isstatedep (N x 3): column 1 the input section (never set by the reference), column 2 state-depend...
std::size_t node_of_station(std::size_t st) const
1-based node index of station st, 0 when the map has no entry.
std::vector< std::size_t > bas_marker_codes(std::size_t ind) const
Sorted held-job codes of the blocking node ind: one per (r, jst, s) the routing sends from class r at...
bool bas_single_server(std::size_t ist) const
A non-INF station with at most one server holds at most one job in total.
void da_recompute_visits_from_rtnodes()
Recompute rt, visits and nodevisits after the caller has rewritten rtnodes in place – the cacheqn dri...
std::vector< NodeDef > nodes
every node, in creation order
std::vector< std::vector< double > > classcap
bool has_sd_routing() const
sn_has_sd_routing: RROBIN, WRROBIN, JSQ, SQ or SDR at some node.
std::vector< std::size_t > rr_weighted_outlinks(std::size_t ind, std::size_t r) const
The WRROBIN cycle: each outlink repeated by its weight, weight 0 once.
bool polling_has_timed_switchover(std::size_t ist, const PollingParam &pp) const
True when some POLLED buffer of station ist declares a non-immediate switchover, i....
std::map< std::size_t, Matrix< T > > csmatrix
The class-switch matrix of a ClassSwitch node, by 1-based NODE index.
std::vector< double > njobs() const
sn.njobs: the population of each class, infinite for an open one.
std::vector< std::pair< std::size_t, std::size_t > > chain_retrieval_edges(const std::vector< std::size_t > &ic, const std::vector< std::size_t > &sel) const
sn_refresh_visits.m retrievalEdges: extra [from, to] chain-block positions for a retrieval cache,...
bool has_breakdown_node(std::size_t ind) const
sn.hasbreakdown(ind): does the NODE's server break down?
std::vector< double > hasbreakdown() const
sn.hasbreakdown (N x 1): 1 where the node's server is subject to breakdowns.
void refresh_router_stateful()
A Router that DISPATCHES (round-robin, JSQ or SQ(d)) holds state, so it must survive the stochastic c...
bool is_open_model() const
sn_is_open_model: EVERY class is open, which is not has_open_classes.
bool sched_is_product_form() const
std::vector< std::vector< DropStrategy > > droprule
std::size_t bas_code(std::size_t r, std::size_t jst, std::size_t s) const
TRUE-BAS HELD-JOB CODES (BUG-110).
std::string log_path
Network.setLogPath / getLogPath: the directory every Logger writes into, and the logPath attribute of...
bool has_blocking() const
Some station can REFUSE a job: its own buffer BINDS, or a finite capacity region caps a set of statio...
void refresh_rt()
sn.rt and sn.rtnodes: the class-expanded routing matrices.
bool priorities_ignored() const
Priorities were declared and no station will read them.
std::vector< Matrix< T > > visits
(nchains) each (nstateful x nclasses)
double buffer_size(std::size_t ist) const
Kendall's K of station IST (1-based), +inf when unbounded.
std::map< std::size_t, std::vector< T > > initmarking
The DECLARED initial state of a stateful node, by 1-based node index.
std::pair< T, T > mark_marginal_moments(const Distrib< T > &d, std::size_t mk) const
Mean and SCV of ONE MARK'S MARGINAL MAP, MarkedMAP.toMAPs(k).
std::vector< double > station_to_stateful() const
sn.stationToStateful (1 x M): the stateful index of each station.
std::map< std::size_t, std::vector< T > > stateprior
bool has_homogeneous_scheduling(SchedStrategy strategy) const
Port of sn_has_homogeneous_scheduling: true when EVERY station uses strategy, the reference's length(...
std::map< std::size_t, CtmcPool< T > > ctmcpool
Heterogeneous server pools rewritten for the CTMC, by 1-based NODE index.
double nclosedjobs() const
sn.nclosedjobs: the total population of the closed classes.
std::vector< std::pair< std::size_t, std::size_t > > fj
fj(f,j): the Join node j that closes the Fork node f, 1-based.
std::size_t nof_stations() const
void set_route_effective(std::size_t r, std::size_t s, std::size_t i, std::size_t j, const T &p)
Write into the routing the consumers actually read.
std::size_t join_siblings(std::size_t joinNode, std::size_t r=0) const
The number of siblings the fork-join pair ending at Join node joinNode (1-based) emits per parent job...
std::vector< double > stateful_to_station() const
sn.statefulToStation (1 x S): the station index of each stateful node, NaN when it is not a station.
std::size_t phasessz_of(std::size_t ist, std::size_t r) const
bool has_product_form() const
sn_has_product_form, conjunct for conjunct.
std::vector< lang::SignalType > signaltype
std::vector< std::size_t > fjclassmap
sn.fjclassmap: the ORIGINAL class of each auxiliary sibling class, 0 for an original class.
std::map< std::size_t, PollingParam > pollingparam
bool is_fluid_node(std::size_t ind) const
Is 1-based node ind a FLUID place (Place.setFluid, MATLAB sn.fluid(ind))?
std::vector< std::size_t > quorum_joins() const
The 1-based Join nodes that fire on a STRICT quorum, i.e.
bool has_fractional_populations() const
std::map< std::size_t, Matrix< T > > statespace
std::size_t markidx_of(std::size_t ist, std::size_t r) const
sn.markidx(i,r): the 1-based MARK that class r carries in station i's marked arrival process,...
std::size_t rr_quantum_phases(std::size_t ist, std::size_t r) const
sn.phasessz(i,r) = max(sn.phases(i,r),1): THE WIDTH of class r's phase block in a state row,...
Matrix< T > stoch_comp_stateful(const Matrix< T > &full, std::size_t nIC) const
The stochastic complement of a NODE-level routing block over the stateful nodes, S = P11 + P12 (I - P...
std::size_t add_station(const Station< T > &st)
Add a station, which is also a node, and grow the service table.
std::vector< std::vector< T > > signalremdist
Matrix< T > station_routing(const std::vector< std::size_t > &ic) const
The chain-restricted routing over the STATEFUL nodes: the node-level routing with the non-stateful no...
bool isfjaugmented
sn.isfjaugmented: this struct came out of fj_tag, so its Fork nodes are STATEFUL and its Join nodes c...
std::vector< std::size_t > station_to_node
(nstations) 1-based node index
static std::vector< bool > chain_reachable(const Matrix< T > &P, const std::vector< std::size_t > &seeds, const std::vector< std::pair< std::size_t, std::size_t > > &edges)
sn_refresh_visits.m chainReachable: states reachable from the seeds along nonzero entries and the ext...
void refresh_routing()
Port of the part of MNetwork.refreshRoutingMatrix this port reaches: the expansion of a routing STRAT...
std::vector< Region > regions
std::size_t nof_classes() const
void refresh_immfeed()
Port of the sn.immfeed block of @@MNetwork/refreshStruct.m.
std::map< std::size_t, ForkParam< T > > forkparam
Variable forking levels, by 1-based Fork node; absent on a plain fork.
static std::string plural(long n, const std::string &singular, const std::string &plural_form)
Count with an agreeing noun, e.g.
static void compiling(const std::string &name)
Announce the compilation of a model structure.
static void compile_detail(const char *fmt,...)
One stage line of a structure compile: silenced inside a Quiet scope, and inside an open run,...
What refreshProcessRepresentations and refreshLST compute FROM a distribution: the (D0,...
Equilibrium distribution of a discrete-time Markov chain, and stochastic complementation.
Limiting distribution of a discrete-time Markov chain whose transition matrix may be reducible.
Stochastic complement of a DTMC partition, a port of matlab/lib/kpctoolbox/mc/dtmc_stochcomp....
The exception types the port throws.
Enumerations and the minimal distribution descriptor shared by the model layer of the C++ port.
int dispatch(const Options &in, bool allow_server, bool no_args)
Everything main did, with the arguments already in hand.
Running progress log of a LINE solver run (the "solver console").
Markovian arrival process descriptors: stationary vectors, rate, moments, autocorrelation and the ind...
Dense matrix and non-owning view.
bool sn_is_phasetype(const std::vector< Matrix< T > > &maps, const std::vector< T > &pie)
Whether a (D0, D1, ...) list is a valid phase-type / MAP representation.
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
DropStrategy
Blocking and loss rules, with the values of MATLAB DropStrategy.
Definition lang_types.h:465
BalkingStrategy
Balking rules, with the values of MATLAB BalkingStrategy.
Definition lang_types.h:486
@ CATASTROPHE
removes EVERY job at the station
Definition lang_types.h:183
PollingOrder
Visit-order rules of a polling server, with the values of MATLAB PollingOrder.
Definition lang_types.h:404
@ CYCLIC
fixed cyclic order (or the polling table)
Definition lang_types.h:405
JoinStrategy
Join rules, with the values of MATLAB JoinStrategy.
Definition lang_types.h:502
RoutingStrategy
Routing strategies, with the values of MATLAB RoutingStrategy.
Definition lang_types.h:430
PollingTimer
Visit-timer scopes of a polling server, with the values of MATLAB PollingTimer.
Definition lang_types.h:412
@ GLOBAL
a timed token: per-class target rotation timers
Definition lang_types.h:415
@ NONE
no visit timer
Definition lang_types.h:413
T dist_lst(const Distrib< T > &d, const T &s)
sn.lst: the Laplace-Stieltjes transform E[exp(-sX)].
HeteroSchedPolicy
How a heterogeneous station picks among its server types, MATLAB HeteroSchedPolicy.
Definition lang_types.h:492
PollingType
Polling service disciplines, with the values of MATLAB PollingType.
Definition lang_types.h:391
@ KLIMITED
serve at most K per visit (K in pollingPar)
Definition lang_types.h:394
@ EXHAUSTIVE
serve until the queue empties
Definition lang_types.h:393
@ GLIMITED
serve at most K of the jobs present at the polling instant
Definition lang_types.h:396
JobClassType
Job class kinds, with the values of MATLAB JobClassType.
Definition lang_types.h:388
ProcessType
Distribution kinds, with the values of MATLAB ProcessType.
Definition lang_types.h:524
std::function< std::vector< T >(const std::vector< T > &)> GdScaling
A globally state-dependent scaling, sn.gdscaling.
Definition lang_types.h:807
bool process_is_markovian(ProcessType p)
ProcessType.isMarkovian: true when sn.proc carries an exact matrix representation of the law,...
Definition lang_types.h:713
std::function< std::vector< T >(const std::vector< T > &)> CdScaling
A class-dependent scaling map, sn.cdscaling.
Definition lang_types.h:794
const char * routing_to_text(RoutingStrategy r)
Definition lang_types.h:443
NodeType
Node kinds, with the values of MATLAB NodeType.
Definition lang_types.h:345
ReplacementStrategy
Cache replacement policies, with the values of MATLAB ReplacementStrategy.
Definition lang_types.h:419
T map_mean(const Map< T > &m)
Mean inter-arrival time, 1/lambda.
Definition map_moment.h:101
std::vector< T > map_pie(const Map< T > &m)
Phase distribution seen by an arriving job, pie = pi D1 / (pi D1 e).
Definition map_moment.h:89
T map_scv(const Map< T > &m)
Squared coefficient of variation.
Definition map_moment.h:140
ReducibleResult< T > dtmc_solve_reducible(const Matrix< T > &P, const std::vector< T > &pin, double zeroColTol=1e-12)
Limiting distribution of a discrete-time Markov chain whose transition matrix may be reducible.
Matrix< T > dtmc_stochcomp(const Matrix< T > &P, const std::vector< std::size_t > &keep)
Stochastic complement of a DTMC partition, a port of matlab/lib/kpctoolbox/mc/dtmc_stochcomp....
SccResult stronglyconncomp(const Matrix< T > &A)
Strongly connected components of a directed graph, and which of them are recurrent (closed under the ...
std::vector< T > dtmc_solve(const Matrix< T > &P)
Stationary distribution of a stochastic matrix P.
Definition dtmc_solve.h:106
void cache_retrieval_class_map(const CacheParam< T > &cp, std::vector< std::size_t > &rc_list, std::vector< std::size_t > &rc_items, std::vector< std::size_t > &rc_orig)
Port of State.cacheRetrievalClassMap: the canonical order of a cache's retrieval classes,...
Matrix< T > station_swap_graph(const NetworkStruct< T > &sn, std::size_t ist)
The swap graph of a PAS / OI station, with the defaults refreshLocalVars.m installs applied.
bool is_oi_loss(const NetworkStruct< T > &sn, std::size_t *qist=nullptr)
Port of sn_is_oi_loss.m: an open Source -> Queue -> Sink system (any number of classes,...
bool station_swap_graph_is_zero(const NetworkStruct< T > &sn, std::size_t ist)
True when the station's materialized swap graph is entirely zero.
const char * routing_to_text(RoutingStrategy r)
Definition lang_types.h:443
void closed_reneging_refusal(const std::string &classname, const std::string &where)
Refuses RENEGING on a class of finite population (LINE:input:Model; MATLAB closedRenegingRefusal....
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
Number-type abstraction for the templated API port.
Product-form state-dependent routing.
Whether a (D0, D1, ...) list is a valid phase-type / MAP representation.
Strongly connected components of a directed graph, and which of them are recurrent (closed under the ...
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
The DECLARED join rule of a Join node, by 1-based node index.
The pass-and-swap / order-independent parameters of a PAS station, keyed by station index (Dorsman an...
The polling controller of a POLLING station, keyed by station index.
FINITE CAPACITY REGIONS, MATLAB's refreshRegions output.
sn.reward: the user-declared reward functions, MATLAB's model.setReward(name, fn).
std::vector< T > mu_vec() const
Phase rates, MATLAB's getMu: the total outgoing rate of each phase.
Matrix< T > D0
The (D0,D1) pair when the type carries one directly.
Definition lang_types.h:921
std::vector< Matrix< T > > Dmark
MMAP per-class D1 blocks / BMAP per-batch-size blocks; empty otherwise.
Definition lang_types.h:931
T rate() const
The rate MATLAB's refreshRates would store: 1/mean, with the Immediate singleton short-circuited to i...
std::vector< T > phi_vec() const
Completion probabilities, MATLAB's getPhi: (D1 e) .
std::size_t phases() const
The order of the representation, MATLAB's sn.phases.
bool is_prior() const
Definition lang_types.h:961
A MAP as the pair of matrices (D0, D1).
Definition map_moment.h:53
Matrix< T > D1
Definition map_moment.h:55
Matrix< T > D0
Definition map_moment.h:54
std::vector< bool > recurrent
recurrent[c-1] is true when component c has no edge leaving it.
std::vector< std::size_t > scc
Component index of each state, 1-based as in MATLAB (0 is never used).
Topology and coefficients of a state-dependent routing subnetwork.
Definition pfqn_sdr.h:59
Server breakdown and repair of a station whose server fails and is repaired.
T failure_rate
sn.breakdownMu: 1 / mean failure time
T down_rate_of(std::size_t cls_1based) const
lang::Distrib< T > repair
time to repair of a down server
lang::Distrib< T > failure
time to failure of an up server
T repair_rate
sn.repairMu: 1 / mean repair time
std::vector< T > down_service_rates
sn.downServiceRates(ist, :): per class, 0 = no service while down.
The popularity LAW each class declared, beside the pmf it expands to.
std::size_t n
support size of a Zipf or a DiscreteSampler
The parameters of a Cache node, MATLAB's sn.nodeparam{ind} for a Cache.
int retrieval_capacity
Delayed-hit retrieval system (Cache.setRetrievalSystem).
T qlru
q-LRU admission probability; 1 admits every miss (plain LRU).
std::vector< Popularity > preadkind
per class, parallel to pread
std::vector< T > initstate
The DECLARED initial contents of the cache, as the reference dumps the node's state row: the per-clas...
std::vector< int > itemsize
Per-item storage cost (size) and per-list cap on the total cost of the resident items (ton21cache Sec...
std::vector< int > costcap
std::map< std::size_t, std::vector< std::size_t > > retrieval_queues
read class(0-based)->nodes
std::vector< std::vector< Matrix< T > > > accost
(u) x (n) of (h+1)x(h+1), or empty
long max_pending_retrieval
Truncation level of block B: how many secondary requests may be merged onto the in-flight fetches of ...
std::vector< std::vector< std::size_t > > retrieval_classes
(nitems x nclasses), 1-based
std::vector< int > itemcap
std::vector< std::size_t > missclass
std::vector< std::size_t > hitclass
lang::ReplacementStrategy replacestrat
std::vector< std::size_t > classitem
Item read by each per-item class of a cache network (MATLAB Cache.setItemReadClasses,...
std::vector< std::vector< T > > pread
(u) x (n), empty row = NaN
CTMC pair form of a MAP service at an FCFS station, written by ctmc::ctmc_mapc on the solver's privat...
Matrix< T > V
landing law (-D0)^-1 D1
std::size_t p
phases of the original MAP
std::vector< std::pair< std::size_t, std::size_t > > pairs
0-based (i,j), i-major, V(i,j) > 0
std::vector< T > done
completion rate D1(i,j)/V(i,j)
bool single
c = 1: carried phase, no pairs
CTMC bookkeeping of a heterogeneous-server station, written by ctmc::ctmc_pools on the solver's priva...
std::vector< std::vector< std::size_t > > len
offset and length of block k of class r
std::vector< std::vector< std::vector< T > > > alpha
entry vector of block k of class r
std::vector< std::vector< std::vector< T > > > exit
exit rates of block k of class r
std::vector< std::vector< bool > > compat
compat[t-1][r-1]
std::vector< double > count
servers per pool
std::vector< std::size_t > alfsorder
pools by ascending class count (ALFS)
std::vector< std::vector< Matrix< T > > > D0
D0 of block k of class r.
std::vector< std::vector< std::size_t > > pools
pools[r-1]: compatible pools of r, ascending
lang::HeteroSchedPolicy policy
bool rotate
ALIS/FAIRNESS order is part of the state.
std::vector< std::vector< std::size_t > > off
std::size_t perm_index(const std::vector< std::size_t > &order) const
1-based index of order in perms, 0 when absent.
std::vector< std::vector< double > > fsfrate
fsfrate[t-1][r-1] = 1/mean (FSF)
std::vector< std::vector< std::size_t > > perms
every pool order, identity first
bool has_map() const
True when the type carries a (D0,D1) pair of its own.
Matrix< T > D0
The (D0,D1) pair when the type carries one directly.
Definition lang_types.h:921
std::vector< Matrix< T > > Dmark
MMAP per-class D1 blocks / BMAP per-batch-size blocks; empty otherwise.
Definition lang_types.h:931
static Distrib disabled_dist()
Matrix< T > D1
Definition lang_types.h:921
static Distrib immediate()
The point mass at zero.
sn.nodeparam{j}.fj: what a Join node needs to fire on identity.
std::vector< std::size_t > origclasses
std::map< std::size_t, std::size_t > quorum
QUORUM joins (JoinStrategy.PARTIAL), keyed by original class: the join fires on the first quorum[r] o...
std::map< std::size_t, std::vector< std::vector< std::size_t > > > auxmatrix
std::map< std::size_t, std::size_t > debtoff
std::map< std::size_t, std::vector< std::size_t > > required
One fork firing synchronization: sn.fjsync{k}.
std::size_t fork
1-based Fork node
std::vector< std::size_t > weightlink
Per-branch tasksPerLink, EMPTY when every branch carries weight.
std::size_t weight
tasksPerLink: siblings emitted per branch
std::vector< std::size_t > branchheads
1-based node per branch
std::size_t join
1-based Join node that closes it
std::size_t cls
1-based ORIGINAL class being forked
std::vector< std::vector< std::size_t > > auxall
(B x T) every auxiliary class of this (fork, class), for the tag scan.
std::vector< std::size_t > auxclasses
the tag's auxiliary class per branch
std::size_t tag
1-based tag this entry allocates
Variable forking levels, the twin of MATLAB sn.nodeparam{f}.fanOutLink / .fanOutProb / ....
std::vector< std::vector< lang::Distrib< T > > > fan_out_dist
static constexpr double Immediate
Rate of an Immediate distribution; its mean is 1/Immediate = 1e-8.
Definition lang_types.h:829
static constexpr double FineTol
Definition lang_types.h:823
static constexpr double Zero
Definition lang_types.h:825
static constexpr double CoarseTol
Definition lang_types.h:824
One job class of the network.
std::size_t refstat
1-based reference station
bool completes
Whether passage through the reference station is a COMPLETION.
double deadline
sn.classdeadline(r): the soft deadline EDD and EDF order by, and the tardiness JMT reports.
int attr_kind
LayeredNetworkElement of the element it stands for.
std::size_t attr_idx
index of that element
double population
infinite for an open class
bool immfeed
Class-level immediate feedback, ORed with the station's own setting into sn.immfeed.
std::size_t spawn
sn.classspawn(r): the 1-based class injected at the SAME station on every completion of this class,...
bool self_looping
A SelfLoopingClass: a closed class that perpetually cycles at its reference station.
bool is_ref_class
marks the chain's reference class
std::function< T(const std::vector< std::size_t > &)> svc_rate_fun
std::vector< std::vector< bool > > swap_graph
The polling controller of a POLLING station, keyed by station index.
std::size_t pk
the K of K-LIMITED
std::vector< lang::Distrib< T > > timer
std::vector< lang::Distrib< T > > table_sw
std::vector< std::size_t > table
The extensions, as the Station fields of the same names.
std::vector< lang::Distrib< T > > switchover
Matrix< T > lincon_A
optional linear constraint A n <= b
std::vector< std::vector< double > > cap
(nstations x nclasses+1), -1 = unbounded
std::string name
The region's declared name, as the wire carries it; a generated one otherwise.
std::vector< double > maxmem
per member station, -1 = unbounded
std::vector< DropStrategy > rule
per class
std::vector< T > size
per class; size is the memory footprint
std::vector< bool > members
membership, independent of the caps
std::function< T(const std::vector< T > &)> fn
std::string kind
The DECLARATIVE form the reward was built from, when it was: the template name (QLen,...
A Logger node's trace configuration, MATLAB's Logger properties and sn.nodeparam{ind}...
std::string file_name
base name, no directory
std::string file_path
directory, MATLAB's model.getLogPath
A node of the network.
std::vector< int > routing_param
The scalar parameter of a parameterized dispatcher, per class: the d of a power-of-d (SQ) choice.
std::vector< std::map< std::size_t, double > > routing_weights
The per-destination weights of a WRROBIN dispatcher, per class: a map from 1-based destination NODE i...
bool queue_object
Declared as a Queue although its INF discipline makes nodetype Delay (Network::add_queue).
std::vector< RoutingStrategy > routing
sn.routing, per class.
double tasks_per_link
Fork.output.tasksPerLink == MATLAB sn.nodeparam{f}.fanOut: how many tasks a fork emits per outgoing l...
The parameters of a retrial station: MATLAB sn.retrialProc and friends.
std::vector< int > max_attempts
0 = unbounded
std::vector< T > retrial_rate
mu_r, the per-class orbit retry rate
std::vector< lang::Distrib< T > > retrial_proc
retrial_proc[r] is the class-r retrial process; empty = not a retrial class.
std::vector< int > max_orbit
MATLAB sn.orbitMaxJobs: -1 = unbounded.
std::vector< int > policy
MATLAB sn.retrialPolicy: 1 = LINEAR (per-job clocks), 2 = CONSTANT (one clock per orbit).
Setup and delay-off of a station that powers down when it falls idle.
bool last(lang::Distrib< T > &su, lang::Distrib< T > &doff) const
The pair the solvers use: the last class that declares one.
std::vector< lang::Distrib< T > > setup
per class, disabled = not declared
std::vector< lang::Distrib< T > > delayoff
per class
Per class; strategy == NONE is a class that declares no balking.
lang::BalkingStrategy strategy
std::vector< BalkingThreshold > thresholds
One balking threshold: with min_jobs <= n <= max_jobs at the station, an arriving job of the class re...
A heterogeneous server pool: count servers that serve only compatible classes, each with its own serv...
std::vector< bool > compatible
per class; empty = every class
std::vector< Distrib< T > > service
per class
One station of the network.
std::vector< Distrib< T > > orbit_impatience
Queue.setOrbitImpatience(class, dist): abandonment from the RETRIAL ORBIT, which is a different popul...
double cap
Station capacity in Kendall's K, as setCapacity sets it.
std::vector< T > jdscalingpeak
sn.jdscalingpeak for this station: the declared peak joint-dependent scaling per class.
std::vector< BalkingParam > balking
std::function< T(const std::vector< std::size_t > &)> svc_rate_fun
sn.nodeparam{ind}.svcRateFun for a PAS / OI station: the TOTAL service rate as a function of the orde...
std::vector< T > batch_reject
Queue.setBatchRejectProbability: per-class rejection of a whole batch.
std::vector< Distrib< T > > patience
Queue.setPatience(class, dist): the abandonment timer of a WAITING job, with impatience[r] naming whi...
std::vector< std::size_t > server_parallelism
Queue.setServerParallelism(class, n): the servers a job seizes for the whole of its service,...
std::vector< Distrib< T > > quantum
Queue.setQuantum(class, distrib): the per-class time slice of a round-robin (SchedStrategy::RR) stati...
std::vector< int > droprule
Per-class blocking rule as an INT, with 0 meaning "not set".
std::vector< T > orbit_join
Queue.setOrbitPersistence(class, p, q), MATLAB sn.orbitJoinProb and sn.orbitPersistProb: a fresh arri...
std::vector< Distrib< T > > polling_timer
SchedStrategy sched
std::vector< std::vector< Distrib< T > > > switchover_pair
Queue.setSwitchover(fromClass, toClass, distrib): the walk the server takes when it turns from servin...
std::vector< Distrib< T > > polling_table_sw
double nservers
may be infinite (a Delay, or an inf-scheduled task)
std::size_t polling_order_class
std::vector< lang::PollingType > polling_type
Polling parameters for a POLLING station, MATLAB's pollingType, switchoverTime and pollingPar on the ...
T orbit_join_of(std::size_t r) const
orbit_join[r] with the default 1 for a missing slot (0-based r).
Matrix< T > swap_graph
sn.nodeparam{ind}.swapGraph: which class a departing job promotes the jobs behind it into.
CdScaling< T > jdscaling
sn.jdscaling for this station: MATLAB's Station.ljdScaling, the JOINT dependence map eta_i(n),...
std::vector< T > cdscalingpeak
sn.cdscalingpeak for this station: the DECLARED peak rate scaling per class, empty when the station i...
std::vector< std::size_t > marked_classes
Source.markedClasses: the 1-based class of each mark of an MMAP arrival.
std::vector< T > lldscaling
sn.lldscaling for this station: the multiplier at population 1, 2, ... Empty when the station is not ...
std::vector< lang::ImpatienceType > impatience
std::vector< T > schedparam
sn.schedparam, per class: the DPS / GPS weight, or the SEPT / LEPT rank.
lang::PollingOrder polling_order
std::vector< std::size_t > polling_table
The polling extensions (Queue.setPollingTable, setPollingOrder, setPollingTimer).
lang::HeteroSchedPolicy hetero_policy
CdScaling< T > cdscaling
sn.cdscaling for this station: the class-dependence map, empty when unset.
std::vector< double > classcap
Per-class buffer from setChainCapacity; infinite where unset.
std::vector< lang::DepartureDiscipline > departure_discipline
Place.departureDiscipline, per class.
std::vector< Distrib< T > > arrival_batch
Source.setArrivalBatch(class, dist): the batch-size law released at each arrival epoch.
std::vector< Distrib< T > > switchover
bool fluid
Place.setFluid (MATLAB sn.fluid): the place holds a continuous LEVEL rather than tokens,...
std::vector< T > orbit_search
Queue.setOrbitalSearch(class, theta), MATLAB sn.orbitSearchProb: on a service completion at a retrial...
lang::PollingTimer polling_timer_scope
T orbit_search_of(std::size_t r) const
orbit_search[r] with the default 0 for a missing slot (0-based r).
std::vector< T > orbit_persist
std::vector< bool > immfeed
Node-level immediate feedback, per class; empty when the station sets none.
std::vector< ServerType > server_types
std::size_t attr_idx
LQN element this station stands for.
T orbit_persist_of(std::size_t r) const
orbit_persist[r] with the default 1 for a missing slot (0-based r).
One fluid arc of a mode: node is the 1-based fluid place, value a rate or an impulse.
A fluid rate dependence: the firing rate is multiplied by fun(level(node)).
std::function< double(double)> fun
A marking-dependent fluid flow (setFluidFlowDependence): the flow of the mode on fluid place node is ...
std::function< double(const std::vector< double > &)> fun
A fluid guard: the mode is enabled only while level(node) >= thr (sgn = +1) or <= thr (sgn = -1).
The parameters of a Transition node: MATLAB sn.nodeparam{ind} for an SPN transition,...
const std::vector< FluidArc > & fluid_rates(std::size_t m) const
static std::vector< T > inhibit_total(const std::vector< Matrix< T > > &a, std::size_t m)
The inhibiting THRESHOLD of one mode per place, class blind.
std::vector< std::vector< FluidDep > > fluiddep
static std::vector< T > arc_total(const std::vector< Matrix< T > > &a, std::size_t m)
The arcs of one mode summed over classes, for a consumer that is class blind BECAUSE THE NET IS SINGL...
bool is_multiclass() const
True when any mode's arcs touch more than one class.
std::vector< double > firingprio
firing priority per mode
std::vector< std::vector< FluidGuard > > fluidguard
std::vector< std::vector< FluidFlowDep > > fluidflowdep
std::vector< lang::TimingStrategy > timing
immediate or timed
std::vector< std::string > modenames
std::vector< std::vector< FluidArc > > fluidimpulse
std::vector< lang::Distrib< T > > firingproc
firing distribution per mode
bool has_fluid_arcs() const
Transition.hasFluidArcs: any mode declares a fluid rate, guard, impulse, rate or flow dependence.
std::vector< double > nmodeservers
servers per mode, may be infinite
const std::vector< FluidArc > & fluid_impulses(std::size_t m) const
std::vector< T > fireweight
weight among simultaneously enabled modes
std::size_t single_class() const
The one class every arc of every mode touches, 1-based; 0 when none does.
std::vector< Matrix< T > > firing
firing[m](p,r): class-r tokens mode m moves to/from place p when it fires.
std::vector< Matrix< T > > enabling
enabling[m](p,r): class-r tokens of place p (0-based node) mode m needs.
const std::vector< FluidDep > & fluid_deps(std::size_t m) const
const std::vector< FluidFlowDep > & fluid_flow_deps(std::size_t m) const
std::vector< std::function< T(const std::vector< T > &)> > firingdep
Marking-dependent firing-rate multiplier g_m(marking); an empty entry is the unit multiplier.
std::vector< Matrix< T > > inhibiting
inhibiting[m](p,r): class-r tokens of p that BLOCK mode m (Inf = never).
const std::vector< FluidGuard > & fluid_guards(std::size_t m) const
std::vector< std::vector< FluidArc > > fluidrate
FSPN arcs per mode, MATLAB sn.transparam{ind}.fluidrate/fluidguard/fluidimpulse/fluiddep.
std::vector< std::size_t > firingphases
phase count per mode, 0 when non-Markovian