LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_ssa_serial.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 */
5#ifndef LINE_SOLVERS_SSA_SOLVER_SSA_SERIAL_H
6#define LINE_SOLVERS_SSA_SOLVER_SSA_SERIAL_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * SolverSSA, the `serial` method: a port of `solver_ssa_reachability.m`, of the
12 * run loop of `solver_ssa.m`, and of `solver_ssa_analyzer_serial.m`.
13 *
14 * WHAT THE METHOD IS, AND HOW IT DIFFERS FROM THE NRM. The NRM rewrites the
15 * network as a reaction grid over (node, class, phase) counts and never touches
16 * the state ENCODING. The serial engine simulates the network in its own
17 * encoding instead: at every step it applies the SAME event handlers the CTMC
18 * generator applies (`after_event`, `after_global_event`) to the current network
19 * state, collects every enabled synchronization with its rate, and takes one
20 * Gillespie direct-method step. That is why it reaches models the NRM refuses --
21 * anything the encoding can express, the handlers can move -- and why it is
22 * slower: the enabled set is rebuilt from scratch at every firing, as the
23 * reference's own inlined `solver_ssa_findenabled` does.
24 *
25 * TWO ENGINES, TWO STREAMS. A seed-fixed result from the serial engine cannot be
26 * reproduced by the NRM and vice versa: they consume different draws in a
27 * different order. Neither can be reproduced by MATLAB, the JAR or native
28 * Python, for the reason `ssa_types.h` states at length. A cross-codebase check
29 * against this engine is STATISTICAL. A simulated number without its sample
30 * count and its seed is not a measurement, which is why `SsaSerialSolution`
31 * carries both and why the tests compare against the exact CTMC only inside a
32 * stated Monte Carlo band.
33 *
34 * THE JUMP CHAIN IS DRAWN IN ONE STEP, NOT TWO. MATLAB calls `State.afterEvent`
35 * with `isSimulation = true`, which SAMPLES one successor row and returns its
36 * probability; the direct method then picks among the sampled rows. The C++
37 * `after_event` is the enumeration-mode handler and returns EVERY successor with
38 * its probability, so this port flattens the (synchronization, active row,
39 * passive row) triples into one weighted list and draws from it once. The two
40 * are the same jump chain -- P(triple) = rate * p_active * p_route * p_passive,
41 * normalized -- reached with a different number of uniforms, which is exactly
42 * the stream difference above and not a modelling difference.
43 *
44 * ZERO-RATE ROWS ARE DROPPED, NOT FLOORED. The reference rewrites a zero or NaN
45 * rate to 1e-38 "so that it is never selected", which leaves it in the enabled
46 * list and in the arrival/departure rate statistics. Dropping it is the same
47 * sample path to within 1e-38 and keeps `depRates` exactly the rate the CTMC
48 * generator would accumulate for the same state, which is what makes the
49 * throughput comparable between the two solvers.
50 *
51 * THE STATE ROW DOES NOT GROW HERE, SO IT STARTS WIDE. MATLAB's simulation-mode
52 * handlers widen a buffer when a job arrives and no slot is free, and
53 * `solver_ssa_reachability` left-pads the stored spaces to match. The C++
54 * handlers derive the buffer width from the row they are handed, so a path
55 * seeded at the natural width of the EMPTY marginal would silently saturate at
56 * one waiting job per station. The initial state is therefore padded to the
57 * WIDEST row each stateful node's local encoding admits (`serial_detail::
58 * max_row_width`), which is the width `space_generator` gives every state of
59 * that node, and the path then lives inside the enumerated encoding for free.
60 *
61 * DOUBLE ONLY, for the reason `solver_ssa_nrm.h` gives: the sample path is
62 * generated from exponential clocks drawn as `-log(u)`, there is no exact value
63 * to compute, and the answer's error is the Monte Carlo error rather than the
64 * rounding. A non-`double` backend is refused BY NAME.
65 */
66
67#include <algorithm>
68#include <cmath>
69#include <cstddef>
70#include <limits>
71#include <map>
72#include <memory>
73#include <string>
74#include <type_traits>
75#include <vector>
76
79#include "line/lang/qn/fj_tag.h"
82#include "line/lang/qn/state.h"
89#include "line/util/error.h"
91#include "line/util/matrix.h"
92
93namespace line {
94namespace ssa {
95
96/**
97 * The serial engine's knobs: `SsaOptions` plus the three the serial path reads
98 * and the NRM has no use for.
99 *
100 * `cutoff` (declared on the base, see `SsaOptions::cutoff`) bounds an open class exactly as SolverCTMC's does, and for the same
101 * reason: it fixes how wide a station's buffer encoding is, so it decides where
102 * the truncation sits. A refused arrival at the truncation boundary is a LOSS
103 * (`arrival_is_lost` on an open class), which is what the CTMC truncation does
104 * too, so the two solvers truncate the same model the same way.
105 */
107 std::size_t state_max = 3000000; ///< refuse a reachable space larger than this
108};
109
110/**
111 * Port of `solver_ssa_reachability.m`'s return: `[SSq, SSh, sn.space]`.
112 *
113 * `node_space[i]` is the reference's `space{i}`, the distinct local rows node
114 * `i` was seen in; `hash` is `SSh`, one 1-BASED index into `node_space[i]` per
115 * stateful node per state; `ssq` is `SSq`, the same states with their local rows
116 * concatenated. The three are redundant by construction and the reference
117 * returns all three because its callers index states by node (`SSh`) and read
118 * them flat (`SSq`).
119 *
120 * THE ORDER IS THE WALK'S, NOT THE REFERENCE'S. The reference pushes and pops a
121 * stack of its own; this reuses `reachable_space_generator`, whose stack order
122 * differs. The SET is the same and nothing downstream indexes it positionally
123 * across codebases, so the difference is not observable in a metric.
124 */
125template <class T>
127 std::vector<qn::NetState<T>> space; ///< the reachable states
128 std::vector<std::vector<std::vector<T>>> node_space; ///< `sn.space`, per stateful node
129 std::vector<std::vector<std::size_t>> hash; ///< `SSh`, 1-based per node
130 Matrix<T> ssq; ///< `SSq`, states x concatenated width
131};
132
133/** One sample path, in the shape `solver_ssa.m` returns it. */
134template <class T>
136 /** The DISTINCT states visited, in first-visit order (the reference's `u`). */
137 std::vector<qn::NetState<T>> space;
138 /**
139 * The region token FIFOs of each of those states, the reference's `fcrBuf`.
140 *
141 * Empty (one empty vector per region, or no vectors at all) on every model
142 * without a WAITQ region. A parked job is in NO station, so it appears in no
143 * queue length and is visible only here -- the JMT report convention, which
144 * `ctmc_waitq_parked` states for the exact solver and
145 * `SsaSerialSolution::parked` for this one.
146 */
147 std::vector<std::vector<std::vector<std::size_t>>> buf;
148 /** `pi`: the fraction of simulated time spent in each of them. */
149 std::vector<double> pi;
150 /** `SSq`: the per-(station, class) job counts of each distinct state. */
152 /**
153 * `arvRates` / `depRates`, indexed [distinct state][stateful-1][class-1].
154 *
155 * They are a deterministic function of the state, so one sample per state is
156 * the exact value and not an estimate -- which is what lets the analyzer
157 * multiply them by `pi` and get a throughput rather than a sample mean. The
158 * reference says as much where it keeps `arvRatesSamples(ui(s),...)`.
159 */
160 std::vector<std::vector<std::vector<double>>> arv_rates, dep_rates;
161 /**
162 * The DERIVED rates per state, laid out like `arv_rates`: how fast the
163 * transitions enabled in that state START a class-r service at a stateful
164 * node, and how fast they PUSH a class-r job in service back into the
165 * buffer there. Annotations on the arcs the engine already walks, so no
166 * rate, probability or state depends on them.
167 */
168 std::vector<std::vector<std::vector<double>>> start_rates, preempt_rates;
169 /**
170 * The rate of the cache MERGE transitions, i.e. of the delayed hits, in the
171 * same [state][stateful-1][class-1] shape and by the same argument.
172 *
173 * A delayed hit is invisible in `dep_rates`: the merged request is released
174 * later, in the HIT class, and is indistinguishable there from a true hit.
175 * The merge itself is the only cache transition that EMPTIES the node -- it
176 * decrements the read class and adds nothing -- which is what identifies it.
177 */
178 std::vector<std::vector<std::vector<double>>> dly_rates;
179 /** `tranSysState{1}`: the cumulative time at each firing. */
180 std::vector<double> tran_time;
181 /** `tranSync`: which synchronization fired, `sync.size() + g` for a global one. */
182 std::vector<std::size_t> tran_sync;
183 /**
184 * The row of `space` the path OCCUPIED over `[t-dt, t]`, one per firing.
185 *
186 * The trace and the distinct-state table are two views of the same path and
187 * the samplers need both: `sampleSys` prints the state at each event and
188 * `getProb` sums the time spent in one state, so keeping only `pi` would
189 * lose the order and keeping only the rows would lose the aggregation. It
190 * indexes the state BEFORE the firing, exactly as `pi` weights it.
191 */
192 std::vector<std::size_t> tran_state;
193 double simulated_time = 0.0;
194 std::size_t samples = 0; ///< firings actually performed
195 std::size_t warmup = 0; ///< leading firings excluded from `pi`
196 unsigned long seed = 0; ///< the stream this path came from
197};
198
199/** The serial analyzer's return: the metric table, the path, and the stream. */
200template <class T>
202 SsaSolution avg; ///< QN, UN, RN, TN, XN, CN; `method` = "serial"
204 unsigned long seed = 0; ///< carried beside the numbers, never implied
205 std::vector<SsaCacheRatio> cache;
206 /**
207 * `fjclassmap` of the tag augmentation, empty on a model with no Fork.
208 *
209 * The PATH inside `run` is the augmented one -- its classes are the sibling
210 * classes `fj_tag` invented -- while `avg` has been folded back onto the
211 * classes the caller declared. The map is what relates the two, and it is
212 * returned rather than discarded for the reason SolverCTMC returns it: a
213 * caller reading the trajectory needs to know which class a sibling came
214 * from.
215 */
216 std::vector<std::size_t> fjclassmap;
217 /**
218 * Mean number of jobs parked in a region FIFO, per class of the struct that
219 * ran. Zero everywhere without a WAITQ region.
220 *
221 * IT IS IN NO QLen, so a population check on a closed model has to add it
222 * back by hand. That is the JMT convention `ctmc_waitq_parked` reports for
223 * the exact solver and not an omission here.
224 */
225 std::vector<double> parked;
226 /**
227 * The struct the path was simulated on when it differs from the caller's (`ctmc_mapc` widens
228 * a multiserver MAP server block into pairs), else null. The rows of `run` are in ITS layout.
229 */
230 std::shared_ptr<const qn::NetworkStruct<T>> solved_sn;
231};
232
233namespace serial_detail {
234
235using lang::NodeType;
237
238/**
239 * `solver_ssa.m`'s own guards, plus what this port cannot represent.
240 *
241 * Reneging and QUEUE_LENGTH balking are simulated: `refresh_sync` emits a RENEGE
242 * action from the station's own patience and the arrival handler applies the
243 * balking band. What the state machinery cannot serve (non-exponential patience,
244 * wait-based balking) is refused through `state_impatience_unsupported`, the
245 * CTMC's own list. Heterogeneous servers (`nodeparam.nservertypes`) have no
246 * field in the C++ `NetworkStruct`, so that guard would be dead code. The same
247 * holds for the class-switch mask violation the reference
248 * raises inside its scan: `sn.csmask` is not carried, and the state-dependent
249 * routing that can violate it is refused when the struct is built.
250 */
251template <class T>
252bool serial_check(const qn::NetworkStruct<T>& sn, bool raise = true, bool skip_fork = false) {
253 const std::string impatience = qn::state_impatience_unsupported(sn, "SolverSSA(method='serial')");
254 if (!impatience.empty()) {
255 if (!raise) return false;
256 throw UnsupportedError(ErrorKind{"Impatience"}, impatience);
257 }
258 // A WAITQ region parks refused jobs in a FIFO the engine carries beside the
259 // network state, and the combinations that FIFO has no meaning against are
260 // the CTMC's own: one list, so the two solvers refuse the same models with
261 // the same sentence and neither can silently accept what the other rejects.
262 if (!sn.regions.empty()) {
263 // The rule decides which machinery runs, so the gate is the matching
264 // one: `ctmc_check_waitq_support` for the token FIFO, and the DROP-only
265 // checker otherwise, which is what refuses BAS/BBS/RSRD by name.
266 try {
269 else
271 } catch (const UnsupportedError&) {
272 if (!raise) return false;
273 throw;
274 }
275 }
276 // A Fork fires through `fjsync`, which only the TAG-AUGMENTED struct carries
277 // (`fj_tag`). A raw fork-join struct reaching the engine would find no
278 // firing at all: the fork would never emit, the branches would stay empty
279 // and the path would report a network that transparently swallows every
280 // forked task. The analyzer augments before it runs, so this refusal is
281 // reachable only by a caller who drove the engine directly.
282 if (!skip_fork && sn.has_fork() && !sn.isfjaugmented) {
283 if (!raise) return false;
284 throw UnsupportedError(ErrorKind{"Fork"},
285 "SolverSSA(method='serial'): the model contains a Fork node and has not been "
286 "tag-augmented. A fork fires through `sn.fjsync` / `State.afterFJEvent`, which only "
287 "`fj_tag` builds; call `solver_ssa_serial_analyzer`, which augments and folds the "
288 "sibling classes back, rather than the engine directly");
289 }
290 for (std::size_t i = 0; i < sn.nstations; ++i) {
291 const typename std::map<std::size_t, qn::RetrialParam<T>>::const_iterator rit =
292 sn.retrialparam.find(i + 1);
293 if (rit == sn.retrialparam.end()) continue;
294 bool any = false;
295 std::size_t served = 0;
296 for (std::size_t r = 0; r < rit->second.retrial_proc.size(); ++r) {
297 if (rit->second.retrial_proc[r].disabled) continue;
298 any = true;
299 if (rit->second.retrial_proc[r].type != lang::ProcessType::EXP) {
300 if (!raise) return false;
301 throw UnsupportedError(ErrorKind{"Retrial"},
302 "SolverSSA(method='serial'): station '" + sn.stations[i].name +
303 "' retries with non-exponential patience. SOLVER_SSA supports only "
304 "exponential (memoryless) retrial delay in every codebase, because the orbit "
305 "carries no remaining-delay phase");
306 }
307 if (r < rit->second.max_attempts.size() && rit->second.max_attempts[r] > 0) {
308 if (!raise) return false;
309 throw UnsupportedError(ErrorKind{"Retrial"},
310 "SolverSSA(method='serial'): station '" + sn.stations[i].name +
311 "' declares a finite retrial max-attempts count. SOLVER_SSA supports only "
312 "unlimited retrials in every codebase, because the attempt counter is not "
313 "part of the state");
314 }
315 if (r < sn.stations[i].orbit_impatience.size() &&
316 !sn.stations[i].orbit_impatience[r].disabled) {
317 if (!raise) return false;
318 throw UnsupportedError(ErrorKind{"Retrial"},
319 "SolverSSA(method='serial'): station '" + sn.stations[i].name +
320 "' declares abandonment from the retrial orbit. SOLVER_SSA does not model "
321 "it in any codebase; use SolverMAM or SolverLDES");
322 }
323 }
324 if (!any) continue;
325 for (std::size_t r = 0; r < sn.nclasses; ++r)
326 if (!sn.disabled[i][r] && sn.service[i][r].D0.rows() > 0) ++served;
327 if (served > 1) {
328 if (!raise) return false;
329 throw UnsupportedError(ErrorKind{"Retrial"},
330 "SolverSSA(method='serial'): station '" + sn.stations[i].name +
331 "' is a multi-class retrial station. SOLVER_SSA supports retrial only for "
332 "single-class stations in every codebase");
333 }
334 }
335 return true;
336}
337
338/**
339 * Time-averaged servers held for a pending REPLY signal, per (station, calling class).
340 *
341 * Port of `ssa_reply_held.m`. A job of a class with a synchronous call leaves its caller
342 * but keeps the server there until the reply returns; the hold lives in the reply block
343 * that trails the caller's local row (`reply_block_info`), where `to_marginal` does not
344 * see it. All zero for a model without synchronous calls.
345 */
346template <class T>
347Matrix<double> reply_held(const qn::NetworkStruct<T>& sn, const SsaSerialRun<T>& r) {
348 const std::size_t M = sn.nstations, K = sn.nclasses;
349 Matrix<double> held(M, K, 0.0);
350 if (sn.replyblock.empty()) return held;
351 for (std::size_t ist = 1; ist <= M; ++ist) {
352 const std::size_t ind = sn.node_of_station(ist);
353 const std::size_t isf = sn.stateful_of_station(ist);
354 if (isf == 0 || sn.replyblock.size() < ind) continue;
355 bool any = false;
356 for (std::size_t k = 0; k < sn.replyblock[ind - 1].size(); ++k)
357 any = any || sn.replyblock[ind - 1][k];
358 if (!any) continue;
359 const qn::ReplyBlockInfo info = qn::reply_block_info(sn, ind);
360 if (info.width == 0) continue;
361 for (std::size_t s = 0; s < r.space.size() && s < r.pi.size(); ++s) {
362 if (r.pi[s] == 0) continue;
363 const std::vector<T>& row = r.space[s].local[isf - 1];
364 // the block trails the row; a buffer grows on the left only
365 for (std::size_t pos = 0; pos < info.classes.size(); ++pos) {
366 const std::size_t col = row.size() - info.width + pos;
367 held(ist - 1, info.classes[pos] - 1) += r.pi[s] * num_traits<T>::to_double(row[col]);
368 }
369 }
370 }
371 return held;
372}
373
374/**
375 * TRUE BAS (BUG-110) destination attribution of held jobs, the SSA twin of the
376 * shift in `solver_ctmc_avg_from_pi` and of MATLAB `ssa_bas_held.m`, JAR
377 * `Solver_ssa_analyzer_serial.applyBasHeld` and python `serial.py`
378 * `_add_bas_held`.
379 *
380 * A held job sits at its blocking station in the state, but it has FINISHED
381 * service there and is waiting to enter its target, so its time-averaged count
382 * per target code moves from QN(ist, r) to QN(jst, s); at an INF holding station
383 * the utilization is the queue length, so UN(ist, r) loses the same share. RN is
384 * read afterwards from the shifted QN. A model without true BAS is untouched.
385 */
386template <class T>
387void apply_bas_held(const qn::NetworkStruct<T>& sn, const SsaSerialRun<T>& r,
388 Matrix<double>& QN, Matrix<double>& UN) {
389 if (sn.isbasblocking.empty()) return;
390 for (std::size_t ist = 1; ist <= sn.nstations; ++ist) {
391 const std::size_t ind = sn.node_of_station(ist);
392 const std::size_t isf = sn.stateful_of_station(ist);
393 if (ind == 0 || isf == 0 || ind > sn.isbasblocking.size()) continue;
394 if (!sn.isbasblocking[ind - 1]) continue;
395 const std::vector<std::size_t> codes = sn.bas_marker_codes(ind);
396 if (codes.empty()) continue;
397 const std::size_t nc = qn::NetworkStruct<T>::bas_ncols(codes);
398 const bool inf = sn.stations[ist - 1].sched == lang::SchedStrategy::INF;
399 for (std::size_t kk = 0; kk < codes.size(); ++kk) {
400 std::size_t rr = 0, jst = 0, ss = 0;
401 sn.bas_decode(codes[kk], rr, jst, ss);
402 double shift = 0.0;
403 for (std::size_t s = 0; s < r.space.size() && s < r.pi.size(); ++s) {
404 if (r.pi[s] == 0) continue;
405 const std::vector<T>& row = r.space[s].local[isf - 1];
406 if (row.size() < nc) continue;
407 shift += r.pi[s] * num_traits<T>::to_double(row[row.size() - nc + kk]);
408 }
409 if (!(shift > 0)) continue;
410 QN(ist - 1, rr - 1) -= shift;
411 QN(jst - 1, ss - 1) += shift;
412 if (inf) UN(ist - 1, rr - 1) -= shift;
413 }
414 }
415}
416
417/**
418 * Can `solver_ssa_serial_analyzer` run this model at all?
419 *
420 * The dispatcher's fallback test, and it is the SAME body as the refusal above
421 * so the two cannot drift. The fork guard is skipped because the analyzer
422 * augments before the engine sees the struct, so a raw fork-join model IS one
423 * the serial path runs -- answering otherwise would send it back to the NRM,
424 * which excludes fork-join in every codebase.
425 */
426template <class T>
427bool serial_can_run(const qn::NetworkStruct<T>& sn) {
428 return serial_check(sn, false, true);
429}
430
431/**
432 * The widest local row stateful node `ind` admits, which is the width
433 * `space_generator` gives EVERY state of that node.
434 *
435 * WHY IT IS COMPUTED RATHER THAN ENUMERATED. Taking the width from
436 * `space_generator` would mean building the whole cartesian product across
437 * nodes, which is the cost simulation exists to avoid. The width of one node's
438 * row is a property of that node alone: for an ordered (class-tag) buffer it
439 * grows with the TOTAL jobs held and not with how they split across classes, and
440 * for every other encoding it is constant. So one call to `from_marginal_node`
441 * at a maximal admissible marginal settles it, and the split is chosen to fill
442 * the classes in order precisely because a lopsided multiset has the fewest
443 * permutations for `from_marginal` to enumerate.
444 *
445 * The descent to a smaller total is not defensive padding: `from_marginal_node`
446 * returns NO rows for a marginal the station cannot hold, and the joint bound
447 * (`cap` against the sum of the per-class bounds) can be met by a marginal that
448 * some other constraint inside the handler still rejects.
449 */
450template <class T>
451std::size_t max_row_width(const qn::NetworkStruct<T>& sn, std::size_t ind,
452 const std::vector<std::size_t>& cutoff) {
453 const std::size_t R = sn.nclasses;
454 const std::size_t ist = sn.nodes[ind - 1].station;
455 std::vector<std::size_t> ph(R, 1);
456 if (ist != 0)
457 for (std::size_t r = 0; r < R; ++r) ph[r] = sn.phasessz_of(ist, r + 1);
458
459 // A stateful non-station (a Cache, a Join, a Transition) holds a per-class
460 // count and its local variables, both of fixed width, so the empty marginal
461 // already gives the final width.
462 if (ist == 0 || sn.stations[ist - 1].nodetype == NodeType::Source) {
463 std::vector<T> row;
464 if (!qn::from_marginal_node_first(sn, ind, std::vector<std::size_t>(R, 0), ph, row))
465 throw UnsupportedError(ErrorKind{"Model"}, "SolverSSA(method='serial'): node '" + sn.nodes[ind - 1].name +
466 "' admits no state at all, so no sample path can start");
467 return row.size();
468 }
469
470 // The per-class bound: the class population when closed, the cutoff when
471 // open, never above the station's own per-class capacity.
472 std::vector<std::size_t> bound(R, 0);
473 for (std::size_t r = 0; r < R; ++r) {
474 const double nj = sn.njobs()[r];
475 double b = std::isfinite(nj) ? nj : static_cast<double>(cutoff[r]);
476 const double cc = sn.classcap[ist - 1][r];
477 if (cc < b) b = cc;
478 if (!(b > 0)) b = 0;
479 bound[r] = static_cast<std::size_t>(b);
480 }
481 double tcapd = sn.cap[ist - 1];
482 std::size_t total = 0;
483 for (std::size_t r = 0; r < R; ++r) total += bound[r];
484 if (std::isfinite(tcapd) && tcapd < static_cast<double>(total))
485 total = static_cast<std::size_t>(tcapd);
486
487 // A PAS / OI station is the one encoding `from_marginal_node` cannot size:
488 // its row is the ORDERED JOB LIST, one position per job, and the function
489 // builds the ordinary [buffer | server] split instead -- which for a
490 // single-server station returns a ONE-COLUMN row however many jobs the
491 // marginal holds. A path seeded at that width would hold one job and block
492 // every further arrival, so the width is taken from the job bound directly.
493 if (sn.stations[ist - 1].sched == SchedStrategy::PAS ||
494 sn.stations[ist - 1].sched == SchedStrategy::OI)
495 return total + sn.nvars_of(ind);
496
497 for (std::size_t t = total + 1; t-- > 0;) {
498 std::vector<std::size_t> n(R, 0);
499 std::size_t left = t;
500 for (std::size_t r = 0; r < R && left > 0; ++r) {
501 n[r] = std::min(left, bound[r]);
502 left -= n[r];
503 }
504 if (left > 0) continue; // this total does not fit the per-class bounds
505 const std::vector<std::vector<T>> rows = qn::from_marginal_node(sn, ind, n, ph);
506 if (!rows.empty()) return rows[0].size();
507 }
508 throw UnsupportedError(ErrorKind{"Model"}, "SolverSSA(method='serial'): station '" + sn.stations[ist - 1].name +
509 "' admits no state at all, so no sample path can start");
510}
511
512/**
513 * The initial network state, padded to the encoding width of every node.
514 *
515 * The marginal is `Network.initDefault`'s -- every closed class's jobs at its
516 * reference station -- taken from the CTMC analyzer so the two solvers start the
517 * same model in the same state. The LEFT pad is not a convention chosen here: it
518 * is what `space_generator` does to the narrow rows, and every slicer in
519 * `state_events.h` measures its blocks from the RIGHT-hand end, so a right pad
520 * would shift the server block and silently decode the wrong queue.
521 */
522template <class T>
523qn::NetState<T> wide_init_state(const qn::NetworkStruct<T>& sn,
524 const std::vector<std::size_t>& cutoff) {
525 qn::NetState<T> init;
526 if (!ctmc::analyzer_detail::default_init_state(sn, init))
527 throw UnsupportedError(ErrorKind{"Model"},
528 "SolverSSA(method='serial'): the model's initial state admits no state; check the "
529 "class populations against their reference stations");
530 for (std::size_t f = 0; f < sn.stateful_nodes.size(); ++f) {
531 const std::size_t w = max_row_width(sn, sn.stateful_nodes[f], cutoff);
532 if (init.local[f].size() > w) continue; // already at or beyond the encoding width
533 init.local[f].insert(init.local[f].begin(), w - init.local[f].size(),
534 num_traits<T>::from_int(0));
535 }
536 return init;
537}
538
539} // namespace serial_detail
540
541/**
542 * Port of `solver_ssa_reachability.m`: the states the DYNAMICS can occupy,
543 * decomposed per stateful node.
544 *
545 * The walk itself is `reachable_space_generator`, which applies the same
546 * handlers to the same synchronization list and additionally walks `gsync`. The
547 * reference's reachability walks only `sync`, so an SPN's firing states reach it
548 * through `solver_ssa`'s own global scan instead of through this function; here
549 * they are in the space from the start, which is strictly more of the reachable
550 * set and never less.
551 *
552 * WHAT THIS ADDS OVER THE WALK is the decomposition the reference returns and
553 * the CTMC does not need: the per-node list of distinct local rows, and the
554 * per-state index into it. That is the reference's `space{i}` / `SSh` pair, and
555 * it exists so a caller can address a state by node without carrying the rows.
556 */
557template <class T>
560 serial_detail::serial_check(sn);
562 copt.cutoff = opt.cutoff;
563 copt.state_max = opt.state_max;
564 const std::vector<std::size_t> cutoff = ctmc::analyzer_detail::resolve_cutoff(sn, copt);
565 const std::vector<qn::Sync<T>> sync = qn::refresh_sync(sn);
566 const std::vector<qn::GlobalSync<T>> gsync = qn::refresh_global_sync(sn);
567 const qn::NetState<T> init = serial_detail::wide_init_state(sn, cutoff);
568
570 // A WAITQ region's states are AUGMENTED with the token FIFO, which a
571 // `NetState` cannot hold, so this decomposition has no row to report them
572 // in and refuses rather than returning the region-free walk under the
573 // region's name. The metrics do not need it: the engine carries the FIFO
574 // itself and `SsaSerialRun::buf` reports it.
576 throw UnsupportedError(ErrorKind{"Region"},
577 "solver_ssa_reachability: the model declares a WAITQ finite capacity region, whose "
578 "states carry a per-region token FIFO outside every node; this decomposition is "
579 "per-node and cannot represent it. Use `solver_ssa_serial_analyzer`, whose run carries "
580 "the FIFO, or `solver_ctmc_waitq` for the exact augmented space");
581 // The cutoff resolved above bounds the walk, as it bounds SolverCTMC's:
582 // without it an open model's Source produces forever and the walk runs to
583 // `state_max` rather than answering.
584 out.space = ctmc::reachable_space_generator(sn, init, sync, gsync, opt.state_max,
585 std::vector<qn::FjSync<T>>(), cutoff);
586 // A DROP region censors the space exactly as it censors SolverCTMC's: the
587 // forbidden states are never occupied, so leaving them in would report a
588 // reachable set the dynamics cannot reach.
590
591 const std::size_t NF = sn.stateful_nodes.size();
592 out.node_space.assign(NF, std::vector<std::vector<T>>());
593 out.hash.assign(out.space.size(), std::vector<std::size_t>(NF, 0));
594 // One map per node, keyed on the row itself: the reference's `matchrow`,
595 // which is a linear scan and turns the decomposition quadratic on a space
596 // large enough to be worth walking.
597 std::vector<std::map<std::vector<double>, std::size_t>> seen(NF);
598 for (std::size_t s = 0; s < out.space.size(); ++s)
599 for (std::size_t f = 0; f < NF; ++f) {
600 std::vector<double> key(out.space[s].local[f].size(), 0.0);
601 for (std::size_t j = 0; j < key.size(); ++j)
602 key[j] = num_traits<T>::to_double(out.space[s].local[f][j]);
603 const typename std::map<std::vector<double>, std::size_t>::const_iterator it =
604 seen[f].find(key);
605 if (it != seen[f].end()) {
606 out.hash[s][f] = it->second;
607 } else {
608 out.node_space[f].push_back(out.space[s].local[f]);
609 seen[f][key] = out.node_space[f].size();
610 out.hash[s][f] = out.node_space[f].size();
611 }
612 }
613
614 std::size_t width = 0;
615 for (std::size_t f = 0; f < NF; ++f)
616 width += out.space.empty() ? 0 : out.space[0].local[f].size();
617 out.ssq = Matrix<T>(out.space.size(), width, num_traits<T>::from_int(0));
618 for (std::size_t s = 0; s < out.space.size(); ++s) {
619 std::size_t col = 0;
620 for (std::size_t f = 0; f < NF; ++f)
621 for (std::size_t j = 0; j < out.space[s].local[f].size(); ++j)
622 out.ssq(s, col++) = out.space[s].local[f][j];
623 }
624 return out;
625}
626
627/**
628 * The serial engine: the sample path of `solver_ssa.m`'s main loop.
629 *
630 * It is a class for the reason `NrmEngine` is: the loop threads the current
631 * state, the visited-state table, the two rate tables and the trace through
632 * every step, and the reference threads the same through one long function.
633 */
634template <class T>
636public:
637 /**
638 * `fjsync` is the fork firing list of the TAG-AUGMENTED struct, empty for a
639 * model with no Fork. It is passed in rather than derived because the
640 * augmentation produces the struct and the firing list together and `sn`
641 * must be the augmented one: deriving it here would leave the two able to
642 * disagree about which classes the branches carry.
643 */
645 const std::vector<qn::FjSync<T>>& fjsync = std::vector<qn::FjSync<T>>())
646 : sn_(sn), opt_(opt), rng_(opt.seed), fjsync_(fjsync) {
647 serial_detail::serial_check(sn);
649 copt.cutoff = opt.cutoff;
650 copt.state_max = opt.state_max;
651 const std::vector<std::size_t> cutoff = ctmc::analyzer_detail::resolve_cutoff(sn, copt);
652 sync_ = qn::refresh_sync(sn);
653 gsync_ = qn::refresh_global_sync(sn);
654 sdr_ = sn.has_rtfun_routing();
655 // WHICH REGION MACHINERY, decided exactly as SolverCTMC decides it: a
656 // model whose every region class applies DROP is CENSORED, because a
657 // refused job is destroyed and the chain simply never occupies the
658 // forbidden states; one WAITQ class anywhere puts the whole model on the
659 // token-FIFO relation, which handles its DROP classes inline. Choosing
660 // differently from the CTMC here would make the simulator and the exact
661 // solver answer different models under one model file.
663 if (!sn.regions.empty()) {
664 if (waitq_) {
665 caps_ = ctmc::waitq_detail::extract_caps(sn);
666 ctmc::waitq_detail::resolve_lmax(sn, cutoff, caps_);
667 } // the DROP-only rule set is checked by `serial_check` above
668 }
669 init_bas();
670 // The initial row carries the zeroed held-job block of every true-BAS
671 // station: `from_marginal` emits the zero held vector first, and the
672 // left pad below never touches the trailing block.
673 init_.net = serial_detail::wide_init_state(sn, cutoff);
674 init_.buf.assign(caps_.size(), std::vector<std::size_t>());
675 if (!sn.regions.empty() && !region_admissible(init_.net))
676 throw InputError(
677 "SolverSSA(method='serial'): the model's initial state violates a finite capacity "
678 "region; the region cannot hold the model's initial population, so no sample path "
679 "can start");
680 }
681
682 /** Run `opt.samples` firings and return the path with its statistics. */
684
685 /** The synchronization list the trace's `tran_sync` indexes. */
686 const std::vector<qn::Sync<T>>& sync() const { return sync_; }
687 /** The state the path starts from, at full encoding width. */
688 const qn::NetState<T>& init_state() const { return init_.net; }
689
690private:
691 /** One enabled transition: where it goes and what it contributes. */
692 struct Move {
693 std::size_t sync = 0; ///< index into `sync_`, or `sync_.size() + g`
694 double weight = 0.0; ///< rate * p_active * p_route * p_passive
696 };
697
698 const qn::NetworkStruct<T>& sn_;
699 SsaSerialOptions opt_;
700 SsaRng rng_;
701 std::vector<qn::Sync<T>> sync_;
702 std::vector<qn::GlobalSync<T>> gsync_;
703 std::vector<qn::FjSync<T>> fjsync_;
704 std::vector<ctmc::waitq_detail::RegionCaps<T>> caps_;
705 bool waitq_ = false;
706 /** The routing must be re-evaluated at every state visited (Krzesinski SDR). */
707 bool sdr_ = false;
709
710 /**
711 * TRUE BAS (BUG-110), per synchronization: what the CTMC generator works out
712 * per sync before its state loop, computed once here because the path visits
713 * one state at a time. `on` marks a DEP from a true-BAS blocking station to a
714 * stateful node; `tgt` is 1 + the block position of this sync's target code
715 * (class, destination station, arriving class), 0 when that target never
716 * refuses and so has no counter.
717 */
718 struct BasSync {
719 bool on = false;
720 std::vector<std::size_t> codes;
721 std::size_t nc = 0, tgt = 0, ist = 0;
722 bool single = false;
723 std::vector<std::size_t> ph, shift;
724 };
725 std::vector<BasSync> bas_;
726
727 void init_bas() {
728 const std::size_t local = sn_.nodes.size() + 1;
729 bas_.assign(sync_.size(), BasSync());
730 for (std::size_t a = 0; a < sync_.size(); ++a) {
731 const qn::Sync<T>& sy = sync_[a];
732 const std::size_t na = sy.active.node, np = sy.passive.node;
733 if (sy.active.event != lang::EventType::DEP || np == local || na == 0 ||
734 na > sn_.isbasblocking.size() || !sn_.isbasblocking[na - 1] ||
735 sn_.nodes[na - 1].station == 0)
736 continue;
737 BasSync& b = bas_[a];
738 b.on = true;
739 b.codes = sn_.bas_marker_codes(na);
740 b.nc = qn::NetworkStruct<T>::bas_ncols(b.codes);
741 b.ist = sn_.nodes[na - 1].station;
742 b.single = sn_.bas_single_server(b.ist);
743 const std::size_t jst = sn_.nodes[np - 1].station;
744 if (jst != 0) {
745 const std::size_t code = sn_.bas_code(sy.active.cls, jst, sy.passive.cls);
746 for (std::size_t k = 0; k < b.codes.size(); ++k)
747 if (b.codes[k] == code) b.tgt = k + 1;
748 }
749 std::size_t w = 0;
750 for (std::size_t k = 1; k <= sn_.nclasses; ++k) {
751 b.ph.push_back(sn_.phasessz_of(b.ist, k));
752 b.shift.push_back(w);
753 w += b.ph.back();
754 }
755 }
756 }
757
758 /** `ctmc_region_admissible` on one network state, the DROP censoring test. */
759 bool region_admissible(const qn::NetState<T>& st) const {
760 if (sn_.regions.empty()) return true;
761 std::vector<qn::NetState<T>> one(1, st);
762 const Matrix<T> A = ctmc::ctmc_state_space_aggr(sn_, one);
763 std::vector<T> nir(A.cols());
764 for (std::size_t c = 0; c < A.cols(); ++c) nir[c] = A(0, c);
765 return ctmc::ctmc_region_admissible(sn_, nir);
766 }
767
768 /**
769 * The reference's inlined `solver_ssa_findenabled`: every synchronization
770 * that can fire in `st`, with the arrival and departure rates it carries.
771 */
772 void enabled(const ctmc::WaitqState<T>& st, std::vector<Move>& moves,
773 std::vector<std::vector<double>>& arv, std::vector<std::vector<double>>& dep,
774 std::vector<std::vector<double>>& dly,
775 std::vector<std::vector<double>>& start,
776 std::vector<std::vector<double>>& preempt) const;
777
778 /**
779 * `phi(n)` on the CURRENT sample-path state, as an (nstations*nclasses)
780 * row-major vector of scalings. The twin of `ctmc_gd_factor`'s single row.
781 */
782 std::vector<T> gd_factor_now(const qn::NetState<T>& ns) const {
783 const std::size_t M = sn_.stations.size(), K = sn_.nclasses;
784 const T zero = num_traits<T>::from_int(0);
785 std::vector<T> npop(M * K, zero);
786 for (std::size_t ist = 1; ist <= M; ++ist) {
787 const std::size_t isf = sn_.stateful_of_station(ist);
788 if (isf == 0) continue;
789 if (sn_.stations[ist - 1].nodetype == lang::NodeType::Source) continue;
790 const std::size_t ind = sn_.node_of_station(ist);
791 std::vector<std::size_t> ph(K, 1), shift(K, 0);
792 std::size_t w = 0;
793 for (std::size_t k = 0; k < K; ++k) {
794 ph[k] = sn_.phasessz_of(ist, k + 1);
795 shift[k] = w;
796 w += ph[k];
797 }
798 const qn::Marginal<T> m =
799 qn::to_marginal(sn_, ist, ns.local[isf - 1], ph, shift, sn_.nvars_of(ind));
800 for (std::size_t k = 0; k < K; ++k) npop[(ist - 1) * K + k] = m.nir[k];
801 }
802 const std::vector<T> v = sn_.gdscaling(npop);
803 std::vector<T> out(M * K, num_traits<T>::from_int(1));
804 for (std::size_t i = 0; i < M; ++i)
805 for (std::size_t r = 0; r < K; ++r) {
806 const T f = v.size() == 1 ? v[0] : (v.size() == M ? v[i] : v[i * K + r]);
807 if (!(num_traits<T>::to_double(f) >= 0))
808 throw InputError(
809 "the global dependence handle returned a non-finite or negative scaling");
810 out[i * K + r] = f;
811 }
812 return out;
813 }
814};
815
816template <class T>
817void SsaSerialEngine<T>::enabled(const ctmc::WaitqState<T>& st, std::vector<Move>& moves,
818 std::vector<std::vector<double>>& arv,
819 std::vector<std::vector<double>>& dep,
820 std::vector<std::vector<double>>& dly,
821 std::vector<std::vector<double>>& start,
822 std::vector<std::vector<double>>& preempt) const {
823 const std::size_t local = sn_.nodes.size() + 1; // the dummy passive node
824 const std::size_t R = sn_.nclasses;
825 moves.clear();
826 for (std::size_t f = 0; f < arv.size(); ++f)
827 for (std::size_t r = 0; r < R; ++r) {
828 arv[f][r] = 0.0;
829 dep[f][r] = 0.0;
830 dly[f][r] = 0.0;
831 start[f][r] = 0.0;
832 preempt[f][r] = 0.0;
833 }
834
835 // A WAITQ REGION REPLACES THE WHOLE ENUMERATION rather than filtering it.
836 // The token FIFO is state the network encoding cannot hold, a refused job
837 // parks instead of being lost, and every firing runs a release cascade to a
838 // fixed point, so there is no per-move filter that turns the ordinary
839 // relation into this one. `waitq_successors` IS that relation, shared with
840 // the CTMC generator. Its own support gate has already refused an SPN and a
841 // fork-join model beside a WAITQ region, so no global or fork firing can
842 // reach here on this branch.
843 if (waitq_) {
844 std::vector<ctmc::waitq_detail::Successor<T>> succ;
845 ctmc::waitq_detail::waitq_successors(sn_, sync_, caps_, st, succ);
846 for (std::size_t i = 0; i < succ.size(); ++i) {
847 const ctmc::waitq_detail::Successor<T>& su = succ[i];
848 const double w = num_traits<T>::to_double(su.w);
849 if (!(w > 0)) continue;
850 Move m;
851 m.sync = su.sync;
852 m.weight = w;
853 m.next = su.next;
854 moves.push_back(m);
855 if (su.dep_isf != 0) dep[su.dep_isf - 1][su.dep_cls - 1] += w;
856 for (std::size_t q = 0; q < su.arv.size(); ++q)
857 arv[su.arv[q].first - 1][su.arv[q].second - 1] += w;
858 }
859 return;
860 }
861
862 const qn::NetState<T>& base = st.net;
863 // Global (Whittle) rate scaling declared through `set_global_dependence`. It
864 // reads the FULL population matrix, so it is a CONSTANT within one state and
865 // factors out of the per-transition rates, exactly as in `solver_ctmc`. The
866 // CTMC tabulates it once per state of the enumerated space; a simulator has
867 // one state at a time, so the table collapses to this single row.
868 std::vector<T> gd_now;
869 const bool has_gd = static_cast<bool>(sn_.gdscaling);
870 if (has_gd) gd_now = gd_factor_now(base);
871 // The state-dependent routing table, for the same reason and at the same
872 // scope: one evaluation of eq. (10) per state, not one per synchronization.
873 // The CTMC tabulates it over the enumerated space; a sample path holds one
874 // state at a time, so the table collapses to this single matrix.
875 Matrix<T> rt_now;
876 if (sdr_) rt_now = qn::rt_state(sn_, base.local);
877 for (std::size_t a = 0; a < sync_.size(); ++a) {
878 const qn::Sync<T>& sy = sync_[a];
879 const std::size_t isf_a = sn_.stateful_index(sy.active.node);
880 if (isf_a == 0) continue; // a stateless node schedules nothing
881 const std::size_t isf_p =
882 sy.passive.node == local ? 0 : sn_.stateful_index(sy.passive.node);
883 if (sy.passive.node != local && isf_p == 0) continue;
884
885 // Immediate feedback (sn.immfeed): the departure half of a self-loop must
886 // not promote a waiting job, so the fed-back arrival seizes the server it
887 // just left. See qn::immfeed_self_loop; this is the reference's
888 // solver_ssa.m immfeed_selfloop.
889 //
890 // TRUE BAS (BUG-110) splits a DEP at a blocking station into variants,
891 // exactly as the CTMC generator does (`solver_ctmc`): a TRANSFER of one
892 // held job for this sync's target (rate 1e7, routing probability 1, that
893 // counter minus one) and a FRESH COMPLETION of a job still in service
894 // (rate scaled by free/nr, absent when a single server is holding a
895 // job). A held row fires as the same row with its block cleared, and
896 // each variant writes back the block its outcome carries. Outside true
897 // BAS there is one variant, the event's own outcome.
898 const BasSync& bs = bas_[a];
899 std::vector<std::pair<qn::EventOutcome<T>, bool>> variants;
900 std::vector<long> bas_held;
901 long bas_nr = 0, bas_heldr = 0;
902 bool bas_any = false;
903 if (!bs.on) {
904 variants.push_back(std::make_pair(
905 qn::after_event(sn_, sy.active.node, base.local[isf_a - 1], sy.active.event,
906 sy.active.cls, qn::immfeed_self_loop(sn_, sy)),
907 false));
908 } else {
909 const std::vector<T>& cur = base.local[isf_a - 1];
910 const std::size_t w0 = cur.size() - bs.nc;
911 bas_held.assign(bs.nc, 0);
912 for (std::size_t k = 0; k < bs.nc; ++k) {
913 bas_held[k] = static_cast<long>(std::llround(num_traits<T>::to_double(cur[w0 + k])));
914 if (bas_held[k] > 0) bas_any = true;
915 }
916 for (std::size_t k = 0; k < bs.codes.size(); ++k) {
917 std::size_t rr = 0, jj = 0, ss = 0;
918 sn_.bas_decode(bs.codes[k], rr, jj, ss);
919 if (rr == sy.active.cls) bas_heldr += bas_held[k];
920 }
921 const qn::Marginal<T> mg =
922 qn::to_marginal(sn_, bs.ist, cur, bs.ph, bs.shift, sn_.nvars_of(sy.active.node));
923 bas_nr = static_cast<long>(
924 std::llround(num_traits<T>::to_double(mg.sir[sy.active.cls - 1])));
925 std::vector<T> zrow = cur;
926 for (std::size_t k = 0; k < bs.nc; ++k) zrow[w0 + k] = num_traits<T>::from_int(0);
927 const qn::EventOutcome<T> ev = qn::after_event(sn_, sy.active.node, zrow, sy.active.event,
928 sy.active.cls, qn::immfeed_self_loop(sn_, sy));
929 if (!ev.space.empty()) {
930 if (bas_any && bs.tgt != 0 && bas_held[bs.tgt - 1] > 0) {
931 qn::EventOutcome<T> tr = ev;
932 for (std::size_t i = 0; i < tr.space.size(); ++i) {
933 for (std::size_t k = 0; k < bs.nc; ++k)
934 tr.space[i][tr.space[i].size() - bs.nc + k] =
935 num_traits<T>::from_int(bas_held[k] - (k + 1 == bs.tgt ? 1 : 0));
936 tr.rate[i] = num_traits<T>::from_double(1e7); // BAS_TRANSFER_RATE
937 }
938 variants.push_back(std::make_pair(tr, true));
939 }
940 if (!bas_any) {
941 variants.push_back(std::make_pair(ev, false));
942 } else if (!bs.single && bas_nr > 0 && bas_nr - bas_heldr > 0) {
943 qn::EventOutcome<T> fr = ev;
944 const double f = static_cast<double>(bas_nr - bas_heldr) /
945 static_cast<double>(bas_nr);
946 for (std::size_t i = 0; i < fr.space.size(); ++i) {
947 for (std::size_t k = 0; k < bs.nc; ++k)
948 fr.space[i][fr.space[i].size() - bs.nc + k] =
949 num_traits<T>::from_int(bas_held[k]);
950 fr.rate[i] = T(fr.rate[i] * num_traits<T>::from_double(f));
951 }
952 variants.push_back(std::make_pair(fr, false));
953 }
954 }
955 }
956 // PHASE is scaled too, or phase-type service would advance unscaled
957 const bool gd_here = has_gd && sn_.nodes[sy.active.node - 1].station != 0 &&
958 (sy.active.event == lang::EventType::DEP ||
959 sy.active.event == lang::EventType::PHASE);
960 const double gd_f =
961 gd_here ? num_traits<T>::to_double(
962 gd_now[(sn_.nodes[sy.active.node - 1].station - 1) * R +
963 (sy.active.cls - 1)])
964 : 1.0;
965 // A cache READ whose successor holds one job FEWER is the delayed-hit
966 // merge: the request joined an in-flight fetch and is held in block B, so
967 // it leaves no departure to count and is released later in the hit class.
968 // Every other cache READ keeps the server block flat.
969 const bool cache_read = sy.active.event == lang::EventType::READ &&
970 sn_.nodes[sy.active.node - 1].nodetype == lang::NodeType::Cache;
971 double srv_pre = 0.0;
972 if (cache_read)
973 for (std::size_t r = 0; r < R && r < base.local[isf_a - 1].size(); ++r)
974 srv_pre += num_traits<T>::to_double(base.local[isf_a - 1][r]);
975
976 double fired = 0.0; // what this synchronization contributes from here
977 for (std::size_t vi = 0; vi < variants.size(); ++vi) {
978 const qn::EventOutcome<T>& oa = variants[vi].first;
979 const bool bas_transfer = variants[vi].second;
980 for (std::size_t ia = 0; ia < oa.space.size(); ++ia) {
981 // A BAS transfer is immediate and is not scaled by phi(n).
982 const double rate = num_traits<T>::to_double(oa.rate[ia]) * (bas_transfer ? 1.0 : gd_f);
983 const double pa = num_traits<T>::to_double(oa.prob[ia]);
984 if (!(rate > 0) || !(pa > 0)) continue;
985 bool merged = false;
986 if (cache_read) {
987 double srv_post = 0.0;
988 for (std::size_t r = 0; r < R && r < oa.space[ia].size(); ++r)
989 srv_post += num_traits<T>::to_double(oa.space[ia][r]);
990 merged = srv_post - srv_pre == -1.0;
991 }
992
993 if (sy.passive.node == local) {
994 Move m;
995 m.sync = a;
996 m.weight = rate * pa;
997 m.next = st;
998 m.next.net.local[isf_a - 1] = oa.space[ia];
999 // A DROP region CENSORS the chain: a transition into a state the
1000 // region forbids is not taken at all, which is what deleting the
1001 // state from the CTMC's space and re-closing its rows amounts
1002 // to. The move is dropped whole, so it contributes neither a
1003 // departure nor an arrival, exactly as the deleted column does.
1004 if (!region_admissible(m.next.net)) continue;
1005 fired += m.weight;
1006 if (merged) dly[isf_a - 1][sy.active.cls - 1] += m.weight;
1007 // The START/PREEMPT tags of this arc, weighted like the rate it
1008 // carries: they annotate the transition itself. Written for
1009 // EVERY action, not only for departures -- a retrial or a
1010 // polling switchover starts service without being a DEP.
1011 ssa_detail::add_tag_rates(start, preempt, sn_, sy.active.node, oa, ia, m.weight);
1012 moves.push_back(m);
1013 continue;
1014 }
1015 // A self-loop synchronization reads the passive node's state AFTER
1016 // the active half has been applied, since they are the same node.
1017 const std::vector<T>& src =
1018 sy.passive.node == sy.active.node ? oa.space[ia] : base.local[isf_p - 1];
1019 const qn::EventOutcome<T> op = qn::after_event(sn_, sy.passive.node, src,
1020 sy.passive.event, sy.passive.cls);
1021 // NO ROWS is a BLOCK, not a loss: the destination has no room and
1022 // cannot take the job, so the upstream departure is disabled and the
1023 // synchronization simply does not appear in the enabled list. This
1024 // is the reference's `prob_sync_p = 0`.
1025 // The routing probability, read at the state the job LEAVES from,
1026 // which is what `sub_sdr` reads.
1027 double proute =
1028 sy.passive.statedep
1029 ? num_traits<T>::to_double(rt_now(sy.passive.rt_row, sy.passive.rt_col))
1030 : num_traits<T>::to_double(sy.passive.prob);
1031 // ROUND-ROBIN reads the pointer the ACTIVE node carries once its own
1032 // departure has advanced it, exactly as the CTMC generator does; the
1033 // uniform expansion in `sy.passive.prob` would make the dispatcher a
1034 // coin. The pointer lives in the state, so the serial engine needs
1035 // no cursor of its own -- unlike the NRM, which walks the arcs.
1036 if (sy.active.event == lang::EventType::DEP &&
1037 sn_.rr_var_slot(sy.active.node, sy.active.cls) != 0) {
1038 const std::size_t w = sn_.nvars_of(sy.active.node);
1039 const std::vector<T>& arow = oa.space[ia];
1040 std::size_t dest = 0;
1041 if (arow.size() >= w) {
1042 const std::vector<T> var(arow.end() - w, arow.end());
1043 dest = sn_.rr_dest(sy.active.node, sy.active.cls, var);
1044 }
1045 proute = (dest == sy.passive.node && sy.passive.cls == sy.active.cls) ? 1.0 : 0.0;
1046 }
1047 // A held job's route was drawn when it blocked.
1048 if (bas_transfer) proute = 1.0;
1049 // TRUE BAS, the become-blocked half. The destination refused the
1050 // arrival outright, so the completing job cannot leave: it stays in
1051 // the server it completed in and the counter of THIS target code goes
1052 // up by one, nothing else moves. The weight is the (free-share and
1053 // phi(n) scaled) completion rate times the routing probability to
1054 // this target. It is NOT a departure, so it adds to neither `dep` nor
1055 // `arv`, as the CTMC keeps its `bas_block` edges out of `dep_rates`.
1056 if (op.space.empty() && bs.on && !bas_transfer && bs.tgt != 0 &&
1057 !(bs.single && bas_any) && bas_nr > 0 && bas_nr - bas_heldr > 0 && proute > 0) {
1058 Move m;
1059 m.sync = a;
1060 m.weight = rate * pa * proute;
1061 m.next = st;
1062 std::vector<T>& brow = m.next.net.local[isf_a - 1];
1063 brow[brow.size() - bs.nc + (bs.tgt - 1)] =
1064 num_traits<T>::from_int(bas_held[bs.tgt - 1] + 1);
1065 if (m.weight > 0) moves.push_back(m);
1066 continue;
1067 }
1068 for (std::size_t ip = 0; ip < op.space.size(); ++ip) {
1069 const double pp = num_traits<T>::to_double(op.prob[ip]);
1070 if (!(pp > 0)) continue;
1071 Move m;
1072 m.sync = a;
1073 m.weight = rate * pa * proute * pp;
1074 if (!(m.weight > 0)) continue;
1075 m.next = st;
1076 m.next.net.local[isf_a - 1] = oa.space[ia];
1077 m.next.net.local[isf_p - 1] = op.space[ip];
1078 if (!region_admissible(m.next.net)) continue;
1079 fired += m.weight;
1080 if (merged) dly[isf_a - 1][sy.active.cls - 1] += m.weight;
1081 // both halves are tagged: the arrival half is where most
1082 // service starts happen
1083 ssa_detail::add_tag_rates(start, preempt, sn_, sy.active.node, oa, ia, m.weight);
1084 ssa_detail::add_tag_rates(start, preempt, sn_, sy.passive.node, op, ip, m.weight);
1085 moves.push_back(m);
1086 }
1087 }
1088 }
1089 // A DEP synchronization is one job LEAVING the active node and ENTERING
1090 // the passive one, so the same rate is a departure there and an arrival
1091 // here. The passive half of a LOCAL action is the dummy node, which is
1092 // nobody's arrival.
1093 if (sy.active.event == lang::EventType::DEP && fired > 0) {
1094 dep[isf_a - 1][sy.active.cls - 1] += fired;
1095 if (isf_p != 0) arv[isf_p - 1][sy.passive.cls - 1] += fired;
1096 }
1097 }
1098
1099 for (std::size_t g = 0; g < gsync_.size(); ++g) {
1100 const qn::GlobalOutcome<T> go = qn::after_global_event(sn_, base, gsync_[g]);
1101 for (std::size_t io = 0; io < go.space.size(); ++io) {
1102 const double w = num_traits<T>::to_double(go.rate[io]) *
1103 num_traits<T>::to_double(go.prob[io]);
1104 if (!(w > 0)) continue;
1105 Move m;
1106 m.sync = sync_.size() + g;
1107 m.weight = w;
1108 m.next = st;
1109 m.next.net = go.space[io];
1110 if (!region_admissible(m.next.net)) continue;
1111 moves.push_back(m);
1112 // A FIRE consumes from its PRE places and produces to its POST
1113 // places, which is a departure and an arrival respectively; an
1114 // ENABLE only reads the markings and moves nothing.
1115 if (gsync_[g].active.event != lang::EventType::FIRE) continue;
1116 for (std::size_t j = 0; j < gsync_[g].passive.size(); ++j) {
1117 const qn::ModeEvent<T>& pev = gsync_[g].passive[j];
1118 const std::size_t pisf = sn_.stateful_index(pev.node);
1119 if (pisf == 0 || pev.cls == 0 || pev.cls > R) continue;
1120 if (pev.event == lang::EventType::PRE) dep[pisf - 1][pev.cls - 1] += w;
1121 else if (pev.event == lang::EventType::POST) arv[pisf - 1][pev.cls - 1] += w;
1122 }
1123 }
1124 }
1125
1126 // FORK FIRINGS, atomic across the fork and every branch head, so like an SPN
1127 // firing they take the whole network state and cannot be decomposed into
1128 // sync halves. `refresh_sync` emits no DEP for a Fork, which is why nothing
1129 // above has already counted them.
1130 //
1131 // ONE DEPARTURE, B ARRIVALS. The parent leaves the fork in its own class and
1132 // one sibling enters each branch head in the tag's auxiliary class, so the
1133 // rate statistics are accumulated by hand exactly as `solver_ctmc` does:
1134 // an ordinary synchronization has no way to express a one-to-many emission.
1135 for (std::size_t k = 0; k < fjsync_.size(); ++k) {
1136 const qn::FjSync<T>& e = fjsync_[k];
1137 const std::size_t isf_f = sn_.stateful_index(e.fork);
1138 if (isf_f == 0) continue;
1139 const qn::GlobalOutcome<T> fo = qn::after_fj_event(sn_, e, base);
1140 double fired = 0.0;
1141 for (std::size_t io = 0; io < fo.space.size(); ++io) {
1142 const double w = num_traits<T>::to_double(fo.rate[io]) *
1143 num_traits<T>::to_double(fo.prob[io]);
1144 if (!(w > 0)) continue;
1145 Move m;
1146 m.sync = sync_.size() + gsync_.size() + k;
1147 m.weight = w;
1148 m.next = st;
1149 m.next.net = fo.space[io];
1150 if (!region_admissible(m.next.net)) continue;
1151 fired += w;
1152 moves.push_back(m);
1153 }
1154 if (!(fired > 0)) continue;
1155 dep[isf_f - 1][e.cls - 1] += fired;
1156 for (std::size_t b = 0; b < e.branchheads.size(); ++b) {
1157 const std::size_t isf_b = sn_.stateful_index(e.branchheads[b]);
1158 if (isf_b != 0) arv[isf_b - 1][e.auxclasses[b] - 1] += fired;
1159 }
1160 }
1161}
1162
1163template <class T>
1165 // The exponential holding time is drawn as -log(u)/lambda, so the backend
1166 // must have a logarithm at all. The analyzer gates on `double` before it
1167 // instantiates this, so a caller reaching the assert is one that reached
1168 // past the gate and would otherwise get a compile error deep inside the
1169 // uniform draw instead of a sentence naming the reason.
1171 "solver_ssa_serial: an SSA sample path is generated from exponential clocks "
1172 "drawn as -log(u)/rate, which needs transcendental arithmetic");
1173
1174 const std::size_t NF = sn_.stateful_nodes.size();
1175 const std::size_t R = sn_.nclasses;
1176 SsaSerialRun<T> out;
1177 out.seed = opt_.seed;
1178 out.warmup = static_cast<std::size_t>(
1179 std::floor(std::max(0.0, std::min(0.99, opt_.warmupfrac)) *
1180 static_cast<double>(opt_.samples)));
1181
1182 ctmc::WaitqState<T> cur = init_;
1183 std::vector<Move> moves;
1184 std::vector<std::vector<double>> arv(NF, std::vector<double>(R, 0.0));
1185 std::vector<std::vector<double>> dep(NF, std::vector<double>(R, 0.0));
1186 std::vector<std::vector<double>> dly(NF, std::vector<double>(R, 0.0));
1187 // Derived START/PREEMPT rates, sampled exactly like the three above: the
1188 // rate at which the transitions enabled in the current state start a
1189 // class-r service, or push a class-r job in service back into the buffer.
1190 std::vector<std::vector<double>> start(NF, std::vector<double>(R, 0.0));
1191 std::vector<std::vector<double>> preempt(NF, std::vector<double>(R, 0.0));
1192 std::vector<double> weights;
1193 std::map<std::vector<double>, std::size_t> index; // state key -> row of `space`
1194
1195 double cur_time = 0.0;
1196 out.tran_time.reserve(opt_.samples);
1197 out.tran_sync.reserve(opt_.samples);
1198 bool time_stopped = false;
1199 for (std::size_t n = 0; n < opt_.samples; ++n) {
1200 // Wall-clock budget (options.timeout), read every 1024 firings: the
1201 // path collected so far is the interim solution, as the reference's
1202 // serial loop condition `~lineTimeoutExceeded` stops it.
1203 if (n > 0 && (n & 1023u) == 0 && util::timeout_exceeded()) {
1204 time_stopped = true;
1205 break;
1206 }
1207 enabled(cur, moves, arv, dep, dly, start, preempt);
1208 if (moves.empty())
1209 throw NumericError(ErrorKind{"Deadlock"},
1210 "solver_ssa_serial: the sample path entered a deadlock before collecting all "
1211 "samples, no synchronization is enabled");
1212
1213 weights.resize(moves.size());
1214 double tot = 0.0;
1215 for (std::size_t i = 0; i < moves.size(); ++i) {
1216 weights[i] = moves[i].weight;
1217 tot += weights[i];
1218 }
1219 const std::size_t sel = rng_.draw(weights);
1220 // The transition is drawn BEFORE the holding time, as the reference
1221 // draws them: the two are independent, so the order changes only which
1222 // stream this engine is, and being a nameable stream is the point.
1223 const double dt = -std::log(rng_.uniform()) / tot;
1224
1225 // The state is recorded with the time spent IN it, so the pair belongs
1226 // to the state before the firing, not after.
1227 //
1228 // THE KEY IS THE AUGMENTED ONE and the stored row is the network half.
1229 // Two states that agree on every node but differ in a region FIFO are
1230 // DIFFERENT states -- their enabled sets differ -- so merging them would
1231 // put two rate rows on one entry and report whichever was seen first.
1232 // `space` therefore may hold the same network row twice, once per FIFO
1233 // content, which every consumer here handles: each row carries its own
1234 // `pi` and the metrics are sums over rows, never lookups by row.
1235 const std::vector<double> key = ctmc::waitq_detail::waitq_key(cur);
1236 std::size_t si;
1237 const typename std::map<std::vector<double>, std::size_t>::const_iterator it =
1238 index.find(key);
1239 if (it != index.end()) {
1240 si = it->second;
1241 } else {
1242 si = out.space.size();
1243 index[key] = si;
1244 out.space.push_back(cur.net);
1245 out.buf.push_back(cur.buf);
1246 out.pi.push_back(0.0);
1247 out.arv_rates.push_back(arv);
1248 out.dep_rates.push_back(dep);
1249 out.dly_rates.push_back(dly);
1250 out.start_rates.push_back(start);
1251 out.preempt_rates.push_back(preempt);
1252 }
1253 // The warmup discard drops the transient from the TIME AVERAGE only: the
1254 // states themselves stay in the table, so a state visited only during
1255 // the transient keeps its (exact) rate row and contributes zero weight.
1256 if (n >= out.warmup) {
1257 out.pi[si] += dt;
1258 out.simulated_time += dt;
1259 }
1260 cur_time += dt;
1261 out.tran_time.push_back(cur_time);
1262 out.tran_sync.push_back(moves[sel].sync);
1263 out.tran_state.push_back(si);
1264
1265 cur = moves[sel].next;
1266 out.samples = n + 1;
1267 }
1268 // A budget that ran out inside the warmup leaves no time-averaged sample at
1269 // all, which is no interim solution of anything.
1270 if (time_stopped && !(out.simulated_time > 0.0))
1271 throw NumericError(ErrorKind{"Timeout"},
1272 "solver_ssa_serial: the wall-clock time budget (options.timeout) ran "
1273 "out inside the warmup, before any sample was collected");
1274
1275 double tot_pi = 0.0;
1276 for (std::size_t s = 0; s < out.pi.size(); ++s) tot_pi += out.pi[s];
1277 if (tot_pi > 0)
1278 for (std::size_t s = 0; s < out.pi.size(); ++s) out.pi[s] /= tot_pi;
1279 out.ssq = ctmc::ctmc_state_space_aggr(sn_, out.space);
1280 return out;
1281}
1282
1283namespace serial_detail {
1284
1285/** `map_mean(PH{ist}{k})`, or a negative sentinel when the pair has no process. */
1286template <class T>
1287double service_mean(const qn::NetworkStruct<T>& sn, std::size_t ist, std::size_t k) {
1288 const lang::Distrib<T>& d = sn.service[ist - 1][k - 1];
1289 if (d.disabled || d.D0.rows() == 0) return -1.0;
1290 mam::Map<T> m;
1291 m.D0 = d.D0;
1292 m.D1 = d.D1;
1293 try {
1295 } catch (const Error&) {
1296 return -1.0; // a zero-rate process has no mean; the reference skips it too
1297 }
1298}
1299
1300} // namespace serial_detail
1301
1302/**
1303 * Port of `solver_ssa_analyzer_serial.m`: run the serial engine and reduce its
1304 * path to the metric table.
1305 *
1306 * THE UTILIZATION ESTIMATOR IS THE REFERENCE'S, discipline by discipline. An
1307 * INF station is utilized by every job it holds; a PS-family station takes the
1308 * ARRIVAL rate over rate*servers, because the offered load is what a processor
1309 * sharing server carries; every other discipline takes the arrival rate times
1310 * the mean service time over the servers. A class that can be DROPPED -- an open
1311 * class at a station with a finite capacity -- is measured on the CARRIED rate
1312 * instead, because the offered rate counts arrivals that never entered service.
1313 *
1314 * ONE DIVERGENCE FROM THE REFERENCE, stated rather than hidden:
1315 *
1316 * THE CACHE LOOP IS INDEXED BY NODE, NOT BY STATEFUL INDEX. The reference
1317 * writes `sn.nodetype(isf) == NodeType.Cache` with `isf` running over the
1318 * STATEFUL nodes, so on any model whose stateful indices differ from its node
1319 * indices -- one with a Source, a Router or a ClassSwitch, which is most of
1320 * them -- it tests the type of the wrong node. Reproducing that would report
1321 * hit ratios for a node that is not the cache.
1322 *
1323 * A PAS STATION takes the reference's `otherwise` branch, T*E[S]/c, and NOT the
1324 * in-service occupancy `solver_ctmc_avg_from_pi` computes for the same station.
1325 * The two disagree because a pass-and-swap job does not engage a single server;
1326 * the reference serial analyzer is what is ported here, and the disagreement is
1327 * named so it is not mistaken for a defect in either.
1328 */
1329template <class T>
1331 const SsaSerialOptions& opt,
1332 const std::vector<qn::FjSync<T>>& fjsync) {
1333 // `if constexpr`, not a run-time test: the engine reaches `map_mean` and the
1334 // logarithm of a uniform, so a Rational instantiation would fail to COMPILE
1335 // rather than refuse. The gate has to keep the body from being instantiated.
1336 if constexpr (!std::is_same<T, double>::value) {
1337 (void)sn_arg;
1338 (void)opt;
1339 throw UnsupportedError(ErrorKind{"Arithmetic"},
1340 "solver_ssa_serial: an SSA sample path is generated from exponential clocks, which "
1341 "are logarithms of uniform draws; there is no exact value to compute and a wider "
1342 "float carries no information the Monte Carlo error does not swamp. Rerun with "
1343 "--arith double");
1344 } else {
1345 using lang::SchedStrategy;
1346 // A MAP service at an FCFS station runs in the pair form SolverCTMC uses (`ctmc_mapc`):
1347 // one sampler per (station, class) chained in start order, as JMT and LDES draw it.
1348 qn::NetworkStruct<T> sn_mapc;
1349 const bool mapc = ctmc::ctmc_mapc(sn_arg, sn_mapc);
1350 const qn::NetworkStruct<T>& sn = mapc ? sn_mapc : sn_arg;
1351 const std::size_t M = sn.nstations, K = sn.nclasses;
1353 out.seed = opt.seed;
1354 if (mapc) out.solved_sn = std::make_shared<const qn::NetworkStruct<T>>(sn);
1355
1356 SsaSerialEngine<T> eng(sn, opt, fjsync);
1357 out.run = eng.run();
1358 const SsaSerialRun<T>& r = out.run;
1359
1360 // The parked population, per class: a token carries the class its job
1361 // will enter in, so the mean is the time average of the FIFO contents.
1362 out.parked.assign(K, 0.0);
1363 for (std::size_t s = 0; s < r.buf.size() && s < r.pi.size(); ++s)
1364 for (std::size_t f = 0; f < r.buf[s].size(); ++f)
1365 for (std::size_t j = 0; j < r.buf[s][f].size(); ++j) {
1366 const std::size_t cls = (r.buf[s][f][j] - 1) % K + 1;
1367 out.parked[cls - 1] += r.pi[s];
1368 }
1369
1370 SsaSolution& a = out.avg;
1371 a.method = "serial";
1372 a.samples = r.samples;
1374 a.QN = Matrix<double>(M, K, 0.0);
1375 a.UN = Matrix<double>(M, K, 0.0);
1376 a.RN = Matrix<double>(M, K, 0.0);
1377 a.TN = Matrix<double>(M, K, 0.0);
1378 a.XN.assign(K, 0.0);
1379 a.CN.assign(K, 0.0);
1380 a.StartN = Matrix<double>(M, K, 0.0);
1381 a.PreemptN = Matrix<double>(M, K, 0.0);
1382
1383 // System throughput is the DEPARTURE rate at each class's reference
1384 // station, which is what makes X a per-class quantity rather than a sum.
1385 for (std::size_t k = 1; k <= K; ++k) {
1386 const std::size_t refsf = sn.stateful_of_station(sn.classes[k - 1].refstat);
1387 if (refsf == 0) continue;
1388 for (std::size_t s = 0; s < r.space.size(); ++s)
1389 a.XN[k - 1] += r.pi[s] * r.dep_rates[s][refsf - 1][k - 1];
1390 }
1391
1392 // The reference's `isempty(sn.lldscaling) && isempty(sn.cdscaling)` test
1393 // is over the WHOLE matrix, so one load-dependent station puts every
1394 // station on the scaling branch. That is kept: at a station with no
1395 // scaling the branch degenerates to T*E[S]/c, which differs from the
1396 // unscaled branch only in using the carried rather than the offered
1397 // rate, and reproducing the reference's table means reproducing that.
1398 bool scaled = static_cast<bool>(sn.gdscaling);
1399 for (std::size_t i = 0; i < M; ++i)
1400 if (!sn.stations[i].lldscaling.empty() || sn.stations[i].cdscaling) scaled = true;
1401
1402 for (std::size_t ist = 1; ist <= M; ++ist) {
1403 const std::size_t isf = sn.stateful_of_station(ist);
1404 if (isf == 0) continue;
1405 const SchedStrategy sched = sn.stations[ist - 1].sched;
1406 const double S = sn.stations[ist - 1].nservers;
1407 for (std::size_t k = 1; k <= K; ++k) {
1408 for (std::size_t s = 0; s < r.space.size(); ++s) {
1409 a.TN(ist - 1, k - 1) += r.pi[s] * r.dep_rates[s][isf - 1][k - 1];
1410 a.QN(ist - 1, k - 1) +=
1411 r.pi[s] * num_traits<T>::to_double(r.ssq(s, (ist - 1) * K + k - 1));
1412 // same time average as TN, over the derived tag rates
1413 if (s < r.start_rates.size()) {
1414 a.StartN(ist - 1, k - 1) += r.pi[s] * r.start_rates[s][isf - 1][k - 1];
1415 a.PreemptN(ist - 1, k - 1) += r.pi[s] * r.preempt_rates[s][isf - 1][k - 1];
1416 }
1417 }
1418 }
1419
1420 const bool is_ps = sched == SchedStrategy::PS || sched == SchedStrategy::DPS ||
1421 sched == SchedStrategy::GPS || sched == SchedStrategy::LPS;
1422 // A SOURCE holds no jobs, so QLen, Util and hence RespT are zero
1423 // there BY DEFINITION and only its throughput is a quantity -- the
1424 // rule `solver_ssa_nrm.h` states at length and `solver_ctmc_avg_from_pi`
1425 // applies by the same `continue`. The reference serial analyzer has
1426 // no such branch and lets a Source fall into `otherwise`, where it
1427 // divides the arrival rate by a server count `solver_ssa.m` has
1428 // meanwhile overwritten with the station's capacity; that product is
1429 // not a utilization of anything.
1430 if (sn.stations[ist - 1].nodetype == lang::NodeType::Source ||
1431 sched == SchedStrategy::EXT)
1432 continue;
1433 if (sched == SchedStrategy::INF) {
1434 for (std::size_t k = 1; k <= K; ++k) {
1435 a.UN(ist - 1, k - 1) = a.QN(ist - 1, k - 1);
1436 // a global dependence re-times the think time too, so its declared peak normalizes the
1437 // delay row as well (T*E[S]/peak, as SolverCTMC and LDES)
1438 if (sn.gdscaling && sn.gdscalingpeak.size() >= ist * K) {
1439 const double pk = num_traits<T>::to_double(sn.gdscalingpeak[(ist - 1) * K + (k - 1)]);
1440 const double mean = serial_detail::service_mean(sn, ist, k);
1441 if (pk > 0.0 && mean >= 0.0) a.UN(ist - 1, k - 1) = a.TN(ist - 1, k - 1) * mean / pk;
1442 }
1443 }
1444 continue;
1445 }
1446 if (scaled) {
1447 // The EFFECTIVE server count a load-dependent station can
1448 // deliver: `max(c, max_n lld(n))`. A class-dependent station
1449 // normalizes by its DECLARED peak instead, which is the only
1450 // thing the utilization can be a fraction of.
1451 double ceff = S;
1452 const std::vector<T>& lld = sn.stations[ist - 1].lldscaling;
1453 for (std::size_t j = 0; j < lld.size(); ++j)
1454 ceff = std::max(ceff, num_traits<T>::to_double(lld[j]));
1455 const bool is_cd = static_cast<bool>(sn.stations[ist - 1].cdscaling);
1456 const bool is_jd = static_cast<bool>(sn.stations[ist - 1].jdscaling);
1457 // A global (Whittle) dependence rescales the service rate the
1458 // same way, so the peak IT declares normalizes Util too.
1459 const bool is_gd = static_cast<bool>(sn.gdscaling);
1460 std::vector<T> gdpk;
1461 if (is_gd)
1462 gdpk.assign(sn.gdscalingpeak.begin() + (ist - 1) * K,
1463 sn.gdscalingpeak.begin() + ist * K);
1464 for (std::size_t k = 1; k <= K; ++k) {
1465 const double mean = serial_detail::service_mean(sn, ist, k);
1466 if (mean < 0) continue;
1467 // The divisor is the PRODUCT of the declared peaks when either
1468 // dependence is present, and the effective server count only
1469 // otherwise: a station carrying both scales its rate by both,
1470 // so normalizing by one of them alone leaves the other's factor
1471 // in the reported utilization.
1472 double cdiv = ceff;
1473 if (is_cd || is_jd || is_gd) {
1474 cdiv = 1.0;
1475 const std::vector<T>* pks[3] = {&sn.stations[ist - 1].cdscalingpeak,
1476 &sn.stations[ist - 1].jdscalingpeak,
1477 &gdpk};
1478 const char* names[3] = {"setClassDependence", "setJointDependence",
1479 "setGlobalDependence"};
1480 const bool on[3] = {is_cd, is_jd, is_gd};
1481 for (std::size_t h = 0; h < 3; ++h) {
1482 if (!on[h]) continue;
1483 const std::vector<T>& pk = *pks[h];
1484 if (pk.size() < k || !(num_traits<T>::to_double(pk[k - 1]) > 0))
1485 throw InputError(
1486 "SolverSSA(method='serial'): station '" +
1487 sn.stations[ist - 1].name +
1488 "' declares a dependent scaling with no declared peak rate. "
1489 "Utilization there is T*E[S]/peak, so pass the peak to " +
1490 names[h]);
1491 cdiv *= num_traits<T>::to_double(pk[k - 1]);
1492 }
1493 }
1494 a.UN(ist - 1, k - 1) = cdiv > 0 ? a.TN(ist - 1, k - 1) * mean / cdiv : 0.0;
1495 }
1496 continue;
1497 }
1498
1499 // A class whose jobs can be lost here is measured on the carried
1500 // rate; everything else on the offered rate, which is exact in
1501 // steady state and is what the reference reports.
1502 for (std::size_t k = 1; k <= K; ++k) {
1503 const double mean = serial_detail::service_mean(sn, ist, k);
1504 if (mean < 0) continue;
1505 // A job that reneges or balks leaves without service, as a dropped one does. RENEGING counts for a
1506 // closed class too, as in the CTMC analyzer (solver_ctmc.h, MATLAB solver_ctmc_analyzer.m).
1507 const qn::Station<T>& stk = sn.stations[ist - 1];
1508 const bool reneging = num_traits<T>::to_double(qn::station_renege_mu(sn, ist, k)) > 0;
1509 const bool balking = k <= stk.balking.size() &&
1510 stk.balking[k - 1].strategy != lang::BalkingStrategy::NONE;
1511 const bool can_drop = (!std::isfinite(sn.njobs()[k - 1]) &&
1512 (std::isfinite(sn.cap[ist - 1]) ||
1513 std::isfinite(sn.classcap[ist - 1][k - 1]) || balking)) ||
1514 reneging;
1515 double arv = 0.0;
1516 if (!can_drop)
1517 for (std::size_t s = 0; s < r.space.size(); ++s)
1518 arv += r.pi[s] * r.arv_rates[s][isf - 1][k - 1];
1519 if (is_ps) {
1520 const double mu = num_traits<T>::to_double(sn.rates(ist - 1, k - 1));
1521 if (!(mu > 0)) continue;
1522 a.UN(ist - 1, k - 1) =
1523 (can_drop ? a.TN(ist - 1, k - 1) / mu : arv / mu) / S;
1524 } else {
1525 a.UN(ist - 1, k - 1) =
1526 (can_drop ? a.TN(ist - 1, k - 1) * mean : arv * mean) / S;
1527 }
1528 }
1529 }
1530
1531 // SYNCHRONOUS CALLS (REPLY signals), as `solver_ctmc_avg_from_pi` and the reference's
1532 // `ssa_reply_held`: a caller waiting for its reply still HOLDS its server, counted in the
1533 // reply block at the tail of the local row. The hold is added to QLen and Util but not to
1534 // RespT, since the waiting job is at its callee and not here.
1535 serial_detail::apply_bas_held(sn, r, a.QN, a.UN);
1536
1537 const Matrix<double> held = serial_detail::reply_held(sn, r);
1538 for (std::size_t ist = 1; ist <= M; ++ist) {
1539 const double S = sn.stations[ist - 1].nservers;
1540 for (std::size_t k = 1; k <= K; ++k) {
1541 if (held(ist - 1, k - 1) == 0) continue;
1542 a.QN(ist - 1, k - 1) += held(ist - 1, k - 1);
1543 a.UN(ist - 1, k - 1) += held(ist - 1, k - 1) / S;
1544 }
1545 }
1546
1547 // Little's law per station, then the per-class system response time.
1548 for (std::size_t k = 1; k <= K; ++k) {
1549 for (std::size_t ist = 1; ist <= M; ++ist)
1550 a.RN(ist - 1, k - 1) =
1551 a.TN(ist - 1, k - 1) > 0
1552 ? (a.QN(ist - 1, k - 1) - held(ist - 1, k - 1)) / a.TN(ist - 1, k - 1)
1553 : 0.0;
1554 // The reference's `CN(k) = NK(k)/XN(k)` with NK the class population:
1555 // infinite for an open class, which its NaN sweep does NOT clear and
1556 // which the NRM engine reports identically.
1557 if (a.XN[k - 1] > 0) a.CN[k - 1] = sn.classes[k - 1].population / a.XN[k - 1];
1558 }
1559
1560 // The cache write-back: every read leaves as exactly one of hit or miss,
1561 // so the two departure streams divide the read rate between them and
1562 // their ratio is the realized hit probability. The reference stores it
1563 // into `sn.nodeparam{ind}.actualhitprob`; the struct is const here, so it
1564 // is returned beside the table instead.
1565 const double nan = std::numeric_limits<double>::quiet_NaN();
1566 for (typename std::map<std::size_t, qn::CacheParam<T>>::const_iterator ci =
1567 sn.nodeparam.begin();
1568 ci != sn.nodeparam.end(); ++ci) {
1569 const std::size_t ind = ci->first;
1570 if (ind == 0 || ind > sn.nodes.size()) continue;
1571 if (sn.nodes[ind - 1].nodetype != lang::NodeType::Cache) continue;
1572 const std::size_t isf = sn.stateful_index(ind);
1573 if (isf == 0) continue;
1574 SsaCacheRatio cr;
1575 cr.node = ind;
1576 cr.hitprob.assign(K, nan);
1577 cr.missprob.assign(K, nan);
1578 cr.residt.assign(K, nan);
1579 std::vector<double> dly(K, 0.0);
1580 bool any_delayed = false;
1581 for (std::size_t k = 1; k <= K; ++k) {
1582 if (ci->second.hitclass.size() < k || ci->second.missclass.size() < k) continue;
1583 const std::size_t h = ci->second.hitclass[k - 1];
1584 const std::size_t mi = ci->second.missclass[k - 1];
1585 if (h == 0 || mi == 0 || h > K || mi > K) continue;
1586 double th = 0.0, tm = 0.0, td = 0.0;
1587 for (std::size_t s = 0; s < r.space.size(); ++s) {
1588 th += r.pi[s] * r.dep_rates[s][isf - 1][h - 1];
1589 tm += r.pi[s] * r.dep_rates[s][isf - 1][mi - 1];
1590 if (s < r.dly_rates.size()) td += r.pi[s] * r.dly_rates[s][isf - 1][k - 1];
1591 }
1592 if (th + tm > 0) {
1593 // `th` already carries the released delayed hits, so the
1594 // delayed share is CARVED OUT of it rather than added as a
1595 // fourth share.
1596 cr.hitprob[k - 1] = std::max(th - td, 0.0) / (th + tm);
1597 cr.missprob[k - 1] = tm / (th + tm);
1598 dly[k - 1] = td / (th + tm);
1599 if (td > 0) any_delayed = true;
1600 }
1601 }
1602 if (any_delayed) cr.delayedprob = dly;
1603 out.cache.push_back(cr);
1604 }
1605 return out;
1606 }
1607}
1608
1609
1610/**
1611 * Port of `solver_ssa_analyzer_serial.m` plus the fork-join wrapper
1612 * `@@SolverSSA/runAnalyzer.m` puts in front of it.
1613 *
1614 * A FORK-JOIN MODEL IS SIMULATED ON THE TAG-AUGMENTED COPY, exactly as
1615 * SolverCTMC solves it there: the fork emits one sibling per branch in a class
1616 * of its own, the tag is what lets the Join recognize which siblings belong to
1617 * the same parent, and `fj_tag` is the only thing that builds the `fjsync`
1618 * firing list the engine fires. The sample path in the returned run is
1619 * therefore indexed by the AUGMENTED classes; only the metric table is folded
1620 * back, which is why `fjclassmap` travels with it.
1621 */
1622template <class T>
1624 const SsaSerialOptions& opt) {
1625 // The augmentation is skipped entirely on a non-`double` backend so the
1626 // refusal a caller reads is the arithmetic one, from inside the engine,
1627 // rather than a fork-join message about a model whose real problem is that
1628 // an exponential clock has no exact value.
1629 if constexpr (!std::is_same<T, double>::value) {
1630 return solver_ssa_serial_on_struct(sn_in, opt, std::vector<qn::FjSync<T>>());
1631 } else {
1632 // `solver_ssa_analyzer.m:25`: a non-Markovian law is walked as its fitted
1633 // genuine phase-type (`phfit = 'ph'`), as in `solver_ssa`. Done here too
1634 // because `-a prob` and `-a sample` reach this entry directly. The
1635 // path's rows are in the converted struct's phase layout, so it is
1636 // handed back as `solved_sn` unless a later transform already set one.
1637 std::shared_ptr<qn::NetworkStruct<T>> conv;
1638 if (api::sn_has_nonmarkov(sn_in, false)) {
1639 conv = std::make_shared<qn::NetworkStruct<T>>(sn_in);
1641 no.phfit = api::PhFit::Ph;
1642 api::sn_nonmarkov_toph(*conv, no);
1643 }
1644 const qn::NetworkStruct<T>& sn = conv ? *conv : sn_in;
1645 if (!tr::has_fork_join(sn)) {
1647 if (conv && !out.solved_sn) out.solved_sn = conv;
1648 return out;
1649 }
1650 const qn::FjTagged<T> fjt = qn::fj_tag(sn);
1652 tr::fj_foldback(sn, out.avg, fjt.fjclassmap, fjt.korig);
1653 out.fjclassmap = fjt.fjclassmap;
1654 out.parked.resize(fjt.korig);
1655 return out;
1656 }
1657}
1658
1659/**
1660 * The `serial` entry of `solver_ssa_analyzer.m`.
1661 *
1662 * The reference reaches it from `default` (when the NRM eligibility gate fails),
1663 * from `ssa`, from `serial` and from `para`/`parallel` without the Parallel
1664 * Computing Toolbox. `para`/`parallel` is NOT that: it replicates the SAME
1665 * engine across workers and averages, so answering it with one replica would
1666 * report a number at a different variance from the one asked for, and it refuses
1667 * by name here.
1668 */
1669template <class T>
1671 const SsaSerialOptions& opt) {
1672 const std::string& m = opt.method;
1673 if (m == "default" || m == "ssa" || m == "serial") return solver_ssa_serial_analyzer(sn, opt);
1674 if (m == "para" || m == "pana" || m == "parallel")
1675 throw UnsupportedError(ErrorKind{"Method"},
1676 "SolverSSA: the '" + m +
1677 "' method runs the serial engine on several workers and averages the replicas "
1678 "(solver_ssa_analyzer_parallel.m). The engine is ported; the replication is not, and "
1679 "one replica has a different variance from the average of many. Use 'serial'");
1680 throw UnsupportedError(ErrorKind{"Method"}, "SolverSSA(serial): '" + m +
1681 "' is not a method this entry accepts; it implements 'serial' and the "
1682 "'default' and 'ssa' aliases that reach it");
1683}
1684
1685} // namespace ssa
1686} // namespace line
1687
1688#endif // LINE_SOLVERS_SSA_SOLVER_SSA_SERIAL_H
Base error for the multiprecision C++ port.
Definition error.h:73
InputError(const std::string &what)
Definition error.h:105
NumericError(const std::string &what)
Definition error.h:112
A refusal: the feature, method or analysis is not covered: LINE:unsupported:<kind>.
Definition error.h:117
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
std::size_t nvars_of(std::size_t ind) const
Total local-variable width of node ind (1-based).
std::size_t stateful_index(std::size_t ind) const
1-based stateful index of node ind, 0 when the node is not stateful.
GdScaling< T > gdscaling
sn.gdscaling: the network-level globally state-dependent (Whittle) rate scaling phi(n).
static std::size_t bas_ncols(const std::vector< std::size_t > &codes)
Width of the held-job block: one counter per code, at least one column.
std::vector< bool > isbasblocking
sn.isbasblocking, per NODE: true where the node is the BLOCKING (upstream) side of a true-BAS relatio...
void bas_decode(std::size_t code, std::size_t &r, std::size_t &jst, std::size_t &s) const
Inverse of bas_code: 1-based (r, jst, s) for a code >= 1.
std::size_t rr_var_slot(std::size_t ind, std::size_t r) const
1-BASED index of the pointer of (ind, r) INSIDE the node's local-variable block, or 0 when that pair ...
std::vector< std::size_t > bas_marker_codes(std::size_t ind) const
Sorted held-job codes of the blocking node ind: one per (r, jst, s) the routing sends from class r at...
bool bas_single_server(std::size_t ist) const
A non-INF station with at most one server holds at most one job in total.
std::vector< NodeDef > nodes
every node, in creation order
std::size_t bas_code(std::size_t r, std::size_t jst, std::size_t s) const
TRUE-BAS HELD-JOB CODES (BUG-110).
The serial engine: the sample path of solver_ssa.m's main loop.
const std::vector< qn::Sync< T > > & sync() const
The synchronization list the trace's tran_sync indexes.
SsaSerialEngine(const qn::NetworkStruct< T > &sn, const SsaSerialOptions &opt, const std::vector< qn::FjSync< T > > &fjsync=std::vector< qn::FjSync< T > >())
fjsync is the fork firing list of the TAG-AUGMENTED struct, empty for a model with no Fork.
const qn::NetState< T > & init_state() const
The state the path starts from, at full encoding width.
SsaSerialRun< T > run()
Run opt.samples firings and return the path with its statistics.
The exception types the port throws.
Port of matlab/src/api/fj/sn_fj_validate.m and matlab/src/io/@@ModelAdapter/fjtag....
Fork-join TAG AUGMENTATION: the fold-back half of the transform/lift pair that CTMC and SSA share.
options.timeout: one wall-clock budget per top-level solve, on a per-THREAD deadline stack.
Markovian arrival process descriptors: stationary vectors, rate, moments, autocorrelation and the ind...
Dense matrix and non-owning view.
bool sn_has_nonmarkov(const qn::NetworkStruct< T > &sn, bool preserve_det=false)
Whether any law in the struct would be replaced, so a caller can skip copying the struct when there i...
@ Ph
Bernstein density fit: a genuine phase-type, shape-carrying.
void sn_nonmarkov_toph(qn::NetworkStruct< T > &sn, const NonmarkovOptions &opts=NonmarkovOptions())
Replace every non-Markovian service and firing law by a Markovian surrogate.
bool ctmc_region_admissible(const NetworkStruct< T > &sn, const std::vector< T > &nir)
True when nir – the per-(station, class) counts of one state, in (ist-1)*K + k order – satisfies ever...
bool ctmc_mapc(const qn::NetworkStruct< T > &in, qn::NetworkStruct< T > &out)
Rewrite a copy of in into out when it has a MAP service at an FCFS station; false,...
std::vector< NetState< T > > ctmc_filter_regions(const NetworkStruct< T > &sn, const std::vector< NetState< T > > &space)
The states of space a DROP region admits, in their original order.
void ctmc_check_region_rules(const NetworkStruct< T > &sn)
Refuse the region rules this port does not implement.
Matrix< T > ctmc_state_space_aggr(const NetworkStruct< T > &sn, const std::vector< NetState< T > > &space)
Port of StateSpaceAggr: the per-(station, class) job counts of every state, as an (nstates x nstation...
bool ctmc_has_waitq_region(const NetworkStruct< T > &sn)
True when the model declares a region that applies anything other than DROP.
std::vector< NetState< T > > reachable_space_generator(const NetworkStruct< T > &sn, const NetState< T > &init, const std::vector< Sync< T > > &sync, const std::vector< qn::GlobalSync< T > > &gsync=std::vector< qn::GlobalSync< T > >(), std::size_t maxst=3000000, const std::vector< qn::FjSync< T > > &fjsync=std::vector< qn::FjSync< T > >(), const std::vector< std::size_t > &cutoff=std::vector< std::size_t >(), const std::vector< std::vector< std::size_t > > &cutoff_mat=std::vector< std::vector< std::size_t > >())
Port of State.reachableSpaceGenerator: the states reachable from init.
void ctmc_check_waitq_support(const NetworkStruct< T > &sn)
The combinations the reference gates, plus the two this port cannot represent.
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
@ PHASE
service advances a phase WITHOUT departing
Definition lang_types.h:121
@ READ
a cache item is read
Definition lang_types.h:122
@ POST
produce to a place or queue buffer
Definition lang_types.h:127
@ DEP
a job departs
Definition lang_types.h:120
@ FIRE
an SPN mode fires
Definition lang_types.h:125
@ PRE
consume from a place or queue buffer, no server effect
Definition lang_types.h:126
NodeType
Node kinds, with the values of MATLAB NodeType.
Definition lang_types.h:345
T map_mean(const Map< T > &m)
Mean inter-arrival time, 1/lambda.
Definition map_moment.h:101
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,...
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
std::vector< std::vector< T > > from_marginal_node(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< std::size_t > &n, const std::vector< std::size_t > &phases)
Port of State.fromMarginal at its OWN signature: the reference indexes by NODE, not by station,...
Definition state.h:2332
bool from_marginal_node_first(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< std::size_t > &n, const std::vector< std::size_t > &phases, std::vector< T > &out)
The FIRST row from_marginal_node emits, BUILT rather than enumerated.
Definition state.h:2887
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...
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.
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.
FjTagged< T > fj_tag(const NetworkStruct< T > &sn, std::size_t tag_pool=0)
Port of ModelAdapter.fjtag.
Definition fj_tag.h:321
std::vector< GlobalSync< T > > refresh_global_sync(const NetworkStruct< T > &sn)
Port of MNetwork.refreshGlobalSync: the ENABLE and FIRE synchronizations.
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.
Matrix< T > rt_state(const NetworkStruct< T > &sn, const std::vector< std::vector< T > > &local)
Port of sn.rtfun: the routing over the stateful nodes AT ONE STATE.
Definition state.h:391
SsaSerialSolution< T > solver_ssa_serial(const qn::NetworkStruct< T > &sn, const SsaSerialOptions &opt)
The serial entry of solver_ssa_analyzer.m.
SsaSerialSolution< T > solver_ssa_serial_analyzer(const qn::NetworkStruct< T > &sn_in, const SsaSerialOptions &opt)
Port of solver_ssa_analyzer_serial.m plus the fork-join wrapper @@SolverSSA/runAnalyzer....
SsaReachability< T > solver_ssa_reachability(const qn::NetworkStruct< T > &sn, const SsaSerialOptions &opt=SsaSerialOptions())
Port of solver_ssa_reachability.m: the states the DYNAMICS can occupy, decomposed per stateful node.
SsaSerialSolution< T > solver_ssa_serial_on_struct(const qn::NetworkStruct< T > &sn_arg, const SsaSerialOptions &opt, const std::vector< qn::FjSync< T > > &fjsync)
Port of solver_ssa_analyzer_serial.m: run the serial engine and reduce its path to the metric table.
void fj_foldback(const qn::NetworkStruct< T > &sn, Avg &a, const std::vector< std::size_t > &fjclassmap, std::size_t korig)
Reduce the augmented metrics onto the original classes.
bool has_fork_join(const qn::NetworkStruct< T > &sn)
Whether the model needs the tag augmentation at all.
bool timeout_exceeded()
The checkpoint: true when the innermost budget has run out, marking it tripped.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
Replace every non-Markovian service and firing law by a Markovian surrogate.
Port of solver_ctmc.m: the infinitesimal generator of a queueing network, assembled from the enumerat...
Port of solver_ctmc_analyzer.m and the parts of @@SolverCTMC/runAnalyzer.m that surround one solve: t...
Finite Capacity Regions in SolverCTMC: the DROP rule, as a filter on the enumerated state space,...
Port of solver_ctmc_fcr_waitq.m: the reachability-built generator of a model whose finite capacity re...
Controls, results and the random source of SolverSSA.
Port of the MATLAB +State package: the encoding that turns a station's state row into marginal job co...
Port of the event half of MATLAB's +State package: the successor states an event produces at one node...
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
options.config.nonmkv and friends.
PhFit phfit
which surrogate family
The SolverCTMC knobs this port honours.
std::size_t state_max
refuse a space larger than this
double cutoff
< 0 = not given
One augmented state: the network state, plus the token FIFO of every region.
std::vector< std::vector< std::size_t > > buf
Matrix< T > D0
The (D0,D1) pair when the type carries one directly.
Definition lang_types.h:921
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
The parameters of a Cache node, MATLAB's sn.nodeparam{ind} for a Cache.
One fork firing synchronization: sn.fjsync{k}.
The augmented struct and everything needed to read its results back.
Definition fj_tag.h:72
std::vector< FjSync< T > > fjsync
Definition fj_tag.h:77
NetworkStruct< T > V
Definition fj_tag.h:73
std::size_t korig
Definition fj_tag.h:79
std::vector< std::size_t > fjclassmap
fjclassmap[a-1] is the ORIGINAL class of auxiliary class a, 0 for originals.
Definition fj_tag.h:75
One network state: the per-stateful-node local rows it is composed of.
Definition state.h:3022
Where node ind keeps its reply-block counters inside the local vars.
std::vector< std::size_t > classes
1-based calling classes holding a block
One station of the network.
std::vector< BalkingParam > balking
What the cache write-back of solver_ssa_analyzer_serial.m produces (and the NRM's).
Definition ssa_types.h:174
std::size_t node
1-based Cache node index
Definition ssa_types.h:175
std::vector< double > delayedprob
The delayed-hit share, EMPTY off a retrieval system.
Definition ssa_types.h:184
std::vector< double > missprob
per class, NaN where undefined
Definition ssa_types.h:176
std::vector< double > hitprob
Definition ssa_types.h:176
std::vector< double > residt
actualresidt: NaN, and NOT a port gap.
Definition ssa_types.h:190
Controls, defaulting to SolverOptions('SSA') in the reference.
Definition ssa_types.h:71
Port of solver_ssa_reachability.m's return: [SSq, SSh, sn.space].
std::vector< std::vector< std::vector< T > > > node_space
sn.space, per stateful node
Matrix< T > ssq
SSq, states x concatenated width
std::vector< qn::NetState< T > > space
the reachable states
std::vector< std::vector< std::size_t > > hash
SSh, 1-based per node
The serial engine's knobs: SsaOptions plus the three the serial path reads and the NRM has no use for...
std::size_t state_max
refuse a reachable space larger than this
One sample path, in the shape solver_ssa.m returns it.
std::vector< qn::NetState< T > > space
The DISTINCT states visited, in first-visit order (the reference's u).
std::vector< double > tran_time
tranSysState{1}: the cumulative time at each firing.
std::vector< std::size_t > tran_state
The row of space the path OCCUPIED over [t-dt, t], one per firing.
Matrix< T > ssq
SSq: the per-(station, class) job counts of each distinct state.
std::vector< std::vector< std::vector< double > > > start_rates
The DERIVED rates per state, laid out like arv_rates: how fast the transitions enabled in that state ...
std::size_t warmup
leading firings excluded from pi
unsigned long seed
the stream this path came from
std::vector< std::vector< std::vector< double > > > arv_rates
arvRates / depRates, indexed [distinct state][stateful-1][class-1].
std::vector< std::vector< std::vector< std::size_t > > > buf
The region token FIFOs of each of those states, the reference's fcrBuf.
std::size_t samples
firings actually performed
std::vector< std::vector< std::vector< double > > > dly_rates
The rate of the cache MERGE transitions, i.e.
std::vector< std::vector< std::vector< double > > > dep_rates
std::vector< std::vector< std::vector< double > > > preempt_rates
std::vector< double > pi
pi: the fraction of simulated time spent in each of them.
std::vector< std::size_t > tran_sync
tranSync: which synchronization fired, sync.size() + g for a global one.
The serial analyzer's return: the metric table, the path, and the stream.
std::vector< SsaCacheRatio > cache
std::vector< double > parked
Mean number of jobs parked in a region FIFO, per class of the struct that ran.
SsaSolution avg
QN, UN, RN, TN, XN, CN; method = "serial".
std::shared_ptr< const qn::NetworkStruct< T > > solved_sn
The struct the path was simulated on when it differs from the caller's (ctmc_mapc widens a multiserve...
unsigned long seed
carried beside the numbers, never implied
std::vector< std::size_t > fjclassmap
fjclassmap of the tag augmentation, empty on a model with no Fork.
What the analyzer returns, in the same shape as the MVA and fluid results.
Definition ssa_types.h:154
std::vector< double > XN
Definition ssa_types.h:156
std::vector< double > CN
Definition ssa_types.h:156
Matrix< double > UN
Definition ssa_types.h:155
Matrix< double > RN
Definition ssa_types.h:155
Matrix< double > StartN
The DERIVED rates, (nstations x nclasses): how often per unit time a class-r service STARTS at statio...
Definition ssa_types.h:164
double simulated_time
Simulated time the metrics are averaged over; the reference's totalTime.
Definition ssa_types.h:168
Matrix< double > TN
Definition ssa_types.h:155
std::size_t samples
Reaction firings actually performed.
Definition ssa_types.h:170
Matrix< double > QN
Definition ssa_types.h:155
std::string method
The concrete algorithm, as the reference's method.
Definition ssa_types.h:166
Matrix< double > PreemptN
Definition ssa_types.h:164