LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_ssa_nrm_space.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_NRM_SPACE_H
6#define LINE_SOLVERS_SSA_SOLVER_SSA_NRM_SPACE_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * SolverSSA, the EXPLICIT STATE SPACE variant of the Next Reaction Method: a
12 * port of `solver_ssa_nrm_space.m` and of the `else` branch of
13 * `solver_ssa_analyzer_nrm.m` that consumes it, together with
14 * `solver_ssa_findenabled.m`.
15 *
16 * HOW IT DIFFERS FROM THE PLAIN NRM. `solver_ssa_nrm.m` integrates the metrics
17 * along the path and never stores a state, so its cost is independent of how
18 * large the state space is. This variant instead TABULATES the path: it records
19 * every distinct state it visits, the time spent in each, and the whole
20 * propensity vector at each, and the analyzer then forms the means as `pi * A`
21 * rather than as a running time integral. That is the same answer by a different
22 * route -- which is exactly what makes the two testable against each other, and
23 * what the reference's `options.config.state_space_gen` switch selects between
24 * (`none` and `default` take the plain engine, anything else takes this one).
25 *
26 * WHAT THE TABLE BUYS. A propensity is a deterministic function of the state, so
27 * one observation of it IS its exact value and not a sample mean. The departure
28 * rates this variant reports are therefore exact per state, and all the Monte
29 * Carlo error left in the answer sits in `pi`. The plain engine cannot make that
30 * separation, because it never learns that two instants were the same state.
31 *
32 * WHAT IT COSTS, AND WHY THIS PORT REFUSES OPEN MODELS. The table has one row
33 * per distinct state, so the variant is only viable when the reachable space is
34 * small enough to enumerate. In the AGGREGATE reaction network an open model has
35 * no such space: `rtnodes` gives a Sink no outgoing routing, so jobs accumulate
36 * in its slot forever, and a Source's slot is a fictitious token that every
37 * arrival decrements and nothing replenishes. Every firing therefore reaches a
38 * state never seen before, the table grows one row per sample, and `pi` becomes
39 * a uniform law over the trace. The reference does not guard this; here an open
40 * model is REFUSED BY NAME, as is any closed model whose space exceeds the
41 * declared cap, because a truncated table would report a normalized `pi` over
42 * whichever states happened to fit.
43 *
44 * NO PHASE EXPANSION. The state is the (node, class) population vector, so a
45 * non-exponential service process is not represented: `solver_ssa_nrm_space.m`
46 * reads `sn.rates` alone and its propensity switch has five arms (EXT, INF, PS,
47 * FCFS/LCFS, and non-station). A phase-type process is refused by name rather
48 * than silently collapsed onto its mean rate, which would report the right
49 * throughput and the wrong queue length.
50 *
51 * ONE DELIBERATE DIVERGENCE, and it is a reference defect that MATLAB has
52 * already fixed on the other side. `solver_ssa_nrm_space.m` line 295 draws the
53 * destination with `1+find(rand>=cdfVec{kfire},1)`. `find(...,1)` returns the
54 * FIRST true index and the predicate holds on a prefix, so the expression
55 * collapses to 2 for every draw above `cdfVec(1)`: with three or more
56 * destinations the third onwards are never selected. `solver_ssa_nrm.m` line
57 * 1464 names this misuse in a comment and uses the inverse CDF instead, and
58 * `NrmEngine` is ported from the fixed form. This file uses the fixed form too,
59 * because reproducing the defect would silently misroute jobs and would make the
60 * two engines disagree on exactly the models they exist to cross-check.
61 *
62 * DOUBLE ONLY, for the reason `solver_ssa_nrm.h` gives: the clocks are `-log(u)`
63 * of a uniform, there is no exact value to compute, and the answer's error is
64 * the Monte Carlo error rather than the rounding.
65 *
66 * WHY `ssa_find_enabled` IS HERE. It is the standalone form of the scan the
67 * serial engine inlines (`solver_ssa.m` carries both and switches on
68 * `use_inline`), and it answers the same question this variant is built around:
69 * what can fire from a given state, tabulated rather than evaluated on the fly.
70 * It works at the STATE ENCODING level, not on the aggregate populations, so it
71 * does not interoperate with the engine below and is not used by it; the two are
72 * independent ports that share a file.
73 */
74
75#include <algorithm>
76#include <cmath>
77#include <cstddef>
78#include <limits>
79#include <map>
80#include <string>
81#include <type_traits>
82#include <vector>
83
86#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// solver_ssa_findenabled.m
98// ---------------------------------------------------------------------------
99
100/** One transition the enabled scan found: where it goes, and at what rate. */
101template <class T>
103 /** `enabled_sync`: index into `sync`, or `sync.size() + g` for a global one. */
104 std::size_t sync = 0;
105 /** `enabled_rates`: rate * p_active * p_route * p_passive. */
106 double rate = 0.0;
107 /** `enabled_next_states{act}`: the whole network state after it fires. */
109};
110
111/**
112 * Port of `solver_ssa_findenabled.m`: every synchronization that can fire in
113 * `state`, with the arrival and departure rates each carries.
114 *
115 * THE ENUMERATION IS WIDER THAN THE REFERENCE'S, and deliberately so. MATLAB
116 * calls `State.afterEvent` with `isSimulation = true`, which SAMPLES one
117 * successor row and returns the probability it was drawn with; the C++
118 * `after_event` is the enumeration-mode handler and returns every successor with
119 * its probability. So one reference entry becomes one entry per (active row,
120 * passive row) pair here, and the caller draws from the flattened list in one
121 * step instead of two. The induced jump chain is identical; the number of
122 * uniforms consumed is not, which is a statement about which random stream this
123 * is and not about which model it simulates.
124 *
125 * A ZERO RATE IS DROPPED rather than rewritten to 1e-38 "so that it is never
126 * selected". Keeping it leaves it in the arrival and departure statistics, where
127 * it is not a rounding difference but a rate the CTMC generator does not have,
128 * and these rates are what the analyzers integrate.
129 *
130 * `arv` and `dep` are indexed [stateful-1][class-1] and are OVERWRITTEN, not
131 * accumulated, so a caller may reuse one pair of buffers across states.
132 */
133template <class T>
134std::vector<EnabledEvent<T>> ssa_find_enabled(const qn::NetworkStruct<T>& sn,
135 const std::vector<qn::Sync<T>>& sync,
136 const std::vector<qn::GlobalSync<T>>& gsync,
137 const qn::NetState<T>& state,
138 std::vector<std::vector<double>>* arv = nullptr,
139 std::vector<std::vector<double>>* dep = nullptr) {
140 const std::size_t local = sn.nodes.size() + 1; // the dummy passive node
141 const std::size_t R = sn.nclasses;
142 const std::size_t NF = sn.stateful_nodes.size();
143 std::vector<EnabledEvent<T>> out;
144 if (arv) arv->assign(NF, std::vector<double>(R, 0.0));
145 if (dep) dep->assign(NF, std::vector<double>(R, 0.0));
146
147 for (std::size_t a = 0; a < sync.size(); ++a) {
148 const qn::Sync<T>& sy = sync[a];
149 const std::size_t isf_a = sn.stateful_index(sy.active.node);
150 if (isf_a == 0) continue; // a stateless node schedules nothing
151 const std::size_t isf_p =
152 sy.passive.node == local ? 0 : sn.stateful_index(sy.passive.node);
153 if (sy.passive.node != local && isf_p == 0) continue;
154
155 const qn::EventOutcome<T> oa = qn::after_event(sn, sy.active.node, state.local[isf_a - 1],
156 sy.active.event, sy.active.cls);
157 double fired = 0.0;
158 for (std::size_t ia = 0; ia < oa.space.size(); ++ia) {
159 const double rate = num_traits<T>::to_double(oa.rate[ia]);
160 const double pa = num_traits<T>::to_double(oa.prob[ia]);
161 if (!(rate > 0) || !(pa > 0)) continue;
162
163 if (sy.passive.node == local) {
165 e.sync = a;
166 e.rate = rate * pa;
167 e.next = state;
168 e.next.local[isf_a - 1] = oa.space[ia];
169 fired += e.rate;
170 out.push_back(e);
171 continue;
172 }
173 // A self-loop synchronization reads the passive node AFTER the
174 // active half has been applied, since they are the same node.
175 const std::vector<T>& src =
176 sy.passive.node == sy.active.node ? oa.space[ia] : state.local[isf_p - 1];
177 const qn::EventOutcome<T> op =
178 qn::after_event(sn, sy.passive.node, src, sy.passive.event, sy.passive.cls);
179 // NO ROWS is the reference's `prob_sync_p = 0`: the destination
180 // cannot take the job, so the upstream departure is disabled rather
181 // than fired into a state that does not exist.
182 for (std::size_t ip = 0; ip < op.space.size(); ++ip) {
183 const double pp = num_traits<T>::to_double(op.prob[ip]);
184 if (!(pp > 0)) continue;
186 e.sync = a;
187 e.rate = rate * pa * num_traits<T>::to_double(sy.passive.prob) * pp;
188 if (!(e.rate > 0)) continue;
189 e.next = state;
190 e.next.local[isf_a - 1] = oa.space[ia];
191 e.next.local[isf_p - 1] = op.space[ip];
192 fired += e.rate;
193 out.push_back(e);
194 }
195 }
196 // A DEP is one job leaving the active node and entering the passive one,
197 // so the same rate is a departure there and an arrival here.
198 if (sy.active.event == lang::EventType::DEP && fired > 0) {
199 if (dep) (*dep)[isf_a - 1][sy.active.cls - 1] += fired;
200 if (arv && isf_p != 0) (*arv)[isf_p - 1][sy.passive.cls - 1] += fired;
201 }
202 }
203
204 for (std::size_t g = 0; g < gsync.size(); ++g) {
205 const qn::GlobalOutcome<T> go = qn::after_global_event(sn, state, gsync[g]);
206 for (std::size_t io = 0; io < go.space.size(); ++io) {
207 const double w = num_traits<T>::to_double(go.rate[io]) *
209 if (!(w > 0)) continue;
211 e.sync = sync.size() + g;
212 e.rate = w;
213 e.next = go.space[io];
214 out.push_back(e);
215 if (gsync[g].active.event != lang::EventType::FIRE) continue;
216 for (std::size_t j = 0; j < gsync[g].passive.size(); ++j) {
217 const qn::ModeEvent<T>& pev = gsync[g].passive[j];
218 const std::size_t pisf = sn.stateful_index(pev.node);
219 if (pisf == 0 || pev.cls == 0 || pev.cls > R) continue;
220 if (pev.event == lang::EventType::PRE && dep)
221 (*dep)[pisf - 1][pev.cls - 1] += w;
222 else if (pev.event == lang::EventType::POST && arv)
223 (*arv)[pisf - 1][pev.cls - 1] += w;
224 }
225 }
226 }
227 return out;
228}
229
230// ---------------------------------------------------------------------------
231// solver_ssa_nrm_space.m
232// ---------------------------------------------------------------------------
233
234/**
235 * The knobs the space variant reads.
236 *
237 * `state_max` is the size of the table this variant is willing to build. It is
238 * not a truncation: the run refuses by name on reaching it, because a `pi`
239 * normalized over the states that happened to fit is a distribution over the
240 * wrong chain.
241 */
243 std::size_t state_max = 20000;
244};
245
246/**
247 * One state of the aggregate chain: the (node, class) populations, and the
248 * ordered buffer contents of every buffered node.
249 *
250 * THE BUFFERS ARE PART OF THE STATE, not bookkeeping beside it. Two FCFS states
251 * with the same populations but a different waiting order have different
252 * propensities, since the rate reads the jobs actually in service; the reference
253 * says as much where its hash function concatenates the buffer contents onto the
254 * population vector. The buffer is newest-first, so a departure takes the last
255 * entry under FCFS and the first under LCFS.
256 */
258 std::vector<double> n;
259 std::vector<std::vector<std::size_t>> buf;
260};
261
262/** What `solver_ssa_nrm_space.m` returns, plus what makes it a measurement. */
263template <class T>
265 /** `outspace`: the distinct states visited, in first-visit order. */
266 std::vector<NrmSpaceState> space;
267 /** `pi`: the fraction of simulated time spent in each of them. */
268 std::vector<double> pi;
269 /**
270 * `depRates`, (states x nnodes*nclasses): the departure rate of each (node,
271 * class) in each state, read off the cached propensity vector.
272 *
273 * EXACT PER STATE, not a sample mean: a propensity is a function of the
274 * state, so observing it once is knowing it. The reference stores the same
275 * vector in `reactCache` for the same reason.
276 */
278 /** `t`: the cumulative time at each firing. */
279 std::vector<double> tran_time;
280 /** `kfires`: which reaction fired. */
281 std::vector<std::size_t> tran_rx;
282 double simulated_time = 0.0;
283 std::size_t samples = 0;
284 unsigned long seed = 0;
285};
286
287/** The metric table, the table it came from, and the stream that produced it. */
288template <class T>
294
295namespace space_detail {
296
297using lang::NodeType;
299
300/** True for the two ordered-buffer disciplines this variant's rate law covers. */
301inline bool space_sched_buffered(SchedStrategy s) {
302 return s == SchedStrategy::FCFS || s == SchedStrategy::LCFS;
303}
304
305} // namespace space_detail
306
307/**
308 * The aggregate NRM engine of `solver_ssa_nrm_space.m`.
309 *
310 * It is a class for the reason `NrmEngine` is, and it is a SEPARATE class rather
311 * than a mode of that one because the two disagree about what a state is: this
312 * one has no phase dimension, five rate laws instead of thirteen, and a table
313 * keyed on (population, buffers) that the plain engine has no place to put. The
314 * pieces that look alike -- the stoichiometry from `rtnodes`, the dependency
315 * sets, the newest-first buffer -- are alike because both are ports of the same
316 * reference construction, and are written out here rather than shared because
317 * `NrmEngine` exposes none of them.
318 */
319template <class T>
321public:
323 : sn_(sn), opt_(opt), rng_(opt.seed) {
324 check();
325 build_layout();
326 build_reactions();
327 build_dependencies();
328 build_initial_state();
329 }
330
331 /** Run `opt.samples` firings and return the tabulated path. */
333
334 /**
335 * The reachable aggregate state space, closed forward from the initial state
336 * over the REACTIONS alone.
337 *
338 * This is the space the run indexes into, and it is derived from the
339 * reaction network rather than from the state handlers, so comparing it with
340 * `reachable_space_generator`'s answer compares two independent accounts of
341 * what the model can do.
342 */
343 std::vector<NrmSpaceState> enumerate_space() const;
344
345 std::size_t nreactions() const { return nrx_; }
346 std::size_t nslots() const { return NS_; }
347 const NrmSpaceState& initial() const { return init_; }
348 /** The whole propensity vector at a state, the reference's `reactCache` entry. */
349 std::vector<double> propensities(const NrmSpaceState& s) const {
350 std::vector<double> A(nrx_, 0.0);
351 for (std::size_t k = 0; k < nrx_; ++k) A[k] = propensity(k, s);
352 return A;
353 }
354
355private:
356 using SchedStrategy = lang::SchedStrategy;
357
358 const qn::NetworkStruct<T>& sn_;
360 SsaRng rng_;
361
362 std::size_t I_ = 0, K_ = 0, M_ = 0, NS_ = 0, nrx_ = 0;
363 std::vector<bool> is_station_;
364 std::vector<std::size_t> to_station_;
365 std::vector<SchedStrategy> sched_;
366 std::vector<double> mi_;
367 std::vector<std::vector<double>> rate_;
368
370 /** Per reaction: the slot it consumes, its destination slots and their CDF. */
371 std::vector<std::size_t> rx_node_, rx_class_, rx_from_, rx_det_dest_;
372 std::vector<std::vector<std::size_t>> rx_to_;
373 std::vector<std::vector<double>> rx_cdf_;
374 std::vector<std::size_t> rx_nnzp_;
375 std::vector<std::vector<std::size_t>> D_;
376
377 NrmSpaceState init_;
378
379 void check();
380 void build_layout();
381 void build_reactions();
382 void build_dependencies();
383 void build_initial_state();
384
385 double class_pop(const std::vector<double>& X, std::size_t ind, std::size_t r) const {
386 return X[ind * K_ + r];
387 }
388 double node_pop(const std::vector<double>& X, std::size_t ind) const {
389 double s = 0.0;
390 for (std::size_t r = 0; r < K_; ++r) s += X[ind * K_ + r];
391 return s;
392 }
393 double propensity(std::size_t j, const NrmSpaceState& s) const;
394 void update_buffers(std::size_t kfire, const std::vector<double>& n,
395 std::vector<std::vector<std::size_t>>& bufs, std::size_t dest_pos,
396 bool have_dest) const;
397
398 static constexpr std::size_t npos = static_cast<std::size_t>(-1);
399};
400
401/**
402 * What this variant cannot represent, refused before a single firing.
403 *
404 * The scheduling list is the propensity switch of `solver_ssa_nrm_space.m`, and
405 * it is much shorter than the plain NRM's: the reference's own analyzer stub
406 * narrows it further still, to INF/EXT/PS.
407 */
408template <class T>
409void NrmSpaceEngine<T>::check() {
410 for (std::size_t i = 0; i < sn_.nstations; ++i) {
411 const SchedStrategy s = sn_.stations[i].sched;
412 if (s == SchedStrategy::INF || s == SchedStrategy::EXT || s == SchedStrategy::PS ||
413 s == SchedStrategy::FCFS || s == SchedStrategy::LCFS)
414 continue;
415 throw UnsupportedError(ErrorKind{"SchedStrategy"},
416 "solver_ssa_nrm_space: station '" + sn_.stations[i].name + "' uses '" +
417 std::string(lang::sched_to_text(s)) +
418 "' scheduling, which has no rate law in the explicit state-space variant. Its "
419 "propensity switch covers EXT, INF, PS, FCFS and LCFS only; use method='nrm', whose "
420 "engine carries the full set");
421 }
422 for (std::size_t i = 0; i < sn_.nstations; ++i)
423 for (std::size_t r = 0; r < sn_.nclasses; ++r) {
424 if (sn_.disabled[i][r]) continue;
425 const lang::ProcessType pt = sn_.service[i][r].type;
428 continue;
429 throw UnsupportedError(ErrorKind{"NonExponential"},
430 "solver_ssa_nrm_space: class '" + sn_.classes[r].name +
431 "' has non-exponential service at station '" + sn_.stations[i].name +
432 "'. The explicit state-space variant carries no phase dimension -- its state is "
433 "the (node, class) population vector and it reads sn.rates alone -- so a "
434 "phase-type process cannot be represented; use method='nrm', which expands it");
435 }
436 for (std::size_t r = 0; r < sn_.nclasses; ++r)
437 if (!std::isfinite(sn_.classes[r].population))
438 throw UnsupportedError(ErrorKind{"OpenClass"},
439 "solver_ssa_nrm_space: class '" + sn_.classes[r].name +
440 "' is open. In the aggregate reaction network a Sink has no outgoing routing and "
441 "a Source's slot is a fictitious token that every arrival consumes, so the "
442 "aggregate state space of an open model is unbounded: every firing would add a "
443 "row to the table and pi would become the uniform law over the trace. Use "
444 "method='nrm', which integrates the metrics and stores no states");
445 // The plain NRM gained both of these on 2026-09-24; this variant did not, and
446 // the dispatch gate no longer stops them before they reach it.
447 for (std::size_t i = 0; i < sn_.nstations; ++i)
448 if (sn_.stations[i].cdscaling || sn_.stations[i].jdscaling)
449 throw UnsupportedError(ErrorKind{"ClassDependence"},
450 "solver_ssa_nrm_space: station '" + sn_.stations[i].name +
451 "' declares a class- or joint-dependent scaling. The explicit state-space "
452 "variant builds its propensities from sn.rates without evaluating the handle; "
453 "use method='nrm', whose engine applies it");
454 if (!sn_.regions.empty())
455 throw UnsupportedError(ErrorKind{"Region"},
456 "solver_ssa_nrm_space: the model declares a finite capacity region. The explicit "
457 "state-space variant carries no region gate and no WAITQ FIFO; use method='nrm', "
458 "whose engine carries both");
459 for (const qn::NodeDef& nd : sn_.nodes) {
460 switch (nd.nodetype) {
462 throw UnsupportedError(ErrorKind{"Cache"},
463 "solver_ssa_nrm_space: node '" + nd.name +
464 "' is a Cache. The aggregate reaction network is built from sn.rtnodes and "
465 "sn.rates alone and carries no cache contents, so the hit/miss class switch "
466 "cannot be resolved at firing time");
469 throw UnsupportedError(ErrorKind{"Place"},
470 "solver_ssa_nrm_space: node '" + nd.name +
471 "' makes this model a stochastic Petri net. A firing is atomic across every "
472 "arc it touches and is not a (node, class) departure, which is the only "
473 "reaction shape this variant builds");
476 throw UnsupportedError(ErrorKind{"Fork"},
477 "solver_ssa_nrm_space: node '" + nd.name +
478 "' makes this a fork-join model. A fork emits on several branches at once, "
479 "which no single-destination reaction can express, and the NRM does not "
480 "handle fork-join in any codebase");
481 default:
482 break;
483 }
484 }
485 // `sn.isslc`, the SELF-LOOPING CLASS whose reaction consumes a job and
486 // produces none, has no field in the C++ NetworkStruct, so the reference's
487 // `Srow(from) = -Inf` branch is unreachable here rather than unported.
488}
489
490template <class T>
491void NrmSpaceEngine<T>::build_layout() {
492 I_ = sn_.nof_nodes();
493 K_ = sn_.nclasses;
494 M_ = sn_.nstations;
495 NS_ = I_ * K_;
496
497 is_station_.assign(I_, false);
498 to_station_.assign(I_, npos);
499 for (std::size_t i = 0; i < I_; ++i)
500 if (sn_.nodes[i].station != 0) {
501 is_station_[i] = true;
502 to_station_[i] = sn_.nodes[i].station - 1;
503 }
504 sched_.assign(M_, SchedStrategy::FCFS);
505 for (std::size_t i = 0; i < M_; ++i) sched_[i] = sn_.stations[i].sched;
506
507 // A non-station is given the immediate rate and an unbounded server count,
508 // which is what makes a Router or a ClassSwitch a pass-through in the
509 // aggregate chain rather than a place a job can accumulate.
510 mi_.assign(I_, lang::GlobalConstants::MaxInt);
511 rate_.assign(I_, std::vector<double>(K_, 0.0));
512 for (std::size_t i = 0; i < I_; ++i) {
513 if (is_station_[i]) {
514 const std::size_t ist = to_station_[i];
515 mi_[i] = sn_.stations[ist].nservers;
516 if (!std::isfinite(mi_[i])) mi_[i] = lang::GlobalConstants::MaxInt;
517 for (std::size_t r = 0; r < K_; ++r)
518 if (!sn_.disabled[ist][r])
519 rate_[i][r] = num_traits<T>::to_double(sn_.rates(ist, r));
520 } else {
521 for (std::size_t r = 0; r < K_; ++r) rate_[i][r] = lang::GlobalConstants::Immediate;
522 }
523 }
524}
525
526/**
527 * The stoichiometry, one reaction per (node, class).
528 *
529 * There is no phase dimension, so a reaction IS a departure: it consumes one job
530 * from its own slot and deposits the routing probability into every slot
531 * `rtnodes` sends it to. The fractional entries are not a fluid relaxation --
532 * they are the weights the destination draw reads, and exactly one destination
533 * receives the whole job at firing time.
534 */
535template <class T>
536void NrmSpaceEngine<T>::build_reactions() {
537 nrx_ = I_ * K_;
538 rx_node_.assign(nrx_, 0);
539 rx_class_.assign(nrx_, 0);
540 rx_from_.assign(nrx_, 0);
541 rx_det_dest_.assign(nrx_, npos);
542 rx_to_.assign(nrx_, std::vector<std::size_t>());
543 rx_cdf_.assign(nrx_, std::vector<double>());
544 rx_nnzp_.assign(nrx_, 0);
545 S_ = Matrix<double>(NS_, nrx_, 0.0);
546
547 for (std::size_t ind = 0; ind < I_; ++ind)
548 for (std::size_t r = 0; r < K_; ++r) {
549 const std::size_t k = ind * K_ + r;
550 rx_node_[k] = ind;
551 rx_class_[k] = r;
552 rx_from_[k] = k;
553 S_(k, k) -= 1.0;
554 for (std::size_t jnd = 0; jnd < I_; ++jnd)
555 for (std::size_t s = 0; s < K_; ++s) {
556 const double p =
557 num_traits<T>::to_double(sn_.rtnodes(ind * K_ + r, jnd * K_ + s));
558 if (!(p > 0.0)) continue;
559 S_(jnd * K_ + s, k) += p;
560 }
561 }
562
563 // `P = S; P(P<0) = P(P<0)+1`: a class routing back into its own slot must
564 // compete with the other destinations on equal footing, which subtracting
565 // the consumed job first is what achieves.
566 for (std::size_t k = 0; k < nrx_; ++k) {
567 std::vector<double> Pcol(NS_, 0.0);
568 for (std::size_t i = 0; i < NS_; ++i) {
569 const double v = S_(i, k);
570 Pcol[i] = v < 0.0 ? v + 1.0 : v;
571 if (v > 0.0 && rx_det_dest_[k] == npos) rx_det_dest_[k] = i;
572 }
573 for (std::size_t i = 0; i < NS_; ++i)
574 if (Pcol[i] != 0.0) ++rx_nnzp_[k];
575 // A job that routes back into the slot it came from with probability one
576 // leaves an ALL-ZERO stoichiometry column, so `find(S(:,k) > 0)` finds
577 // nothing and the reference records no destination. At a buffered
578 // station that loses the job from the buffer while leaving the
579 // population alone, breaking numel(buf) == max(0, total - mi) and
580 // silencing the rate law. Naming the source as the destination is the
581 // same arithmetic on the population and the correct one on the buffer.
582 if (rx_nnzp_[k] == 1 && rx_det_dest_[k] == npos && Pcol[rx_from_[k]] != 0.0)
583 rx_det_dest_[k] = rx_from_[k];
584 if (rx_nnzp_[k] > 1) {
585 double acc = 0.0;
586 for (std::size_t i = 0; i < NS_; ++i)
587 if (Pcol[i] != 0.0) {
588 rx_to_[k].push_back(i);
589 acc += Pcol[i];
590 rx_cdf_[k].push_back(acc);
591 }
592 }
593 }
594}
595
596/**
597 * The dependency sets: which propensities a firing invalidates.
598 *
599 * Every rate law reads its node's WHOLE class-count vector, so a firing that
600 * touches any slot of a node invalidates every reaction consuming from that
601 * node, not merely the slot that moved.
602 */
603template <class T>
604void NrmSpaceEngine<T>::build_dependencies() {
605 D_.assign(nrx_, std::vector<std::size_t>());
606 for (std::size_t k = 0; k < nrx_; ++k) {
607 std::vector<bool> touched(I_, false);
608 for (std::size_t i = 0; i < NS_; ++i)
609 if (S_(i, k) != 0.0) touched[i / K_] = true;
610 for (std::size_t ind = 0; ind < I_; ++ind) {
611 if (!touched[ind]) continue;
612 for (std::size_t r = 0; r < K_; ++r) D_[k].push_back(ind * K_ + r);
613 }
614 std::sort(D_[k].begin(), D_[k].end());
615 D_[k].erase(std::unique(D_[k].begin(), D_[k].end()), D_[k].end());
616 }
617}
618
619/**
620 * The initial state.
621 *
622 * The reference reads `sn.state` through `State.toMarginalAggr`; this port has
623 * no State package on the aggregate side, so it uses the same rule
624 * `solver_ssa_nrm.h` does -- a closed class starts entirely at its reference
625 * station. The chain is ergodic, so the steady-state means do not depend on the
626 * choice.
627 */
628template <class T>
629void NrmSpaceEngine<T>::build_initial_state() {
630 init_.n.assign(NS_, 0.0);
631 init_.buf.assign(I_, std::vector<std::size_t>());
632 for (std::size_t r = 0; r < K_; ++r) {
633 const double pop = sn_.classes[r].population;
634 if (!(pop > 0.0)) continue;
635 const std::size_t rs = sn_.classes[r].refstat;
636 if (rs < 1 || rs > M_)
637 throw InputError("solver_ssa_nrm_space: class '" + sn_.classes[r].name +
638 "' has no reference station");
639 init_.n[(sn_.station_to_node[rs - 1] - 1) * K_ + r] = pop;
640 }
641 // The buffer holds exactly the waiting jobs, so its length is the excess
642 // over the server count; which classes wait is immaterial to the steady
643 // state, so they are taken in class order.
644 for (std::size_t ind = 0; ind < I_; ++ind) {
645 if (!is_station_[ind] || !space_detail::space_sched_buffered(sched_[to_station_[ind]]))
646 continue;
647 double waiting = std::max(0.0, node_pop(init_.n, ind) - mi_[ind]);
648 for (std::size_t r = 0; r < K_ && waiting > 0.0; ++r) {
649 const double take = std::min(waiting, init_.n[ind * K_ + r]);
650 for (std::size_t c = 0; c < static_cast<std::size_t>(take); ++c)
651 init_.buf[ind].push_back(r);
652 waiting -= take;
653 }
654 }
655}
656
657/** The five-armed propensity switch of `solver_ssa_nrm_space.m` lines 136-161. */
658template <class T>
659double NrmSpaceEngine<T>::propensity(std::size_t j, const NrmSpaceState& st) const {
660 const std::size_t ind = rx_node_[j], r = rx_class_[j];
661 const std::vector<double>& X = st.n;
662 if (!is_station_[ind]) {
663 // A pass-through node moves at most one job at a time at the immediate
664 // rate: the min is what keeps an empty node silent rather than firing at
665 // 1e8 into a slot that holds nothing.
666 return rate_[ind][r] * std::min(1.0, class_pop(X, ind, r));
667 }
668 const std::size_t ist = to_station_[ind];
669 const double eps = lang::GlobalConstants::Zero;
670 switch (sched_[ist]) {
671 case SchedStrategy::EXT:
672 return rate_[ind][r];
673 case SchedStrategy::INF:
674 return rate_[ind][r] * class_pop(X, ind, r);
675 case SchedStrategy::PS: {
676 if (K_ == 1) return rate_[ind][r] * std::min(mi_[ind], class_pop(X, ind, r));
677 const double tot = node_pop(X, ind);
678 return rate_[ind][r] * (class_pop(X, ind, r) / (eps + tot)) *
679 std::min(mi_[ind], eps + tot);
680 }
681 case SchedStrategy::FCFS:
682 case SchedStrategy::LCFS: {
683 // The jobs actually in service are the class population less the
684 // class-r jobs still waiting, which is why the buffer has to be part
685 // of the state and not merely of the bookkeeping.
686 double waiting = 0.0;
687 for (std::size_t c : st.buf[ind])
688 if (c == r) waiting += 1.0;
689 return rate_[ind][r] * std::max(0.0, class_pop(X, ind, r) - waiting);
690 }
691 default:
692 throw UnsupportedError(ErrorKind{"SchedStrategy"},
693 "solver_ssa_nrm_space: the scheduling policy '" +
694 std::string(lang::sched_to_text(sched_[ist])) + "' at station '" +
695 sn_.stations[ist].name + "' has no rate law in the explicit state-space variant");
696 }
697}
698
699/**
700 * `updateBuffers`: the ordered buffers after reaction `kfire` has fired.
701 *
702 * A departure frees a server, so the discipline promotes a waiting job: FCFS
703 * takes the oldest, which is the LAST entry of a newest-first buffer, and LCFS
704 * the newest, which is the first. An arrival joins the buffer only when it finds
705 * every server busy, and the test is made on the POST-firing population, which
706 * already counts the arriving job.
707 */
708template <class T>
709void NrmSpaceEngine<T>::update_buffers(std::size_t kfire, const std::vector<double>& n,
710 std::vector<std::vector<std::size_t>>& bufs,
711 std::size_t dest_pos, bool have_dest) const {
712 const std::size_t ind = rx_node_[kfire];
713 if (is_station_[ind] && !bufs[ind].empty()) {
714 const SchedStrategy s = sched_[to_station_[ind]];
715 if (s == SchedStrategy::FCFS) bufs[ind].pop_back();
716 else if (s == SchedStrategy::LCFS) bufs[ind].erase(bufs[ind].begin());
717 }
718 if (!have_dest || dest_pos == npos) return;
719 const std::size_t jnd = dest_pos / K_, s = dest_pos % K_;
720 if (!is_station_[jnd] || !space_detail::space_sched_buffered(sched_[to_station_[jnd]])) return;
721 if (node_pop(n, jnd) > mi_[jnd]) bufs[jnd].insert(bufs[jnd].begin(), s);
722}
723
724namespace space_detail {
725
726/** The table key: the populations, then each node's buffer behind a separator. */
727inline std::vector<double> space_key(const NrmSpaceState& s) {
728 std::vector<double> key = s.n;
729 for (std::size_t i = 0; i < s.buf.size(); ++i) {
730 // The separator keeps two different splits of the same concatenation
731 // from colliding, which a plain flatten would allow.
732 key.push_back(-1.0);
733 for (std::size_t j = 0; j < s.buf[i].size(); ++j)
734 key.push_back(static_cast<double>(s.buf[i][j]) + 1.0);
735 }
736 return key;
737}
738
739} // namespace space_detail
740
741template <class T>
742std::vector<NrmSpaceState> NrmSpaceEngine<T>::enumerate_space() const {
743 std::vector<NrmSpaceState> out;
744 std::map<std::vector<double>, std::size_t> seen;
745 std::vector<std::size_t> stack;
746 seen[space_detail::space_key(init_)] = 0;
747 out.push_back(init_);
748 stack.push_back(0);
749
750 std::size_t expanded = 0;
751 while (!stack.empty()) {
752 // Wall-clock budget (options.timeout), every 1024 states: a reachable
753 // set cut short has no valid partial solution, so it raises.
754 if ((++expanded & 1023u) == 0)
755 util::timeout_check("SSA state-space enumeration (raise the budget)");
756 const std::size_t si = stack.back();
757 stack.pop_back();
758 const NrmSpaceState st = out[si]; // by value: `out` grows inside the loop
759 for (std::size_t k = 0; k < nrx_; ++k) {
760 if (!(propensity(k, st) > 0.0)) continue;
761 // Every destination the firing could draw is a distinct successor,
762 // which is what makes this the reachable set of the CHAIN rather
763 // than of one realization of it.
764 std::vector<std::size_t> dests;
765 if (rx_nnzp_[k] > 1) dests = rx_to_[k];
766 else if (rx_det_dest_[k] != npos) dests.push_back(rx_det_dest_[k]);
767 else dests.push_back(npos);
768 for (std::size_t d = 0; d < dests.size(); ++d) {
769 NrmSpaceState ns = st;
770 ns.n[rx_from_[k]] -= 1.0;
771 if (dests[d] != npos) ns.n[dests[d]] += 1.0;
772 update_buffers(k, ns.n, ns.buf, dests[d], dests[d] != npos);
773 const std::vector<double> key = space_detail::space_key(ns);
774 if (seen.find(key) != seen.end()) continue;
775 if (out.size() >= opt_.state_max)
776 throw UnsupportedError(ErrorKind{"StateSpace"},
777 "solver_ssa_nrm_space: the reachable aggregate state space exceeds the "
778 "cap of " + std::to_string(opt_.state_max) +
779 " states. The explicit state-space variant tabulates one row per state, "
780 "so a larger space is refused rather than truncated: a pi normalized over "
781 "the states that happened to fit is the law of a different chain. Raise "
782 "state_max, or use method='nrm', which stores no states");
783 seen[key] = out.size();
784 out.push_back(ns);
785 stack.push_back(out.size() - 1);
786 }
787 }
788 }
789 return out;
790}
791
792template <class T>
794 // The clocks are -log(u), so the backend must have a logarithm at all. The
795 // analyzer gates on `double` before instantiating this; a caller reaching
796 // the assert got past that gate and deserves a sentence rather than a
797 // compile error inside the uniform draw.
799 "solver_ssa_nrm_space: the Next Reaction Method draws its clocks as -log(u), "
800 "which needs transcendental arithmetic");
801
803 out.seed = opt_.seed;
804 if (nrx_ == 0) return out;
805
806 NrmSpaceState cur = init_;
807 std::vector<double> Ak(nrx_, 0.0), Pk(nrx_, 0.0), Tk(nrx_, 0.0), tau(nrx_, 0.0);
808 for (std::size_t k = 0; k < nrx_; ++k) {
809 Ak[k] = propensity(k, cur);
810 Pk[k] = -std::log(rng_.uniform());
811 tau[k] = Ak[k] > 0.0 ? (Pk[k] - Tk[k]) / Ak[k] : std::numeric_limits<double>::infinity();
812 }
813
814 // The table. `pi` accumulates holding time and the propensity vector is
815 // stored the first time a state is seen, exactly as `reactCache` does.
816 std::map<std::vector<double>, std::size_t> index;
817 std::vector<std::vector<double>> cached;
818 double total_time = 0.0;
819
820 out.tran_time.reserve(opt_.samples);
821 out.tran_rx.reserve(opt_.samples);
822 // Warmup discard (`ssa_resolve_warmupfrac`): the first `n_warm` sojourns
823 // enter no probability. The path and its clock keep every firing.
824 const std::size_t n_warm = ssa_warmup_firings(opt_.warmupfrac, opt_.samples);
825 bool time_stopped = false;
826 for (std::size_t n = 0; n < opt_.samples; ++n) {
827 // Wall-clock budget (options.timeout), every 1024 firings: the path so
828 // far is the interim solution, as `solver_ssa_nrm.m` stops it.
829 if (n > 0 && (n & 1023u) == 0 && util::timeout_exceeded()) {
830 time_stopped = true;
831 break;
832 }
833 std::size_t kfire = 0;
834 double dt = std::numeric_limits<double>::infinity();
835 for (std::size_t k = 0; k < nrx_; ++k)
836 if (tau[k] < dt) {
837 dt = tau[k];
838 kfire = k;
839 }
840 if (std::isinf(dt))
841 throw NumericError(ErrorKind{"Degenerate"},
842 "solver_ssa_nrm_space: deadlock -- every reaction has propensity zero, so the "
843 "sample path cannot advance");
844
845 // The state is recorded with the time spent IN it, so the pair belongs
846 // to the state before the firing.
847 const std::vector<double> key = space_detail::space_key(cur);
848 const std::map<std::vector<double>, std::size_t>::const_iterator it = index.find(key);
849 std::size_t si;
850 if (it != index.end()) {
851 si = it->second;
852 } else {
853 if (out.space.size() >= opt_.state_max)
854 throw UnsupportedError(ErrorKind{"StateSpace"},
855 "solver_ssa_nrm_space: the path has visited more than the cap of " +
856 std::to_string(opt_.state_max) +
857 " distinct states. The explicit state-space variant tabulates one row per "
858 "state, so it is refused rather than truncated: a pi normalized over the "
859 "states that happened to fit is the law of a different chain. Raise "
860 "state_max, or use method='nrm', which stores no states");
861 si = out.space.size();
862 index[key] = si;
863 out.space.push_back(cur);
864 out.pi.push_back(0.0);
865 cached.push_back(Ak);
866 }
867 if (n >= n_warm) out.pi[si] += dt;
868 total_time += dt;
869 out.tran_time.push_back(total_time);
870 out.tran_rx.push_back(kfire);
871
872 // Apply the firing.
873 std::size_t dest = npos;
874 if (rx_nnzp_[kfire] > 1) {
875 // Inverse CDF: the smallest index whose cumulative weight exceeds
876 // the draw. See the divergence note at the top of this file.
877 const double u = rng_.uniform();
878 std::size_t sel = rx_cdf_[kfire].size() - 1;
879 for (std::size_t i = 0; i < rx_cdf_[kfire].size(); ++i)
880 if (rx_cdf_[kfire][i] > u) {
881 sel = i;
882 break;
883 }
884 dest = rx_to_[kfire][sel];
885 cur.n[rx_from_[kfire]] -= 1.0;
886 cur.n[dest] += 1.0;
887 } else {
888 for (std::size_t i = 0; i < NS_; ++i)
889 if (S_(i, kfire) != 0.0) cur.n[i] += S_(i, kfire);
890 dest = rx_det_dest_[kfire];
891 }
892 update_buffers(kfire, cur.n, cur.buf, dest, dest != npos);
893
894 for (std::size_t k = 0; k < nrx_; ++k) Tk[k] += Ak[k] * dt;
895 // D covers every node the stoichiometry touched, source and every
896 // candidate destination alike, and the arrival's buffer join is already
897 // applied when those are refreshed. What it does NOT cover is a
898 // PROMOTION: the departing job's replacement enters service without any
899 // slot moving, and at a self-routing reaction the column is all zeros
900 // and D is empty outright. A firing at a buffered node therefore forces
901 // a sweep, which is the same order as the clock scan above and so costs
902 // nothing asymptotically.
903 for (std::size_t k : D_[kfire]) Ak[k] = propensity(k, cur);
904 if (is_station_[rx_node_[kfire]] &&
905 space_detail::space_sched_buffered(sched_[to_station_[rx_node_[kfire]]]))
906 for (std::size_t k = 0; k < nrx_; ++k) Ak[k] = propensity(k, cur);
907
908 Pk[kfire] -= std::log(rng_.uniform());
909 for (std::size_t k = 0; k < nrx_; ++k)
910 tau[k] =
911 Ak[k] > 0.0 ? (Pk[k] - Tk[k]) / Ak[k] : std::numeric_limits<double>::infinity();
912 out.samples = n + 1;
913 }
914 // Stopped inside the warmup: every sojourn so far is excluded by
915 // definition, so there is no interim probability to return.
916 if (time_stopped && out.samples <= n_warm)
917 throw NumericError(ErrorKind{"Timeout"},
918 "solver_ssa_nrm_space: the wall-clock time budget (options.timeout) "
919 "ran out inside the warmup, before any sample was collected");
920
921 double tot = 0.0;
922 for (std::size_t s = 0; s < out.pi.size(); ++s) tot += out.pi[s];
923 if (tot > 0)
924 for (std::size_t s = 0; s < out.pi.size(); ++s) out.pi[s] /= tot;
925 out.simulated_time = total_time;
926
927 // The departure rate of (node, class) in a state IS the propensity of its
928 // reaction there, which is why the cache is what the analyzer reads.
929 out.dep_rates = Matrix<double>(out.space.size(), NS_, 0.0);
930 for (std::size_t s = 0; s < out.space.size(); ++s)
931 for (std::size_t k = 0; k < nrx_; ++k)
932 out.dep_rates(s, rx_from_[k]) += cached[s][k];
933 return out;
934}
935
936/** `solver_ssa_nrm_space.m`: run the tabulating engine. */
937template <class T>
943
944/**
945 * Port of the `else` branch of `solver_ssa_analyzer_nrm.m`, the one
946 * `state_space_gen` selects: the means as `pi * A` over the tabulated states.
947 *
948 * THE STANDALONE `solver_ssa_nrm_space_analyzer.m` IS A STUB. Its whole body is
949 * the INF/EXT/PS scheduling gate and a debug line; it assigns none of its nine
950 * declared outputs, so calling it in MATLAB raises "Output argument not
951 * assigned". The working analyzer is the branch ported here, whose utilization
952 * switch admits FCFS and LCFS as well -- which is also the set the engine has
953 * rate laws for, so narrowing to the stub's three would refuse models this
954 * variant can simulate. The stub's narrower gate is therefore NOT reproduced,
955 * and the divergence is named rather than hidden.
956 *
957 * A SOURCE REPORTS ZERO QLen AND ZERO Util, not the negative number the
958 * reference's `UN(ist,:) = QN(ist,:)` produces for an EXT station: the Source
959 * slot is a fictitious token that arrivals consume, so its time average is
960 * 1 - E[jobs in system]. `solver_ssa_nrm.h` states the rule at length and this
961 * port applies it everywhere. It is moot for the models this variant accepts,
962 * since an open one is refused outright, and it is kept so the rule holds
963 * uniformly.
964 */
965template <class T>
967 const SsaNrmSpaceOptions& opt) {
968 // `if constexpr`, not a run-time test: the engine takes the logarithm of a
969 // uniform, so a Rational instantiation would fail to COMPILE rather than
970 // refuse. The gate has to keep the body from being instantiated at all.
971 if constexpr (!std::is_same<T, double>::value) {
972 (void)sn;
973 (void)opt;
974 throw UnsupportedError(ErrorKind{"Arithmetic"},
975 "solver_ssa_nrm_space: an SSA sample path is generated from exponential clocks, which "
976 "are logarithms of uniform draws; there is no exact value to compute and a wider "
977 "float carries no information the Monte Carlo error does not swamp. Rerun with "
978 "--arith double");
979 } else {
981 const std::size_t M = sn.nstations, K = sn.nclasses;
983 out.seed = opt.seed;
984
986 out.run = eng.run();
987 const SsaNrmSpaceRun<T>& r = out.run;
988
989 SsaSolution& a = out.avg;
990 a.method = "nrm.space";
991 a.samples = r.samples;
993 a.QN = Matrix<double>(M, K, 0.0);
994 a.UN = Matrix<double>(M, K, 0.0);
995 a.RN = Matrix<double>(M, K, 0.0);
996 a.TN = Matrix<double>(M, K, 0.0);
997 a.XN.assign(K, 0.0);
998 a.CN.assign(K, 0.0);
999
1000 for (std::size_t k = 0; k < K; ++k) {
1001 const std::size_t refnd = sn.station_to_node[sn.classes[k].refstat - 1];
1002 for (std::size_t s = 0; s < r.space.size(); ++s)
1003 a.XN[k] += r.pi[s] * r.dep_rates(s, (refnd - 1) * K + k);
1004 }
1005
1006 for (std::size_t ist = 0; ist < M; ++ist) {
1007 const std::size_t ind = sn.station_to_node[ist];
1008 for (std::size_t k = 0; k < K; ++k)
1009 for (std::size_t s = 0; s < r.space.size(); ++s) {
1010 a.TN(ist, k) += r.pi[s] * r.dep_rates(s, (ind - 1) * K + k);
1011 a.QN(ist, k) += r.pi[s] * r.space[s].n[(ind - 1) * K + k];
1012 }
1013
1014 const SchedStrategy sched = sn.stations[ist].sched;
1015 if (sched == SchedStrategy::EXT ||
1016 sn.stations[ist].nodetype == lang::NodeType::Source) {
1017 for (std::size_t k = 0; k < K; ++k) a.QN(ist, k) = 0.0;
1018 continue;
1019 }
1020 if (sched == SchedStrategy::INF) {
1021 for (std::size_t k = 0; k < K; ++k) a.UN(ist, k) = a.QN(ist, k);
1022 continue;
1023 }
1024 // PS, FCFS and LCFS: the carried load T/(mu*c). A class-dependent
1025 // station normalizes by its DECLARED peak instead, which is the only
1026 // thing its utilization can be a fraction of.
1027 const bool is_cd = static_cast<bool>(sn.stations[ist].cdscaling);
1028 const bool is_jd = static_cast<bool>(sn.stations[ist].jdscaling);
1029 for (std::size_t k = 0; k < K; ++k) {
1030 if (sn.disabled[ist][k]) continue;
1031 const double mu = num_traits<T>::to_double(sn.rates(ist, k));
1032 if (!(mu > 0)) continue;
1033 // The divisor is the PRODUCT of whichever declared peaks are
1034 // present -- `solver_ssa_nrm.m:1784-1785` -- and the server count
1035 // when neither is.
1036 double sdiv = sn.stations[ist].nservers;
1037 if (is_cd || is_jd) {
1038 sdiv = 1.0;
1039 const std::vector<T>* pks[2] = {&sn.stations[ist].cdscalingpeak,
1040 &sn.stations[ist].jdscalingpeak};
1041 const char* names[2] = {"setClassDependence", "setJointDependence"};
1042 const bool on[2] = {is_cd, is_jd};
1043 for (std::size_t h = 0; h < 2; ++h) {
1044 if (!on[h]) continue;
1045 const std::vector<T>& pk = *pks[h];
1046 if (pk.size() <= k || !(num_traits<T>::to_double(pk[k]) > 0))
1047 throw InputError(
1048 "solver_ssa_nrm_space: station '" + sn.stations[ist].name +
1049 "' declares a dependent scaling with no declared peak rate. "
1050 "Utilization there is T/mu/peak, so pass the peak to " + names[h]);
1051 sdiv *= num_traits<T>::to_double(pk[k]);
1052 }
1053 }
1054 a.UN(ist, k) = sdiv > 0 ? a.TN(ist, k) / mu / sdiv : 0.0;
1055 }
1056 }
1057
1058 for (std::size_t k = 0; k < K; ++k) {
1059 for (std::size_t ist = 0; ist < M; ++ist)
1060 a.RN(ist, k) = a.TN(ist, k) > 0 ? a.QN(ist, k) / a.TN(ist, k) : 0.0;
1061 if (a.XN[k] > 0) a.CN[k] = sn.classes[k].population / a.XN[k];
1062 }
1063 return out;
1064 }
1065}
1066
1067} // namespace ssa
1068} // namespace line
1069
1070#endif // LINE_SOLVERS_SSA_SOLVER_SSA_NRM_SPACE_H
InputError(const std::string &what)
Definition error.h:105
NumericError(const std::string &what)
Definition error.h:112
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
std::size_t nof_nodes() const
std::vector< std::vector< Distrib< T > > > service
service[i][r], 0-based station and class; a disabled entry marks a pair never visited.
std::vector< std::vector< bool > > disabled
std::vector< JobClass > classes
std::vector< Station< T > > stations
stations[k-1] is the k-th station
Matrix< T > rates
(nstations x nclasses) service rates and SCVs, with a PARALLEL disabled flag instead of MATLAB's NaN ...
std::vector< NodeDef > nodes
every node, in creation order
std::vector< std::size_t > station_to_node
(nstations) 1-based node index
std::vector< Region > regions
The aggregate NRM engine of solver_ssa_nrm_space.m.
NrmSpaceEngine(const qn::NetworkStruct< T > &sn, const SsaNrmSpaceOptions &opt)
std::vector< double > propensities(const NrmSpaceState &s) const
The whole propensity vector at a state, the reference's reactCache entry.
SsaNrmSpaceRun< T > run()
Run opt.samples firings and return the tabulated path.
std::vector< NrmSpaceState > enumerate_space() const
The reachable aggregate state space, closed forward from the initial state over the REACTIONS alone.
const NrmSpaceState & initial() const
The uniform source, MATLAB's rand.
Definition ssa_types.h:202
What refreshProcessRepresentations and refreshLST compute FROM a distribution: the (D0,...
The exception types the port throws.
options.timeout: one wall-clock budget per top-level solve, on a per-THREAD deadline stack.
Dense matrix and non-owning view.
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
@ 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
ProcessType
Distribution kinds, with the values of MATLAB ProcessType.
Definition lang_types.h:524
const char * sched_to_text(SchedStrategy s)
Definition lang_types.h:248
NodeType
Node kinds, with the values of MATLAB NodeType.
Definition lang_types.h:345
double tot(const std::vector< double > &pops)
SchedStrategy
The three scheduling disciplines the AMVA and Schmidt recursions branch on.
GlobalOutcome< T > after_global_event(const NetworkStruct< T > &sn, const NetState< T > &glspace, const GlobalSync< T > &gl)
Port of State.afterGlobalEvent: an SPN mode ENABLEs or FIREs.
EventOutcome< T > after_event(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.
std::size_t ssa_warmup_firings(double warmupfrac, std::size_t samples)
Firings whose tallies an engine discards: floor(warmupfrac * samples), with an unset (negative) fract...
Definition ssa_types.h:148
std::vector< EnabledEvent< T > > ssa_find_enabled(const qn::NetworkStruct< T > &sn, const std::vector< qn::Sync< T > > &sync, const std::vector< qn::GlobalSync< T > > &gsync, const qn::NetState< T > &state, std::vector< std::vector< double > > *arv=nullptr, std::vector< std::vector< double > > *dep=nullptr)
Port of solver_ssa_findenabled.m: every synchronization that can fire in state, with the arrival and ...
SsaNrmSpaceSolution< T > solver_ssa_nrm_space_analyzer(const qn::NetworkStruct< T > &sn, const SsaNrmSpaceOptions &opt)
Port of the else branch of solver_ssa_analyzer_nrm.m, the one state_space_gen selects: the means as p...
SsaNrmSpaceRun< T > solver_ssa_nrm_space(const qn::NetworkStruct< T > &sn, const SsaNrmSpaceOptions &opt)
solver_ssa_nrm_space.m: run the tabulating engine.
bool timeout_exceeded()
The checkpoint: true when the innermost budget has run out, marking it tripped.
void timeout_check(const char *where)
The raising checkpoint, for a computation with no valid partial result: throws LINE:numerical:Timeout...
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
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
static constexpr double Immediate
Rate of an Immediate distribution; its mean is 1/Immediate = 1e-8.
Definition lang_types.h:829
static constexpr double Zero
Definition lang_types.h:825
static constexpr double MaxInt
Stand-in for an unbounded COUNT, MATLAB GlobalConstants.MaxInt.
Definition lang_types.h:834
What one event produces at one node: the successor rows, their rates and their probabilities,...
std::vector< T > prob
per-row probability of the choice
std::vector< std::vector< T > > space
successor local state rows
std::vector< T > rate
per-row rate, -1 on a passive half
What one global event produces: a whole network state per outcome.
std::vector< T > rate
std::vector< NetState< T > > space
std::vector< T > prob
A GLOBAL synchronization: an SPN mode event and the place arcs it drives.
One half of a GLOBAL synchronization: a mode event at a node.
std::size_t node
1-based node index (a Transition, or a place)
std::size_t cls
1-based class the arc moves
One network state: the per-stateful-node local rows it is composed of.
Definition state.h:3022
std::vector< std::vector< T > > local
local[isf] is that node's state row
Definition state.h:3023
One synchronization: an ACTIVE event and the PASSIVE event it drives.
SyncEvent< T > passive
SyncEvent< T > active
One transition the enabled scan found: where it goes, and at what rate.
qn::NetState< T > next
enabled_next_states{act}: the whole network state after it fires.
double rate
enabled_rates: rate * p_active * p_route * p_passive.
std::size_t sync
enabled_sync: index into sync, or sync.size() + g for a global one.
One state of the aggregate chain: the (node, class) populations, and the ordered buffer contents of e...
std::vector< std::vector< std::size_t > > buf
The knobs the space variant reads.
What solver_ssa_nrm_space.m returns, plus what makes it a measurement.
std::vector< double > tran_time
t: the cumulative time at each firing.
std::vector< double > pi
pi: the fraction of simulated time spent in each of them.
std::vector< std::size_t > tran_rx
kfires: which reaction fired.
Matrix< double > dep_rates
depRates, (states x nnodes*nclasses): the departure rate of each (node, class) in each state,...
std::vector< NrmSpaceState > space
outspace: the distinct states visited, in first-visit order.
The metric table, the table it came from, and the stream that produced it.
Controls, defaulting to SolverOptions('SSA') in the reference.
Definition ssa_types.h:71
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
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