LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
network_builder.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_BUILDER_H
6#define LINE_LANG_QN_NETWORK_BUILDER_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * The Network constructor API: Queue, Delay, Source, Sink, Router,
12 * ClassSwitch, Cache, Fork and Join, the job classes, and `link`.
13 *
14 * This is the port of what a MATLAB model script writes -- `Network`,
15 * `Queue(model, name, sched)`, `queue.setService(class, dist)`,
16 * `model.link(P)` -- feeding the SAME refresh as every other front end, so a
17 * model built here and a model read from a file produce the same
18 * `NetworkStruct`. The split is deliberate and mirrors `lqn_builder.h` /
19 * `lqn_reader.h`: stage one constructs, stage two (`NetworkStruct::refresh_*`)
20 * derives, and only stage two is allowed to compute anything.
21 *
22 * INDEX SPACES. Every method takes and returns 1-based NODE indices, which is
23 * what a model script deals in; the station index is an internal detail of the
24 * struct and is looked up here. `add_*` returns the node index of the node it
25 * created, and `add_*_class` the class index.
26 *
27 * WHAT IS REFUSED, and where. The builder accepts the feature set SolverMVA
28 * declares (`SolverMVA.getFeatureSet`); the refresh refuses a state-dependent
29 * routing strategy by name, and each solver refuses what it cannot analyse.
30 * Nothing is silently mapped onto a neighbour.
31 */
32
33#include <algorithm>
34#include <cmath>
35#include <cstddef>
36#include <iostream>
37#include <limits>
38#include <map>
39#include <string>
40#include <utility>
41#include <vector>
42
46#include "line/lang/prior.h"
48#include "line/num/number.h"
49#include "line/util/error.h"
50#include "line/util/matrix.h"
51
52namespace line {
53namespace qn {
54
55/**
56 * The routing matrix a model script fills in, MATLAB's `P` cell array.
57 *
58 * `P{r,s}(i,j)` is the probability that a job leaving node i in class r enters
59 * node j in class s. The single-class form `set(i, j, p)` is the shorthand a
60 * one-class model uses, and is exactly `set(1, 1, i, j, p)`.
61 */
62template <class T>
64 public:
65 void set(std::size_t r, std::size_t s, std::size_t i, std::size_t j, const T& p) {
66 entries[Key(r, s, i, j)] = p;
67 }
68 void set(std::size_t i, std::size_t j, const T& p) { set(1, 1, i, j, p); }
69
70 /**
71 * `P.set(class, Network.serialRouting(...))`: install a one-class block.
72 *
73 * The source block's class coordinates are deliberately ignored. A serial
74 * routing matrix is a topology block; this call assigns that topology to
75 * the requested class, exactly as the MATLAB, JAR and Python APIs do.
76 */
77 void set(std::size_t cls, const RoutingMatrix<T>& block) {
78 for (const auto& kv : block.entries)
79 set(cls, cls, kv.first.i, kv.first.j, kv.second);
80 }
81
82 T get(std::size_t r, std::size_t s, std::size_t i, std::size_t j) const {
83 auto it = entries.find(Key(r, s, i, j));
84 return it == entries.end() ? num_traits<T>::from_int(0) : it->second;
85 }
86
87 struct Key {
88 std::size_t r, s, i, j;
89 Key(std::size_t r_, std::size_t s_, std::size_t i_, std::size_t j_)
90 : r(r_), s(s_), i(i_), j(j_) {}
91 bool operator<(const Key& o) const {
92 if (r != o.r) return r < o.r;
93 if (s != o.s) return s < o.s;
94 if (i != o.i) return i < o.i;
95 return j < o.j;
96 }
97 };
98 std::map<Key, T> entries;
99};
100
101/**
102 * A queueing network under construction.
103 *
104 * The object owns a `NetworkStruct` and hands out a refreshed reference to it.
105 * `get_struct()` runs the whole refresh chain each time it is called, because
106 * every setter can have moved a quantity the chain derives; a caller that
107 * changes nothing and asks twice pays for the second refresh, which is the same
108 * bargain MATLAB's `hasStruct` cache makes on the other side.
109 */
110template <class T>
111class Network {
112 public:
113 explicit Network(const std::string& nm) { sn_.name = nm; }
114
115 // -----------------------------------------------------------------------
116 // Nodes
117 // -----------------------------------------------------------------------
118
119 /**
120 * A queueing station. The default discipline is FCFS, as in MATLAB.
121 *
122 * INF SCHEDULING BUILDS A DELAY. MATLAB's Queue constructor sets
123 * numberOfServers = Inf on that branch and getNodeTypes then reports the
124 * station as NodeType.Delay (the JAR does both with Integer.MAX_VALUE), and
125 * the analyzers partition the stations on those two fields:
126 * sn_get_product_form_chain_params splits by NODETYPE, so a Queue node left
127 * at one server was handed to the linearizer as a finite-server queue and
128 * reported utilization 1 and a saturated response time where the reference
129 * reports a delay (2.4494/19.5506 against 0.1253/21.8747 on a two-station
130 * closed model with 22 jobs).
131 */
132 std::size_t add_queue(const std::string& nm, SchedStrategy sched = SchedStrategy::FCFS) {
133 Station<T> st;
134 st.name = nm;
135 st.nodetype = (sched == SchedStrategy::INF) ? NodeType::Delay : NodeType::Queue;
136 st.sched = sched;
137 st.nservers = (sched == SchedStrategy::INF)
138 ? std::numeric_limits<double>::infinity()
139 : 1.0;
140 const std::size_t ist = sn_.add_station(st);
141 sn_.nodes[sn_.station_to_node[ist - 1] - 1].queue_object = true;
142 init_node(sn_.station_to_node[ist - 1]);
143 return sn_.station_to_node[ist - 1];
144 }
145
146 /** An infinite-server station (a Delay, MATLAB's `Delay` / `DelayStation`). */
147 std::size_t add_delay(const std::string& nm) {
148 Station<T> st;
149 st.name = nm;
150 st.nodetype = NodeType::Delay;
151 st.sched = SchedStrategy::INF;
152 st.nservers = std::numeric_limits<double>::infinity();
153 const std::size_t ist = sn_.add_station(st);
154 init_node(sn_.station_to_node[ist - 1]);
155 return sn_.station_to_node[ist - 1];
156 }
157
158 /**
159 * The external arrival station.
160 *
161 * It IS a station -- its "service" process is the arrival process -- with
162 * the EXT discipline and one server, exactly as MATLAB's Source is built.
163 */
164 std::size_t add_source(const std::string& nm) {
165 if (sn_.sourceIdx != 0)
166 throw InputError(ErrorKind{"Model"}, "Network '" + sn_.name + "' already has a Source; a network holds at most one. "
167 "Give every open class its arrival process on that Source.");
168 Station<T> st;
169 st.name = nm;
170 st.nodetype = NodeType::Source;
171 st.sched = SchedStrategy::EXT;
172 st.nservers = 1.0;
173 const std::size_t ist = sn_.add_station(st);
174 sn_.sourceIdx = ist;
175 init_node(sn_.station_to_node[ist - 1]);
176 return sn_.station_to_node[ist - 1];
177 }
178
179 /** The external departure node. It is NOT a station and holds no jobs. */
180 std::size_t add_sink(const std::string& nm) {
181 if (sn_.sinkNode != 0) throw InputError(ErrorKind{"Model"}, "Network '" + sn_.name + "' already has a Sink; a network holds at most one. Route every open class to that Sink.");
182 const std::size_t nd = sn_.add_node(nm, NodeType::Sink, false);
183 sn_.sinkNode = nd;
184 init_node(nd);
185 return nd;
186 }
187
188 /** A stateless routing node. */
189 std::size_t add_router(const std::string& nm) {
190 const std::size_t nd = sn_.add_node(nm, NodeType::Router, false);
191 init_node(nd);
192 return nd;
193 }
194
195 /**
196 * A Logger node: a pass-through that records every job crossing it.
197 *
198 * It holds no jobs and changes no routing probability, so it is eliminated
199 * by the same stochastic complement that removes a Router; what makes it a
200 * distinct node type is that `used_lang_features` emits Logger/LogTunnel
201 * from it, so a solver with no logging refuses the model by name rather
202 * than silently dropping the trace the user asked for.
203 */
204 std::size_t add_logger(const std::string& nm, const std::string& log_file = std::string()) {
205 const std::size_t nd = sn_.add_node(nm, NodeType::Logger, false);
206 init_node(nd);
207 // `Logger.m` splits the argument and keeps only the base name; the
208 // directory is the model's log path, which every Logger shares.
209 std::string base = log_file;
210 const std::size_t slash = base.find_last_of('/');
211 if (slash != std::string::npos) base = base.substr(slash + 1);
212 sn_.nodes[nd - 1].logger.file_name = base;
213 return nd;
214 }
215
216 /** `Network.setLogPath`: the directory every Logger of this model writes into. */
217 void set_log_path(const std::string& path) { sn_.log_path = path; }
218
219 /**
220 * A ClassSwitch node carrying the (nclasses x nclasses) switching matrix.
221 *
222 * The classes must exist before the node, since the matrix is indexed by
223 * them; that is also the order a MATLAB script writes.
224 */
225 std::size_t add_class_switch(const std::string& nm, const Matrix<T>& C) {
226 if (C.rows() != sn_.classes.size() || C.cols() != sn_.classes.size())
227 throw InputError("ClassSwitch '" + nm +
228 "': the matrix must be (nclasses x nclasses); declare the classes "
229 "before the node");
230 const std::size_t nd = sn_.add_node(nm, NodeType::ClassSwitch, false);
231 sn_.csmatrix[nd] = C;
232 init_node(nd);
233 return nd;
234 }
235
236 /**
237 * A ClassSwitch node whose matrix is installed LATER, by
238 * `set_class_switch_matrix`.
239 *
240 * FOR A FILE READER, which meets the nodes before the classes. A `.jsimg`
241 * and a `.lqnx` both list their nodes first, and a closed class names its
242 * reference STATION, so neither order can be satisfied without deferring
243 * one of the two -- MATLAB's own `ClassSwitch` constructor stores the matrix
244 * without checking it against a class list that does not exist yet, which is
245 * the same deferral by another name.
246 *
247 * THE MATRIX IS LEFT EMPTY, not filled with an identity: an identity is a
248 * valid switching matrix (every class keeps its own), so a caller who forgot
249 * to install the real one would get a plausible model instead of an error.
250 */
251 std::size_t add_class_switch(const std::string& nm) {
252 const std::size_t nd = sn_.add_node(nm, NodeType::ClassSwitch, false);
253 sn_.csmatrix[nd] = Matrix<T>();
254 init_node(nd);
255 return nd;
256 }
257
258 /** Install the switching matrix of a ClassSwitch created without one. */
259 void set_class_switch_matrix(std::size_t node, const Matrix<T>& C) {
260 if (node == 0 || node > sn_.nodes.size())
261 throw InputError("set_class_switch_matrix: node index is out of range");
262 if (sn_.nodes[node - 1].nodetype != NodeType::ClassSwitch)
263 throw InputError("set_class_switch_matrix: node '" + sn_.nodes[node - 1].name +
264 "' is not a ClassSwitch");
265 if (C.rows() != sn_.classes.size() || C.cols() != sn_.classes.size())
266 throw InputError("set_class_switch_matrix: the matrix of '" +
267 sn_.nodes[node - 1].name +
268 "' must be (nclasses x nclasses)");
269 sn_.csmatrix[node] = C;
270 }
271
272 /** A Fork node. It holds no jobs and is removed by the stochastic complement.
273 * `tasks_per_link` (Fork.output.tasksPerLink) defaults to 1. */
274 std::size_t add_fork(const std::string& nm, double tasks_per_link = 1.0) {
275 const std::size_t nd = sn_.add_node(nm, NodeType::Fork, false);
276 sn_.nodes[nd - 1].tasks_per_link = tasks_per_link;
277 init_node(nd);
278 return nd;
279 }
280
281 /**
282 * Variable forking levels on an existing Fork, the twin of MATLAB
283 * `Fork.setTasksPerLink(jobclass, n)`,
284 * `Fork.setTasksPerLinkDistribution(jobclass, dist [, destNode])` and
285 * `Fork.setBranchProbability(jobclass, destNode, p)`.
286 *
287 * The block is allocated lazily and only on a fork that actually declares an
288 * override, so a plain fork has no `sn.forkparam` entry at all and every
289 * consumer can tell the classic case from the variable one by asking
290 * `sn.fork_param_of(f)` for a null.
291 *
292 * `dest_node` 0 means every outgoing link of that class. Classes and nodes
293 * are 1-based, as everywhere in this port.
294 *
295 * An override is RECORDED and replayed when the routing is installed, so
296 * these may be called in either order with respect to `link()` -- as the
297 * MATLAB, Java and Python setters may, which store the override on the
298 * Forker section and materialise it at refresh time. Recording rather than
299 * writing is what buys that: `dest_node = 0` means "every link this class
300 * takes", a set that does not exist until the routing does.
301 */
302 void set_fork_tasks_per_link(std::size_t fork_node, std::size_t jobclass,
303 double tasks, std::size_t dest_node = 0) {
304 ForkOverride ov;
305 ov.kind = ForkOverride::TASKS;
306 ov.fork = fork_node;
307 ov.cls = jobclass;
308 ov.dest = dest_node;
309 ov.value = tasks;
310 record_fork_override(ov);
311 }
312
313 /** A random jobs-per-link degree, redrawn per link and per forked job. */
314 void set_fork_tasks_per_link_dist(std::size_t fork_node, std::size_t jobclass,
315 const lang::Distrib<T>& dist,
316 std::size_t dest_node = 0) {
318 throw InputError("set_fork_tasks_per_link_dist: the jobs-per-link "
319 "distribution must be a DiscreteSampler");
320 ForkOverride ov;
321 ov.kind = ForkOverride::DIST;
322 ov.fork = fork_node;
323 ov.cls = jobclass;
324 ov.dest = dest_node;
325 ov.dist = dist;
326 record_fork_override(ov);
327 }
328
329 /** A branch that fires only with probability `prob`. */
330 void set_fork_branch_probability(std::size_t fork_node, std::size_t jobclass,
331 std::size_t dest_node, double prob) {
332 if (prob < 0.0 || prob > 1.0)
333 throw InputError("set_fork_branch_probability: a branch activation "
334 "probability must lie in [0,1]");
335 ForkOverride ov;
336 ov.kind = ForkOverride::PROB;
337 ov.fork = fork_node;
338 ov.cls = jobclass;
339 ov.dest = dest_node;
340 ov.value = prob;
341 record_fork_override(ov);
342 }
343
344 /**
345 * A Join node, which IS a station: it serves at an infinite rate, and the
346 * synchronisation delay is supplied by the fork-join transform.
347 */
348 std::size_t add_join(const std::string& nm, std::size_t fork_node) {
349 const std::size_t nd = add_join_unbound(nm);
350 bind_join(nd, fork_node);
351 return nd;
352 }
353
354 /**
355 * The Join station on its own, with the fork left to `bind_join`.
356 *
357 * A Join IS a station, so creating it late shifts every station index after
358 * it, and the result document is indexed by station row. A reader that has
359 * to see the Fork first therefore declares the Join here, in the position
360 * the model gives it, and binds the pair once the Fork exists.
361 */
362 std::size_t add_join_unbound(const std::string& nm) {
363 Station<T> st;
364 st.name = nm;
365 st.nodetype = NodeType::Join;
366 st.sched = SchedStrategy::INF;
367 st.nservers = std::numeric_limits<double>::infinity();
368 const std::size_t ist = sn_.add_station(st);
369 const std::size_t nd = sn_.station_to_node[ist - 1];
370 init_node(nd);
371 return nd;
372 }
373
374 /** Record which Fork a Join created by `add_join_unbound` closes. */
375 void bind_join(std::size_t join_node, std::size_t fork_node) {
376 if (join_node == 0 || join_node > sn_.nodes.size() ||
377 sn_.nodes[join_node - 1].nodetype != NodeType::Join)
378 throw InputError("bind_join: the node being bound is not a Join");
379 if (fork_node == 0 || fork_node > sn_.nodes.size() ||
380 sn_.nodes[fork_node - 1].nodetype != NodeType::Fork)
381 throw InputError("Join '" + sn_.nodes[join_node - 1].name +
382 "': the node it closes is not a Fork");
383 sn_.fj.emplace_back(fork_node, join_node);
384 }
385
386 /**
387 * A Place: an SPN token container. Modelled as an INF-scheduled station so
388 * the marginal machinery treats its tokens as "in service", which is the
389 * encoding `State.toMarginal` folds the buffer slot back into.
390 */
391 std::size_t add_place(const std::string& nm) { return add_place(nm, SchedStrategy::INF); }
392
393 /**
394 * A Place whose EMBEDDED QUEUE is served under `sched`: the QUEUEING PLACE
395 * of a queueing Petri net, `Place(model, name, schedStrategy)` in MATLAB.
396 *
397 * A token arriving here is NOT immediately available to the output
398 * transitions. It joins the place's own queue, is served by the place's own
399 * servers, and only on completion does it reach the DEPOSITORY that the
400 * output arcs draw from. That is the whole of the construct, and it is why
401 * the discipline has to be declared at construction: MATLAB's
402 * `installQueueServer` picks the server SECTION from it, and the section is
403 * what decides the server count.
404 *
405 * DECLARING THE DISCIPLINE DOES NOT YET MAKE IT A QUEUEING PLACE.
406 * `is_queueing_place` keys on a service process being present, which is
407 * `Place.queueing` being raised by `setService` and not by the constructor;
408 * a place built with a discipline and left without a service law is an
409 * ordinary pass-through place, exactly as in the reference.
410 *
411 * The server count follows the section: one server for the queueing
412 * disciplines and infinitely many for INF, which is also the ordinary
413 * place's own shape, so `add_place(nm)` is this call at INF.
414 */
415 std::size_t add_place(const std::string& nm, SchedStrategy sched) {
416 Station<T> st;
417 st.name = nm;
418 st.nodetype = NodeType::Place;
419 st.sched = sched;
420 st.nservers = (sched == SchedStrategy::INF)
421 ? std::numeric_limits<double>::infinity()
422 : 1.0;
423 const std::size_t ist = sn_.add_station(st);
424 init_node(sn_.station_to_node[ist - 1]);
425 return sn_.station_to_node[ist - 1];
426 }
427
428 /**
429 * A Transition: the firing rules of an SPN, as `Transition` in MATLAB.
430 *
431 * A transition has MODES, not classes: each mode has its own enabling and
432 * inhibiting conditions over the places, its own firing effect, and its own
433 * firing process. The parameters are transcribed from the reference's
434 * `refreshPetriNetNodes.m`, so `State.fromMarginal` finds the fields it
435 * reads instead of a node it cannot decode.
436 */
437 std::size_t add_transition(const std::string& nm, const TransitionParam<T>& par) {
438 if (par.nmodes == 0)
439 throw InputError("add_transition: a transition needs at least one mode");
440 if (par.enabling.size() != par.nmodes || par.firing.size() != par.nmodes)
441 throw InputError(
442 "add_transition: enabling and firing must have one entry per mode");
443 const std::size_t nd = sn_.add_node(nm, NodeType::Transition, true);
444 sn_.transparam[nd] = par;
445 init_node(nd);
446 return nd;
447 }
448
449 /**
450 * A Transition with NO modes yet: `Transition(model, name)` as MATLAB, the
451 * JAR and Python spell it, with the modes declared afterwards.
452 *
453 * THE NODE IS REGISTERED FIRST, which is the whole point of this overload.
454 * A transition is itself a node, so the arc matrices of the form above are
455 * (nnodes x nclasses) over a node count that does not exist until the LAST
456 * transition has been added -- a caller building a net through that
457 * overload has to hand-count the total and re-count it whenever the net
458 * gains a node. Here the arcs are held SPARSELY as (mode, node, class)
459 * triples and materialised against the finished model by `get_struct()`,
460 * so nothing has to be counted and nothing can be counted wrong.
461 */
462 std::size_t add_transition(const std::string& nm) {
463 const std::size_t nd = sn_.add_node(nm, NodeType::Transition, true);
464 sn_.transparam[nd] = TransitionParam<T>();
465 pending_arcs_[nd];
466 init_node(nd);
467 return nd;
468 }
469
470 /**
471 * `Transition.addMode(name)`: a new firing mode, returning its 1-based
472 * index. The defaults are the reference's own -- one server, TIMED,
473 * priority one, weight one, and no firing law until `set_mode_distribution`
474 * gives it one.
475 */
476 std::size_t add_mode(std::size_t node, const std::string& nm) {
477 TransitionParam<T>& tp = declarative_transition(node, "add_mode");
478 tp.modenames.push_back(nm);
481 tp.firingphases.push_back(0);
482 tp.nmodeservers.push_back(1.0);
483 tp.firingprio.push_back(1.0);
484 tp.fireweight.push_back(num_traits<T>::from_int(1));
485 tp.firingdep.push_back(std::function<T(const std::vector<T>&)>());
486 tp.fluidrate.emplace_back();
487 tp.fluidguard.emplace_back();
488 tp.fluidimpulse.emplace_back();
489 tp.fluiddep.emplace_back();
490 tp.fluidflowdep.emplace_back();
491 // Placeholders: the arcs are sparse until `materialize_transitions()`
492 // sizes them, but every per-mode vector must stay the same length.
493 tp.enabling.push_back(Matrix<T>());
494 tp.inhibiting.push_back(Matrix<T>());
495 tp.firing.push_back(Matrix<T>());
496 tp.nmodes = tp.modenames.size();
497 return tp.nmodes;
498 }
499
500 /** `Transition.setDistribution(mode, dist)`: the mode's firing law. */
501 void set_mode_distribution(std::size_t node, std::size_t mode, const Distrib<T>& d) {
502 mode_param(node, mode, "set_mode_distribution").firingproc[mode - 1] = d;
503 }
504
505 /** `Transition.setTimingStrategy(mode, strategy)`: TIMED or IMMEDIATE. */
506 void set_mode_timing(std::size_t node, std::size_t mode, lang::TimingStrategy ts) {
507 mode_param(node, mode, "set_mode_timing").timing[mode - 1] = ts;
508 }
509
510 /** `Transition.setNumberOfServers(mode, n)`; `GlobalConstants::MaxInt` is infinite. */
511 void set_mode_servers(std::size_t node, std::size_t mode, double n) {
512 mode_param(node, mode, "set_mode_servers").nmodeservers[mode - 1] = n;
513 }
514
515 /** `Transition.setFiringPriorities(mode, priority)`. */
516 void set_firing_priority(std::size_t node, std::size_t mode, double prio) {
517 mode_param(node, mode, "set_firing_priority").firingprio[mode - 1] = prio;
518 }
519
520 /** `Transition.setFiringWeights(mode, weight)`: the share among tied modes. */
521 void set_firing_weight(std::size_t node, std::size_t mode, const T& w) {
522 mode_param(node, mode, "set_firing_weight").fireweight[mode - 1] = w;
523 }
524
525 /** `Transition.setFiringRateDependence(mode, g)`: g(marking) scales the rate. */
526 void set_mode_firing_dependence(std::size_t node, std::size_t mode,
527 const std::function<T(const std::vector<T>&)>& g) {
528 mode_param(node, mode, "set_mode_firing_dependence").firingdep[mode - 1] = g;
529 }
530
531 /**
532 * `Transition.setFluidRate(mode, place, rate)`: the FSPN flow of a TIMED mode into (rate > 0) or out of
533 * (rate < 0) a fluid place, per running server. A zero rate removes the arc.
534 */
535 void set_mode_fluid_rate(std::size_t node, std::size_t mode, std::size_t place, double rate) {
536 TransitionParam<T>& tp = fluid_mode(node, mode, "set_mode_fluid_rate");
537 fluid_place_arg(place, "set_mode_fluid_rate");
538 if (!std::isfinite(rate))
539 throw InputError("set_mode_fluid_rate: the fluid rate must be a finite scalar");
540 set_fluid_row(tp.fluidrate[mode - 1], place, rate);
541 }
542
543 /**
544 * `Transition.setFluidGuard(mode, place, op, threshold)`: the mode is enabled only while the level of the
545 * fluid place satisfies `level op threshold`, op ">=" or "<=". One guard per place; an empty op removes it.
546 */
547 void set_mode_fluid_guard(std::size_t node, std::size_t mode, std::size_t place,
548 const std::string& op, double threshold) {
549 TransitionParam<T>& tp = fluid_mode(node, mode, "set_mode_fluid_guard");
550 fluid_place_arg(place, "set_mode_fluid_guard");
551 std::vector<typename TransitionParam<T>::FluidGuard>& g = tp.fluidguard[mode - 1];
552 for (std::size_t k = g.size(); k-- > 0;)
553 if (g[k].node == place) g.erase(g.begin() + static_cast<std::ptrdiff_t>(k));
554 if (op.empty()) return;
555 int sgn = 0;
556 if (op == ">=") sgn = 1;
557 else if (op == "<=") sgn = -1;
558 else throw InputError("set_mode_fluid_guard: the fluid guard operator must be '>=' or '<='");
559 if (!std::isfinite(threshold) || threshold < 0.0)
560 throw InputError(
561 "set_mode_fluid_guard: the fluid guard threshold must be a finite non-negative scalar");
563 fg.node = place;
564 fg.sgn = sgn;
565 fg.thr = threshold;
566 g.push_back(fg);
567 }
568
569 /**
570 * `Transition.setFluidImpulse(mode, place, delta)`: every firing of the mode moves the level of the fluid
571 * place by `delta` at once, truncated at the place's bounds. A zero delta removes the impulse.
572 */
573 void set_mode_fluid_impulse(std::size_t node, std::size_t mode, std::size_t place, double delta) {
574 TransitionParam<T>& tp = fluid_mode(node, mode, "set_mode_fluid_impulse");
575 fluid_place_arg(place, "set_mode_fluid_impulse");
576 if (!std::isfinite(delta))
577 throw InputError("set_mode_fluid_impulse: the fluid impulse must be a finite scalar");
578 set_fluid_row(tp.fluidimpulse[mode - 1], place, delta);
579 }
580
581 /**
582 * `Transition.setFluidRateDependence(mode, place, h)`: the firing rate of a TIMED, exponential mode is
583 * multiplied by h(level) of the fluid place; several places multiply. An empty `h` removes the dependence.
584 * The memoryless restriction is the one `set_mode_firing_dependence` carries, so set the Exp law first.
585 */
586 void set_mode_fluid_dependence(std::size_t node, std::size_t mode, std::size_t place,
587 const std::function<double(double)>& h) {
588 TransitionParam<T>& tp = fluid_mode(node, mode, "set_mode_fluid_dependence");
589 fluid_place_arg(place, "set_mode_fluid_dependence");
590 std::vector<typename TransitionParam<T>::FluidDep>& d = tp.fluiddep[mode - 1];
591 for (std::size_t k = d.size(); k-- > 0;)
592 if (d[k].node == place) d.erase(d.begin() + static_cast<std::ptrdiff_t>(k));
593 if (!h) return;
594 if (tp.timing[mode - 1] == lang::TimingStrategy::IMMEDIATE)
595 throw UnsupportedError(ErrorKind{"Transition"},
596 "set_mode_fluid_dependence: fluid rate dependence is not supported for IMMEDIATE modes");
597 if (tp.firingproc[mode - 1].disabled || tp.firingproc[mode - 1].type != lang::ProcessType::EXP)
598 throw UnsupportedError(ErrorKind{"Distribution"},
599 "set_mode_fluid_dependence: fluid rate dependence is supported only for exponentially "
600 "distributed (memoryless) firing; set an Exp distribution on the mode first");
602 fd.node = place;
603 fd.fun = h;
604 d.push_back(fd);
605 }
606
607 /**
608 * `Transition.setFluidFlowDependence(mode, place, phi, readPlaces)`: the flow of the mode into or out of the
609 * fluid place becomes k * rate * phi(M), k the running servers. M is the flattened marking described at
610 * `TransitionParam::FluidFlowDep`, filled on the token places `read` (1-based node indices); an empty `read`
611 * means the mode's input places, resolved at `get_struct()`. An empty `phi` removes the dependence.
612 */
613 void set_mode_fluid_flow_dependence(std::size_t node, std::size_t mode, std::size_t place,
614 const std::function<double(const std::vector<double>&)>& phi,
615 const std::vector<std::size_t>& read = std::vector<std::size_t>()) {
616 TransitionParam<T>& tp = fluid_mode(node, mode, "set_mode_fluid_flow_dependence");
617 fluid_place_arg(place, "set_mode_fluid_flow_dependence");
618 std::vector<typename TransitionParam<T>::FluidFlowDep>& d = tp.fluidflowdep[mode - 1];
619 for (std::size_t k = d.size(); k-- > 0;)
620 if (d[k].node == place) d.erase(d.begin() + static_cast<std::ptrdiff_t>(k));
621 if (!phi) return;
623 fd.node = place;
624 fd.fun = phi;
625 for (std::size_t q : read) {
626 if (q == 0 || q > sn_.nodes.size() || sn_.nodes[q - 1].nodetype != NodeType::Place)
627 throw InputError("set_mode_fluid_flow_dependence: the places a fluid flow dependence reads must be "
628 "Place nodes");
629 fd.read.push_back(q);
630 }
631 std::sort(fd.read.begin(), fd.read.end());
632 fd.read.erase(std::unique(fd.read.begin(), fd.read.end()), fd.read.end());
633 fd.read_given = !fd.read.empty();
634 d.push_back(fd);
635 }
636
637 /**
638 * `Transition.setEnablingConditions(mode, class, place, tokens)`: how many
639 * class-r tokens the mode needs at `place` before it may fire.
640 *
641 * The CLASS IS NOT DECORATION: a mode needing two Class1 tokens must not be
642 * enabled by Class2 tokens sitting at the same place, so the arc is keyed
643 * by the (place, class) pair and not by the place alone.
644 */
645 void set_enabling_conditions(std::size_t node, std::size_t mode, std::size_t cls,
646 std::size_t place, const T& tokens) {
647 arc_target(node, mode, cls, place, true, "set_enabling_conditions");
648 pending_arcs_[node].enab.push_back(TransitionArc(mode, place, cls, tokens));
649 }
650
651 /**
652 * `Transition.setInhibitingConditions(mode, class, place, tokens)`: the
653 * class-r count at `place` that BLOCKS the mode. Absent means never, which
654 * the materialised matrix spells as infinity.
655 */
656 void set_inhibiting_conditions(std::size_t node, std::size_t mode, std::size_t cls,
657 std::size_t place, const T& tokens) {
658 arc_target(node, mode, cls, place, true, "set_inhibiting_conditions");
659 pending_arcs_[node].inhib.push_back(TransitionArc(mode, place, cls, tokens));
660 }
661
662 /**
663 * `Transition.setFiringOutcome(mode, class, node, tokens)`: the class-r
664 * tokens the firing deposits. The destination is any node the firing may
665 * reach, a Sink included, which is why it is not narrowed to a Place.
666 */
667 void set_firing_outcome(std::size_t node, std::size_t mode, std::size_t cls,
668 std::size_t dest, const T& tokens) {
669 arc_target(node, mode, cls, dest, false, "set_firing_outcome");
670 pending_arcs_[node].fire.push_back(TransitionArc(mode, dest, cls, tokens));
671 }
672
673 /**
674 * `Queue.setRetrial(...)`: a station with an ORBIT instead of a waiting
675 * line. An arrival finding every server busy joins the orbit and re-attempts
676 * at `rate`; a completion does NOT promote from the orbit, so the state is
677 * an (in-service, orbit) split rather than an ordered buffer.
678 */
679 void set_retrial(std::size_t node, std::size_t cls, const Distrib<T>& proc, const T& rate,
680 int max_attempts = 0) {
681 if (node == 0 || node > sn_.nodes.size())
682 throw InputError("set_retrial: node index is out of range");
683 const std::size_t ist = sn_.nodes[node - 1].station;
684 if (ist == 0) throw InputError("set_retrial: node is not a station");
685 // Size against the LIVE class list: sn_.nclasses is a finalize-time
686 // field and is still zero while the model is being built, so sizing
687 // against it left the vectors empty and the write below went out of
688 // bounds.
689 const std::size_t K = sn_.classes.size();
690 if (cls == 0 || cls > K)
691 throw InputError("set_retrial: class index is out of range");
692 RetrialParam<T>& rp = sn_.retrialparam[ist];
693 if (rp.retrial_proc.size() < K) {
694 rp.retrial_proc.resize(K);
695 rp.retrial_rate.resize(K, num_traits<T>::from_int(0));
696 rp.max_attempts.resize(K, 0);
697 }
698 if (rp.policy.size() < K) rp.policy.resize(K, 1);
699 if (rp.max_orbit.size() < K) rp.max_orbit.resize(K, -1);
700 rp.retrial_proc[cls - 1] = proc;
701 rp.retrial_rate[cls - 1] = rate;
702 rp.max_attempts[cls - 1] = max_attempts;
703 // As `Queue.setRetrial` does, the orbit is also declared as the class's drop rule,
704 // which is what MAM and LDES read to recognise a retrial station.
705 set_drop_rule(node, cls, max_attempts > 0 ? DropStrategy::RETRIAL_WITH_LIMIT
706 : DropStrategy::RETRIAL);
707 }
708
709 /**
710 * The policy and bound of `Queue.setOrbit(class, dist, policy, maxOrbit)`
711 * on a class already declared by set_retrial: policy 1 = LINEAR (every
712 * orbiting job retries at its own rate), 2 = CONSTANT (the orbit retries as
713 * a whole); max_orbit = -1 leaves the orbit unbounded.
714 *
715 * As the reference does, the orbit lives in the station buffer: the
716 * capacity becomes nservers + max_orbit, or Inf for an unbounded orbit,
717 * and a station with no finite server count gets one server. The JSON
718 * reader passes `size_buffer = false`, since the document carries its own
719 * `buffer` and that value is authoritative.
720 */
721 void set_orbit_policy(std::size_t node, std::size_t cls, int policy, int max_orbit,
722 bool size_buffer = true) {
723 if (node == 0 || node > sn_.nodes.size())
724 throw InputError("set_orbit_policy: node index is out of range");
725 const std::size_t ist = sn_.nodes[node - 1].station;
726 typename std::map<std::size_t, RetrialParam<T> >::iterator it = sn_.retrialparam.find(ist);
727 if (ist == 0 || it == sn_.retrialparam.end() || cls == 0 ||
728 cls > it->second.retrial_proc.size() || it->second.retrial_proc[cls - 1].disabled)
729 throw InputError("set_orbit_policy: the class has no retrial declared at this station");
730 if (policy != 1 && policy != 2)
731 throw InputError("set_orbit_policy: the policy must be 1 (LINEAR) or 2 (CONSTANT)");
732 if (max_orbit < -1)
733 throw InputError("set_orbit_policy: max_orbit must be -1 (unbounded) or non-negative");
734 it->second.policy[cls - 1] = policy;
735 it->second.max_orbit[cls - 1] = max_orbit;
736 if (size_buffer) {
737 Station<T>& st = sn_.stations[ist - 1];
738 if (!std::isfinite(st.nservers) || st.nservers < 1.0) set_number_of_servers(node, 1.0);
739 st.cap = max_orbit < 0 ? std::numeric_limits<double>::infinity()
740 : st.nservers + double(max_orbit);
741 }
742 }
743
744 /**
745 * `Queue.setPatience(class, dist, type)`: the abandonment timer of a job
746 * WAITING at the station, and which impatience rule the timer belongs to.
747 */
748 void set_patience(std::size_t node, std::size_t cls, const Distrib<T>& dist,
750 Station<T>& st = station_ref(node, cls, "set_patience");
752 if (kind == lang::ImpatienceType::RENEGING && std::isfinite(sn_.classes[cls - 1].population))
753 closed_reneging_refusal(sn_.classes[cls - 1].name, " at queue \"" + sn_.nodes[node - 1].name + "\"");
754 grow_class_slot(st.patience, cls, Distrib<T>::disabled_dist());
755 grow_class_slot(st.impatience, cls, lang::ImpatienceType::NONE);
756 st.patience[cls - 1] = dist;
757 st.impatience[cls - 1] = kind;
758 }
759
760 /** `Queue.setOrbitImpatience(class, dist)`: abandonment from the retrial orbit. */
761 void set_orbit_impatience(std::size_t node, std::size_t cls, const Distrib<T>& dist) {
762 Station<T>& st = station_ref(node, cls, "set_orbit_impatience");
763 grow_class_slot(st.orbit_impatience, cls, Distrib<T>::disabled_dist());
764 st.orbit_impatience[cls - 1] = dist;
765 }
766
767 /** `Queue.setBatchRejectProbability(class, p)`. */
768 void set_batch_reject(std::size_t node, std::size_t cls, const T& p) {
769 Station<T>& st = station_ref(node, cls, "set_batch_reject");
770 grow_class_slot(st.batch_reject, cls, num_traits<T>::from_int(0));
771 st.batch_reject[cls - 1] = p;
772 }
773
774 /**
775 * `Queue.setOrbitPersistence(class, joinProb, persistProb)`: non-persistent
776 * retrial customers (Phung-Duc 2019, Sec. 2). A fresh arrival that finds
777 * every server busy joins the orbit with probability `join_prob` and is
778 * lost otherwise; a retrial that finds every server busy returns to the
779 * orbit with probability `persist_prob` and leaves the system otherwise.
780 * Both default to 1. A closed class cannot leave the network, so p < 1 or
781 * q < 1 on one is refused (LINE:unsupported:Retrial).
782 */
783 void set_orbit_persistence(std::size_t node, std::size_t cls, const T& join_prob,
784 const T& persist_prob = num_traits<T>::from_int(1)) {
785 Station<T>& st = station_ref(node, cls, "set_orbit_persistence");
786 const double p = num_traits<T>::to_double(join_prob);
787 const double q = num_traits<T>::to_double(persist_prob);
788 if (!std::isfinite(p) || p < 0.0 || p > 1.0)
789 throw InputError("Orbit join probability must be in [0, 1].");
790 if (!std::isfinite(q) || q < 0.0 || q > 1.0)
791 throw InputError("Orbit persistence probability must be in [0, 1].");
792 if ((p < 1.0 || q < 1.0) && std::isfinite(sn_.classes[cls - 1].population))
793 throw UnsupportedError(ErrorKind{"Retrial"},
794 "Non-persistent retrial customers leave the network, which a closed class cannot do; "
795 "use an open class.");
796 grow_class_slot(st.orbit_join, cls, num_traits<T>::from_int(1));
797 grow_class_slot(st.orbit_persist, cls, num_traits<T>::from_int(1));
798 st.orbit_join[cls - 1] = join_prob;
799 st.orbit_persist[cls - 1] = persist_prob;
800 }
801
802 /**
803 * `Queue.setOrbitalSearch(class, prob)`: orbital search (Artalejo, Joshua
804 * and Krishnamoorthy 2002). On each service completion at this retrial
805 * station the freed server takes a class-`cls` orbiting job with
806 * probability `prob` instead of staying idle. Default 0; the probabilities
807 * over the classes must sum to at most 1.
808 */
809 void set_orbital_search(std::size_t node, std::size_t cls, const T& prob) {
810 Station<T>& st = station_ref(node, cls, "set_orbital_search");
811 const double th = num_traits<T>::to_double(prob);
812 if (!std::isfinite(th) || th < 0.0 || th > 1.0)
813 throw InputError("Orbital search probability must be in [0, 1].");
814 double total = th;
815 for (std::size_t r = 0; r < st.orbit_search.size(); ++r)
816 if (r != cls - 1) total += num_traits<T>::to_double(st.orbit_search[r]);
817 if (total > 1.0 + 1e-12)
818 throw InputError("Orbital search probabilities over the classes must sum to at most 1.");
819 grow_class_slot(st.orbit_search, cls, num_traits<T>::from_int(0));
820 st.orbit_search[cls - 1] = prob;
821 }
822
823 /**
824 * `Queue.setBalking(class, strategy, thresholds)`: an arrival that refuses
825 * to JOIN, on the state it finds. Distinct from reneging, which abandons a
826 * job that has already joined.
827 */
828 void set_balking(std::size_t node, std::size_t cls, lang::BalkingStrategy strategy,
829 const std::vector<typename Station<T>::BalkingThreshold>& thresholds) {
830 Station<T>& st = station_ref(node, cls, "set_balking");
831 grow_class_slot(st.balking, cls, typename Station<T>::BalkingParam());
832 st.balking[cls - 1].strategy = strategy;
833 st.balking[cls - 1].thresholds = thresholds;
834 }
835
836 /** `Queue.addServerType(...)`: one heterogeneous server pool of the station. */
837 void add_server_type(std::size_t node, const typename Station<T>::ServerType& stype) {
838 const std::size_t ist = station_of(node, "add_server_type");
839 sn_.stations[ist - 1].server_types.push_back(stype);
840 // The pools size the station, as in MATLAB/JAR updateTotalServerCount
841 double total = 0.0;
842 for (const auto& pool : sn_.stations[ist - 1].server_types) total += pool.count;
843 sn_.stations[ist - 1].nservers = total;
844 }
845
846 /**
847 * `Queue.setServerParallelism(class, n)`: the servers a job seizes for the
848 * whole of its service. The station then serves at most floor(c/n) such jobs
849 * at a time.
850 */
851 void set_server_parallelism(std::size_t node, std::size_t cls, std::size_t n) {
852 Station<T>& st = station_ref(node, cls, "set_server_parallelism");
853 if (n < 1) {
854 throw InputError("set_server_parallelism: parallelism must be a positive integer");
855 }
856 if (std::isfinite(st.nservers) && static_cast<double>(n) > st.nservers) {
857 throw InputError(
858 "set_server_parallelism: parallelism " + std::to_string(n) + " exceeds the " +
859 std::to_string(static_cast<long long>(st.nservers)) + " servers of station '" +
860 sn_.nodes[node - 1].name + "', so a job of this class could never enter service");
861 }
862 grow_class_slot(st.server_parallelism, cls, static_cast<std::size_t>(1));
863 st.server_parallelism[cls - 1] = n;
864 }
865
866 /** `Queue.setHeteroSchedPolicy(...)`: how the server pools are picked among. */
867 void set_hetero_sched_policy(std::size_t node, lang::HeteroSchedPolicy policy) {
868 sn_.stations[station_of(node, "set_hetero_sched_policy") - 1].hetero_policy = policy;
869 }
870
871 /**
872 * `Source.setArrivalBatch(class, dist)`: the batch-size law released at each
873 * arrival epoch. The arrival process itself only spaces the epochs.
874 */
875 void set_arrival_batch(std::size_t node, std::size_t cls, const Distrib<T>& dist) {
876 Station<T>& st = station_ref(node, cls, "set_arrival_batch");
877 if (!dist.disabled) {
878 // A batch must carry at least one job: a law that can return zero is rejected, not clamped, as in the other codebases.
879 const T one = num_traits<T>::from_int(1);
880 bool zero_in_support = false;
881 switch (dist.type) {
885 zero_in_support = true;
886 break;
888 zero_in_support = !dist.params.empty() && dist.params[0] < one;
889 break;
891 for (const T& x : dist.trace) zero_in_support = zero_in_support || x < one;
892 break;
893 default:
894 break;
895 }
896 if (zero_in_support)
897 throw InputError("set_arrival_batch: the batch-size law can return a value below one; a batch must carry "
898 "at least one job, so its support must be {1,2,...}");
899 if (dist.mean < one)
900 throw InputError("set_arrival_batch: the batch-size law has mean below one; a batch must carry at least "
901 "one job, so its support must be {1,2,...}");
902 }
903 grow_class_slot(st.arrival_batch, cls, Distrib<T>::disabled_dist());
904 st.arrival_batch[cls - 1] = dist;
905 }
906
907 /** `Source.markedClasses`: the 1-based class carried by each mark of an MMAP. */
908 void set_marked_classes(std::size_t node, const std::vector<std::size_t>& classes) {
909 sn_.stations[station_of(node, "set_marked_classes") - 1].marked_classes = classes;
910 }
911
912 /** `Place.setDepartureDiscipline(class, rule)`. */
913 void set_departure_discipline(std::size_t node, std::size_t cls,
915 Station<T>& st = station_ref(node, cls, "set_departure_discipline");
917 st.departure_discipline[cls - 1] = rule;
918 }
919
920 /** `Place.setState(marking)`: the initial token count of the place, per class. */
921 void set_initial_marking(std::size_t node, const std::vector<T>& tokens) {
922 if (node == 0 || node > sn_.nodes.size())
923 throw InputError("set_initial_marking: node index is out of range");
924 if (sn_.nodes[node - 1].nodetype != NodeType::Place)
925 throw InputError("set_initial_marking: only a Place carries an initial marking");
926 sn_.initmarking[node] = tokens;
927 }
928
929 /**
930 * `Place.setFluid(flag)`: the place holds one real level in [0, fluid capacity] instead of tokens, the fluid
931 * place of an FSPN. Fluid moves only through the fluid arcs of the transitions; token arcs on it are refused
932 * by the solvers rather than here, because the arcs may be declared before the flag.
933 */
934 void set_place_fluid(std::size_t node, bool fluid) {
935 place_station(node, "set_place_fluid").fluid = fluid;
936 }
937
938 /** `Place.setFluidCapacity(B)`: the level ceiling of a fluid place, Inf when unbounded. */
939 void set_fluid_capacity(std::size_t node, double cap) {
940 if (std::isnan(cap) || cap <= 0.0)
941 throw InputError("set_fluid_capacity: the fluid capacity must be a positive scalar, or Inf "
942 "for an unbounded place");
943 place_station(node, "set_fluid_capacity").fluidcap = cap;
944 }
945
946 /** `Place.setFluidLevel(x0)`: the initial level of a fluid place. */
947 void set_fluid_level(std::size_t node, double level) {
948 if (!std::isfinite(level) || level < 0.0)
949 throw InputError("set_fluid_level: the initial fluid level must be a finite non-negative scalar");
950 place_station(node, "set_fluid_level").fluidinit = level;
951 }
952
953 /** `Place.isFluid()`, `getFluidCapacity()` and `getFluidLevel()`. */
954 bool is_place_fluid(std::size_t node) { return place_station(node, "is_place_fluid").fluid; }
955 double get_fluid_capacity(std::size_t node) {
956 return place_station(node, "get_fluid_capacity").fluidcap;
957 }
958 double get_fluid_level(std::size_t node) { return place_station(node, "get_fluid_level").fluidinit; }
959
960 /** `Transition.hasFluidArcs()`: any mode declares a flow, guard, impulse or fluid rate dependence. */
961 bool has_fluid_arcs(std::size_t node) const {
962 const auto it = sn_.transparam.find(node);
963 return it != sn_.transparam.end() && it->second.has_fluid_arcs();
964 }
965
966 /**
967 * `StatefulNode.setStatePrior(space, prior)`: a distribution over the rows
968 * of a DECLARED state space. The two are set together because a prior
969 * indexes that space and means nothing without it.
970 */
971 void set_state_prior(std::size_t node, const Matrix<T>& space, const std::vector<T>& prior) {
972 if (node == 0 || node > sn_.nodes.size())
973 throw InputError("set_state_prior: node index is out of range");
974 if (space.rows() != prior.size())
975 throw InputError(
976 "set_state_prior: the prior has one entry per ROW of the declared state space");
977 sn_.statespace[node] = space;
978 sn_.stateprior[node] = prior;
979 }
980
981 /** `Join.setStrategy(...)`: STD waits for every sibling, PARTIAL for a quorum. */
982 void set_join_strategy(std::size_t node, lang::JoinStrategy strategy, double quorum = 0.0) {
983 if (node == 0 || node > sn_.nodes.size())
984 throw InputError("set_join_strategy: node index is out of range");
985 if (sn_.nodes[node - 1].nodetype != NodeType::Join)
986 throw InputError("set_join_strategy: the node is not a Join");
987 typename NetworkStruct<T>::JoinDecl jd;
988 jd.strategy = strategy;
989 jd.quorum = quorum;
990 sn_.joindecl[node] = jd;
991 }
992
993 /** The per-destination weights of a WRROBIN dispatcher, per (node, class). */
994 void set_routing_weights(std::size_t node, std::size_t cls,
995 const std::map<std::size_t, double>& weights) {
996 if (node == 0 || node > sn_.nodes.size())
997 throw InputError("set_routing_weights: node index is out of range");
998 std::vector<std::map<std::size_t, double>>& rw = sn_.nodes[node - 1].routing_weights;
999 if (rw.size() < sn_.classes.size()) rw.resize(sn_.classes.size());
1000 if (cls == 0 || cls > rw.size())
1001 throw InputError("set_routing_weights: class index is out of range");
1002 rw[cls - 1] = weights;
1003 }
1004
1005 /** The d of a power-of-d (SQ) dispatcher, per (node, class). */
1006 void set_routing_param(std::size_t node, std::size_t cls, int d) {
1007 if (node == 0 || node > sn_.nodes.size())
1008 throw InputError("set_routing_param: node index is out of range");
1009 std::vector<int>& rp = sn_.nodes[node - 1].routing_param;
1010 if (rp.size() < sn_.classes.size()) rp.resize(sn_.classes.size(), 0);
1011 if (cls == 0 || cls > rp.size())
1012 throw InputError("set_routing_param: class index is out of range");
1013 rp[cls - 1] = d;
1014 }
1015
1016 /**
1017 * `Queue.setDelayOff(class, setupTime, delayoffTime)`: the station powers
1018 * down after sitting idle for the delay-off time, and the next arrival pays
1019 * the setup time before service. The pair is set together because a setup
1020 * with no delay-off never fires and a delay-off with no setup is free.
1021 */
1022 void set_setup_delayoff(std::size_t node, std::size_t cls, const Distrib<T>& setup,
1023 const Distrib<T>& delayoff) {
1024 const std::size_t ist = station_of(node, "set_setup_delayoff");
1025 const std::size_t K = sn_.classes.size();
1026 if (cls == 0 || cls > K)
1027 throw InputError("set_setup_delayoff: class index is out of range");
1028 SetupDelayOffParam<T>& sp = sn_.setupparam[ist];
1029 if (sp.setup.size() < K) {
1030 sp.setup.resize(K, Distrib<T>::disabled_dist());
1031 sp.delayoff.resize(K, Distrib<T>::disabled_dist());
1032 }
1033 sp.setup[cls - 1] = setup;
1034 sp.delayoff[cls - 1] = delayoff;
1035 }
1036
1037 /**
1038 * `Queue.setBreakdown(failure, repair, downService)`: the server alternates
1039 * up and down on the two clocks.
1040 *
1041 * BOTH CLOCKS ARE REQUIRED. A server that fails and is never repaired is a
1042 * different model -- an absorbing one -- and the reference declines to infer
1043 * it from a missing repair time rather than treating it as infinite.
1044 *
1045 * `down_service` is per class and OPTIONAL; an entry left disabled means the
1046 * class gets no service while the server is down, which is the ordinary
1047 * reading. A declared one must be EXPONENTIAL: a phase-type degraded service
1048 * would need its own phase block in the joint chain and no codebase builds
1049 * one, so it is refused by name rather than approximated by its mean.
1050 */
1051 void set_breakdown(std::size_t node, const Distrib<T>& failure, const Distrib<T>& repair,
1052 const std::vector<Distrib<T>>& down_service = std::vector<Distrib<T>>()) {
1053 const std::size_t ist = station_of(node, "set_breakdown");
1054 if (failure.disabled || repair.disabled)
1055 throw InputError(
1056 "set_breakdown: both a failure and a repair time are required; a server that "
1057 "never recovers is an absorbing model, not a breakdown");
1058 const double fm = num_traits<T>::to_double(failure.mean);
1059 const double rm = num_traits<T>::to_double(repair.mean);
1060 if (!(fm > 0.0) || !(rm > 0.0))
1061 throw InputError("set_breakdown: the failure and repair times must have positive means");
1062 const std::size_t K = sn_.classes.size();
1063 BreakdownParam<T>& bp = sn_.breakdownparam[ist];
1064 bp.failure = failure;
1065 bp.repair = repair;
1066 bp.failure_rate = T(num_traits<T>::from_int(1) / failure.mean);
1067 bp.repair_rate = T(num_traits<T>::from_int(1) / repair.mean);
1069 for (std::size_t r = 0; r < K && r < down_service.size(); ++r) {
1070 const Distrib<T>& d = down_service[r];
1071 if (d.disabled) continue;
1073 throw UnsupportedError(ErrorKind{"Breakdown"},
1074 "set_breakdown: station '" + sn_.stations[ist - 1].name +
1075 "': the down-server service distribution must be exponential; a phase-type "
1076 "degraded service would need its own phase block in the joint chain");
1077 if (num_traits<T>::to_double(d.mean) > 0.0)
1079 }
1080 }
1081
1082 /** A Cache node with its item population, list capacities and popularity. */
1083 std::size_t add_cache(const std::string& nm, const CacheParam<T>& par) {
1084 const std::size_t nd = sn_.add_node(nm, NodeType::Cache, true);
1085 sn_.nodeparam[nd] = par;
1086 init_node(nd);
1087 return nd;
1088 }
1089
1090 /**
1091 * `Cache.setItemReadClasses(readClasses, hitClasses)`: declare that
1092 * `read_classes[i]` is the request stream for item i at this cache. Use at the
1093 * cache the exogenous requests enter, where the per-item classes are the
1094 * caller's own; item popularity is then carried by the per-class request rates
1095 * rather than by a popularity the cache draws from. This is what keeps a cache
1096 * network free of arc-level class switching, so no class acquires a default
1097 * route into the cache the model never intended. `hit_classes` is either one
1098 * class shared by every item or one per item.
1099 */
1100 void set_item_read_classes(std::size_t cache_node,
1101 const std::vector<std::size_t>& read_classes,
1102 const std::vector<std::size_t>& hit_classes) {
1103 auto it = sn_.nodeparam.find(cache_node);
1104 if (it == sn_.nodeparam.end())
1105 throw InputError("setItemReadClasses: node is not a Cache");
1106 CacheParam<T>& cp = it->second;
1107 const std::size_t nitems = cp.nitems;
1108 if (read_classes.size() != nitems)
1109 throw InputError("setItemReadClasses: pass exactly one read class per item");
1110 const std::vector<std::size_t> hit =
1111 per_item_classes(hit_classes, nitems, "setItemReadClasses hit");
1112 const std::size_t K = sn_.classes.size();
1113 cp.pread.resize(K);
1114 cp.preadkind.resize(K);
1115 cp.hitclass.resize(K, 0);
1116 cp.missclass.resize(K, 0);
1117 cp.classitem.resize(K, 0);
1118 for (std::size_t i = 0; i < nitems; ++i) {
1119 std::vector<T> onehot(nitems, num_traits<T>::from_int(0));
1120 onehot[i] = num_traits<T>::from_int(1);
1121 cp.pread[read_classes[i] - 1] = onehot;
1122 cp.hitclass[read_classes[i] - 1] = hit[i];
1123 cp.classitem[read_classes[i] - 1] = i + 1;
1124 }
1125 cache_item_classes_[cache_node] = read_classes;
1126 }
1127
1128 /**
1129 * `Cache.setRead(jobclass, popularity)`: class `r` (1-based) reads the cache, drawing items
1130 * from the pmf `pmf` over the ranks 1..nitems. May be called after the classes exist, which is
1131 * what a CacheParam given at construction cannot do once the node precedes its classes.
1132 */
1133 void set_cache_read(std::size_t cache_node, std::size_t r, const std::vector<T>& pmf) {
1134 CacheParam<T>& cp = cache_param_for_class(cache_node, r, "set_read");
1135 if (pmf.size() != cp.nitems)
1136 throw InputError("set_read: the popularity has " + std::to_string(pmf.size()) +
1137 " entries and the cache '" + sn_.nodes[cache_node - 1].name + "' " +
1138 std::to_string(cp.nitems) + " items");
1139 cp.pread[r - 1] = pmf;
1140 cp.preadkind[r - 1] = typename CacheParam<T>::Popularity();
1141 }
1142
1143 /**
1144 * `Cache.setRead(jobclass, Zipf(s, n))` or `DiscreteSampler(p)`: the law is expanded to its pmf,
1145 * which every solver reads, and kept in `preadkind` because JMT's Cache section takes it as is.
1146 */
1147 void set_cache_read(std::size_t cache_node, std::size_t r, const lang::Distrib<T>& d) {
1148 std::vector<T> pmf;
1149 typename CacheParam<T>::Popularity kind;
1150 if (d.type == lang::ProcessType::ZIPF && d.params.size() >= 2) {
1151 const double sv = num_traits<T>::to_double(d.params[0]);
1152 const std::size_t n = static_cast<std::size_t>(num_traits<T>::to_double(d.params[1]));
1153 double h = 0.0;
1154 for (std::size_t k = 1; k <= n; ++k) h += std::pow(double(k), -sv);
1155 for (std::size_t k = 1; k <= n; ++k)
1156 pmf.push_back(num_traits<T>::from_double(std::pow(double(k), -sv) / h));
1158 kind.s = sv;
1159 kind.n = n;
1160 } else if (d.type == lang::ProcessType::DISCRETESAMPLER) {
1161 pmf = d.params;
1163 kind.n = pmf.size();
1164 } else {
1165 throw InputError("set_read: an item popularity is a Zipf or a DiscreteSampler over the item ranks");
1166 }
1167 set_cache_read(cache_node, r, pmf);
1168 cache_param_for_class(cache_node, r, "set_read").preadkind[r - 1] = kind;
1169 }
1170
1171 /** `Cache.setHitClass(jobclass, hitclass)`: a class-`r` read that hits leaves as class `h`. */
1172 void set_cache_hit_class(std::size_t cache_node, std::size_t r, std::size_t h) {
1173 CacheParam<T>& cp = cache_param_for_class(cache_node, r, "set_hit_class");
1174 check_class(h, "set_hit_class");
1175 cp.hitclass[r - 1] = h;
1176 }
1177
1178 /** `Cache.setMissClass(jobclass, missclass)`: a class-`r` read that misses leaves as class `m`. */
1179 void set_cache_miss_class(std::size_t cache_node, std::size_t r, std::size_t m) {
1180 CacheParam<T>& cp = cache_param_for_class(cache_node, r, "set_miss_class");
1181 check_class(m, "set_miss_class");
1182 cp.missclass[r - 1] = m;
1183 }
1184
1185 /**
1186 * `Cache.setMissCache(readClass, nextCache, hitClassAtNext)`: send this cache's
1187 * misses to `next_cache` preserving item identity, by minting one class per item
1188 * there and making the miss class of item i here its read class for item i.
1189 * Returns the minted classes. The cache-to-cache arc itself is registered here
1190 * and injected by `link()`, so the caller routes only its own topology.
1191 */
1192 std::vector<std::size_t> set_miss_cache(std::size_t cache_node, std::size_t next_cache,
1193 const std::vector<std::size_t>& hit_classes_at_next) {
1194 auto it = sn_.nodeparam.find(cache_node);
1195 auto itn = sn_.nodeparam.find(next_cache);
1196 if (it == sn_.nodeparam.end() || itn == sn_.nodeparam.end())
1197 throw InputError("setMissCache: both nodes must be Caches");
1198 if (it->second.nitems != itn->second.nitems)
1199 throw InputError("setMissCache: a cache network requires one common item set");
1200 auto self_it = cache_item_classes_.find(cache_node);
1201 if (self_it == cache_item_classes_.end())
1202 throw InputError("setMissCache: call setItemReadClasses on the source cache first");
1203 const std::vector<std::size_t> self_cls = self_it->second;
1204 const std::size_t nitems = it->second.nitems;
1205 const std::vector<std::size_t> hit =
1206 per_item_classes(hit_classes_at_next, nitems, "setMissCache hit");
1207
1208 std::vector<std::size_t> minted;
1209 minted.reserve(nitems);
1210 const bool closed = sn_.classes[self_cls[0] - 1].type == JobClassType::CLOSED;
1211 const std::size_t refstat = sn_.classes[self_cls[0] - 1].refstat;
1212 for (std::size_t i = 0; i < nitems; ++i) {
1213 std::size_t cls;
1214 if (closed)
1215 cls = add_closed_class(sn_.nodes[next_cache - 1].name + "_item" + std::to_string(i + 1),
1216 0.0, sn_.station_to_node[refstat - 1]);
1217 else
1218 cls = add_open_class(sn_.nodes[next_cache - 1].name + "_item" + std::to_string(i + 1));
1219 minted.push_back(cls);
1220 }
1221 // the class count grew, so re-size both caches' per-class vectors once
1222 const std::size_t K = sn_.classes.size();
1223 for (std::size_t nd : {cache_node, next_cache}) {
1224 CacheParam<T>& c = sn_.nodeparam.at(nd);
1225 c.pread.resize(K);
1226 c.preadkind.resize(K);
1227 c.hitclass.resize(K, 0);
1228 c.missclass.resize(K, 0);
1229 c.classitem.resize(K, 0);
1230 }
1231 CacheParam<T>& src = sn_.nodeparam.at(cache_node);
1232 CacheParam<T>& dst = sn_.nodeparam.at(next_cache);
1233 for (std::size_t i = 0; i < nitems; ++i) {
1234 std::vector<T> onehot(nitems, num_traits<T>::from_int(0));
1235 onehot[i] = num_traits<T>::from_int(1);
1236 dst.pread[minted[i] - 1] = onehot;
1237 dst.hitclass[minted[i] - 1] = hit[i];
1238 dst.classitem[minted[i] - 1] = i + 1;
1239 src.missclass[self_cls[i] - 1] = minted[i];
1240 // the miss hop is part of the construction, not of the user's topology:
1241 // register it here and let link() inject it, as the MATLAB helper does
1242 // through retrievalRoutingEntries
1243 cache_miss_arcs_.push_back(CacheMissArc(minted[i], cache_node, next_cache));
1244 }
1245 cache_item_classes_[next_cache] = minted;
1246 return minted;
1247 }
1248
1249 /**
1250 * `Cache.setItemMissClass(readClass, missClasses)`: terminate a cache network,
1251 * every per-item class of this cache reporting a miss as the matching entry of
1252 * `miss_classes`, which the caller routes onward.
1253 */
1254 void set_item_miss_class(std::size_t cache_node, const std::vector<std::size_t>& miss_classes) {
1255 auto it = sn_.nodeparam.find(cache_node);
1256 if (it == sn_.nodeparam.end())
1257 throw InputError("setItemMissClass: node is not a Cache");
1258 auto self_it = cache_item_classes_.find(cache_node);
1259 if (self_it == cache_item_classes_.end())
1260 throw InputError("setItemMissClass: the cache has no per-item classes");
1261 const std::vector<std::size_t>& self_cls = self_it->second;
1262 const std::vector<std::size_t> miss =
1263 per_item_classes(miss_classes, self_cls.size(), "setItemMissClass miss");
1264 CacheParam<T>& cp = it->second;
1265 cp.missclass.resize(sn_.classes.size(), 0);
1266 for (std::size_t i = 0; i < self_cls.size(); ++i)
1267 cp.missclass[self_cls[i] - 1] = miss[i];
1268 }
1269
1270 /**
1271 * `Cache.setRetrievalSystem(readClass, missClass, queues)`: a delayed-hit
1272 * cache whose misses are fetched by circulating a per-item retrieval class
1273 * through `queue_nodes` and back to the cache. Creates one retrieval class
1274 * per item, each inheriting the read class's service at every retrieval queue
1275 * (call `set_service(queue, readClass, ...)` first); the routing among the
1276 * cache and the queues is inherited from the read class in `link()`. Records
1277 * the retrieval capacity (nitems - total cache capacity), the queue node
1278 * list, and the item -> retrieval-class map that `cache_retrieval_inputs`
1279 * reads. Must be called after the read/miss classes and the cache exist.
1280 */
1281 void set_retrieval_system(std::size_t cache_node, std::size_t read_class,
1282 std::size_t miss_class, const std::vector<std::size_t>& queue_nodes) {
1283 auto it = sn_.nodeparam.find(cache_node);
1284 if (it == sn_.nodeparam.end())
1285 throw InputError("setRetrievalSystem: node is not a Cache");
1286 CacheParam<T>& cp = it->second;
1287 if (queue_nodes.empty())
1288 throw InputError("setRetrievalSystem: the retrieval system has no stations");
1289 const std::size_t nitems = cp.nitems;
1290 int totalcap = 0;
1291 for (int c : cp.itemcap) totalcap += c;
1292 cp.retrieval_capacity = static_cast<int>(nitems) - totalcap;
1293 cp.retrieval_queues[read_class - 1] = queue_nodes; // 0-based key, 1-based nodes
1294
1295 // capture the read class's service distribution at each queue up front; an unset (disabled) entry is the
1296 // reference's empty serviceProcess{r}, refused with its text (Cache.m setRetrievalSystem)
1297 std::vector<Distrib<T> > svc;
1298 svc.reserve(queue_nodes.size());
1299 for (std::size_t q : queue_nodes) {
1300 const std::size_t st = station_of(q, "setRetrievalSystem");
1301 const Distrib<T>& d = sn_.service[st - 1][read_class - 1];
1303 throw InputError("No service distribution for the read class at queue \"" +
1304 sn_.nodes[q - 1].name +
1305 "\"; call queue.setService(readClass, ...) before setRetrievalSystem.");
1306 svc.push_back(d);
1307 }
1308
1309 cp.retrieval_classes.assign(nitems, std::vector<std::size_t>(sn_.classes.size(), 0));
1310 const bool closed = sn_.classes[read_class - 1].type == JobClassType::CLOSED;
1311 const std::size_t refstat = sn_.classes[read_class - 1].refstat;
1312 for (std::size_t i = 0; i < nitems; ++i) {
1313 std::size_t rc;
1314 if (closed)
1315 rc = add_closed_class(sn_.classes[read_class - 1].name + "_retrievalClass_" +
1316 std::to_string(i + 1),
1317 0.0, sn_.station_to_node[refstat - 1]);
1318 else
1319 rc = add_open_class(sn_.classes[read_class - 1].name + "_retrievalClass_" +
1320 std::to_string(i + 1));
1321 for (std::size_t s = 0; s < queue_nodes.size(); ++s) {
1322 set_service(queue_nodes[s], rc, svc[s]);
1323 // at most one retrieval of a given item is ever in flight
1324 set_class_capacity(queue_nodes[s], rc, 1.0);
1325 }
1326 // grow the retrieval_classes rows to the new class count and record
1327 for (std::size_t k = 0; k < nitems; ++k)
1328 cp.retrieval_classes[k].resize(sn_.classes.size(), 0);
1329 cp.retrieval_classes[i][read_class - 1] = rc;
1330 // The returning READ of a retrieval class reads ITS OWN item, and is
1331 // logged as the miss that started the fetch. Without these two the
1332 // state-based solvers see a class that reads nothing, so the fetch
1333 // never completes and the retrieval sub-network is never entered.
1334 const std::size_t K = sn_.classes.size();
1335 cp.pread.resize(K);
1336 cp.preadkind.resize(K);
1337 cp.hitclass.resize(K, 0);
1338 cp.missclass.resize(K, 0);
1339 std::vector<T> onehot(nitems, num_traits<T>::from_int(0));
1340 onehot[i] = num_traits<T>::from_int(1);
1341 cp.pread[rc - 1] = onehot;
1342 cp.missclass[rc - 1] = miss_class;
1343 }
1344 }
1345
1346 /** `Cache.setRetrievalSystem(readClass, missClass, queue)` with a single Queue, as the reference accepts. */
1347 void set_retrieval_system(std::size_t cache_node, std::size_t read_class, std::size_t miss_class,
1348 std::size_t queue_node) {
1349 set_retrieval_system(cache_node, read_class, miss_class, std::vector<std::size_t>(1, queue_node));
1350 }
1351
1352 /**
1353 * `queue.setItemServiceRate(cache, readClass, item, rate)` (Queue.m): override, at `queue_node`, the
1354 * retrieval service of one item of `read_class` with Exp(rate). `item` is 1-based. The default is the read
1355 * class's own service at that queue, copied by set_retrieval_system.
1356 */
1357 void set_item_service_rate(std::size_t queue_node, std::size_t cache_node, std::size_t read_class,
1358 std::size_t item, const T& rate) {
1359 set_service(queue_node, retrieval_class_of(cache_node, read_class, item), Distrib<T>::exp_rate(rate));
1360 }
1361
1362 /**
1363 * `Cache.setItemRoutingProbability(readClass, item, source, dest, p)`: the probability of routing the
1364 * retrieval class of `item` from `source_node` to `dest_node` (a retrieval queue or the cache itself).
1365 * Applied by link() after the read-class template, so it overrides that single edge; p = 0 deletes it.
1366 */
1367 void set_item_routing_probability(std::size_t cache_node, std::size_t read_class, std::size_t item,
1368 std::size_t source_node, std::size_t dest_node, const T& p) {
1369 const std::size_t rc = retrieval_class_of(cache_node, read_class, item);
1370 if (num_traits<T>::to_double(p) < 0) return; // addRetrievalRoutingEntry drops a negative probability
1371 retrieval_routing_entries_.push_back(RetrievalRoutingEntry(rc, source_node, dest_node, p));
1372 }
1373
1374 /** Short alias of set_item_routing_probability (Cache.setItemRoutingProb). */
1375 void set_item_routing_prob(std::size_t cache_node, std::size_t read_class, std::size_t item,
1376 std::size_t source_node, std::size_t dest_node, const T& p) {
1377 set_item_routing_probability(cache_node, read_class, item, source_node, dest_node, p);
1378 }
1379
1380 // -----------------------------------------------------------------------
1381 // Classes
1382 // -----------------------------------------------------------------------
1383
1384 /** A closed class of the given population, referencing a station node. */
1385 std::size_t add_closed_class(const std::string& nm, double njobs, std::size_t refstat_node,
1386 int prio = 0) {
1387 if (!(njobs >= 0.0) || std::isinf(njobs))
1388 throw InputError("ClosedClass '" + nm + "': the population must be finite");
1389 JobClass cl;
1390 cl.name = nm;
1391 cl.type = JobClassType::CLOSED;
1392 cl.population = njobs;
1393 cl.refstat = station_of(refstat_node, "ClosedClass '" + nm + "'");
1394 cl.prio = prio;
1395 const std::size_t r = sn_.add_class(cl);
1396 grow_class_vectors();
1397 return r;
1398 }
1399
1400 /**
1401 * An open class. Its reference station is the Source, which must exist:
1402 * an open class with no arrival station has no reference for its visits.
1403 */
1404 std::size_t add_open_class(const std::string& nm, int prio = 0) {
1405 if (sn_.sourceIdx == 0)
1406 throw InputError("OpenClass '" + nm +
1407 "': the model has no Source to reference; add one first");
1408 JobClass cl;
1409 cl.name = nm;
1410 cl.type = JobClassType::OPEN;
1411 cl.population = std::numeric_limits<double>::infinity();
1412 cl.refstat = sn_.sourceIdx;
1413 cl.prio = prio;
1414 const std::size_t r = sn_.add_class(cl);
1415 grow_class_vectors();
1416 return r;
1417 }
1418
1419 /**
1420 * `SelfLoopingClass(model, name, njobs, refstat, prio)`: a closed class
1421 * whose jobs perpetually cycle at their reference station.
1422 *
1423 * Built as a closed class because that is all it is -- the self-loop is in
1424 * the routing, and `SelfLoopingClass.m` adds no state -- with the subclass
1425 * recorded so the wire type survives a round trip.
1426 */
1427 std::size_t add_self_looping_class(const std::string& nm, double njobs,
1428 std::size_t refstat_node, int prio = 0) {
1429 const std::size_t r = add_closed_class(nm, njobs, refstat_node, prio);
1430 sn_.classes[r - 1].self_looping = true;
1431 return r;
1432 }
1433
1434 /** `JobClass.setReferenceClass(true)`: `sn.refclass(c)` picks this class. */
1435 void set_reference_class(std::size_t cls) {
1436 class_ref(cls, "set_reference_class").is_ref_class = true;
1437 }
1438
1439 /** `JobClass.deadline`: the soft deadline EDD, EDF and JMT's tardiness use. */
1440 void set_class_deadline(std::size_t cls, double due) {
1441 class_ref(cls, "set_class_deadline").deadline = due;
1442 }
1443
1444 /**
1445 * `JobClass.spawnClass` (`sn.classspawn`): the class injected at the same
1446 * station on every completion of `cls`.
1447 */
1448 void set_class_spawn(std::size_t cls, std::size_t spawn_cls) {
1449 const std::size_t K = sn_.classes.size();
1450 if (spawn_cls == 0 || spawn_cls > K)
1451 throw InputError("set_class_spawn: the spawned class index is out of range");
1452 class_ref(cls, "set_class_spawn").spawn = spawn_cls;
1453 }
1454
1455 /**
1456 * `JobClass.setPatience(kind, dist)`: the CLASS-WIDE abandonment law.
1457 *
1458 * The reference has no class-indexed patience in `sn`: `refreshStruct`
1459 * reads it through `Queue.getPatience`, which falls back to the class
1460 * setting wherever the station declares none, so the class-level law is
1461 * materialized onto every Queue and Delay here for exactly that reason.
1462 * A station-level `setPatience` therefore wins, as it does in MATLAB.
1463 */
1464 void set_class_patience(std::size_t cls, const Distrib<T>& dist,
1466 const std::size_t K = sn_.classes.size();
1467 if (cls == 0 || cls > K) throw InputError("set_class_patience: class index out of range");
1469 if (kind == lang::ImpatienceType::RENEGING && std::isfinite(sn_.classes[cls - 1].population))
1470 closed_reneging_refusal(sn_.classes[cls - 1].name, "");
1471 for (std::size_t ist = 0; ist < sn_.stations.size(); ++ist) {
1472 const std::size_t ind = sn_.station_to_node[ist];
1473 const lang::NodeType nt = sn_.nodes[ind - 1].nodetype;
1474 if (nt != lang::NodeType::Queue && nt != lang::NodeType::Delay) continue;
1475 Station<T>& st = sn_.stations[ist];
1476 grow_class_slot(st.patience, cls, Distrib<T>::disabled_dist());
1477 grow_class_slot(st.impatience, cls, lang::ImpatienceType::NONE);
1478 if (!st.patience[cls - 1].disabled) continue; // the station setting wins
1479 st.patience[cls - 1] = dist;
1480 st.impatience[cls - 1] = kind;
1481 }
1482 }
1483
1484 /**
1485 * `JobClass.setReplySignalClass(reply)` (`sn.syncreply`), plus the
1486 * `sn.replyblock` the state layer needs.
1487 *
1488 * The reference derives the block rather than being told it
1489 * (`refreshLocalVars.m:340-386`): a server is held at every non-Source,
1490 * non-INF station the REPLY class can be routed INTO, and every such
1491 * station must be FCFS because a held server is encoded as a per-class
1492 * counter. That derivation needs the routing, so it runs in `finalize()`;
1493 * this only records the binding.
1494 */
1495 void set_reply_signal_class(std::size_t call_cls, std::size_t reply_cls) {
1496 const std::size_t K = sn_.classes.size();
1497 if (call_cls == 0 || call_cls > K || reply_cls == 0 || reply_cls > K)
1498 throw InputError("set_reply_signal_class: class index is out of range");
1499 // resize, not assign: a class added since the last binding must not erase the earlier bindings
1500 if (sn_.syncreply.size() < K) sn_.syncreply.resize(K, 0);
1501 sn_.syncreply[call_cls - 1] = reply_cls;
1503 }
1504
1505 // -----------------------------------------------------------------------
1506 // Station parameters
1507 // -----------------------------------------------------------------------
1508
1509 /**
1510 * MATLAB `setPatience`: a Defective patience (never abandons w.p. pInf) is
1511 * refused by name with `LINE:unsupported:Reneging`.
1512 */
1515 throw UnsupportedError(ErrorKind{"Reneging"},
1516 "Defective patience is not supported: the law never fires with probability "
1517 "pInf, and no solver models an infinite patience. Give the patient fraction its "
1518 "own class without patience, or set the inner law as the patience.");
1519 }
1520
1521 /**
1522 * MATLAB `Queue.setService` / `Source.setArrival`: a Defective law has an
1523 * infinite mean, so it is refused at the station with `LINE:input:Argument`.
1524 */
1525 static void refuse_defective(const Distrib<T>& d, const char* what) {
1527 throw InputError(ErrorKind{"Argument"},
1528 std::string("A Defective law is infinite with probability pInf, so its mean is Inf "
1529 "and it cannot be a ") + what + " time. Use it as a lifetime or failure "
1530 "law, or MassAtOrigin for an atom at zero.");
1531 }
1532
1533 /**
1534 * `station.setService(class, dist)`.
1535 *
1536 * A Prior gets its MIXTURE moments here, where a Markovian family gets the
1537 * moments of its (D0,D1): both are the "what does the struct report before
1538 * anything solves" question, and leaving a Prior at mean 0 would make a
1539 * struct dump read as an Immediate.
1540 */
1541 void set_service(std::size_t node, std::size_t cls, const Distrib<T>& d) {
1542 refuse_defective(d, "service");
1543 Distrib<T> dd = d;
1544 if (dd.is_prior())
1546 else
1548 sn_.set_service(station_of(node, "setService"), cls, dd);
1549 }
1550
1551 /** `source.setArrival(class, dist)`: the same table, at the Source. */
1552 void set_arrival(std::size_t node, std::size_t cls, const Distrib<T>& d) {
1553 const std::size_t ist = station_of(node, "setArrival");
1554 if (sn_.stations[ist - 1].nodetype != NodeType::Source)
1555 throw InputError("setArrival: node '" + sn_.nodes[node - 1].name + "' is not a Source");
1556 refuse_defective(d, "interarrival");
1557 Distrib<T> dd = d;
1558 if (dd.is_prior())
1560 else
1562 sn_.set_service(ist, cls, dd);
1563 }
1564
1565 /**
1566 * `queue.setNumberOfServers(n)`.
1567 *
1568 * IT IS A NO-OP ON AN INF-SCHEDULED STATION, which is what MATLAB does: the
1569 * method switches on the discipline and ignores the request for
1570 * SchedStrategy.INF. Lowering the multiplicity onto the station instead
1571 * looks harmless and is not -- utilization at a finite-server station is
1572 * divided by the server count, so an inf-scheduled station would report a
1573 * utilization a factor `n` too small.
1574 */
1575 void set_number_of_servers(std::size_t node, double n) {
1576 const std::size_t ist = station_of(node, "setNumberOfServers");
1577 if (sn_.stations[ist - 1].sched == SchedStrategy::INF) return;
1578 // ZERO IS A COUNT, as in the reference: a station that never completes a
1579 // job, whose visiting closed chains `sn_zero_capacity` parks there.
1580 if (!(n >= 0.0)) throw InputError("setNumberOfServers: the server count must be >= 0");
1581 sn_.stations[ist - 1].nservers = n;
1582 // getNodeTypes reads the COUNT: a queue given infinitely many servers is
1583 // reported as a Delay station, which is the field the analyzers partition on
1584 if (std::isinf(n) && sn_.stations[ist - 1].nodetype == NodeType::Queue)
1585 sn_.stations[ist - 1].nodetype = NodeType::Delay;
1586 }
1587
1588 /** `station.setCapacity(k)`, the K of Kendall's notation. */
1589 void set_capacity(std::size_t node, double k) {
1590 sn_.stations[station_of(node, "setCapacity") - 1].cap = k;
1591 }
1592
1593 /** `station.setChainCapacity(class, k)`. */
1594 void set_class_capacity(std::size_t node, std::size_t cls, double k) {
1595 Station<T>& st = sn_.stations[station_of(node, "setChainCapacity") - 1];
1596 st.classcap.resize(sn_.classes.size(), std::numeric_limits<double>::infinity());
1597 st.classcap[cls - 1] = k;
1598 }
1599
1600 /**
1601 * `queue.setImmediateFeedback(class)`: a completing job of that class is fed
1602 * straight back into service, HOLDING THE SERVER, rather than being routed
1603 * out and re-queued.
1604 *
1605 * Node-scoped. `set_class_immediate_feedback` is the class-wide spelling;
1606 * `sn.immfeed` is the OR of the two, as `refreshStruct` computes it.
1607 */
1608 void set_immediate_feedback(std::size_t node, std::size_t cls) {
1609 Station<T>& st = sn_.stations[station_of(node, "setImmediateFeedback") - 1];
1610 st.immfeed.resize(sn_.classes.size(), false);
1611 st.immfeed[cls - 1] = true;
1612 }
1613
1614 /** `jobclass.setImmediateFeedback()`: the same property, class-wide. */
1615 void set_class_immediate_feedback(std::size_t cls) {
1616 sn_.classes[cls - 1].immfeed = true;
1617 }
1618
1619 /** `station.setDropRule(class, rule)`. */
1620 void set_drop_rule(std::size_t node, std::size_t cls, DropStrategy rule) {
1621 Station<T>& st = sn_.stations[station_of(node, "setDropRule") - 1];
1622 st.droprule.resize(sn_.classes.size(), 0);
1623 st.droprule[cls - 1] = static_cast<int>(rule);
1624 }
1625
1626 /**
1627 * `Queue.setServiceRateFunction(muFun)`: the TOTAL service rate of a PAS or
1628 * OI station as a function of the ordered microstate, a 1-based list of
1629 * class indices in queue order.
1630 *
1631 * Only PAS and OI take one, and the reference errors on any other
1632 * discipline. As `Queue.setServiceRateFunction` does, this ALSO installs a
1633 * representative per-class service distribution `Exp(mu([r]))`, so that the
1634 * ordinary rate/procid machinery stays consistent; the authoritative
1635 * description of the station remains mu(c). A class whose mu([r]) is not
1636 * positive and finite is disabled there, again as the reference does.
1637 *
1638 * `swap_graph` is `sn.nodeparam{ind}.swapGraph`, empty (all zero) for a
1639 * genuinely order-independent station.
1640 */
1642 std::size_t node, const std::function<T(const std::vector<std::size_t>&)>& muFun,
1643 const Matrix<T>& swap_graph = Matrix<T>()) {
1644 const std::size_t ist = station_of(node, "setServiceRateFunction");
1645 Station<T>& st = sn_.stations[ist - 1];
1646 if (st.sched != SchedStrategy::PAS && st.sched != SchedStrategy::OI)
1647 throw InputError(
1648 "setServiceRateFunction is only applicable to PAS (pass-and-swap) and OI "
1649 "(order-independent) queues");
1650 if (!muFun) throw InputError("setServiceRateFunction: the rate function is empty");
1651 st.svc_rate_fun = muFun;
1652 st.swap_graph = swap_graph;
1653 // ONE DECLARATION, TWO READERS. `solver_nc_oi` and `solver_mva_oi` read
1654 // the rate function off the Station; `to_marginal`, the PAS event
1655 // handler and the JSON writer read it off `sn.pasparam`. Filling only
1656 // one left the other with no rate function AND no error: a model built
1657 // here fell back to "every job present is in service" in every
1658 // state-space consumer, and a model loaded from JSON (which fills
1659 // `pasparam` alone, via `set_pas`) was refused by the OI solvers.
1660 pas_mirror(ist, muFun, swap_graph);
1661 for (std::size_t r = 1; r <= sn_.classes.size(); ++r) {
1662 const T rate_r = muFun(std::vector<std::size_t>{r});
1663 const double v = num_traits<T>::to_double(rate_r);
1664 set_service(node, r, (std::isfinite(v) && v > 0.0) ? Distrib<T>::exp_rate(rate_r)
1666 }
1667 }
1668
1669 /**
1670 * `Queue.setPollingType(rule, par)`: the polling discipline of a POLLING
1671 * station, identical across all class buffers as the reference assumes. Only
1672 * K-limited and G-limited carry a parameter; every other rule ignores it.
1673 */
1674 void set_polling_type(std::size_t node, lang::PollingType rule, int par = 0) {
1675 Station<T>& st = sn_.stations[station_of(node, "setPollingType") - 1];
1676 if (st.sched != SchedStrategy::POLLING)
1677 throw InputError("setPollingType is only applicable to a POLLING station");
1678 const bool limited = rule == lang::PollingType::KLIMITED || rule == lang::PollingType::GLIMITED;
1679 if (limited && par < 1)
1681 ? "K-limited polling requires a parameter K >= 1"
1682 : "G-limited polling requires a parameter K >= 1");
1683 st.polling_type.assign(sn_.classes.size(), rule);
1684 st.polling_par = limited ? par : 0;
1685 }
1686
1687 /**
1688 * `Queue.setPollingTable(table, swlegs)`: the visit sequence of a POLLING
1689 * station (1-based classes, repeats allowed) and, optionally, the walk out
1690 * of each table position (a disabled entry falls back to the class
1691 * switchover of that entry). Refused with a load-dependent order.
1692 */
1693 void set_polling_table(std::size_t node, const std::vector<std::size_t>& table,
1694 const std::vector<Distrib<T>>& swlegs = std::vector<Distrib<T>>()) {
1695 Station<T>& st = sn_.stations[station_of(node, "setPollingTable") - 1];
1696 if (st.sched != SchedStrategy::POLLING)
1697 throw InputError(ErrorKind{"Model"},
1698 "setPollingTable can only be invoked on queues with SchedStrategy.POLLING.");
1699 const std::size_t R = sn_.classes.size();
1700 if (table.empty())
1701 throw InputError(ErrorKind{"Argument"}, "The polling table must list class indices between 1 and " +
1702 std::to_string(R) + ".");
1703 for (std::size_t c : table)
1704 if (c < 1 || c > R)
1705 throw InputError(ErrorKind{"Argument"},
1706 "The polling table must list class indices between 1 and " +
1707 std::to_string(R) + ".");
1709 throw InputError(ErrorKind{"Model"},
1710 "A polling table cannot be combined with a load-dependent polling order.");
1711 if (!swlegs.empty() && swlegs.size() != table.size())
1712 throw InputError(ErrorKind{"Argument"},
1713 "setPollingTable needs one switchover entry per table position (" +
1714 std::to_string(table.size()) + ").");
1715 st.polling_table = table;
1716 st.polling_table_sw = swlegs;
1717 st.polling_table_sw.resize(table.size(), Distrib<T>::disabled_dist());
1718 }
1719
1720 /**
1721 * `Queue.setPollingOrder(order, prioclass, L)`: the visit-order rule. Under
1722 * THRESHOLD the server goes to `prioclass` (1-based) whenever its buffer
1723 * holds more than `threshold` jobs at a visit end, else SKIPEMPTY.
1724 */
1725 void set_polling_order(std::size_t node, lang::PollingOrder order, std::size_t prioclass = 0,
1726 long threshold = -1) {
1727 Station<T>& st = sn_.stations[station_of(node, "setPollingOrder") - 1];
1728 if (st.sched != SchedStrategy::POLLING)
1729 throw InputError(ErrorKind{"Model"},
1730 "setPollingOrder can only be invoked on queues with SchedStrategy.POLLING.");
1731 if (order != lang::PollingOrder::CYCLIC && !st.polling_table.empty())
1732 throw InputError(ErrorKind{"Model"},
1733 "A load-dependent polling order cannot be combined with a polling table.");
1734 st.polling_order_class = 0;
1736 if (order == lang::PollingOrder::THRESHOLD) {
1737 if (prioclass == 0)
1738 throw InputError(ErrorKind{"Argument"},
1739 "The THRESHOLD polling order needs the priority class and the threshold L.");
1740 if (threshold < 0)
1741 throw InputError(ErrorKind{"Argument"}, "The polling threshold L must be a non-negative integer.");
1742 st.polling_order_class = prioclass;
1743 st.polling_order_threshold = threshold;
1744 }
1745 st.polling_order = order;
1746 }
1747
1748 /**
1749 * `Queue.setPollingTimer(dist, scope, preemptive)`: a visit timer per class
1750 * (one law for all classes, or one per class). NONE clears it.
1751 */
1752 void set_polling_timer(std::size_t node, const std::vector<Distrib<T>>& dists,
1753 lang::PollingTimer scope = lang::PollingTimer::LOCAL, bool preemptive = false) {
1754 Station<T>& st = sn_.stations[station_of(node, "setPollingTimer") - 1];
1755 if (st.sched != SchedStrategy::POLLING)
1756 throw InputError(ErrorKind{"Model"},
1757 "setPollingTimer can only be invoked on queues with SchedStrategy.POLLING.");
1758 const std::size_t R = sn_.classes.size();
1759 std::vector<Distrib<T>> tl;
1760 if (dists.size() == 1)
1761 tl.assign(R, dists[0]);
1762 else if (dists.size() == R)
1763 tl = dists;
1764 else
1765 throw InputError(ErrorKind{"Argument"},
1766 "setPollingTimer needs one distribution per class (" + std::to_string(R) + ").");
1767 if (scope == lang::PollingTimer::NONE) tl.clear();
1768 for (const Distrib<T>& d : tl)
1769 if (d.disabled || d.type == lang::ProcessType::IMMEDIATE || d.type == lang::ProcessType::DISABLED)
1770 throw InputError(ErrorKind{"Argument"}, "A polling timer must be a strictly positive distribution.");
1771 st.polling_timer = tl;
1772 st.polling_timer_scope = scope;
1773 st.polling_timer_preempt = preemptive;
1774 }
1775
1776 /** `Queue.setSwitchover(jobclass, distrib)`: the switchover time of a class. */
1777 void set_switchover(std::size_t node, std::size_t cls, const Distrib<T>& so) {
1778 Station<T>& st = sn_.stations[station_of(node, "setSwitchover") - 1];
1779 if (st.sched != SchedStrategy::POLLING)
1780 throw InputError("setSwitchover is only applicable to a POLLING station");
1781 st.switchover.resize(sn_.classes.size(), Distrib<T>::immediate());
1782 st.switchover[cls - 1] = so;
1783 }
1784
1785 /**
1786 * `Queue.setSwitchover(fromClass, toClass, distrib)`: the walk between two
1787 * CLASSES at an ordinary station, the reference's (K x K) form.
1788 *
1789 * An UNDECLARED pair stays Disabled and is therefore not serialized, which
1790 * is what the JAR and python write. MATLAB fills its cell with Immediate
1791 * instead and writes all K^2 entries; the two mean the same thing, since no
1792 * solver reads a pairwise switchover, and the sparse form is the one that
1793 * round-trips a document unchanged.
1794 *
1795 * Refused at a POLLING station, where a switchover is the walk out of one
1796 * BUFFER and is declared per class by the overload above. MATLAB, the JAR
1797 * and python refuse it there too: each used to accept it and read back a
1798 * different leg.
1799 */
1800 void set_switchover(std::size_t node, std::size_t from_cls, std::size_t to_cls,
1801 const Distrib<T>& so) {
1802 Station<T>& st = sn_.stations[station_of(node, "setSwitchover") - 1];
1803 if (st.sched == SchedStrategy::POLLING)
1804 throw InputError(
1805 "setSwitchover(fromClass, toClass, distrib) is not applicable to a POLLING "
1806 "station, whose switchover is the walk out of one buffer and is declared per "
1807 "class");
1808 const std::size_t K = sn_.classes.size();
1809 if (from_cls == 0 || from_cls > K || to_cls == 0 || to_cls > K)
1810 throw InputError("setSwitchover: class index is out of range");
1811 if (st.switchover_pair.empty())
1812 st.switchover_pair.assign(K, std::vector<Distrib<T>>(K, Distrib<T>::disabled_dist()));
1813 st.switchover_pair[from_cls - 1][to_cls - 1] = so;
1814 }
1815
1816 /**
1817 * `Queue.setQuantum(jobclass, distrib)`: the time slice of a class at a
1818 * round-robin station. Refused at any other station and for a Disabled or
1819 * Immediate law, as MATLAB refuses them (LINE:input:Argument). A Det
1820 * quantum is accepted here and refused by the state-space solvers, which
1821 * need a phase-type slice.
1822 */
1823 void set_quantum(std::size_t node, std::size_t cls, const Distrib<T>& q) {
1824 Station<T>& st = sn_.stations[station_of(node, "setQuantum") - 1];
1825 if (st.sched != SchedStrategy::RR)
1826 throw InputError(ErrorKind{"Argument"}, "setQuantum can only be invoked on queues with SchedStrategy.RR.");
1828 throw InputError(ErrorKind{"Argument"},
1829 "The RR quantum must be a non-degenerate time distribution (Exp, Erlang, "
1830 "HyperExp, APH, Coxian, PH, or Det for simulation).");
1831 const std::size_t K = sn_.classes.size();
1832 if (cls == 0 || cls > K) throw InputError(ErrorKind{"Argument"}, "setQuantum: class index is out of range");
1833 Distrib<T> qq = q;
1835 if (st.quantum.size() < K) st.quantum.resize(K, Distrib<T>::disabled_dist());
1836 st.quantum[cls - 1] = qq;
1837 }
1838
1839 /** `Queue.setQuantum(distrib)`: the same time slice for every class. */
1840 void set_quantum(std::size_t node, const Distrib<T>& q) {
1841 for (std::size_t r = 1; r <= sn_.classes.size(); ++r) set_quantum(node, r, q);
1842 }
1843
1844 /** The DPS / GPS weight of a class at a station. */
1845 void set_sched_param(std::size_t node, std::size_t cls, const T& weight) {
1846 Station<T>& st = sn_.stations[station_of(node, "setSchedParam") - 1];
1847 st.schedparam.resize(sn_.classes.size(), num_traits<T>::from_int(1));
1848 st.schedparam[cls - 1] = weight;
1849 }
1850
1851 /**
1852 * `station.setLoadDependence(alpha)`: the rate multiplier at population
1853 * 1, 2, ... The vector is indexed from population one, as `sn.lldscaling`
1854 * is, so entry 0 is the multiplier of a station holding one job.
1855 */
1856 void set_load_dependence(std::size_t node, const std::vector<T>& alpha) {
1857 // `Queue.setLoadDependence` admits PS, DPS and FCFS only and refuses
1858 // every other discipline by name, in the reference and in the JAR. This
1859 // port accepted any station, so a model the reference refuses to BUILD
1860 // (a load-dependent SIRO, LCFS, HOL or INF station) was solved here.
1861 const lang::SchedStrategy sched =
1862 sn_.stations[station_of(node, "setLoadDependence") - 1].sched;
1863 if (sched != lang::SchedStrategy::PS && sched != lang::SchedStrategy::DPS &&
1865 throw UnsupportedError(ErrorKind{"LoadDependence"},
1866 "Load-dependence supported only for processor sharing (PS), discriminatory "
1867 "processor sharing (DPS) and first-come first-serve (FCFS) stations.");
1868 set_limited_load_dependence(node, alpha);
1869 }
1870
1871 /**
1872 * `Station.setLimitedLoadDependence(alpha)`: the same setter with no
1873 * discipline gate. It is what a model TRANSFORMATION calls (the FES
1874 * aggregation builds stations the user-facing gate would refuse), exactly
1875 * as `aggregateFES.m` and the LN layer builder do in the reference.
1876 */
1877 void set_limited_load_dependence(std::size_t node, const std::vector<T>& alpha) {
1878 if (alpha.empty()) throw InputError("setLoadDependence: the scaling vector is empty");
1879 sn_.stations[station_of(node, "setLoadDependence") - 1].lldscaling = alpha;
1880 }
1881
1882 /**
1883 * `station.setClassDependence(beta, peakRatePerClass)`.
1884 *
1885 * The peak is a scalar broadcast across the classes, or one value per class;
1886 * it is the declared max_n beta_r(n) that utilization is normalized by, and
1887 * the reference makes it mandatory because it cannot be recovered from beta
1888 * without sweeping the whole lattice -- a sweep that needs a bound the
1889 * handle does not carry, and an open class has none.
1890 *
1891 * An empty peak is accepted HERE and refused where it is READ, matching
1892 * `getLimitedClassDependencePeak`. That contract is only worth anything if
1893 * every reader honours it, and they do: SolverCTMC, `solver_mva_run_analyzer`,
1894 * `solver_nc_conv`, both SSA engines and the LDES engine each throw by name.
1895 * SolverMVA was the exception until 2026-08-19, silently writing a column of
1896 * ZEROS into U instead. `set_joint_dependence` below takes the peak as a
1897 * REQUIRED argument and refuses at declaration; both shapes end in an error.
1898 */
1899 void set_class_dependence(std::size_t node, const CdScaling<T>& fun,
1900 const std::vector<T>& peak = std::vector<T>()) {
1901 Station<T>& st = sn_.stations[station_of(node, "setClassDependence") - 1];
1902 const std::size_t K = sn_.classes.size();
1903 st.cdscaling = fun;
1904 if (peak.empty())
1905 st.cdscalingpeak.clear();
1906 else if (peak.size() == 1)
1907 st.cdscalingpeak.assign(K, peak[0]);
1908 else if (peak.size() == K)
1909 st.cdscalingpeak = peak;
1910 else
1911 throw InputError(
1912 "setClassDependence: peakRatePerClass must be a scalar or a vector of length "
1913 "nclasses");
1914 }
1915
1916 /**
1917 * `station.setJointDependence(eta, peakRatePerClass)`: MATLAB's
1918 * `Station.ljdScaling` / `ljdScalingPeak`.
1919 *
1920 * The peak is MANDATORY, exactly as in `Station.setJointDependence`, and for
1921 * the same reason as `setClassDependence`: utilization at a dependent station
1922 * is reported as T*S/peak, and max_n eta_i(n) is not recoverable from the
1923 * handle without sweeping the whole lattice.
1924 */
1925 void set_joint_dependence(std::size_t node, const CdScaling<T>& fun,
1926 const std::vector<T>& peak) {
1927 Station<T>& st = sn_.stations[station_of(node, "setJointDependence") - 1];
1928 const std::size_t K = sn_.classes.size();
1929 if (peak.empty())
1930 throw InputError(
1931 "setJointDependence: joint dependence requires an explicit peak rate; pass a "
1932 "scalar (identical peak for every class) or a per-class vector");
1933 st.jdscaling = fun;
1934 if (peak.size() == 1)
1935 st.jdscalingpeak.assign(K, peak[0]);
1936 else if (peak.size() == K)
1937 st.jdscalingpeak = peak;
1938 else
1939 throw InputError(
1940 "setJointDependence: peakRatePerClass must be a scalar or a vector of length "
1941 "nclasses");
1942 }
1943
1944 /**
1945 * `model.setGlobalDependence(phi, peak)`: MATLAB's `Network.gdScaling`.
1946 *
1947 * Declares a globally state-dependent rate scaling phi(n) whose argument is
1948 * the FULL (nstations x nclasses) population matrix, row-major, rather than
1949 * one station's slice. This is the Whittle primitive: when phi satisfies
1950 * phi_s(n) phi_t(n-e_s) = phi_t(n) phi_s(n-e_t) the chain is reversible with
1951 * pi(n) ~ Phi(n) prod rho_s^n_s and is insensitive; it also expresses
1952 * bandwidth sharing, where a route holds several links at once.
1953 *
1954 * phi returns one scalar (broadcast), one entry per station, or one entry per
1955 * (station, class) in row-major order. The peak is MANDATORY for the same
1956 * reason as `set_class_dependence`: utilization is reported as T*S/peak, at
1957 * EVERY station once a handle is present, the delays among them.
1958 * Only SolverCTMC, SolverSSA and SolverLDES honour the handle.
1959 */
1960 void set_global_dependence(const GdScaling<T>& fun, const std::vector<T>& peak) {
1961 set_global_dependence(fun, peak, 10);
1962 }
1963
1964 /**
1965 * As above, with an explicit per-slot OPEN-class truncation used when phi is
1966 * materialized onto the JSON wire (closed classes are tabulated up to their own
1967 * population). It plays no part in solving, and exists because a handle cannot
1968 * cross a language boundary: the writer needs to know how far the lattice
1969 * extends. Set it to the cutoff the model is solved at.
1970 */
1971 void set_global_dependence(const GdScaling<T>& fun, const std::vector<T>& peak,
1972 int wire_cutoff) {
1973 if (!fun)
1974 throw InputError("setGlobalDependence: the scaling must be a callable");
1975 const std::size_t M = sn_.stations.size(), K = sn_.classes.size();
1976 if (peak.empty())
1977 throw InputError(
1978 "setGlobalDependence: a global dependence requires an explicit peak rate; pass a "
1979 "scalar, one entry per station, or one entry per (station, class)");
1980 for (std::size_t i = 0; i < peak.size(); ++i)
1981 if (num_traits<T>::to_double(peak[i]) <= 0)
1982 throw InputError("setGlobalDependence: peak must be positive");
1983 // Probe now so a wrong output shape is refused at declaration time rather
1984 // than midway through state-space generation.
1985 for (int probe = 0; probe < 2; ++probe) {
1986 const std::vector<T> n(M * K, num_traits<T>::from_int(probe));
1987 const std::vector<T> v = fun(n);
1988 if (v.size() != 1 && v.size() != M && v.size() != M * K)
1989 throw InputError(
1990 "setGlobalDependence: the handle must return a scalar, one entry per station, "
1991 "or one entry per (station, class)");
1992 for (std::size_t j = 0; j < v.size(); ++j)
1993 if (!(num_traits<T>::to_double(v[j]) >= 0))
1994 throw InputError(
1995 "setGlobalDependence: the handle must return finite nonnegative scalings");
1996 }
1997 if (wire_cutoff < 1)
1998 throw InputError("setGlobalDependence: wireCutoff must be a positive integer");
1999 sn_.gdscaling = fun;
2000 sn_.gdscalingcutoff = wire_cutoff;
2001 if (peak.size() == 1)
2002 sn_.gdscalingpeak.assign(M * K, peak[0]);
2003 else if (peak.size() == M) {
2004 sn_.gdscalingpeak.assign(M * K, num_traits<T>::from_int(1));
2005 for (std::size_t i = 0; i < M; ++i)
2006 for (std::size_t r = 0; r < K; ++r) sn_.gdscalingpeak[i * K + r] = peak[i];
2007 } else if (peak.size() == M * K)
2008 sn_.gdscalingpeak = peak;
2009 else
2010 throw InputError(
2011 "setGlobalDependence: peak must be a scalar, one entry per station, or one entry "
2012 "per (station, class)");
2013 }
2014
2015 /** `node.setRouting(class, strategy)`. */
2016 void set_routing(std::size_t node, std::size_t cls, RoutingStrategy rs) {
2017 NodeDef& nd = sn_.nodes[node - 1];
2018 nd.routing.resize(sn_.classes.size(), RoutingStrategy::PROB);
2019 nd.routing[cls - 1] = rs;
2020 }
2021
2022 /** `jobclass.completes = flag`: whether a passage through the reference station counts as a completion. */
2023 void set_class_completes(std::size_t cls, bool flag) { sn_.classes[cls - 1].completes = flag; }
2024
2025 /**
2026 * `node.setStateDepRouting(class, departure, branches, level, C, d)`.
2027 *
2028 * Declares `entry` the entry centre e of a subnetwork Q(V,V) served by the
2029 * product-form state-dependent routing of A. E. Krzesinski, "Multiclass
2030 * Queueing Networks with State-Dependent Routing", Performance Evaluation
2031 * 7(2):125-143, 1987.
2032 *
2033 * All node indices are 1-based, as elsewhere in the builder. `departure`
2034 * may equal `entry` in a central server model. `branches` follows the
2035 * paper's own indexing: `branches[0]` must be empty because branch index 1
2036 * denotes the complement M-V, and `branches[b]` lists the nodes of branch b
2037 * with its entry centre first and its departure centre last. `level[b]` is
2038 * the index t of the subnetwork with B_b in V_t - V_{t+1}, and `level[0]`
2039 * is ignored. `C` holds the T coefficients C_t and `d` the T by B
2040 * coefficients d_tb, read for 1 <= t <= level[b].
2041 *
2042 * Negative C_t and positive d_tb make the routing prefer the least
2043 * congested branches and impose the population bounds m_b <= d_tb/(-C_t)
2044 * and v_t <= D_tt/(-C_t). The residual probability returns the customer to
2045 * the departure centre, the busy form of waiting of Sec. 2.5, so the entry
2046 * node needs a self-loop when entry and departure coincide.
2047 */
2048 void set_state_dep_routing(std::size_t entry, std::size_t departure,
2049 const std::vector<std::vector<std::size_t>>& branches,
2050 const std::vector<std::size_t>& level,
2051 const std::vector<double>& C, const Matrix<double>& d,
2052 std::size_t cls = 0) {
2053 if (branches.size() < 2 || !branches[0].empty())
2054 throw InputError("set_state_dep_routing: branches[0] must be empty, branch index 1 "
2055 "denotes the complement M-V");
2056 const std::size_t B = branches.size();
2057 if (level.size() != B)
2058 throw InputError("set_state_dep_routing: level must have one entry per branch index, "
2059 "including the unused index 0");
2060 pfqn::SdrStruct nodesdr;
2061 nodesdr.entry = entry - 1;
2062 nodesdr.departure = departure - 1;
2063 nodesdr.branch.assign(B, std::vector<std::size_t>());
2064 nodesdr.entryOf.assign(B, 0);
2065 nodesdr.departureOf.assign(B, 0);
2066 for (std::size_t b = 1; b < B; ++b) {
2067 if (branches[b].empty())
2068 throw InputError("set_state_dep_routing: branch " + std::to_string(b + 1) +
2069 " is empty");
2070 for (std::size_t k = 0; k < branches[b].size(); ++k)
2071 nodesdr.branch[b].push_back(branches[b][k] - 1);
2072 nodesdr.entryOf[b] = branches[b].front() - 1;
2073 nodesdr.departureOf[b] = branches[b].back() - 1;
2074 }
2075 nodesdr.level = level;
2076 nodesdr.C = C;
2077 nodesdr.d = d;
2078
2079 // Station-indexed twin. Every centre of an SDR network must be a
2080 // station: the product form is over queue lengths, and a stateless node
2081 // holds none.
2082 std::vector<std::size_t> node_to_station(sn_.nodes.size(), 0);
2083 std::vector<bool> is_station(sn_.nodes.size(), false);
2084 for (std::size_t k = 0; k < sn_.station_to_node.size(); ++k) {
2085 node_to_station[sn_.station_to_node[k] - 1] = k;
2086 is_station[sn_.station_to_node[k] - 1] = true;
2087 }
2088 struct Map {
2089 const std::vector<std::size_t>& n2s;
2090 const std::vector<bool>& isst;
2091 const NetworkStruct<T>& sn;
2092 std::size_t operator()(std::size_t nd) const {
2093 if (nd >= isst.size() || !isst[nd])
2094 throw InputError("set_state_dep_routing: node '" + sn.nodes[nd].name +
2095 "' takes part in state-dependent routing but is not a "
2096 "station: the product form is over queue lengths, and a "
2097 "stateless node holds none");
2098 return n2s[nd];
2099 }
2100 } to_station{node_to_station, is_station, sn_};
2101
2102 pfqn::SdrStruct stsdr = nodesdr;
2103 stsdr.entry = to_station(nodesdr.entry);
2104 stsdr.departure = to_station(nodesdr.departure);
2105 for (std::size_t b = 1; b < B; ++b) {
2106 for (std::size_t k = 0; k < nodesdr.branch[b].size(); ++k)
2107 stsdr.branch[b][k] = to_station(nodesdr.branch[b][k]);
2108 stsdr.entryOf[b] = to_station(nodesdr.entryOf[b]);
2109 stsdr.departureOf[b] = to_station(nodesdr.departureOf[b]);
2110 }
2111 pfqn::pfqn_sdrcoeff(stsdr); // validates the declaration and its population bounds
2112
2113 sn_.sdr_nodes = nodesdr;
2114 sn_.sdr = stsdr;
2115 const std::size_t K = sn_.classes.size();
2116 if (cls == 0) {
2117 for (std::size_t r = 1; r <= K; ++r) set_routing(entry, r, RoutingStrategy::SDR);
2118 } else {
2119 set_routing(entry, cls, RoutingStrategy::SDR);
2120 }
2121 }
2122
2123 // Routing
2124
2125 /** An empty routing matrix, MATLAB's `model.initRoutingMatrix`. */
2127
2128 /**
2129 * `model.serialRouting(nodes)`: a unit-probability path through `nodes`.
2130 *
2131 * A path ending at a Sink stays open. Every other path is closed back onto
2132 * its first node, matching MATLAB's `Network.serialRouting` convention for
2133 * closed models. The returned matrix is a one-class topology block and can
2134 * be passed directly to `link`, or assigned to a class with `P.set(cls, block)`.
2135 */
2136 RoutingMatrix<T> serial_routing(const std::vector<std::size_t>& nodes) const {
2138 for (std::size_t k = 0; k < nodes.size(); ++k) {
2139 if (nodes[k] == 0 || nodes[k] > sn_.nodes.size())
2140 throw InputError("serialRouting: the path names a node that does not exist");
2141 if (k + 1 < nodes.size()) P.set(nodes[k], nodes[k + 1], num_traits<T>::from_int(1));
2142 }
2143 if (nodes.size() > 1 && sn_.nodes[nodes.back() - 1].nodetype != NodeType::Sink)
2144 P.set(nodes.back(), nodes.front(), num_traits<T>::from_int(1));
2145 return P;
2146 }
2147
2148 /**
2149 * `model.link(P)`: install the routing.
2150 *
2151 * The probabilities are stored as given. A node whose strategy is RAND
2152 * needs only the CONNECTIONS -- any positive entry marks one -- and the
2153 * refresh replaces them by the uniform split.
2154 */
2155 void link(const RoutingMatrix<T>& Pm) {
2156 for (const auto& kv : Pm.entries) {
2157 const auto& k = kv.first;
2158 if (k.r == 0 || k.r > sn_.classes.size() || k.s == 0 || k.s > sn_.classes.size())
2159 throw InputError("link: the routing matrix names a class that does not exist");
2160 if (k.i == 0 || k.i > sn_.nodes.size() || k.j == 0 || k.j > sn_.nodes.size())
2161 throw InputError("link: the routing matrix names a node that does not exist");
2162 }
2163 // A CLASS SWITCH ON A LINK BECOMES A NODE, as `@MNetwork/link.m:225-329`
2164 // makes it. This port used to keep `P{r,s}(i,j)` with r != s as an EDGE
2165 // attribute and synthesize nothing, which the analytical solvers read
2166 // correctly through route_eff but which cost two things nothing else
2167 // could supply: the node table had no CS_ row to report (a node the
2168 // reference counts, so cache_replc_fifo showed 2 nodes against 3), and
2169 // the JSIM export had nowhere to put the switch at all -- `jmt_writer.h`
2170 // can only emit a ClassSwitch for a node whose type IS ClassSwitch, so
2171 // JMT silently simulated the UNSWITCHED model.
2172 //
2173 // The rewrite makes every surviving route SAME-CLASS; the switching
2174 // lives entirely in the inserted node's matrix.
2175 const std::size_t K = sn_.classes.size();
2176 const std::size_t I = sn_.nodes.size(); // before any insertion
2177 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
2178 RoutingMatrix<T> P = Pm;
2179 // Deferred miss hops from Cache.setMissCache. They are part of the cache
2180 // network's own construction, and the per-item classes they carry do not
2181 // exist when the caller builds its routing matrix.
2182 for (std::size_t a = 0; a < cache_miss_arcs_.size(); ++a) {
2183 const CacheMissArc& mc = cache_miss_arcs_[a];
2184 P.set(mc.cls, mc.cls, mc.from_node, mc.to_node, one);
2185 }
2186 // A SELF-LOOPING CLASS IS ROUTED HERE, NOT BY THE CALLER (`link.m:78-86`): any row it was given is
2187 // dropped and replaced by the unit loop at its reference station. Without it the class had no route
2188 // at all, so its chain had zero visits and MVA failed on a zero residence time, CTMC on an empty space.
2189 for (std::size_t r = 1; r <= K; ++r) {
2190 if (!sn_.classes[r - 1].self_looping) continue;
2191 for (auto it = P.entries.begin(); it != P.entries.end();)
2192 it = it->first.r == r ? P.entries.erase(it) : std::next(it);
2193 const std::size_t ref = sn_.node_of_station(sn_.classes[r - 1].refstat);
2194 P.set(r, r, ref, ref, one);
2195 }
2196 std::map<std::pair<std::size_t, std::size_t>, std::size_t> csid; // (i,j) -> 1-based node
2197 for (std::size_t i = 1; i <= I; ++i)
2198 for (std::size_t j = 1; j <= I; ++j) {
2199 Matrix<T> C(K, K, zero);
2200 bool any = false;
2201 for (std::size_t r = 1; r <= K; ++r)
2202 for (std::size_t s = 1; s <= K; ++s) {
2203 const T p = P.get(r, s, i, j);
2204 if (num_traits<T>::to_double(p) != 0.0) any = true;
2205 C(r - 1, s - 1) = p;
2206 }
2207 if (!any) continue; // no link at all: the reference's identity, no node
2208 // CONDITIONED ON THE JOB TAKING THIS LINK, so each row is
2209 // renormalised; a class that never leaves i for j keeps itself.
2210 bool offdiag = false;
2211 for (std::size_t r = 1; r <= K; ++r) {
2212 T S = zero;
2213 for (std::size_t s = 1; s <= K; ++s) S += C(r - 1, s - 1);
2214 if (num_traits<T>::to_double(S) > 0) {
2215 for (std::size_t s = 1; s <= K; ++s) C(r - 1, s - 1) = T(C(r - 1, s - 1) / S);
2216 } else {
2217 C(r - 1, r - 1) = one;
2218 }
2219 for (std::size_t s = 1; s <= K; ++s)
2220 if (s != r && num_traits<T>::to_double(C(r - 1, s - 1)) != 0.0) offdiag = true;
2221 }
2222 if (!offdiag) continue; // `~isdiag`: a pure same-class link needs no node
2223 // THE SINK -> SOURCE ARC IS THE OPEN-NETWORK CLOSURE, NOT A LINK.
2224 // A job cannot be routed out of a Sink, so an arc from one into a
2225 // Source is never something a user asked for: it is what makes an
2226 // open chain irreducible for the visit computation, and the
2227 // reference adds it in refreshStruct AFTER link.m has run, so
2228 // link.m never sees it and synthesizes nothing for it. This port
2229 // reads a model.json where linemodel_save has already written the
2230 // closure in, and where it changes class -- an open model that
2231 // enters as InitClass and leaves as HitClass closes as
2232 // `P{HitClass,InitClass}(Sink,Source)` -- the class change looked
2233 // like a switch on a link and grew a CS_Sink_to_Source node. The
2234 // extra hop HALVED every downstream visit: on cache_replc_routing
2235 // both Delays reported throughput 0.2/0.3 against MATLAB's
2236 // 0.4/0.6, in every engine at once. The route is still installed
2237 // below; only the node is not.
2238 if (sn_.nodes[i - 1].nodetype == NodeType::Sink &&
2239 sn_.nodes[j - 1].nodetype == NodeType::Source)
2240 continue;
2241 csid[std::make_pair(i, j)] =
2242 add_class_switch("CS_" + sn_.nodes[i - 1].name + "_to_" + sn_.nodes[j - 1].name, C);
2243 }
2244 // RE-ROUTE i -> cs -> j, the reference's own three assignments. The
2245 // switching probability is folded into the FIRST leg in the departing
2246 // class, and the second leg is deterministic in the arriving class.
2247 for (const auto& kv : csid) {
2248 const std::size_t i = kv.first.first, j = kv.first.second, c = kv.second;
2249 for (std::size_t r = 1; r <= K; ++r)
2250 for (std::size_t s = 1; s <= K; ++s) {
2251 const T p = P.get(r, s, i, j);
2252 if (!(num_traits<T>::to_double(p) > 0)) continue;
2253 P.set(r, r, i, c, T(P.get(r, r, i, c) + p));
2254 P.set(r, s, i, j, zero);
2255 P.set(s, s, c, j, one);
2256 }
2257 }
2258 for (const auto& kv : P.entries) {
2259 const auto& k = kv.first;
2260 sn_.set_route(k.r, k.s, k.i, k.j, kv.second);
2261 }
2262 // A retrieval class inherits the read class's routing among the cache and
2263 // the retrieval queues: it circulates them the same way, entering at the
2264 // cache and returning to it. Set once P is installed (setRetrievalSystem
2265 // runs before link, as the reference documents).
2266 for (const auto& np : sn_.nodeparam) {
2267 const std::size_t ci = np.first; // 1-based cache node
2268 const CacheParam<T>& cp = np.second;
2269 if (cp.retrieval_capacity <= 0) continue;
2270 for (const auto& rq : cp.retrieval_queues) {
2271 const std::size_t rd = rq.first + 1; // 1-based read class
2272 std::vector<std::size_t> nodeset = rq.second; // 1-based queue nodes
2273 nodeset.push_back(ci);
2274 bool minted = false;
2275 const std::size_t Inodes = sn_.nodes.size();
2276 for (std::size_t i = 0; i < cp.nitems; ++i) {
2277 const std::size_t rc = cp.retrieval_classes[i][rd - 1];
2278 if (rc == 0) continue;
2279 minted = true;
2280 // The template is a DEFAULT: a source node the caller ALREADY routed for
2281 // this retrieval class keeps its own row, since merging the two can only
2282 // yield a row summing past 1. Decided before any write, so the template's
2283 // own entries never count as caller-declared.
2284 std::vector<bool> declared(nodeset.size(), false);
2285 for (std::size_t si = 0; si < nodeset.size(); ++si)
2286 for (std::size_t b = 1; b <= Inodes && !declared[si]; ++b)
2287 if (Pm.get(rc, rc, nodeset[si], b) > num_traits<T>::from_int(0))
2288 declared[si] = true;
2289 for (std::size_t si = 0; si < nodeset.size(); ++si) {
2290 if (declared[si]) continue;
2291 for (std::size_t b : nodeset) {
2292 const T p = Pm.get(rd, rd, nodeset[si], b);
2293 if (p > num_traits<T>::from_int(0))
2294 sn_.set_route(rc, rc, nodeset[si], b, p);
2295 }
2296 }
2297 }
2298 // CONSUME the read class's template edges over the queue set,
2299 // as `link.m:187-194` does. They were only ever a TEMPLATE from
2300 // which each retrieval class's circulation is copied; leaving
2301 // them in place makes the read class circulate the fetch
2302 // stations on its own, so each retrieval class becomes a
2303 // separate communicating class and the chain decomposition
2304 // reports one singleton chain per item instead of one chain
2305 // over all of them. Measured before the fix on a closed
2306 // Delay+Cache+Fetch model: 4 chains against MATLAB's 1, and
2307 // every visit at the fetch station zero against MATLAB's 1.5
2308 // per retrieval class.
2309 if (minted)
2310 for (std::size_t a : nodeset)
2311 for (std::size_t b : nodeset)
2312 if (Pm.get(rd, rd, a, b) > num_traits<T>::from_int(0))
2313 sn_.set_route(rd, rd, a, b, num_traits<T>::from_int(0));
2314 }
2315 }
2316 // the per-item overrides of set_item_routing_probability, after the template; later entries win
2317 for (const RetrievalRoutingEntry& e : retrieval_routing_entries_)
2318 sn_.set_route(e.cls, e.cls, e.from_node, e.to_node, e.p);
2319
2320 // A (node, class) PAIR THE CALLER NEVER ROUTED IS LEFT ON RAND, which is
2321 // where `addLink` leaves it in the reference: `setProbRouting` is what
2322 // turns a pair PROB, and it is called only for the entries the routing
2323 // matrix actually carries. The distinction is not bookkeeping.
2324 //
2325 // It decides the VISITS. `getRoutingMatrix` expands RAND uniformly over
2326 // the node's connections, so the pair gets a row; PROB with no entries
2327 // leaves the row EMPTY, and an empty row is an UNVISITED station. On
2328 // `gallery_erlerl1` -- Class1 declares Source->Queue, Class2 declares
2329 // Queue->Sink -- the Queue came out unvisited by Class1 and every metric
2330 // of the model was zero. The `served` mask in `refresh_visits` is what
2331 // keeps the fill honest: it drops the (station, class) pairs with no
2332 // service law.
2333 //
2334 // It also decides the SAMPLE PATH. `saveRoutingStrategy` writes a
2335 // RandomStrategy for a RAND pair and an EmpiricalStrategy for a PROB
2336 // one, and JMT draws from the node's stream for a random split EVEN AT
2337 // ONE DESTINATION -- so the two consume the stream differently and part
2338 // company at the same seed. On `fj_cs_prefork` that was a 14% gap on
2339 // Queue1 against a golden JMT itself produced.
2340 //
2341 // A SELF-LOOPING CLASS AND A SIGNAL ARE LEFT ALONE: the first never
2342 // leaves its station, and the second is routed explicitly by P.
2343 const std::size_t Kc = sn_.classes.size(), Ic = sn_.nodes.size();
2344 for (std::size_t i = 1; i <= Ic; ++i) {
2345 NodeDef& nd = sn_.nodes[i - 1];
2346 nd.routing.resize(Kc, RoutingStrategy::PROB);
2347 bool linked = false;
2348 for (std::size_t j = 1; j <= Ic && !linked; ++j)
2349 for (std::size_t a = 1; a <= Kc && !linked; ++a)
2350 for (std::size_t b = 1; b <= Kc && !linked; ++b)
2351 if (num_traits<T>::to_double(sn_.get_route(a, b, i, j)) > 0.0) linked = true;
2352 if (!linked) continue;
2353 for (std::size_t r = 1; r <= Kc; ++r) {
2354 if (nd.routing[r - 1] != RoutingStrategy::PROB) continue;
2355 if (sn_.classes[r - 1].self_looping) continue;
2356 if (r <= sn_.issignal.size() && sn_.issignal[r - 1]) continue;
2357 bool routed = false;
2358 for (std::size_t j = 1; j <= Ic && !routed; ++j)
2359 for (std::size_t s = 1; s <= Kc && !routed; ++s)
2360 if (num_traits<T>::to_double(sn_.get_route(r, s, i, j)) > 0.0) routed = true;
2361 if (!routed) nd.routing[r - 1] = RoutingStrategy::RAND;
2362 }
2363 }
2364
2365 // A variable forking level declared BEFORE the routing existed. Its
2366 // destination set is read off the routing, so this is the first moment
2367 // it can be resolved; a call made after `link()` is applied where it
2368 // stands, which is what raising the flag first buys, and replaying here
2369 // is idempotent.
2370 routing_linked_ = true;
2371 apply_fork_overrides();
2372 }
2373
2374 // -----------------------------------------------------------------------
2375 // Struct
2376 // -----------------------------------------------------------------------
2377
2378 /** The refreshed struct, MATLAB's `model.getStruct()`. */
2380 materialize_transitions();
2381 if (routing_installed()) apply_fork_overrides();
2382 validate();
2383 sn_.refresh_struct();
2384 // The fork block of refreshStruct.m, and it belongs HERE rather than in
2385 // refresh_struct(): it needs the MMT transformation, which is built on a
2386 // refreshed struct, exactly as the reference calls ModelAdapter.mmt after
2387 // refreshChains. fj_tag's own refresh_struct() therefore skips it, which
2388 // is what `~isFJAugmented` buys the reference.
2390 // THE STRUCT'S CONTRACT, checked on each rebuild in debug mode: see sn_contract.h. This port
2391 // rebuilds the struct on every call, so every call is a rebuild.
2393 std::vector<std::string> violations = api::sn_validate_contract(sn_);
2394 if (!violations.empty()) {
2395 std::string msg;
2396 for (const auto& x : violations) msg += "\n " + x;
2397 std::cerr << "[LINE] Warning: The NetworkStruct of model " << sn_.name
2398 << " violates sn_contract:" << msg << std::endl;
2399 }
2400 }
2401 return sn_;
2402 }
2403
2404 /** `model.getClassSwitchingMask()`: entry (r-1, s-1) is true if some node can switch class r into s. */
2405 std::vector<std::vector<bool>> get_class_switching_mask() { return get_struct().csmask; }
2406
2407 /** The struct WITHOUT refreshing it, for a caller that is still building. */
2408 NetworkStruct<T>& raw_struct() { return sn_; }
2409
2410 /**
2411 * `Queue.setService(@(c) ...)` for a pass-and-swap / order-independent
2412 * station: the total service rate mu(c) of an ordered list of 1-based
2413 * class indices, and the swap graph saying which class may take another's
2414 * place. An OI station is the special case of an empty swap graph.
2415 */
2416 void set_pas(std::size_t node,
2417 const std::function<T(const std::vector<std::size_t>&)>& mu,
2418 const std::vector<std::vector<bool>>& swap_graph =
2419 std::vector<std::vector<bool>>()) {
2420 const std::size_t ist = station_of(node, "set_pas");
2421 typename NetworkStruct<T>::PasParam pp;
2422 pp.svc_rate_fun = mu;
2423 pp.swap_graph = swap_graph;
2424 if (pp.swap_graph.empty())
2425 pp.swap_graph.assign(sn_.classes.size(), std::vector<bool>(sn_.classes.size(), false));
2426 sn_.pasparam[ist] = pp;
2427 // The other half of the same declaration; see `set_service_rate_function`.
2428 Station<T>& stp = sn_.stations[ist - 1];
2429 stp.svc_rate_fun = mu;
2430 const std::size_t R = pp.swap_graph.size();
2432 for (std::size_t a = 0; a < R; ++a)
2433 for (std::size_t b = 0; b < pp.swap_graph[a].size(); ++b)
2434 if (pp.swap_graph[a][b]) G(a, b) = num_traits<T>::from_int(1);
2435 stp.swap_graph = G;
2436 }
2437
2438 /**
2439 * Copy a PAS/OI declaration into `sn.pasparam`, the form the state-space
2440 * layer reads. The (R x R) swap adjacency crosses as a boolean matrix
2441 * because that is the shape `after_event`'s swap walk indexes.
2442 */
2443 void pas_mirror(std::size_t ist,
2444 const std::function<T(const std::vector<std::size_t>&)>& mu,
2445 const Matrix<T>& swap_graph) {
2446 typename NetworkStruct<T>::PasParam pp;
2447 pp.svc_rate_fun = mu;
2448 const std::size_t R = sn_.classes.size();
2449 pp.swap_graph.assign(R, std::vector<bool>(R, false));
2450 for (std::size_t a = 0; a < R && a < swap_graph.rows(); ++a)
2451 for (std::size_t b = 0; b < R && b < swap_graph.cols(); ++b)
2452 pp.swap_graph[a][b] = num_traits<T>::to_double(swap_graph(a, b)) != 0.0;
2453 sn_.pasparam[ist] = pp;
2454 }
2455
2456 /**
2457 * `Queue.setPollingType(...)`: the polling discipline of a POLLING station
2458 * and the switchover walks between its buffers.
2459 *
2460 * `switchover[r-1]` is the walk the server takes when LEAVING buffer r. An
2461 * Immediate walk is folded rather than represented, so it costs no state.
2462 */
2463 void set_polling(std::size_t node, lang::PollingType ptype,
2464 const std::vector<Distrib<T>>& switchover = std::vector<Distrib<T>>(),
2465 std::size_t pk = 1) {
2466 const std::size_t ist = station_of(node, "set_polling");
2467 if (sn_.stations[ist - 1].sched != SchedStrategy::POLLING)
2468 throw InputError("set_polling: the station is not POLLING-scheduled");
2470 pp.ptype = ptype;
2471 pp.pk = pk;
2472 pp.switchover = switchover;
2473 if (pp.switchover.size() < sn_.classes.size())
2474 pp.switchover.resize(sn_.classes.size(), Distrib<T>::disabled_dist());
2475 sn_.pollingparam[ist] = pp;
2476 }
2477
2478 /**
2479 * Declare a SYNCHRONOUS call: a job of `call_cls` leaving `node` keeps its
2480 * server until a job of the REPLY class `reply_cls` arrives back here.
2481 *
2482 * The block is one nvars column per (node, calling class), so it stays
2483 * zero-width -- and every other model's state width unchanged -- unless a
2484 * model actually declares a reply. `node` is checked here and marked, but
2485 * `refresh_replyblock` re-derives the whole block from the routing on every
2486 * refresh, exactly as the reference does; naming a node is therefore an
2487 * assertion about this model, not the definition of the block.
2488 */
2489 void set_sync_reply(std::size_t node, std::size_t call_cls, std::size_t reply_cls) {
2490 const std::size_t K = sn_.classes.size();
2491 if (node == 0 || node > sn_.nodes.size())
2492 throw InputError("set_sync_reply: node index is out of range");
2493 if (call_cls == 0 || call_cls > K || reply_cls == 0 || reply_cls > K)
2494 throw InputError("set_sync_reply: class index is out of range");
2495 const std::size_t ist = sn_.nodes[node - 1].station;
2496 if (ist == 0) throw InputError("set_sync_reply: node is not a station");
2497 // No discipline check here: like MATLAB refreshLocalVars, refresh_replyblock refuses a non-FCFS, non-INF
2498 // station by name, and only where the reply actually arrives, so declaring the binding is always legal
2499 // grow, never reassign: a node or class added since the last call must not erase earlier bindings
2500 if (sn_.replyblock.size() < sn_.nodes.size()) sn_.replyblock.resize(sn_.nodes.size());
2501 for (std::vector<bool>& row : sn_.replyblock)
2502 if (row.size() < K) row.resize(K, false);
2503 if (sn_.syncreply.size() < K) sn_.syncreply.resize(K, 0);
2504 sn_.replyblock[node - 1][call_cls - 1] = true;
2505 sn_.syncreply[call_cls - 1] = reply_cls;
2507 }
2508
2509 /**
2510 * `FiniteCapacityRegion(model, nodes)`: a cap on the jobs held ACROSS a set
2511 * of stations.
2512 *
2513 * `class_max_jobs[r]` and `global_max_jobs` are -1 for unbounded, the
2514 * reference's sentinel; the per-class cap is additionally tightened by
2515 * `floor(class_max_memory[r] / class_size[r])` when a memory budget is set,
2516 * because a class whose footprint exceeds the budget cannot have as many
2517 * jobs resident as its job cap alone would allow.
2518 *
2519 * @param nodes 1-based node indices; each must be a station
2520 * @param class_max_jobs (K) per-class job cap inside the region, -1 for unbounded
2521 * @param global_max_jobs cap on the total jobs inside the region, -1 for unbounded
2522 * @param rule (K) per-class drop strategy applied when the cap is reached
2523 * @param class_max_memory (K) per-class memory budget, -1 for unbounded
2524 * @param class_size (K) per-job memory footprint of each class
2525 * @param global_max_memory cap on the total memory inside the region, -1 for unbounded
2526 */
2527 std::size_t add_region(const std::vector<std::size_t>& nodes,
2528 const std::vector<double>& class_max_jobs,
2529 double global_max_jobs = -1.0,
2530 const std::vector<DropStrategy>& rule = std::vector<DropStrategy>(),
2531 const std::vector<double>& class_max_memory = std::vector<double>(),
2532 const std::vector<T>& class_size = std::vector<T>(),
2533 double global_max_memory = -1.0,
2534 const std::string& name = std::string()) {
2535 const std::size_t M = sn_.stations.size(), K = sn_.classes.size();
2536 typename NetworkStruct<T>::Region rg;
2537 rg.name = name;
2538 rg.cap.assign(M, std::vector<double>(K + 1, -1.0));
2539 rg.maxmem.assign(M, -1.0);
2540 rg.members.assign(M, false);
2541 // A class beyond the region's own vectors defaults to WAITQ, weight 1
2542 // and size 1, exactly as refreshRegions does -- NOT to DROP, which
2543 // would silently start losing jobs of a class added after the region.
2544 rg.rule.assign(K, DropStrategy::WAITQ);
2545 rg.weight.assign(K, num_traits<T>::from_int(1));
2546 rg.size.assign(K, num_traits<T>::from_int(1));
2547 for (std::size_t r = 0; r < K && r < rule.size(); ++r) rg.rule[r] = rule[r];
2548 for (std::size_t r = 0; r < K && r < class_size.size(); ++r) rg.size[r] = class_size[r];
2549
2550 for (std::size_t j = 0; j < nodes.size(); ++j) {
2551 const std::size_t ist = station_of(nodes[j], "addRegion");
2552 rg.members[ist - 1] = true;
2553 for (std::size_t r = 0; r < K; ++r) {
2554 // A class beyond the region's own job-cap vector is UNBOUNDED and
2555 // is not clamped by the memory budget either: refreshRegions.m
2556 // takes the `continue` before it reaches the memory block. Applying
2557 // the clamp here would cap a class MATLAB leaves free, whenever
2558 // class_max_memory is the longer of the two vectors.
2559 if (r >= class_max_jobs.size()) {
2560 rg.cap[ist - 1][r] = -1.0;
2561 continue;
2562 }
2563 double c = class_max_jobs[r];
2564 if (r < class_max_memory.size() && class_max_memory[r] != -1.0) {
2565 const double sz = num_traits<T>::to_double(rg.size[r]);
2566 if (sz > 0) {
2567 const double memjobs = std::floor(class_max_memory[r] / sz);
2568 c = c == -1.0 ? memjobs : std::min(c, memjobs);
2569 }
2570 }
2571 rg.cap[ist - 1][r] = c;
2572 }
2573 rg.cap[ist - 1][K] = global_max_jobs;
2574 rg.maxmem[ist - 1] = global_max_memory;
2575 }
2576 sn_.regions.push_back(rg);
2577 return sn_.regions.size();
2578 }
2579
2580 /**
2581 * `FiniteCapacityRegion.setClassWeight`: the per-class weight the region's
2582 * global cap counts a job against, defaulting to 1. A weight of 2 makes one
2583 * job of the class consume two of the region's slots.
2584 */
2585 void set_region_weights(std::size_t region, const std::vector<T>& weight) {
2586 if (region == 0 || region > sn_.regions.size())
2587 throw InputError("set_region_weights: region index is out of range");
2588 typename NetworkStruct<T>::Region& rg = sn_.regions[region - 1];
2589 for (std::size_t r = 0; r < rg.weight.size() && r < weight.size(); ++r)
2590 rg.weight[r] = weight[r];
2591 }
2592
2593 /** The optional linear constraint A n <= b a region may carry beyond its caps. */
2594 void set_region_constraint(std::size_t region, const Matrix<T>& A, const std::vector<T>& b) {
2595 if (region == 0 || region > sn_.regions.size())
2596 throw InputError("set_region_constraint: region index is out of range");
2597 if (A.rows() != b.size())
2598 throw InputError("set_region_constraint: A and b disagree on the number of rows");
2599 sn_.regions[region - 1].lincon_A = A;
2600 sn_.regions[region - 1].lincon_b = b;
2601 }
2602
2603 /**
2604 * `model.setReward(name, fn)`: a named reward evaluated on the AGGREGATE
2605 * state row, the per-(station, class) job counts in `(ist-1)*K + k` order.
2606 *
2607 * Redeclaring a name REPLACES it rather than adding a second reward under
2608 * the same name, so a caller refining a definition does not end up with two
2609 * answers labelled identically.
2610 */
2611 void set_reward(const std::string& nm,
2612 const std::function<T(const std::vector<T>&)>& fn,
2613 const std::string& kind = std::string(), std::size_t node = 0,
2614 std::size_t cls = 0) {
2615 for (std::size_t i = 0; i < sn_.reward.size(); ++i)
2616 if (sn_.reward[i].name == nm) {
2617 sn_.reward[i].fn = fn;
2618 sn_.reward[i].kind = kind;
2619 sn_.reward[i].node = node;
2620 sn_.reward[i].cls = cls;
2621 return;
2622 }
2623 typename NetworkStruct<T>::Reward rw;
2624 rw.name = nm;
2625 rw.fn = fn;
2626 rw.kind = kind;
2627 rw.node = node;
2628 rw.cls = cls;
2629 sn_.reward.push_back(rw);
2630 }
2631
2632 /**
2633 * Declare a class to be a G-network SIGNAL rather than a job.
2634 *
2635 * A signal never joins a station: it removes jobs already there and is
2636 * annihilated. `target` is the 1-based class it may remove, or 0 for the
2637 * classic untargeted Gelenbe customer. `remdist` is the batch-size pmf
2638 * indexed by batch size 0,1,2,...; empty means "remove exactly one".
2639 */
2640 void set_signal(std::size_t cls, lang::SignalType type,
2642 std::size_t target = 0,
2643 const std::vector<T>& remdist = std::vector<T>()) {
2644 const std::size_t K = sn_.classes.size();
2645 if (cls == 0 || cls > K) throw InputError("set_signal: class index is out of range");
2646 if (target > K) throw InputError("set_signal: target class index is out of range");
2647 // GROW, never reset: a class added after an earlier set_signal must not erase that declaration
2648 if (sn_.issignal.size() < K) {
2649 sn_.issignal.resize(K, false);
2650 sn_.signaltype.resize(K, lang::SignalType::NEGATIVE);
2651 sn_.signaltarget.resize(K, 0);
2652 sn_.signalrempolicy.resize(K, lang::RemovalPolicy::RANDOM);
2653 sn_.signalremdist.resize(K, std::vector<T>());
2654 }
2655 sn_.issignal[cls - 1] = true;
2656 sn_.signaltype[cls - 1] = type;
2657 sn_.signaltarget[cls - 1] = target;
2658 sn_.signalrempolicy[cls - 1] = policy;
2659 sn_.signalremdist[cls - 1] = remdist;
2660 }
2661
2662 std::size_t station_index(std::size_t node) const { return station_of(node, "station_index"); }
2663
2664 private:
2665 NetworkStruct<T> sn_;
2666
2667 /** One arc declared through the setter API, before it has a matrix to live in. */
2668 struct TransitionArc {
2669 std::size_t mode, node, cls;
2670 T count;
2671 TransitionArc(std::size_t m, std::size_t n, std::size_t c, const T& v)
2672 : mode(m), node(n), cls(c), count(v) {}
2673 };
2674
2675 /** The pre, inhibitor and post arcs of one transition, still sparse. */
2676 struct TransitionArcs {
2677 std::vector<TransitionArc> enab, inhib, fire;
2678 };
2679
2680 /**
2681 * The sparse arcs of every transition built through `add_transition(name)`,
2682 * keyed by node.
2683 *
2684 * Membership is also what tells a DECLARATIVE transition from one handed a
2685 * finished `TransitionParam`, whose matrices belong to the caller and are
2686 * normalised rather than rebuilt.
2687 */
2688 std::map<std::size_t, TransitionArcs> pending_arcs_;
2689
2690 /** The param block of a transition whose modes are still being declared. */
2691 TransitionParam<T>& declarative_transition(std::size_t node, const char* what) {
2692 if (node == 0 || node > sn_.nodes.size())
2693 throw InputError(std::string(what) + ": node index is out of range");
2694 if (sn_.nodes[node - 1].nodetype != NodeType::Transition)
2695 throw InputError(std::string(what) + ": node '" + sn_.nodes[node - 1].name +
2696 "' is not a Transition");
2697 if (pending_arcs_.find(node) == pending_arcs_.end())
2698 throw InputError(std::string(what) + ": the Transition '" + sn_.nodes[node - 1].name +
2699 "' was created from a finished TransitionParam, so its modes are "
2700 "already fixed; create it as add_transition(name) to declare them "
2701 "one at a time");
2702 return sn_.transparam[node];
2703 }
2704
2705 /** The same, with the mode index checked against the modes declared so far. */
2706 TransitionParam<T>& mode_param(std::size_t node, std::size_t mode, const char* what) {
2707 TransitionParam<T>& tp = declarative_transition(node, what);
2708 if (mode == 0 || mode > tp.nmodes)
2709 throw InputError(std::string(what) + ": the Transition '" + sn_.nodes[node - 1].name +
2710 "' has no mode " + std::to_string(mode));
2711 return tp;
2712 }
2713
2714 /** The station block of a Place node, for the fluid setters. */
2715 Station<T>& place_station(std::size_t node, const char* what) {
2716 if (node == 0 || node > sn_.nodes.size())
2717 throw InputError(std::string(what) + ": node index is out of range");
2718 if (sn_.nodes[node - 1].nodetype != NodeType::Place)
2719 throw InputError(std::string(what) + ": node '" + sn_.nodes[node - 1].name +
2720 "' is not a Place");
2721 return sn_.stations[sn_.nodes[node - 1].station - 1];
2722 }
2723
2724 /** `mode_param`, with the four fluid lists grown to the mode count (a mode added before they existed). */
2725 TransitionParam<T>& fluid_mode(std::size_t node, std::size_t mode, const char* what) {
2726 TransitionParam<T>& tp = mode_param(node, mode, what);
2727 if (tp.fluidrate.size() < tp.nmodes) tp.fluidrate.resize(tp.nmodes);
2728 if (tp.fluidguard.size() < tp.nmodes) tp.fluidguard.resize(tp.nmodes);
2729 if (tp.fluidimpulse.size() < tp.nmodes) tp.fluidimpulse.resize(tp.nmodes);
2730 if (tp.fluiddep.size() < tp.nmodes) tp.fluiddep.resize(tp.nmodes);
2731 if (tp.fluidflowdep.size() < tp.nmodes) tp.fluidflowdep.resize(tp.nmodes);
2732 return tp;
2733 }
2734
2735 /** A fluid arc must name a Place, as `Transition.fluidPlaceIndex` checks. */
2736 void fluid_place_arg(std::size_t place, const char* what) const {
2737 if (place == 0 || place > sn_.nodes.size() || sn_.nodes[place - 1].nodetype != NodeType::Place)
2738 throw InputError(std::string(what) + ": a fluid arc must name a Place");
2739 }
2740
2741 /** `Transition.setRow`: replace the [node, value] entry of `place`, dropping it when the value is 0. */
2742 static void set_fluid_row(std::vector<typename TransitionParam<T>::FluidArc>& a, std::size_t place,
2743 double val) {
2744 for (std::size_t k = a.size(); k-- > 0;)
2745 if (a[k].node == place) a.erase(a.begin() + static_cast<std::ptrdiff_t>(k));
2746 if (val == 0.0) return;
2747 typename TransitionParam<T>::FluidArc fa;
2748 fa.node = place;
2749 fa.value = val;
2750 a.push_back(fa);
2751 }
2752
2753 /** Check the (mode, class, node) an arc names; a pre-arc must name a Place. */
2754 void arc_target(std::size_t node, std::size_t mode, std::size_t cls, std::size_t target,
2755 bool must_be_place, const char* what) {
2756 mode_param(node, mode, what);
2757 if (cls == 0 || cls > sn_.classes.size())
2758 throw InputError(std::string(what) +
2759 ": class index is out of range; declare the job class before the "
2760 "arcs that move its tokens");
2761 if (target == 0 || target > sn_.nodes.size())
2762 throw InputError(std::string(what) + ": the node the arc names is out of range");
2763 if (must_be_place && sn_.nodes[target - 1].nodetype != NodeType::Place)
2764 throw InputError(std::string(what) + ": '" + sn_.nodes[target - 1].name +
2765 "' is not a Place, and only a Place holds the tokens a mode tests");
2766 }
2767
2768 /** Write the sparse arcs of one kind into the matrices just sized for them. */
2769 static void fill_arcs(std::vector<Matrix<T> >& dst, const std::vector<TransitionArc>& arcs) {
2770 for (std::size_t a = 0; a < arcs.size(); ++a)
2771 dst[arcs[a].mode - 1](arcs[a].node - 1, arcs[a].cls - 1) = arcs[a].count;
2772 }
2773
2774 /**
2775 * Bring a caller's own arc matrices to (nnodes x nclasses).
2776 *
2777 * A SHORT one is padded, because the entries it lacks are arcs the caller
2778 * never declared. A WIDER one is refused: every consumer walks an arc
2779 * matrix row by row against the marking, so extra rows are read past the
2780 * end of it, and `Matrix::operator()` does not bounds-check.
2781 */
2782 static void normalize_arcs(std::vector<Matrix<T> >& a, std::size_t N, std::size_t K,
2783 bool inhibitor, const std::string& nm, const char* what) {
2784 for (std::size_t m = 0; m < a.size(); ++m) {
2785 if (a[m].rows() == N && a[m].cols() == K) continue;
2786 if (a[m].rows() > N || a[m].cols() > K)
2787 throw InputError(
2788 "the Transition '" + nm + "' has an " + what + " matrix of " +
2789 std::to_string(a[m].rows()) + "x" + std::to_string(a[m].cols()) +
2790 " against a model of " + std::to_string(N) + " nodes and " +
2791 std::to_string(K) + " classes; an arc matrix is read row by row against "
2792 "the marking, so a wider one is read past its end");
2793 Matrix<T> grown(N, K, inhibitor ? no_inhibitor() : num_traits<T>::from_int(0));
2794 for (std::size_t q = 0; q < a[m].rows(); ++q)
2795 for (std::size_t r = 0; r < a[m].cols(); ++r) grown(q, r) = a[m](q, r);
2796 a[m] = grown;
2797 }
2798 }
2799
2800 /**
2801 * The "no inhibitor arc here" entry, ON DEMAND.
2802 *
2803 * It is infinity, which an EXACT-ARITHMETIC T cannot hold: building one
2804 * eagerly threw "Cannot convert a non-finite number to an integer" on every
2805 * `Network<Rational>`, Petri net or not. Only a net that actually has an
2806 * inhibitor matrix to fill pays for it.
2807 */
2808 static T no_inhibitor() {
2809 return num_traits<T>::from_double(std::numeric_limits<double>::infinity());
2810 }
2811
2812 /**
2813 * Give every transition its (nnodes x nclasses) arc matrices.
2814 *
2815 * A DECLARATIVE transition's matrices are REBUILT from its sparse arcs, so
2816 * the call is idempotent and a net that gained a node or a class after its
2817 * arcs were declared still gets matrices of the right shape. One built from
2818 * a finished `TransitionParam` keeps the caller's matrices and is only
2819 * normalised.
2820 */
2821 void materialize_transitions() {
2822 if (sn_.transparam.empty()) return;
2823 const std::size_t N = sn_.nodes.size(), K = sn_.classes.size();
2824 const T zero = num_traits<T>::from_int(0);
2825 for (typename std::map<std::size_t, TransitionParam<T> >::iterator it =
2826 sn_.transparam.begin();
2827 it != sn_.transparam.end(); ++it) {
2828 TransitionParam<T>& tp = it->second;
2829 const std::string& nm = sn_.nodes[it->first - 1].name;
2830 if (pending_arcs_.find(it->first) == pending_arcs_.end()) {
2831 normalize_arcs(tp.enabling, N, K, false, nm, "enabling");
2832 normalize_arcs(tp.inhibiting, N, K, true, nm, "inhibiting");
2833 normalize_arcs(tp.firing, N, K, false, nm, "firing");
2834 continue;
2835 }
2836 if (tp.nmodes == 0)
2837 throw InputError("Network '" + sn_.name + "': the Transition '" + nm +
2838 "' has no mode, and every transition needs at least one");
2839 const TransitionArcs& pa = pending_arcs_[it->first];
2840 tp.enabling.assign(tp.nmodes, Matrix<T>(N, K, zero));
2841 tp.inhibiting.assign(tp.nmodes, Matrix<T>(N, K, no_inhibitor()));
2842 tp.firing.assign(tp.nmodes, Matrix<T>(N, K, zero));
2843 fill_arcs(tp.enabling, pa.enab);
2844 fill_arcs(tp.inhibiting, pa.inhib);
2845 fill_arcs(tp.firing, pa.fire);
2846 // The phase count is DERIVED from the law AND the timing, so it is
2847 // recomputed here rather than left to whichever of the two setters
2848 // the caller happened to call last.
2849 for (std::size_t m = 0; m < tp.nmodes; ++m)
2850 tp.firingphases[m] =
2851 tp.timing[m] == lang::TimingStrategy::IMMEDIATE || tp.firingproc[m].disabled
2852 ? 0
2853 : lang::dist_to_map(tp.firingproc[m]).order();
2854 }
2855 resolve_fluid_flow_reads();
2856 }
2857
2858 /**
2859 * The default read set of a fluid flow dependence, as refreshPetriNetNodes resolves it: the input places of the
2860 * mode, the rows of its enabling matrix with a positive entry. Recomputed on every refresh, so an arc added
2861 * after the setter is still read.
2862 */
2863 void resolve_fluid_flow_reads() {
2864 for (typename std::map<std::size_t, TransitionParam<T> >::iterator it = sn_.transparam.begin();
2865 it != sn_.transparam.end(); ++it) {
2866 TransitionParam<T>& tp = it->second;
2867 for (std::size_t m = 0; m < tp.fluidflowdep.size(); ++m) {
2868 for (typename TransitionParam<T>::FluidFlowDep& fd : tp.fluidflowdep[m]) {
2869 if (fd.read_given) continue;
2870 fd.read.clear();
2871 if (m >= tp.enabling.size()) continue;
2872 const Matrix<T>& en = tp.enabling[m];
2873 for (std::size_t q = 0; q < en.rows(); ++q)
2874 for (std::size_t r = 0; r < en.cols(); ++r)
2875 if (num_traits<T>::to_double(en(q, r)) > 0.0) {
2876 fd.read.push_back(q + 1);
2877 break;
2878 }
2879 }
2880 }
2881 }
2882 }
2883
2884 /** Per-item read classes of each cache in a cache network, keyed by cache node. */
2885 std::map<std::size_t, std::vector<std::size_t> > cache_item_classes_;
2886
2887 /** A miss hop registered by `set_miss_cache`, injected into P by `link()`. */
2888 struct CacheMissArc {
2889 std::size_t cls, from_node, to_node;
2890 CacheMissArc(std::size_t c, std::size_t f, std::size_t t)
2891 : cls(c), from_node(f), to_node(t) {}
2892 };
2893 std::vector<CacheMissArc> cache_miss_arcs_;
2894
2895 /** A per-item retrieval edge from `set_item_routing_probability`, injected by `link()` (link.m:213-226). */
2896 struct RetrievalRoutingEntry {
2897 std::size_t cls, from_node, to_node;
2898 T p;
2899 RetrievalRoutingEntry(std::size_t c, std::size_t f, std::size_t t, const T& q)
2900 : cls(c), from_node(f), to_node(t), p(q) {}
2901 };
2902 std::vector<RetrievalRoutingEntry> retrieval_routing_entries_;
2903
2904 /** The 1-based retrieval class of `item` (1-based) of `read_class` at `cache_node`, or the reference's error. */
2905 std::size_t retrieval_class_of(std::size_t cache_node, std::size_t read_class, std::size_t item) const {
2906 const auto it = sn_.nodeparam.find(cache_node);
2907 std::size_t rc = 0;
2908 if (it != sn_.nodeparam.end() && item >= 1 && item <= it->second.retrieval_classes.size() &&
2909 read_class >= 1 && read_class <= it->second.retrieval_classes[item - 1].size())
2910 rc = it->second.retrieval_classes[item - 1][read_class - 1];
2911 if (rc == 0)
2912 throw InputError("No retrieval class defined for the given class/item; call setRetrievalSystem first.");
2913 return rc;
2914 }
2915
2916 /** The CacheParam of `cache_node`, its per-class vectors padded to the classes declared so far. */
2917 CacheParam<T>& cache_param_for_class(std::size_t cache_node, std::size_t r, const char* who) {
2918 auto it = sn_.nodeparam.find(cache_node);
2919 if (cache_node == 0 || cache_node > sn_.nodes.size() || it == sn_.nodeparam.end() ||
2920 sn_.nodes[cache_node - 1].nodetype != NodeType::Cache)
2921 throw InputError(std::string(who) + ": node is not a Cache");
2922 check_class(r, who);
2923 CacheParam<T>& cp = it->second;
2924 const std::size_t K = sn_.classes.size();
2925 if (cp.pread.size() < K) cp.pread.resize(K);
2926 if (cp.preadkind.size() < K) cp.preadkind.resize(K);
2927 if (cp.hitclass.size() < K) cp.hitclass.resize(K, 0);
2928 if (cp.missclass.size() < K) cp.missclass.resize(K, 0);
2929 if (cp.classitem.size() < K) cp.classitem.resize(K, 0);
2930 return cp;
2931 }
2932
2933 /** Refuse a 1-based class index that names no declared class. */
2934 void check_class(std::size_t r, const char* who) const {
2935 if (r == 0 || r > sn_.classes.size())
2936 throw InputError(std::string(who) + ": class index " + std::to_string(r) +
2937 " names no declared class; create the class before passing it");
2938 }
2939
2940 /** One class shared by every item, or one per item. */
2941 static std::vector<std::size_t> per_item_classes(const std::vector<std::size_t>& spec,
2942 std::size_t nitems, const char* what) {
2943 if (spec.size() == nitems) return spec;
2944 if (spec.size() == 1) return std::vector<std::size_t>(nitems, spec[0]);
2945 throw InputError(std::string(what) +
2946 ": pass one class per item or a single class shared by all");
2947 }
2948
2949 /** The class record, with the index checked against the live class list. */
2950 JobClass& class_ref(std::size_t cls, const char* what) {
2951 if (cls == 0 || cls > sn_.classes.size())
2952 throw InputError(std::string(what) + ": class index is out of range");
2953 return sn_.classes[cls - 1];
2954 }
2955
2956 void init_node(std::size_t nd) {
2957 sn_.nodes[nd - 1].routing.assign(sn_.classes.size(), RoutingStrategy::PROB);
2958 }
2959
2960 /** Grow the per-class vectors of every node and station after a new class. */
2961 void grow_class_vectors() {
2962 const std::size_t K = sn_.classes.size();
2963 for (NodeDef& nd : sn_.nodes) nd.routing.resize(K, RoutingStrategy::PROB);
2964 for (Station<T>& st : sn_.stations) {
2965 if (!st.classcap.empty())
2966 st.classcap.resize(K, std::numeric_limits<double>::infinity());
2967 if (!st.droprule.empty()) st.droprule.resize(K, 0);
2968 if (!st.schedparam.empty()) st.schedparam.resize(K, num_traits<T>::from_int(1));
2969 }
2970 }
2971
2972 /** The station of a node, with the class index checked against the live class list. */
2973 Station<T>& station_ref(std::size_t node, std::size_t cls, const char* what) {
2974 const std::size_t ist = station_of(node, what);
2975 if (cls == 0 || cls > sn_.classes.size())
2976 throw InputError(std::string(what) + ": class index is out of range");
2977 return sn_.stations[ist - 1];
2978 }
2979
2980 /**
2981 * Widen an OPTIONAL per-class vector to hold `cls`, filling with the
2982 * "not declared" value. The vectors start empty on purpose -- an empty one
2983 * means the station declares none of this property at all -- so they cannot
2984 * be sized in `grow_class_vectors` without turning every station into one
2985 * that declares it.
2986 */
2987 template <class V>
2988 void grow_class_slot(std::vector<V>& v, std::size_t cls, const V& fill) {
2989 const std::size_t K = sn_.classes.size();
2990 if (v.size() < K) v.resize(K < cls ? cls : K, fill);
2991 }
2992
2993 std::size_t station_of(std::size_t node, const std::string& what) const {
2994 if (node == 0 || node > sn_.nodes.size())
2995 throw InputError(what + ": node index " + std::to_string(node) + " does not exist");
2996 const std::size_t ist = sn_.nodes[node - 1].station;
2997 if (ist == 0)
2998 throw InputError(what + ": node '" + sn_.nodes[node - 1].name +
2999 "' is not a station (it serves no jobs)");
3000 return ist;
3001 }
3002
3003 /** One recorded `Fork.set*` call, replayed once the routing is installed. */
3004 struct ForkOverride {
3005 enum Kind { TASKS, DIST, PROB };
3006 Kind kind = TASKS;
3007 std::size_t fork = 0, cls = 0, dest = 0;
3008 double value = 0.0;
3009 lang::Distrib<T> dist;
3010 };
3011 std::vector<ForkOverride> fork_overrides_;
3012 /** Set by `link()`. See `routing_installed()`. */
3013 bool routing_linked_ = false;
3014
3015 /**
3016 * Record an override, and apply it at once when the routing already exists.
3017 *
3018 * Applying eagerly is not an optimisation: it is what makes an override
3019 * naming a node that the fork does not reach fail AT THE CALL, where the
3020 * caller can see which line is wrong, rather than at `get_struct()`.
3021 */
3022 void record_fork_override(const ForkOverride& ov) {
3023 if (ov.fork == 0 || ov.fork > sn_.nodes.size() ||
3024 sn_.nodes[ov.fork - 1].nodetype != NodeType::Fork)
3025 throw InputError("the node given is not a Fork of this model");
3026 if (ov.cls == 0 || ov.cls > sn_.classes.size())
3027 throw InputError("a fork override names a class that does not exist");
3028 fork_overrides_.push_back(ov);
3029 if (routing_installed()) apply_fork_override(ov);
3030 }
3031
3032 /**
3033 * True once `link()` has written a routing block a fork override can read.
3034 *
3035 * A FLAG, not a size test on `rtnodes`. The size test could only become
3036 * true after a `get_struct()` had already refreshed the struct, so an
3037 * override recorded AFTER `link()` was applied by neither the eager path
3038 * here nor the replay in `get_struct()`, and was silently dropped.
3039 */
3040 bool routing_installed() const { return routing_linked_; }
3041
3042 /** Replay every recorded override, in the order the model declared them. */
3043 void apply_fork_overrides() {
3044 for (std::size_t i = 0; i < fork_overrides_.size(); ++i)
3045 apply_fork_override(fork_overrides_[i]);
3046 }
3047
3048 void apply_fork_override(const ForkOverride& ov) {
3049 qn::ForkParam<T>& f = fork_param(ov.fork);
3050 const std::vector<std::size_t> dests = fork_dests(ov.fork, ov.dest);
3051 for (std::size_t x = 0; x < dests.size(); ++x) {
3052 const std::size_t k = dests[x];
3053 switch (ov.kind) {
3054 case ForkOverride::TASKS:
3055 f.fan_out_link(k - 1, ov.cls - 1) = num_traits<T>::from_double(ov.value);
3056 break;
3057 case ForkOverride::DIST:
3058 f.fan_out_dist[k - 1][ov.cls - 1] = ov.dist;
3059 // the scalar slot carries the mean, so a consumer that only
3060 // reads fan_out_link still sees E[tasks per link]
3061 f.fan_out_link(k - 1, ov.cls - 1) = ov.dist.mean;
3062 break;
3063 case ForkOverride::PROB:
3064 f.fan_out_prob(k - 1, ov.cls - 1) = num_traits<T>::from_double(ov.value);
3065 break;
3066 }
3067 }
3068 refresh_fork_scalar(sn_.nodes[ov.fork - 1], f);
3069 }
3070
3071 /**
3072 * The fork's node record, with its variable-forking-level matrices sized on
3073 * first use.
3074 *
3075 * They start EMPTY on every fork, so a consumer can tell a plain fork from
3076 * one with overrides without inspecting entries; the first override is what
3077 * allocates them, seeded from `tasks_per_link` and probability 1 on the
3078 * links the model actually declares.
3079 */
3080 qn::ForkParam<T>& fork_param(std::size_t fork_node) {
3081 if (fork_node == 0 || fork_node > sn_.nodes.size() ||
3082 sn_.nodes[fork_node - 1].nodetype != NodeType::Fork)
3083 throw InputError("the node given is not a Fork of this model");
3084 qn::ForkParam<T>& f = sn_.forkparam[fork_node];
3085 const std::size_t I = sn_.nodes.size(), K = sn_.classes.size();
3086 if (f.fan_out_link.rows() == I && f.fan_out_link.cols() == K) return f;
3087 const T zero = num_traits<T>::from_int(0);
3088 f.fan_out_link = Matrix<T>(I, K, zero);
3089 f.fan_out_prob = Matrix<T>(I, K, zero);
3090 f.fan_out_dist.assign(I, std::vector<lang::Distrib<T> >(K));
3091 const T tpl = num_traits<T>::from_double(sn_.nodes[fork_node - 1].tasks_per_link);
3092 const T one = num_traits<T>::from_int(1);
3093 for (std::size_t k = 1; k <= I; ++k)
3094 for (std::size_t r = 1; r <= K; ++r)
3095 if (fork_links_to(fork_node, k, r)) {
3096 f.fan_out_link(k - 1, r - 1) = tpl;
3097 f.fan_out_prob(k - 1, r - 1) = one;
3098 }
3099 return f;
3100 }
3101
3102 /**
3103 * Keep the scalar `tasks_per_link` consistent with the per-link mean, so a
3104 * solver that has not been taught the matrices degrades to E[tasks per
3105 * link] and not to a value the fork never emits.
3106 *
3107 * The branch probability is folded in HERE and not into `fan_out_link`,
3108 * because JMT and LDES read the two separately: `fan_out_link` is the count
3109 * GIVEN the branch fires, `fan_out_prob` is whether it fires at all.
3110 */
3111 void refresh_fork_scalar(qn::NodeDef& nd, const qn::ForkParam<T>& f) {
3112 double acc = 0.0;
3113 std::size_t cnt = 0;
3114 for (std::size_t k = 0; k < f.fan_out_link.rows(); ++k)
3115 for (std::size_t r = 0; r < f.fan_out_link.cols(); ++r) {
3116 if (num_traits<T>::to_double(f.fan_out_prob(k, r)) == 0.0) continue;
3117 acc += num_traits<T>::to_double(f.fan_out_link(k, r)) *
3118 num_traits<T>::to_double(f.fan_out_prob(k, r));
3119 ++cnt;
3120 }
3121 if (cnt > 0) nd.tasks_per_link = acc / static_cast<double>(cnt);
3122 }
3123
3124 /**
3125 * True when class r of `fork_node` routes to node k.
3126 *
3127 * READ OFF THE ROUTING `link()` WRITES, not off `rtnodes`. `rtnodes` is
3128 * DERIVED, built by `refresh_routing()` inside `refresh_struct()`, so it is
3129 * still empty at the end of `link()` -- which is precisely where the
3130 * recorded overrides are replayed. Asking it there answered "this fork
3131 * links nowhere" for every destination: `dest_node = 0` raised "call link()
3132 * before the override" from inside `link()` itself, and a named destination
3133 * fared worse, seeding the whole fan-out with zeros so every branch got
3134 * probability 0 and the model solved on a fork that never fires. `route_eff`
3135 * is the expansion when there is one and the declared `P` otherwise, which
3136 * is the same source the linked-node scan in `link()` already uses.
3137 */
3138 bool fork_links_to(std::size_t fork_node, std::size_t k, std::size_t r) const {
3139 const std::size_t K = sn_.classes.size();
3140 for (std::size_t s = 1; s <= K; ++s)
3141 if (num_traits<T>::to_double(sn_.route_eff(r, s, fork_node, k)) != 0.0) return true;
3142 return false;
3143 }
3144
3145 /**
3146 * Node indexes a fork override applies to. `dest_node` 0 means every
3147 * destination the fork actually links to, so the routing must be in place
3148 * by the time this runs -- which is what the recorded-override replay in
3149 * `link()` guarantees whichever order the caller used.
3150 */
3151 std::vector<std::size_t> fork_dests(std::size_t fork_node, std::size_t dest_node) const {
3152 std::vector<std::size_t> out;
3153 const std::size_t I = sn_.nodes.size(), K = sn_.classes.size();
3154 if (dest_node != 0) {
3155 if (dest_node > I)
3156 throw InputError("a fork override names a node that does not exist");
3157 out.push_back(dest_node);
3158 return out;
3159 }
3160 for (std::size_t k = 1; k <= I; ++k)
3161 for (std::size_t r = 1; r <= K; ++r)
3162 if (fork_links_to(fork_node, k, r)) { out.push_back(k); break; }
3163 if (out.empty())
3164 throw InputError("a fork override was set on '" + sn_.nodes[fork_node - 1].name +
3165 "', which links nowhere yet: call link() before the override");
3166 return out;
3167 }
3168
3169 /**
3170 * The checks a model must pass before its struct means anything.
3171 *
3172 * They are the ones whose absence produces a struct that solves to a
3173 * plausible wrong answer rather than to an error: a class with no service
3174 * anywhere, an open class with no arrival, a Fork with no Join.
3175 */
3176 void validate() const {
3177 if (sn_.classes.empty()) throw InputError("Network '" + sn_.name + "': it has no classes");
3178 if (sn_.stations.empty())
3179 throw InputError("Network '" + sn_.name + "': it has no stations");
3180 // WHO SWITCHES INTO WHOM. A job can enter a class by arriving in it, or
3181 // by CLASS SWITCHING into it from another class -- through a routing
3182 // block with r != s, through a ClassSwitch node's matrix, or through a
3183 // cache's hit/miss/retrieval switch. `switches` is that edge relation,
3184 // and the only test below that reads it is the "no service process
3185 // anywhere" one: a class reached ONLY by switching legitimately has no
3186 // service of its own at some stations.
3187 //
3188 // There is deliberately NO reachability closure over these edges any
3189 // more. It existed to refuse an open class no job can enter, which is
3190 // not an error -- see the note on `gallery_erlerl1` below. MATLAB and
3191 // python have no check of this kind at all, so there was never a
3192 // reference predicate to copy. `validate()` runs BEFORE
3193 // `refresh_routing`, so the edges are read from the raw `P` and from
3194 // `csmatrix`, not from `Peff`, which does not exist yet.
3195 const std::size_t K = sn_.classes.size();
3196 const T zero = num_traits<T>::from_int(0);
3197 std::vector<std::vector<bool>> switches(K, std::vector<bool>(K, false));
3198 for (std::size_t r = 0; r < K; ++r)
3199 for (std::size_t sc = 0; sc < K; ++sc) {
3200 if (r == sc) continue;
3201 for (std::size_t i = 1; i <= sn_.nodes.size() && !switches[r][sc]; ++i)
3202 for (std::size_t j = 1; j <= sn_.nodes.size(); ++j)
3203 if (sn_.get_route(r + 1, sc + 1, i, j) > zero) {
3204 switches[r][sc] = true;
3205 break;
3206 }
3207 }
3208 for (const auto& kv : sn_.csmatrix) {
3209 const Matrix<T>& C = kv.second;
3210 for (std::size_t r = 0; r < K && r < C.rows(); ++r)
3211 for (std::size_t sc = 0; sc < K && sc < C.cols(); ++sc)
3212 if (r != sc && C(r, sc) > zero) switches[r][sc] = true;
3213 }
3214 for (const auto& kv : sn_.nodeparam) {
3215 const CacheParam<T>& cp = kv.second;
3216 for (std::size_t r = 0; r < K; ++r) {
3217 if (r < cp.hitclass.size() && cp.hitclass[r] >= 1 && cp.hitclass[r] <= K)
3218 switches[r][cp.hitclass[r] - 1] = true;
3219 if (r < cp.missclass.size() && cp.missclass[r] >= 1 && cp.missclass[r] <= K)
3220 switches[r][cp.missclass[r] - 1] = true;
3221 }
3222 for (const auto& row : cp.retrieval_classes)
3223 for (std::size_t r = 0; r < K && r < row.size(); ++r)
3224 if (row[r] >= 1 && row[r] <= K) switches[r][row[r] - 1] = true;
3225 }
3226 // SPAWN ON COMPLETION REACHES A CLASS TOO. A phase-2 continuation is
3227 // injected by the completion of its trigger and never arrives at a
3228 // Source or crosses a switch, so without this edge it reads as a class
3229 // no job can enter and a well-formed LQN phase-2 model is refused.
3230 for (std::size_t r = 0; r < K; ++r)
3231 if (sn_.classes[r].spawn >= 1 && sn_.classes[r].spawn <= K)
3232 switches[r][sn_.classes[r].spawn - 1] = true;
3233 for (std::size_t r = 0; r < sn_.classes.size(); ++r) {
3234 // A class reached only by switching legitimately has no service of
3235 // its own at some stations; the served test still applies to the
3236 // rest, so it is kept for every class that is not switched into.
3237 bool switched_into = false;
3238 for (std::size_t q = 0; q < K; ++q)
3239 if (switches[q][r]) switched_into = true;
3240 bool served = false;
3241 for (std::size_t i = 0; i < sn_.stations.size(); ++i)
3242 if (!sn_.service[i][r].disabled) served = true;
3243 // In an SPN the timing lives in the transition modes, not in station
3244 // service: a Place is a token container and only a QUEUEING place
3245 // carries a service process, so a token class served nowhere is a
3246 // well-formed net rather than an incomplete one.
3247 bool petri = false;
3248 for (std::size_t nd = 0; nd < sn_.nodes.size(); ++nd)
3249 if (sn_.nodes[nd].nodetype == NodeType::Transition) petri = true;
3250 if (!served && !switched_into && !petri)
3251 throw InputError("Network '" + sn_.name + "': class '" + sn_.classes[r].name +
3252 "' has no service process at any station");
3253 // AN UNREACHABLE OPEN CLASS IS WELL FORMED, and this used to refuse
3254 // it. `gallery_erlerl1` ships in all three reference suites with a
3255 // second open class whose arrival is Disabled and which nothing
3256 // routes into; MATLAB and native Python both SOLVE it and simply
3257 // report no row for that class, because a class no job can enter
3258 // carries zero of every metric and the table drops an all-zero row.
3259 // The refusal made this port the only one that could not read its
3260 // own gallery. Same argument as the fork-with-no-join case below:
3261 // a construct the reference suites ship and the reference solvers
3262 // answer is not an input error, whatever it looks like in isolation.
3263 }
3264 // A FORK WITH NO JOIN IS WELL FORMED ONLY IF ITS SIBLINGS CAN LEAVE.
3265 // `fj_nojoin` ships in all three reference suites as an OPEN model
3266 // whose fork branches each end at the Sink, and MATLAB and native
3267 // Python both solve it, so a blanket refusal is wrong: the
3268 // synchronisation point is what a Join provides, and a model that
3269 // never synchronises simply has none (see fj_driver.h, which drives
3270 // forkLambda from the fork's own firing rate in that case).
3271 //
3272 // A join-less fork whose branches RETURN INTO THE MODEL is a different
3273 // object. Every firing turns one job into k siblings, none of them ever
3274 // merges and none ever departs, so the population is not conserved and
3275 // grows without bound. The reference has no check for it and cannot
3276 // solve it either: `sortForks` calls `nestedForks(f, [])`, whose
3277 // `startNode == endNode` test can never hold against an empty join, and
3278 // on a closed model it recurses until MATLAB reports "Out of memory.
3279 // The likely cause is an infinite recursion" (measured 2026-07-30).
3280 // Refusing here names the node the caller has to close.
3281 for (std::size_t i = 0; i < sn_.nodes.size(); ++i) {
3282 if (sn_.nodes[i].nodetype != NodeType::Fork) continue;
3283 bool closed = false;
3284 for (const auto& fjp : sn_.fj)
3285 if (fjp.first == i + 1) closed = true;
3286 if (closed) continue;
3287 // Can a sibling ever leave? Reachability of a Sink from the Fork
3288 // over the raw routing graph, any class pair -- `validate()` runs
3289 // before refresh_routing, so `Peff` does not exist yet.
3290 std::vector<bool> seen(sn_.nodes.size(), false);
3291 std::vector<std::size_t> stack(1, i + 1);
3292 seen[i] = true;
3293 bool departs = false;
3294 while (!stack.empty() && !departs) {
3295 const std::size_t u = stack.back();
3296 stack.pop_back();
3297 for (std::size_t v = 1; v <= sn_.nodes.size() && !departs; ++v) {
3298 if (seen[v - 1]) continue;
3299 bool edge = false;
3300 for (std::size_t r = 1; r <= K && !edge; ++r)
3301 for (std::size_t s = 1; s <= K; ++s)
3302 if (sn_.get_route(r, s, u, v) > zero) {
3303 edge = true;
3304 break;
3305 }
3306 if (!edge) continue;
3307 if (sn_.nodes[v - 1].nodetype == NodeType::Sink) {
3308 departs = true;
3309 break;
3310 }
3311 seen[v - 1] = true;
3312 stack.push_back(v);
3313 }
3314 }
3315 if (!departs)
3316 throw InputError("Network '" + sn_.name + "': the Fork '" + sn_.nodes[i].name +
3317 "' is not closed by a Join and no Sink is reachable from it, "
3318 "so its siblings can neither merge nor depart");
3319 }
3320 }
3321};
3322
3323} // namespace qn
3324} // namespace line
3325
3326#endif // LINE_LANG_QN_NETWORK_BUILDER_H
Malformed or inconsistent input (dimensions, negative populations, ...): LINE:input:<kind>.
Definition error.h:103
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
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
void set_service_rate_function(std::size_t node, const std::function< T(const std::vector< std::size_t > &)> &muFun, const Matrix< T > &swap_graph=Matrix< T >())
Queue.setServiceRateFunction(muFun): the TOTAL service rate of a PAS or OI station as a function of t...
void set_drop_rule(std::size_t node, std::size_t cls, DropStrategy rule)
void set_state_prior(std::size_t node, const Matrix< T > &space, const std::vector< T > &prior)
StatefulNode.setStatePrior(space, prior): a distribution over the rows of a DECLARED state space.
void set_departure_discipline(std::size_t node, std::size_t cls, lang::DepartureDiscipline rule)
Place.setDepartureDiscipline(class, rule).
std::size_t add_logger(const std::string &nm, const std::string &log_file=std::string())
A Logger node: a pass-through that records every job crossing it.
void set_global_dependence(const GdScaling< T > &fun, const std::vector< T > &peak, int wire_cutoff)
As above, with an explicit per-slot OPEN-class truncation used when phi is materialized onto the JSON...
void set_load_dependence(std::size_t node, const std::vector< T > &alpha)
station.setLoadDependence(alpha): the rate multiplier at population 1, 2, ... The vector is indexed f...
void set_mode_fluid_impulse(std::size_t node, std::size_t mode, std::size_t place, double delta)
Transition.setFluidImpulse(mode, place, delta): every firing of the mode moves the level of the fluid...
void set_class_capacity(std::size_t node, std::size_t cls, double k)
std::size_t add_source(const std::string &nm)
The external arrival station.
std::size_t add_fork(const std::string &nm, double tasks_per_link=1.0)
A Fork node.
void bind_join(std::size_t join_node, std::size_t fork_node)
void set_enabling_conditions(std::size_t node, std::size_t mode, std::size_t cls, std::size_t place, const T &tokens)
Transition.setEnablingConditions(mode, class, place, tokens): how many class-r tokens the mode needs ...
void set_arrival_batch(std::size_t node, std::size_t cls, const Distrib< T > &dist)
Source.setArrivalBatch(class, dist): the batch-size law released at each arrival epoch.
void set_item_routing_prob(std::size_t cache_node, std::size_t read_class, std::size_t item, std::size_t source_node, std::size_t dest_node, const T &p)
Short alias of set_item_routing_probability (Cache.setItemRoutingProb).
double get_fluid_level(std::size_t node)
std::size_t add_open_class(const std::string &nm, int prio=0)
void set_cache_read(std::size_t cache_node, std::size_t r, const std::vector< T > &pmf)
Cache.setRead(jobclass, popularity): class r (1-based) reads the cache, drawing items from the pmf pm...
static void refuse_defective(const Distrib< T > &d, const char *what)
MATLAB Queue.setService / Source.setArrival: a Defective law has an infinite mean,...
void set_mode_timing(std::size_t node, std::size_t mode, lang::TimingStrategy ts)
Transition.setTimingStrategy(mode, strategy): TIMED or IMMEDIATE.
std::size_t add_place(const std::string &nm, SchedStrategy sched)
A Place whose EMBEDDED QUEUE is served under sched: the QUEUEING PLACE of a queueing Petri net,...
Network(const std::string &nm)
void set_firing_weight(std::size_t node, std::size_t mode, const T &w)
Transition.setFiringWeights(mode, weight): the share among tied modes.
void set_class_patience(std::size_t cls, const Distrib< T > &dist, lang::ImpatienceType kind=lang::ImpatienceType::RENEGING)
JobClass.setPatience(kind, dist): the CLASS-WIDE abandonment law.
void set_cache_miss_class(std::size_t cache_node, std::size_t r, std::size_t m)
Cache.setMissClass(jobclass, missclass): a class-r read that misses leaves as class m.
std::size_t add_delay(const std::string &nm)
An infinite-server station (a Delay, MATLAB's Delay / DelayStation).
void set_orbital_search(std::size_t node, std::size_t cls, const T &prob)
Queue.setOrbitalSearch(class, prob): orbital search (Artalejo, Joshua and Krishnamoorthy 2002).
void set_class_spawn(std::size_t cls, std::size_t spawn_cls)
JobClass.spawnClass (sn.classspawn): the class injected at the same station on every completion of cl...
void set_polling_timer(std::size_t node, const std::vector< Distrib< T > > &dists, lang::PollingTimer scope=lang::PollingTimer::LOCAL, bool preemptive=false)
Queue.setPollingTimer(dist, scope, preemptive): a visit timer per class (one law for all classes,...
void set_mode_fluid_dependence(std::size_t node, std::size_t mode, std::size_t place, const std::function< double(double)> &h)
Transition.setFluidRateDependence(mode, place, h): the firing rate of a TIMED, exponential mode is mu...
void set_region_constraint(std::size_t region, const Matrix< T > &A, const std::vector< T > &b)
The optional linear constraint A n <= b a region may carry beyond its caps.
RoutingMatrix< T > init_routing_matrix() const
An empty routing matrix, MATLAB's model.initRoutingMatrix.
std::vector< std::size_t > set_miss_cache(std::size_t cache_node, std::size_t next_cache, const std::vector< std::size_t > &hit_classes_at_next)
Cache.setMissCache(readClass, nextCache, hitClassAtNext): send this cache's misses to next_cache pres...
void set_class_immediate_feedback(std::size_t cls)
jobclass.setImmediateFeedback(): the same property, class-wide.
void set_retrieval_system(std::size_t cache_node, std::size_t read_class, std::size_t miss_class, std::size_t queue_node)
Cache.setRetrievalSystem(readClass, missClass, queue) with a single Queue, as the reference accepts.
void set_mode_distribution(std::size_t node, std::size_t mode, const Distrib< T > &d)
Transition.setDistribution(mode, dist): the mode's firing law.
void set_polling(std::size_t node, lang::PollingType ptype, const std::vector< Distrib< T > > &switchover=std::vector< Distrib< T > >(), std::size_t pk=1)
Queue.setPollingType(...): the polling discipline of a POLLING station and the switchover walks betwe...
bool is_place_fluid(std::size_t node)
Place.isFluid(), getFluidCapacity() and getFluidLevel().
std::size_t add_router(const std::string &nm)
A stateless routing node.
void set_initial_marking(std::size_t node, const std::vector< T > &tokens)
Place.setState(marking): the initial token count of the place, per class.
void set_mode_fluid_rate(std::size_t node, std::size_t mode, std::size_t place, double rate)
Transition.setFluidRate(mode, place, rate): the FSPN flow of a TIMED mode into (rate > 0) or out of (...
void set_inhibiting_conditions(std::size_t node, std::size_t mode, std::size_t cls, std::size_t place, const T &tokens)
Transition.setInhibitingConditions(mode, class, place, tokens): the class-r count at place that BLOCK...
void set_orbit_persistence(std::size_t node, std::size_t cls, const T &join_prob, const T &persist_prob=num_traits< T >::from_int(1))
Queue.setOrbitPersistence(class, joinProb, persistProb): non-persistent retrial customers (Phung-Duc ...
void set_number_of_servers(std::size_t node, double n)
RoutingMatrix< T > serial_routing(const std::vector< std::size_t > &nodes) const
model.serialRouting(nodes): a unit-probability path through nodes.
void set_joint_dependence(std::size_t node, const CdScaling< T > &fun, const std::vector< T > &peak)
station.setJointDependence(eta, peakRatePerClass): MATLAB's Station.ljdScaling / ljdScalingPeak.
bool has_fluid_arcs(std::size_t node) const
Transition.hasFluidArcs(): any mode declares a flow, guard, impulse or fluid rate dependence.
void set_fork_tasks_per_link(std::size_t fork_node, std::size_t jobclass, double tasks, std::size_t dest_node=0)
Variable forking levels on an existing Fork, the twin of MATLAB Fork.setTasksPerLink(jobclass,...
void set_patience(std::size_t node, std::size_t cls, const Distrib< T > &dist, lang::ImpatienceType kind=lang::ImpatienceType::RENEGING)
Queue.setPatience(class, dist, type): the abandonment timer of a job WAITING at the station,...
void set_mode_firing_dependence(std::size_t node, std::size_t mode, const std::function< T(const std::vector< T > &)> &g)
Transition.setFiringRateDependence(mode, g): g(marking) scales the rate.
void set_item_service_rate(std::size_t queue_node, std::size_t cache_node, std::size_t read_class, std::size_t item, const T &rate)
queue.setItemServiceRate(cache, readClass, item, rate) (Queue.m): override, at queue_node,...
void set_reply_signal_class(std::size_t call_cls, std::size_t reply_cls)
JobClass.setReplySignalClass(reply) (sn.syncreply), plus the sn.replyblock the state layer needs.
void set_class_completes(std::size_t cls, bool flag)
jobclass.completes = flag: whether a passage through the reference station counts as a completion.
std::size_t add_queue(const std::string &nm, SchedStrategy sched=SchedStrategy::FCFS)
A queueing station.
void set_class_switch_matrix(std::size_t node, const Matrix< T > &C)
Install the switching matrix of a ClassSwitch created without one.
void set_routing(std::size_t node, std::size_t cls, RoutingStrategy rs)
node.setRouting(class, strategy).
std::size_t add_transition(const std::string &nm)
A Transition with NO modes yet: Transition(model, name) as MATLAB, the JAR and Python spell it,...
void set_join_strategy(std::size_t node, lang::JoinStrategy strategy, double quorum=0.0)
Join.setStrategy(...): STD waits for every sibling, PARTIAL for a quorum.
void set_fork_branch_probability(std::size_t fork_node, std::size_t jobclass, std::size_t dest_node, double prob)
A branch that fires only with probability prob.
void set_item_routing_probability(std::size_t cache_node, std::size_t read_class, std::size_t item, std::size_t source_node, std::size_t dest_node, const T &p)
Cache.setItemRoutingProbability(readClass, item, source, dest, p): the probability of routing the ret...
std::size_t add_cache(const std::string &nm, const CacheParam< T > &par)
A Cache node with its item population, list capacities and popularity.
void set_cache_read(std::size_t cache_node, std::size_t r, const lang::Distrib< T > &d)
Cache.setRead(jobclass, Zipf(s, n)) or DiscreteSampler(p): the law is expanded to its pmf,...
void set_reward(const std::string &nm, const std::function< T(const std::vector< T > &)> &fn, const std::string &kind=std::string(), std::size_t node=0, std::size_t cls=0)
model.setReward(name, fn): a named reward evaluated on the AGGREGATE state row, the per-(station,...
void set_fluid_capacity(std::size_t node, double cap)
Place.setFluidCapacity(B): the level ceiling of a fluid place, Inf when unbounded.
std::size_t add_mode(std::size_t node, const std::string &nm)
Transition.addMode(name): a new firing mode, returning its 1-based index.
std::size_t add_self_looping_class(const std::string &nm, double njobs, std::size_t refstat_node, int prio=0)
SelfLoopingClass(model, name, njobs, refstat, prio): a closed class whose jobs perpetually cycle at t...
void set_marked_classes(std::size_t node, const std::vector< std::size_t > &classes)
Source.markedClasses: the 1-based class carried by each mark of an MMAP.
std::size_t add_closed_class(const std::string &nm, double njobs, std::size_t refstat_node, int prio=0)
void set_sched_param(std::size_t node, std::size_t cls, const T &weight)
The DPS / GPS weight of a class at a station.
std::size_t add_class_switch(const std::string &nm, const Matrix< T > &C)
A ClassSwitch node carrying the (nclasses x nclasses) switching matrix.
void set_fork_tasks_per_link_dist(std::size_t fork_node, std::size_t jobclass, const lang::Distrib< T > &dist, std::size_t dest_node=0)
A random jobs-per-link degree, redrawn per link and per forked job.
void set_firing_priority(std::size_t node, std::size_t mode, double prio)
Transition.setFiringPriorities(mode, priority).
std::vector< std::vector< bool > > get_class_switching_mask()
model.getClassSwitchingMask(): entry (r-1, s-1) is true if some node can switch class r into s.
std::size_t add_sink(const std::string &nm)
The external departure node.
const NetworkStruct< T > & get_struct()
The refreshed struct, MATLAB's model.getStruct().
std::size_t add_class_switch(const std::string &nm)
A ClassSwitch node whose matrix is installed LATER, by set_class_switch_matrix.
void set_batch_reject(std::size_t node, std::size_t cls, const T &p)
Queue.setBatchRejectProbability(class, p).
void set_polling_order(std::size_t node, lang::PollingOrder order, std::size_t prioclass=0, long threshold=-1)
Queue.setPollingOrder(order, prioclass, L): the visit-order rule.
void set_class_dependence(std::size_t node, const CdScaling< T > &fun, const std::vector< T > &peak=std::vector< T >())
station.setClassDependence(beta, peakRatePerClass).
void set_fluid_level(std::size_t node, double level)
Place.setFluidLevel(x0): the initial level of a fluid place.
void set_state_dep_routing(std::size_t entry, std::size_t departure, const std::vector< std::vector< std::size_t > > &branches, const std::vector< std::size_t > &level, const std::vector< double > &C, const Matrix< double > &d, std::size_t cls=0)
node.setStateDepRouting(class, departure, branches, level, C, d).
std::size_t add_place(const std::string &nm)
A Place: an SPN token container.
void set_routing_weights(std::size_t node, std::size_t cls, const std::map< std::size_t, double > &weights)
The per-destination weights of a WRROBIN dispatcher, per (node, class).
void set_mode_fluid_flow_dependence(std::size_t node, std::size_t mode, std::size_t place, const std::function< double(const std::vector< double > &)> &phi, const std::vector< std::size_t > &read=std::vector< std::size_t >())
Transition.setFluidFlowDependence(mode, place, phi, readPlaces): the flow of the mode into or out of ...
void set_item_miss_class(std::size_t cache_node, const std::vector< std::size_t > &miss_classes)
Cache.setItemMissClass(readClass, missClasses): terminate a cache network, every per-item class of th...
void set_log_path(const std::string &path)
Network.setLogPath: the directory every Logger of this model writes into.
void set_capacity(std::size_t node, double k)
station.setCapacity(k), the K of Kendall's notation.
NetworkStruct< T > & raw_struct()
The struct WITHOUT refreshing it, for a caller that is still building.
void set_switchover(std::size_t node, std::size_t cls, const Distrib< T > &so)
Queue.setSwitchover(jobclass, distrib): the switchover time of a class.
void set_cache_hit_class(std::size_t cache_node, std::size_t r, std::size_t h)
Cache.setHitClass(jobclass, hitclass): a class-r read that hits leaves as class h.
void set_place_fluid(std::size_t node, bool fluid)
Place.setFluid(flag): the place holds one real level in [0, fluid capacity] instead of tokens,...
void set_immediate_feedback(std::size_t node, std::size_t cls)
queue.setImmediateFeedback(class): a completing job of that class is fed straight back into service,...
static void refuse_defective_patience(const Distrib< double > &d)
void set_balking(std::size_t node, std::size_t cls, lang::BalkingStrategy strategy, const std::vector< typename Station< T >::BalkingThreshold > &thresholds)
Queue.setBalking(class, strategy, thresholds): an arrival that refuses to JOIN, on the state it finds...
void set_polling_table(std::size_t node, const std::vector< std::size_t > &table, const std::vector< Distrib< T > > &swlegs=std::vector< Distrib< T > >())
Queue.setPollingTable(table, swlegs): the visit sequence of a POLLING station (1-based classes,...
void add_server_type(std::size_t node, const typename Station< T >::ServerType &stype)
Queue.addServerType(...): one heterogeneous server pool of the station.
void set_quantum(std::size_t node, std::size_t cls, const Distrib< T > &q)
Queue.setQuantum(jobclass, distrib): the time slice of a class at a round-robin station.
void set_setup_delayoff(std::size_t node, std::size_t cls, const Distrib< T > &setup, const Distrib< T > &delayoff)
Queue.setDelayOff(class, setupTime, delayoffTime): the station powers down after sitting idle for the...
void set_retrieval_system(std::size_t cache_node, std::size_t read_class, std::size_t miss_class, const std::vector< std::size_t > &queue_nodes)
Cache.setRetrievalSystem(readClass, missClass, queues): a delayed-hit cache whose misses are fetched ...
void set_class_deadline(std::size_t cls, double due)
JobClass.deadline: the soft deadline EDD, EDF and JMT's tardiness use.
void link(const RoutingMatrix< T > &Pm)
model.link(P): install the routing.
void set_routing_param(std::size_t node, std::size_t cls, int d)
The d of a power-of-d (SQ) dispatcher, per (node, class).
void set_retrial(std::size_t node, std::size_t cls, const Distrib< T > &proc, const T &rate, int max_attempts=0)
Queue.setRetrial(...): a station with an ORBIT instead of a waiting line.
void set_service(std::size_t node, std::size_t cls, const Distrib< double > &d)
void set_reference_class(std::size_t cls)
JobClass.setReferenceClass(true): sn.refclass(c) picks this class.
void pas_mirror(std::size_t ist, const std::function< double(const std::vector< std::size_t > &)> &mu, const Matrix< double > &swap_graph)
std::size_t add_join_unbound(const std::string &nm)
void set_hetero_sched_policy(std::size_t node, lang::HeteroSchedPolicy policy)
Queue.setHeteroSchedPolicy(...): how the server pools are picked among.
void set_limited_load_dependence(std::size_t node, const std::vector< double > &alpha)
std::size_t add_join(const std::string &nm, std::size_t fork_node)
A Join node, which IS a station: it serves at an infinite rate, and the synchronisation delay is supp...
void set_breakdown(std::size_t node, const Distrib< T > &failure, const Distrib< T > &repair, const std::vector< Distrib< T > > &down_service=std::vector< Distrib< T > >())
Queue.setBreakdown(failure, repair, downService): the server alternates up and down on the two clocks...
void set_pas(std::size_t node, const std::function< T(const std::vector< std::size_t > &)> &mu, const std::vector< std::vector< bool > > &swap_graph=std::vector< std::vector< bool > >())
Queue.setService(@(c) ...) for a pass-and-swap / order-independent station: the total service rate mu...
void set_item_read_classes(std::size_t cache_node, const std::vector< std::size_t > &read_classes, const std::vector< std::size_t > &hit_classes)
Cache.setItemReadClasses(readClasses, hitClasses): declare that read_classes[i] is the request stream...
void set_mode_servers(std::size_t node, std::size_t mode, double n)
Transition.setNumberOfServers(mode, n); GlobalConstants::MaxInt is infinite.
void set_switchover(std::size_t node, std::size_t from_cls, std::size_t to_cls, const Distrib< T > &so)
Queue.setSwitchover(fromClass, toClass, distrib): the walk between two CLASSES at an ordinary station...
void set_firing_outcome(std::size_t node, std::size_t mode, std::size_t cls, std::size_t dest, const T &tokens)
Transition.setFiringOutcome(mode, class, node, tokens): the class-r tokens the firing deposits.
std::size_t add_transition(const std::string &nm, const TransitionParam< T > &par)
A Transition: the firing rules of an SPN, as Transition in MATLAB.
void set_orbit_impatience(std::size_t node, std::size_t cls, const Distrib< T > &dist)
Queue.setOrbitImpatience(class, dist): abandonment from the retrial orbit.
void set_sync_reply(std::size_t node, std::size_t call_cls, std::size_t reply_cls)
Declare a SYNCHRONOUS call: a job of call_cls leaving node keeps its server until a job of the REPLY ...
void set_signal(std::size_t cls, lang::SignalType type, lang::RemovalPolicy policy=lang::RemovalPolicy::RANDOM, std::size_t target=0, const std::vector< double > &remdist=std::vector< double >())
void set_global_dependence(const GdScaling< T > &fun, const std::vector< T > &peak)
model.setGlobalDependence(phi, peak): MATLAB's Network.gdScaling.
void set_server_parallelism(std::size_t node, std::size_t cls, std::size_t n)
Queue.setServerParallelism(class, n): the servers a job seizes for the whole of its service.
std::size_t station_index(std::size_t node) const
void set_orbit_policy(std::size_t node, std::size_t cls, int policy, int max_orbit, bool size_buffer=true)
The policy and bound of Queue.setOrbit(class, dist, policy, maxOrbit) on a class already declared by ...
void set_region_weights(std::size_t region, const std::vector< T > &weight)
FiniteCapacityRegion.setClassWeight: the per-class weight the region's global cap counts a job agains...
void set_quantum(std::size_t node, const Distrib< T > &q)
Queue.setQuantum(distrib): the same time slice for every class.
void set_arrival(std::size_t node, std::size_t cls, const Distrib< T > &d)
source.setArrival(class, dist): the same table, at the Source.
std::size_t add_region(const std::vector< std::size_t > &nodes, const std::vector< double > &class_max_jobs, double global_max_jobs=-1.0, const std::vector< DropStrategy > &rule=std::vector< DropStrategy >(), const std::vector< double > &class_max_memory=std::vector< double >(), const std::vector< T > &class_size=std::vector< T >(), double global_max_memory=-1.0, const std::string &name=std::string())
FiniteCapacityRegion(model, nodes): a cap on the jobs held ACROSS a set of stations.
void set_mode_fluid_guard(std::size_t node, std::size_t mode, std::size_t place, const std::string &op, double threshold)
Transition.setFluidGuard(mode, place, op, threshold): the mode is enabled only while the level of the...
double get_fluid_capacity(std::size_t node)
void set_polling_type(std::size_t node, lang::PollingType rule, int par=0)
Queue.setPollingType(rule, par): the polling discipline of a POLLING station, identical across all cl...
The routing matrix a model script fills in, MATLAB's P cell array.
void set(std::size_t cls, const RoutingMatrix< T > &block)
P.set(class, Network.serialRouting(...)): install a one-class block.
T get(std::size_t r, std::size_t s, std::size_t i, std::size_t j) const
void set(std::size_t r, std::size_t s, std::size_t i, std::size_t j, const T &p)
void set(std::size_t i, std::size_t j, const T &p)
std::map< Key, double > entries
What refreshProcessRepresentations and refreshLST compute FROM a distribution: the (D0,...
The exception types the port throws.
Dense matrix and non-owning view.
std::vector< std::string > sn_validate_contract(const SnFieldViews &views, bool error=false)
The contract violations of a field view; with error true, throws InternalError with id LINE:internal:...
void sn_fj_nodevisits_mmt(qn::NetworkStruct< T > &sn)
Rewrite sn.nodevisits with the MMT correction.
bool sn_validate_requested()
True when get_struct should validate: debug verbosity, or LINE_VALIDATE_SN=1.
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
TimingStrategy
SPN transition timing, with the values of MATLAB TimingStrategy.
Definition lang_types.h:382
@ IMMEDIATE
fires with zero delay, resolved by weight and priority
Definition lang_types.h:384
@ TIMED
fires after its firing distribution elapses
Definition lang_types.h:383
BalkingStrategy
Balking rules, with the values of MATLAB BalkingStrategy.
Definition lang_types.h:486
SignalType
G-network signal classes, with the values of MATLAB SignalType.
Definition lang_types.h:180
@ REPLY
completes a synchronous call, releasing a held server
Definition lang_types.h:181
@ NEGATIVE
removes a batch of jobs (Gelenbe's negative customer)
Definition lang_types.h:182
PollingOrder
Visit-order rules of a polling server, with the values of MATLAB PollingOrder.
Definition lang_types.h:404
@ THRESHOLD
a priority buffer above its threshold, else SKIPEMPTY
Definition lang_types.h:408
@ CYCLIC
fixed cyclic order (or the polling table)
Definition lang_types.h:405
void prior_refresh_moments(Distrib< T > &d)
Write the mixture moments onto a Prior, the counterpart of dist_refresh_moments for the Markovian fam...
Definition prior.h:346
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
@ LOCAL
a timer per visit, drawn at the polling instant
Definition lang_types.h:414
@ NONE
no visit timer
Definition lang_types.h:413
DepartureDiscipline
When a Place releases a served token, MATLAB DepartureDiscipline.
Definition lang_types.h:499
RemovalPolicy
Which job a negative signal removes, with the values of MATLAB RemovalPolicy.
Definition lang_types.h:187
@ RANDOM
uniform over waiting AND in-service jobs
Definition lang_types.h:188
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
@ GLIMITED
serve at most K of the jobs present at the polling instant
Definition lang_types.h:396
std::function< std::vector< T >(const std::vector< T > &)> GdScaling
A globally state-dependent scaling, sn.gdscaling.
Definition lang_types.h:807
std::function< std::vector< T >(const std::vector< T > &)> CdScaling
A class-dependent scaling map, sn.cdscaling.
Definition lang_types.h:794
void dist_refresh_moments(Distrib< T > &d)
Fill in the first two moments of a distribution given by its matrices.
NodeType
Node kinds, with the values of MATLAB NodeType.
Definition lang_types.h:345
ImpatienceType
Impatience kinds, with the values of MATLAB ImpatienceType.
Definition lang_types.h:483
SdrCoeff pfqn_sdrcoeff(const SdrStruct &sdr)
Validates an SDR structure and returns its derived coefficients.
Definition pfqn_sdr.h:105
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....
std::vector< Frame > & stack()
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
Number-type abstraction for the templated API port.
Prior: parameter uncertainty as a weighted set of alternative models.
Post-MMT node visits of a fork-join model.
Check a NetworkStruct against its contract (sn_contract.h): the C++ twin of MATLAB's sn_validate.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
std::string name
Definition error.h:38
std::vector< T > params
Constructor arguments, in MATLAB getParam order.
Definition lang_types.h:894
std::vector< T > trace
Replayer / Trace samples; empty for every other type.
Definition lang_types.h:896
bool is_prior() const
Definition lang_types.h:961
Topology and coefficients of a state-dependent routing subnetwork.
Definition pfqn_sdr.h:59
std::vector< std::size_t > departureOf
departureOf[b] is the departure centre d(b) of branch b.
Definition pfqn_sdr.h:69
std::vector< std::size_t > entryOf
entryOf[b] is the entry centre e(b) of branch b.
Definition pfqn_sdr.h:67
std::vector< std::size_t > level
level[b] is the unique t with B_b in V_t - V_{t+1}; level[0] is unused.
Definition pfqn_sdr.h:71
Matrix< double > d
Coefficients d_tb of eq.
Definition pfqn_sdr.h:75
std::vector< double > C
Coefficients C_t of eq.
Definition pfqn_sdr.h:73
std::size_t departure
Departure centre d of Q(V,V); may equal entry.
Definition pfqn_sdr.h:63
std::vector< std::vector< std::size_t > > branch
branch[b] holds the centres of branch b, b >= 1; branch[0] is unused.
Definition pfqn_sdr.h:65
std::size_t entry
Entry centre e of Q(V,V).
Definition pfqn_sdr.h:61
Server breakdown and repair of a station whose server fails and is repaired.
T failure_rate
sn.breakdownMu: 1 / mean failure time
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).
std::vector< Popularity > preadkind
per class, parallel to pread
std::map< std::size_t, std::vector< std::size_t > > retrieval_queues
read class(0-based)->nodes
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
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
static Distrib exp_rate(const T &r)
static Distrib disabled_dist()
static Distrib immediate()
The point mass at zero.
One job class of the network.
std::size_t refstat
1-based reference station
double population
infinite for an open class
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...
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 > > switchover
FINITE CAPACITY REGIONS, MATLAB's refreshRegions output.
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
sn.reward: the user-declared reward functions, MATLAB's model.setReward(name, fn).
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 node of the network.
std::vector< RoutingStrategy > routing
sn.routing, per class.
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).
Key(std::size_t r_, std::size_t s_, std::size_t i_, std::size_t j_)
bool operator<(const Key &o) const
Setup and delay-off of a station that powers down when it falls idle.
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.
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...
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 ...
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< 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).
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
std::vector< T > orbit_search
Queue.setOrbitalSearch(class, theta), MATLAB sn.orbitSearchProb: on a service completion at a retrial...
lang::PollingTimer polling_timer_scope
std::vector< T > orbit_persist
std::vector< bool > immfeed
Node-level immediate feedback, per class; empty when the station sets none.
A fluid rate dependence: the firing rate is multiplied by fun(level(node)).
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,...
std::vector< std::vector< FluidDep > > fluiddep
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
std::vector< double > nmodeservers
servers per mode, may be infinite
std::vector< T > fireweight
weight among simultaneously enabled modes
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.
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).
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