LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
state_events.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_STATE_EVENTS_H
6#define LINE_LANG_QN_STATE_EVENTS_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * Port of the event half of MATLAB's `+State` package: the successor states an
12 * event produces at one node, with their rates and probabilities. This is what
13 * turns the enumerated state space of `state.h` into a generator.
14 *
15 * THE ACTIVE / PASSIVE CONVENTION. An event is ACTIVE at the node that
16 * schedules it and PASSIVE at the node that receives it -- a DEP at one station
17 * IS the ARV at the next. Only the active half knows a rate, so the passive
18 * half returns the sentinel -1 and the generator assembly substitutes the
19 * active rate. The sentinel is unambiguous because a rate is never negative.
20 *
21 * WHY PROBABILITIES ARE SEPARATE FROM RATES. One event can have several
22 * successors: an entering job picks its service phase, a signal picks the job
23 * it removes, a random-order queue picks whom to serve. The rate belongs to the
24 * event and the probability to the choice, so a single (state, event) pair
25 * yields a ROW of successors and the generator entry is rate * prob.
26 */
27
28#include <cmath>
29#include <cstddef>
30#include <limits>
31#include <algorithm>
32#include <functional>
33#include <string>
34#include <utility>
35#include <vector>
36
44#include "line/lang/qn/state.h"
45#include "line/util/error.h"
46
47namespace line {
48namespace qn {
49
50using lang::EventType;
51
52/**
53 * What one event produces at one node: the successor rows, their rates and
54 * their probabilities, all three the same length.
55 */
56template <class T>
58 std::vector<std::vector<T>> space; ///< successor local state rows
59 std::vector<T> rate; ///< per-row rate, -1 on a passive half
60 std::vector<T> prob; ///< per-row probability of the choice
61 /// START annotation: the 1-based classes that BEGIN or RESUME holding a
62 /// server on each successor row. An instantaneous tag on the arc the row
63 /// already carries, never an event of its own, so no rate, probability or
64 /// state depends on it. Usually empty; kept as a list so one arc can start
65 /// several jobs (a region release cascade does).
66 std::vector<std::vector<std::size_t>> start;
67 /// PREEMPT annotation: the 1-based classes pushed back into the buffer.
68 std::vector<std::vector<std::size_t>> preempt;
69 bool empty() const { return space.empty(); }
70};
71
72/**
73 * Tag the successor row just appended to OUT: START_CLS begins service on it
74 * and PREEMPT_CLS is displaced by it, either 0 for none. The tag vectors are
75 * grown to match `space`, so only the arcs that carry a tag need to say
76 * anything and every other row is an empty list.
77 */
78template <typename T>
79inline void tag_last(EventOutcome<T>& out, std::size_t start_cls, std::size_t preempt_cls) {
80 if (out.space.empty()) return;
81 out.start.resize(out.space.size());
82 out.preempt.resize(out.space.size());
83 if (start_cls) out.start.back().push_back(start_cls);
84 if (preempt_cls) out.preempt.back().push_back(preempt_cls);
85}
86
87/**
88 * Bring the tag vectors up to one entry per successor, so a caller can index
89 * them exactly like `space`.
90 */
91template <typename T>
92inline void pad_tags(EventOutcome<T>& out) {
93 out.start.resize(out.space.size());
94 out.preempt.resize(out.space.size());
95}
96
97/**
98 * Port of `State.toMarginalAggr`: the job counts of one node's state row,
99 * without the per-phase detail `to_marginal` also computes.
100 *
101 * It is NOT simply a projection of `to_marginal`: it accepts stateful
102 * non-stations (whose row is a plain per-class count ahead of the local
103 * variables), and it leaves the preemptive families out of its buffer switch,
104 * so for those it reports only the jobs IN SERVICE. That asymmetry is the
105 * reference's, and it is load-bearing -- the arrival branch uses this to test
106 * for room, where counting a preempted job twice would refuse a valid arrival.
107 *
108 * @param sn the network struct
109 * @param ind NODE index (1-based), as in the reference
110 * @param state_i the node's state row
111 * @return (ni, nir): total jobs and jobs per class
112 */
113template <class T>
114std::pair<T, std::vector<T>> to_marginal_aggr(const NetworkStruct<T>& sn, std::size_t ind,
115 const std::vector<T>& state_i) {
116 const std::size_t R = sn.nclasses;
117 const T zero = num_traits<T>::from_int(0);
118 std::vector<T> nir(R, zero);
119 if (ind == 0 || ind > sn.nodes.size())
120 throw InputError("to_marginal_aggr: node index is out of range");
121 const NodeDef& nd = sn.nodes[ind - 1];
122 const std::size_t ist = nd.station;
123 const std::size_t nvar = sn.nvars_of(ind);
124
125 // A Join of an FJ-augmented struct is a station whose row is a bare per-class
126 // count: it holds jobs waiting to synchronize, with no buffer/phase split and
127 // no service at all, so the station path below would read its counts as
128 // buffer tags.
129 if (sn.isfjaugmented && nd.nodetype == NodeType::Join && state_i.size() >= R) {
130 T ni = zero;
131 for (std::size_t r = 0; r < R; ++r) {
132 nir[r] = state_i[state_i.size() - R + r];
133 ni += nir[r];
134 }
135 return std::make_pair(ni, nir);
136 }
137
138 // A stateful non-station carries a per-class count ahead of its local
139 // variables. A node with nothing but bookkeeping (a Router's round-robin
140 // pointer) still has to report R zeros, so callers can index nir[r].
141 if (ist == 0) {
142 const std::size_t bufw = state_i.size() > nvar ? state_i.size() - nvar : 0;
143 for (std::size_t r = 0; r < R && r < bufw; ++r) nir[r] = state_i[r];
144 T ni = zero;
145 for (std::size_t r = 0; r < R; ++r) ni += nir[r];
146 return std::make_pair(ni, nir);
147 }
148
149 // A Source reports zero, not Inf: its jobs are external, and the EXT
150 // sentinel `to_marginal` returns describes the encoding, not a count that
151 // an arrival branch could compare against a capacity.
152 if (nd.nodetype == NodeType::Source) return std::make_pair(zero, nir);
153
154 std::vector<std::size_t> K(R, 1), Ks(R, 0);
155 std::size_t srvw = 0;
156 for (std::size_t r = 0; r < R; ++r) {
157 K[r] = sn.phasessz_of(ist, r + 1);
158 Ks[r] = srvw;
159 srvw += K[r];
160 }
161 if (state_i.size() < nvar + srvw)
162 throw InputError("to_marginal_aggr: state row is narrower than its server block");
163 const std::size_t srv0 = state_i.size() - nvar - srvw;
164
165 for (std::size_t r = 0; r < R; ++r)
166 for (std::size_t k = 0; k < K[r]; ++k) nir[r] += state_i[srv0 + Ks[r] + k];
167
168 const SchedStrategy sched = sn.stations[ist - 1].sched;
169 if (sched == SchedStrategy::EXT) {
170 // Reached only by an EXT station that is not a Source node, since the
171 // Source returns zero above. It carries the same clamp as `to_marginal`
172 // and for the same reason: an exact type has no infinity, and building
173 // one from a double Inf throws rather than saturating.
174 const T ext = num_traits<T>::is_exact
177 std::numeric_limits<double>::infinity());
178 for (std::size_t r = 0; r < R; ++r) nir[r] = ext;
179 } else if (state_detail::buffer_is_class_tag(sched)) {
180 for (std::size_t r = 0; r < R; ++r) {
181 const T tag = num_traits<T>::from_int(static_cast<long>(r + 1));
182 for (std::size_t b = 0; b < srv0; ++b)
183 if (state_i[b] == tag) nir[r] += num_traits<T>::from_int(1);
184 }
185 } else if (state_detail::buffer_is_tag_phase_pairs(sched)) {
186 // Only the EVEN positions are class tags; the odd ones record the phase
187 // each preempted job was interrupted in. Without this arm a preempted
188 // job was invisible here and nir counted the server alone, unlike
189 // `to_marginal`, which has carried the paired decode all along.
190 if (srv0 > 1)
191 for (std::size_t r = 0; r < R; ++r) {
192 const T tag = num_traits<T>::from_int(static_cast<long>(r + 1));
193 for (std::size_t b = 0; b < srv0; b += 2)
194 if (state_i[b] == tag) nir[r] += num_traits<T>::from_int(1);
195 }
196 } else if (state_detail::buffer_is_per_class_count(sched)) {
197 for (std::size_t r = 0; r < R && r < srv0; ++r) nir[r] += state_i[r];
198 } else if (sched == SchedStrategy::PAS || sched == SchedStrategy::OI) {
199 // A PAS / OI row is the ORDERED JOB LIST and nothing else: entry `b` is
200 // the 1-based class of the job in position b, 0 for an empty slot, which
201 // is the encoding `after_event_station_pas` reads and writes. It has no
202 // buffer/server split at all, so the server-block sum taken above
203 // counted the LAST LIST POSITION as a phase occupancy -- it is discarded
204 // here and the whole row is scanned instead.
205 //
206 // WITHOUT THIS BRANCH the station reports a queue length of about zero
207 // while the jobs are demonstrably in it, in EVERY solver that reduces a
208 // state through this function (SolverCTMC's `solver_ctmc_avg_from_pi`
209 // and SolverSSA's serial analyzer both do), and the capacity filter in
210 // `after_event_station_arv` compares that zero against the station's
211 // bound. A wrong NUMBER, never an error.
212 for (std::size_t r = 0; r < R; ++r) nir[r] = zero;
213 const std::size_t w = state_i.size() > nvar ? state_i.size() - nvar : 0;
214 for (std::size_t b = 0; b < w; ++b) {
215 const double v = num_traits<T>::to_double(state_i[b]);
216 const long tag = static_cast<long>(v + 0.5);
217 if (tag >= 1 && static_cast<std::size_t>(tag) <= R)
218 nir[tag - 1] += num_traits<T>::from_int(1);
219 }
220 }
221
222 // A disabled class holds no jobs whatever the row says. A Place is exempt:
223 // its tokens are not services, so it has no rate to be disabled.
224 if (nd.nodetype != NodeType::Place)
225 for (std::size_t r = 0; r < R; ++r)
226 if (sn.disabled[ist - 1][r]) nir[r] = zero;
227
228 T ni = zero;
229 for (std::size_t r = 0; r < R; ++r) ni += nir[r];
230 return std::make_pair(ni, nir);
231}
232
233/**
234 * Port of `State.isPhysicalCapacity`: true when the bound at (ist, class) is a
235 * PHYSICAL capacity rather than a state-space CUTOFF on an open class.
236 *
237 * The distinction decides what a refused arrival means. The producer's
238 * capacity arguments have the cutoff folded in -- `solver_ssa` overwrites
239 * cap/classcap with min(cutoff, physical) -- so at a cutoff boundary they read
240 * finite even with no physical cap. Treating that as physical would turn a
241 * state-space TRUNCATION into a self-loop loss, which reports a wrong arrival
242 * rate and perturbs the sample path.
243 *
244 * The in-producer signal is the DROP RULE: `refreshCapacity` sets a non-WAITQ
245 * rule exactly when the capacity is physical, and a cutoff-bounded open class
246 * keeps the WAITQ default.
247 */
248template <class T>
249bool is_physical_capacity(const NetworkStruct<T>& sn, std::size_t ist, std::size_t cls) {
250 if (sn.droprule.size() < ist || sn.droprule[ist - 1].size() < cls) return false;
251 const DropStrategy dr = sn.droprule[ist - 1][cls - 1];
252 return dr != DropStrategy::WAITQ && static_cast<int>(dr) != 0;
253}
254
255/**
256 * Port of `State.arrivalIsLost`: true when an arrival that finds no room is
257 * LOST, false when it must BLOCK the upstream instead. Every refusal path
258 * branches on this, and the two outcomes are encoded differently:
259 *
260 * LOST -> leave the state UNCHANGED, a self-loop. The event still fires,
261 * so the OFFERED job reaches the arrival-rate statistic and the
262 * loss appears as ArvR - Tput. A self-loop cancels on the
263 * generator diagonal, so it cannot move the stationary law.
264 * BLOCKED -> return NO rows. That disables the upstream departure until room
265 * frees, which is what the become-blocked edge tests for.
266 *
267 * The rule is the CLASS TYPE, not the drop rule: a closed network's population
268 * is a defining invariant, so a closed job can never be dropped. An explicit
269 * BAS/BBS/RSRD rule asks for blocking for any class.
270 */
271template <class T>
272bool arrival_is_lost(const NetworkStruct<T>& sn, std::size_t ist, std::size_t cls) {
273 if (sn.droprule.size() >= ist && sn.droprule[ist - 1].size() >= cls) {
274 const DropStrategy dr = sn.droprule[ist - 1][cls - 1];
275 if (dr == DropStrategy::BAS || dr == DropStrategy::BBS || dr == DropStrategy::RSRD)
276 return false; // the user asked for blocking explicitly
277 }
278 // The rule above sees only THIS station's declaration. Under the upstream
279 // declaration form the BAS rule sits on the blocking station, not on the
280 // destination where the refusal happens, so the destination side is recorded
281 // separately by `refresh_bas_blocking`. Without this branch an open class
282 // refused here would be declared lost, the become-blocked edge would never
283 // fire, and the blocking station would behave as if its destination were
284 // unbounded.
285 if (sn.isbasdestination.size() >= ist && sn.isbasdestination[ist - 1].size() >= cls &&
286 sn.isbasdestination[ist - 1][cls - 1])
287 return false;
288 // Open -> lost, closed -> blocked. This decides only what happens once the
289 // arrival has already been refused, never whether it is refused.
290 const double nj = sn.njobs()[cls - 1];
291 return !std::isfinite(nj);
292}
293
294/** How a station's state row splits into [buffer | server | local vars]. */
295template <class T>
296struct RowLayout {
297 std::vector<std::size_t> K; ///< phases per class
298 std::vector<std::size_t> Ks; ///< offset of class r's phase block
299 std::size_t srvw = 0; ///< total server width
300 std::size_t nvar = 0; ///< local-variable width
301 std::size_t bufw = 0; ///< buffer width, the only discipline-dependent part
302};
303
304template <class T>
305RowLayout<T> row_layout(const NetworkStruct<T>& sn, std::size_t ind, std::size_t width) {
306 const std::size_t R = sn.nclasses;
307 const std::size_t ist = sn.nodes[ind - 1].station;
308 RowLayout<T> L;
309 L.K.assign(R, 1);
310 L.Ks.assign(R, 0);
311 for (std::size_t r = 0; r < R; ++r) {
312 L.K[r] = sn.phasessz_of(ist, r + 1);
313 L.Ks[r] = L.srvw;
314 L.srvw += L.K[r];
315 }
316 L.nvar = sn.nvars_of(ind);
317 if (width < L.nvar + L.srvw)
318 throw InputError("after_event_station: the state row is narrower than its server block");
319 L.bufw = width - L.nvar - L.srvw;
320 return L;
321}
322
323/**
324 * The entry-phase distribution `pie{ist}{class}`: which phase a service STARTS
325 * in. This is `map_pie`, the equilibrium embedded at DEPARTURE instants, and
326 * NOT `map_prob`, the time-stationary law of D0+D1 -- the two differ whenever
327 * the process is not exponential (for Erlang-2, entry is [1,0] while the
328 * time-stationary law is [0.5,0.5]).
329 *
330 * A Place has no service process, so its "phases" carry no rate; the reference
331 * falls back on a uniform choice there rather than leaving the vector NaN.
332 */
333template <class T>
334std::vector<T> entry_phase_dist(const NetworkStruct<T>& sn, std::size_t ist, std::size_t cls) {
335 const std::size_t nph = sn.phases_of(ist, cls);
336 const lang::Distrib<T>& d = sn.service[ist - 1][cls - 1];
337 std::vector<T> pie;
338 if (d.D0.rows() == nph && d.D1.rows() == nph && nph > 0 && !d.disabled) {
339 mam::Map<T> m;
340 m.D0 = d.D0;
341 m.D1 = d.D1;
342 try {
343 pie = mam::map_pie(m);
344 } catch (const Error&) {
345 pie.clear(); // a zero-rate process has no entry law; fall back below
346 }
347 }
348 bool ok = pie.size() == nph;
349 if (ok) {
351 for (std::size_t k = 0; k < nph; ++k) s += pie[k];
352 ok = num_traits<T>::to_double(s) > 0 && std::isfinite(num_traits<T>::to_double(s));
353 }
354 if (!ok) {
355 pie.assign(nph, num_traits<T>::from_int(0));
356 if (nph > 0) {
358 static_cast<long>(nph)));
359 for (std::size_t k = 0; k < nph; ++k) pie[k] = u;
360 }
361 }
362 return pie;
363}
364
365/** Where node `ind` keeps its reply-block counters inside the local vars. */
367 std::vector<std::size_t> classes; ///< 1-based calling classes holding a block
368 std::vector<std::size_t> slot; ///< slot[r-1] = 0-based column, or npos
369 std::size_t width = 0;
370};
371
372/** Defined below; the polling branches of ARV, DEP and SWITCH use these. */
373template <class T>
374void polling_get(const PollingInfo<T>& pi, const std::vector<T>& var, std::size_t srvclass,
375 std::size_t& pos, std::size_t& swk, long& ctr);
376template <class T>
377std::vector<T> polling_set(const PollingInfo<T>& pi, std::vector<T> var, std::size_t pos,
378 std::size_t swk, long ctr);
379template <class T>
380void polling_next(const PollingInfo<T>& pi, std::size_t pos, const std::vector<long>& nbuf,
381 std::size_t R, bool arrived, std::size_t& q, int& mode, long& budget);
382template <class T>
383void polling_land(const NetworkStruct<T>& sn, std::size_t ist, const PollingInfo<T>& pi,
384 std::size_t q, int mode, long budget, const std::vector<T>& buf,
385 const std::vector<T>& srv, const std::vector<T>& var, const RowLayout<T>& L,
386 std::vector<std::vector<T>>& rows, std::vector<T>& probs);
387
388/** The outcomes of `State.pollingAdvance`: full controller rows with weights. */
389template <class T>
391 std::vector<std::vector<long>> C; ///< full controller vectors, width 5+R
392 std::vector<int> mode; ///< 1 visit, 2 switchover, 0 park
393 std::vector<std::size_t> q; ///< the class a visit serves
394 std::vector<T> prob;
395};
396template <class T>
397std::vector<long> polling_get_full(const PollingInfo<T>& pi, const std::vector<T>& var, std::size_t srvclass);
398template <class T>
399std::vector<T> polling_set_full(const PollingInfo<T>& pi, std::vector<T> var, const std::vector<long>& c);
400template <class T>
401PollingAdvance<T> polling_advance(const PollingInfo<T>& pi, std::vector<long> c, const std::vector<long>& nbuf,
402 bool arrived);
403template <class T>
404void polling_land_all(const NetworkStruct<T>& sn, std::size_t ist, const PollingInfo<T>& pi,
405 const PollingAdvance<T>& B, const std::vector<T>& buf, const std::vector<T>& srv,
406 const std::vector<T>& var, const RowLayout<T>& L, std::vector<std::vector<T>>& rows,
407 std::vector<T>& probs, std::vector<std::size_t>& starts);
408
409/** Defined below; the reply block subtracts held servers in the ARV branch. */
410template <class T>
411double reply_blocked(const NetworkStruct<T>& sn, std::size_t ind, const std::vector<T>& var);
412
413/** Defined below; the departure branch records a server held for a reply. */
414template <class T>
415ReplyBlockInfo reply_block_info(const NetworkStruct<T>& sn, std::size_t ind);
416
417/** Defined below; servers held for pending replies, weighted by server parallelism. */
418template <class T>
419double reply_held_servers(const NetworkStruct<T>& sn, std::size_t ind, const std::vector<T>& var,
420 const std::vector<double>& par);
421
422/** Defined below; the ARV and DEP branches divert to it before any slicing. */
423template <class T>
425 const std::vector<T>& inspace, EventType event,
426 std::size_t cls);
427
428/**
429 * Port of the ARV branch of `State.afterEventStation`: an arriving class-`cls`
430 * job joins node `ind`, whose local state is `inspace`.
431 *
432 * The event is PASSIVE -- the upstream departure sets the rate -- so every row
433 * returned carries the -1 sentinel. It is nevertheless the branch with the most
434 * successors, because the entering job chooses its service phase, and under the
435 * preemptive disciplines it also chooses which job to displace.
436 *
437 * ONE ROW IN, MANY ROWS OUT. The reference threads a whole matrix of input
438 * rows through this handler and partitions them with logical masks
439 * (`idle_srv`, `all_busy_srv`). Every caller in the CTMC and SSA paths passes a
440 * single row, so those masks degenerate to a branch, which is what this port
441 * writes. The successor set is identical.
442 */
443template <class T>
445 const std::vector<T>& inspace, std::size_t cls) {
446 const std::size_t R = sn.nclasses;
447 const std::size_t ist = sn.nodes[ind - 1].station;
448 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
449 const T minus_one = num_traits<T>::from_int(-1);
450 EventOutcome<T> out;
451 if (ist == 0) throw InputError("after_event_station_arv: node is not a station");
452 const SchedStrategy sched = sn.stations[ist - 1].sched;
453 // A pass-and-swap station has no buffer/server split at all, so it must be
454 // diverted before any slicing happens.
455 if (sched == SchedStrategy::PAS || sched == SchedStrategy::OI)
456 return after_event_station_pas(sn, ind, inspace, EventType::ARV, cls);
457 const RowLayout<T> L = row_layout(sn, ind, inspace.size());
458
459 // A Place holds a marking, not a service facility: it has no servers and no
460 // phases, so an arriving token only increments the class marking. Running
461 // it through the scheduling branches below would write into a phase slot
462 // the row does not have, widening the state so it no longer matches the
463 // enumerated space -- and the arrival would then be silently dropped.
464 if (sn.nodes[ind - 1].nodetype == NodeType::Place) {
465 std::vector<T> row = inspace;
466 const double cap = sn.classcap[ist - 1][cls - 1];
467 if (num_traits<T>::to_double(inspace[cls - 1]) < cap) {
468 row[cls - 1] += one;
469 out.space.push_back(row);
470 out.rate.push_back(minus_one);
471 out.prob.push_back(one);
472 } else {
473 // Place full: the arrival is blocked and lost, with no state change.
474 out.space.push_back(row);
475 out.rate.push_back(minus_one);
476 out.prob.push_back(zero);
477 }
478 return out;
479 }
480
481 const std::pair<T, std::vector<T>> mg = to_marginal_aggr(sn, ind, inspace);
482 const double ni = num_traits<T>::to_double(mg.first);
483 const double nir_c = num_traits<T>::to_double(mg.second[cls - 1]);
484 const double cap_i = sn.cap[ist - 1];
485 const double ccap = sn.classcap[ist - 1][cls - 1];
486 const double S = sn.stations[ist - 1].nservers;
487 std::vector<T> pentry = entry_phase_dist(sn, ist, cls);
488 // MAP service in pair form (`ctmc_mapc`): a start from the class memory h enters pair (h,j)
489 // w.p. V(h,j); pairs starting elsewhere are unreachable, and an idle start sets h := j.
490 const CtmcMapc<T>* mcA = sn.mapc_of(ist, cls);
491 const std::size_t mslotA = mcA ? sn.map_var_slot(ind, cls) : 0;
492 if (mcA) {
493 const long hA = static_cast<long>(num_traits<T>::to_double(inspace[L.bufw + L.srvw + mslotA]));
494 for (std::size_t t = 0; t < mcA->pairs.size(); ++t)
495 pentry[t] = static_cast<long>(mcA->pairs[t].first) + 1 == hA
496 ? mcA->V(mcA->pairs[t].first, mcA->pairs[t].second) : zero;
497 for (std::size_t t = 0; mcA->single && t < mcA->p; ++t) // c = 1: start in the carried phase
498 pentry[t] = static_cast<long>(t) + 1 == hA ? one : zero;
499 }
500
501 // Setup and delay-off (ctmc_blocks.h): a server OFF, setting up or in
502 // delay-off is not an idle server; the arrival's own wake-up is applied
503 // before this handler runs (`setup_arrival_variants`). Server parallelism:
504 // the job starts only when nobody waits and its servers are free.
505 const std::size_t setupw =
506 sched == SchedStrategy::FCFS && sn.setupparam.count(ist) ? ctmc_tail_width(sn, ind) : 0;
507 const std::vector<double> parA =
508 sched == SchedStrategy::FCFS ? parallelism_of(sn, ind) : std::vector<double>();
509
510 for (std::size_t kentry = 0; kentry < L.K[cls - 1]; ++kentry) {
511 if (mcA && num_traits<T>::to_double(pentry[kentry]) == 0) continue;
512 std::vector<T> buf(inspace.begin(), inspace.begin() + L.bufw);
513 std::vector<T> srv(inspace.begin() + L.bufw, inspace.begin() + L.bufw + L.srvw);
514 std::vector<T> var(inspace.begin() + L.bufw + L.srvw, inspace.end());
515 std::vector<std::vector<T>> cand; // (buf, srv, var) triples, flattened below
516 std::vector<T> cand_prob;
517 // START/PREEMPT tag of each candidate: the class that takes a server on
518 // that row and the class it displaces, 0 for neither. Filtered with the
519 // rows themselves at the capacity gate below.
520 std::vector<std::size_t> cand_start, cand_preempt;
521
522 double occ = 0; // jobs currently in service
523 for (std::size_t j = 0; j < srv.size(); ++j) occ += num_traits<T>::to_double(srv[j]);
524
525 if (sched == SchedStrategy::EXT) {
526 // A Source accepts a virtual arrival from the Sink for any open
527 // class: the reservoir is unbounded, so the state does not move.
528 if (!std::isfinite(sn.njobs()[cls - 1])) {
529 out.space.push_back(inspace);
530 out.rate.push_back(zero);
531 out.prob.push_back(one);
532 return out;
533 }
534 continue;
535 }
536
537 if (sched == SchedStrategy::PS || sched == SchedStrategy::INF ||
538 sched == SchedStrategy::DPS || sched == SchedStrategy::GPS ||
539 sched == SchedStrategy::PSPRIO || sched == SchedStrategy::DPSPRIO ||
540 sched == SchedStrategy::GPSPRIO || sched == SchedStrategy::LPS) {
541 // Every job is in service at once, so the arrival never queues.
542 const std::size_t col = L.Ks[cls - 1] + kentry;
543 std::size_t started = 0;
544 if (num_traits<T>::to_double(srv[col]) < ccap) {
545 srv[col] += one;
546 started = cls; // the job enters service at once
547 cand_prob.push_back(pentry[kentry]);
548 } else {
549 cand_prob.push_back(zero);
550 }
551 std::vector<T> row = buf;
552 row.insert(row.end(), srv.begin(), srv.end());
553 row.insert(row.end(), var.begin(), var.end());
554 cand.push_back(row);
555 cand_start.push_back(started);
556 cand_preempt.push_back(0);
557 } else if (sched == SchedStrategy::POLLING) {
558 // The CONTROLLER decides who is served, not the arrival: a job
559 // joins its class buffer and waits for the server to walk to it,
560 // even when the facility is idle, because the server is then in a
561 // switchover. The one exception is a PARKED server, which only
562 // arises with an empty station and immediate switchovers: it
563 // reaches the arriving job in zero time and opens a visit at once.
564 const PollingInfo<T> pinfo = polling_info(sn, ind);
565 polling_require_ph(pinfo);
566 std::size_t srvclass = 0;
567 for (std::size_t r = 1; r <= R; ++r) {
568 double tot = 0;
569 for (std::size_t p = 0; p < L.K[r - 1]; ++p)
570 tot += num_traits<T>::to_double(srv[L.Ks[r - 1] + p]);
571 if (tot > 0) { srvclass = r; break; }
572 }
573 const std::vector<long> cA = polling_get_full(pinfo, var, srvclass);
574 if (srvclass == 0 && cA[1] == 0) {
575 // Parked. In a fixed visit order the walk resolves to a visit
576 // on the arriving class; under a load-dependent order the
577 // server waits at the buffer it left, so the job may instead
578 // wait for the switchover out of that buffer.
579 std::vector<long> nbuf(R, 0);
580 for (std::size_t r = 0; r < R && r < L.bufw; ++r)
581 nbuf[r] = static_cast<long>(num_traits<T>::to_double(buf[r]));
582 nbuf[cls - 1] += 1;
583 const PollingAdvance<T> BA = polling_advance(pinfo, cA, nbuf, true);
584 for (std::size_t b = 0; b < BA.mode.size(); ++b) {
585 std::vector<T> bufA = buf, srvA = srv;
586 if (BA.mode[b] == 1) {
587 srvA[L.Ks[cls - 1] + kentry] += one;
588 cand_start.push_back(cls); // a parked server takes it at once
589 } else {
590 bufA[cls - 1] += one;
591 cand_start.push_back(0);
592 }
593 const std::vector<T> varA = polling_set_full(pinfo, var, BA.C[b]);
594 cand_preempt.push_back(0);
595 cand_prob.push_back(T(pentry[kentry] * BA.prob[b]));
596 std::vector<T> row = bufA;
597 row.insert(row.end(), srvA.begin(), srvA.end());
598 row.insert(row.end(), varA.begin(), varA.end());
599 cand.push_back(row);
600 }
601 } else {
602 buf[cls - 1] += one;
603 cand_start.push_back(0);
604 cand_preempt.push_back(0);
605 cand_prob.push_back(pentry[kentry]);
606 std::vector<T> row = buf;
607 row.insert(row.end(), srv.begin(), srv.end());
608 row.insert(row.end(), var.begin(), var.end());
609 cand.push_back(row);
610 }
611 } else if (sched == SchedStrategy::SIRO || sched == SchedStrategy::SEPT ||
612 sched == SchedStrategy::LEPT) {
613 // Test the SERVER occupancy, not the total count: the two agree in
614 // work-conserving states, but an immediate-feedback self-loop
615 // transiently leaves an idle server with a non-empty buffer, and
616 // the fed-back job must re-enter the vacated server.
617 if (occ < S) {
618 srv[L.Ks[cls - 1] + kentry] += one;
619 cand_start.push_back(cls);
620 } else {
621 buf[cls - 1] += one;
622 cand_start.push_back(0);
623 }
624 cand_preempt.push_back(0);
625 cand_prob.push_back(pentry[kentry]);
626 std::vector<T> row = buf;
627 row.insert(row.end(), srv.begin(), srv.end());
628 row.insert(row.end(), var.begin(), var.end());
629 cand.push_back(row);
630 } else if (state_detail::buffer_is_class_tag(sched)) {
631 // ORDERED BUFFER. An idle server takes the job; otherwise it goes
632 // to the first empty slot, and if there is none the arrival is
633 // refused -- which is a LOSS or a BLOCK, never a silent drop.
634 // Servers held for a pending REPLY are NOT available to an
635 // arriving job, so a job may already have to wait while the raw
636 // occupancy is below the server count. Zero for every model
637 // without reply signals.
638 double seff = S - reply_blocked(sn, ind, var);
639 for (std::size_t k = 0; k < setupw && k < var.size(); ++k)
640 seff -= num_traits<T>::to_double(var[var.size() - setupw + k]);
641 if (!parA.empty()) {
642 // python `parallel_seff`: one more than the jobs in service when
643 // the job may start, the jobs in service otherwise
644 double busy = 0;
645 for (std::size_t r = 0; r < R; ++r)
646 for (std::size_t k = 0; k < L.K[r]; ++k)
647 busy += parA[r] * num_traits<T>::to_double(srv[L.Ks[r] + k]);
648 bool waiting = false;
649 for (std::size_t b = 0; b < L.bufw && !waiting; ++b)
650 waiting = num_traits<T>::to_double(buf[b]) > 0;
651 // servers held by pending synchronous calls, n_r per call
652 const double held = reply_held_servers(sn, ind, var, parA);
653 const bool fits = busy + held + parA[cls - 1] <= S;
654 seff = (fits && !waiting) ? occ + 1 : occ;
655 }
656 if (occ < seff) {
657 srv[L.Ks[cls - 1] + kentry] += one;
658 if (mcA && !mcA->single)
659 var[mslotA] = num_traits<T>::from_int(static_cast<long>(mcA->pairs[kentry].second + 1));
660 std::vector<T> row = buf;
661 row.insert(row.end(), srv.begin(), srv.end());
662 row.insert(row.end(), var.begin(), var.end());
663 cand.push_back(row);
664 cand_prob.push_back(pentry[kentry]);
665 cand_start.push_back(cls);
666 cand_preempt.push_back(0);
667 } else {
668 std::size_t slot = 0; // 1-based index of the LAST empty slot
669 for (std::size_t b = 0; b < L.bufw; ++b)
670 if (num_traits<T>::to_double(buf[b]) == 0) slot = b + 1;
671 // A structurally free column is not enough: the CAPACITY must
672 // also permit the placement. Gating on the capacity only for a
673 // PHYSICAL bound keeps a state-space cutoff a truncation --
674 // firing the gate at a cutoff would turn it into a self-loop.
675 const bool has_room = is_physical_capacity(sn, ist, cls)
676 ? (ni < cap_i && nir_c < ccap)
677 : true;
678 if (slot > 0 && has_room) {
679 buf[slot - 1] = num_traits<T>::from_int(static_cast<long>(cls));
680 if (sched == SchedStrategy::LCFSPRIO) {
681 // Keep the buffer priority-canonical (from_marginal): the job moves right past every waiting
682 // job of a strictly less urgent level, landing at the tail of its own level (MATLAB
683 // afterEventStation). The order ACROSS levels is never read by an LCFSPRIO server.
684 const int pc = sn.classes[cls - 1].prio;
685 for (std::size_t c = slot - 1; c + 1 < L.bufw; ++c) {
686 const double nb = num_traits<T>::to_double(buf[c + 1]);
687 if (!(nb > 0) || sn.classes[static_cast<std::size_t>(nb) - 1].prio <= pc) break;
688 buf[c] = buf[c + 1];
689 buf[c + 1] = num_traits<T>::from_int(static_cast<long>(cls));
690 }
691 }
692 std::vector<T> row = buf;
693 row.insert(row.end(), srv.begin(), srv.end());
694 row.insert(row.end(), var.begin(), var.end());
695 cand.push_back(row);
696 cand_prob.push_back(pentry[kentry]);
697 cand_start.push_back(0); // the job waits in the buffer
698 cand_preempt.push_back(0);
699 } else if (arrival_is_lost(sn, ist, cls) &&
700 is_physical_capacity(sn, ist, cls)) {
701 // LOST: keep the row unchanged, so the event still fires
702 // and the OFFERED job reaches the arrival-rate statistic.
703 // A self-loop cancels on the generator diagonal, so the
704 // stationary law cannot move.
705 //
706 // ONLY A DECLARED BUFFER MAY LOSE A JOB. `slot == 0` also
707 // fires when the row is merely as wide as the STATE-SPACE
708 // CUTOFF let it be, and there the reference emits no
709 // successor at all -- the state above the cutoff is absent,
710 // not refused. Emitting the self-loop there costs nothing on
711 // the generator (the diagonal absorbs it) and everything on
712 // the RATES, which count the loop as a departure of the
713 // upstream Source: on mqn_multiserver_fcfs 20 such loops
714 // moved Source Tput from 0.24763 to 0.26040, an arrival rate
715 // no job ever carried, and left ArvR above Tput at a station
716 // that drops nothing. `has_room` above already draws exactly
717 // this line for the capacity test.
718 cand.push_back(inspace);
719 cand_prob.push_back(pentry[kentry]);
720 cand_start.push_back(0); // the job is lost: it starts nothing
721 cand_preempt.push_back(0);
722 }
723 // BLOCKED: emit nothing, which disables the upstream departure
724 // until room frees. That absence is what the become-blocked
725 // edge tests for.
726 }
727 } else if (state_detail::buffer_is_tag_phase_pairs(sched)) {
728 // PREEMPTIVE FAMILY. The buffer holds [class, phase] pairs, because
729 // a displaced job must remember where it was interrupted. An idle
730 // server simply takes the arrival; a busy one forces a CHOICE of
731 // victim, so the event has one successor per (class, phase) in
732 // service, weighted by that server's share of the occupancy.
733 if (occ < S) {
734 srv[L.Ks[cls - 1] + kentry] += one;
735 std::vector<T> row = buf;
736 row.insert(row.end(), srv.begin(), srv.end());
737 row.insert(row.end(), var.begin(), var.end());
738 cand.push_back(row);
739 cand_prob.push_back(pentry[kentry]);
740 cand_start.push_back(cls);
741 cand_preempt.push_back(0);
742 } else {
743 // Priority-awareness is a property of the DECLARED policy, never
744 // of the data: inferring it from the class priorities turned
745 // plain LCFSPR/FCFSPR into something that is neither the base
746 // policy nor the PRIO variant.
747 const bool prio_aware = sched == SchedStrategy::FCFSPRPRIO ||
748 sched == SchedStrategy::FCFSPIPRIO ||
749 sched == SchedStrategy::LCFSPRPRIO ||
750 sched == SchedStrategy::LCFSPIPRIO;
751 const bool lcfs_family = sched == SchedStrategy::LCFSPRPRIO ||
752 sched == SchedStrategy::LCFSPIPRIO;
753 // FCFS-PR/PI: an ARRIVAL NEVER PREEMPTS. The base discipline
754 // serves in arrival order, and the PLAIN variants read no
755 // priorities at all, so every class sits in ONE group and the
756 // arrival can only wait; preemption belongs to the PRIO variants
757 // and only ACROSS groups. LCFS-PR/PI is the opposite case, keeping
758 // the NEWEST job in service, so there a plain arrival always
759 // preempts. Letting plain FCFSPR/FCFSPI preempt made them LCFS-PR
760 // by another name: invisible on an exponential single-chain queue,
761 // whose queue-length process is the same either way, and wrong
762 // wherever WHICH job holds the server matters -- a fork-join, where
763 // the sibling that completes decides when the Join fires, or any
764 // phase-type service, where the interrupted phase is carried.
765 const bool fcfs_never_preempts = sched == SchedStrategy::FCFSPR ||
766 sched == SchedStrategy::FCFSPI;
767 // PR resumes the victim in the phase it held; PI restarts it
768 // from the entry phase. That single value is the whole
769 // difference between the two families in this branch.
770 const bool resume = sched == SchedStrategy::LCFSPR ||
771 sched == SchedStrategy::LCFSPRPRIO ||
772 sched == SchedStrategy::FCFSPR ||
773 sched == SchedStrategy::FCFSPRPRIO;
774 bool can_preempt_any = false;
775 for (std::size_t cp = 1; cp <= R && !fcfs_never_preempts; ++cp) {
776 if (prio_aware) {
777 // Across priority groups a strictly higher-priority
778 // arrival preempts. WITHIN a group the base discipline
779 // decides: LCFS-PR keeps the NEWEST job in service, so
780 // an equal-priority arrival preempts; FCFS-PR never
781 // lets an arrival preempt.
782 const int pa = sn.classes[cls - 1].prio;
783 const int pv = sn.classes[cp - 1].prio;
784 if (lcfs_family ? (pa > pv) : (pa >= pv)) continue;
785 }
786 for (std::size_t pp = 0; pp < L.K[cp - 1]; ++pp) {
787 const std::size_t vcol = L.Ks[cp - 1] + pp;
788 const double busy = num_traits<T>::to_double(srv[vcol]);
789 if (busy <= 0) continue;
790 can_preempt_any = true;
791 std::vector<T> b2 = buf, s2 = srv;
792 s2[vcol] -= one;
793 s2[L.Ks[cls - 1] + kentry] += one;
794 // Rightmost empty PAIR, which is where a displaced job
795 // is stored; the class column is one left of the zero
796 // the scan finds.
797 std::size_t slot = 0;
798 for (std::size_t b = 0; b < L.bufw; ++b)
799 if (num_traits<T>::to_double(b2[b]) == 0) slot = b;
800 if (slot == 0) continue; // no room to hold the victim
801 b2[slot - 1] = num_traits<T>::from_int(static_cast<long>(cp));
802 b2[slot] = resume ? num_traits<T>::from_int(static_cast<long>(pp + 1))
803 : one;
804 std::vector<T> row = b2;
805 row.insert(row.end(), s2.begin(), s2.end());
806 row.insert(row.end(), var.begin(), var.end());
807 cand.push_back(row);
808 // the displaced job leaves the server and the arriving
809 // one takes it, on the same arc
810 cand_start.push_back(cls);
811 cand_preempt.push_back(cp);
812 // The victim is drawn uniformly among the jobs in
813 // service, so its share of the occupancy weights the
814 // successor.
815 cand_prob.push_back(T(pentry[kentry] * num_traits<T>::from_double(busy / occ)));
816 }
817 }
818 // Every busy server holds a job this arrival may not displace,
819 // so the job WAITS instead. Without this the loop above emits
820 // nothing, the arrival transition does not exist at all, and
821 // the class can never enter a busy station -- its queue is
822 // then silently understated. It is stored as a (class, entry
823 // phase) pair exactly as a preempted job is, so promotion
824 // resumes it from that phase.
825 if ((prio_aware || fcfs_never_preempts) && !can_preempt_any) {
826 std::size_t slot = 0;
827 for (std::size_t b = 0; b < L.bufw; ++b)
828 if (num_traits<T>::to_double(buf[b]) == 0) slot = b;
829 if (slot > 0) {
830 std::vector<T> b2 = buf;
831 b2[slot - 1] = num_traits<T>::from_int(static_cast<long>(cls));
832 b2[slot] = num_traits<T>::from_int(static_cast<long>(kentry + 1));
833 std::vector<T> row = b2;
834 row.insert(row.end(), srv.begin(), srv.end());
835 row.insert(row.end(), var.begin(), var.end());
836 cand.push_back(row);
837 cand_prob.push_back(pentry[kentry]);
838 cand_start.push_back(0); // it preempts nothing and waits
839 cand_preempt.push_back(0);
840 }
841 }
842 }
843 } else {
844 throw UnsupportedError(ErrorKind{"SchedStrategy"},
845 std::string("after_event_station_arv: the ") + lang::sched_to_text(sched) +
846 " discipline is not ported yet");
847 }
848
849 // The capacity filter of the reference: drop any successor that would
850 // exceed the station or class bound.
851 for (std::size_t c = 0; c < cand.size(); ++c) {
852 const std::pair<T, std::vector<T>> og = to_marginal_aggr(sn, ind, cand[c]);
853 if (num_traits<T>::to_double(og.second[cls - 1]) > ccap) continue;
854 if (num_traits<T>::to_double(og.first) > cap_i) continue;
855 out.space.push_back(cand[c]);
856 out.rate.push_back(minus_one);
857 out.prob.push_back(cand_prob[c]);
858 // the capacity gate drops rows, so the tags are attached here
859 tag_last(out, c < cand_start.size() ? cand_start[c] : 0,
860 c < cand_preempt.size() ? cand_preempt[c] : 0);
861 }
862 }
863 pad_tags(out);
864 return out;
865}
866
867/**
868 * `sn.mu` and `sn.phi` for one (station, class), derived as MATLAB's
869 * `Markovian.getMu` / `getPhi` derive them from the (D0, D1) pair:
870 *
871 * mu(k) = -D0(k,k) total exit rate of phase k
872 * phi(k) = sum_j D1(k,j) / -D0(k,k) probability the exit COMPLETES service
873 *
874 * so mu*phi is the departure rate and mu*(1-phi) the phase-advance rate. An
875 * Immediate process has D0(1,1) = 0 and takes phi = 1, since every exit of a
876 * zero-duration service is a completion.
877 */
878template <class T>
879std::pair<std::vector<T>, std::vector<T>> phase_rates(const NetworkStruct<T>& sn,
880 std::size_t ist, std::size_t cls) {
881 const lang::Distrib<T>& d = sn.service[ist - 1][cls - 1];
882 const std::size_t n = sn.phases_of(ist, cls);
883 std::vector<T> mu(n, num_traits<T>::from_int(0)), phi(n, num_traits<T>::from_int(1));
884 if (d.D0.rows() != n || d.D1.rows() != n) return std::make_pair(mu, phi);
885 for (std::size_t k = 0; k < n; ++k) {
886 const T dk = T(-d.D0(k, k));
887 mu[k] = dk;
888 if (num_traits<T>::to_double(dk) == 0) {
889 phi[k] = num_traits<T>::from_int(1); // Immediate: every exit completes
890 continue;
891 }
893 for (std::size_t j = 0; j < n; ++j) s += d.D1(k, j);
894 phi[k] = T(s / dk);
895 }
896 return std::make_pair(mu, phi);
897}
898
899/** The limited-load-dependent multiplier at population `n`, 1 when unset. */
900template <class T>
901T lld_factor(const NetworkStruct<T>& sn, std::size_t ist, double n) {
902 const std::vector<T>& s = sn.stations[ist - 1].lldscaling;
903 if (s.empty()) return num_traits<T>::from_int(1);
904 // Beyond the declared levels the scaling holds at its last value, which is
905 // what "limited" load-dependence means: the curve is flat past the limit.
906 if (!std::isfinite(n) || n >= static_cast<double>(s.size())) return s.back();
907 if (n < 1) return num_traits<T>::from_int(1);
908 return s[static_cast<std::size_t>(n) - 1];
909}
910
911/**
912 * Port of `State.cdclassfactor`: the class-dependence multiplier of a class-`cls`
913 * rate at the per-class population `nir`.
914 *
915 * `cdscaling` maps a 1 x R population vector to the R dimensionless scalings
916 * beta_r(n); the component of the class whose service is firing is the factor.
917 * A handle returning a SCALAR is the neutral case and yields 1 for every class,
918 * which is why the read is clamped to the vector's last entry rather than
919 * indexed blindly -- the reference's `v(min(class, numel(v)))`.
920 *
921 * `jdscaling` is folded in multiplicatively here, exactly as
922 * `State.afterEventInit` folds eta_i into the effective per-station handle.
923 * Doing it at the point of use rather than by rewriting the struct keeps the two
924 * fields distinguishable for the product-form tests elsewhere.
925 */
926template <class T>
927T cd_factor(const NetworkStruct<T>& sn, std::size_t ist, const std::vector<T>& nir,
928 std::size_t cls) {
929 const T one = num_traits<T>::from_int(1);
930 const Station<T>& st = sn.stations[ist - 1];
931 if (!st.cdscaling && !st.jdscaling) return one;
932 T f = one;
933 const CdScaling<T>* handles[2] = {&st.cdscaling, &st.jdscaling};
934 for (std::size_t h = 0; h < 2; ++h) {
935 const CdScaling<T>& fun = *handles[h];
936 if (!fun) continue;
937 const std::vector<T> v = fun(nir);
938 if (v.empty())
939 throw InputError(
940 "cd_factor: the class-dependence map returned an empty scaling vector");
941 f = T(f * v[std::min(cls, v.size()) - 1]);
942 }
943 return f;
944}
945
946/**
947 * The population the *PRIO disciplines actually share the server among.
948 *
949 * While every job fits in a server nobody is waiting and precedence is moot, so
950 * this is the plain marginal. Once the station saturates only the MOST URGENT
951 * group present is served (a LOWER `classprio` value is more urgent in LINE),
952 * and both the share and the load-dependent lookup are taken over that group
953 * alone -- `nirprio` / `niprio` in `State.afterEventStation`.
954 */
955template <class T>
956struct PrioPop {
957 std::vector<T> nir; ///< `nirprio` when masked, the plain marginal otherwise
958 double ni = 0; ///< `niprio` when masked, the plain total otherwise
959 bool masked = false; ///< whether the saturated-station mask was applied
960 bool served = true; ///< false when `cls` is not in the most urgent group
961};
962
963/** Compute the *PRIO effective population; a no-op for every other discipline. */
964template <class T>
965PrioPop<T> prio_pop(const NetworkStruct<T>& sn, std::size_t ist, const Marginal<T>& m,
966 std::size_t cls, double ni, double S) {
967 const std::size_t R = sn.nclasses;
968 const SchedStrategy sched = sn.stations[ist - 1].sched;
969 PrioPop<T> p;
970 p.nir = m.nir;
971 p.ni = ni;
972 const bool prio_aware = sched == SchedStrategy::PSPRIO ||
973 sched == SchedStrategy::DPSPRIO ||
974 sched == SchedStrategy::GPSPRIO;
975 if (!prio_aware || ni <= S) return p;
976 double best = std::numeric_limits<double>::infinity();
977 for (std::size_t r = 0; r < R; ++r)
978 if (num_traits<T>::to_double(m.nir[r]) > 0)
979 best = std::min(best, static_cast<double>(sn.classes[r].prio));
980 if (static_cast<double>(sn.classes[cls - 1].prio) != best) {
981 p.served = false;
982 return p;
983 }
984 p.masked = true;
985 p.ni = 0;
986 for (std::size_t r = 0; r < R; ++r) {
987 if (static_cast<double>(sn.classes[r].prio) != best)
990 }
991 return p;
992}
993
994/** Defined below; DEP and PHASE must share one definition of the share. */
995template <class T>
996T service_share(const NetworkStruct<T>& sn, std::size_t ist, const Marginal<T>& m,
997 std::size_t cls, double ni, double S);
998
999/**
1000 * Port of the DEP branch of `State.afterEventStation`: a class-`cls` job
1001 * completes service at station `ind`.
1002 *
1003 * This is the ACTIVE half, so unlike ARV it carries real rates, and the rate is
1004 * where the disciplines actually differ -- the state update is nearly the same
1005 * for all of them. Two rate conventions appear, and they are not
1006 * interchangeable:
1007 *
1008 * mu(k)*phi(k)*kir -- the processor-sharing family, where the completion
1009 * rate is the phase rate times the share of the server
1010 * D1(k,kdest)*kir -- the FCFS family, where the MAP matrix already encodes
1011 * both the completion and the phase the NEXT service
1012 * starts in, so the destination phase is enumerated
1013 */
1014template <class T>
1016 const std::vector<T>& inspace, std::size_t cls,
1017 bool no_promote = false) {
1018 const std::size_t R = sn.nclasses;
1019 const std::size_t ist = sn.nodes[ind - 1].station;
1020 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
1021 EventOutcome<T> out;
1022 if (ist == 0) throw InputError("after_event_station_dep: node is not a station");
1023 const SchedStrategy sched = sn.stations[ist - 1].sched;
1024 if (sched == SchedStrategy::PAS || sched == SchedStrategy::OI)
1025 return after_event_station_pas(sn, ind, inspace, EventType::DEP, cls);
1026 const RowLayout<T> L = row_layout(sn, ind, inspace.size());
1027 const double S = sn.stations[ist - 1].nservers;
1028
1029 std::vector<std::size_t> ph(R, 1), shift(R, 0);
1030 for (std::size_t r = 0; r < R; ++r) {
1031 ph[r] = L.K[r];
1032 shift[r] = L.Ks[r];
1033 }
1034 // THE MARK OF A MARKED (MMAP) SOURCE CLASS, and the class whose phase block
1035 // its departures actually read. All marks share ONE modulating chain, held
1036 // in the CARRIER's block (mark 1); a later mark owns a single always-zero
1037 // column (`phasessz_of`), so reading its own block would find no token and
1038 // the class would never emit. `markof == 0` leaves every other station and
1039 // every unmarked class on `cls`, exactly as before.
1040 const std::size_t markof = sched == SchedStrategy::EXT ? sn.markidx_of(ist, cls) : 0;
1041 std::size_t phcls = cls;
1042 if (markof > 0) {
1043 const std::size_t carrier = sn.mark_carrier_of(ist);
1044 if (carrier >= 1 && carrier <= R) phcls = carrier;
1045 }
1046
1047 const Marginal<T> m = to_marginal(sn, ist, inspace, ph, shift, L.nvar);
1048 if (num_traits<T>::to_double(m.sir[phcls - 1]) <= 0) return out; // nothing to depart
1049
1050 const std::pair<std::vector<T>, std::vector<T>> mp = phase_rates(sn, ist, cls);
1051 const std::vector<T>& mu = mp.first;
1052 const std::vector<T>& phi = mp.second;
1053 const lang::Distrib<T>& d = sn.service[ist - 1][cls - 1];
1054
1055 double ni = 0;
1056 for (std::size_t r = 0; r < R; ++r) ni += num_traits<T>::to_double(m.nir[r]);
1057 // Both dependence factors multiply every rate this branch emits, so they are
1058 // folded into ONE scalar named `lld` for the arithmetic below. Their
1059 // ARGUMENTS differ at a saturated *PRIO station, and the reference is not
1060 // uniform about it: the load-dependent lookup takes the priority-masked
1061 // total `niprio` for all three *PRIO disciplines, while the class-dependence
1062 // handle takes the masked vector `nirprio` only for DPSPRIO and GPSPRIO and
1063 // the plain marginal for PSPRIO (afterEventStation.m:709-711 vs :746-748 and
1064 // :808-810). That asymmetry is reproduced rather than smoothed: smoothing it
1065 // would move every reported metric on a model that has both.
1066 const PrioPop<T> pp = prio_pop(sn, ist, m, cls, ni, S);
1067 const bool cd_takes_prio =
1068 pp.masked && (sched == SchedStrategy::DPSPRIO || sched == SchedStrategy::GPSPRIO);
1069 const T lld = T(lld_factor(sn, ist, pp.ni) *
1070 cd_factor(sn, ist, cd_takes_prio ? pp.nir : m.nir, cls));
1071
1072 // A retrial station does NOT promote from the orbit on completion: an
1073 // orbiting job re-enters only through a RETRY at the retrial rate. The
1074 // same suppression serves an immediate-feedback self-loop, where the
1075 // departing job holds the server for its own re-arrival.
1076 bool suppress_promote = no_promote;
1077 {
1078 const typename std::map<std::size_t, RetrialParam<T>>::const_iterator rit =
1079 sn.retrialparam.find(ist);
1080 if (rit != sn.retrialparam.end())
1081 for (std::size_t r = 0; r < rit->second.retrial_proc.size(); ++r)
1082 if (!rit->second.retrial_proc[r].disabled) { suppress_promote = true; break; }
1083 }
1084
1085 for (std::size_t k = 0; k < L.K[phcls - 1]; ++k) {
1086 std::vector<T> buf(inspace.begin(), inspace.begin() + L.bufw);
1087 std::vector<T> srv(inspace.begin() + L.bufw, inspace.begin() + L.bufw + L.srvw);
1088 std::vector<T> var(inspace.begin() + L.bufw + L.srvw, inspace.end());
1089 const std::size_t col = L.Ks[phcls - 1] + k;
1090 if (num_traits<T>::to_double(srv[col]) <= 0) continue;
1091 const T kir = m.kir[phcls - 1][k];
1092
1093 if (sched == SchedStrategy::EXT) {
1094 // A Source EMITS an arrival. Its reservoir is unbounded, so no job
1095 // count changes; what moves is the MODULATING PHASE, from k to
1096 // kentry at rate D1(k, kentry). For an exponential source that is
1097 // the single entry lambda and the state is unchanged, which is why
1098 // the arrival stream is memoryless; for a MAP it is exactly the
1099 // correlation the source is there to produce.
1100 if (!std::isfinite(sn.njobs()[cls - 1])) {
1101 // THE MARK'S OWN BLOCK, not the aggregate. `d.D1` is the sum
1102 // over marks, so reading it for a marked class gives every one
1103 // of them the WHOLE stream: two read classes off one MMAP each
1104 // arrived at the full 2.5/s instead of the 1.9 and 0.6 their
1105 // blocks carry, doubling the offered load and erasing the
1106 // popularity difference the marks exist to express.
1107 const Matrix<T>& D1k =
1108 markof > 0 && markof <= d.Dmark.size() ? d.Dmark[markof - 1] : d.D1;
1109 for (std::size_t ke = 0; ke < L.K[phcls - 1]; ++ke) {
1110 const T arv = D1k(k, ke);
1111 // ZERO is the only entry skipped. A matrix-exponential
1112 // arrival process (the CME surrogate of a Gamma or Uniform
1113 // source) carries NEGATIVE D1 entries that belong to the
1114 // balance equations; dropping them inflates the arrival
1115 // rate. For a MAP every entry is nonnegative, so nothing
1116 // changes there. See _kb/07-cross-language-parity.md.
1117 if (num_traits<T>::to_double(arv) == 0) continue;
1118 std::vector<T> row = inspace;
1119 row[L.bufw + L.Ks[phcls - 1] + k] -= one;
1120 row[L.bufw + L.Ks[phcls - 1] + ke] += one;
1121 out.space.push_back(row);
1122 out.rate.push_back(T(lld * arv));
1123 out.prob.push_back(one);
1124 }
1125 }
1126 } else if (sched == SchedStrategy::INF || sched == SchedStrategy::PS ||
1127 sched == SchedStrategy::LPS || sched == SchedStrategy::DPS ||
1128 sched == SchedStrategy::GPS || sched == SchedStrategy::PSPRIO ||
1129 sched == SchedStrategy::DPSPRIO || sched == SchedStrategy::GPSPRIO) {
1130 srv[col] -= one;
1131 // The same share PHASE uses: a completion and an internal phase
1132 // advance are driven by the identical fraction of the server, so
1133 // they must never be computed two different ways.
1134 const T rate = T(mu[k] * phi[k] * kir * service_share(sn, ist, m, cls, ni, S));
1135 std::vector<T> row = buf;
1136 row.insert(row.end(), srv.begin(), srv.end());
1137 row.insert(row.end(), var.begin(), var.end());
1138 out.space.push_back(row);
1139 out.rate.push_back(T(lld * rate));
1140 out.prob.push_back(one);
1141 } else if (state_detail::buffer_is_class_tag(sched) && sched != SchedStrategy::FCFS) {
1142 // HOL, LCFS and LCFSPRIO share FCFS's ordered buffer but NOT its
1143 // rate convention: the completion rate is mu*phi*kir, summed over
1144 // destination phases rather than enumerated. What separates the
1145 // three is only WHICH waiting job is promoted.
1146 const bool has_waiting = ni > S && !suppress_promote;
1147 const T rate = T(mu[k] * phi[k] * kir);
1148 srv[col] -= one;
1149 if (!has_waiting) {
1150 std::vector<T> row = buf;
1151 row.insert(row.end(), srv.begin(), srv.end());
1152 row.insert(row.end(), var.begin(), var.end());
1153 out.space.push_back(row);
1154 out.rate.push_back(T(lld * rate));
1155 out.prob.push_back(one);
1156 continue;
1157 }
1158 // Position of the job that starts service, 0-based; L.bufw = none.
1159 std::size_t pos = L.bufw;
1160 if (sched == SchedStrategy::LCFS) {
1161 // Plain LCFS is NOT priority-aware: it always promotes the most
1162 // recent arrival. Arrivals fill the rightmost empty slot, so
1163 // the newest job is the FIRST nonzero column. Branching here on
1164 // the class priorities would silently turn every LCFS station
1165 // with distinct priorities into an LCFSPRIO one.
1166 for (std::size_t b = 0; b < L.bufw; ++b)
1167 if (num_traits<T>::to_double(buf[b]) != 0) { pos = b; break; }
1168 } else {
1169 // HOL and LCFSPRIO serve the highest-priority waiting group
1170 // first; in LINE a LOWER classprio value is more urgent. Within
1171 // the group HOL takes the oldest job (rightmost) and LCFSPRIO
1172 // the newest (leftmost), which is how each relates to its
1173 // non-priority base discipline.
1174 double best = std::numeric_limits<double>::infinity();
1175 for (std::size_t b = 0; b < L.bufw; ++b) {
1176 const double v = num_traits<T>::to_double(buf[b]);
1177 if (v <= 0) continue;
1178 const double p = sn.classes[static_cast<std::size_t>(v) - 1].prio;
1179 if (p < best) best = p;
1180 }
1181 if (std::isfinite(best))
1182 for (std::size_t b = 0; b < L.bufw; ++b) {
1183 const double v = num_traits<T>::to_double(buf[b]);
1184 if (v <= 0) continue;
1185 if (sn.classes[static_cast<std::size_t>(v) - 1].prio != best) continue;
1186 pos = b;
1187 if (sched == SchedStrategy::LCFSPRIO) break; // leftmost
1188 }
1189 }
1190 if (pos == L.bufw) continue;
1191 const std::size_t hc = static_cast<std::size_t>(num_traits<T>::to_double(buf[pos]));
1192 std::vector<T> b2 = buf;
1193 if (sched == SchedStrategy::LCFS) {
1194 // LCFS clears the slot IN PLACE, leaving a hole; the next
1195 // arrival refills it, since arrivals seek the rightmost empty
1196 // slot. The priority variants instead close the gap.
1197 b2[pos] = zero;
1198 } else {
1199 for (std::size_t b = pos; b > 0; --b) b2[b] = b2[b - 1];
1200 b2[0] = zero;
1201 }
1202 const std::vector<T> pentry = entry_phase_dist(sn, ist, hc);
1203 for (std::size_t ke = 0; ke < L.K[hc - 1]; ++ke) {
1204 std::vector<T> s3 = srv;
1205 s3[L.Ks[hc - 1] + ke] += one;
1206 std::vector<T> row = b2;
1207 row.insert(row.end(), s3.begin(), s3.end());
1208 row.insert(row.end(), var.begin(), var.end());
1209 out.space.push_back(row);
1210 out.rate.push_back(T(lld * rate * pentry[ke]));
1211 out.prob.push_back(one);
1212 tag_last(out, hc, 0); // the promoted job takes the freed server
1213 }
1214 } else if (state_detail::buffer_is_class_tag(sched)) {
1215 // FCFS. D1(k, kdest) is the completion rate that leaves the process
1216 // in phase kdest, so the destination phase has to be enumerated
1217 // rather than summed away.
1218 //
1219 // A synchronous call: this departing job KEEPS its server until its
1220 // REPLY returns here, so the server is not handed to a waiting job;
1221 // it is recorded as held in the reply block instead. Servers already
1222 // held that way are likewise unavailable, so a job can be waiting
1223 // while the raw occupancy is below the server count.
1224 std::vector<T> var2 = var;
1225 bool holds_reply = false;
1226 if (sn.replyblock.size() >= ind && sn.replyblock[ind - 1].size() >= cls &&
1227 sn.replyblock[ind - 1][cls - 1]) {
1228 const ReplyBlockInfo ri = reply_block_info(sn, ind);
1229 const std::size_t sl = ri.slot[cls - 1];
1230 if (sl != static_cast<std::size_t>(-1) && sl < var2.size()) {
1231 var2[sl] += one;
1232 holds_reply = true;
1233 }
1234 }
1235 const double nb = reply_blocked(sn, ind, var);
1236 // At a setup/delay-off station servers may be OFF or setting up while
1237 // jobs wait, so the count test does not say whether a job waits; the
1238 // buffer does, and the freed (ACTIVE) server takes its head.
1239 bool waiting_now = ni > (S - nb);
1240 if (sched == SchedStrategy::FCFS && sn.setupparam.count(ist) && ctmc_tail_width(sn, ind) > 0)
1241 waiting_now = L.bufw > 0 && num_traits<T>::to_double(buf[L.bufw - 1]) > 0;
1242 const bool has_waiting = waiting_now && !suppress_promote && !holds_reply;
1243 // Pair form: the completion rate is done(k) and the class memory is left as it is. A single
1244 // server instead records the phase kd the completion leaves the MAP in.
1245 const CtmcMapc<T>* mcD = sn.mapc_of(ist, cls);
1246 const bool pairD = mcD && !mcD->single;
1247 const std::size_t mslotD = mcD ? sn.map_var_slot(ind, cls) : 0;
1248 const std::vector<T> var2_in = var2;
1249 for (std::size_t kd = 0; kd < L.K[cls - 1]; ++kd) {
1250 if (pairD && kd > 0) break;
1251 const T rate = pairD ? T(mcD->done[k] * kir) : T(d.D1(k, kd) * kir);
1252 var2 = var2_in;
1253 if (mcD && mcD->single) var2[mslotD] = num_traits<T>::from_int(static_cast<long>(kd + 1));
1254 std::vector<T> s2 = srv;
1255 s2[col] -= one;
1256 if (!has_waiting) {
1257 std::vector<T> row = buf;
1258 row.insert(row.end(), s2.begin(), s2.end());
1259 row.insert(row.end(), var2.begin(), var2.end());
1260 out.space.push_back(row);
1261 out.rate.push_back(T(lld * rate));
1262 out.prob.push_back(one);
1263 continue;
1264 }
1265 // Promote the head of the buffer. The head is the LAST column:
1266 // the buffer shifts RIGHT as jobs join, so the oldest job sits
1267 // at the end -- which is what makes the discipline first-come.
1268 const double headv = num_traits<T>::to_double(buf[L.bufw - 1]);
1269 if (headv <= 0) continue;
1270 const std::size_t hc = static_cast<std::size_t>(headv);
1271 std::vector<T> b2(L.bufw, zero);
1272 for (std::size_t b = 1; b < L.bufw; ++b) b2[b] = buf[b - 1];
1273 std::vector<T> pentry = entry_phase_dist(sn, ist, hc);
1274 // Pair form of the promoted class: it starts from its memory h, as in ARV.
1275 const CtmcMapc<T>* mcP = sn.mapc_of(ist, hc);
1276 const std::size_t mslotP = mcP ? sn.map_var_slot(ind, hc) : 0;
1277 if (mcP) {
1278 const long hP = static_cast<long>(num_traits<T>::to_double(var2[mslotP]));
1279 for (std::size_t t = 0; t < mcP->pairs.size(); ++t)
1280 pentry[t] = static_cast<long>(mcP->pairs[t].first) + 1 == hP
1281 ? mcP->V(mcP->pairs[t].first, mcP->pairs[t].second) : zero;
1282 for (std::size_t t = 0; mcP->single && t < mcP->p; ++t)
1283 pentry[t] = static_cast<long>(t) + 1 == hP ? one : zero;
1284 }
1285 for (std::size_t ke = 0; ke < L.K[hc - 1]; ++ke) {
1286 if (mcP && num_traits<T>::to_double(pentry[ke]) == 0) continue;
1287 std::vector<T> s3 = s2;
1288 s3[L.Ks[hc - 1] + ke] += one;
1289 std::vector<T> var3 = var2;
1290 if (mcP && !mcP->single)
1291 var3[mslotP] = num_traits<T>::from_int(static_cast<long>(mcP->pairs[ke].second + 1));
1292 std::vector<T> row = b2;
1293 row.insert(row.end(), s3.begin(), s3.end());
1294 row.insert(row.end(), var3.begin(), var3.end());
1295 const T r3 = T(lld * rate * pentry[ke]);
1296 out.space.push_back(row);
1297 out.rate.push_back(r3);
1298 // A branch that cannot happen carries probability zero, not
1299 // one: a PH whose entry vector does not reach every phase
1300 // would otherwise contribute phantom departures.
1301 out.prob.push_back(num_traits<T>::to_double(r3) == 0 ? zero : one);
1302 tag_last(out, hc, 0); // the head of the buffer takes the freed server
1303 }
1304 }
1305 } else if (sched == SchedStrategy::POLLING) {
1306 // A completion ends the VISIT unless the discipline still allows
1307 // another job of the same class; when it ends, the server walks the
1308 // cyclic order to the next tangible controller state.
1309 const PollingInfo<T> pinfo = polling_info(sn, ind);
1310 polling_require_ph(pinfo);
1311 const T rate = T(mu[k] * phi[k] * kir);
1312 if (num_traits<T>::to_double(rate) <= 0) continue;
1313 const std::vector<long> cD = polling_get_full(pinfo, var, cls);
1314 const long ctr = cD[2];
1315 // No job can complete while the server is walking.
1316 if (cD[1] != 0) continue;
1317 std::vector<long> nbuf(R, 0);
1318 for (std::size_t r = 0; r < R && r < L.bufw; ++r)
1319 nbuf[r] = static_cast<long>(num_traits<T>::to_double(buf[r]));
1320 srv[col] -= one;
1321 long ctrnext = 0;
1322 bool goon = false;
1323 switch (pinfo.ptype) {
1325 ctrnext = 0;
1326 goon = nbuf[cls - 1] > 0; // the visit ends when it drains
1327 break;
1330 ctrnext = ctr - 1; // one of the gated jobs completed
1331 goon = ctrnext > 0;
1332 break;
1334 ctrnext = ctr - 1; // one of the K permitted services used
1335 goon = ctrnext > 0 && nbuf[cls - 1] > 0;
1336 break;
1338 ctrnext = ctr; // the target level is fixed for the visit
1339 goon = nbuf[cls - 1] > ctr;
1340 break;
1341 }
1342 // A visit timer that expired during this service ends the visit
1343 // with it, whatever the discipline.
1344 if (pinfo.tmode != lang::PollingTimer::NONE && cD[4] == 0) goon = false;
1346 if (goon) {
1347 std::vector<long> cg = cD;
1348 cg[2] = ctrnext;
1349 BD.C.push_back(cg);
1350 BD.mode.push_back(1);
1351 BD.q.push_back(cls);
1352 BD.prob.push_back(one);
1353 } else {
1354 BD = polling_advance(pinfo, cD, nbuf, false);
1355 }
1356 std::vector<std::vector<T>> rows;
1357 std::vector<T> probs;
1358 std::vector<std::size_t> starts;
1359 polling_land_all(sn, ist, pinfo, BD, buf, srv, var, L, rows, probs, starts);
1360 for (std::size_t j = 0; j < rows.size(); ++j) {
1361 out.space.push_back(rows[j]);
1362 out.rate.push_back(T(lld * rate * probs[j]));
1363 out.prob.push_back(one);
1364 // a visit pulls a waiting job into the server; a switchover or
1365 // a park starts nobody
1366 tag_last(out, starts[j], 0);
1367 }
1368 } else if (state_detail::buffer_is_tag_phase_pairs(sched)) {
1369 // THE PREEMPT-RESUME / PREEMPT-INDEPENDENT FAMILY, all eight members.
1370 // Every arm of the reference carries the same rate law, mu*phi*kir
1371 // summed over destination phases (afterEventStation.m:1045, :1081,
1372 // :1118, :1150, :1188, :1234, :1286, :1332); what separates them is
1373 // WHICH waiting job is promoted and in WHICH phase it restarts.
1374 const T rate = T(mu[k] * phi[k] * kir);
1375 srv[col] -= one;
1376 const bool prio_aware = sched == SchedStrategy::FCFSPRPRIO ||
1377 sched == SchedStrategy::FCFSPIPRIO ||
1378 sched == SchedStrategy::LCFSPRPRIO ||
1379 sched == SchedStrategy::LCFSPIPRIO;
1380 const bool lcfs = sched == SchedStrategy::LCFSPR ||
1381 sched == SchedStrategy::LCFSPI ||
1382 sched == SchedStrategy::LCFSPRPRIO ||
1383 sched == SchedStrategy::LCFSPIPRIO;
1384 // PR resumes the promoted job in the phase it was interrupted in;
1385 // PI discards that phase and restarts from the entry distribution.
1386 // That single value is the whole PR-vs-PI difference.
1387 const bool resume = sched == SchedStrategy::LCFSPR ||
1388 sched == SchedStrategy::LCFSPRPRIO ||
1389 sched == SchedStrategy::FCFSPR ||
1390 sched == SchedStrategy::FCFSPRPRIO;
1391 // Class column, 0-based and hence EVEN; L.bufw means "nobody waits".
1392 std::size_t pos = L.bufw;
1393 if (ni > S && !suppress_promote && L.bufw >= 2) {
1394 double best = std::numeric_limits<double>::infinity();
1395 if (prio_aware)
1396 // Only the class columns carry a class tag: reading the
1397 // phase columns too would let a phase index masquerade as a
1398 // class and win the group, which is what the reference's
1399 // FCFSPIPRIO/LCFSPIPRIO arms do (:1290, :1336) while its
1400 // PR-PRIO arms correctly restrict to `class_cols` (:1194).
1401 for (std::size_t b = 0; b + 1 < L.bufw; b += 2) {
1402 const double v = num_traits<T>::to_double(buf[b]);
1403 if (v <= 0) continue;
1404 const double p = sn.classes[static_cast<std::size_t>(v) - 1].prio;
1405 if (p < best) best = p;
1406 }
1407 for (std::size_t b = 0; b + 1 < L.bufw; b += 2) {
1408 const double v = num_traits<T>::to_double(buf[b]);
1409 if (v <= 0) continue;
1410 if (prio_aware && sn.classes[static_cast<std::size_t>(v) - 1].prio != best)
1411 continue;
1412 pos = b;
1413 // The buffer is newest-first, so LCFS takes the FIRST such
1414 // pair (:1052 colfirstnnz) and FCFS the LAST (:1121
1415 // colLastNnz). LCFS does NOT take the rightmost slot.
1416 if (lcfs) break;
1417 }
1418 }
1419 if (pos == L.bufw) {
1420 std::vector<T> row = buf;
1421 row.insert(row.end(), srv.begin(), srv.end());
1422 row.insert(row.end(), var.begin(), var.end());
1423 out.space.push_back(row);
1424 out.rate.push_back(T(lld * rate));
1425 out.prob.push_back(one);
1426 continue;
1427 }
1428 const std::size_t hc = static_cast<std::size_t>(num_traits<T>::to_double(buf[pos]));
1429 const std::size_t kst =
1430 static_cast<std::size_t>(num_traits<T>::to_double(buf[pos + 1]));
1431 if (hc == 0 || hc > R || kst == 0 || kst > L.K[hc - 1])
1432 throw InputError("after_event_station_dep: station '" +
1433 sn.stations[ist - 1].name +
1434 "' holds a waiting job whose [class, phase] pair is malformed");
1435 // Close the hole by padding a whole EMPTY PAIR on the left, keeping
1436 // the buffer right-aligned as `from_marginal` enumerates it and as
1437 // afterEventStation.m:1267-1274 requires. Removing the pair in place
1438 // (:1055, :1125) or padding one slot on each side (:1222) leaves a
1439 // layout the enumerator never emits, so the successor is unreachable
1440 // and the generator becomes reducible.
1441 std::vector<T> b2(L.bufw, zero);
1442 for (std::size_t b = 2; b <= pos + 1; ++b) b2[b] = buf[b - 2];
1443 for (std::size_t b = pos + 2; b < L.bufw; ++b) b2[b] = buf[b];
1444 if (resume) {
1445 std::vector<T> s3 = srv;
1446 s3[L.Ks[hc - 1] + kst - 1] += one;
1447 std::vector<T> row = b2;
1448 row.insert(row.end(), s3.begin(), s3.end());
1449 row.insert(row.end(), var.begin(), var.end());
1450 out.space.push_back(row);
1451 out.rate.push_back(T(lld * rate));
1452 out.prob.push_back(one);
1453 tag_last(out, hc, 0); // the promoted job resumes on the freed server
1454 } else {
1455 const std::vector<T> pentry = entry_phase_dist(sn, ist, hc);
1456 for (std::size_t ke = 0; ke < L.K[hc - 1]; ++ke) {
1457 std::vector<T> s3 = srv;
1458 s3[L.Ks[hc - 1] + ke] += one;
1459 std::vector<T> row = b2;
1460 row.insert(row.end(), s3.begin(), s3.end());
1461 row.insert(row.end(), var.begin(), var.end());
1462 out.space.push_back(row);
1463 out.rate.push_back(T(lld * rate * pentry[ke]));
1464 out.prob.push_back(one);
1465 tag_last(out, hc, 0);
1466 }
1467 }
1468 } else if (state_detail::buffer_is_per_class_count(sched)) {
1469 // A per-class-count buffer promotes by COUNT, since no order is
1470 // recorded. SIRO picks the next job at random, so every waiting
1471 // class is a distinct successor with its share of the queue.
1472 srv[col] -= one;
1473 const T rate = T(mu[k] * phi[k] * kir);
1474 double waiting = 0;
1475 for (std::size_t r = 0; r < R; ++r) waiting += num_traits<T>::to_double(buf[r]);
1476 if (waiting <= 0 || suppress_promote) {
1477 std::vector<T> row = buf;
1478 row.insert(row.end(), srv.begin(), srv.end());
1479 row.insert(row.end(), var.begin(), var.end());
1480 out.space.push_back(row);
1481 out.rate.push_back(T(lld * rate));
1482 out.prob.push_back(one);
1483 continue;
1484 }
1485 // SEPT and LEPT share SIRO's buffer layout but NOT its draw: the
1486 // freed server takes the waiting class with the shortest (SEPT) or
1487 // longest (LEPT) mean service time, deterministically, as
1488 // afterEventStation.m does through the schedparam rank. A tie goes
1489 // to the lowest class index.
1490 std::size_t ept_pick = 0;
1491 if (sched == SchedStrategy::SEPT || sched == SchedStrategy::LEPT) {
1492 const bool sept = sched == SchedStrategy::SEPT;
1493 double best = 0;
1494 for (std::size_t r = 1; r <= R; ++r) {
1495 if (num_traits<T>::to_double(buf[r - 1]) <= 0) continue;
1496 double v = num_traits<T>::to_double(sn.rates(ist - 1, r - 1));
1497 if (!std::isfinite(v))
1498 v = sept ? -std::numeric_limits<double>::infinity()
1499 : std::numeric_limits<double>::infinity();
1500 if (ept_pick == 0 || (sept ? v > best : v < best)) {
1501 ept_pick = r;
1502 best = v;
1503 }
1504 }
1505 }
1506 for (std::size_t r = 1; r <= R; ++r) {
1507 double nb = num_traits<T>::to_double(buf[r - 1]);
1508 if (nb <= 0) continue;
1509 if (ept_pick != 0) {
1510 if (r != ept_pick) continue;
1511 nb = waiting; // the ranked class is promoted with probability one
1512 }
1513 const std::vector<T> pentry = entry_phase_dist(sn, ist, r);
1514 for (std::size_t ke = 0; ke < L.K[r - 1]; ++ke) {
1515 std::vector<T> b2 = buf, s2 = srv;
1516 b2[r - 1] -= one;
1517 s2[L.Ks[r - 1] + ke] += one;
1518 std::vector<T> row = b2;
1519 row.insert(row.end(), s2.begin(), s2.end());
1520 row.insert(row.end(), var.begin(), var.end());
1521 out.space.push_back(row);
1522 out.rate.push_back(T(lld * rate));
1523 out.prob.push_back(T(num_traits<T>::from_double(nb / waiting) * pentry[ke]));
1524 tag_last(out, r, 0); // the drawn waiting class takes the server
1525 }
1526 }
1527 } else {
1528 throw UnsupportedError(ErrorKind{"SchedStrategy"},
1529 std::string("after_event_station_dep: the ") + lang::sched_to_text(sched) +
1530 " discipline is not ported yet");
1531 }
1532 }
1533 pad_tags(out);
1534 return out;
1535}
1536
1537/**
1538 * The fraction of the station's capacity a class-`cls` job in phase `k`
1539 * receives, which is the only part of the rate the discipline decides.
1540 *
1541 * PHASE and DEP share this factor exactly: an internal phase transition is
1542 * driven by the same server share as a completion, which is why a job under PS
1543 * advances through its phases more slowly when the station is busy. Only the
1544 * MATRIX differs -- D0(k,kdest) for a phase advance, D1 for a completion.
1545 */
1546template <class T>
1547T service_share(const NetworkStruct<T>& sn, std::size_t ist, const Marginal<T>& m,
1548 std::size_t cls, double ni, double S) {
1549 const std::size_t R = sn.nclasses;
1550 const SchedStrategy sched = sn.stations[ist - 1].sched;
1551 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
1552
1553 // The *PRIO variants behave as their base discipline while every job fits
1554 // in a server -- with n <= c nobody is waiting, so precedence is moot. Once
1555 // the station saturates, only the MOST URGENT group present is served, and
1556 // the sharing is computed among that group alone. `prio_pop` is the single
1557 // definition of that group, shared with the load-dependent lookup.
1558 const PrioPop<T> p = prio_pop(sn, ist, m, cls, ni, S);
1559 if (!p.served) return zero; // a lower-priority class gets no service at all
1560 const std::vector<T>& nir = p.nir;
1561 const double nieff = p.ni;
1562
1563 if (sched == SchedStrategy::PS || sched == SchedStrategy::LPS ||
1564 sched == SchedStrategy::PSPRIO)
1565 return nieff > 0 ? num_traits<T>::from_double(std::min(nieff, S) / nieff) : zero;
1566 if (sched == SchedStrategy::DPS || sched == SchedStrategy::GPS ||
1567 sched == SchedStrategy::DPSPRIO || sched == SchedStrategy::GPSPRIO) {
1568 if (S > 1)
1569 throw UnsupportedError(ErrorKind{"MultiServer"},
1570 "state_events: multi-server DPS/GPS stations are not supported");
1571 const bool dps = sched == SchedStrategy::DPS || sched == SchedStrategy::DPSPRIO;
1572 const std::vector<T>& w = sn.stations[ist - 1].schedparam;
1573 T wsum = zero;
1574 for (std::size_t r = 0; r < R; ++r) wsum += w[r];
1575 T denom = zero;
1576 for (std::size_t r = 0; r < R; ++r) {
1577 // DPS weights by the job COUNTS; GPS shares between the classes
1578 // PRESENT, so each contributes at most one however many it holds.
1579 const T nr = dps ? nir[r] : (num_traits<T>::to_double(nir[r]) > 0 ? one : zero);
1580 denom += T(w[r] / wsum * nr);
1581 }
1582 const T nc = nir[cls - 1];
1583 if (num_traits<T>::to_double(denom) == 0 || num_traits<T>::to_double(nc) == 0)
1584 return zero;
1585 const T sh = T((w[cls - 1] / wsum) / denom);
1586 return dps ? sh : T(sh / nc);
1587 }
1588 // INF and the queueing disciplines: a job in service holds a whole server.
1589 return one;
1590}
1591
1592/**
1593 * Port of the PHASE branch of `State.afterEventStation`: service advances a
1594 * phase WITHOUT completing.
1595 *
1596 * The rate is D0(k, kdest), the off-diagonal of the hidden generator, times the
1597 * same server share a completion gets. Keeping PHASE and DEP on one share is
1598 * what makes a phase-type service slow down consistently under contention; a
1599 * phase advance at full speed under PS would shorten the effective service.
1600 */
1601template <class T>
1603 const std::vector<T>& inspace, std::size_t cls) {
1604 const std::size_t R = sn.nclasses;
1605 const std::size_t ist = sn.nodes[ind - 1].station;
1606 const T one = num_traits<T>::from_int(1);
1607 EventOutcome<T> out;
1608 if (ist == 0) throw InputError("after_event_station_phase: node is not a station");
1609 const RowLayout<T> L = row_layout(sn, ind, inspace.size());
1610 const double S = sn.stations[ist - 1].nservers;
1611
1612 std::vector<std::size_t> ph(R, 1), shift(R, 0);
1613 for (std::size_t r = 0; r < R; ++r) {
1614 ph[r] = L.K[r];
1615 shift[r] = L.Ks[r];
1616 }
1617 const Marginal<T> m = to_marginal(sn, ist, inspace, ph, shift, L.nvar);
1618 if (num_traits<T>::to_double(m.nir[cls - 1]) <= 0) return out;
1619
1620 double ni = 0;
1621 for (std::size_t r = 0; r < R; ++r) ni += num_traits<T>::to_double(m.nir[r]);
1622 // Unlike DEP, the PHASE branch takes the UNMASKED population for both
1623 // factors even at a saturated *PRIO station (afterEventStation.m:1688): the
1624 // masking there is a property of the completion rate, not of the lookup, and
1625 // `service_share` already zeroes a non-urgent class's advance.
1626 const T lld = T(lld_factor(sn, ist, ni) * cd_factor(sn, ist, m.nir, cls));
1627 const T share = service_share(sn, ist, m, cls, ni, S);
1628 const lang::Distrib<T>& d = sn.service[ist - 1][cls - 1];
1629 if (d.D0.rows() != L.K[cls - 1]) return out;
1630 const CtmcMapc<T>* mcS = sn.mapc_of(ist, cls);
1631
1632 for (std::size_t k = 0; k < L.K[cls - 1]; ++k) {
1633 if (num_traits<T>::to_double(inspace[L.bufw + L.Ks[cls - 1] + k]) <= 0) continue;
1634 for (std::size_t kd = 0; kd < L.K[cls - 1]; ++kd) {
1635 if (kd == k) continue; // the diagonal is the exit rate, not a move
1636 std::vector<T> row = inspace;
1637 row[L.bufw + L.Ks[cls - 1] + k] -= one;
1638 row[L.bufw + L.Ks[cls - 1] + kd] += one;
1639 // A single-server MAP in carried form keeps its memory equal to the phase in service.
1640 if (mcS && mcS->single)
1641 row[L.bufw + L.srvw + sn.map_var_slot(ind, cls)] = num_traits<T>::from_int(static_cast<long>(kd + 1));
1642 out.space.push_back(row);
1643 out.rate.push_back(T(lld * d.D0(k, kd) * m.kir[cls - 1][k] * share));
1644 out.prob.push_back(one);
1645 }
1646 }
1647 return out;
1648}
1649
1650/**
1651 * `sn.impatienceMu(ist,cls)`: the rate of an exponential reneging patience, 0 when the class
1652 * declares none. The analyzers refuse a non-exponential patience before any event fires.
1653 */
1654template <class T>
1655T station_renege_mu(const NetworkStruct<T>& sn, std::size_t ist, std::size_t cls) {
1656 const Station<T>& st = sn.stations[ist - 1];
1657 if (cls > st.impatience.size() || st.impatience[cls - 1] != lang::ImpatienceType::RENEGING ||
1658 cls > st.patience.size() || st.patience[cls - 1].disabled ||
1659 !(st.patience[cls - 1].mean > num_traits<T>::from_int(0)))
1660 return num_traits<T>::from_int(0);
1661 return T(num_traits<T>::from_int(1) / st.patience[cls - 1].mean);
1662}
1663
1664/**
1665 * Port of `solver_ctmc_state_supports.m`: the impatience laws the state machinery cannot
1666 * serve, as the refusal sentence, or "" when it can. RENEGE and RETRY fire at a memoryless
1667 * rate and balking reads the station population, so a non-exponential patience or retrial
1668 * delay, a wait-based balking rule, a finite attempt count, orbit abandonment and a
1669 * multi-class retrial station would otherwise be answered as if they were absent.
1670 */
1671template <class T>
1672std::string state_impatience_unsupported(const NetworkStruct<T>& sn, const std::string& solver) {
1673 // RENEGE fires at (waiting jobs) * impatienceMu with no per-job patience phase, so the law
1674 // must be EXPONENTIAL, not merely Markovian (MATLAB sn_patience_exp_refusal)
1675 const std::string patWhy = ::line::api::sn_patience_exp_refusal(sn);
1676 if (!patWhy.empty()) return patWhy + " Use SolverLDES or SolverJMT for any other patience.";
1677 for (std::size_t i = 0; i < sn.stations.size(); ++i) {
1678 const Station<T>& st = sn.stations[i];
1679 for (std::size_t r = 0; r < st.balking.size(); ++r)
1680 if (st.balking[r].strategy != lang::BalkingStrategy::NONE &&
1682 return solver + " supports only QUEUE_LENGTH balking. Use SolverLDES or SolverJMT "
1683 "for wait-time-based balking.";
1684 }
1685 for (const auto& kv : sn.retrialparam) {
1686 const RetrialParam<T>& rp = kv.second;
1687 const Station<T>& st = sn.stations[kv.first - 1];
1688 bool any = false;
1689 for (std::size_t r = 0; r < rp.retrial_proc.size(); ++r) {
1690 if (rp.retrial_proc[r].disabled) continue;
1691 any = true;
1692 if (rp.retrial_proc[r].type != lang::ProcessType::EXP)
1693 return solver + " supports only exponential (memoryless) retrial delay. Use "
1694 "SolverLDES for a non-exponential retrial delay (SolverMAM requires an exponential one too).";
1695 if (r < rp.max_attempts.size() && rp.max_attempts[r] > 0) {
1696 // A finite maxAttempts is an attempt-level block of the CTMC
1697 // (ctmc_blocks.h), served for an OPEN class under the LINEAR
1698 // policy with persistent customers and no orbital search
1699 // (python `_finite_attempts_refusal`).
1700 if (solver != "SolverCTMC")
1701 return solver + " supports only unlimited retrials (maxAttempts=-1). Use SolverCTMC "
1702 "or SolverLDES for a finite maxAttempts.";
1703 const std::string& name = st.name;
1704 if (std::isfinite(sn.njobs()[r]))
1705 return solver + " cannot lose closed-class jobs after their last retrial at " + name +
1706 ": the chain would empty. A finite maxAttempts needs an open class.";
1707 if (r < rp.policy.size() && rp.policy[r] == 2)
1708 return solver + " serves a finite maxAttempts only under the LINEAR retrial policy at " +
1709 name + ": the CONSTANT policy retries the oldest orbiting job. Use SolverLDES.";
1711 return solver + " does not combine a finite maxAttempts with non-persistent customers at " +
1712 name + ". Use SolverLDES.";
1714 return solver + " does not combine a finite maxAttempts with orbital search at " + name +
1715 ". Use SolverLDES.";
1716 }
1717 if (r < st.orbit_impatience.size() && !st.orbit_impatience[r].disabled)
1718 return solver + " does not model abandonment from the retrial orbit "
1719 "(set_orbit_impatience). Use SolverMAM or SolverLDES.";
1720 }
1721 if (!any) continue;
1722 std::size_t served = 0;
1723 for (std::size_t r = 0; r < sn.nclasses; ++r)
1724 if (!sn.disabled[kv.first - 1][r] && sn.service[kv.first - 1][r].D0.rows() > 0) ++served;
1725 if (served > 1)
1726 return solver + " supports retrial only for single-class stations. Use SolverLDES for "
1727 "multi-class retrial.";
1728 }
1729 return "";
1730}
1731
1732/** True when station `ist` declares exponential reneging for some class. */
1733template <class T>
1734bool station_has_reneging(const NetworkStruct<T>& sn, std::size_t ist) {
1735 for (std::size_t r = 1; r <= sn.nclasses; ++r)
1736 if (station_renege_mu(sn, ist, r) > num_traits<T>::from_int(0)) return true;
1737 return false;
1738}
1739
1740/**
1741 * `sn.retrialMu(ist,cls)`: the rate of the exponential retrial delay, falling back to the
1742 * scalar `retrial_rate` when no process is given; 0 when the class has no orbit.
1743 */
1744template <class T>
1745T station_retrial_mu(const NetworkStruct<T>& sn, std::size_t ist, std::size_t cls) {
1746 const T zero = num_traits<T>::from_int(0);
1747 const typename std::map<std::size_t, RetrialParam<T>>::const_iterator rit =
1748 sn.retrialparam.find(ist);
1749 if (rit == sn.retrialparam.end()) return zero;
1750 const RetrialParam<T>& rp = rit->second;
1751 if (cls <= rp.retrial_proc.size() && !rp.retrial_proc[cls - 1].disabled &&
1752 rp.retrial_proc[cls - 1].mean > zero)
1753 return T(num_traits<T>::from_int(1) / rp.retrial_proc[cls - 1].mean);
1754 if (cls <= rp.retrial_rate.size() && rp.retrial_rate[cls - 1] > zero)
1755 return rp.retrial_rate[cls - 1];
1756 return zero;
1757}
1758
1759/** `sn.retrialPolicy(ist,cls) == CONSTANT`: one retry clock for the whole orbit. */
1760template <class T>
1761bool station_retrial_constant(const NetworkStruct<T>& sn, std::size_t ist, std::size_t cls) {
1762 const typename std::map<std::size_t, RetrialParam<T>>::const_iterator rit =
1763 sn.retrialparam.find(ist);
1764 return rit != sn.retrialparam.end() && cls <= rit->second.policy.size() &&
1765 rit->second.policy[cls - 1] == 2;
1766}
1767
1768/**
1769 * Port of the QUEUE_LENGTH balking branch of the ARV event: with the probability of the
1770 * threshold band holding the PRE-arrival station population, the arriving job refuses to
1771 * join and is lost, so the station row is left unchanged; every admitted branch is scaled
1772 * by one minus that probability. EXPECTED_WAIT and COMBINED read a mean wait, not the
1773 * state, and are refused by the analyzers.
1774 */
1775template <class T>
1776void apply_station_balking(const NetworkStruct<T>& sn, std::size_t ind,
1777 const std::vector<T>& inspace, std::size_t cls, EventOutcome<T>& out) {
1778 const std::size_t ist = sn.nodes[ind - 1].station;
1779 if (ist == 0 || out.space.empty()) return;
1780 const Station<T>& st = sn.stations[ist - 1];
1781 if (cls > st.balking.size() || st.balking[cls - 1].strategy != lang::BalkingStrategy::QUEUE_LENGTH)
1782 return;
1783 const std::size_t R = sn.nclasses;
1784 const RowLayout<T> L = row_layout(sn, ind, inspace.size());
1785 std::vector<std::size_t> ph(R, 1), shift(R, 0);
1786 for (std::size_t r = 0; r < R; ++r) {
1787 ph[r] = L.K[r];
1788 shift[r] = L.Ks[r];
1789 }
1790 const double qlen = num_traits<T>::to_double(to_marginal(sn, ist, inspace, ph, shift, L.nvar).ni);
1791 T pbalk = num_traits<T>::from_int(0);
1792 for (const typename Station<T>::BalkingThreshold& th : st.balking[cls - 1].thresholds)
1793 if (qlen >= th.min_jobs && (th.max_jobs < 0 || qlen <= th.max_jobs)) {
1794 pbalk = th.probability;
1795 break;
1796 }
1797 if (!(pbalk > num_traits<T>::from_int(0))) return;
1798 for (std::size_t i = 0; i < out.prob.size(); ++i)
1799 out.prob[i] = T(out.prob[i] * (num_traits<T>::from_int(1) - pbalk));
1800 out.space.push_back(inspace);
1801 out.rate.push_back(num_traits<T>::from_int(-1));
1802 out.prob.push_back(pbalk);
1803 pad_tags(out);
1804}
1805
1806/** True when station `ist` (1-based) has a retrial process for some class. */
1807template <class T>
1808bool station_is_retrial(const NetworkStruct<T>& sn, std::size_t ist) {
1809 const typename std::map<std::size_t, RetrialParam<T>>::const_iterator rit =
1810 sn.retrialparam.find(ist);
1811 if (rit == sn.retrialparam.end()) return false;
1812 for (std::size_t r = 0; r < rit->second.retrial_proc.size(); ++r)
1813 if (!rit->second.retrial_proc[r].disabled) return true;
1814 return false;
1815}
1816
1817/**
1818 * Non-persistent retrial customers, the ARV half (Phung-Duc 2019, Sec. 2): at a
1819 * retrial station a fresh class-`cls` arrival that finds every server busy joins
1820 * the orbit with probability `orbit_join` and is lost otherwise, so the station
1821 * row is left unchanged on the lost branch. Same form as the balking branch,
1822 * and applied after it, as `afterEventStation.m` does.
1823 */
1824template <class T>
1825void apply_station_orbit_join(const NetworkStruct<T>& sn, std::size_t ind,
1826 const std::vector<T>& inspace, std::size_t cls, EventOutcome<T>& out) {
1827 const std::size_t ist = sn.nodes[ind - 1].station;
1828 if (ist == 0 || out.space.empty() || !station_is_retrial(sn, ist)) return;
1829 const T one = num_traits<T>::from_int(1);
1830 const T p = sn.stations[ist - 1].orbit_join_of(cls - 1);
1831 if (!(p < one)) return;
1832 const RowLayout<T> L = row_layout(sn, ind, inspace.size());
1833 double occ = 0;
1834 for (std::size_t j = 0; j < L.srvw; ++j) occ += num_traits<T>::to_double(inspace[L.bufw + j]);
1835 if (occ < sn.stations[ist - 1].nservers) return;
1836 for (std::size_t i = 0; i < out.prob.size(); ++i) out.prob[i] = T(out.prob[i] * p);
1837 std::vector<T> inrow = inspace;
1838 std::size_t wmax = 0;
1839 for (std::size_t i = 0; i < out.space.size(); ++i) wmax = std::max(wmax, out.space[i].size());
1840 if (wmax > inrow.size()) inrow.insert(inrow.begin(), wmax - inrow.size(), num_traits<T>::from_int(0));
1841 out.space.push_back(inrow);
1842 out.rate.push_back(num_traits<T>::from_int(-1));
1843 out.prob.push_back(T(one - p));
1844 pad_tags(out);
1845}
1846
1847/**
1848 * Orbital search (Artalejo, Joshua and Krishnamoorthy 2002), the DEP half: port
1849 * of `orbitalSearchSplit` in `afterEventStation.m`. Each DEP successor of a
1850 * retrial station frees one server (a retrial station never promotes from the
1851 * orbit). With probability `orbit_search[s]` the server immediately takes a
1852 * class-s orbiting job (entry phase drawn from pie), provided the successor's
1853 * class-s orbit is not empty; with the remaining probability it stays idle.
1854 * Rates are split, so the total DEP rate is unchanged.
1855 */
1856template <class T>
1858 const std::vector<T>& inspace, EventOutcome<T>& out) {
1859 const std::size_t ist = sn.nodes[ind - 1].station;
1860 if (ist == 0 || out.space.empty() || !station_is_retrial(sn, ist)) return;
1861 const std::size_t R = sn.nclasses;
1862 const Station<T>& st = sn.stations[ist - 1];
1863 const T zero = num_traits<T>::from_int(0);
1864 const T one = num_traits<T>::from_int(1);
1865 bool any = false;
1866 for (std::size_t r = 0; r < R; ++r) any = any || st.orbit_search_of(r) > zero;
1867 if (!any) return;
1868 const RowLayout<T> L = row_layout(sn, ind, inspace.size());
1869 const std::size_t nbuf = L.bufw, nsrv = L.srvw;
1870 pad_tags(out);
1871 if (out.prob.size() == 1 && out.space.size() > 1) out.prob.assign(out.space.size(), out.prob[0]);
1872 EventOutcome<T> add;
1873 const std::size_t nrows = out.space.size();
1874 for (std::size_t j = 0; j < nrows; ++j) {
1875 const std::vector<T>& row = out.space[j];
1876 if (row.size() < nbuf + nsrv)
1877 throw InputError("Orbital search at station '" + sn.nodes[ind - 1].name +
1878 "': a departure successor has " + std::to_string(row.size()) +
1879 " columns, fewer than the " + std::to_string(nbuf + nsrv) +
1880 " buffer and server columns.");
1881 // the successor may be left-padded wider than the input row
1882 const std::size_t off = row.size() - inspace.size();
1883 const std::size_t b0 = off, bufw = nbuf;
1884 double busy = 0;
1885 for (std::size_t c = 0; c < nsrv; ++c) busy += num_traits<T>::to_double(row[b0 + bufw + c]);
1886 if (busy >= st.nservers) continue; // no free server in this successor
1887 T keep = one;
1888 for (std::size_t sc = 0; sc < R; ++sc) {
1889 const T theta = st.orbit_search_of(sc);
1890 if (!(theta > zero)) continue;
1891 const T tag = num_traits<T>::from_int(static_cast<long>(sc + 1));
1892 std::size_t slot = bufw;
1893 for (std::size_t b = 0; b < bufw; ++b)
1894 if (row[b0 + b] == tag) { slot = b; break; }
1895 if (slot == bufw) continue; // empty class-s orbit: the search finds nobody
1896 keep = T(keep - theta);
1897 const std::vector<T> pentry = entry_phase_dist(sn, ist, sc + 1);
1898 for (std::size_t ke = 0; ke < L.K[sc]; ++ke) {
1899 if (!(num_traits<T>::to_double(pentry[ke]) > 0)) continue;
1900 std::vector<T> rk = row;
1901 for (std::size_t b = slot; b > 0; --b) rk[b0 + b] = rk[b0 + b - 1];
1902 rk[b0] = zero;
1903 rk[b0 + bufw + L.Ks[sc] + ke] += one;
1904 add.space.push_back(rk);
1905 add.rate.push_back(T(out.rate[j] * theta * pentry[ke]));
1906 add.prob.push_back(out.prob[j]);
1907 std::vector<std::size_t> stg = out.start[j];
1908 stg.push_back(sc + 1);
1909 add.start.push_back(stg);
1910 add.preempt.push_back(out.preempt[j]);
1911 }
1912 }
1913 out.rate[j] = T(out.rate[j] * keep);
1914 }
1915 for (std::size_t i = 0; i < add.space.size(); ++i) {
1916 out.space.push_back(add.space[i]);
1917 out.rate.push_back(add.rate[i]);
1918 out.prob.push_back(add.prob[i]);
1919 out.start.push_back(add.start[i]);
1920 out.preempt.push_back(add.preempt[i]);
1921 }
1922 // drop arcs whose whole rate moved to the search branches (orbit_search = 1)
1923 EventOutcome<T> live;
1924 for (std::size_t i = 0; i < out.space.size(); ++i) {
1925 if (!(out.rate[i] > zero)) continue;
1926 live.space.push_back(out.space[i]);
1927 live.rate.push_back(out.rate[i]);
1928 live.prob.push_back(out.prob[i]);
1929 live.start.push_back(out.start[i]);
1930 live.preempt.push_back(out.preempt[i]);
1931 }
1932 out = live;
1933}
1934
1935/**
1936 * Port of the RENEGE branch: a WAITING class-`cls` job abandons the queue.
1937 *
1938 * Patience is exponential, so every waiting job abandons at the same rate and
1939 * the aggregate out of this state is (waiting count) * mu. Which job leaves is
1940 * therefore immaterial -- waiting jobs are exchangeable under memoryless
1941 * patience -- so the reference removes the first tagged slot and re-pads a zero
1942 * on the left, keeping the buffer in the right-aligned form the arrival handler
1943 * expects.
1944 */
1945template <class T>
1947 const std::vector<T>& inspace, std::size_t cls,
1948 const T& impatience_mu) {
1949 const std::size_t R = sn.nclasses;
1950 const std::size_t ist = sn.nodes[ind - 1].station;
1951 EventOutcome<T> out;
1952 if (ist == 0) throw InputError("after_event_station_renege: node is not a station");
1953 const RowLayout<T> L = row_layout(sn, ind, inspace.size());
1954
1955 std::vector<std::size_t> ph(R, 1), shift(R, 0);
1956 for (std::size_t r = 0; r < R; ++r) {
1957 ph[r] = L.K[r];
1958 shift[r] = L.Ks[r];
1959 }
1960 const Marginal<T> m = to_marginal(sn, ist, inspace, ph, shift, L.nvar);
1961 const double waiting = num_traits<T>::to_double(m.nir[cls - 1]) -
1962 num_traits<T>::to_double(m.sir[cls - 1]);
1963 if (waiting <= 0) return out;
1964 // The station's own impatienceMu unless the caller supplies one, as for breakdowns.
1965 const T mu = impatience_mu > num_traits<T>::from_int(0) ? impatience_mu
1966 : station_renege_mu(sn, ist, cls);
1967 if (!(mu > num_traits<T>::from_int(0))) return out;
1968
1969 const T tag = num_traits<T>::from_int(static_cast<long>(cls));
1970 std::size_t slot = L.bufw;
1971 for (std::size_t b = 0; b < L.bufw; ++b)
1972 if (inspace[b] == tag) { slot = b; break; }
1973 if (slot == L.bufw) return out;
1974
1975 std::vector<T> row = inspace;
1976 for (std::size_t b = slot; b > 0; --b) row[b] = row[b - 1];
1977 row[0] = num_traits<T>::from_int(0);
1978 out.space.push_back(row);
1979 out.rate.push_back(T(num_traits<T>::from_double(waiting) * mu));
1980 out.prob.push_back(num_traits<T>::from_int(1));
1981 return out;
1982}
1983
1984/**
1985 * Port of the RETRY branch: an ORBITING class-`cls` job retries entry.
1986 *
1987 * The retry succeeds only when a server is free; otherwise the job stays in
1988 * orbit and the event is not generated at all, which is exactly what
1989 * distinguishes a retrial queue from a queue whose buffer is called an orbit.
1990 *
1991 * @param constant_policy CONSTANT retrial: one controller retries for the whole
1992 * orbit, so the rate does NOT scale with the orbit size. Under the
1993 * default LINEAR policy every orbiting job carries its own timer and the
1994 * aggregate rate is (orbit size) * mu.
1995 * @param sn the refreshed network struct
1996 * @param ind index of the station the event fires at
1997 * @param inspace the state the event is applied to
1998 * @param cls class of the retrying job
1999 * @param retrial_mu retrial rate of that class
2000 */
2001template <class T>
2003 const std::vector<T>& inspace, std::size_t cls,
2004 const T& retrial_mu, bool constant_policy = false) {
2005 const std::size_t R = sn.nclasses;
2006 const std::size_t ist = sn.nodes[ind - 1].station;
2007 const T one = num_traits<T>::from_int(1);
2008 EventOutcome<T> out;
2009 if (ist == 0) throw InputError("after_event_station_retry: node is not a station");
2010 const RowLayout<T> L = row_layout(sn, ind, inspace.size());
2011 const double S = sn.stations[ist - 1].nservers;
2012
2013 std::vector<std::size_t> ph(R, 1), shift(R, 0);
2014 for (std::size_t r = 0; r < R; ++r) {
2015 ph[r] = L.K[r];
2016 shift[r] = L.Ks[r];
2017 }
2018 const Marginal<T> m = to_marginal(sn, ist, inspace, ph, shift, L.nvar);
2019 const double orbit = num_traits<T>::to_double(m.nir[cls - 1]) -
2020 num_traits<T>::to_double(m.sir[cls - 1]);
2021 double occ = 0;
2022 for (std::size_t j = 0; j < L.srvw; ++j) occ += num_traits<T>::to_double(inspace[L.bufw + j]);
2023 if (orbit <= 0) return out;
2024 // Non-persistent orbit (Phung-Duc 2019, Sec. 2): a retrial that finds every
2025 // server busy abandons with probability 1 - orbit_persist, so one orbiting
2026 // job leaves the system at (aggregate retrial rate) * (1 - q). With
2027 // probability q it returns to the orbit, a self-loop that is not generated.
2028 const T q = sn.stations[ist - 1].orbit_persist_of(cls - 1);
2029 if (occ >= S && !(q < one)) return out;
2030
2031 const T tag = num_traits<T>::from_int(static_cast<long>(cls));
2032 std::size_t slot = L.bufw;
2033 for (std::size_t b = 0; b < L.bufw; ++b)
2034 if (inspace[b] == tag) { slot = b; break; }
2035 if (slot == L.bufw) return out;
2036
2037 // The station's own retrialMu and policy unless the caller supplies a rate, as for breakdowns.
2038 const bool from_struct = !(retrial_mu > num_traits<T>::from_int(0));
2039 const T mu = from_struct ? station_retrial_mu(sn, ist, cls) : retrial_mu;
2040 if (!(mu > num_traits<T>::from_int(0))) return out;
2041 const bool constant = from_struct ? station_retrial_constant(sn, ist, cls) : constant_policy;
2042 const T agg = constant ? mu : T(num_traits<T>::from_double(orbit) * mu);
2043 if (occ >= S) {
2044 std::vector<T> row = inspace;
2045 for (std::size_t b = slot; b > 0; --b) row[b] = row[b - 1];
2046 row[0] = num_traits<T>::from_int(0);
2047 out.space.push_back(row);
2048 out.rate.push_back(T(agg * (one - q)));
2049 out.prob.push_back(one);
2050 pad_tags(out);
2051 return out;
2052 }
2053 const std::vector<T> pentry = entry_phase_dist(sn, ist, cls);
2054 for (std::size_t ke = 0; ke < L.K[cls - 1]; ++ke) {
2055 if (num_traits<T>::to_double(pentry[ke]) <= 0) continue;
2056 std::vector<T> row = inspace;
2057 for (std::size_t b = slot; b > 0; --b) row[b] = row[b - 1];
2058 row[0] = num_traits<T>::from_int(0);
2059 row[L.bufw + L.Ks[cls - 1] + ke] += one;
2060 out.space.push_back(row);
2061 out.rate.push_back(T(agg * pentry[ke]));
2062 out.prob.push_back(one);
2063 // A successful retry is the only way into the server at a retrial
2064 // station (its departures never promote from the orbit), so it carries
2065 // the START the startRate == TN + preemptRate identity needs.
2066 tag_last(out, cls, 0);
2067 }
2068 pad_tags(out);
2069 return out;
2070}
2071
2072/**
2073 * Port of the FAILURE and REPAIR branches: the server goes down, or comes back.
2074 *
2075 * Only the STATUS column moves, which is the trailing local variable. Jobs in
2076 * service are NOT lost: service is memoryless here, so an interrupted job
2077 * resumes on repair with no state to remember. The passive half of the
2078 * synchronization is LOCAL, so no job moves anywhere in the network either.
2079 *
2080 * @param up true for REPAIR (0 -> 1), false for FAILURE (1 -> 0)
2081 * @param mu breakdownMu for a failure, repairMu for a repair
2082 * @param sn the refreshed network struct
2083 * @param ind index of the station the event fires at
2084 * @param inspace the state the event is applied to
2085 */
2086template <class T>
2088 const std::vector<T>& inspace, bool up,
2089 const T& mu) {
2090 EventOutcome<T> out;
2091 if (inspace.empty() || !sn.has_breakdown_node(ind)) return out;
2092 const double status = num_traits<T>::to_double(inspace.back());
2093 // A failure needs an UP server and a repair a DOWN one; anything else is
2094 // not an admissible transition and must produce no edge at all.
2095 if ((up && status != 0) || (!up && status != 1)) return out;
2096 std::vector<T> row = inspace;
2097 row.back() = num_traits<T>::from_int(up ? 1 : 0);
2098 // The rate is the station's own breakdownMu / repairMu unless the caller
2099 // supplies one; no caller does today, so the struct is the source of truth.
2100 T rate = mu;
2101 if (!(rate > num_traits<T>::from_int(0))) {
2102 const BreakdownParam<T>& bp = sn.breakdownparam.at(sn.nodes[ind - 1].station);
2103 rate = up ? bp.repair_rate : bp.failure_rate;
2104 }
2105 out.space.push_back(row);
2106 out.rate.push_back(rate);
2107 out.prob.push_back(num_traits<T>::from_int(1));
2108 return out;
2109}
2110
2111/**
2112 * Port of `State.afterEventFork`: an event at a STATEFUL Fork node.
2113 *
2114 * The fork's state is a plain per-class count of PARENT jobs momentarily held
2115 * between their arrival and the firing. An arrival buffers one; a DEPARTURE DOES
2116 * NOT EXIST, because the multi-branch emission is atomic across several nodes and
2117 * cannot be decomposed into a departure here plus an arrival there --
2118 * `refresh_sync` emits no DEP sync for a Fork and `after_fj_event` fires instead.
2119 *
2120 * The arrival rate is left UNSET (the reference writes -1) because an ARV is the
2121 * PASSIVE half of a synchronization: the rate belongs to the active departure
2122 * upstream.
2123 */
2124template <class T>
2126 const std::vector<T>& inspace, EventType event,
2127 std::size_t cls) {
2128 const std::size_t R = sn.nclasses;
2129 EventOutcome<T> out;
2130 if (event != EventType::ARV) return out;
2131 if (inspace.size() < R)
2132 throw InputError("after_event_fork: the Fork state row at node '" + sn.nodes[ind - 1].name +
2133 "' is narrower than the class set");
2134 // An OPEN chain's fork-join section is truncated at its tag pool (the CTMC
2135 // cutoff, `fj_tag`): a parent arriving while that many already wait for a
2136 // tag is not held, as python `after_event_fork` refuses it.
2137 if (!std::isfinite(sn.njobs()[cls - 1])) {
2138 for (std::map<std::size_t, FjJoinParam>::const_iterator jt = sn.fjjoinparam.begin();
2139 jt != sn.fjjoinparam.end(); ++jt) {
2140 if (jt->second.fork != ind) continue;
2141 const std::map<std::size_t, std::vector<std::vector<std::size_t>>>::const_iterator ax =
2142 jt->second.auxmatrix.find(cls);
2143 if (ax == jt->second.auxmatrix.end() || ax->second.empty()) continue;
2144 const double pool = static_cast<double>(ax->second[0].size());
2145 if (num_traits<T>::to_double(inspace[inspace.size() - R + cls - 1]) >= pool) return out;
2146 }
2147 }
2148 std::vector<T> row = inspace;
2149 // The counts are the LAST R columns, which is where `from_marginal_node`
2150 // puts them and where `after_fj_event` reads them.
2151 row[row.size() - R + cls - 1] += num_traits<T>::from_int(1);
2152 out.space.push_back(row);
2153 out.rate.push_back(num_traits<T>::from_int(-1));
2154 out.prob.push_back(num_traits<T>::from_int(1));
2155 return out;
2156}
2157
2158/**
2159 * Port of `State.afterEventJoin`: an event at a Join node of an FJ-augmented
2160 * struct.
2161 *
2162 * The join's state is a plain per-class count vector of BUFFERED jobs, so it
2163 * bypasses the buffer/server/local slicing every other station takes -- a join
2164 * performs no service, it performs a rendezvous.
2165 *
2166 * ARV buffers the arriving job or sibling. DEP in an ORIGINAL class r fires when
2167 * either a plain (never-forked) class-r job is buffered, or some tag has its full
2168 * required sibling multiset present; the firing consumes the siblings of the
2169 * LOWEST complete tag, which is the same canonical choice the fork's allocation
2170 * makes and is what keeps the two in step. DEP in an AUXILIARY class is refused
2171 * outright: a sibling never departs on its own, it is consumed by the parent's
2172 * firing, and letting it depart would release a job the fork never emitted.
2173 */
2174template <class T>
2176 const std::vector<T>& inspace, EventType event,
2177 std::size_t cls) {
2178 const std::size_t R = sn.nclasses;
2179 const T one = num_traits<T>::from_int(1);
2180 EventOutcome<T> out;
2181 if (inspace.size() < R)
2182 throw InputError("after_event_join: the Join state row at node '" + sn.nodes[ind - 1].name +
2183 "' is narrower than the class set");
2184 const std::size_t off = inspace.size() - R;
2185 const typename std::map<std::size_t, FjJoinParam>::const_iterator jit =
2186 sn.fjjoinparam.find(ind);
2187 const FjJoinParam* fjp = jit == sn.fjjoinparam.end() ? 0 : &jit->second;
2188
2189 if (event == EventType::ARV) {
2190 std::vector<T> row = inspace;
2191 // A straggler of a tag whose QUORUM already fired is discarded here: the
2192 // row's leading debt counters (one per tag, `fj_tag`) say how many of
2193 // that tag's siblings are still on the branches.
2194 std::size_t slot = static_cast<std::size_t>(-1);
2195 if (fjp && fjp->debtwidth > 0)
2196 for (std::size_t x = 0; x < fjp->origclasses.size() && slot == static_cast<std::size_t>(-1); ++x) {
2197 const std::size_t r = fjp->origclasses[x];
2198 const std::map<std::size_t, std::size_t>::const_iterator q = fjp->quorum.find(r);
2199 const std::map<std::size_t, std::vector<std::vector<std::size_t>>>::const_iterator ax =
2200 fjp->auxmatrix.find(r);
2201 if (q == fjp->quorum.end() || ax == fjp->auxmatrix.end()) continue;
2202 for (std::size_t b = 0; b < ax->second.size() && slot == static_cast<std::size_t>(-1); ++b)
2203 for (std::size_t t = 0; t < ax->second[b].size(); ++t)
2204 if (ax->second[b][t] == cls) {
2205 slot = fjp->debtoff.at(r) + t;
2206 break;
2207 }
2208 }
2209 if (slot != static_cast<std::size_t>(-1) && slot < off &&
2210 num_traits<T>::to_double(row[slot]) > 0)
2211 row[slot] -= one;
2212 else
2213 row[off + cls - 1] += one;
2214 out.space.push_back(row);
2215 out.rate.push_back(num_traits<T>::from_int(-1));
2216 out.prob.push_back(one);
2217 return out;
2218 }
2219 if (event != EventType::DEP) return out;
2220
2221 if (fjp) {
2222 for (std::size_t x = 0; x < fjp->origclasses.size(); ++x) {
2223 const std::map<std::size_t, std::vector<std::vector<std::size_t>>>::const_iterator ait =
2224 fjp->auxmatrix.find(fjp->origclasses[x]);
2225 if (ait == fjp->auxmatrix.end()) continue;
2226 for (std::size_t b = 0; b < ait->second.size(); ++b)
2227 for (std::size_t t = 0; t < ait->second[b].size(); ++t)
2228 if (ait->second[b][t] == cls) return out; // an auxiliary class
2229 }
2230 }
2231
2233 if (num_traits<T>::to_double(inspace[off + cls - 1]) > 0) {
2234 // A plain job that never went through the fork: it passes straight
2235 // through, since a join is a rendezvous only for siblings.
2236 std::vector<T> row = inspace;
2237 row[off + cls - 1] -= one;
2238 out.space.push_back(row);
2239 out.rate.push_back(imm);
2240 out.prob.push_back(one);
2241 return out;
2242 }
2243 if (!fjp) return out;
2244 const std::map<std::size_t, std::vector<std::vector<std::size_t>>>::const_iterator ait =
2245 fjp->auxmatrix.find(cls);
2246 const std::map<std::size_t, std::vector<std::size_t>>::const_iterator rit =
2247 fjp->required.find(cls);
2248 if (ait == fjp->auxmatrix.end() || rit == fjp->required.end()) return out;
2249 const std::vector<std::vector<std::size_t>>& aux = ait->second;
2250 const std::vector<std::size_t>& req = rit->second;
2251 if (aux.empty()) return out;
2252 const std::size_t B = aux.size(), Tt = aux[0].size();
2253 // QUORUM (JoinStrategy.PARTIAL): the join fires on the lowest FRESH tag
2254 // (no stragglers pending) holding k siblings in total, whichever branches
2255 // they came from; they are consumed, and the tag's debt counter records how
2256 // many of its siblings are still on the branches (python after_event_join).
2257 const std::map<std::size_t, std::size_t>::const_iterator qit = fjp->quorum.find(cls);
2258 if (qit != fjp->quorum.end()) {
2259 const std::size_t doff = fjp->debtoff.at(cls);
2260 double total = 0;
2261 for (std::size_t b = 0; b < req.size(); ++b) total += static_cast<double>(req[b]);
2262 for (std::size_t t = 0; t < Tt; ++t) {
2263 if (doff + t >= off || num_traits<T>::to_double(inspace[doff + t]) != 0) continue;
2264 double held = 0;
2265 for (std::size_t b = 0; b < B; ++b) held += num_traits<T>::to_double(inspace[off + aux[b][t] - 1]);
2266 if (held < static_cast<double>(qit->second)) continue;
2267 std::vector<T> row = inspace;
2268 for (std::size_t b = 0; b < B; ++b) row[off + aux[b][t] - 1] = num_traits<T>::from_int(0);
2269 row[doff + t] = num_traits<T>::from_int(static_cast<long>(total - held + 0.5));
2270 out.space.push_back(row);
2271 out.rate.push_back(imm);
2272 out.prob.push_back(one);
2273 return out; // the LOWEST fresh tag only
2274 }
2275 return out;
2276 }
2277 for (std::size_t t = 0; t < Tt; ++t) {
2278 bool complete = true;
2279 for (std::size_t b = 0; b < B && complete; ++b) {
2280 const std::size_t a = aux[b][t];
2281 const double need = b < req.size() ? static_cast<double>(req[b]) : 1.0;
2282 if (num_traits<T>::to_double(inspace[off + a - 1]) < need) complete = false;
2283 }
2284 if (!complete) continue;
2285 std::vector<T> row = inspace;
2286 for (std::size_t b = 0; b < B; ++b) {
2287 const std::size_t a = aux[b][t];
2288 const long need = b < req.size() ? static_cast<long>(req[b]) : 1;
2289 row[off + a - 1] -= num_traits<T>::from_int(need);
2290 }
2291 out.space.push_back(row);
2292 out.rate.push_back(imm);
2293 out.prob.push_back(one);
2294 return out; // the LOWEST complete tag only; the rest are permutations
2295 }
2296 return out;
2297}
2298
2299/**
2300 * Port of `State.afterEventStation`'s dispatch: the successors of one event at
2301 * one station.
2302 *
2303 * The event-specific rates -- patience, retrial and breakdown -- are read from
2304 * the struct, as the reference reads `impatienceMu`, `retrialMu` and
2305 * `breakdownMu`/`repairMu`: `station_renege_mu`, `station_retrial_mu` and the
2306 * station's `breakdownparam` failure/repair rates are the default, and a
2307 * positive rate passed by the caller overrides them. Every other rate is
2308 * likewise computed from the struct.
2309 */
2310template <class T>
2311void rr_advance_row(const NetworkStruct<T>& sn, std::size_t ind, std::size_t cls,
2312 std::vector<std::vector<T>>& rows);
2313
2314/**
2315 * Port of `State.afterEventRouter`: a Router holds a job for the instant it
2316 * takes to decide where it goes.
2317 *
2318 * The row is [per-class counts | local vars], with no buffer and no phase: a
2319 * Router serves nothing, so there is no service state to carry. An ARRIVAL adds
2320 * the job at an UNSPECIFIED rate (-1), which is the reference's marker for a
2321 * passive half whose rate the active half sets; a DEPARTURE removes it at the
2322 * Immediate rate and advances the dispatch pointer, so the router never holds a
2323 * job for a positive length of time.
2324 */
2325template <class T>
2327 const std::vector<T>& inspace, EventType event,
2328 std::size_t cls) {
2329 EventOutcome<T> out;
2330 const std::size_t R = sn.nclasses;
2331 if (inspace.size() < R) return out;
2332 const T one = num_traits<T>::from_int(1);
2333 if (event == EventType::ARV) {
2334 std::vector<T> row = inspace;
2335 row[cls - 1] = T(row[cls - 1] + one);
2336 out.space.push_back(row);
2337 // Passive action: the rate is the active half's, not this node's.
2338 out.rate.push_back(num_traits<T>::from_int(-1));
2339 out.prob.push_back(one);
2340 return out;
2341 }
2342 if (event == EventType::DEP) {
2343 if (!(num_traits<T>::to_double(inspace[cls - 1]) > 0)) return out;
2344 std::vector<T> row = inspace;
2345 row[cls - 1] = T(row[cls - 1] - one);
2346 out.space.push_back(row);
2348 out.prob.push_back(one);
2349 rr_advance_row(sn, ind, cls, out.space);
2350 return out;
2351 }
2352 return out;
2353}
2354
2355/**
2356 * Advance the round-robin dispatch pointer of (IND, CLS) in every successor row.
2357 *
2358 * The local-variable block is the TAIL of a state row, so the pointer is located
2359 * from the right; `rr_var_slot` gives its 1-based index inside that block. A
2360 * no-op wherever the pair does not dispatch round-robin.
2361 */
2362template <class T>
2363void rr_advance_row(const NetworkStruct<T>& sn, std::size_t ind, std::size_t cls,
2364 std::vector<std::vector<T>>& rows) {
2365 if (sn.rr_var_slot(ind, cls) == 0) return;
2366 const std::size_t w = sn.nvars_of(ind);
2367 if (w == 0) return;
2368 for (std::size_t i = 0; i < rows.size(); ++i) {
2369 if (rows[i].size() < w) continue;
2370 std::vector<T> var(rows[i].end() - w, rows[i].end());
2371 sn.rr_advance(ind, cls, var);
2372 std::copy(var.begin(), var.end(), rows[i].end() - w);
2373 }
2374}
2375
2376namespace pool_detail {
2377
2378/** One successor of a pooled service start: the buffer, the servers, its weight and the class started. */
2379template <class T>
2381 std::vector<T> buf, srv;
2382 T p;
2383 std::size_t cls;
2384};
2385
2386/** Class s starts service on pool t in every entry phase of the pool's block. */
2387template <class T>
2388void pool_start(const CtmcPool<T>& pool, const std::vector<std::size_t>& Ks,
2389 const std::vector<T>& buf, const std::vector<T>& srv, std::size_t s,
2390 std::size_t t, const T& w, std::vector<PoolStart<T>>& out) {
2391 const std::vector<std::size_t>& ps = pool.pools[s - 1];
2392 std::size_t k = 0;
2393 while (k < ps.size() && ps[k] != t) ++k;
2394 const std::vector<T>& a = pool.alpha[s - 1][k];
2395 for (std::size_t j = 0; j < a.size(); ++j) {
2396 if (!(num_traits<T>::to_double(a[j]) > 0)) continue;
2397 PoolStart<T> st{buf, srv, T(w * a[j]), s};
2398 st.srv[Ks[s - 1] + pool.off[s - 1][k] + j] += num_traits<T>::from_int(1);
2399 out.push_back(st);
2400 }
2401}
2402
2403/** The freed server of pool t takes the next compatible waiting job, in the discipline's order. */
2404template <class T>
2405std::vector<PoolStart<T>> pool_serve_next(const NetworkStruct<T>& sn, const CtmcPool<T>& pool,
2406 SchedStrategy sched, const std::vector<std::size_t>& Ks,
2407 const std::vector<T>& buf, const std::vector<T>& srv,
2408 std::size_t t) {
2409 const std::size_t R = sn.nclasses;
2410 const T one = num_traits<T>::from_int(1), zero = num_traits<T>::from_int(0);
2411 std::vector<PoolStart<T>> out;
2412 if (sched == SchedStrategy::SIRO) {
2413 double tot = 0;
2414 for (std::size_t s = 0; s < R; ++s)
2415 if (pool.compat[t - 1][s]) tot += num_traits<T>::to_double(buf[s]);
2416 if (tot <= 0) {
2417 out.push_back(PoolStart<T>{buf, srv, one, 0});
2418 return out;
2419 }
2420 for (std::size_t s = 0; s < R; ++s) {
2421 const double bs = num_traits<T>::to_double(buf[s]);
2422 if (!pool.compat[t - 1][s] || bs <= 0) continue;
2423 std::vector<T> b = buf;
2424 b[s] -= one;
2425 pool_start(pool, Ks, b, srv, s + 1, t, num_traits<T>::from_double(bs / tot), out);
2426 }
2427 return out;
2428 }
2429 std::vector<std::size_t> pos;
2430 for (std::size_t p = 0; p < buf.size(); ++p) {
2431 const long c = static_cast<long>(num_traits<T>::to_double(buf[p]) + 0.5);
2432 if (c >= 1 && static_cast<std::size_t>(c) <= R && pool.compat[t - 1][c - 1]) pos.push_back(p);
2433 }
2434 if (pos.empty()) {
2435 out.push_back(PoolStart<T>{buf, srv, one, 0});
2436 return out;
2437 }
2438 const auto cls_at = [&](std::size_t p) {
2439 return static_cast<std::size_t>(num_traits<T>::to_double(buf[p]) + 0.5);
2440 };
2441 if (sched == SchedStrategy::HOL || sched == SchedStrategy::LCFSPRIO) {
2442 int best = sn.classes[cls_at(pos[0]) - 1].prio;
2443 for (std::size_t i = 1; i < pos.size(); ++i)
2444 best = std::min(best, sn.classes[cls_at(pos[i]) - 1].prio); // lower value, higher priority
2445 std::vector<std::size_t> keep;
2446 for (std::size_t i = 0; i < pos.size(); ++i)
2447 if (sn.classes[cls_at(pos[i]) - 1].prio == best) keep.push_back(pos[i]);
2448 pos.swap(keep);
2449 }
2450 // LCFS takes the leftmost (newest) job, the others the rightmost (oldest)
2451 const bool lcfs = sched == SchedStrategy::LCFS || sched == SchedStrategy::LCFSPRIO;
2452 const std::size_t p = lcfs ? pos.front() : pos.back();
2453 const std::size_t s = cls_at(p);
2454 std::vector<T> b(1, zero);
2455 for (std::size_t q = 0; q < buf.size(); ++q)
2456 if (q != p) b.push_back(buf[q]);
2457 pool_start(pool, Ks, b, srv, s, t, one, out);
2458 return out;
2459}
2460
2461} // namespace pool_detail
2462
2463/**
2464 * Port of `State.afterEventStationPool`: ARV, DEP and PHASE at a station whose
2465 * heterogeneous server pools `ctmc::ctmc_pools` rewrote (`sn.ctmcpool`). The row is
2466 * [buffer | servers | pool order]: the buffer holds the WAITING jobs only (class ids
2467 * right-aligned, the rightmost the oldest; per-class counts under SIRO), and the
2468 * class-r server block holds one sub-block of phases per compatible pool. LDES
2469 * semantics: an arrival takes a compatible pool with a free server, chosen by the
2470 * HeteroSchedPolicy (ORDER lowest index, ALFS least flexible, FSF fastest, RAIS
2471 * uniform, ALIS/FAIRNESS first of the rotating order, rotated only when there was
2472 * more than one candidate), or waits; a freed server of pool t takes the first
2473 * waiting job, in the discipline's order, that t can serve.
2474 */
2475template <class T>
2477 const std::vector<T>& inspace, EventType event,
2478 std::size_t cls) {
2480 const std::size_t R = sn.nclasses;
2481 const std::size_t ist = sn.nodes[ind - 1].station;
2482 const CtmcPool<T>& pool = sn.ctmcpool.at(ind);
2483 const SchedStrategy sched = sn.stations[ist - 1].sched;
2484 const T one = num_traits<T>::from_int(1), minus_one = num_traits<T>::from_int(-1);
2485 const RowLayout<T> L = row_layout(sn, ind, inspace.size());
2486 const std::vector<T> buf(inspace.begin(), inspace.begin() + L.bufw);
2487 const std::vector<T> srv(inspace.begin() + L.bufw, inspace.begin() + L.bufw + L.srvw);
2488 const std::vector<T> var(inspace.begin() + L.bufw + L.srvw, inspace.end());
2489 const std::vector<std::size_t>& myp = pool.pools[cls - 1];
2490 EventOutcome<T> out;
2491 const auto emit = [&](const std::vector<T>& b, const std::vector<T>& s, const std::vector<T>& v,
2492 const T& rate, const T& prob, std::size_t started) {
2493 std::vector<T> row = b;
2494 row.insert(row.end(), s.begin(), s.end());
2495 row.insert(row.end(), v.begin(), v.end());
2496 out.space.push_back(row);
2497 out.rate.push_back(rate);
2498 out.prob.push_back(prob);
2499 tag_last(out, started, 0);
2500 };
2501 if (myp.empty()) return out; // the class is not served here
2502 if (event == EventType::ARV) {
2503 const std::pair<T, std::vector<T>> mg = to_marginal_aggr(sn, ind, inspace);
2504 const double ni = num_traits<T>::to_double(mg.first);
2505 const double nir = num_traits<T>::to_double(mg.second[cls - 1]);
2506 if (is_physical_capacity(sn, ist, cls) &&
2507 (ni >= sn.cap[ist - 1] || nir >= sn.classcap[ist - 1][cls - 1])) {
2508 // a lost job leaves the state unchanged, so the arrival still fires; else blocked
2509 if (arrival_is_lost(sn, ist, cls)) emit(buf, srv, var, minus_one, one, 0);
2510 pad_tags(out);
2511 return out;
2512 }
2513 std::vector<double> busy(pool.ntypes, 0.0);
2514 for (std::size_t r = 0; r < R; ++r)
2515 for (std::size_t k = 0; k < pool.pools[r].size(); ++k)
2516 for (std::size_t j = 0; j < pool.len[r][k]; ++j)
2517 busy[pool.pools[r][k] - 1] +=
2518 num_traits<T>::to_double(srv[L.Ks[r] + pool.off[r][k] + j]);
2519 std::vector<std::size_t> cand;
2520 for (std::size_t k = 0; k < myp.size(); ++k)
2521 if (busy[myp[k] - 1] < pool.count[myp[k] - 1]) cand.push_back(myp[k]);
2522 if (cand.empty()) {
2523 // no free compatible server: the job waits
2524 std::vector<T> b = buf;
2525 if (sched == SchedStrategy::SIRO) {
2526 b[cls - 1] += one;
2527 } else {
2528 std::size_t slot = 0; // 1-based index of the last empty slot
2529 for (std::size_t q = 0; q < b.size(); ++q)
2530 if (num_traits<T>::to_double(b[q]) == 0) slot = q + 1;
2531 if (slot == 0) {
2532 b.insert(b.begin(), num_traits<T>::from_int(0));
2533 slot = 1;
2534 }
2535 b[slot - 1] = num_traits<T>::from_int(static_cast<long>(cls));
2536 }
2537 emit(b, srv, var, minus_one, one, 0);
2538 pad_tags(out);
2539 return out;
2540 }
2541 std::vector<std::size_t> choice(1, cand[0]);
2542 std::vector<T> pchoice(1, one);
2543 std::vector<T> varc = var;
2544 if (cand.size() > 1) {
2545 switch (pool.policy) {
2547 for (std::size_t q = 0; q < pool.alfsorder.size(); ++q)
2548 if (std::find(cand.begin(), cand.end(), pool.alfsorder[q]) != cand.end()) {
2549 choice[0] = pool.alfsorder[q];
2550 break;
2551 }
2552 break;
2554 std::size_t at = 0; // the first maximum wins ties
2555 for (std::size_t q = 1; q < cand.size(); ++q)
2556 if (pool.fsfrate[cand[q] - 1][cls - 1] > pool.fsfrate[cand[at] - 1][cls - 1]) at = q;
2557 choice[0] = cand[at];
2558 break;
2559 }
2561 choice = cand;
2562 pchoice.assign(cand.size(), num_traits<T>::from_double(1.0 / static_cast<double>(cand.size())));
2563 break;
2566 if (pool.rotate) {
2567 const std::size_t vp = varc.size() - 1;
2568 const std::size_t pid =
2569 static_cast<std::size_t>(num_traits<T>::to_double(varc[vp]) + 0.5);
2570 std::vector<std::size_t> ord = pool.perms.at(pid - 1);
2571 for (std::size_t q = 0; q < ord.size(); ++q)
2572 if (std::find(cand.begin(), cand.end(), ord[q]) != cand.end()) {
2573 choice[0] = ord[q];
2574 ord.erase(ord.begin() + static_cast<std::ptrdiff_t>(q));
2575 ord.push_back(choice[0]);
2576 break;
2577 }
2578 varc[vp] = num_traits<T>::from_int(static_cast<long>(pool.perm_index(ord)));
2579 }
2580 break;
2581 default:
2582 break; // ORDER: the lowest index
2583 }
2584 }
2585 std::vector<PoolStart<T>> starts;
2586 for (std::size_t c = 0; c < choice.size(); ++c)
2587 pool_detail::pool_start(pool, L.Ks, buf, srv, cls, choice[c], pchoice[c], starts);
2588 for (std::size_t i = 0; i < starts.size(); ++i)
2589 emit(starts[i].buf, starts[i].srv, varc, minus_one, starts[i].p, cls);
2590 pad_tags(out);
2591 return out;
2592 }
2593 for (std::size_t k = 0; k < myp.size(); ++k) {
2594 const std::size_t t = myp[k];
2595 for (std::size_t j = 0; j < pool.len[cls - 1][k]; ++j) {
2596 const std::size_t col = L.Ks[cls - 1] + pool.off[cls - 1][k] + j;
2597 const T nj = srv[col];
2598 if (!(num_traits<T>::to_double(nj) > 0)) continue;
2599 if (event == EventType::DEP) {
2600 const T ex = pool.exit[cls - 1][k][j];
2601 if (!(num_traits<T>::to_double(ex) > 0)) continue;
2602 std::vector<T> sd = srv;
2603 sd[col] -= one;
2604 const std::vector<PoolStart<T>> nx =
2605 pool_detail::pool_serve_next(sn, pool, sched, L.Ks, buf, sd, t);
2606 for (std::size_t b = 0; b < nx.size(); ++b)
2607 emit(nx[b].buf, nx[b].srv, var, T(ex * nj * nx[b].p), one, nx[b].cls);
2608 } else if (event == EventType::PHASE) {
2609 const Matrix<T>& D0 = pool.D0[cls - 1][k];
2610 for (std::size_t jd = 0; jd < pool.len[cls - 1][k]; ++jd) {
2611 if (jd == j || !(num_traits<T>::to_double(D0(j, jd)) > 0)) continue;
2612 std::vector<T> sp = srv;
2613 sp[col] -= one;
2614 sp[L.Ks[cls - 1] + pool.off[cls - 1][k] + jd] += one;
2615 emit(buf, sp, var, T(D0(j, jd) * nj), one, 0);
2616 }
2617 }
2618 }
2619 }
2620 pad_tags(out);
2621 return out;
2622}
2623
2624namespace rr_detail {
2625
2626/**
2627 * `sub_bufpush`: put (class R, phase K) at the TAIL of a paired buffer, the
2628 * rightmost empty pair (the oldest job is on the right). A full buffer is
2629 * widened by one pair on the LEFT, which is how the reference grows it; the
2630 * state-space walkers left-pad every row to the node's widest one, and every
2631 * block is measured from the right, so the extra pair shifts nothing.
2632 */
2633template <class T>
2634std::vector<T> bufpush(std::vector<T> buf, std::size_t r, std::size_t k) {
2635 std::size_t e = static_cast<std::size_t>(-1);
2636 for (std::size_t j = 0; 2 * j + 1 < buf.size(); ++j)
2637 if (num_traits<T>::to_double(buf[2 * j]) == 0) e = j;
2638 if (e == static_cast<std::size_t>(-1)) {
2639 buf.insert(buf.begin(), 2, num_traits<T>::from_int(0));
2640 e = 0;
2641 }
2642 buf[2 * e] = num_traits<T>::from_int(static_cast<long>(r));
2643 buf[2 * e + 1] = num_traits<T>::from_int(static_cast<long>(k));
2644 return buf;
2645}
2646
2647/** One successor of `promote`: the row, its probability and the started class (0 for none). */
2648template <class T>
2649struct Promoted {
2650 std::vector<T> row;
2652 std::size_t start;
2653};
2654
2655/**
2656 * `sub_promote`: move the HEAD of the buffer (its rightmost non-empty pair)
2657 * into service with a fresh quantum, one successor per quantum entry phase.
2658 * With an empty buffer the row is returned unchanged with probability 1.
2659 */
2660template <class T>
2661std::vector<Promoted<T>> promote(const std::vector<T>& y, std::size_t bufw, std::size_t srv0,
2662 const std::vector<std::size_t>& Ks, std::size_t rroff,
2663 const RrInfo<T>& ri) {
2664 const T one = num_traits<T>::from_int(1);
2665 std::vector<Promoted<T>> out;
2666 std::size_t h = static_cast<std::size_t>(-1);
2667 for (std::size_t j = 0; 2 * j + 1 < bufw; ++j)
2668 if (num_traits<T>::to_double(y[2 * j]) > 0) h = j;
2669 if (h == static_cast<std::size_t>(-1)) {
2670 out.push_back(Promoted<T>{y, one, 0});
2671 return out;
2672 }
2673 const std::size_t c = static_cast<std::size_t>(num_traits<T>::to_double(y[2 * h]));
2674 const std::size_t kc = static_cast<std::size_t>(num_traits<T>::to_double(y[2 * h + 1]));
2675 std::vector<T> z = y;
2676 // buf = [0, 0, buf before the head, buf after the head]
2677 for (std::size_t b = 2 * h + 1; b >= 2; --b) z[b] = z[b - 2];
2678 z[0] = num_traits<T>::from_int(0);
2679 z[1] = num_traits<T>::from_int(0);
2680 z[srv0 + Ks[c - 1] + (kc - 1)] += one;
2681 const std::vector<T>& qa = ri.qa[c - 1];
2682 for (std::size_t q = 0; q < ri.Q[c - 1]; ++q) {
2683 if (!(num_traits<T>::to_double(qa[q]) > 0)) continue;
2684 std::vector<T> w = z;
2685 w[rroff + ri.col(c - 1, kc - 1, q)] += one;
2686 out.push_back(Promoted<T>{w, qa[q], c});
2687 }
2688 return out;
2689}
2690
2691} // namespace rr_detail
2692
2693/**
2694 * Port of `State.afterEventStationRR`: round robin with a finite quantum
2695 * (Haverkort 1998, Sect. 6.4) at one state row.
2696 *
2697 * The row is the FCFS preempt-resume layout [paired buffer | server | vars],
2698 * with the quantum block m(r,k,q) inside the vars (`rr_info`). The events:
2699 *
2700 * ARV an idle server takes the job in its entry phase k and a quantum
2701 * entry phase q (prob pie(k)*qa(q)); a busy one queues it at the tail.
2702 * DEP a completion in (k,q) at rate scale*m*mu(k)*phi(k), then the head
2703 * of the buffer enters service with a fresh quantum.
2704 * PHASE a service phase move k->kd at rate scale*m*D0(k,kd), a quantum
2705 * phase move q->qd at rate m*T(q,qd), and the quantum EXPIRY at rate
2706 * m*t(q): with nobody waiting the job simply restarts its quantum,
2707 * otherwise it is preempted (phase kept) to the tail and the head is
2708 * promoted. The quantum runs in real time, so it is not scaled by the
2709 * load or class dependence.
2710 *
2711 * Refused by name: a non-phase-type quantum (LINE:unsupported:Det), a
2712 * Markov-modulated service (LINE:unsupported:MAP), signal arrivals, balking,
2713 * and every other event (LINE:unsupported:SchedStrategy_RR).
2714 */
2715template <class T>
2717 const std::vector<T>& x, EventType event, std::size_t cls) {
2718 const std::size_t R = sn.nclasses;
2719 const std::size_t ist = sn.nodes[ind - 1].station;
2720 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
2721 const std::string& nodename = sn.nodes[ind - 1].name;
2722 EventOutcome<T> out;
2723
2724 const RrInfo<T> ri = rr_info(sn, ind);
2725 for (std::size_t r = 0; r < R; ++r)
2726 if (!ri.markovian[r])
2727 throw UnsupportedError(ErrorKind{"Det"},
2728 "The quantum of class " + sn.classes[r].name + " at round-robin station " + nodename +
2729 " has no renewal phase-type form, so it has no state-space representation. Use a "
2730 "phase-type quantum (Exp, Erlang, HyperExp, APH, Coxian, PH) or simulate the model.");
2731 for (std::size_t r = 0; r < R && r < sn.nvars[ind - 1].size(); ++r)
2732 if (sn.nvars[ind - 1][r] > 0)
2733 throw UnsupportedError(ErrorKind{"MAP"},
2734 "Round-robin station " + nodename + " has a Markov-modulated (MAP) service, whose "
2735 "modulating phase would have to survive the quantum preemptions; this is not encoded.");
2736 if (event != EventType::ARV && event != EventType::DEP && event != EventType::PHASE)
2737 throw UnsupportedError(ErrorKind{"SchedStrategy_RR"},
2738 std::string("Event ") + lang::event_to_text(event) + " is not supported at round-robin station " +
2739 nodename + " (no reneging, retrial, breakdown or switchover at an RR queue).");
2740
2741 const RowLayout<T> L = row_layout(sn, ind, x.size());
2742 const std::size_t bufw = L.bufw;
2743 const std::size_t srv0 = bufw;
2744 const std::size_t rroff = bufw + L.srvw + ri.boff;
2745 const std::size_t c0 = cls - 1;
2746 const auto srvc = [&](std::size_t r0, std::size_t k0) { return srv0 + L.Ks[r0] + k0; };
2747 const auto blk = [&](std::size_t r0, std::size_t k0, std::size_t q0) { return rroff + ri.col(r0, k0, q0); };
2748 const auto push = [&](const std::vector<T>& row, const T& rate, const T& prob, std::size_t st,
2749 std::size_t pr) {
2750 out.space.push_back(row);
2751 out.rate.push_back(rate);
2752 out.prob.push_back(prob);
2753 tag_last(out, st, pr);
2754 };
2755
2756 std::size_t nbufjobs = 0;
2757 double nsrv = 0;
2758 std::vector<T> nir(R, zero);
2759 for (std::size_t b = 0; b + 1 < bufw; b += 2) {
2760 const double tag = num_traits<T>::to_double(x[b]);
2761 if (tag > 0) {
2762 ++nbufjobs;
2763 const std::size_t c = static_cast<std::size_t>(tag);
2764 if (c >= 1 && c <= R) nir[c - 1] += one;
2765 }
2766 }
2767 for (std::size_t r = 0; r < R; ++r)
2768 for (std::size_t k = 0; k < L.K[r]; ++k) {
2769 nsrv += num_traits<T>::to_double(x[srvc(r, k)]);
2770 nir[r] += x[srvc(r, k)];
2771 }
2772 const double ni = static_cast<double>(nbufjobs) + nsrv;
2773 const double S = sn.stations[ist - 1].nservers;
2774 const T scale = ni <= 0 ? one : T(lld_factor(sn, ist, ni) * cd_factor(sn, ist, nir, cls));
2775
2776 switch (event) {
2777 case EventType::ARV: {
2778 if (sn.issignal.size() >= cls && sn.issignal[c0])
2779 throw UnsupportedError(ErrorKind{"Signal"},
2780 "Signal (negative customer) arrivals are not supported at round-robin station " + nodename + ".");
2781 const Station<T>& st = sn.stations[ist - 1];
2782 if (st.balking.size() > c0 && st.balking[c0].strategy != lang::BalkingStrategy::NONE)
2783 throw UnsupportedError(ErrorKind{"Balking"},
2784 "Balking is not supported at round-robin station " + nodename + ".");
2785 const double cap = sn.cap.size() >= ist ? sn.cap[ist - 1] : std::numeric_limits<double>::infinity();
2786 const double ccap = (sn.classcap.size() >= ist && sn.classcap[ist - 1].size() > c0)
2787 ? sn.classcap[ist - 1][c0]
2788 : std::numeric_limits<double>::infinity();
2789 if (ni + 1 > cap || num_traits<T>::to_double(nir[c0]) + 1 > ccap) {
2790 // LOST: a self-loop, so the offered job reaches the arrival
2791 // statistic. BLOCKED, or beyond the cutoff: no successor.
2792 if (is_physical_capacity(sn, ist, cls) && arrival_is_lost(sn, ist, cls))
2793 push(x, T(-one), one, 0, 0);
2794 break;
2795 }
2796 const std::vector<T> pie = entry_phase_dist(sn, ist, cls);
2797 const std::vector<T> buf(x.begin(), x.begin() + static_cast<std::ptrdiff_t>(bufw));
2798 for (std::size_t ke = 0; ke < pie.size() && ke < L.K[c0]; ++ke) {
2799 if (!(num_traits<T>::to_double(pie[ke]) > 0)) continue;
2800 if (nsrv < S) {
2801 const std::vector<T>& qa = ri.qa[c0];
2802 for (std::size_t q = 0; q < ri.Q[c0]; ++q) {
2803 if (!(num_traits<T>::to_double(qa[q]) > 0)) continue;
2804 std::vector<T> y = x;
2805 y[srvc(c0, ke)] += one;
2806 y[blk(c0, ke, q)] += one;
2807 push(y, T(-one), T(pie[ke] * qa[q]), cls, 0);
2808 }
2809 } else {
2810 std::vector<T> y = rr_detail::bufpush(buf, cls, ke + 1);
2811 y.insert(y.end(), x.begin() + static_cast<std::ptrdiff_t>(bufw), x.end());
2812 push(y, T(-one), pie[ke], 0, 0);
2813 }
2814 }
2815 break;
2816 }
2817 case EventType::DEP: {
2818 const std::pair<std::vector<T>, std::vector<T>> mp = phase_rates(sn, ist, cls);
2819 for (std::size_t k = 0; k < mp.first.size() && k < L.K[c0]; ++k) {
2820 const T tk = T(mp.first[k] * mp.second[k]);
2821 if (!(num_traits<T>::to_double(tk) > 0)) continue;
2822 for (std::size_t q = 0; q < ri.Q[c0]; ++q) {
2823 const T m = x[blk(c0, k, q)];
2824 if (!(num_traits<T>::to_double(m) > 0)) continue;
2825 std::vector<T> y = x;
2826 y[srvc(c0, k)] -= one;
2827 y[blk(c0, k, q)] -= one;
2828 const std::vector<rr_detail::Promoted<T>> ys = rr_detail::promote(y, bufw, srv0, L.Ks, rroff, ri);
2829 for (std::size_t j = 0; j < ys.size(); ++j)
2830 push(ys[j].row, T(scale * m * tk * ys[j].prob), one, ys[j].start, 0);
2831 }
2832 }
2833 break;
2834 }
2835 case EventType::PHASE: {
2836 const Matrix<T>& D0 = sn.service[ist - 1][c0].D0;
2837 const Matrix<T>& QT = ri.qT[c0];
2838 const std::vector<T>& tq = ri.qt[c0];
2839 const std::vector<T>& qa = ri.qa[c0];
2840 const std::size_t Kc = L.K[c0], Qc = ri.Q[c0];
2841 for (std::size_t k = 0; k < Kc; ++k)
2842 for (std::size_t q = 0; q < Qc; ++q) {
2843 const T m = x[blk(c0, k, q)];
2844 if (!(num_traits<T>::to_double(m) > 0)) continue;
2845 // service phase move, the quantum phase kept
2846 for (std::size_t kd = 0; kd < Kc && k < D0.rows(); ++kd) {
2847 if (kd == k || kd >= D0.cols() || !(num_traits<T>::to_double(D0(k, kd)) > 0)) continue;
2848 std::vector<T> y = x;
2849 y[srvc(c0, k)] -= one;
2850 y[srvc(c0, kd)] += one;
2851 y[blk(c0, k, q)] -= one;
2852 y[blk(c0, kd, q)] += one;
2853 push(y, T(scale * m * D0(k, kd)), one, 0, 0);
2854 }
2855 // quantum phase move, the service phase kept
2856 for (std::size_t qd = 0; qd < Qc; ++qd) {
2857 if (qd == q || !(num_traits<T>::to_double(QT(q, qd)) > 0)) continue;
2858 std::vector<T> y = x;
2859 y[blk(c0, k, q)] -= one;
2860 y[blk(c0, k, qd)] += one;
2861 push(y, T(m * QT(q, qd)), one, 0, 0);
2862 }
2863 // quantum expiry
2864 if (!(num_traits<T>::to_double(tq[q]) > 0)) continue;
2865 std::vector<T> y = x;
2866 y[srvc(c0, k)] -= one;
2867 y[blk(c0, k, q)] -= one;
2868 if (nbufjobs == 0) {
2869 // nobody waits: the job keeps the server with a fresh
2870 // quantum; a restart in the same phase is a self-loop
2871 for (std::size_t qd = 0; qd < Qc; ++qd) {
2872 if (qd == q || !(num_traits<T>::to_double(qa[qd]) > 0)) continue;
2873 std::vector<T> z = y;
2874 z[srvc(c0, k)] += one;
2875 z[blk(c0, k, qd)] += one;
2876 push(z, T(m * tq[q] * qa[qd]), one, 0, 0);
2877 }
2878 } else {
2879 const std::vector<rr_detail::Promoted<T>> ys = rr_detail::promote(y, bufw, srv0, L.Ks, rroff, ri);
2880 for (std::size_t j = 0; j < ys.size(); ++j) {
2881 const std::vector<T> b(ys[j].row.begin(),
2882 ys[j].row.begin() + static_cast<std::ptrdiff_t>(bufw));
2883 std::vector<T> z = rr_detail::bufpush(b, cls, k + 1);
2884 z.insert(z.end(), ys[j].row.begin() + static_cast<std::ptrdiff_t>(bufw), ys[j].row.end());
2885 push(z, T(m * tq[q] * ys[j].prob), one, ys[j].start, cls);
2886 }
2887 }
2888 }
2889 break;
2890 }
2891 default:
2892 break;
2893 }
2894 // One width per outcome, left-padded as the reference's `sub_append` does.
2895 std::size_t wmax = 0;
2896 for (std::size_t i = 0; i < out.space.size(); ++i) wmax = std::max(wmax, out.space[i].size());
2897 for (std::size_t i = 0; i < out.space.size(); ++i)
2898 if (out.space[i].size() < wmax) out.space[i].insert(out.space[i].begin(), wmax - out.space[i].size(), zero);
2899 pad_tags(out);
2900 return out;
2901}
2902
2903template <class T>
2905 const std::vector<T>& inspace, EventType event,
2906 std::size_t cls, bool no_promote = false,
2907 const T& aux_rate = num_traits<T>::from_int(0)) {
2908 // SERVER BREAKDOWN, `afterEventStation.m:36-65`. A down server (trailing
2909 // status 0) does not serve, so DEP and PHASE produce nothing -- unless a
2910 // degraded down-server rate is configured for the class, in which case the
2911 // up-server outcome is computed below and its rates rescaled by
2912 // downRate/upRate. Gating here keeps every scheduling branch unaware of it.
2913 if ((event == EventType::DEP || event == EventType::PHASE) && !inspace.empty() &&
2914 sn.has_breakdown_node(ind) && num_traits<T>::to_double(inspace.back()) == 0) {
2915 const std::size_t ist = sn.nodes[ind - 1].station;
2916 const T down = sn.breakdownparam.at(ist).down_rate_of(cls);
2917 if (!(down > num_traits<T>::from_int(0))) return EventOutcome<T>();
2918 const T upr = sn.rates(ist - 1, cls - 1);
2919 const double upd = num_traits<T>::to_double(upr);
2920 if (!std::isfinite(upd) || !(upd > 0.0))
2921 throw InputError("Station '" + sn.nodes[ind - 1].name +
2922 "' declares a down-server service rate for class '" +
2923 sn.classes[cls - 1].name +
2924 "' but has no finite up-server service rate to rescale.");
2925 // Evaluate the UP handler on the same row with the status set to up, then
2926 // put the status back to down in every successor: the outage does not end
2927 // because a job completed.
2928 std::vector<T> upspace = inspace;
2929 upspace.back() = num_traits<T>::from_int(1);
2930 EventOutcome<T> o =
2931 after_event_station_base(sn, ind, upspace, event, cls, no_promote, aux_rate);
2932 const T scale = T(down / upr);
2933 for (std::size_t i = 0; i < o.space.size(); ++i) {
2934 if (!o.space[i].empty()) o.space[i].back() = num_traits<T>::from_int(0);
2935 o.rate[i] = T(o.rate[i] * scale);
2936 }
2937 return o;
2938 }
2939 // heterogeneous server pools rewritten for the CTMC (`ctmc::ctmc_pools`)
2940 if ((event == EventType::ARV || event == EventType::DEP || event == EventType::PHASE) &&
2941 !sn.ctmcpool.empty() && sn.ctmcpool.count(ind))
2942 return after_event_station_pool(sn, ind, inspace, event, cls);
2943 // ROUND ROBIN with a finite quantum keeps a quantum-phase block next to the
2944 // FCFS preempt-resume layout and is handled on its own, as
2945 // `afterEventStation.m` hands it to `afterEventStationRR`.
2946 {
2947 const std::size_t ist = sn.nodes[ind - 1].station;
2948 if (ist != 0 && sn.stations[ist - 1].sched == SchedStrategy::RR) {
2949 if (no_promote)
2950 throw UnsupportedError(ErrorKind{"SchedStrategy_RR"},
2951 "Immediate feedback (a self-loop that keeps the server) is not supported at "
2952 "round-robin station " + sn.nodes[ind - 1].name + ".");
2953 EventOutcome<T> out = after_event_station_rr(sn, ind, inspace, event, cls);
2954 if (event == EventType::DEP) rr_advance_row(sn, ind, cls, out.space);
2955 return out;
2956 }
2957 }
2958 switch (event) {
2959 case EventType::ARV:
2960 // A signal class arriving is not an arrival at all: it removes
2961 // jobs and is annihilated, so it never reaches the scheduling
2962 // branches. A REPLY signal is the exception -- it completes a
2963 // synchronous call and then joins as an ordinary job.
2964 if (sn.issignal.size() >= cls && sn.issignal[cls - 1]) {
2965 if (!(sn.signaltype.size() >= cls &&
2966 sn.signaltype[cls - 1] == lang::SignalType::REPLY))
2967 return after_event_station_signal(sn, ind, inspace, cls);
2968 // A REPLY takes the reply path only at a station that actually
2969 // holds a block for it; elsewhere it is a plain job class and
2970 // falls through to ordinary arrival handling.
2971 if (reply_block_info(sn, ind).width > 0)
2972 return after_event_station_reply(sn, ind, inspace, cls);
2973 }
2974 {
2975 EventOutcome<T> out = after_event_station_arv(sn, ind, inspace, cls);
2976 apply_station_balking(sn, ind, inspace, cls, out);
2977 apply_station_orbit_join(sn, ind, inspace, cls, out);
2978 return out;
2979 }
2980 case EventType::DEP: {
2981 EventOutcome<T> out = after_event_station_dep(sn, ind, inspace, cls, no_promote);
2982 // Orbital search at a retrial station: the freed server may take an
2983 // orbiting job instead of staying idle (afterEventStation.m DEP).
2984 if (!no_promote) apply_station_orbital_search(sn, ind, inspace, out);
2985 // ROUND-ROBIN DISPATCH advances on every completion, which is what
2986 // makes the next destination deterministic; the generator then reads
2987 // the pointer OUT OF THIS SUCCESSOR to pick the link. Without the
2988 // advance the pointer is a frozen coordinate and every job takes the
2989 // same link, which is random routing with the wrong support rather
2990 // than round robin. Reference: `afterEventStation.m:632-658`.
2991 rr_advance_row(sn, ind, cls, out.space);
2992 // TRUE BAS: the held-job block (one counter per target code, see
2993 // NetworkStruct::bas_marker_codes) rides through this event
2994 // UNCHANGED. Splitting a departure into the transfer of a held job
2995 // (1e7, decrementing its code) and a fresh completion (rate scaled by
2996 // the free share of the class in service) is the caller's job, since
2997 // only the caller sees the destination's occupancy and which target
2998 // the outcome reaches (BUG-110; solver_ctmc.h, bas_dep_variants).
2999 return out;
3000 }
3001 case EventType::PHASE:
3002 return after_event_station_phase(sn, ind, inspace, cls);
3003 case EventType::RENEGE:
3004 return after_event_station_renege(sn, ind, inspace, cls, aux_rate);
3005 case EventType::RETRY:
3006 return after_event_station_retry(sn, ind, inspace, cls, aux_rate);
3007 case EventType::SWITCH:
3008 return after_event_station_switch(sn, ind, inspace, cls);
3009 case EventType::FAILURE:
3010 return after_event_station_breakdown(sn, ind, inspace, false, aux_rate);
3011 case EventType::REPAIR:
3012 return after_event_station_breakdown(sn, ind, inspace, true, aux_rate);
3013 case EventType::LOCAL:
3014 return EventOutcome<T>(); // a dummy event moves nothing
3015 default:
3016 throw UnsupportedError(ErrorKind{"Event"}, std::string("after_event_station: the ") +
3017 lang::event_to_text(event) +
3018 " event is not ported yet");
3019 }
3020}
3021
3022namespace blocks_events {
3023
3024/** Jobs in service in a station row: the server block's total. */
3025template <class T>
3026double srv_count(const RowLayout<T>& L, const std::vector<T>& row) {
3027 double c = 0;
3028 for (std::size_t j = 0; j < L.srvw; ++j) c += num_traits<T>::to_double(row[L.bufw + j]);
3029 return c;
3030}
3031
3032template <class T>
3033bool buffer_empty(const RowLayout<T>& L, const std::vector<T>& row) {
3034 for (std::size_t b = 0; b < L.bufw; ++b)
3035 if (num_traits<T>::to_double(row[b]) > 0) return false;
3036 return true;
3037}
3038
3039template <class T>
3040double block_sum(const std::vector<T>& row, std::size_t w) {
3041 double s = 0;
3042 for (std::size_t k = 0; k < w; ++k) s += num_traits<T>::to_double(row[row.size() - w + k]);
3043 return s;
3044}
3045
3046/**
3047 * Servers held at `ind` by synchronous calls awaiting a REPLY (python
3048 * `setup_delayoff._held`). A held server is neither idle nor in the setup
3049 * block: it finished a job and waits for the reply, so an arrival cannot take
3050 * it and a departure cannot start its delay-off.
3051 */
3052template <class T>
3053double held_servers(const NetworkStruct<T>& sn, std::size_t ind, const RowLayout<T>& L,
3054 const std::vector<T>& row) {
3055 if (row.size() <= L.bufw + L.srvw) return 0.0;
3056 const std::vector<T> var(row.begin() + L.bufw + L.srvw, row.end());
3057 return reply_blocked(sn, ind, var);
3058}
3059
3060/**
3061 * The calling class whose held server a REPLY of class `cls` releases at `ind`,
3062 * or 0 when `cls` answers no call held there (python `_calling_class`).
3063 */
3064template <class T>
3065std::size_t calling_class(const NetworkStruct<T>& sn, std::size_t ind, std::size_t cls) {
3066 if (ind == 0 || sn.replyblock.size() < ind) return 0;
3067 const std::vector<bool>& rb = sn.replyblock[ind - 1];
3068 for (std::size_t r = 1; r <= rb.size() && r <= sn.syncreply.size(); ++r)
3069 if (sn.syncreply[r - 1] == cls && rb[r - 1]) return r;
3070 return 0;
3071}
3072
3073/** True when a class-`cls` departure from `ind` keeps its server for a synchronous call. */
3074template <class T>
3075bool holds_call(const NetworkStruct<T>& sn, std::size_t ind, std::size_t cls) {
3076 return ind >= 1 && sn.replyblock.size() >= ind && sn.replyblock[ind - 1].size() >= cls &&
3077 cls >= 1 && sn.replyblock[ind - 1][cls - 1];
3078}
3079
3080/** Append one successor with its tags. */
3081template <class T>
3082void push(EventOutcome<T>& out, const std::vector<T>& row, const T& rate, const T& prob,
3083 const std::vector<std::size_t>& start, const std::vector<std::size_t>& preempt) {
3084 out.space.push_back(row);
3085 out.rate.push_back(rate);
3086 out.prob.push_back(prob);
3087 out.start.push_back(start);
3088 out.preempt.push_back(preempt);
3089}
3090
3091/**
3092 * Pre-arrival moves of the setup block (python `setup_arrival_variants`): with
3093 * an idle ACTIVE server the row is unchanged; with none, a DELAYOFF server
3094 * (uniformly among them) is woken and serves the job at once; with none in
3095 * DELAYOFF, an OFF server starts the ARRIVING class's setup in a phase drawn
3096 * from its initial vector, and the job waits.
3097 */
3098template <class T>
3099std::vector<std::pair<std::vector<T>, T>> setup_arrival_variants(const NetworkStruct<T>& sn,
3100 std::size_t ind,
3101 const SetupInfo<T>& si,
3102 const RowLayout<T>& L,
3103 const std::vector<T>& row,
3104 std::size_t cls) {
3105 const T one = num_traits<T>::from_int(1);
3106 std::vector<std::pair<std::vector<T>, T>> out;
3107 if (calling_class(sn, ind, cls) > 0) {
3108 // a REPLY brings back the server its call held: it wakes nobody
3109 out.push_back(std::make_pair(row, one));
3110 return out;
3111 }
3112 const std::size_t base = row.size() - si.width;
3113 // servers held for pending replies are neither idle nor in the block
3114 const double active =
3115 static_cast<double>(si.c) - block_sum(row, si.width) - held_servers(sn, ind, L, row);
3116 if (srv_count(L, row) < active) {
3117 out.push_back(std::make_pair(row, one));
3118 return out;
3119 }
3120 double nd = 0;
3121 for (typename std::map<std::size_t, SetupLaw<T>>::const_iterator it = si.delay.begin();
3122 it != si.delay.end(); ++it)
3123 for (std::size_t k = 0; k < it->second.S.rows(); ++k)
3124 nd += num_traits<T>::to_double(row[base + it->second.off + k]);
3125 if (nd > 0) {
3126 for (typename std::map<std::size_t, SetupLaw<T>>::const_iterator it = si.delay.begin();
3127 it != si.delay.end(); ++it)
3128 for (std::size_t k = 0; k < it->second.S.rows(); ++k) {
3129 const double n = num_traits<T>::to_double(row[base + it->second.off + k]);
3130 if (!(n > 0)) continue;
3131 std::vector<T> nr = row;
3132 nr[base + it->second.off + k] -= one;
3133 out.push_back(std::make_pair(nr, num_traits<T>::from_double(n / nd)));
3134 }
3135 return out;
3136 }
3137 const typename std::map<std::size_t, SetupLaw<T>>::const_iterator su = si.setup.find(cls);
3138 if (num_traits<T>::to_double(row[base]) > 0 && su != si.setup.end()) {
3139 for (std::size_t k = 0; k < su->second.S.rows(); ++k) {
3140 if (!(num_traits<T>::to_double(su->second.alpha[k]) > 0)) continue;
3141 std::vector<T> nr = row;
3142 nr[base] -= one;
3143 nr[base + su->second.off + k] += one;
3144 out.push_back(std::make_pair(nr, su->second.alpha[k]));
3145 }
3146 return out;
3147 }
3148 out.push_back(std::make_pair(row, one));
3149 return out;
3150}
3151
3152/**
3153 * Post-departure moves (python `setup_departure_variants`): a server freed onto
3154 * an empty buffer starts the DEPARTING class's delay-off.
3155 *
3156 * Synchronous calls: a REPLY leaving releases the server its call held, and
3157 * that server finished a job of the CALLING class, whose delay-off law it
3158 * follows; a calling class's own departure keeps its server for the reply, so
3159 * it frees none and starts no delay-off.
3160 */
3161template <class T>
3162std::vector<std::pair<std::vector<T>, T>> setup_departure_variants(const NetworkStruct<T>& sn,
3163 std::size_t ind,
3164 const SetupInfo<T>& si,
3165 const RowLayout<T>& L,
3166 const std::vector<T>& row,
3167 std::size_t cls) {
3168 const T one = num_traits<T>::from_int(1);
3169 std::vector<std::pair<std::vector<T>, T>> out;
3170 const std::size_t caller = calling_class(sn, ind, cls);
3171 if (caller > 0) {
3172 cls = caller;
3173 } else if (holds_call(sn, ind, cls)) {
3174 out.push_back(std::make_pair(row, one));
3175 return out;
3176 }
3177 const typename std::map<std::size_t, SetupLaw<T>>::const_iterator dl = si.delay.find(cls);
3178 if (!buffer_empty(L, row) || dl == si.delay.end() ||
3179 srv_count(L, row) >= static_cast<double>(si.c) - block_sum(row, si.width) -
3180 held_servers(sn, ind, L, row)) {
3181 // a job still waits, or no ACTIVE server idles (the freed one took a
3182 // waiting job, or is held for a reply)
3183 out.push_back(std::make_pair(row, one));
3184 return out;
3185 }
3186 const std::size_t base = row.size() - si.width;
3187 for (std::size_t k = 0; k < dl->second.S.rows(); ++k) {
3188 if (!(num_traits<T>::to_double(dl->second.alpha[k]) > 0)) continue;
3189 std::vector<T> nr = row;
3190 nr[base + dl->second.off + k] += one;
3191 out.push_back(std::make_pair(nr, dl->second.alpha[k]));
3192 }
3193 return out;
3194}
3195
3196} // namespace blocks_events
3197
3198/**
3199 * after_event at a setup/delay-off station (python `_after_event_setup`): the
3200 * block moves wrap the ordinary FCFS arrival and departure, and SETUP and
3201 * DELAYOFF are the block's own clocks (python `setup_local_event`).
3202 */
3203template <class T>
3205 const std::vector<T>& inspace, EventType event, std::size_t cls,
3206 bool no_promote, const T& aux_rate, const SetupInfo<T>& si) {
3207 const T one = num_traits<T>::from_int(1);
3208 const std::size_t ist = si.ist;
3209 const RowLayout<T> L = row_layout(sn, ind, inspace.size());
3210 EventOutcome<T> out;
3211 if (event == EventType::SETUP || event == EventType::DELAYOFF) {
3212 const std::map<std::size_t, SetupLaw<T>>& table =
3213 event == EventType::SETUP ? si.setup : si.delay;
3214 const typename std::map<std::size_t, SetupLaw<T>>::const_iterator it = table.find(cls);
3215 if (it == table.end()) return out;
3216 const SetupLaw<T>& law = it->second;
3217 const std::size_t base = inspace.size() - si.width;
3218 const std::size_t nph = law.S.rows();
3219 for (std::size_t k = 0; k < nph; ++k) {
3220 const T n = inspace[base + law.off + k];
3221 if (!(num_traits<T>::to_double(n) > 0)) continue;
3222 for (std::size_t j = 0; j < nph; ++j) {
3223 if (j == k || !(num_traits<T>::to_double(law.S(k, j)) > 0)) continue;
3224 std::vector<T> nr = inspace;
3225 nr[base + law.off + k] -= one;
3226 nr[base + law.off + j] += one;
3227 blocks_events::push(out, nr, T(n * law.S(k, j)), one, std::vector<std::size_t>(),
3228 std::vector<std::size_t>());
3229 }
3230 if (!(num_traits<T>::to_double(law.exit[k]) > 0)) continue;
3231 std::vector<T> nr = inspace;
3232 nr[base + law.off + k] -= one;
3233 const T rate = T(n * law.exit[k]);
3234 if (event == EventType::DELAYOFF) {
3235 nr[base] += one; // the delay-off expires: the server turns OFF
3236 blocks_events::push(out, nr, rate, one, std::vector<std::size_t>(),
3237 std::vector<std::size_t>());
3238 continue;
3239 }
3240 // the server that finished its setup is ACTIVE and takes the head-of-line job
3241 const double headv = L.bufw > 0 ? num_traits<T>::to_double(nr[L.bufw - 1]) : 0.0;
3242 if (!(headv > 0)) {
3243 blocks_events::push(out, nr, rate, one, std::vector<std::size_t>(),
3244 std::vector<std::size_t>());
3245 continue;
3246 }
3247 const std::size_t hc = static_cast<std::size_t>(headv + 0.5);
3248 const std::vector<T> pie = entry_phase_dist(sn, ist, hc);
3249 for (std::size_t ke = 0; ke < L.K[hc - 1]; ++ke) {
3250 if (!(ke < pie.size() && num_traits<T>::to_double(pie[ke]) > 0)) continue;
3251 std::vector<T> pr = nr;
3252 for (std::size_t b = L.bufw - 1; b > 0; --b) pr[b] = nr[b - 1];
3253 pr[0] = num_traits<T>::from_int(0);
3254 pr[L.bufw + L.Ks[hc - 1] + ke] += one;
3255 blocks_events::push(out, pr, rate, pie[ke], std::vector<std::size_t>(1, hc),
3256 std::vector<std::size_t>());
3257 }
3258 }
3259 return out;
3260 }
3261 if (event == EventType::ARV) {
3262 const std::vector<std::pair<std::vector<T>, T>> vs =
3263 blocks_events::setup_arrival_variants(sn, ind, si, L, inspace, cls);
3264 for (std::size_t v = 0; v < vs.size(); ++v) {
3265 EventOutcome<T> o =
3266 after_event_station_base(sn, ind, vs[v].first, event, cls, no_promote, aux_rate);
3267 pad_tags(o);
3268 for (std::size_t i = 0; i < o.space.size(); ++i)
3269 blocks_events::push(out, o.space[i], o.rate[i], T(vs[v].second * o.prob[i]),
3270 o.start[i], o.preempt[i]);
3271 }
3272 return out;
3273 }
3274 // DEP
3275 EventOutcome<T> o = after_event_station_base(sn, ind, inspace, event, cls, no_promote, aux_rate);
3276 pad_tags(o);
3277 for (std::size_t i = 0; i < o.space.size(); ++i) {
3278 const RowLayout<T> Li = row_layout(sn, ind, o.space[i].size());
3279 const std::vector<std::pair<std::vector<T>, T>> vs =
3280 blocks_events::setup_departure_variants(sn, ind, si, Li, o.space[i], cls);
3281 for (std::size_t v = 0; v < vs.size(); ++v)
3282 blocks_events::push(out, vs[v].first, o.rate[i], T(o.prob[i] * vs[v].second),
3283 o.start[i], o.preempt[i]);
3284 }
3285 return out;
3286}
3287
3288/**
3289 * ARV and RETRY at a finite-attempt retrial station (python `after_event_attempts`).
3290 *
3291 * The orbit stays where the unlimited retrial keeps it, as class tokens in the
3292 * buffer; the trailing block counts the orbiting jobs per failed-retry level.
3293 * Under the LINEAR policy each orbiting job carries its own clock, so level a
3294 * retries at n[a]*mu: a success takes a level-a job into service, a failure
3295 * moves it to level a+1, or loses it from the last level.
3296 */
3297template <class T>
3299 const std::vector<T>& inspace, EventType event, std::size_t cls,
3300 bool no_promote, const T& aux_rate, const AttemptsLayout& ai) {
3301 const T one = num_traits<T>::from_int(1);
3302 const std::size_t R = sn.nclasses;
3303 const std::size_t ist = ai.ist, M = ai.M;
3304 EventOutcome<T> out;
3305 const auto orbit_size = [&](const std::vector<T>& row) -> double {
3306 const RowLayout<T> L = row_layout(sn, ind, row.size());
3307 std::vector<std::size_t> ph(R, 1), shift(R, 0);
3308 for (std::size_t r = 0; r < R; ++r) {
3309 ph[r] = L.K[r];
3310 shift[r] = L.Ks[r];
3311 }
3312 const Marginal<T> m = to_marginal(sn, ist, row, ph, shift, L.nvar);
3313 return std::floor(num_traits<T>::to_double(m.nir[ai.cls - 1]) -
3314 num_traits<T>::to_double(m.sir[ai.cls - 1]) + 0.5);
3315 };
3316 if (event == EventType::ARV) {
3317 EventOutcome<T> o = after_event_station_base(sn, ind, inspace, event, cls, no_promote, aux_rate);
3318 pad_tags(o);
3319 const double before = cls == ai.cls ? orbit_size(inspace) : 0.0;
3320 for (std::size_t i = 0; i < o.space.size(); ++i) {
3321 std::vector<T> nr = o.space[i];
3322 // the arrival found every server busy: it joins the orbit at level 0
3323 if (cls == ai.cls && orbit_size(nr) > before) nr[nr.size() - M] += one;
3324 blocks_events::push(out, nr, o.rate[i], o.prob[i], o.start[i], o.preempt[i]);
3325 }
3326 return out;
3327 }
3328 // RETRY of the retrial class
3329 if (cls != ai.cls) return out;
3330 const std::size_t n = inspace.size();
3331 std::vector<double> blk(M, 0.0);
3332 double orbit = 0;
3333 for (std::size_t a = 0; a < M; ++a) {
3334 blk[a] = num_traits<T>::to_double(inspace[n - M + a]);
3335 orbit += blk[a];
3336 }
3337 if (!(orbit > 0)) return out;
3338 EventOutcome<T> o = after_event_station_base(sn, ind, inspace, event, cls, no_promote, aux_rate);
3339 pad_tags(o);
3340 const RowLayout<T> L = row_layout(sn, ind, n);
3341 const bool server_free = blocks_events::srv_count(L, inspace) < sn.stations[ist - 1].nservers;
3342 if (!o.space.empty() && server_free) {
3343 // the ordinary retry fired the whole orbit at orbit * mu; split it over
3344 // the levels by their share of the orbit
3345 for (std::size_t i = 0; i < o.space.size(); ++i)
3346 for (std::size_t a = 0; a < M; ++a) {
3347 if (!(blk[a] > 0)) continue;
3348 std::vector<T> nr = o.space[i];
3349 nr[nr.size() - M + a] -= one;
3350 blocks_events::push(out, nr, T(o.rate[i] * num_traits<T>::from_double(blk[a] / orbit)),
3351 one, o.start[i], std::vector<std::size_t>());
3352 }
3353 return out;
3354 }
3355 // every server busy: each level-a job fails at its own rate
3356 const T mu = aux_rate > num_traits<T>::from_int(0) ? aux_rate : station_retrial_mu(sn, ist, ai.cls);
3357 for (std::size_t a = 0; a < M; ++a) {
3358 if (!(blk[a] > 0)) continue;
3359 std::vector<T> nr = inspace;
3360 nr[n - M + a] -= one;
3361 if (a + 1 < M) {
3362 nr[n - M + a + 1] += one;
3363 } else if (state_detail::buffer_is_class_tag(sn.stations[ist - 1].sched)) {
3364 // the job failed its last allowed retry: it leaves the orbit, lost
3365 const T tag = num_traits<T>::from_int(static_cast<long>(ai.cls));
3366 std::size_t slot = L.bufw;
3367 for (std::size_t b = 0; b < L.bufw; ++b)
3368 if (nr[b] == tag) { slot = b; break; }
3369 if (slot == L.bufw) continue;
3370 for (std::size_t b = slot; b > 0; --b) nr[b] = nr[b - 1];
3371 nr[0] = num_traits<T>::from_int(0);
3372 } else {
3373 nr[ai.cls - 1] -= one; // a per-class-count buffer
3374 }
3375 blocks_events::push(out, nr, T(num_traits<T>::from_double(blk[a]) * mu), one,
3376 std::vector<std::size_t>(), std::vector<std::size_t>());
3377 }
3378 return out;
3379}
3380
3381/**
3382 * Hand freed servers to the head-of-line jobs while the head fits (python
3383 * `promote_fitting`): `(row, prob, started classes)` over the entry phases drawn.
3384 */
3385template <class T>
3386void promote_fitting(const NetworkStruct<T>& sn, std::size_t ind, const std::vector<double>& par,
3387 const std::vector<T>& row, const T& p, std::vector<std::size_t> started,
3388 std::vector<std::pair<std::pair<std::vector<T>, T>, std::vector<std::size_t>>>& out) {
3389 const std::size_t R = sn.nclasses;
3390 const std::size_t ist = sn.nodes[ind - 1].station;
3391 const RowLayout<T> L = row_layout(sn, ind, row.size());
3392 const double headv = L.bufw > 0 ? num_traits<T>::to_double(row[L.bufw - 1]) : 0.0;
3393 if (!(headv > 0)) {
3394 out.push_back(std::make_pair(std::make_pair(row, p), started));
3395 return;
3396 }
3397 const std::size_t h = static_cast<std::size_t>(headv + 0.5);
3398 double busy = 0;
3399 for (std::size_t r = 0; r < R; ++r)
3400 for (std::size_t k = 0; k < L.K[r]; ++k)
3401 busy += par[r] * num_traits<T>::to_double(row[L.bufw + L.Ks[r] + k]);
3402 // servers held by pending synchronous calls are not free either, n_r per call
3403 const std::vector<T> var(row.begin() + L.bufw + L.srvw, row.end());
3404 const double held = reply_held_servers(sn, ind, var, par);
3405 if (busy + held + par[h - 1] > sn.stations[ist - 1].nservers) {
3406 out.push_back(std::make_pair(std::make_pair(row, p), started));
3407 return;
3408 }
3409 const std::vector<T> pie = entry_phase_dist(sn, ist, h);
3410 for (std::size_t k = 0; k < L.K[h - 1]; ++k) {
3411 if (!(k < pie.size() && num_traits<T>::to_double(pie[k]) > 0)) continue;
3412 std::vector<T> nr = row;
3413 for (std::size_t b = L.bufw - 1; b > 0; --b) nr[b] = row[b - 1];
3414 nr[0] = num_traits<T>::from_int(0);
3415 nr[L.bufw + L.Ks[h - 1] + k] += num_traits<T>::from_int(1);
3416 std::vector<std::size_t> st = started;
3417 if (std::find(st.begin(), st.end(), h) == st.end()) st.push_back(h);
3418 promote_fitting(sn, ind, par, nr, T(p * pie[k]), st, out);
3419 }
3420}
3421
3422/**
3423 * A departure at a station with server parallelism (python `after_event`'s
3424 * parallel arm): it frees its job's servers without the ordinary one-for-one
3425 * promotion, which `promote_fitting` replaces.
3426 */
3427template <class T>
3429 const std::vector<T>& inspace, std::size_t cls,
3430 const T& aux_rate, const std::vector<double>& par) {
3431 EventOutcome<T> out;
3432 EventOutcome<T> o = after_event_station_base(sn, ind, inspace, EventType::DEP, cls, true, aux_rate);
3433 pad_tags(o);
3434 for (std::size_t i = 0; i < o.space.size(); ++i) {
3435 std::vector<std::pair<std::pair<std::vector<T>, T>, std::vector<std::size_t>>> pf;
3436 promote_fitting(sn, ind, par, o.space[i], num_traits<T>::from_int(1), o.start[i], pf);
3437 for (std::size_t x = 0; x < pf.size(); ++x)
3438 blocks_events::push(out, pf[x].first.first, o.rate[i], T(pf[x].first.second * o.prob[i]),
3439 pf[x].second, o.preempt[i]);
3440 }
3441 return out;
3442}
3443
3444/**
3445 * Port of `State.afterEventStation`: the station dispatcher, with the CTMC
3446 * station blocks of ctmc_blocks.h wrapped around the ordinary handlers
3447 * (`after_event_station_base`), in the order of python `after_event`: setup
3448 * and delay-off, retrial attempt levels, server parallelism.
3449 */
3450template <class T>
3452 const std::vector<T>& inspace, EventType event,
3453 std::size_t cls, bool no_promote = false,
3454 const T& aux_rate = num_traits<T>::from_int(0)) {
3455 const std::size_t tailw = ctmc_tail_width(sn, ind);
3456 if (tailw > 0 && (event == EventType::ARV || event == EventType::DEP ||
3457 event == EventType::SETUP || event == EventType::DELAYOFF)) {
3458 const SetupInfo<T> si = setup_info(sn, ind);
3459 if (si.valid) return after_event_setup(sn, ind, inspace, event, cls, no_promote, aux_rate, si);
3460 }
3461 if (tailw > 0 && (event == EventType::ARV || event == EventType::RETRY)) {
3462 const AttemptsLayout ai = attempts_info(sn, ind);
3463 if (ai.valid) return after_event_attempts(sn, ind, inspace, event, cls, no_promote, aux_rate, ai);
3464 }
3465 if (event == EventType::DEP && !no_promote) {
3466 const std::vector<double> par = parallelism_of(sn, ind);
3467 if (!par.empty()) return after_event_parallel(sn, ind, inspace, cls, aux_rate, par);
3468 }
3469 return after_event_station_base(sn, ind, inspace, event, cls, no_promote, aux_rate);
3470}
3471
3472/**
3473 * Port of `State.afterEventTransition`, the PHASE arm: one running server of
3474 * the given mode advances its firing phase (`cls` is interpreted as the MODE,
3475 * as in the reference). ENABLE and FIRE are global events handled by
3476 * `after_global_event`, so they return an empty outcome here, matching the
3477 * reference's no-op arms.
3478 *
3479 * RATE. The MATLAB body multiplies the phase-k move rate by BOTH
3480 * kir(:,mode,k) and nir(mode) (afterEventTransition.m:38-40), but nir is the
3481 * sum of kir over the phases, so the extra factor counts the running servers
3482 * twice; the JAR and the native python carry D0(k,kdest) * kir alone, and
3483 * this port follows them.
3484 *
3485 * The row layout is the one `after_global_event` slices:
3486 * [buf(nmodes) | srv(sum fK) | fired(nmodes) | var].
3487 */
3488template <class T>
3490 const std::vector<T>& inspace, EventType event,
3491 std::size_t mode) {
3492 EventOutcome<T> out;
3493 if (event != EventType::PHASE) return out; // ENABLE / FIRE are global
3494 const typename std::map<std::size_t, TransitionParam<T>>::const_iterator it =
3495 sn.transparam.find(ind);
3496 if (it == sn.transparam.end())
3497 throw InputError("after_event_transition: node has no TransitionParam");
3498 const TransitionParam<T>& tp = it->second;
3499 if (mode == 0 || mode > tp.nmodes)
3500 throw InputError("after_event_transition: mode index is out of range");
3501 const T one = num_traits<T>::from_int(1);
3502
3503 std::vector<std::size_t> fK(tp.nmodes, 1), fKs(tp.nmodes, 0);
3504 std::size_t tot = 0;
3505 for (std::size_t m = 0; m < tp.nmodes; ++m) {
3506 fK[m] = m < tp.firingphases.size() && tp.firingphases[m] > 0 ? tp.firingphases[m] : 1;
3507 fKs[m] = tot;
3508 tot += fK[m];
3509 }
3510 if (fK[mode - 1] <= 1) return out; // a single phase has no internal move
3511 if (mode - 1 >= tp.firingproc.size() ||
3512 tp.firingproc[mode - 1].D0.rows() != fK[mode - 1])
3513 return out;
3514 const Matrix<T>& D0 = tp.firingproc[mode - 1].D0;
3515
3516 for (std::size_t k = 0; k < fK[mode - 1]; ++k) {
3517 const std::size_t idx = tp.nmodes + fKs[mode - 1] + k;
3518 const T cnt = inspace[idx];
3519 if (!(num_traits<T>::to_double(cnt) > 0)) continue;
3520 for (std::size_t kd = 0; kd < fK[mode - 1]; ++kd) {
3521 if (kd == k) continue; // the diagonal is the exit rate, not a move
3522 if (!(num_traits<T>::to_double(D0(k, kd)) > 0)) continue;
3523 std::vector<T> row = inspace;
3524 row[idx] -= one;
3525 row[tp.nmodes + fKs[mode - 1] + kd] += one;
3526 out.space.push_back(row);
3527 out.rate.push_back(T(D0(k, kd) * cnt));
3528 out.prob.push_back(one);
3529 }
3530 }
3531 return out;
3532}
3533
3534/**
3535 * Port of `State.afterEvent`: the successors of one event at one NODE.
3536 *
3537 * The reference's body is mostly slicing -- it cuts `inspace` into buffer,
3538 * server and local-variable blocks and hands the pieces to the per-node-type
3539 * handler. This port slices inside each handler instead (`row_layout`), so what
3540 * remains here is the dispatch itself and the guards that precede it.
3541 *
3542 * A class the station does not accept short-circuits: `phases_of` is zero
3543 * there, and every downstream index into the server block would be out of
3544 * range. That guard is the reference's `K(class) == 0` test.
3545 *
3546 * `cls` IS A MODE, NOT A CLASS, on a Transition's PHASE action; see the guard.
3547 */
3548template <class T>
3550 const std::vector<T>& inspace, EventType event, std::size_t cls,
3551 bool no_promote = false,
3552 const T& aux_rate = num_traits<T>::from_int(0)) {
3553 if (ind == 0 || ind > sn.nodes.size())
3554 throw InputError("after_event: node index is out of range");
3555 const NodeDef& nd = sn.nodes[ind - 1];
3556 // THE `cls` SLOT IS NOT ALWAYS A CLASS. On a Transition's PHASE action it
3557 // carries the MODE, which `refresh_sync` puts there deliberately ("one
3558 // server phase-change action per MODE, not per class") and
3559 // `after_event_transition` reads back as such. Bounding it by `nclasses`
3560 // refused every mode past the class count: spn_basic_closed is one class
3561 // and three modes, so modes 2 and 3 raised "class index is out of range"
3562 // and no closed SPN with more modes than classes could be walked at all.
3563 // The mode bound belongs to the handler, which already applies it against
3564 // `tp.nmodes`, so only the non-Transition case is checked here.
3565 const bool cls_is_mode = (nd.nodetype == NodeType::Transition && event == EventType::PHASE);
3566 if (!cls_is_mode && (cls == 0 || cls > sn.nclasses))
3567 throw InputError("after_event: class index is out of range");
3568
3569 // A Join of an FJ-augmented struct IS a station, but its state is a bare
3570 // per-class count vector: it performs a rendezvous, not a service, so it must
3571 // bypass the buffer/server slicing before `after_event_station` sees it.
3572 if (sn.isfjaugmented && nd.nodetype == NodeType::Join)
3573 return after_event_join(sn, ind, inspace, event, cls);
3574
3575 if (nd.station != 0) {
3576 // A class with no service process at this station cannot be involved
3577 // in any event here.
3578 if (sn.phases_of(nd.station, cls) == 0) return EventOutcome<T>();
3579 return after_event_station(sn, ind, inspace, event, cls, no_promote, aux_rate);
3580 }
3581 if (!nd.stateful) return EventOutcome<T>(); // a stateless node holds nothing
3582
3583 if (nd.nodetype == NodeType::Cache) return after_event_cache(sn, ind, inspace, event, cls);
3584 if (nd.nodetype == NodeType::Fork) return after_event_fork(sn, ind, inspace, event, cls);
3585 if (nd.nodetype == NodeType::Transition)
3586 return after_event_transition(sn, ind, inspace, event, cls);
3587 if (nd.nodetype == NodeType::Router) return after_event_router(sn, ind, inspace, event, cls);
3588
3589 throw UnsupportedError(ErrorKind{"Event"}, "after_event: events at stateful non-station node '" + nd.name +
3590 "' are not ported yet");
3591}
3592
3593namespace signal_detail {
3594
3595/** Merge duplicate destinations so the generator sees one entry per state. */
3596template <class T>
3597void merge_states(std::vector<std::vector<T>>& sp, std::vector<T>& pr) {
3598 std::vector<std::vector<T>> us;
3599 std::vector<T> up;
3600 for (std::size_t i = 0; i < sp.size(); ++i) {
3601 std::size_t at = us.size();
3602 for (std::size_t j = 0; j < us.size(); ++j)
3603 if (us[j] == sp[i]) { at = j; break; }
3604 if (at == us.size()) {
3605 us.push_back(sp[i]);
3606 up.push_back(pr[i]);
3607 } else {
3608 up[at] += pr[i];
3609 }
3610 }
3611 sp.swap(us);
3612 pr.swap(up);
3613}
3614
3615} // namespace signal_detail
3616
3617/**
3618 * Port of `State.signalBatchPMF`: the batch size a negative signal removes.
3619 *
3620 * The pmf is CLIPPED at the eligible population: an oversized batch empties
3621 * the station rather than driving the queue negative, so the whole tail
3622 * P(B >= n) lumps onto "remove all n". That is the same clipping LDES applies
3623 * with min(B,n) and the tail term MAM uses.
3624 */
3625template <class T>
3626std::pair<std::vector<std::size_t>, std::vector<T>> signal_batch_pmf(
3627 const NetworkStruct<T>& sn, std::size_t cls, std::size_t ntot) {
3628 std::vector<std::size_t> kv;
3629 std::vector<T> kp;
3630 if (sn.signalremdist.size() < cls || sn.signalremdist[cls - 1].empty()) {
3631 kv.push_back(1);
3632 kp.push_back(num_traits<T>::from_int(1));
3633 return std::make_pair(kv, kp);
3634 }
3635 const std::vector<T>& d = sn.signalremdist[cls - 1];
3636 T head_sum = num_traits<T>::from_int(0);
3637 for (std::size_t b = 0; b < ntot; ++b) {
3638 const T p = b < d.size() ? d[b] : num_traits<T>::from_int(0);
3639 if (num_traits<T>::to_double(p) > 0) {
3640 kv.push_back(b);
3641 kp.push_back(p);
3642 }
3643 head_sum += p;
3644 }
3645 const double tail = 1.0 - num_traits<T>::to_double(head_sum);
3646 if (tail > 0) {
3647 kv.push_back(ntot);
3648 kp.push_back(num_traits<T>::from_double(tail));
3649 }
3650 if (kv.empty()) {
3651 kv.push_back(1);
3652 kp.push_back(num_traits<T>::from_int(1));
3653 return std::make_pair(kv, kp);
3654 }
3655 T tot = num_traits<T>::from_int(0);
3656 for (std::size_t i = 0; i < kp.size(); ++i) tot += kp[i];
3657 if (num_traits<T>::to_double(tot) > 0)
3658 for (std::size_t i = 0; i < kp.size(); ++i) kp[i] = T(kp[i] / tot);
3659 return std::make_pair(kv, kp);
3660}
3661
3662/**
3663 * Port of `State.afterEventStationSignal`: a G-network signal arrives.
3664 *
3665 * A signal NEVER joins the station. It removes jobs already there and is
3666 * annihilated, so the event is passive throughout and the successors differ
3667 * only in which victims were taken.
3668 *
3669 * Victim selection has two tiers, and conflating them is the trap: FCFS and
3670 * LCFS rank by AGE, which only an ordered buffer records, so at a per-class
3671 * count buffer an age policy degenerates to a uniform draw. They also drain
3672 * the waiting line completely before touching a server, whereas RANDOM draws
3673 * uniformly across waiting and in-service jobs alike.
3674 */
3675template <class T>
3677 const std::vector<T>& inspace, std::size_t cls) {
3678 const std::size_t R = sn.nclasses;
3679 const std::size_t ist = sn.nodes[ind - 1].station;
3680 const T zero = num_traits<T>::from_int(0), one = num_traits<T>::from_int(1);
3681 const T minus_one = num_traits<T>::from_int(-1);
3682 EventOutcome<T> out;
3683 if (ist == 0) throw InputError("after_event_station_signal: node is not a station");
3684 const RowLayout<T> L = row_layout(sn, ind, inspace.size());
3685 const SchedStrategy sched = sn.stations[ist - 1].sched;
3686 const double S = sn.stations[ist - 1].nservers;
3687
3688 std::vector<std::size_t> ph(R, 1), shift(R, 0);
3689 for (std::size_t r = 0; r < R; ++r) {
3690 ph[r] = L.K[r];
3691 shift[r] = L.Ks[r];
3692 }
3693 const Marginal<T> m = to_marginal(sn, ist, inspace, ph, shift, L.nvar);
3694
3695 // A CATASTROPHE empties the station outright, ignoring the batch pmf: a
3696 // catastrophe removes every job by definition.
3697 if (sn.signaltype.size() >= cls && sn.signaltype[cls - 1] == lang::SignalType::CATASTROPHE) {
3698 std::vector<T> row(L.bufw + L.srvw, zero);
3699 row.insert(row.end(), inspace.end() - L.nvar, inspace.end());
3700 out.space.push_back(row);
3701 out.rate.push_back(minus_one);
3702 out.prob.push_back(one);
3703 return out;
3704 }
3705
3706 // Eligible victim classes: the declared target, or every non-signal class
3707 // for the classic untargeted negative customer.
3708 std::vector<std::size_t> tgt;
3709 const std::size_t declared = sn.signaltarget.size() >= cls ? sn.signaltarget[cls - 1] : 0;
3710 if (declared >= 1) {
3711 tgt.push_back(declared);
3712 } else {
3713 for (std::size_t r = 1; r <= R; ++r)
3714 if (sn.issignal.size() < r || !sn.issignal[r - 1]) tgt.push_back(r);
3715 }
3716 std::vector<std::size_t> elig;
3717 std::size_t ntot = 0;
3718 for (std::size_t i = 0; i < tgt.size(); ++i) {
3719 const double nr = num_traits<T>::to_double(m.nir[tgt[i] - 1]);
3720 if (nr > 0) {
3721 elig.push_back(tgt[i]);
3722 ntot += static_cast<std::size_t>(nr);
3723 }
3724 }
3725 if (elig.empty()) {
3726 // No victim: the signal simply vanishes, leaving the state unchanged.
3727 out.space.push_back(inspace);
3728 out.rate.push_back(minus_one);
3729 out.prob.push_back(one);
3730 return out;
3731 }
3732
3733 const lang::RemovalPolicy policy = sn.signalrempolicy.size() >= cls
3734 ? sn.signalrempolicy[cls - 1]
3736 const bool ordered = state_detail::buffer_is_class_tag(sched) ||
3737 state_detail::buffer_is_tag_phase_pairs(sched);
3738 const bool paired = state_detail::buffer_is_tag_phase_pairs(sched);
3739 const bool counted = state_detail::buffer_is_per_class_count(sched);
3740 const std::pair<std::vector<std::size_t>, std::vector<T>> pmf =
3741 signal_batch_pmf(sn, cls, ntot);
3742
3743 std::vector<std::vector<T>> acc;
3744 std::vector<T> accp;
3745 for (std::size_t ik = 0; ik < pmf.first.size(); ++ik) {
3746 if (num_traits<T>::to_double(pmf.second[ik]) <= 0) continue;
3747 std::vector<std::vector<T>> cur(1, inspace);
3748 std::vector<T> curp(1, one);
3749 // Remove one job at a time: sequential draws without replacement give
3750 // a uniform choice of the removed SUBSET.
3751 for (std::size_t step = 0; step < pmf.first[ik]; ++step) {
3752 std::vector<std::vector<T>> nxt;
3753 std::vector<T> nxtp;
3754 for (std::size_t row = 0; row < cur.size(); ++row) {
3755 std::vector<T> buf(cur[row].begin(), cur[row].begin() + L.bufw);
3756 std::vector<T> srv(cur[row].begin() + L.bufw,
3757 cur[row].begin() + L.bufw + L.srvw);
3758 const std::vector<T> var(cur[row].begin() + L.bufw + L.srvw, cur[row].end());
3759
3760 // Waiting victims, as (position, class, multiplicity).
3761 std::vector<std::size_t> wpos, wcls, wwt;
3762 if (ordered) {
3763 for (std::size_t b = 0; b < L.bufw; b += paired ? 2 : 1) {
3764 const double v = num_traits<T>::to_double(buf[b]);
3765 if (v <= 0) continue;
3766 bool ok = false;
3767 for (std::size_t e = 0; e < elig.size(); ++e)
3768 if (elig[e] == static_cast<std::size_t>(v)) ok = true;
3769 if (!ok) continue;
3770 wpos.push_back(b);
3771 wcls.push_back(static_cast<std::size_t>(v));
3772 wwt.push_back(1);
3773 }
3774 } else if (counted) {
3775 for (std::size_t e = 0; e < elig.size(); ++e) {
3776 const std::size_t r = elig[e];
3777 if (r > L.bufw) continue;
3778 const double v = num_traits<T>::to_double(buf[r - 1]);
3779 if (v <= 0) continue;
3780 wpos.push_back(r - 1);
3781 wcls.push_back(r);
3782 wwt.push_back(static_cast<std::size_t>(v));
3783 }
3784 }
3785 // In-service victims, per (class, phase).
3786 std::vector<std::size_t> scls, sph, scnt;
3787 for (std::size_t e = 0; e < elig.size(); ++e) {
3788 const std::size_t r = elig[e];
3789 for (std::size_t p = 0; p < L.K[r - 1]; ++p) {
3790 const double v = num_traits<T>::to_double(srv[L.Ks[r - 1] + p]);
3791 if (v <= 0) continue;
3792 scls.push_back(r);
3793 sph.push_back(p);
3794 scnt.push_back(static_cast<std::size_t>(v));
3795 }
3796 }
3797 std::size_t nwait = 0, nsrv = 0;
3798 for (std::size_t i = 0; i < wwt.size(); ++i) nwait += wwt[i];
3799 for (std::size_t i = 0; i < scnt.size(); ++i) nsrv += scnt[i];
3800 if (nwait == 0 && nsrv == 0) {
3801 // Already drained: nothing left for this step to remove.
3802 nxt.push_back(cur[row]);
3803 nxtp.push_back(curp[row]);
3804 continue;
3805 }
3806
3807 std::vector<std::vector<T>> sp;
3808 std::vector<T> pr;
3809 const bool age_ordered =
3810 ordered && (policy == lang::RemovalPolicy::FCFS ||
3811 policy == lang::RemovalPolicy::LCFS);
3812 if (age_ordered && nwait > 0) {
3813 // The head of line is the LAST occupied slot, the newest
3814 // arrival the first: the buffer is right-aligned.
3815 std::size_t pick = 0;
3816 for (std::size_t i = 0; i < wpos.size(); ++i)
3817 if (policy == lang::RemovalPolicy::FCFS ? wpos[i] > wpos[pick]
3818 : wpos[i] < wpos[pick])
3819 pick = i;
3820 std::vector<T> b2 = buf;
3821 b2.erase(b2.begin() + wpos[pick], b2.begin() + wpos[pick] + (paired ? 2 : 1));
3822 b2.insert(b2.begin(), paired ? 2 : 1, zero);
3823 std::vector<T> nr = b2;
3824 nr.insert(nr.end(), srv.begin(), srv.end());
3825 nr.insert(nr.end(), var.begin(), var.end());
3826 sp.push_back(nr);
3827 pr.push_back(one);
3828 } else {
3829 // RANDOM draws over everything present; FCFS/LCFS at a
3830 // count buffer drain the waiting line first, and only reach
3831 // the servers once it is empty.
3832 const std::size_t total = policy == lang::RemovalPolicy::RANDOM
3833 ? nwait + nsrv
3834 : (nwait > 0 ? nwait : nsrv);
3835 for (std::size_t i = 0; i < wpos.size(); ++i) {
3836 std::vector<T> b2 = buf;
3837 if (counted) {
3838 b2[wcls[i] - 1] -= one;
3839 } else {
3840 b2.erase(b2.begin() + wpos[i],
3841 b2.begin() + wpos[i] + (paired ? 2 : 1));
3842 b2.insert(b2.begin(), paired ? 2 : 1, zero);
3843 }
3844 std::vector<T> nr = b2;
3845 nr.insert(nr.end(), srv.begin(), srv.end());
3846 nr.insert(nr.end(), var.begin(), var.end());
3847 sp.push_back(nr);
3848 pr.push_back(num_traits<T>::from_double(static_cast<double>(wwt[i]) /
3849 static_cast<double>(total)));
3850 }
3851 if (policy == lang::RemovalPolicy::RANDOM || nwait == 0) {
3852 for (std::size_t i = 0; i < scls.size(); ++i) {
3853 std::vector<T> b2 = buf, s2 = srv;
3854 s2[L.Ks[scls[i] - 1] + sph[i]] -= one;
3855 // The freed server pulls in the head of line, where
3856 // the station keeps one at all.
3857 double occ = 0;
3858 for (std::size_t j = 0; j < s2.size(); ++j)
3859 occ += num_traits<T>::to_double(s2[j]);
3860 if (L.bufw > 0 && occ < S) {
3861 if (ordered) {
3862 std::size_t hp = L.bufw;
3863 for (std::size_t b = 0; b < L.bufw; b += paired ? 2 : 1)
3864 if (num_traits<T>::to_double(b2[b]) > 0) hp = b;
3865 if (hp != L.bufw) {
3866 const std::size_t pc = static_cast<std::size_t>(
3867 num_traits<T>::to_double(b2[hp]));
3868 std::size_t pp = 0;
3869 if (paired) {
3870 const double v =
3871 num_traits<T>::to_double(b2[hp + 1]);
3872 pp = v >= 1 ? static_cast<std::size_t>(v) - 1 : 0;
3873 }
3874 b2.erase(b2.begin() + hp,
3875 b2.begin() + hp + (paired ? 2 : 1));
3876 b2.insert(b2.begin(), paired ? 2 : 1, zero);
3877 s2[L.Ks[pc - 1] + pp] += one;
3878 }
3879 } else if (counted) {
3880 // A count buffer carries no order, so the
3881 // lowest-indexed waiting class is promoted
3882 // to keep the map single-valued; the actual
3883 // service order is resolved by the rates.
3884 for (std::size_t r = 1; r <= R && r <= L.bufw; ++r)
3885 if (num_traits<T>::to_double(b2[r - 1]) > 0) {
3886 b2[r - 1] -= one;
3887 s2[L.Ks[r - 1]] += one;
3888 break;
3889 }
3890 }
3891 }
3892 std::vector<T> nr = b2;
3893 nr.insert(nr.end(), s2.begin(), s2.end());
3894 nr.insert(nr.end(), var.begin(), var.end());
3895 sp.push_back(nr);
3896 pr.push_back(num_traits<T>::from_double(
3897 static_cast<double>(scnt[i]) / static_cast<double>(total)));
3898 }
3899 }
3900 }
3901 signal_detail::merge_states(sp, pr);
3902 for (std::size_t i = 0; i < sp.size(); ++i) {
3903 nxt.push_back(sp[i]);
3904 nxtp.push_back(T(curp[row] * pr[i]));
3905 }
3906 }
3907 signal_detail::merge_states(nxt, nxtp);
3908 cur.swap(nxt);
3909 curp.swap(nxtp);
3910 }
3911 for (std::size_t i = 0; i < cur.size(); ++i) {
3912 acc.push_back(cur[i]);
3913 accp.push_back(T(pmf.second[ik] * curp[i]));
3914 }
3915 }
3916 signal_detail::merge_states(acc, accp);
3917 out.space.swap(acc);
3918 out.prob.swap(accp);
3919 out.rate.assign(out.space.size(), minus_one);
3920 return out;
3921}
3922
3923/**
3924 * Port of `State.passAndSwap`: the transition a service completion triggers at
3925 * a pass-and-swap station (Dorsman and Gardner 2024, Sect. 2.3).
3926 *
3927 * The completing job scans FORWARD from its own position for the first job it
3928 * may swap with per the graph G, takes that job's place and ejects it; the
3929 * ejected job repeats the scan. The chain ends at a job with no swappable
3930 * successor, and THAT job departs -- which is why the departing class is in
3931 * general not the class whose service completed.
3932 *
3933 * @param c 0-based list of 1-based class indices, oldest first
3934 * @param p 0-based position whose service token completed
3935 * @param G class-compatibility graph, G[a][b] true when a may swap with b
3936 * @return (the list after the transition, the 1-based departing class)
3937 */
3938template <class T>
3939std::pair<std::vector<std::size_t>, std::size_t> pass_and_swap(
3940 const std::vector<std::size_t>& c, std::size_t p,
3941 const std::vector<std::vector<bool>>& G) {
3942 const std::size_t n = c.size();
3943 if (p >= n) throw InputError("pass_and_swap: position is out of range for the state");
3944 std::vector<std::size_t> chain(1, p);
3945 std::size_t moving = c[p], cur = p;
3946 for (;;) {
3947 std::size_t q = n;
3948 for (std::size_t j = cur + 1; j < n; ++j)
3949 if (moving - 1 < G.size() && c[j] - 1 < G[moving - 1].size() &&
3950 G[moving - 1][c[j] - 1]) {
3951 q = j;
3952 break;
3953 }
3954 if (q == n) break; // no swappable successor: this job departs
3955 chain.push_back(q);
3956 moving = c[q];
3957 cur = q;
3958 }
3959 const std::size_t dep = c[chain.back()];
3960 // Shift classes one step along the chain; the last is overwritten because
3961 // it departed, and the head-of-chain slot is then removed.
3962 std::vector<std::size_t> cnew = c;
3963 for (std::size_t i = 0; i + 1 < chain.size(); ++i) cnew[chain[i + 1]] = c[chain[i]];
3964 cnew.erase(cnew.begin() + chain[0]);
3965 return std::make_pair(cnew, dep);
3966}
3967
3968/**
3969 * Per-position service rate increments Delta_mu(c1..cp) = mu(c1..cp) - mu(c1..c_{p-1}).
3970 */
3971template <class T, class F>
3972inline std::vector<double> pas_increments(const F& mu_fun, const std::vector<std::size_t>& c) {
3973 std::vector<double> inc(c.size(), 0.0);
3974 double mu_prev = 0.0;
3975 for (std::size_t p = 0; p < c.size(); ++p) {
3976 const std::vector<std::size_t> prefix(c.begin(), c.begin() + p + 1);
3977 const double mu_cur = num_traits<T>::to_double(mu_fun(prefix));
3978 inc[p] = mu_cur - mu_prev;
3979 mu_prev = mu_cur;
3980 }
3981 return inc;
3982}
3983
3984/**
3985 * Tag the successor just appended to OUT with the PAS positions that started
3986 * service on it: those of CNEW that are served (Delta_mu > 0) and were not
3987 * served in COLD. Under a swap the tag follows the POSITION rather than the job
3988 * identity, since pass-and-swap redefines which job holds a position.
3989 */
3990template <class T, class F>
3991inline void pas_tag_started(EventOutcome<T>& out, const F& mu_fun,
3992 const std::vector<std::size_t>& cold,
3993 const std::vector<std::size_t>& cnew) {
3994 if (!mu_fun || out.space.empty()) return;
3995 const std::vector<double> inc_new = pas_increments<T>(mu_fun, cnew);
3996 const std::vector<double> inc_old = pas_increments<T>(mu_fun, cold);
3997 for (std::size_t p = 0; p < inc_new.size(); ++p) {
3998 if (inc_new[p] <= 0) continue;
3999 if (p < inc_old.size() && inc_old[p] > 0) continue; // already served
4000 tag_last(out, cnew[p], 0);
4001 }
4002}
4003
4004/**
4005 * Port of `State.afterEventStationPAS`: events at a pass-and-swap station.
4006 *
4007 * The state here is NOT the [buffer | server] split every other discipline
4008 * uses: it is the full ordered list of class indices, left-aligned and zero
4009 * padded, with no server block at all. Service is governed by the rate
4010 * function mu(c) rather than by a per-class rate, so the whole notion of "in
4011 * service" is replaced by a token at each position.
4012 */
4013template <class T>
4015 const std::vector<T>& inspace, EventType event,
4016 std::size_t cls) {
4017 const std::size_t ist = sn.nodes[ind - 1].station;
4018 const T one = num_traits<T>::from_int(1), zero = num_traits<T>::from_int(0);
4019 EventOutcome<T> out;
4020 if (ist == 0) throw InputError("after_event_station_pas: node is not a station");
4021 const typename std::map<std::size_t, typename NetworkStruct<T>::PasParam>::const_iterator it =
4022 sn.pasparam.find(ist);
4023 if (it == sn.pasparam.end() || !it->second.svc_rate_fun)
4024 throw InputError(
4025 "after_event_station_pas: the station has no service rate function mu(c); set one "
4026 "with set_pas");
4027
4028 const std::size_t V = sn.nvars_of(ind);
4029 const std::size_t W = inspace.size() - V;
4030 std::vector<std::size_t> c;
4031 for (std::size_t i = 0; i < W; ++i) {
4032 const double v = num_traits<T>::to_double(inspace[i]);
4033 if (v > 0) c.push_back(static_cast<std::size_t>(v));
4034 }
4035 const std::vector<T> var(inspace.begin() + W, inspace.end());
4036 const double cap = sn.cap[ist - 1];
4037 // An uncapped OI/PAS station has no fixed-width list, so it has no state
4038 // space (afterEventStationPAS.m). Its empty state is the one-slot list
4039 // from_marginal hands the analytical routes; filling that slot here would
4040 // block every second arrival silently, so the event is refused by name.
4041 if (!std::isfinite(cap))
4042 throw InputError(
4043 "after_event_station_pas: PAS stations require finite capacity for state-space "
4044 "generation");
4045
4046 if (event == EventType::ARV) {
4047 // The arrival joins at the BACK of the list, which is what records the
4048 // order the rate function is a function of.
4049 if (static_cast<double>(c.size()) >= cap) return out; // full: lost
4050 std::vector<std::size_t> nc = c;
4051 nc.push_back(cls);
4052 // NO SLOT IN THE ENCODING IS A BLOCK, NOT A LOSS. The list occupies one
4053 // row position per job, so a row of width W holds W jobs; emitting a
4054 // successor here and letting `row.resize(W, zero)` cut the list back to
4055 // W would DESTROY the job that did not fit while reporting a state that
4056 // looks exactly like the pre-arrival one -- a customer silently gone
4057 // from a closed network, with no error anywhere. Returning no successor
4058 // disables the upstream departure instead, which is what every other
4059 // discipline's capacity filter does and what the enumerated CTMC space
4060 // does at its own width boundary.
4061 if (nc.size() > W) return out;
4062 std::vector<T> row;
4063 for (std::size_t i = 0; i < nc.size(); ++i)
4064 row.push_back(num_traits<T>::from_int(static_cast<long>(nc[i])));
4065 row.resize(W, zero);
4066 row.insert(row.end(), var.begin(), var.end());
4067 out.space.push_back(row);
4068 out.rate.push_back(num_traits<T>::from_int(-1));
4069 out.prob.push_back(one);
4070 // A PAS station has one clock for the whole station and no server to
4071 // hold, so "in service" means "at a position whose rate increment
4072 // Delta_mu is positive": a job starts exactly when a position goes from
4073 // a zero increment to a positive one. With mu(c) = 1 only the head is
4074 // served (M/M/1), with mu(c) = |c| every position is (M/M/inf), and the
4075 // rule reproduces both.
4076 pas_tag_started<T>(out, it->second.svc_rate_fun, c, nc);
4077 pad_tags(out);
4078 return out;
4079 }
4080 if (event != EventType::DEP) return out; // PAS service is exponential: no PHASE
4081
4082 // Each position holds a service token firing at the INCREMENT of mu over
4083 // the prefix ending there. Summing the increments telescopes to mu(c), so
4084 // the station's total service rate is exactly the rate function.
4085 T mu_prev = zero;
4086 for (std::size_t p = 0; p < c.size(); ++p) {
4087 const std::vector<std::size_t> prefix(c.begin(), c.begin() + p + 1);
4088 const T mu_cur = it->second.svc_rate_fun(prefix);
4089 const T ratep = T(mu_cur - mu_prev);
4090 mu_prev = mu_cur;
4091 if (num_traits<T>::to_double(ratep) <= 0) continue; // position unserved
4092 const std::pair<std::vector<std::size_t>, std::size_t> ps =
4093 pass_and_swap<T>(c, p, it->second.swap_graph);
4094 // The completing token need not eject its own class, so only the
4095 // positions whose chain ends in THIS class contribute to its departure.
4096 if (ps.second != cls) continue;
4097 std::vector<T> row;
4098 for (std::size_t i = 0; i < ps.first.size(); ++i)
4099 row.push_back(num_traits<T>::from_int(static_cast<long>(ps.first[i])));
4100 row.resize(W, zero);
4101 row.insert(row.end(), var.begin(), var.end());
4102 out.space.push_back(row);
4103 out.rate.push_back(ratep);
4104 out.prob.push_back(one);
4105 pas_tag_started<T>(out, it->second.svc_rate_fun, c, ps.first);
4106 }
4107 pad_tags(out);
4108 return out;
4109}
4110
4111/**
4112 * Port of `State.replyBlockInfo`: the layout of the reply block.
4113 *
4114 * The block trails the modulation, routing and shared-node columns of nvars,
4115 * occupying columns 2R+1+r. Appending is deliberate -- every existing nvars
4116 * reader keeps its indices, and the columns stay zero-width for models without
4117 * reply signals, so no other model changes state width.
4118 */
4119template <class T>
4121 const std::size_t R = sn.nclasses;
4122 ReplyBlockInfo ri;
4123 ri.slot.assign(R, static_cast<std::size_t>(-1));
4124 if (sn.nvars.size() < ind || sn.nvars[ind - 1].size() < 3 * R + 1) return ri;
4125 std::size_t pos = 0;
4126 for (std::size_t j = 0; j < 2 * R + 1; ++j) pos += sn.nvars[ind - 1][j];
4127 for (std::size_t r = 1; r <= R; ++r)
4128 if (sn.nvars[ind - 1][2 * R + r] > 0) {
4129 ri.slot[r - 1] = pos;
4130 ri.classes.push_back(r);
4131 ++pos;
4132 ++ri.width;
4133 }
4134 return ri;
4135}
4136
4137/** How many servers node `ind` is holding for pending replies, from its vars. */
4138template <class T>
4139double reply_blocked(const NetworkStruct<T>& sn, std::size_t ind, const std::vector<T>& var) {
4140 const ReplyBlockInfo ri = reply_block_info(sn, ind);
4141 double nb = 0;
4142 for (std::size_t i = 0; i < ri.classes.size(); ++i) {
4143 const std::size_t s = ri.slot[ri.classes[i] - 1];
4144 // The slot is an index into the local-variable block, which is the
4145 // TAIL of the row, so it is offset from the start of `var`.
4146 if (s != static_cast<std::size_t>(-1) && s < var.size())
4147 nb += num_traits<T>::to_double(var[s]);
4148 }
4149 return nb;
4150}
4151
4152/**
4153 * Servers node `ind` holds for pending replies (MATLAB `State.ctmcHeldServers`,
4154 * python `server_parallelism._held_servers`). Under server parallelism a
4155 * pending call of class r holds the `par[r-1]` servers its job seized, not one;
4156 * with `par` empty (every class seizes one server) it is `reply_blocked`.
4157 */
4158template <class T>
4159double reply_held_servers(const NetworkStruct<T>& sn, std::size_t ind, const std::vector<T>& var,
4160 const std::vector<double>& par) {
4161 const ReplyBlockInfo ri = reply_block_info(sn, ind);
4162 double h = 0;
4163 for (std::size_t i = 0; i < ri.classes.size(); ++i) {
4164 const std::size_t r = ri.classes[i];
4165 const std::size_t s = ri.slot[r - 1];
4166 if (s == static_cast<std::size_t>(-1) || s >= var.size()) continue;
4167 h += (r - 1 < par.size() ? par[r - 1] : 1.0) * num_traits<T>::to_double(var[s]);
4168 }
4169 return h;
4170}
4171
4172/**
4173 * Port of `State.afterEventStationReply`: a REPLY signal completes a
4174 * synchronous call at the station holding the server for it.
4175 *
4176 * A REPLY is not a negative customer. It releases one held server and then
4177 * JOINS as an ordinary job carrying the call result onward, so unlike
4178 * NEGATIVE or CATASTROPHE it is not annihilated.
4179 *
4180 * PASS-THROUGH is the subtle part: the released server is taken by the reply
4181 * ITSELF, never by a waiting job. The reply is work this station already paid
4182 * for, so queueing it behind the residents both misreports its residence and
4183 * steals capacity. Its service is typically Immediate, so the server is handed
4184 * straight back and the ordinary departure path then promotes the head of
4185 * line -- which also keeps the occupancy within the server count, unlike
4186 * admitting the reply on top of a promoted job.
4187 */
4188template <class T>
4190 const std::vector<T>& inspace, std::size_t cls) {
4191 const std::size_t R = sn.nclasses;
4192 const std::size_t ist = sn.nodes[ind - 1].station;
4193 const T one = num_traits<T>::from_int(1), zero = num_traits<T>::from_int(0);
4194 EventOutcome<T> out;
4195 if (ist == 0) throw InputError("after_event_station_reply: node is not a station");
4196 const RowLayout<T> L = row_layout(sn, ind, inspace.size());
4197 const ReplyBlockInfo ri = reply_block_info(sn, ind);
4198 const double S = sn.stations[ist - 1].nservers;
4199
4200 // The calling class this reply releases: the one whose expected reply IS
4201 // this class and which holds a block here.
4202 std::size_t callclass = 0;
4203 for (std::size_t i = 0; i < ri.classes.size(); ++i) {
4204 const std::size_t r = ri.classes[i];
4205 if (sn.syncreply.size() >= r && sn.syncreply[r - 1] == cls) {
4206 callclass = r;
4207 break;
4208 }
4209 }
4210
4211 std::vector<T> buf(inspace.begin(), inspace.begin() + L.bufw);
4212 std::vector<T> srv(inspace.begin() + L.bufw, inspace.begin() + L.bufw + L.srvw);
4213 std::vector<T> var(inspace.begin() + L.bufw + L.srvw, inspace.end());
4214
4215 if (callclass > 0) {
4216 const std::size_t s = ri.slot[callclass - 1];
4217 if (s != static_cast<std::size_t>(-1) && s < var.size() &&
4218 num_traits<T>::to_double(var[s]) > 0)
4219 var[s] -= one;
4220 }
4221
4222 // The reply joins: into a free server, enumerating its entry phase, or at
4223 // the tail of the buffer. Servers still held for OTHER pending replies are
4224 // not available, which is what `Seff` subtracts.
4225 const double seff = S - reply_blocked(sn, ind, var);
4226 double occ = 0;
4227 for (std::size_t j = 0; j < srv.size(); ++j) occ += num_traits<T>::to_double(srv[j]);
4228 bool fits = occ < seff;
4229 // Server parallelism counts SERVERS: n_r per job in service and per call
4230 // still held, plus the n of the reply's own class (MATLAB
4231 // `sub_joinReply`, python `parallel_fits`).
4232 const std::vector<double> par = sn.stations[ist - 1].sched == SchedStrategy::FCFS
4233 ? parallelism_of(sn, ind)
4234 : std::vector<double>();
4235 if (!par.empty()) {
4236 double busy = 0;
4237 for (std::size_t r = 0; r < R; ++r)
4238 for (std::size_t k = 0; k < L.K[r]; ++k)
4239 busy += par[r] * num_traits<T>::to_double(srv[L.Ks[r] + k]);
4240 fits = busy + reply_held_servers(sn, ind, var, par) + par[cls - 1] <= S;
4241 }
4242 if (fits) {
4243 const std::vector<T> pentry = entry_phase_dist(sn, ist, cls);
4244 for (std::size_t ke = 0; ke < L.K[cls - 1]; ++ke) {
4245 if (num_traits<T>::to_double(pentry[ke]) <= 0) continue;
4246 std::vector<T> s2 = srv;
4247 s2[L.Ks[cls - 1] + ke] += one;
4248 std::vector<T> row = buf;
4249 row.insert(row.end(), s2.begin(), s2.end());
4250 row.insert(row.end(), var.begin(), var.end());
4251 out.space.push_back(row);
4252 out.rate.push_back(num_traits<T>::from_int(-1));
4253 out.prob.push_back(pentry[ke]);
4254 }
4255 return out;
4256 }
4257 // Every available server is busy: queue at the tail, which for a
4258 // right-aligned buffer is the LAST empty slot.
4259 std::vector<T> b2 = buf;
4260 std::size_t slot = b2.size();
4261 for (std::size_t b = 0; b < b2.size(); ++b)
4262 if (num_traits<T>::to_double(b2[b]) == 0) slot = b;
4263 if (slot == b2.size()) {
4264 b2.insert(b2.begin(), zero);
4265 slot = 0;
4266 }
4267 b2[slot] = num_traits<T>::from_int(static_cast<long>(cls));
4268 std::vector<T> row = b2;
4269 row.insert(row.end(), srv.begin(), srv.end());
4270 row.insert(row.end(), var.begin(), var.end());
4271 out.space.push_back(row);
4272 out.rate.push_back(num_traits<T>::from_int(-1));
4273 out.prob.push_back(one);
4274 return out;
4275}
4276
4277
4278/** Read (pos, swk, ctr) out of the local-variable block. */
4279template <class T>
4280void polling_get(const PollingInfo<T>& pi, const std::vector<T>& var, std::size_t srvclass,
4281 std::size_t& pos, std::size_t& swk, long& ctr) {
4282 pos = pi.ipos != static_cast<std::size_t>(-1)
4283 ? static_cast<std::size_t>(num_traits<T>::to_double(var[pi.off + pi.ipos]))
4284 : (srvclass > 0 && srvclass <= pi.pos_of.size() && pi.pos_of[srvclass - 1] > 0
4285 ? pi.pos_of[srvclass - 1]
4286 : (pi.canon_pos > 0 ? pi.canon_pos : 1));
4287 swk = pi.iswk != static_cast<std::size_t>(-1)
4288 ? static_cast<std::size_t>(num_traits<T>::to_double(var[pi.off + pi.iswk]))
4289 : 0;
4290 ctr = pi.ictr != static_cast<std::size_t>(-1)
4291 ? static_cast<long>(num_traits<T>::to_double(var[pi.off + pi.ictr]))
4292 : 0;
4293}
4294
4295/** Write (pos, swk, ctr) back into the local-variable block. */
4296template <class T>
4297std::vector<T> polling_set(const PollingInfo<T>& pi, std::vector<T> var, std::size_t pos,
4298 std::size_t swk, long ctr) {
4299 if (pi.ipos != static_cast<std::size_t>(-1))
4300 var[pi.off + pi.ipos] = num_traits<T>::from_int(static_cast<long>(pos));
4301 if (pi.iswk != static_cast<std::size_t>(-1))
4302 var[pi.off + pi.iswk] = num_traits<T>::from_int(static_cast<long>(swk));
4303 if (pi.ictr != static_cast<std::size_t>(-1))
4304 var[pi.off + pi.ictr] = num_traits<T>::from_int(ctr);
4305 return var;
4306}
4307
4308/** Port of `State.pollingBudget`: how many services this visit may perform. */
4309template <class T>
4310long polling_budget(const PollingInfo<T>& pi, long nbufq) {
4311 switch (pi.ptype) {
4312 case lang::PollingType::EXHAUSTIVE: return 0; // unused: drains instead
4313 case lang::PollingType::GATED: return nbufq; // exactly those found
4314 case lang::PollingType::KLIMITED: return static_cast<long>(pi.pk);
4315 case lang::PollingType::DECREMENTING: return nbufq - 1;
4316 case lang::PollingType::GLIMITED: return std::min(static_cast<long>(pi.pk), nbufq);
4317 default: throw UnsupportedError(ErrorKind{"SchedStrategy_POLLING"}, "polling_budget: unsupported polling type");
4318 }
4319}
4320
4321/**
4322 * Port of `State.pollingNext`: where the server goes from buffer `pos`.
4323 *
4324 * Returns mode 1 to open a visit at q, 2 to enter the switchover into q, and 0
4325 * to PARK. Parking is reachable only with every switchover immediate, where a
4326 * server completing a full lap without finding work would otherwise cycle in
4327 * zero time forever.
4328 */
4329template <class T>
4330void polling_next(const PollingInfo<T>& pi, std::size_t pos, const std::vector<long>& nbuf,
4331 std::size_t R, bool arrived, std::size_t& q, int& mode, long& budget) {
4332 if (arrived && pi.polled[pos - 1] && nbuf[pos - 1] > 0) {
4333 // The switchover into pos is already paid for, so a visit starts here.
4334 q = pos;
4335 mode = 1;
4336 budget = polling_budget(pi, nbuf[pos - 1]);
4337 return;
4338 }
4339 std::size_t p = pos;
4340 for (std::size_t step = 0; step < R; ++step) { // a full lap, ending at pos
4341 p = p % R + 1;
4342 if (!pi.polled[p - 1]) continue;
4343 if (pi.has_sw[p - 1]) {
4344 q = p;
4345 mode = 2;
4346 budget = 0;
4347 return;
4348 }
4349 if (nbuf[p - 1] > 0) {
4350 q = p;
4351 mode = 1;
4352 budget = polling_budget(pi, nbuf[p - 1]);
4353 return;
4354 }
4355 }
4356 q = pos;
4357 mode = 0;
4358 budget = 0;
4359}
4360
4361/** Port of `State.pollingLand`: the states the walk lands in, with weights. */
4362template <class T>
4363void polling_land(const NetworkStruct<T>& sn, std::size_t ist, const PollingInfo<T>& pi,
4364 std::size_t q, int mode, long budget, const std::vector<T>& buf,
4365 const std::vector<T>& srv, const std::vector<T>& var, const RowLayout<T>& L,
4366 std::vector<std::vector<T>>& rows, std::vector<T>& probs) {
4367 const T one = num_traits<T>::from_int(1);
4368 if (mode == 1) {
4369 // Open or continue a visit at q: pull a waiting class-q job in.
4370 std::vector<T> b2 = buf;
4371 b2[q - 1] -= one;
4372 const std::vector<T> pentry = entry_phase_dist(sn, ist, q);
4373 for (std::size_t ke = 0; ke < L.K[q - 1]; ++ke) {
4374 if (num_traits<T>::to_double(pentry[ke]) <= 0) continue;
4375 std::vector<T> s2 = srv;
4376 s2[L.Ks[q - 1] + ke] += one;
4377 std::vector<T> row = b2;
4378 row.insert(row.end(), s2.begin(), s2.end());
4379 const std::vector<T> v2 = polling_set(pi, var, q, 0, budget);
4380 row.insert(row.end(), v2.begin(), v2.end());
4381 rows.push_back(row);
4382 probs.push_back(pentry[ke]);
4383 }
4384 } else if (mode == 2) {
4385 // Enter the switchover into q: the facility stays EMPTY while walking.
4386 for (std::size_t ke = 0; ke < pi.ksw[q - 1]; ++ke) {
4387 if (num_traits<T>::to_double(pi.sw_pie[q - 1][ke]) <= 0) continue;
4388 std::vector<T> row = buf;
4389 row.insert(row.end(), srv.begin(), srv.end());
4390 const std::vector<T> v2 = polling_set(pi, var, q, ke + 1, 0);
4391 row.insert(row.end(), v2.begin(), v2.end());
4392 rows.push_back(row);
4393 probs.push_back(pi.sw_pie[q - 1][ke]);
4394 }
4395 } else {
4396 // Park: held until the next arrival wakes the server.
4397 std::vector<T> row = buf;
4398 row.insert(row.end(), srv.begin(), srv.end());
4399 const std::vector<T> v2 = polling_set(pi, var, q, 0, 0);
4400 row.insert(row.end(), v2.begin(), v2.end());
4401 rows.push_back(row);
4402 probs.push_back(one);
4403 }
4404}
4405
4406
4407/** Port of `State.pollingGetFull`: [pos, swk, ctr, src, tht, trt_1..R]. */
4408template <class T>
4409std::vector<long> polling_get_full(const PollingInfo<T>& pi, const std::vector<T>& var, std::size_t srvclass) {
4410 const std::size_t R = pi.polled.size();
4411 std::vector<long> c(5 + R, 0);
4412 std::size_t pos = 0, swk = 0;
4413 long ctr = 0;
4414 polling_get(pi, var, srvclass, pos, swk, ctr);
4415 c[0] = static_cast<long>(pos);
4416 c[1] = static_cast<long>(swk);
4417 c[2] = ctr;
4418 const std::size_t npos = static_cast<std::size_t>(-1);
4419 auto rd = [&](std::size_t i) { return static_cast<long>(num_traits<T>::to_double(var[pi.off + i])); };
4420 if (pi.isrc != npos)
4421 c[3] = rd(pi.isrc);
4422 else if (c[1] > 0)
4423 c[3] = static_cast<long>(pi.src_default);
4424 if (pi.itht != npos) c[4] = rd(pi.itht);
4425 for (std::size_t r = 0; r < R && r < pi.itrt.size(); ++r)
4426 if (pi.itrt[r] != npos) c[5 + r] = rd(pi.itrt[r]);
4427 return c;
4428}
4429
4430/** Port of `State.pollingSetFull`: write the materialized entries back. */
4431template <class T>
4432std::vector<T> polling_set_full(const PollingInfo<T>& pi, std::vector<T> var, const std::vector<long>& c) {
4433 var = polling_set(pi, var, static_cast<std::size_t>(c[0]), static_cast<std::size_t>(c[1]), c[2]);
4434 const std::size_t npos = static_cast<std::size_t>(-1);
4435 if (pi.isrc != npos) var[pi.off + pi.isrc] = num_traits<T>::from_int(c[3]);
4436 if (pi.itht != npos) var[pi.off + pi.itht] = num_traits<T>::from_int(c[4]);
4437 for (std::size_t r = 0; r < pi.itrt.size(); ++r)
4438 if (pi.itrt[r] != npos) var[pi.off + pi.itrt[r]] = num_traits<T>::from_int(c[5 + r]);
4439 return var;
4440}
4441
4442/** Port of `State.pollingChoose`: the next buffer under a load-dependent order, 0 if none. */
4443template <class T>
4444std::size_t polling_choose(const PollingInfo<T>& pi, std::size_t i, const std::vector<long>& nbuf) {
4445 const std::size_t R = pi.polled.size();
4446 auto skip_empty = [&]() -> std::size_t {
4447 std::size_t p = i;
4448 for (std::size_t step = 0; step < R; ++step) {
4449 p = p % R + 1;
4450 if (pi.polled[p - 1] && nbuf[p - 1] > 0) return p;
4451 }
4452 return 0;
4453 };
4454 switch (pi.order) {
4456 if (nbuf[pi.thr_class - 1] > pi.thr_l) return pi.thr_class;
4457 return skip_empty();
4459 return skip_empty();
4461 long best = 0;
4462 std::size_t j = 0, p = i;
4463 for (std::size_t step = 0; step < R; ++step) {
4464 p = p % R + 1;
4465 if (pi.polled[p - 1] && nbuf[p - 1] > best) {
4466 best = nbuf[p - 1];
4467 j = p;
4468 }
4469 }
4470 return j;
4471 }
4472 default:
4473 throw InternalError(ErrorKind{"Invariant"}, "polling_choose called for a cyclic polling order.");
4474 }
4475}
4476
4478
4479template <class T>
4480void add_row(PollingAdvance<T>& B, const std::vector<long>& c, int mode, std::size_t q, T prob) {
4481 B.C.push_back(c);
4482 B.mode.push_back(mode);
4483 B.q.push_back(q);
4484 B.prob.push_back(prob);
4485}
4486
4487template <class T>
4488void add_visit(const PollingInfo<T>& pi, PollingAdvance<T>& B, std::vector<long> c, std::size_t p,
4489 std::size_t r, const std::vector<long>& nbuf, T prob) {
4490 c[0] = static_cast<long>(p);
4491 c[1] = 0;
4492 c[3] = 0;
4493 c[2] = polling_budget(pi, nbuf[r - 1]);
4494 if (pi.tmode == lang::PollingTimer::LOCAL) {
4495 for (std::size_t k = 0; k < pi.tk[r - 1]; ++k) {
4496 if (num_traits<T>::to_double(pi.t_pie[r - 1][k]) <= 0) continue;
4497 std::vector<long> ck = c;
4498 ck[4] = static_cast<long>(k + 1);
4499 add_row(B, ck, 1, r, T(prob * pi.t_pie[r - 1][k]));
4500 }
4501 } else {
4502 add_row(B, c, 1, r, prob);
4503 }
4504}
4505
4506template <class T>
4507void arrive_at(const PollingInfo<T>& pi, PollingAdvance<T>& B, const std::vector<long>& c,
4508 const std::vector<long>& nbuf, std::size_t p, T prob, std::vector<std::vector<long>>& passC,
4509 std::vector<T>& passP) {
4510 const std::size_t r = pi.ring[p - 1];
4512 const long trt = c[5 + r - 1];
4513 for (std::size_t k = 0; k < pi.tk[r - 1]; ++k) {
4514 if (num_traits<T>::to_double(pi.t_pie[r - 1][k]) <= 0) continue;
4515 std::vector<long> ck = c;
4516 ck[5 + r - 1] = static_cast<long>(k + 1); // TRT_r restarts at every token arrival
4517 const T pk = T(prob * pi.t_pie[r - 1][k]);
4518 if (trt > 0 && nbuf[r - 1] > 0) {
4519 ck[0] = static_cast<long>(p);
4520 ck[2] = polling_budget(pi, nbuf[r - 1]);
4521 ck[4] = trt;
4522 add_row(B, ck, 1, r, pk);
4523 } else {
4524 passC.push_back(ck);
4525 passP.push_back(pk);
4526 }
4527 }
4528 return;
4529 }
4530 if (nbuf[r - 1] > 0) {
4531 add_visit(pi, B, c, p, r, nbuf, prob);
4532 } else {
4533 passC.push_back(c);
4534 passP.push_back(prob);
4535 }
4536}
4537
4538template <class T>
4539void walk(const PollingInfo<T>& pi, PollingAdvance<T>& B, std::vector<long> c, const std::vector<long>& nbuf,
4540 std::size_t p, bool arrived, std::size_t steps_left, T prob, std::size_t startpos) {
4541 if (arrived) {
4542 std::vector<std::vector<long>> passC;
4543 std::vector<T> passP;
4544 arrive_at(pi, B, c, nbuf, p, prob, passC, passP);
4545 for (std::size_t b = 0; b < passC.size(); ++b)
4546 walk(pi, B, passC[b], nbuf, p, false, steps_left, passP[b], startpos);
4547 return;
4548 }
4549 if (steps_left == 0) {
4550 c[0] = static_cast<long>(startpos);
4551 add_row(B, c, 0, 0, prob);
4552 return;
4553 }
4554 const std::size_t p2 = p % pi.M + 1;
4555 if (!pi.polled[pi.ring[p2 - 1] - 1]) {
4556 walk(pi, B, c, nbuf, p2, false, steps_left - 1, prob, startpos);
4557 return;
4558 }
4559 if (pi.has_sw[p2 - 1]) {
4560 for (std::size_t k = 0; k < pi.ksw[p2 - 1]; ++k) {
4561 if (num_traits<T>::to_double(pi.sw_pie[p2 - 1][k]) <= 0) continue;
4562 std::vector<long> ck = c;
4563 ck[0] = static_cast<long>(p2);
4564 ck[1] = static_cast<long>(k + 1);
4565 add_row(B, ck, 2, 0, T(prob * pi.sw_pie[p2 - 1][k]));
4566 }
4567 return;
4568 }
4569 walk(pi, B, c, nbuf, p2, true, steps_left - 1, prob, startpos);
4570}
4571
4572} // namespace polling_detail
4573
4574/**
4575 * Port of `State.pollingAdvance`: every tangible controller configuration the
4576 * server reaches from `c` (pos = the position it LEAVES, or, with `arrived`,
4577 * the one it has just reached), with its probability.
4578 */
4579template <class T>
4580PollingAdvance<T> polling_advance(const PollingInfo<T>& pi, std::vector<long> c, const std::vector<long>& nbuf,
4581 bool arrived) {
4583 const T one = num_traits<T>::from_int(1);
4584 c[1] = 0;
4585 c[2] = 0; // the visit budget is reset with the walk
4586 c[3] = 0;
4587 c[4] = 0;
4588 if (pi.ld) {
4589 const std::size_t i = static_cast<std::size_t>(c[0]);
4590 if (arrived && nbuf[i - 1] > 0) {
4591 polling_detail::add_visit(pi, B, c, i, i, nbuf, one);
4592 return B;
4593 }
4594 const std::size_t j = polling_choose(pi, i, nbuf);
4595 if (j == 0) {
4596 polling_detail::add_row(B, c, 0, 0, one); // wait at the buffer just left
4597 } else if (j == i || !pi.has_sw[i - 1]) {
4598 polling_detail::add_visit(pi, B, c, j, j, nbuf, one);
4599 } else {
4600 for (std::size_t k = 0; k < pi.ksw[i - 1]; ++k) {
4601 if (num_traits<T>::to_double(pi.sw_pie[i - 1][k]) <= 0) continue;
4602 std::vector<long> ck = c;
4603 ck[0] = static_cast<long>(j);
4604 ck[1] = static_cast<long>(k + 1);
4605 ck[3] = static_cast<long>(i);
4606 polling_detail::add_row(B, ck, 2, 0, pi.sw_pie[i - 1][k]);
4607 }
4608 }
4609 return B;
4610 }
4611 const std::size_t p = static_cast<std::size_t>(c[0]);
4612 polling_detail::walk(pi, B, c, nbuf, p, arrived, pi.M, one, p);
4613 return B;
4614}
4615
4616/** Port of `State.pollingLandAll`: the state rows the advance outcomes land in. */
4617template <class T>
4618void polling_land_all(const NetworkStruct<T>& sn, std::size_t ist, const PollingInfo<T>& pi,
4619 const PollingAdvance<T>& B, const std::vector<T>& buf, const std::vector<T>& srv,
4620 const std::vector<T>& var, const RowLayout<T>& L, std::vector<std::vector<T>>& rows,
4621 std::vector<T>& probs, std::vector<std::size_t>& starts) {
4622 const T one = num_traits<T>::from_int(1);
4623 for (std::size_t b = 0; b < B.mode.size(); ++b) {
4624 const std::vector<T> v2 = polling_set_full(pi, var, B.C[b]);
4625 if (B.mode[b] == 1) {
4626 const std::size_t q = B.q[b];
4627 std::vector<T> b2 = buf;
4628 b2[q - 1] -= one;
4629 const std::vector<T> pentry = entry_phase_dist(sn, ist, q);
4630 for (std::size_t ke = 0; ke < L.K[q - 1]; ++ke) {
4631 if (num_traits<T>::to_double(pentry[ke]) <= 0) continue;
4632 std::vector<T> s2 = srv;
4633 s2[L.Ks[q - 1] + ke] += one;
4634 std::vector<T> row = b2;
4635 row.insert(row.end(), s2.begin(), s2.end());
4636 row.insert(row.end(), v2.begin(), v2.end());
4637 rows.push_back(row);
4638 probs.push_back(T(B.prob[b] * pentry[ke]));
4639 starts.push_back(q);
4640 }
4641 } else {
4642 std::vector<T> row = buf;
4643 row.insert(row.end(), srv.begin(), srv.end());
4644 row.insert(row.end(), v2.begin(), v2.end());
4645 rows.push_back(row);
4646 probs.push_back(B.prob[b]);
4647 starts.push_back(0);
4648 }
4649 }
4650}
4651
4652/**
4653 * Port of the SWITCH branch: a polling server advances its switchover timer.
4654 *
4655 * Unlike PHASE, which carries only the internal transitions of a phase-type and
4656 * leaves the absorption to DEP, this event carries BOTH -- a completed
4657 * switchover moves no job, so there is no departure to attach the absorption
4658 * to. It is therefore emitted even for a single-phase switchover, where it
4659 * consists of the absorption alone.
4660 */
4661template <class T>
4663 const std::vector<T>& inspace, std::size_t cls) {
4664 const std::size_t R = sn.nclasses;
4665 const std::size_t ist = sn.nodes[ind - 1].station;
4666 const T one = num_traits<T>::from_int(1);
4667 EventOutcome<T> out;
4668 if (ist == 0) throw InputError("after_event_station_switch: node is not a station");
4669 const PollingInfo<T> pinfo = polling_info(sn, ind);
4670 polling_require_ph(pinfo);
4671 if (!pinfo.valid || !pinfo.swclass[cls - 1]) return out;
4672 const RowLayout<T> L = row_layout(sn, ind, inspace.size());
4673
4674 const std::vector<T> buf(inspace.begin(), inspace.begin() + L.bufw);
4675 const std::vector<T> srv(inspace.begin() + L.bufw, inspace.begin() + L.bufw + L.srvw);
4676 const std::vector<T> var(inspace.begin() + L.bufw + L.srvw, inspace.end());
4677 std::size_t srvclass = 0;
4678 for (std::size_t r = 1; r <= R && srvclass == 0; ++r)
4679 for (std::size_t p = 0; p < L.K[r - 1]; ++p)
4680 if (num_traits<T>::to_double(srv[L.Ks[r - 1] + p]) > 0) {
4681 srvclass = r;
4682 break;
4683 }
4684 const std::vector<long> cS = polling_get_full(pinfo, var, srvclass);
4685 std::vector<long> nbuf(R, 0);
4686 for (std::size_t r = 0; r < R && r < L.bufw; ++r)
4687 nbuf[r] = static_cast<long>(num_traits<T>::to_double(buf[r]));
4688 auto emit = [&](const std::vector<T>& b, const std::vector<T>& sv, const std::vector<long>& c, T rate) {
4689 const std::vector<T> v2 = polling_set_full(pinfo, var, c);
4690 std::vector<T> row = b;
4691 row.insert(row.end(), sv.begin(), sv.end());
4692 row.insert(row.end(), v2.begin(), v2.end());
4693 out.space.push_back(row);
4694 out.rate.push_back(rate);
4695 out.prob.push_back(one);
4696 tag_last(out, 0, 0);
4697 };
4698
4699 // (a) The switchover the server is walking, when it leads to `cls`.
4700 if (srvclass == 0 && cS[1] > 0) {
4701 const std::size_t dest = pinfo.ld ? static_cast<std::size_t>(cS[0]) : pinfo.ring[cS[0] - 1];
4702 const std::size_t law = pinfo.ld ? static_cast<std::size_t>(cS[3]) : static_cast<std::size_t>(cS[0]);
4703 if (dest == cls) {
4704 const std::size_t swk = static_cast<std::size_t>(cS[1]);
4705 const Matrix<T>& D0 = pinfo.sw_d0[law - 1];
4706 const Matrix<T>& D1 = pinfo.sw_d1[law - 1];
4707 for (std::size_t kd = 0; kd < pinfo.ksw[law - 1]; ++kd) {
4708 if (kd + 1 == swk) continue;
4709 if (num_traits<T>::to_double(D0(swk - 1, kd)) <= 0) continue;
4710 std::vector<long> cK = cS;
4711 cK[1] = static_cast<long>(kd + 1);
4712 emit(buf, srv, cK, D0(swk - 1, kd));
4713 }
4714 T rate = num_traits<T>::from_int(0);
4715 for (std::size_t kd = 0; kd < pinfo.ksw[law - 1]; ++kd) rate += D1(swk - 1, kd);
4716 if (num_traits<T>::to_double(rate) > 0) {
4717 const PollingAdvance<T> BS = polling_advance(pinfo, cS, nbuf, true);
4718 std::vector<std::vector<T>> rows;
4719 std::vector<T> probs;
4720 std::vector<std::size_t> starts;
4721 polling_land_all(sn, ist, pinfo, BS, buf, srv, var, L, rows, probs, starts);
4722 for (std::size_t j = 0; j < rows.size(); ++j) {
4723 // A leg re-entering the same phase of the same switchover
4724 // lands in the departure state: a self-loop, not a transition.
4725 if (rows[j] == inspace) continue;
4726 out.space.push_back(rows[j]);
4727 out.rate.push_back(T(rate * probs[j]));
4728 out.prob.push_back(one);
4729 tag_last(out, starts[j], 0);
4730 }
4731 }
4732 }
4733 }
4734
4735 // (b) The visit timer of the class in service.
4736 if (pinfo.tmode != lang::PollingTimer::NONE && srvclass == cls && cS[4] > 0) {
4737 const std::size_t tht = static_cast<std::size_t>(cS[4]);
4738 const Matrix<T>& D0 = pinfo.t_d0[cls - 1];
4739 const Matrix<T>& D1 = pinfo.t_d1[cls - 1];
4740 for (std::size_t kd = 0; kd < pinfo.tk[cls - 1]; ++kd) {
4741 if (kd + 1 == tht) continue;
4742 if (num_traits<T>::to_double(D0(tht - 1, kd)) <= 0) continue;
4743 std::vector<long> cK = cS;
4744 cK[4] = static_cast<long>(kd + 1);
4745 emit(buf, srv, cK, D0(tht - 1, kd));
4746 }
4747 T rate = num_traits<T>::from_int(0);
4748 for (std::size_t kd = 0; kd < pinfo.tk[cls - 1]; ++kd) rate += D1(tht - 1, kd);
4749 if (num_traits<T>::to_double(rate) > 0) {
4750 std::vector<long> cX = cS;
4751 cX[4] = 0;
4752 if (!pinfo.tpreempt) {
4753 emit(buf, srv, cX, rate);
4754 } else {
4755 // The job in service returns to its buffer and the server moves on.
4756 std::vector<T> srvX = srv;
4757 for (std::size_t p = 0; p < L.K[cls - 1]; ++p) srvX[L.Ks[cls - 1] + p] = num_traits<T>::from_int(0);
4758 std::vector<T> bufX = buf;
4759 bufX[cls - 1] += one;
4760 std::vector<long> nbufX = nbuf;
4761 nbufX[cls - 1] += 1;
4762 const PollingAdvance<T> BX = polling_advance(pinfo, cX, nbufX, false);
4763 std::vector<std::vector<T>> rows;
4764 std::vector<T> probs;
4765 std::vector<std::size_t> starts;
4766 polling_land_all(sn, ist, pinfo, BX, bufX, srvX, var, L, rows, probs, starts);
4767 for (std::size_t j = 0; j < rows.size(); ++j) {
4768 out.space.push_back(rows[j]);
4769 out.rate.push_back(T(rate * probs[j]));
4770 out.prob.push_back(one);
4771 tag_last(out, starts[j], cls);
4772 }
4773 }
4774 }
4775 }
4776
4777 // (c) The target rotation timer of `cls` under a timed token.
4778 if (pinfo.tmode == lang::PollingTimer::GLOBAL && cS[5 + cls - 1] > 0) {
4779 const std::size_t trt = static_cast<std::size_t>(cS[5 + cls - 1]);
4780 const Matrix<T>& D0 = pinfo.t_d0[cls - 1];
4781 const Matrix<T>& D1 = pinfo.t_d1[cls - 1];
4782 for (std::size_t kd = 0; kd < pinfo.tk[cls - 1]; ++kd) {
4783 if (kd + 1 == trt) continue;
4784 if (num_traits<T>::to_double(D0(trt - 1, kd)) <= 0) continue;
4785 std::vector<long> cK = cS;
4786 cK[5 + cls - 1] = static_cast<long>(kd + 1);
4787 emit(buf, srv, cK, D0(trt - 1, kd));
4788 }
4789 T rate = num_traits<T>::from_int(0);
4790 for (std::size_t kd = 0; kd < pinfo.tk[cls - 1]; ++kd) rate += D1(trt - 1, kd);
4791 if (num_traits<T>::to_double(rate) > 0) {
4792 std::vector<long> cK = cS;
4793 cK[5 + cls - 1] = 0; // the token will be late at `cls`
4794 emit(buf, srv, cK, rate);
4795 }
4796 }
4797 pad_tags(out);
4798 return out;
4799}
4800
4801
4802/**
4803 * Port of `State.afterEventCache`: events at a Cache node.
4804 *
4805 * A Cache is stateful but is NOT a station, so its row is [per-class counts |
4806 * cache contents | retrieval bitmap] with no buffer or server block. The
4807 * contents region holds one column per cached slot, laid out list by list;
4808 * `cpos(i,j)` is position j of list i.
4809 *
4810 * A READ is INSTANTANEOUS: every branch fires at `GlobalConstants::Immediate`,
4811 * because the read is a routing decision rather than a service. The job enters
4812 * in its read class and leaves in the hit or miss class, so the transition
4813 * both moves the job between classes and rewrites the cache contents.
4814 */
4815template <class T>
4817 const std::vector<T>& inspace, EventType event,
4818 std::size_t cls) {
4819 const std::size_t R = sn.nclasses;
4820 const T one = num_traits<T>::from_int(1), zero = num_traits<T>::from_int(0);
4822 EventOutcome<T> out;
4823 const typename std::map<std::size_t, CacheParam<T>>::const_iterator ci = sn.nodeparam.find(ind);
4824 if (ci == sn.nodeparam.end()) throw InputError("after_event_cache: node has no CacheParam");
4825 const CacheParam<T>& cp = ci->second;
4826 const std::size_t h = cp.itemcap.size();
4827 const std::size_t n = cp.nitems;
4828 std::size_t tcc = 0; // total cache capacity, the width of the contents region
4829 for (std::size_t i = 0; i < h; ++i)
4830 if (cp.itemcap[i] > 0) tcc += static_cast<std::size_t>(cp.itemcap[i]);
4831 // cpos(i,j): position j (1-based) of list i (1-based) in the contents region.
4832 const std::vector<int>& m = cp.itemcap;
4833 struct Cpos {
4834 const std::vector<int>& m;
4835 std::size_t operator()(std::size_t i, std::size_t j) const {
4836 std::size_t base = 0;
4837 for (std::size_t t = 0; t + 1 < i; ++t) base += static_cast<std::size_t>(m[t]);
4838 return base + j - 1;
4839 }
4840 } cpos{m};
4841
4842 std::vector<T> srv(inspace.begin(), inspace.begin() + R);
4843 std::vector<T> var(inspace.begin() + R, inspace.end());
4844
4845 if (event == EventType::ARV) {
4846 srv[cls - 1] += one;
4847 std::vector<T> row = srv;
4848 row.insert(row.end(), var.begin(), var.end());
4849 out.space.push_back(row);
4850 out.rate.push_back(num_traits<T>::from_int(-1)); // passive
4851 out.prob.push_back(one);
4852 return out;
4853 }
4854
4855 if (event == EventType::DEP) {
4856 if (num_traits<T>::to_double(srv[cls - 1]) <= 0) return out;
4857 // A retrieval-class job departs the cache only to BEGIN a retrieval
4858 // (cache -> queue). Nothing in the cache state separates such an outbound job
4859 // from an inbound one, back from the retrieval stations and due to complete its
4860 // fetch on the next READ: both sit in the same per-class server slot. Left
4861 // ambiguous, the DEP and the READ syncs are both enabled and, both being
4862 // immediate, split the probability evenly, so a fetch spans a Geom(1/2) number
4863 // of station visits. Its mean is unchanged (E[N]=1), but its second moment gains
4864 // 2*E0[F]^2 and with it the delayed-hit queue length
4865 // d_i = phi_i lambda_i E0[F_i^2]/(2 E0[F_i]), which for an exponential fetch
4866 // comes out exactly twice too large. The per-item in-flight bit resolves the
4867 // ambiguity: the outbound departure below sets it and the READ that completes
4868 // the fetch clears it, so an outbound job (bit clear) may depart, while an
4869 // inbound one (bit set) may not and is left with its READ as the only action.
4870 // The block lifts as soon as another job shares the cache server, because the
4871 // READ cannot fire then either (it requires exactly one job present) and the
4872 // departure is the only way out of the state.
4873 if (cp.retrieval_capacity > 0 && !cp.retrieval_classes.empty()) {
4874 std::size_t item_dep = 0;
4875 for (std::size_t i = 0; i < cp.retrieval_classes.size() && item_dep == 0; ++i)
4876 for (std::size_t c = 0; c < cp.retrieval_classes[i].size(); ++c)
4877 if (cp.retrieval_classes[i][c] == cls) {
4878 item_dep = i + 1;
4879 break;
4880 }
4881 if (item_dep != 0) {
4882 const std::size_t bitcol = tcc + item_dep - 1;
4883 if (bitcol < var.size()) {
4884 if (num_traits<T>::to_double(var[bitcol]) != 0) {
4885 double srvtot = 0;
4886 for (std::size_t r = 0; r < R; ++r)
4887 srvtot += num_traits<T>::to_double(srv[r]);
4888 if (srvtot == 1) return out; // inbound: only its READ is enabled
4889 } else {
4890 var[bitcol] = one;
4891 }
4892 }
4893 } else {
4894 // A read class that owns retrieval classes always switches at the READ,
4895 // into a hit, a miss or a retrieval class; its cache -> station routing
4896 // exists only so that the retrieval classes can inherit it, and must
4897 // never carry the reading job itself out of the cache unread.
4898 bool owns = false;
4899 for (std::size_t i = 0; i < cp.retrieval_classes.size(); ++i)
4900 if (cls - 1 < cp.retrieval_classes[i].size() &&
4901 cp.retrieval_classes[i][cls - 1] != 0) {
4902 owns = true;
4903 break;
4904 }
4905 if (owns) {
4906 const std::size_t hc =
4907 cls - 1 < cp.hitclass.size() ? static_cast<std::size_t>(cp.hitclass[cls - 1]) : 0;
4908 const std::size_t mc =
4909 cls - 1 < cp.missclass.size() ? static_cast<std::size_t>(cp.missclass[cls - 1]) : 0;
4910 if (hc != cls && mc != cls) return out;
4911 }
4912 }
4913 }
4914 srv[cls - 1] -= one;
4915 std::vector<T> row = srv;
4916 row.insert(row.end(), var.begin(), var.end());
4917 out.space.push_back(row);
4918 out.rate.push_back(imm); // the departure is instantaneous
4919 out.prob.push_back(one);
4920 return out;
4921 }
4922
4923 if (event != EventType::READ) return out;
4924
4925 // A READ needs exactly one job present, and it must be of the reading class.
4926 double tot = 0;
4927 for (std::size_t r = 0; r < R; ++r) tot += num_traits<T>::to_double(srv[r]);
4928 if (num_traits<T>::to_double(srv[cls - 1]) <= 0 || tot != 1) return out;
4929 if (cls - 1 >= cp.pread.size() || cp.pread[cls - 1].empty()) return out;
4930 const std::vector<T>& p = cp.pread[cls - 1];
4931
4932 // The delayed-hit retrieval system. Block A (n columns) marks the items in
4933 // flight; block B (one column per retrieval class) counts the secondary
4934 // requests merged onto those fetches. Its width is read off the row rather
4935 // than off the parameters, because a struct whose space predates the block
4936 // still has to be walkable.
4937 const bool retr = cp.retrieval_capacity > 0 && !cp.retrieval_classes.empty();
4938 std::vector<std::size_t> rc_list, rc_items, rc_orig;
4939 if (retr) cache_retrieval_class_map(cp, rc_list, rc_items, rc_orig);
4940 const std::size_t block_b = tcc + n;
4941 std::size_t width_b = var.size() > block_b ? var.size() - block_b : 0;
4942 if (width_b != rc_list.size()) width_b = 0;
4943 // -1 is the sample path's unbounded merge; an exact solver enumerates block
4944 // B only up to the level it declared, and a merge past that level is refused
4945 // rather than folded into a state the space does not hold.
4946 const double maxpend = cp.max_pending_retrieval < 0
4947 ? std::numeric_limits<double>::infinity()
4948 : static_cast<double>(cp.max_pending_retrieval);
4949 bool from_retrieval = false;
4950 for (std::size_t j = 0; j < rc_list.size(); ++j)
4951 if (rc_list[j] == cls) from_retrieval = true;
4952
4953 for (std::size_t k = 1; k <= n; ++k) {
4954 if (k - 1 >= p.size() || num_traits<T>::to_double(p[k - 1]) <= 0) continue;
4955 std::vector<T> srv_e = srv;
4956 srv_e[cls - 1] -= one;
4957 // The item is searched ONLY in the contents region; the trailing
4958 // retrieval slots are a different namespace.
4959 std::size_t posk = 0;
4960 for (std::size_t c = 0; c < tcc && c < var.size(); ++c)
4961 if (static_cast<std::size_t>(num_traits<T>::to_double(var[c])) == k) {
4962 posk = c + 1;
4963 break;
4964 }
4965 // A RETURNING RETRIEVAL always completes the miss that started it, so it
4966 // takes the miss branch even where the enumeration produced a (then
4967 // unreachable) state holding item k. A retrieval class has no hit class
4968 // to switch into either.
4969 if (from_retrieval) posk = 0;
4970 const Matrix<T>& ac = cp.accost.empty() || cls - 1 >= cp.accost.size() ||
4971 k - 1 >= cp.accost[cls - 1].size()
4972 ? Matrix<T>()
4973 : cp.accost[cls - 1][k - 1];
4974 const bool have_ac = ac.rows() >= h + 1 && ac.cols() >= h + 1;
4975
4976 if (posk == 0) {
4977 // CACHE MISS, or one leg of a retrieval. A fetch is in flight iff
4978 // block A's bit for item k is set.
4979 const bool in_flight =
4980 retr && tcc + k <= var.size() && num_traits<T>::to_double(var[tcc + k - 1]) != 0;
4981 std::size_t r_class = 0;
4982 if (retr && k - 1 < cp.retrieval_classes.size() &&
4983 cls - 1 < cp.retrieval_classes[k - 1].size())
4984 r_class = cp.retrieval_classes[k - 1][cls - 1];
4985 // A retrieval-class job whose item is not recorded in the bitmap is
4986 // outbound: it has not reached the retrieval stations yet, so it has no
4987 // fetch to complete and only its departure is enabled.
4988 if (from_retrieval && !in_flight) continue;
4989
4990 if (!from_retrieval && r_class != 0) {
4991 // BEGIN a fetch, or MERGE onto one already running. The merge is
4992 // the delayed hit: it adds nothing to the cache's server block,
4993 // and is held in block B until the fetch completes and releases
4994 // it in the hit class of the class that issued it.
4995 std::vector<T> srv_b = srv_e;
4996 std::vector<T> var_b = var;
4997 if (!in_flight) {
4998 // The job switches to item k's retrieval class and waits in the cache
4999 // server for the departure that carries it to the retrieval stations.
5000 // That departure, not this READ, sets the in-flight bit, so that an
5001 // outbound retrieval job (bit clear) is distinguishable from an
5002 // inbound one (bit set); see the DEP branch above.
5003 srv_b[r_class - 1] += one;
5004 } else {
5005 if (width_b == 0) continue;
5006 std::size_t bslot = width_b;
5007 for (std::size_t j = 0; j < rc_list.size(); ++j)
5008 if (rc_list[j] == r_class) { bslot = j; break; }
5009 if (bslot >= width_b) continue;
5010 double pend = 0;
5011 for (std::size_t j = 0; j < width_b; ++j)
5012 pend += num_traits<T>::to_double(var_b[block_b + j]);
5013 if (pend >= maxpend) continue; // beyond the truncation level
5014 var_b[block_b + bslot] += one;
5015 }
5016 std::vector<T> row = srv_b;
5017 row.insert(row.end(), var_b.begin(), var_b.end());
5018 out.space.push_back(row);
5019 out.rate.push_back(T(p[k - 1] * imm));
5020 out.prob.push_back(one);
5021 continue;
5022 }
5023
5024 // The fetch is complete (or there is no retrieval system): the job
5025 // leaves in the miss class, the item may be admitted into one of the
5026 // lists, and every request merged onto this fetch is released in the
5027 // SAME transition as a delayed hit.
5028 if (cls - 1 >= cp.missclass.size() || cp.missclass[cls - 1] == 0) continue;
5029 std::vector<T> srv_m = srv_e;
5030 srv_m[cp.missclass[cls - 1] - 1] += one;
5031 std::vector<T> var_m = var;
5032 if (tcc + k <= var_m.size()) var_m[tcc + k - 1] = zero; // retrieval done
5033 for (std::size_t j = 0; j < width_b; ++j) {
5034 if (rc_items[j] != k) continue;
5035 const double held = num_traits<T>::to_double(var_m[block_b + j]);
5036 if (held <= 0) continue;
5037 const std::size_t oc = rc_orig[j];
5038 if (oc - 1 >= cp.hitclass.size() || cp.hitclass[oc - 1] == 0) continue;
5039 srv_m[cp.hitclass[oc - 1] - 1] += var_m[block_b + j];
5040 var_m[block_b + j] = zero;
5041 }
5042
5043 // Column 1 of the access cost is the REJECT branch: the item passes
5044 // through without being cached at all.
5045 const T rej = have_ac ? ac(0, 0) : zero;
5046 if (num_traits<T>::to_double(rej) > 0) {
5047 std::vector<T> row = srv_m;
5048 row.insert(row.end(), var_m.begin(), var_m.end());
5049 out.space.push_back(row);
5050 out.rate.push_back(T(rej * p[k - 1] * imm));
5051 out.prob.push_back(one);
5052 }
5053 for (std::size_t l = 1; l <= h; ++l) {
5054 const T w = have_ac ? ac(0, l) : (l == 1 ? one : zero);
5055 if (num_traits<T>::to_double(w) <= 0) continue;
5056 if (m[l - 1] <= 0) continue;
5057 const std::size_t ml = static_cast<std::size_t>(m[l - 1]);
5059 // Random replacement: the item lands uniformly in any slot.
5060 for (std::size_t rr = 1; rr <= ml; ++rr) {
5061 std::vector<T> vp = var_m;
5062 vp[cpos(l, rr)] = num_traits<T>::from_int(static_cast<long>(k));
5063 std::vector<T> row = srv_m;
5064 row.insert(row.end(), vp.begin(), vp.end());
5065 out.space.push_back(row);
5066 out.rate.push_back(T(w * p[k - 1] /
5067 num_traits<T>::from_int(static_cast<long>(ml)) * imm));
5068 out.prob.push_back(one);
5069 }
5070 } else {
5071 // The ordered families insert at the HEAD, shifting the list
5072 // down by one and evicting its tail.
5073 std::vector<T> vp = var_m;
5074 for (std::size_t j = ml; j >= 2; --j) vp[cpos(l, j)] = var_m[cpos(l, j - 1)];
5075 vp[cpos(l, 1)] = num_traits<T>::from_int(static_cast<long>(k));
5076 T rate = T(w * p[k - 1] * imm);
5077 // q-LRU admits a miss only with probability q; the rest
5078 // passes through uncached.
5080 const T q = cp.qlru;
5081 if (num_traits<T>::to_double(q) < 1) {
5082 std::vector<T> row0 = srv_m;
5083 row0.insert(row0.end(), var_m.begin(), var_m.end());
5084 out.space.push_back(row0);
5085 out.rate.push_back(T(rate * T(one - q)));
5086 out.prob.push_back(one);
5087 }
5088 rate = T(rate * q);
5089 }
5090 if (num_traits<T>::to_double(rate) <= 0) continue;
5091 std::vector<T> row = srv_m;
5092 row.insert(row.end(), vp.begin(), vp.end());
5093 out.space.push_back(row);
5094 out.rate.push_back(rate);
5095 out.prob.push_back(one);
5096 }
5097 }
5098 } else {
5099 // CACHE HIT: the job leaves in the hit class. Which list it was
5100 // found in decides how the contents move.
5101 if (cls - 1 >= cp.hitclass.size() || cp.hitclass[cls - 1] == 0) continue;
5102 std::vector<T> srv_h = srv_e;
5103 srv_h[cp.hitclass[cls - 1] - 1] += one;
5104 std::size_t li = 1, acc = 0;
5105 for (std::size_t t = 0; t < h; ++t) {
5106 const std::size_t mt = m[t] > 0 ? static_cast<std::size_t>(m[t]) : 0;
5107 if (posk <= acc + mt) { li = t + 1; break; }
5108 acc += mt;
5109 }
5110 const std::size_t j = posk - acc;
5111 if (li < h) {
5112 // A HIT BELOW THE TERMINAL LIST PROMOTES, and that is what makes
5113 // an h-list cache more than h caches side by side. Row `li` of
5114 // the access cost routes the item from list li into list
5115 // inew >= li, exactly as `afterEventCache.m` does over `inew =
5116 // i:h`; an empty accost is the reference default
5117 // `diag(ones(1,h),1)` with a 1 in the bottom-right, the linear
5118 // cache that moves the item one list up. Omitting this branch
5119 // froze every list above the first at its initial contents: on
5120 // m=[2,1] only 12 of the 60 configurations stayed reachable, and
5121 // the CTMC hit ratio of cache_compare_replc came out 4.9% low.
5122 for (std::size_t inew = li; inew <= h; ++inew) {
5123 if (m[inew - 1] <= 0) continue;
5124 const std::size_t mn = static_cast<std::size_t>(m[inew - 1]);
5125 const T w = have_ac ? ac(li, inew) : (inew == li + 1 ? one : zero);
5126 if (num_traits<T>::to_double(w) <= 0) continue;
5127 if (inew == li) {
5128 // A hit that stays in list li is a leaf hit (Gast-Van Houdt, QUESTA 2016): the LRU family
5129 // moves the item to the head of list li, while FIFO, strict FIFO and RR change nothing.
5130 std::vector<T> vp = var;
5131 const bool lru = cp.replacestrat != lang::ReplacementStrategy::RR &&
5134 if (lru) {
5135 for (std::size_t t = j; t >= 2; --t) vp[cpos(li, t)] = var[cpos(li, t - 1)];
5136 vp[cpos(li, 1)] = var[cpos(li, j)];
5137 }
5138 std::vector<T> row = srv_h;
5139 row.insert(row.end(), vp.begin(), vp.end());
5140 out.space.push_back(row);
5141 out.rate.push_back(T(w * p[k - 1] * imm));
5142 out.prob.push_back(one);
5143 continue;
5144 }
5146 // Random replacement swaps with a uniformly drawn slot.
5147 for (std::size_t r = 1; r <= mn; ++r) {
5148 std::vector<T> vp = var;
5149 vp[cpos(li, j)] = var[cpos(inew, r)];
5150 vp[cpos(inew, r)] = num_traits<T>::from_int(static_cast<long>(k));
5151 std::vector<T> row = srv_h;
5152 row.insert(row.end(), vp.begin(), vp.end());
5153 out.space.push_back(row);
5154 out.rate.push_back(
5155 T(w * p[k - 1] /
5156 num_traits<T>::from_int(static_cast<long>(mn)) * imm));
5157 out.prob.push_back(one);
5158 }
5159 continue;
5160 }
5161 // Every read below is of the UNMODIFIED row; inew > li here, so
5162 // the source and target lists are distinct.
5163 std::vector<T> vp = var;
5164 // The LRU family closes the gap in list li; FIFO orders by
5165 // insertion and so leaves list li otherwise untouched.
5166 const bool ordered = cp.replacestrat != lang::ReplacementStrategy::FIFO;
5167 if (ordered)
5168 for (std::size_t t = j; t >= 2; --t) vp[cpos(li, t)] = var[cpos(li, t - 1)];
5169 // The tail evicted from the target list takes the slot the
5170 // promoted item vacated.
5171 vp[cpos(li, ordered ? 1 : j)] = var[cpos(inew, mn)];
5172 for (std::size_t t = mn; t >= 2; --t) vp[cpos(inew, t)] = var[cpos(inew, t - 1)];
5173 vp[cpos(inew, 1)] = num_traits<T>::from_int(static_cast<long>(k));
5174 std::vector<T> row = srv_h;
5175 row.insert(row.end(), vp.begin(), vp.end());
5176 out.space.push_back(row);
5177 out.rate.push_back(T(w * p[k - 1] * imm));
5178 out.prob.push_back(one);
5179 }
5183 // A hit in the terminal list does not reorder these: FIFO orders
5184 // by INSERTION, and random replacement has no order to disturb.
5185 std::vector<T> row = srv_h;
5186 row.insert(row.end(), var.begin(), var.end());
5187 out.space.push_back(row);
5188 out.rate.push_back(T(p[k - 1] * imm));
5189 out.prob.push_back(one);
5190 } else {
5191 // LRU and its relatives promote the hit item to the head of its
5192 // list, which is the whole content of "recently used".
5193 std::vector<T> vp = var;
5194 for (std::size_t t = j; t >= 2; --t) vp[cpos(li, t)] = var[cpos(li, t - 1)];
5195 vp[cpos(li, 1)] = var[cpos(li, j)];
5196 std::vector<T> row = srv_h;
5197 row.insert(row.end(), vp.begin(), vp.end());
5198 out.space.push_back(row);
5199 out.rate.push_back(T(p[k - 1] * imm));
5200 out.prob.push_back(one);
5201 }
5202 }
5203 }
5204 return out;
5205}
5206
5207
5208/** One half of a GLOBAL synchronization: a mode event at a node. */
5209template <class T>
5211 EventType event = EventType::LOCAL;
5212 std::size_t node = 0; ///< 1-based node index (a Transition, or a place)
5213 std::size_t mode = 0; ///< 1-based mode index
5214 std::size_t cls = 1; ///< 1-based class the arc moves
5215 T weight = num_traits<T>::from_int(1); ///< arc multiplicity
5216};
5217
5218/**
5219 * A GLOBAL synchronization: an SPN mode event and the place arcs it drives.
5220 *
5221 * Unlike an ordinary Sync, which pairs ONE active with ONE passive, a firing
5222 * touches every input and output place at once -- that atomicity is what makes
5223 * a Petri net transition a transition. PRE passives consume, POST produce, and
5224 * LOCAL passives are read-only (an inhibitor place, whose marking is tested but
5225 * never moved).
5226 */
5227template <class T>
5230 std::vector<ModeEvent<T>> passive;
5231};
5232
5233/**
5234 * Port of `MNetwork.refreshGlobalSync`: the ENABLE and FIRE synchronizations.
5235 *
5236 * An inhibiting place enters as a LOCAL passive rather than a PRE, and only
5237 * when it is not already an enabling or firing place: its marking is read for
5238 * the inhibition test but no token crosses the arc.
5239 */
5240template <class T>
5241std::vector<GlobalSync<T>> refresh_global_sync(const NetworkStruct<T>& sn) {
5242 std::vector<GlobalSync<T>> gsync;
5243 const T one = num_traits<T>::from_int(1);
5244 for (std::size_t ind = 1; ind <= sn.nodes.size(); ++ind) {
5245 if (sn.nodes[ind - 1].nodetype != NodeType::Transition) continue;
5246 const typename std::map<std::size_t, TransitionParam<T>>::const_iterator it =
5247 sn.transparam.find(ind);
5248 if (it == sn.transparam.end()) continue;
5249 const TransitionParam<T>& tp = it->second;
5250 for (int pass = 0; pass < 2; ++pass) {
5251 for (std::size_t m = 1; m <= tp.nmodes; ++m) {
5252 // ONE ENTRY PER (place, class) ARC, which is what makes a
5253 // multiclass net a different net from the class-summed one: a
5254 // Class2 token at a place must not satisfy a Class1 pre-arc, so
5255 // the pair travels into the passive rather than the place alone.
5256 std::vector<std::pair<std::size_t, std::size_t>> enab, fire, inhib;
5257 const Matrix<T>& en = tp.enabling[m - 1];
5258 const Matrix<T>& fi = tp.firing[m - 1];
5259 const Matrix<T>& ih = tp.inhibiting[m - 1];
5260 for (std::size_t q = 0; q < en.rows(); ++q)
5261 for (std::size_t r = 0; r < en.cols(); ++r)
5262 if (num_traits<T>::to_double(en(q, r)) > 0)
5263 enab.push_back(std::make_pair(q + 1, r + 1));
5264 for (std::size_t q = 0; q < fi.rows(); ++q)
5265 for (std::size_t r = 0; r < fi.cols(); ++r)
5266 if (num_traits<T>::to_double(fi(q, r)) > 0)
5267 fire.push_back(std::make_pair(q + 1, r + 1));
5268 for (std::size_t q = 0; q < ih.rows(); ++q)
5269 for (std::size_t r = 0; r < ih.cols(); ++r) {
5270 if (std::isinf(num_traits<T>::to_double(ih(q, r)))) continue;
5271 // The de-duplication is against the PLACE, not the
5272 // (place, class) pair: the passive's job is to bring the
5273 // place's marginal into the outcome, and one copy of a
5274 // place carries every class of it.
5275 bool dup = false;
5276 for (std::size_t i = 0; i < enab.size(); ++i)
5277 dup = dup || enab[i].first == q + 1;
5278 for (std::size_t i = 0; i < fire.size(); ++i)
5279 dup = dup || fire[i].first == q + 1;
5280 for (std::size_t i = 0; i < inhib.size(); ++i)
5281 dup = dup || inhib[i].first == q + 1;
5282 if (!dup) inhib.push_back(std::make_pair(q + 1, r + 1));
5283 }
5284 GlobalSync<T> g;
5285 g.active.event = pass == 0 ? EventType::ENABLE : EventType::FIRE;
5286 g.active.node = ind;
5287 g.active.mode = m;
5288 if (pass == 0) {
5289 // An ENABLE only READS the markings, so every passive is
5290 // LOCAL: enabling it is a test, not a token movement. One
5291 // per PLACE here, since a read of a place reads every class.
5292 std::vector<std::size_t> seen;
5293 auto once = [&](std::size_t q, std::size_t r) {
5294 for (std::size_t i = 0; i < seen.size(); ++i)
5295 if (seen[i] == q) return;
5296 seen.push_back(q);
5297 g.passive.push_back(ModeEvent<T>{EventType::LOCAL, q, m, r, one});
5298 };
5299 for (std::size_t i = 0; i < enab.size(); ++i) once(enab[i].first, enab[i].second);
5300 for (std::size_t i = 0; i < inhib.size(); ++i)
5301 once(inhib[i].first, inhib[i].second);
5302 } else {
5303 for (std::size_t i = 0; i < enab.size(); ++i)
5304 g.passive.push_back(ModeEvent<T>{EventType::PRE, enab[i].first, m,
5305 enab[i].second,
5306 en(enab[i].first - 1, enab[i].second - 1)});
5307 for (std::size_t i = 0; i < fire.size(); ++i)
5308 g.passive.push_back(ModeEvent<T>{EventType::POST, fire[i].first, m,
5309 fire[i].second,
5310 fi(fire[i].first - 1, fire[i].second - 1)});
5311 for (std::size_t i = 0; i < inhib.size(); ++i)
5312 g.passive.push_back(ModeEvent<T>{EventType::LOCAL, inhib[i].first, m,
5313 inhib[i].second, one});
5314 }
5315 gsync.push_back(g);
5316 }
5317 }
5318 }
5319 return gsync;
5320}
5321
5322/** What one global event produces: a whole network state per outcome. */
5323template <class T>
5325 std::vector<NetState<T>> space;
5326 std::vector<T> rate, prob;
5327 /**
5328 * True where the outcome is a firing COMPLETION, i.e. one that applied the
5329 * PRE/POST updates. Callers must NOT re-derive this from the markings: a
5330 * transition whose firing returns exactly what its enabling consumed
5331 * leaves every marking invariant yet still completed.
5332 */
5333 std::vector<bool> completion;
5334 bool empty() const { return space.empty(); }
5335};
5336
5337/**
5338 * Port of `State.afterGlobalEvent`: an SPN mode ENABLEs or FIREs.
5339 *
5340 * This is the one handler that rewrites SEVERAL nodes at once, because a
5341 * firing is atomic across all its arcs. The Transition's own row records how
5342 * many servers of each mode are idle, running (and in which firing phase), and
5343 * have just fired; the places are rewritten through the PRE and POST passives.
5344 */
5345template <class T>
5347 const GlobalSync<T>& gl) {
5348 const std::size_t R = sn.nclasses;
5349 const std::size_t ind = gl.active.node;
5350 const std::size_t mode = gl.active.mode;
5351 const T one = num_traits<T>::from_int(1), zero = num_traits<T>::from_int(0);
5353 GlobalOutcome<T> out;
5354 const std::size_t isf = sn.stateful_index(ind);
5355 if (isf == 0) throw InputError("after_global_event: the transition is not stateful");
5356 const typename std::map<std::size_t, TransitionParam<T>>::const_iterator it =
5357 sn.transparam.find(ind);
5358 if (it == sn.transparam.end()) throw InputError("after_global_event: node has no TransitionParam");
5359 const TransitionParam<T>& tp = it->second;
5360
5361 std::vector<std::size_t> fK(tp.nmodes, 1), fKs(tp.nmodes, 0);
5362 std::size_t tot = 0;
5363 for (std::size_t m = 0; m < tp.nmodes; ++m) {
5364 fK[m] = m < tp.firingphases.size() && tp.firingphases[m] > 0 ? tp.firingphases[m] : 1;
5365 fKs[m] = tot;
5366 tot += fK[m];
5367 }
5368 const std::vector<T>& row = glspace.local[isf - 1];
5369 std::vector<T> buf(row.begin(), row.begin() + tp.nmodes);
5370 std::vector<T> srv(row.begin() + tp.nmodes, row.begin() + tp.nmodes + tot);
5371 std::vector<T> fired(row.begin() + tp.nmodes + tot,
5372 row.begin() + 2 * tp.nmodes + tot);
5373 const std::vector<T> var(row.begin() + 2 * tp.nmodes + tot, row.end());
5374
5375 // The marking of every place this mode reads, node-indexed.
5376 std::vector<std::vector<T>> ep(sn.nodes.size() + 1, std::vector<T>(R, zero));
5377 for (std::size_t j = 0; j < gl.passive.size(); ++j) {
5378 const std::size_t pn = gl.passive[j].node;
5379 const std::size_t pisf = sn.stateful_index(pn);
5380 if (pisf == 0) continue;
5381 const std::pair<T, std::vector<T>> mg = to_marginal_aggr(sn, pn, glspace.local[pisf - 1]);
5382 ep[pn] = mg.second;
5383 }
5384
5385 // The enabling DEGREE: how many concurrent firings the marking supports.
5386 // An inhibitor arc disables the mode outright once its threshold is met.
5387 //
5388 // EVERY TEST IS PER (place, class), the elementwise comparison
5389 // `afterGlobalEvent.m:85` makes against `enabling_m`. Summing the marking
5390 // over classes first, as this port did until 2026-08-12, let a Class2 token
5391 // satisfy a Class1 pre-arc: on a net where Mode1 needs two Class1 tokens at
5392 // P1 and Mode2 one Class2 token there, the summed test fires Mode1 off a
5393 // marking that holds no Class1 token at all.
5394 const Matrix<T>& en_m = tp.enabling[mode - 1];
5395 const Matrix<T>& ih_m = tp.inhibiting[mode - 1];
5396 bool inhibited = false;
5397 for (std::size_t q = 0; q < ih_m.rows(); ++q)
5398 for (std::size_t r = 0; r < ih_m.cols() && r < R; ++r) {
5399 const double thr = num_traits<T>::to_double(ih_m(q, r));
5400 if (std::isinf(thr)) continue;
5401 if (num_traits<T>::to_double(ep[q + 1][r]) >= thr) inhibited = true;
5402 }
5403 bool under = false;
5404 for (std::size_t q = 0; q < en_m.rows(); ++q)
5405 for (std::size_t r = 0; r < en_m.cols() && r < R; ++r) {
5406 const double need = num_traits<T>::to_double(en_m(q, r));
5407 if (need <= 0) continue;
5408 if (num_traits<T>::to_double(ep[q + 1][r]) < need) under = true;
5409 }
5410 long mark_degree = 0;
5411 if (!inhibited && !under) {
5412 long d = 1;
5413 for (;;) {
5414 bool ok = true;
5415 for (std::size_t q = 0; q < en_m.rows() && ok; ++q)
5416 for (std::size_t r = 0; r < en_m.cols() && r < R && ok; ++r) {
5417 const double need = num_traits<T>::to_double(en_m(q, r)) * d;
5418 if (need <= 0) continue;
5419 if (num_traits<T>::to_double(ep[q + 1][r]) < need) ok = false;
5420 }
5421 if (!ok) break;
5422 ++d;
5423 }
5424 mark_degree = d - 1;
5425 }
5426 const double svm = mode - 1 < tp.nmodeservers.size() ? tp.nmodeservers[mode - 1] : 1.0;
5427 const long nsrv = std::isfinite(svm) ? static_cast<long>(svm)
5428 : static_cast<long>(GlobalConstants::MaxInt);
5429
5430 if (gl.active.event == EventType::ENABLE) {
5431 long running = 0;
5432 for (std::size_t k = 0; k < fK[mode - 1]; ++k)
5433 running += static_cast<long>(num_traits<T>::to_double(srv[fKs[mode - 1] + k]));
5434 if (inhibited || under) {
5435 // Disabled: every server of this mode returns to the idle pool.
5436 std::vector<T> b2 = buf, s2 = srv;
5437 b2[mode - 1] = num_traits<T>::from_int(nsrv);
5438 for (std::size_t k = 0; k < fK[mode - 1]; ++k) s2[fKs[mode - 1] + k] = zero;
5439 std::vector<T> nr = b2;
5440 nr.insert(nr.end(), s2.begin(), s2.end());
5441 nr.insert(nr.end(), fired.begin(), fired.end());
5442 nr.insert(nr.end(), var.begin(), var.end());
5443 if (nr == row) return out; // already disabled: not a transition
5444 NetState<T> ns = glspace;
5445 ns.local[isf - 1] = nr;
5446 out.space.push_back(ns);
5447 out.rate.push_back(imm);
5448 out.prob.push_back(one);
5449 out.completion.push_back(false);
5450 return out;
5451 }
5452 const long want = std::min(mark_degree, nsrv);
5453 if (running == want) return out; // nothing to do
5454 if (running < want) {
5455 // Start servers, distributing them over the firing phases by the
5456 // entry law; the multinomial weight is the probability of that
5457 // split.
5458 const long nadd = want - running;
5459 std::vector<T> pe(fK[mode - 1], zero);
5460 if (mode - 1 < tp.firingproc.size() && tp.firingproc[mode - 1].D0.rows() ==
5461 static_cast<std::size_t>(fK[mode - 1])) {
5462 mam::Map<T> mp;
5463 mp.D0 = tp.firingproc[mode - 1].D0;
5464 mp.D1 = tp.firingproc[mode - 1].D1;
5465 const std::vector<T> pv = mam::map_pie(mp);
5466 for (std::size_t k = 0; k < fK[mode - 1]; ++k) pe[k] = pv[k];
5467 } else {
5468 pe[0] = one;
5469 }
5470 // Enumerate the splits of nadd over the phases.
5471 std::vector<std::vector<long>> combs;
5472 std::vector<long> cur(fK[mode - 1], 0);
5473 std::function<void(std::size_t, long)> rec = [&](std::size_t k, long left) {
5474 if (k + 1 == fK[mode - 1]) {
5475 cur[k] = left;
5476 combs.push_back(cur);
5477 return;
5478 }
5479 for (long v = left; v >= 0; --v) {
5480 cur[k] = v;
5481 rec(k + 1, left - v);
5482 }
5483 };
5484 rec(0, nadd);
5485 for (std::size_t i = 0; i < combs.size(); ++i) {
5486 std::vector<T> b2 = buf, s2 = srv;
5487 b2[mode - 1] -= num_traits<T>::from_int(nadd);
5488 double logp = std::lgamma(static_cast<double>(nadd) + 1.0);
5489 bool zeroprob = false;
5490 for (std::size_t k = 0; k < fK[mode - 1]; ++k) {
5491 s2[fKs[mode - 1] + k] += num_traits<T>::from_int(combs[i][k]);
5492 const double pk = num_traits<T>::to_double(pe[k]);
5493 if (pk > 0)
5494 logp += combs[i][k] * std::log(pk) -
5495 std::lgamma(static_cast<double>(combs[i][k]) + 1.0);
5496 else if (combs[i][k] > 0)
5497 zeroprob = true;
5498 }
5499 std::vector<T> nr = b2;
5500 nr.insert(nr.end(), s2.begin(), s2.end());
5501 nr.insert(nr.end(), fired.begin(), fired.end());
5502 nr.insert(nr.end(), var.begin(), var.end());
5503 NetState<T> ns = glspace;
5504 ns.local[isf - 1] = nr;
5505 out.space.push_back(ns);
5506 out.rate.push_back(imm);
5507 out.prob.push_back(zeroprob ? zero : num_traits<T>::from_double(std::exp(logp)));
5508 out.completion.push_back(false);
5509 }
5510 return out;
5511 }
5512 // Stop the surplus servers, chosen uniformly across the phases: the
5513 // weight is the multivariate hypergeometric probability of that choice.
5514 const long ndiff = running - want;
5515 std::vector<long> sv(fK[mode - 1], 0);
5516 for (std::size_t k = 0; k < fK[mode - 1]; ++k)
5517 sv[k] = static_cast<long>(num_traits<T>::to_double(srv[fKs[mode - 1] + k]));
5518 std::vector<std::vector<long>> combs;
5519 std::vector<long> cur(fK[mode - 1], 0);
5520 std::function<void(std::size_t, long)> rec = [&](std::size_t k, long left) {
5521 if (k + 1 == fK[mode - 1]) {
5522 if (left > sv[k]) return;
5523 cur[k] = left;
5524 combs.push_back(cur);
5525 return;
5526 }
5527 for (long v = std::min(left, sv[k]); v >= 0; --v) {
5528 cur[k] = v;
5529 rec(k + 1, left - v);
5530 }
5531 };
5532 rec(0, ndiff);
5533 std::vector<double> w(combs.size(), 0.0);
5534 double wmax = -1e300;
5535 for (std::size_t i = 0; i < combs.size(); ++i) {
5536 double lw = 0;
5537 for (std::size_t k = 0; k < fK[mode - 1]; ++k)
5538 lw += std::lgamma(static_cast<double>(sv[k]) + 1.0) -
5539 std::lgamma(static_cast<double>(combs[i][k]) + 1.0) -
5540 std::lgamma(static_cast<double>(sv[k] - combs[i][k]) + 1.0);
5541 w[i] = lw;
5542 wmax = std::max(wmax, lw);
5543 }
5544 double wsum = 0;
5545 for (std::size_t i = 0; i < w.size(); ++i) {
5546 w[i] = std::exp(w[i] - wmax);
5547 wsum += w[i];
5548 }
5549 for (std::size_t i = 0; i < combs.size(); ++i) {
5550 std::vector<T> b2 = buf, s2 = srv;
5551 for (std::size_t k = 0; k < fK[mode - 1]; ++k)
5552 s2[fKs[mode - 1] + k] = num_traits<T>::from_int(sv[k] - combs[i][k]);
5553 b2[mode - 1] += num_traits<T>::from_int(ndiff);
5554 std::vector<T> nr = b2;
5555 nr.insert(nr.end(), s2.begin(), s2.end());
5556 nr.insert(nr.end(), fired.begin(), fired.end());
5557 nr.insert(nr.end(), var.begin(), var.end());
5558 NetState<T> ns = glspace;
5559 ns.local[isf - 1] = nr;
5560 out.space.push_back(ns);
5561 out.rate.push_back(imm);
5562 out.prob.push_back(num_traits<T>::from_double(wsum > 0 ? w[i] / wsum : 0.0));
5563 out.completion.push_back(false);
5564 }
5565 return out;
5566 }
5567
5568 if (gl.active.event != EventType::FIRE) return out;
5569
5570 const bool immediate_mode = mode - 1 < tp.timing.size() &&
5572 const T fw = immediate_mode && mode - 1 < tp.fireweight.size() ? tp.fireweight[mode - 1] : one;
5573 const long en_degree = inhibited ? 0 : std::min(mark_degree, nsrv);
5574 const long imm_servers = immediate_mode ? std::min(mark_degree, nsrv) : 0;
5575
5576 for (std::size_t k = 0; k < fK[mode - 1]; ++k) {
5577 const double in_k = num_traits<T>::to_double(srv[fKs[mode - 1] + k]);
5578 const bool fires = immediate_mode ? (k == 0 && imm_servers >= 1)
5579 : (in_k > 0 && en_degree >= 1);
5580 if (!fires) continue;
5581 T rate = zero;
5582 if (immediate_mode) {
5583 rate = T(imm * fw * num_traits<T>::from_int(imm_servers));
5584 } else {
5585 T d1sum = zero;
5586 if (mode - 1 < tp.firingproc.size())
5587 for (std::size_t j = 0; j < tp.firingproc[mode - 1].D1.cols(); ++j)
5588 d1sum += tp.firingproc[mode - 1].D1(k, j);
5589 rate = T(d1sum * num_traits<T>::from_double(in_k));
5590 // A marking-dependent firing rate g_mode(marking) is exact here,
5591 // because the CTMC evaluates it per enumerated state.
5592 if (mode - 1 < tp.firingdep.size() && tp.firingdep[mode - 1]) {
5593 // the (node, class) marking flattened node-major, MATLAB's ep_space (nnodes x R)
5594 std::vector<T> mk;
5595 for (std::size_t q = 1; q <= sn.nodes.size(); ++q)
5596 for (std::size_t r = 0; r < R; ++r) mk.push_back(ep[q][r]);
5597 rate = T(rate * tp.firingdep[mode - 1](mk));
5598 }
5599 }
5600 if (num_traits<T>::to_double(rate) <= 0) continue;
5601
5602 std::vector<T> b2 = buf, s2 = srv;
5603 if (in_k > 0) {
5604 s2[fKs[mode - 1] + k] -= one; // the firing server leaves execution
5605 b2[mode - 1] += one; // and returns to the idle pool
5606 }
5607 NetState<T> ns = glspace;
5608 std::vector<T> nr = b2;
5609 nr.insert(nr.end(), s2.begin(), s2.end());
5610 nr.insert(nr.end(), fired.begin(), fired.end());
5611 nr.insert(nr.end(), var.begin(), var.end());
5612 ns.local[isf - 1] = nr;
5613
5614 // The arcs fire ATOMICALLY with the mode: PRE consumes from every
5615 // input place and POST produces into every output place, in one
5616 // transition. Splitting them would let the net occupy a state in which
5617 // the tokens have left one place and not arrived at the other.
5618 for (std::size_t j = 0; j < gl.passive.size(); ++j) {
5619 const ModeEvent<T>& pe2 = gl.passive[j];
5620 if (pe2.event != EventType::PRE && pe2.event != EventType::POST) continue;
5621 const std::size_t pisf = sn.stateful_index(pe2.node);
5622 if (pisf == 0) continue;
5623 std::vector<T>& prow = ns.local[pisf - 1];
5624 const double wgt = num_traits<T>::to_double(pe2.weight);
5625 const std::size_t pist = sn.nodes[pe2.node - 1].station;
5626 const SchedStrategy psched =
5627 pist != 0 ? sn.stations[pist - 1].sched : SchedStrategy::INF;
5628 const std::size_t c = pe2.cls;
5629 if (pe2.event == EventType::PRE) {
5630 if (state_detail::buffer_is_class_tag(psched)) {
5631 // An ordered buffer: consume from the head end, matching
5632 // the discipline rather than a count.
5633 long left = static_cast<long>(wgt);
5634 const T tag = num_traits<T>::from_int(static_cast<long>(c));
5635 if (psched == SchedStrategy::LCFS) {
5636 for (std::size_t b = 0; b < prow.size() && left > 0; ++b)
5637 if (prow[b] == tag) { prow[b] = zero; --left; }
5638 } else {
5639 for (std::size_t b = prow.size(); b-- > 0 && left > 0;)
5640 if (prow[b] == tag) { prow[b] = zero; --left; }
5641 }
5642 } else if (prow.size() > R) {
5643 // A Place with a [count | server] split: drain the server
5644 // slot into the count, as the reference does.
5645 const double totc = num_traits<T>::to_double(prow[c - 1]) +
5646 num_traits<T>::to_double(prow[R + c - 1]);
5647 prow[c - 1] = num_traits<T>::from_double(totc - wgt);
5648 prow[R + c - 1] = zero;
5649 } else if (c - 1 < prow.size()) {
5650 prow[c - 1] -= num_traits<T>::from_double(wgt);
5651 }
5652 } else {
5653 if (state_detail::buffer_is_class_tag(psched)) {
5654 for (long q = 0; q < static_cast<long>(wgt); ++q)
5655 prow.insert(prow.begin(), num_traits<T>::from_int(static_cast<long>(c)));
5656 } else if (c - 1 < prow.size()) {
5657 prow[c - 1] += num_traits<T>::from_double(wgt);
5658 }
5659 }
5660 }
5661 out.space.push_back(ns);
5662 out.rate.push_back(rate);
5663 out.prob.push_back(one);
5664 out.completion.push_back(true);
5665 }
5666 return out;
5667}
5668
5669/** One half of a synchronization: an event at a node, in a class. */
5670template <class T>
5672 EventType event = EventType::LOCAL;
5673 std::size_t node = 0; ///< 1-based node index, or `local` for the dummy
5674 std::size_t cls = 0; ///< 1-based class index
5675 T prob = num_traits<T>::from_int(1); ///< routing probability, passive half
5676 /**
5677 * The routing probability is a FUNCTION of the network state, so `prob`
5678 * holds only the state-independent placeholder and the generator must read
5679 * `rt_state(sn, state)(rt_row, rt_col)` instead.
5680 *
5681 * The reference decides this per ACTIVE NODE (`sn.isstatedep(node_a,3)`) and
5682 * then calls whatever `prob` holds, which throws where a node routes one
5683 * class state-dependently and another by probability. Deciding it per
5684 * SYNCHRONIZATION agrees wherever the reference runs at all, and does not
5685 * throw where it would.
5686 */
5687 bool statedep = false;
5688 std::size_t rt_row = 0; ///< (isf-1)*nclasses + (r-1) of the active half
5689 std::size_t rt_col = 0; ///< (jsf-1)*nclasses + (s-1) of this passive half
5690};
5691
5692/**
5693 * One synchronization: an ACTIVE event and the PASSIVE event it drives.
5694 *
5695 * Every transition of the CTMC is one of these. The active half sets the rate;
5696 * the passive half is where the job lands, weighted by the routing probability.
5697 * A LOCAL passive half means the active event moves no job out of its node --
5698 * a phase change, a reneging job leaving the system, a server failing.
5699 */
5700template <class T>
5704
5705/**
5706 * True when a synchronization is an IMMEDIATE-FEEDBACK SELF-LOOP: a departure
5707 * whose passive half is an arrival back at the same station, in a class the
5708 * station holds its server for (`sn.immfeed`, set by
5709 * `Queue.setImmediateFeedback` or `JobClass.setImmediateFeedback`).
5710 *
5711 * The departure half of such a synchronization must run with `no_promote`, so
5712 * the vacated server is not given to a waiting job and the fed-back arrival
5713 * seizes it instead. Every walk of the synchronization list must consult this,
5714 * or it answers a model in which the self-looping job re-queues behind the
5715 * waiting jobs -- the reference's `immfeed_selfloop`.
5716 *
5717 * The class read is the PASSIVE one: after a class switch the job comes back as
5718 * the class it was switched INTO, and `refresh_sync` folds the switch into
5719 * `sn.rt`, so a class-switching self-loop is still ONE synchronization whose
5720 * passive node is its active node.
5721 */
5722template <class T>
5724 if (sy.active.event != EventType::DEP || sy.passive.node != sy.active.node) return false;
5725 if (sy.active.node == 0 || sy.active.node > sn.nodes.size()) return false;
5726 const std::size_t ist = sn.nodes[sy.active.node - 1].station;
5727 if (ist == 0) return false;
5728 const std::size_t cls_p = sy.passive.cls;
5729 if (ist > sn.immfeed.size() || cls_p == 0 || cls_p > sn.immfeed[ist - 1].size()) return false;
5730 return sn.immfeed[ist - 1][cls_p - 1];
5731}
5732
5733/**
5734 * Port of `MNetwork.refreshSync`: the synchronization list.
5735 *
5736 * The ORDER matters as much as the content: the generator adds rates in this
5737 * order, and while addition is commutative in exact arithmetic it is not in
5738 * floating point, so a reordered list perturbs the last digits of every
5739 * reported metric.
5740 *
5741 * @param impatience_classes (station x class) true where reneging is declared
5742 * @param breakdown_nodes 1-based node indices with a server breakdown
5743 * @param sn the refreshed network struct
5744 */
5745template <class T>
5746std::vector<Sync<T>> refresh_sync(
5747 const NetworkStruct<T>& sn,
5748 const std::vector<std::vector<bool>>& impatience_classes = std::vector<std::vector<bool>>(),
5749 const std::vector<std::size_t>& breakdown_nodes = std::vector<std::size_t>()) {
5750 const std::size_t R = sn.nclasses;
5751 const std::size_t local = sn.nodes.size() + 1; // the dummy passive node
5752 const T one = num_traits<T>::from_int(1);
5753 std::vector<Sync<T>> sync;
5754
5755 for (std::size_t ind = 1; ind <= sn.nodes.size(); ++ind) {
5756 const NodeDef& nd = sn.nodes[ind - 1];
5757 const std::size_t ist = nd.station;
5758 for (std::size_t r = 1; r <= R; ++r) {
5759 // A phase-change action exists only for a multi-phase service:
5760 // with one phase there is no internal transition to make. A
5761 // ROUND-ROBIN station is the exception: its quantum clock moves
5762 // (and expires) whatever the service phase count, as in
5763 // `refreshSync.m`.
5764 if (ist != 0 && (sn.phases_of(ist, r) > 1 ||
5765 (sn.stations[ist - 1].sched == SchedStrategy::RR && sn.phases_of(ist, r) > 0))) {
5766 Sync<T> s;
5767 s.active = SyncEvent<T>{EventType::PHASE, ind, r, one};
5768 s.passive = SyncEvent<T>{EventType::LOCAL, local, r, one};
5769 sync.push_back(s);
5770 }
5771 // The struct's own reneging declaration emits the action too, so a caller that
5772 // passes no `impatience_classes` no longer drops every RENEGE transition.
5773 if (ist != 0 && ((impatience_classes.size() >= ist &&
5774 impatience_classes[ist - 1].size() >= r &&
5775 impatience_classes[ist - 1][r - 1]) ||
5777 Sync<T> s;
5778 s.active = SyncEvent<T>{EventType::RENEGE, ind, r, one};
5779 s.passive = SyncEvent<T>{EventType::LOCAL, local, r, one};
5780 sync.push_back(s);
5781 }
5782 if (ist != 0) {
5783 const typename std::map<std::size_t, RetrialParam<T>>::const_iterator rit =
5784 sn.retrialparam.find(ist);
5785 if (rit != sn.retrialparam.end() && rit->second.retrial_proc.size() >= r &&
5786 !rit->second.retrial_proc[r - 1].disabled) {
5787 Sync<T> s;
5788 s.active = SyncEvent<T>{EventType::RETRY, ind, r, one};
5789 s.passive = SyncEvent<T>{EventType::LOCAL, local, r, one};
5790 sync.push_back(s);
5791 }
5792 }
5793 // Failure and repair are properties of the SERVER, not of a class,
5794 // so exactly one pair is emitted per station rather than one per
5795 // class -- hence the r == 1 guard.
5796 if (ist != 0 && r == 1) {
5797 bool has_bd = sn.has_breakdown_node(ind);
5798 for (std::size_t b = 0; b < breakdown_nodes.size() && !has_bd; ++b)
5799 if (breakdown_nodes[b] == ind) { has_bd = true; break; }
5800 if (has_bd) {
5801 Sync<T> f, rp;
5802 f.active = SyncEvent<T>{EventType::FAILURE, ind, r, one};
5803 f.passive = SyncEvent<T>{EventType::LOCAL, local, r, one};
5804 sync.push_back(f);
5805 rp.active = SyncEvent<T>{EventType::REPAIR, ind, r, one};
5806 rp.passive = SyncEvent<T>{EventType::LOCAL, local, r, one};
5807 sync.push_back(rp);
5808 }
5809 }
5810 // Setup and delay-off clocks (ctmc_blocks.h): one local action per
5811 // class whose setup or delay-off law the station's block holds, only
5812 // where SolverCTMC appended the block (python refresh_sync).
5813 if (ist != 0 && ctmc_tail_width(sn, ind) > 0 && sn.setupparam.count(ist)) {
5814 const SetupInfo<T> si = setup_info(sn, ind);
5815 if (si.valid && si.setup.count(r)) {
5816 Sync<T> s2;
5817 s2.active = SyncEvent<T>{EventType::SETUP, ind, r, one};
5818 s2.passive = SyncEvent<T>{EventType::LOCAL, local, r, one};
5819 sync.push_back(s2);
5820 }
5821 if (si.valid && si.delay.count(r)) {
5822 Sync<T> s2;
5823 s2.active = SyncEvent<T>{EventType::DELAYOFF, ind, r, one};
5824 s2.passive = SyncEvent<T>{EventType::LOCAL, local, r, one};
5825 sync.push_back(s2);
5826 }
5827 }
5828 // A polling station needs a SWITCH action per buffer whose
5829 // entering switchover is a real (non-immediate) walk.
5830 if (ist != 0 && sn.stations[ist - 1].sched == SchedStrategy::POLLING) {
5831 const PollingInfo<T> pinfo = polling_info(sn, ind);
5832 polling_require_ph(pinfo);
5833 if (pinfo.valid && pinfo.swclass[r - 1]) {
5834 Sync<T> s2;
5835 s2.active = SyncEvent<T>{EventType::SWITCH, ind, r, one};
5836 s2.passive = SyncEvent<T>{EventType::LOCAL, local, r, one};
5837 sync.push_back(s2);
5838 }
5839 }
5840 if (!nd.stateful) continue;
5841 // A stateful Fork emits no departure sync: the atomic multi-branch
5842 // emission is a fork firing synchronization instead.
5843 if (nd.nodetype == NodeType::Fork) continue;
5844
5845 // A CACHE READ IS ITS OWN ACTION, not a routing decision. The read
5846 // consults the contents, rewrites them and switches the job into the
5847 // hit or the miss class, so it moves no job between nodes and its
5848 // passive half is the dummy.
5849 //
5850 // THE READ CLASS THEREFORE EMITS NO DEPARTURE HERE. `refresh_routing`
5851 // resolves its unresolved cache split to a uniform half-half so the
5852 // VISIT equations have a number; the reference leaves the same two
5853 // entries NaN, and `ceil(NaN) > 0` is false, so no departure sync is
5854 // built from them. Reproducing the half-half as a synchronization
5855 // would make the sample path decide hit against miss by a coin
5856 // instead of by reading the cache, which is what it did.
5857 bool cache_read_class = false;
5858 if (nd.nodetype == NodeType::Cache) {
5859 const typename std::map<std::size_t, CacheParam<T>>::const_iterator ci =
5860 sn.nodeparam.find(ind);
5861 if (ci != sn.nodeparam.end()) {
5862 if (r - 1 < ci->second.pread.size() && !ci->second.pread[r - 1].empty()) {
5863 Sync<T> s;
5864 s.active = SyncEvent<T>{EventType::READ, ind, r, one};
5865 s.passive = SyncEvent<T>{EventType::READ, local, r, one};
5866 sync.push_back(s);
5867 }
5868 cache_read_class =
5869 r - 1 < ci->second.hitclass.size() && ci->second.hitclass[r - 1] != 0;
5870 }
5871 }
5872 // A stateful Transition emits one server phase-change action per
5873 // MODE, not per class (the JAR gates the same way on the first
5874 // class); its cls slot carries the mode, as `after_event_transition`
5875 // reads it.
5876 if (nd.nodetype == NodeType::Transition && r == 1) {
5877 const typename std::map<std::size_t, TransitionParam<T>>::const_iterator ti =
5878 sn.transparam.find(ind);
5879 if (ti != sn.transparam.end()) {
5880 for (std::size_t m = 1; m <= ti->second.nmodes; ++m) {
5881 Sync<T> s;
5882 s.active = SyncEvent<T>{EventType::PHASE, ind, m, one};
5883 s.passive = SyncEvent<T>{EventType::LOCAL, local, m, one};
5884 sync.push_back(s);
5885 }
5886 }
5887 }
5888 if (cache_read_class) continue;
5889
5890 const std::size_t isf = sn.stateful_index(ind);
5891 for (std::size_t jnd = 1; jnd <= sn.nodes.size(); ++jnd) {
5892 if (!sn.nodes[jnd - 1].stateful) continue;
5893 const std::size_t jsf = sn.stateful_index(jnd);
5894 for (std::size_t s = 1; s <= R; ++s) {
5895 const T p = sn.rt((isf - 1) * R + (r - 1), (jsf - 1) * R + (s - 1));
5896 if (num_traits<T>::to_double(p) <= 0) continue;
5897 Sync<T> ns;
5898 ns.active = SyncEvent<T>{EventType::DEP, ind, r, one};
5899 ns.passive = SyncEvent<T>{EventType::ARV, jnd, s, p};
5900 // SDR reaches `rt` as the uniform placeholder `refresh_routing`
5901 // writes, so the SUPPORT of the mask is right and the values
5902 // are not: the pair exists exactly where a link does, and the
5903 // generator replaces the probability state by state. This is
5904 // the reference's `rtmask = rtfun(emptystate, emptystate)`,
5905 // which likewise keeps every connected pair. JSQ and SQ(d)
5906 // likewise, keyed on the departing class r: their rows
5907 // never switch class, so r and s agree wherever p > 0.
5908 const RoutingStrategy rsr =
5909 nd.routing.size() >= r ? nd.routing[r - 1] : RoutingStrategy::PROB;
5910 if ((nd.routing.size() >= s && nd.routing[s - 1] == RoutingStrategy::SDR) ||
5911 rsr == RoutingStrategy::JSQ || rsr == RoutingStrategy::SQ) {
5912 ns.passive.statedep = true;
5913 ns.passive.rt_row = (isf - 1) * R + (r - 1);
5914 ns.passive.rt_col = (jsf - 1) * R + (s - 1);
5915 }
5916 sync.push_back(ns);
5917 }
5918 }
5919 }
5920 }
5921 return sync;
5922}
5923
5924/**
5925 * Port of `State.afterFJEvent`: fire ONE entry of the fork firing list.
5926 *
5927 * A fork firing is atomic across several nodes -- it consumes the parent at the
5928 * fork and places one sibling at each branch head in the same instant -- so
5929 * unlike every ordinary transition it cannot be decomposed into an active half
5930 * and a passive half. It therefore takes the whole network state, exactly as an
5931 * SPN global synchronization does.
5932 *
5933 * THE TWO ENABLING CONDITIONS.
5934 *
5935 * 1. The fork holds at least one class-r parent.
5936 *
5937 * 2. This entry's tag is the LOWEST FREE tag for this (fork, class). A tag is
5938 * free when its auxiliary classes have zero occupancy NETWORK-WIDE, which is
5939 * why the test scans every stateful node and not just the branches: a
5940 * sibling in transit is still outstanding. Without the canonical choice
5941 * every firing would produce one successor per free tag, all of them
5942 * relabellings of each other, and the chain would carry a factorial number
5943 * of duplicate states.
5944 *
5945 * The emission is applied SEQUENTIALLY over a growing outcome list rather than
5946 * branch-by-branch into one state, because that is what handles the three cases
5947 * a single pass would get wrong: two branches sharing a head node, `weight > 1`
5948 * repeated emissions on one branch, and a non-exponential sibling service whose
5949 * phase-entry mixture makes one arrival into several outcomes.
5950 */
5951template <class T>
5953 const NetState<T>& gl) {
5954 const std::size_t R = sn.nclasses;
5955 GlobalOutcome<T> out;
5956 const std::size_t isf_f = sn.stateful_index(e.fork);
5957 if (isf_f == 0) return out;
5958 const std::vector<T>& fs = gl.local[isf_f - 1];
5959 if (fs.size() < R) return out;
5960 if (num_traits<T>::to_double(fs[fs.size() - R + e.cls - 1]) < 1) return out;
5961
5962 // Tag occupancy, network-wide.
5963 const std::size_t B = e.auxall.size();
5964 if (B == 0 || e.tag == 0 || e.tag > e.auxall[0].size()) return out;
5965 const std::size_t Tt = e.auxall[0].size();
5966 std::vector<double> nglobal(R, 0.0);
5967 for (std::size_t isf = 1; isf <= sn.stateful_nodes.size(); ++isf) {
5968 const std::pair<T, std::vector<T>> mg =
5969 to_marginal_aggr(sn, sn.stateful_nodes[isf - 1], gl.local[isf - 1]);
5970 for (std::size_t r = 0; r < R; ++r) {
5971 const double v = num_traits<T>::to_double(mg.second[r]);
5972 // A Source encodes its reservoir as an infinite marginal; adding it
5973 // would make every tag look occupied. An auxiliary class is never
5974 // generated by a Source, so skipping the non-finite entries cannot
5975 // hide a real sibling.
5976 if (std::isfinite(v)) nglobal[r] += v;
5977 }
5978 }
5979 std::vector<double> occ(Tt, 0.0);
5980 for (std::size_t t = 0; t < Tt; ++t)
5981 for (std::size_t b = 0; b < B; ++b) occ[t] += nglobal[e.auxall[b][t] - 1];
5982 if (occ[e.tag - 1] > 0) return out; // this tag is in use
5983 for (std::size_t t = 0; t + 1 < e.tag; ++t)
5984 if (occ[t] == 0) return out; // a lower tag is free
5985
5986 NetState<T> seed = gl;
5987 seed.local[isf_f - 1][seed.local[isf_f - 1].size() - R + e.cls - 1] -=
5989
5990 std::vector<NetState<T>> partials(1, seed);
5991 std::vector<T> partprob(1, num_traits<T>::from_int(1));
5992 // The emission list, one entry per sibling. `weightlink` is filled only when
5993 // the fork sends different counts down different links; the interleave below
5994 // reproduces `repmat(1:B,1,w)` exactly in the uniform case, so a plain fork
5995 // walks the order it always did.
5996 std::vector<std::size_t> emissions;
5997 if (e.weightlink.empty()) {
5998 const std::size_t w = e.weight == 0 ? 1 : e.weight;
5999 for (std::size_t rep = 0; rep < w; ++rep)
6000 for (std::size_t b = 0; b < B; ++b) emissions.push_back(b);
6001 } else {
6002 std::size_t wmax = 0;
6003 for (std::size_t b = 0; b < e.weightlink.size(); ++b)
6004 if (e.weightlink[b] > wmax) wmax = e.weightlink[b];
6005 for (std::size_t rep = 1; rep <= wmax; ++rep)
6006 for (std::size_t b = 0; b < B; ++b)
6007 if (b < e.weightlink.size() && e.weightlink[b] >= rep) emissions.push_back(b);
6008 }
6009 for (std::size_t ei = 0; ei < emissions.size(); ++ei) {
6010 const std::size_t b = emissions[ei];
6011 const std::size_t bh = e.branchheads[b];
6012 const std::size_t isf_b = sn.stateful_index(bh);
6013 if (isf_b == 0) return GlobalOutcome<T>();
6014 const std::size_t a = e.auxclasses[b];
6015 std::vector<NetState<T>> nextp;
6016 std::vector<T> nextq;
6017 for (std::size_t pp = 0; pp < partials.size(); ++pp) {
6018 const EventOutcome<T> arv =
6019 after_event(sn, bh, partials[pp].local[isf_b - 1], EventType::ARV, a);
6020 if (arv.space.empty()) return GlobalOutcome<T>(); // blocked: no firing
6021 for (std::size_t io = 0; io < arv.space.size(); ++io) {
6022 NetState<T> ns = partials[pp];
6023 ns.local[isf_b - 1] = arv.space[io];
6024 nextp.push_back(ns);
6025 nextq.push_back(io < arv.prob.size() ? T(partprob[pp] * arv.prob[io])
6026 : partprob[pp]);
6027 }
6028 }
6029 partials.swap(nextp);
6030 partprob.swap(nextq);
6031 }
6032
6033 out.space = partials;
6034 for (std::size_t i = 0; i < partials.size(); ++i) {
6036 out.prob.push_back(T(partprob[i] * e.prob));
6037 out.completion.push_back(true);
6038 }
6039 return out;
6040}
6041
6042} // namespace qn
6043} // namespace line
6044
6045#endif // LINE_LANG_QN_STATE_EVENTS_H
Base error for the multiprecision C++ port.
Definition error.h:73
InputError(const std::string &what)
Definition error.h:105
InternalError(const std::string &what)
Definition error.h:133
std::size_t cols() const
Definition matrix.h:90
std::size_t rows() const
Definition matrix.h:89
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
The station blocks SolverCTMC appends to a station's local state for three features the population la...
The exception types the port throws.
Enumerations and the minimal distribution descriptor shared by the model layer of the C++ port.
Markovian arrival process descriptors: stationary vectors, rate, moments, autocorrelation and the ind...
std::string sn_patience_exp_refusal(const qn::NetworkStruct< T > &sn, std::size_t ist, std::size_t r)
Port of sn_patience_exp_refusal.m: the by-name refusal of a reneging patience that is not EXPONENTIAL...
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
@ IMMEDIATE
fires with zero delay, resolved by weight and priority
Definition lang_types.h:384
@ REPLY
completes a synchronous call, releasing a held server
Definition lang_types.h:181
@ CATASTROPHE
removes EVERY job at the station
Definition lang_types.h:183
@ THRESHOLD
a priority buffer above its threshold, else SKIPEMPTY
Definition lang_types.h:408
@ SKIPEMPTY
next non-empty buffer in cyclic order
Definition lang_types.h:406
@ LQF
longest buffer first, ties to the cyclic successor
Definition lang_types.h:407
RoutingStrategy
Routing strategies, with the values of MATLAB RoutingStrategy.
Definition lang_types.h:430
@ LOCAL
a timer per visit, drawn at the polling instant
Definition lang_types.h:414
@ GLOBAL
a timed token: per-class target rotation timers
Definition lang_types.h:415
@ NONE
no visit timer
Definition lang_types.h:413
RemovalPolicy
Which job a negative signal removes, with the values of MATLAB RemovalPolicy.
Definition lang_types.h:187
@ FCFS
the oldest waiting job; servers only once nobody waits
Definition lang_types.h:189
@ LCFS
the newest waiting job; servers only once nobody waits
Definition lang_types.h:190
@ RANDOM
uniform over waiting AND in-service jobs
Definition lang_types.h:188
EventType
The events a state can undergo, with the values of MATLAB EventType.
Definition lang_types.h:116
@ KLIMITED
serve at most K per visit (K in pollingPar)
Definition lang_types.h:394
@ EXHAUSTIVE
serve until the queue empties
Definition lang_types.h:393
@ GATED
serve exactly the jobs present at the polling instant
Definition lang_types.h:392
@ GLIMITED
serve at most K of the jobs present at the polling instant
Definition lang_types.h:396
@ DECREMENTING
serve until the queue is one shorter than at arrival
Definition lang_types.h:395
const char * sched_to_text(SchedStrategy s)
Definition lang_types.h:248
std::function< std::vector< T >(const std::vector< T > &)> CdScaling
A class-dependent scaling map, sn.cdscaling.
Definition lang_types.h:794
const char * event_to_text(EventType e)
Definition lang_types.h:148
@ QLRU
q-LRU: LRU with probabilistic admission on a miss
Definition lang_types.h:426
@ FIFO
first in, first out
Definition lang_types.h:421
std::vector< T > map_pie(const Map< T > &m)
Phase distribution seen by an arriving job, pie = pi D1 / (pi D1 e).
Definition map_moment.h:89
double srv_count(const RowLayout< T > &L, const std::vector< T > &row)
Jobs in service in a station row: the server block's total.
double block_sum(const std::vector< T > &row, std::size_t w)
double held_servers(const NetworkStruct< T > &sn, std::size_t ind, const RowLayout< T > &L, const std::vector< T > &row)
Servers held at ind by synchronous calls awaiting a REPLY (python setup_delayoff._held).
std::vector< std::pair< std::vector< T >, T > > setup_departure_variants(const NetworkStruct< T > &sn, std::size_t ind, const SetupInfo< T > &si, const RowLayout< T > &L, const std::vector< T > &row, std::size_t cls)
Post-departure moves (python setup_departure_variants): a server freed onto an empty buffer starts th...
void push(EventOutcome< T > &out, const std::vector< T > &row, const T &rate, const T &prob, const std::vector< std::size_t > &start, const std::vector< std::size_t > &preempt)
Append one successor with its tags.
bool buffer_empty(const RowLayout< T > &L, const std::vector< T > &row)
bool holds_call(const NetworkStruct< T > &sn, std::size_t ind, std::size_t cls)
True when a class-cls departure from ind keeps its server for a synchronous call.
std::vector< std::pair< std::vector< T >, T > > setup_arrival_variants(const NetworkStruct< T > &sn, std::size_t ind, const SetupInfo< T > &si, const RowLayout< T > &L, const std::vector< T > &row, std::size_t cls)
Pre-arrival moves of the setup block (python setup_arrival_variants): with an idle ACTIVE server the ...
std::size_t calling_class(const NetworkStruct< T > &sn, std::size_t ind, std::size_t cls)
The calling class whose held server a REPLY of class cls releases at ind, or 0 when cls answers no ca...
void add_visit(const PollingInfo< T > &pi, PollingAdvance< T > &B, std::vector< long > c, std::size_t p, std::size_t r, const std::vector< long > &nbuf, T prob)
void add_row(PollingAdvance< T > &B, const std::vector< long > &c, int mode, std::size_t q, T prob)
void arrive_at(const PollingInfo< T > &pi, PollingAdvance< T > &B, const std::vector< long > &c, const std::vector< long > &nbuf, std::size_t p, T prob, std::vector< std::vector< long > > &passC, std::vector< T > &passP)
void walk(const PollingInfo< T > &pi, PollingAdvance< T > &B, std::vector< long > c, const std::vector< long > &nbuf, std::size_t p, bool arrived, std::size_t steps_left, T prob, std::size_t startpos)
std::vector< PoolStart< T > > pool_serve_next(const NetworkStruct< T > &sn, const CtmcPool< T > &pool, SchedStrategy sched, const std::vector< std::size_t > &Ks, const std::vector< T > &buf, const std::vector< T > &srv, std::size_t t)
The freed server of pool t takes the next compatible waiting job, in the discipline's order.
void pool_start(const CtmcPool< T > &pool, const std::vector< std::size_t > &Ks, const std::vector< T > &buf, const std::vector< T > &srv, std::size_t s, std::size_t t, const T &w, std::vector< PoolStart< T > > &out)
Class s starts service on pool t in every entry phase of the pool's block.
std::vector< Promoted< T > > promote(const std::vector< T > &y, std::size_t bufw, std::size_t srv0, const std::vector< std::size_t > &Ks, std::size_t rroff, const RrInfo< T > &ri)
sub_promote: move the HEAD of the buffer (its rightmost non-empty pair) into service with a fresh qua...
std::vector< T > bufpush(std::vector< T > buf, std::size_t r, std::size_t k)
sub_bufpush: put (class R, phase K) at the TAIL of a paired buffer, the rightmost empty pair (the old...
std::string state_impatience_unsupported(const NetworkStruct< T > &sn, const std::string &solver)
Port of solver_ctmc_state_supports.m: the impatience laws the state machinery cannot serve,...
std::vector< T > entry_phase_dist(const NetworkStruct< T > &sn, std::size_t ist, std::size_t cls)
The entry-phase distribution pie{ist}{class}: which phase a service STARTS in.
long polling_budget(const PollingInfo< T > &pi, long nbufq)
Port of State.pollingBudget: how many services this visit may perform.
EventOutcome< T > after_event_join(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventType event, std::size_t cls)
Port of State.afterEventJoin: an event at a Join node of an FJ-augmented struct.
EventOutcome< T > after_event_station_pas(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventType event, std::size_t cls)
Defined below; the ARV and DEP branches divert to it before any slicing.
void tag_last(EventOutcome< T > &out, std::size_t start_cls, std::size_t preempt_cls)
Tag the successor row just appended to OUT: START_CLS begins service on it and PREEMPT_CLS is displac...
SetupInfo< T > setup_info(const NetworkStruct< T > &sn, std::size_t ind)
The ACTIVE setup/delay-off block of node ind: the layout, when SolverCTMC appended it.
void cache_retrieval_class_map(const CacheParam< T > &cp, std::vector< std::size_t > &rc_list, std::vector< std::size_t > &rc_items, std::vector< std::size_t > &rc_orig)
Port of State.cacheRetrievalClassMap: the canonical order of a cache's retrieval classes,...
std::pair< std::vector< std::size_t >, std::vector< T > > signal_batch_pmf(const NetworkStruct< T > &sn, std::size_t cls, std::size_t ntot)
Port of State.signalBatchPMF: the batch size a negative signal removes.
ReplyBlockInfo reply_block_info(const NetworkStruct< T > &sn, std::size_t ind)
Defined below; the departure branch records a server held for a reply.
Marginal< T > to_marginal(const NetworkStruct< T > &sn, std::size_t ist, const std::vector< T > &state_i, const std::vector< std::size_t > &phasesz, const std::vector< std::size_t > &phaseshift, std::size_t nvar=0)
Port of State.toMarginal for a STATION, one state row at a time.
Definition state.h:139
void polling_get(const PollingInfo< T > &pi, const std::vector< T > &var, std::size_t srvclass, std::size_t &pos, std::size_t &swk, long &ctr)
Defined below; the polling branches of ARV, DEP and SWITCH use these.
EventOutcome< T > after_event_setup(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventType event, std::size_t cls, bool no_promote, const T &aux_rate, const SetupInfo< T > &si)
after_event at a setup/delay-off station (python _after_event_setup): the block moves wrap the ordina...
EventOutcome< T > after_event_station_switch(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, std::size_t cls)
Port of the SWITCH branch: a polling server advances its switchover timer.
void rr_advance_row(const NetworkStruct< T > &sn, std::size_t ind, std::size_t cls, std::vector< std::vector< T > > &rows)
Port of State.afterEventStation's dispatch: the successors of one event at one station.
void apply_station_orbital_search(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventOutcome< T > &out)
Orbital search (Artalejo, Joshua and Krishnamoorthy 2002), the DEP half: port of orbitalSearchSplit i...
void polling_next(const PollingInfo< T > &pi, std::size_t pos, const std::vector< long > &nbuf, std::size_t R, bool arrived, std::size_t &q, int &mode, long &budget)
Port of State.pollingNext: where the server goes from buffer pos.
void polling_land_all(const NetworkStruct< T > &sn, std::size_t ist, const PollingInfo< T > &pi, const PollingAdvance< T > &B, const std::vector< T > &buf, const std::vector< T > &srv, const std::vector< T > &var, const RowLayout< T > &L, std::vector< std::vector< T > > &rows, std::vector< T > &probs, std::vector< std::size_t > &starts)
Port of State.pollingLandAll: the state rows the advance outcomes land in.
bool immfeed_self_loop(const NetworkStruct< T > &sn, const Sync< T > &sy)
True when a synchronization is an IMMEDIATE-FEEDBACK SELF-LOOP: a departure whose passive half is an ...
T station_renege_mu(const NetworkStruct< T > &sn, std::size_t ist, std::size_t cls)
sn.impatienceMu(ist,cls): the rate of an exponential reneging patience, 0 when the class declares non...
void polling_require_ph(const PollingInfo< T > &pi)
Refuses a polling station whose switchover legs are not all phase-type.
std::vector< T > polling_set(const PollingInfo< T > &pi, std::vector< T > var, std::size_t pos, std::size_t swk, long ctr)
Write (pos, swk, ctr) back into the local-variable block.
GlobalOutcome< T > after_global_event(const NetworkStruct< T > &sn, const NetState< T > &glspace, const GlobalSync< T > &gl)
Port of State.afterGlobalEvent: an SPN mode ENABLEs or FIREs.
EventOutcome< T > after_event_station_reply(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, std::size_t cls)
Port of State.afterEventStationReply: a REPLY signal completes a synchronous call at the station hold...
EventOutcome< T > after_event_station_arv(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, std::size_t cls)
Port of the ARV branch of State.afterEventStation: an arriving class-cls job joins node ind,...
EventOutcome< T > after_event_station_renege(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, std::size_t cls, const T &impatience_mu)
Port of the RENEGE branch: a WAITING class-cls job abandons the queue.
EventOutcome< T > after_event_cache(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventType event, std::size_t cls)
Port of State.afterEventCache: events at a Cache node.
EventOutcome< T > after_event_station_signal(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, std::size_t cls)
Port of State.afterEventStationSignal: a G-network signal arrives.
T station_retrial_mu(const NetworkStruct< T > &sn, std::size_t ist, std::size_t cls)
sn.retrialMu(ist,cls): the rate of the exponential retrial delay, falling back to the scalar retrial_...
bool is_physical_capacity(const NetworkStruct< T > &sn, std::size_t ist, std::size_t cls)
Port of State.isPhysicalCapacity: true when the bound at (ist, class) is a PHYSICAL capacity rather t...
PollingAdvance< T > polling_advance(const PollingInfo< T > &pi, std::vector< long > c, const std::vector< long > &nbuf, bool arrived)
Port of State.pollingAdvance: every tangible controller configuration the server reaches from c (pos ...
PrioPop< T > prio_pop(const NetworkStruct< T > &sn, std::size_t ist, const Marginal< T > &m, std::size_t cls, double ni, double S)
Compute the *PRIO effective population; a no-op for every other discipline.
T cd_factor(const NetworkStruct< T > &sn, std::size_t ist, const std::vector< T > &nir, std::size_t cls)
Port of State.cdclassfactor: the class-dependence multiplier of a class-cls rate at the per-class pop...
EventOutcome< T > after_event_station_phase(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, std::size_t cls)
Port of the PHASE branch of State.afterEventStation: service advances a phase WITHOUT completing.
bool station_is_retrial(const NetworkStruct< T > &sn, std::size_t ist)
True when station ist (1-based) has a retrial process for some class.
std::pair< std::vector< T >, std::vector< T > > phase_rates(const NetworkStruct< T > &sn, std::size_t ist, std::size_t cls)
sn.mu and sn.phi for one (station, class), derived as MATLAB's Markovian.getMu / getPhi derive them f...
EventOutcome< T > after_event_transition(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventType event, std::size_t mode)
Port of State.afterEventTransition, the PHASE arm: one running server of the given mode advances its ...
EventOutcome< T > after_event_router(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventType event, std::size_t cls)
Port of State.afterEventRouter: a Router holds a job for the instant it takes to decide where it goes...
RrInfo< T > rr_info(const NetworkStruct< T > &sn, std::size_t ind)
Port of State.rrInfo.
Definition rr_info.h:95
T lld_factor(const NetworkStruct< T > &sn, std::size_t ist, double n)
The limited-load-dependent multiplier at population n, 1 when unset.
void promote_fitting(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< double > &par, const std::vector< T > &row, const T &p, std::vector< std::size_t > started, std::vector< std::pair< std::pair< std::vector< T >, T >, std::vector< std::size_t > > > &out)
Hand freed servers to the head-of-line jobs while the head fits (python promote_fitting): (row,...
void pad_tags(EventOutcome< T > &out)
Bring the tag vectors up to one entry per successor, so a caller can index them exactly like space.
std::vector< long > polling_get_full(const PollingInfo< T > &pi, const std::vector< T > &var, std::size_t srvclass)
Port of State.pollingGetFull: [pos, swk, ctr, src, tht, trt_1..R].
void pas_tag_started(EventOutcome< T > &out, const F &mu_fun, const std::vector< std::size_t > &cold, const std::vector< std::size_t > &cnew)
Tag the successor just appended to OUT with the PAS positions that started service on it: those of CN...
std::vector< Sync< T > > refresh_sync(const NetworkStruct< T > &sn, const std::vector< std::vector< bool > > &impatience_classes=std::vector< std::vector< bool > >(), const std::vector< std::size_t > &breakdown_nodes=std::vector< std::size_t >())
Port of MNetwork.refreshSync: the synchronization list.
EventOutcome< T > after_event(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventType event, std::size_t cls, bool no_promote=false, const T &aux_rate=num_traits< T >::from_int(0))
Port of State.afterEvent: the successors of one event at one NODE.
EventOutcome< T > after_event_attempts(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventType event, std::size_t cls, bool no_promote, const T &aux_rate, const AttemptsLayout &ai)
ARV and RETRY at a finite-attempt retrial station (python after_event_attempts).
std::pair< std::vector< std::size_t >, std::size_t > pass_and_swap(const std::vector< std::size_t > &c, std::size_t p, const std::vector< std::vector< bool > > &G)
Port of State.passAndSwap: the transition a service completion triggers at a pass-and-swap station (D...
std::vector< double > parallelism_of(const NetworkStruct< T > &sn, std::size_t ind)
Per-class server degrees n_r (all >= 1) of node ind, or empty when every class seizes one server (pyt...
std::vector< T > polling_set_full(const PollingInfo< T > &pi, std::vector< T > var, const std::vector< long > &c)
Port of State.pollingSetFull: write the materialized entries back.
std::pair< T, std::vector< T > > to_marginal_aggr(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &state_i)
Port of State.toMarginalAggr: the job counts of one node's state row, without the per-phase detail to...
EventOutcome< T > after_event_fork(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventType event, std::size_t cls)
Port of State.afterEventFork: an event at a STATEFUL Fork node.
EventOutcome< T > after_event_station(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventType event, std::size_t cls, bool no_promote=false, const T &aux_rate=num_traits< T >::from_int(0))
Port of State.afterEventStation: the station dispatcher, with the CTMC station blocks of ctmc_blocks....
std::vector< GlobalSync< T > > refresh_global_sync(const NetworkStruct< T > &sn)
Port of MNetwork.refreshGlobalSync: the ENABLE and FIRE synchronizations.
EventOutcome< T > after_event_parallel(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, std::size_t cls, const T &aux_rate, const std::vector< double > &par)
A departure at a station with server parallelism (python after_event's parallel arm): it frees its jo...
EventOutcome< T > after_event_station_pool(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventType event, std::size_t cls)
Port of State.afterEventStationPool: ARV, DEP and PHASE at a station whose heterogeneous server pools...
void apply_station_orbit_join(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, std::size_t cls, EventOutcome< T > &out)
Non-persistent retrial customers, the ARV half (Phung-Duc 2019, Sec.
AttemptsLayout attempts_info(const NetworkStruct< T > &sn, std::size_t ind)
The ACTIVE attempt block of node ind: the layout, when SolverCTMC appended it.
std::vector< double > pas_increments(const F &mu_fun, const std::vector< std::size_t > &c)
Per-position service rate increments Delta_mu(c1..cp) = mu(c1..cp) - mu(c1..c_{p-1}...
EventOutcome< T > after_event_station_base(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventType event, std::size_t cls, bool no_promote=false, const T &aux_rate=num_traits< T >::from_int(0))
T service_share(const NetworkStruct< T > &sn, std::size_t ist, const Marginal< T > &m, std::size_t cls, double ni, double S)
Defined below; DEP and PHASE must share one definition of the share.
void apply_station_balking(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, std::size_t cls, EventOutcome< T > &out)
Port of the QUEUE_LENGTH balking branch of the ARV event: with the probability of the threshold band ...
GlobalOutcome< T > after_fj_event(const NetworkStruct< T > &sn, const FjSync< T > &e, const NetState< T > &gl)
Port of State.afterFJEvent: fire ONE entry of the fork firing list.
bool station_has_reneging(const NetworkStruct< T > &sn, std::size_t ist)
True when station ist declares exponential reneging for some class.
RowLayout< T > row_layout(const NetworkStruct< T > &sn, std::size_t ind, std::size_t width)
EventOutcome< T > after_event_station_dep(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, std::size_t cls, bool no_promote=false)
Port of the DEP branch of State.afterEventStation: a class-cls job completes service at station ind.
bool station_retrial_constant(const NetworkStruct< T > &sn, std::size_t ist, std::size_t cls)
sn.retrialPolicy(ist,cls) == CONSTANT: one retry clock for the whole orbit.
std::size_t ctmc_tail_width(const NetworkStruct< T > &sn, std::size_t ind)
Width of the CTMC station block of node ind (1-based), 0 when it has none.
Definition ctmc_blocks.h:65
double reply_held_servers(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &var, const std::vector< double > &par)
Defined below; servers held for pending replies, weighted by server parallelism.
PollingInfo< T > polling_info(const NetworkStruct< T > &sn, std::size_t ind)
std::size_t polling_choose(const PollingInfo< T > &pi, std::size_t i, const std::vector< long > &nbuf)
Port of State.pollingChoose: the next buffer under a load-dependent order, 0 if none.
EventOutcome< T > after_event_station_breakdown(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, bool up, const T &mu)
Port of the FAILURE and REPAIR branches: the server goes down, or comes back.
bool arrival_is_lost(const NetworkStruct< T > &sn, std::size_t ist, std::size_t cls)
Port of State.arrivalIsLost: true when an arrival that finds no room is LOST, false when it must BLOC...
EventOutcome< T > after_event_station_retry(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, std::size_t cls, const T &retrial_mu, bool constant_policy=false)
Port of the RETRY branch: an ORBITING class-cls job retries entry.
EventOutcome< T > after_event_station_rr(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &x, EventType event, std::size_t cls)
Port of State.afterEventStationRR: round robin with a finite quantum (Haverkort 1998,...
void polling_land(const NetworkStruct< T > &sn, std::size_t ist, const PollingInfo< T > &pi, std::size_t q, int mode, long budget, const std::vector< T > &buf, const std::vector< T > &srv, const std::vector< T > &var, const RowLayout< T > &L, std::vector< std::vector< T > > &rows, std::vector< T > &probs)
Port of State.pollingLand: the states the walk lands in, with weights.
double reply_blocked(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &var)
Defined below; the reply block subtracts held servers in the ARV branch.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
SolverBA BA
Definition solver.h:759
A queueing network and its refreshed NetworkStruct.
State.pollingInfo and the controller description it returns.
State.rrInfo: the quantum-phase block of a round-robin station.
Port of matlab/src/api/sn/sn_patience_handles.m.
Port of the MATLAB +State package: the encoding that turns a station's state row into marginal job co...
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
Matrix< T > D0
The (D0,D1) pair when the type carries one directly.
Definition lang_types.h:921
std::vector< Matrix< T > > Dmark
MMAP per-class D1 blocks / BMAP per-batch-size blocks; empty otherwise.
Definition lang_types.h:931
static constexpr double Immediate
Rate of an Immediate distribution; its mean is 1/Immediate = 1e-8.
Definition lang_types.h:829
A MAP as the pair of matrices (D0, D1).
Definition map_moment.h:53
Matrix< T > D1
Definition map_moment.h:55
Matrix< T > D0
Definition map_moment.h:54
A finite-attempt retrial station (python attempts_info).
std::size_t M
maxAttempts, the number of attempt levels
std::size_t ist
1-based station
std::size_t cls
1-based retrial class
Server breakdown and repair of a station whose server fails and is repaired.
T failure_rate
sn.breakdownMu: 1 / mean failure time
T repair_rate
sn.repairMu: 1 / mean repair time
The parameters of a Cache node, MATLAB's sn.nodeparam{ind} for a Cache.
int retrieval_capacity
Delayed-hit retrieval system (Cache.setRetrievalSystem).
T qlru
q-LRU admission probability; 1 admits every miss (plain LRU).
std::vector< std::vector< Matrix< T > > > accost
(u) x (n) of (h+1)x(h+1), or empty
long max_pending_retrieval
Truncation level of block B: how many secondary requests may be merged onto the in-flight fetches of ...
std::vector< std::vector< std::size_t > > retrieval_classes
(nitems x nclasses), 1-based
std::vector< int > itemcap
std::vector< std::size_t > missclass
std::vector< std::size_t > hitclass
lang::ReplacementStrategy replacestrat
std::vector< std::vector< T > > pread
(u) x (n), empty row = NaN
CTMC pair form of a MAP service at an FCFS station, written by ctmc::ctmc_mapc on the solver's privat...
Matrix< T > V
landing law (-D0)^-1 D1
std::size_t p
phases of the original MAP
std::vector< std::pair< std::size_t, std::size_t > > pairs
0-based (i,j), i-major, V(i,j) > 0
std::vector< T > done
completion rate D1(i,j)/V(i,j)
bool single
c = 1: carried phase, no pairs
CTMC bookkeeping of a heterogeneous-server station, written by ctmc::ctmc_pools on the solver's priva...
std::vector< std::vector< std::size_t > > len
offset and length of block k of class r
std::vector< std::vector< std::vector< T > > > alpha
entry vector of block k of class r
std::vector< std::vector< std::vector< T > > > exit
exit rates of block k of class r
std::vector< std::vector< bool > > compat
compat[t-1][r-1]
std::vector< double > count
servers per pool
std::vector< std::size_t > alfsorder
pools by ascending class count (ALFS)
std::vector< std::vector< Matrix< T > > > D0
D0 of block k of class r.
std::vector< std::vector< std::size_t > > pools
pools[r-1]: compatible pools of r, ascending
lang::HeteroSchedPolicy policy
bool rotate
ALIS/FAIRNESS order is part of the state.
std::vector< std::vector< std::size_t > > off
std::size_t perm_index(const std::vector< std::size_t > &order) const
1-based index of order in perms, 0 when absent.
std::vector< std::vector< double > > fsfrate
fsfrate[t-1][r-1] = 1/mean (FSF)
std::vector< std::vector< std::size_t > > perms
every pool order, identity first
What one event produces at one node: the successor rows, their rates and their probabilities,...
std::vector< T > prob
per-row probability of the choice
std::vector< std::vector< T > > space
successor local state rows
std::vector< T > rate
per-row rate, -1 on a passive half
std::vector< std::vector< std::size_t > > start
START annotation: the 1-based classes that BEGIN or RESUME holding a server on each successor row.
std::vector< std::vector< std::size_t > > preempt
PREEMPT annotation: the 1-based classes pushed back into the buffer.
sn.nodeparam{j}.fj: what a Join node needs to fire on identity.
std::vector< std::size_t > origclasses
std::map< std::size_t, std::size_t > quorum
QUORUM joins (JoinStrategy.PARTIAL), keyed by original class: the join fires on the first quorum[r] o...
std::map< std::size_t, std::vector< std::vector< std::size_t > > > auxmatrix
std::map< std::size_t, std::size_t > debtoff
std::map< std::size_t, std::vector< std::size_t > > required
One fork firing synchronization: sn.fjsync{k}.
std::size_t fork
1-based Fork node
std::vector< std::size_t > weightlink
Per-branch tasksPerLink, EMPTY when every branch carries weight.
std::size_t weight
tasksPerLink: siblings emitted per branch
std::vector< std::size_t > branchheads
1-based node per branch
std::size_t cls
1-based ORIGINAL class being forked
std::vector< std::vector< std::size_t > > auxall
(B x T) every auxiliary class of this (fork, class), for the tag scan.
std::vector< std::size_t > auxclasses
the tag's auxiliary class per branch
std::size_t tag
1-based tag this entry allocates
static constexpr double Immediate
Rate of an Immediate distribution; its mean is 1/Immediate = 1e-8.
Definition lang_types.h:829
static constexpr double MaxInt
Stand-in for an unbounded COUNT, MATLAB GlobalConstants.MaxInt.
Definition lang_types.h:834
What one global event produces: a whole network state per outcome.
std::vector< T > rate
std::vector< NetState< T > > space
std::vector< T > prob
std::vector< bool > completion
True where the outcome is a firing COMPLETION, i.e.
A GLOBAL synchronization: an SPN mode event and the place arcs it drives.
ModeEvent< T > active
std::vector< ModeEvent< T > > passive
What State.toMarginal returns for one station and one state row.
Definition state.h:56
std::vector< std::vector< T > > kir
jobs in service per class and phase
Definition state.h:60
std::vector< T > nir
jobs per class
Definition state.h:58
std::vector< T > sir
jobs in service per class
Definition state.h:59
One half of a GLOBAL synchronization: a mode event at a node.
std::size_t mode
1-based mode index
std::size_t node
1-based node index (a Transition, or a place)
T weight
arc multiplicity
std::size_t cls
1-based class the arc moves
One network state: the per-stateful-node local rows it is composed of.
Definition state.h:3022
std::vector< std::vector< T > > local
local[isf] is that node's state row
Definition state.h:3023
A node of the network.
std::vector< RoutingStrategy > routing
sn.routing, per class.
The outcomes of State.pollingAdvance: full controller rows with weights.
std::vector< int > mode
1 visit, 2 switchover, 0 park
std::vector< std::size_t > q
the class a visit serves
std::vector< std::vector< long > > C
full controller vectors, width 5+R
std::vector< T > prob
Port of State.pollingInfo: the derived description of a polling controller.
std::vector< std::size_t > ring
1-based classes, length M
std::vector< std::vector< T > > t_pie
std::vector< std::size_t > itrt
std::vector< bool > swclass
the class drives a SWITCH event
lang::PollingOrder order
std::vector< bool > has_sw
std::vector< std::size_t > pos_of
1-based first position of each class
std::vector< std::size_t > ksw
std::vector< std::vector< T > > sw_pie
std::vector< std::size_t > tk
timer phases per class (0 = none)
std::size_t thr_class
1-based THRESHOLD class, 0 when none
lang::PollingTimer tmode
std::vector< Matrix< T > > sw_d0
std::vector< Matrix< T > > t_d1
std::vector< Matrix< T > > sw_d1
std::vector< bool > polled
std::vector< Matrix< T > > t_d0
lang::PollingType ptype
The population the *PRIO disciplines actually share the server among.
std::vector< T > nir
nirprio when masked, the plain marginal otherwise
bool served
false when cls is not in the most urgent group
double ni
niprio when masked, the plain total otherwise
bool masked
whether the saturated-station mask was applied
Where node ind keeps its reply-block counters inside the local vars.
std::vector< std::size_t > slot
slot[r-1] = 0-based column, or npos
std::vector< std::size_t > classes
1-based calling classes holding a block
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 > policy
MATLAB sn.retrialPolicy: 1 = LINEAR (per-job clocks), 2 = CONSTANT (one clock per orbit).
How a station's state row splits into [buffer | server | local vars].
std::size_t srvw
total server width
std::size_t bufw
buffer width, the only discipline-dependent part
std::vector< std::size_t > Ks
offset of class r's phase block
std::size_t nvar
local-variable width
std::vector< std::size_t > K
phases per class
The derived description of an RR station's quantum block, MATLAB's rinfo.
Definition rr_info.h:60
std::vector< std::vector< T > > qt
Definition rr_info.h:63
std::vector< std::vector< T > > qa
Definition rr_info.h:63
std::size_t col(std::size_t r, std::size_t k, std::size_t q) const
0-based column of m(r,k,q) inside the block; r, k, q 0-based.
Definition rr_info.h:70
std::vector< std::size_t > Q
Definition rr_info.h:61
std::size_t boff
Definition rr_info.h:66
std::vector< bool > markovian
Definition rr_info.h:64
std::vector< Matrix< T > > qT
Definition rr_info.h:62
The setup/delay-off layout of one station (python setup_info).
Definition ctmc_blocks.h:82
std::map< std::size_t, SetupLaw< T > > setup
keyed by 1-based class
Definition ctmc_blocks.h:87
std::map< std::size_t, SetupLaw< T > > delay
keyed by 1-based class
Definition ctmc_blocks.h:88
std::size_t ist
1-based station
Definition ctmc_blocks.h:84
std::size_t c
server count
Definition ctmc_blocks.h:85
std::size_t width
1 + setup phases + delay-off phases
Definition ctmc_blocks.h:86
One setup or delay-off law in phase-type form, and its offset in the block.
Definition ctmc_blocks.h:73
Matrix< T > S
sub-generator (D0)
Definition ctmc_blocks.h:75
std::vector< T > exit
exit rates -S e
Definition ctmc_blocks.h:76
std::size_t off
offset of phase 0 inside the block
Definition ctmc_blocks.h:77
One balking threshold: with min_jobs <= n <= max_jobs at the station, an arriving job of the class re...
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...
std::vector< BalkingParam > balking
std::vector< Distrib< T > > patience
Queue.setPatience(class, dist): the abandonment timer of a WAITING job, with impatience[r] naming whi...
double nservers
may be infinite (a Delay, or an inf-scheduled task)
CdScaling< T > jdscaling
sn.jdscaling for this station: MATLAB's Station.ljdScaling, the JOINT dependence map eta_i(n),...
std::vector< lang::ImpatienceType > impatience
CdScaling< T > cdscaling
sn.cdscaling for this station: the class-dependence map, empty when unset.
T orbit_search_of(std::size_t r) const
orbit_search[r] with the default 0 for a missing slot (0-based r).
T orbit_persist_of(std::size_t r) const
orbit_persist[r] with the default 1 for a missing slot (0-based r).
One half of a synchronization: an event at a node, in a class.
std::size_t cls
1-based class index
T prob
routing probability, passive half
std::size_t rt_row
(isf-1)*nclasses + (r-1) of the active half
std::size_t rt_col
(jsf-1)*nclasses + (s-1) of this passive half
std::size_t node
1-based node index, or local for the dummy
bool statedep
The routing probability is a FUNCTION of the network state, so prob holds only the state-independent ...
One synchronization: an ACTIVE event and the PASSIVE event it drives.
SyncEvent< T > passive
SyncEvent< T > active
The parameters of a Transition node: MATLAB sn.nodeparam{ind} for an SPN transition,...
std::vector< lang::TimingStrategy > timing
immediate or timed
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::size_t > firingphases
phase count per mode, 0 when non-Markovian
One successor of a pooled service start: the buffer, the servers, its weight and the class started.
One successor of promote: the row, its probability and the started class (0 for none).