LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
ssa_tstep.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_SSA_TSTEP_H
6#define LINE_SOLVERS_SSA_SSA_TSTEP_H
7
8/**
9 * @file
10 * Port of `solver_ssa_analyzer_tstep.m` and `ssa_tstep_refusal.m`: SolverSSA
11 * method `tstep`, the fixed-increment (time-stepped) approximate simulation of
12 * a Markovian queueing network.
13 *
14 * Reference: T. Wang, Y. Song and L. J. Hong, "Fast approximation to
15 * discrete-event simulation of Markovian queueing networks", Proc. 2023 Winter
16 * Simulation Conference, pp. 3613-3624 (WanSH23), Algorithm 1.
17 *
18 * The horizon is cut into steps of length h and the per-(station, class) job
19 * counts are advanced once per step from the events of that step, ignoring
20 * their order. Arrivals (external and routed) are pushed to the END of the
21 * step, so a job that arrives in a step is not served before the next one:
22 *
23 * - Delay (INF): d ~ Bin(n, 1-exp(-mu h)).
24 * - single-class FCFS/SIRO/PS station with c servers: b = min(n,c),
25 * m1 ~ Bin(b, p1), m2 ~ Bin(min(m1, n-b), p2), d = m1 + m2, with
26 * p1 = 1-exp(-x), p2 = (1-exp(-x)(1+x))/(1-exp(-x)), x = mu h.
27 * - multiclass PS (extension, not in the paper): the PS share is frozen over
28 * the step, d_r ~ Bin(n_r, 1-exp(-mu_r min(n,c)/n h)).
29 * - Source: a_r ~ Poisson(lambda_r h).
30 *
31 * Departures and arrivals are routed by one multinomial draw per (station,
32 * class) over `sn_rt_stations` (Router/ClassSwitch nodes and class switching
33 * folded in), drawn as a sequence of conditional binomials; mass routed to the
34 * Source column leaves the network. Counts never go negative and closed
35 * populations are conserved exactly.
36 *
37 * Estimators: QN is the mean of the counts at the step starts after warmup,
38 * TN departures per unit time, UN = QN at a Delay and TN/(mu c) elsewhere,
39 * RN = QN/TN, XN = TN at the reference station, CN = N/XN. The method is an
40 * APPROXIMATION with an O(h) bias (Theorem 1 of the paper); it records no
41 * sample path, so `solver_ssa` serves only the steady-state averages and the
42 * sample/transient entries refuse it.
43 */
44
45#include <algorithm>
46#include <cmath>
47#include <cstdint>
48#include <random>
49#include <string>
50#include <vector>
51
59#include "line/util/error.h"
60
61namespace line {
62namespace ssa {
63
64/**
65 * `ssa_tstep_refusal.m`: the structural rules of `tstep` that
66 * `qn::ssa_tstep_feature_set` cannot express. Empty when the model is accepted,
67 * else the reason. The method keeps only per-(station, class) counts, so an
68 * FCFS or SIRO station must serve at most one class; every station other than a
69 * Source must be INF, PS, FCFS or SIRO; every visited (station, class) needs
70 * exponential service (one phase) with a finite positive rate; FCFS, SIRO and PS
71 * stations need a finite server count.
72 */
74 using SS = lang::SchedStrategy;
75 const std::size_t M = sn.nstations, K = sn.nclasses;
77 for (std::size_t ist = 0; ist < M; ++ist) {
78 const std::size_t ind = sn.station_to_node[ist];
79 const qn::NodeDef& nd = sn.nodes[ind - 1];
80 if (nd.nodetype == qn::NodeType::Source) continue;
81 std::vector<std::size_t> active;
82 for (std::size_t r = 0; r < K; ++r)
83 if (rs.Vst.rows() > ist && rs.Vst.cols() > r && rs.Vst(ist, r) > 0.0) active.push_back(r);
84 // The engine knows Delay, PS, FCFS and SIRO only; refuse the rest here
85 // too, so a direct call that skipped the feature-set gate cannot misread them.
86 const SS sched = sn.stations[ist].sched;
87 if (!(sched == SS::INF || sched == SS::PS || sched == SS::FCFS || sched == SS::SIRO))
88 return std::string("The 'tstep' method supports INF, PS, FCFS and SIRO stations only; station ") +
89 nd.name + " uses " + lang::sched_to_text(sched) + ".";
90 for (std::size_t r : active) {
91 // Non-exponential service. MATLAB's sn.phases gives a non-Markovian
92 // law the order of its Erlang conversion, while phases_of answers 1
93 // for it (network_struct.h), so such a law is refused explicitly.
94 const lang::Distrib<double>& law = sn.service[ist][r];
95 const std::size_t nph = sn.phases_of(ist + 1, r + 1);
96 if (nph > 1)
97 return "The 'tstep' method needs exponential service; station " + nd.name + ", class " +
98 sn.classes[r].name + " has a " + std::to_string(nph) + "-phase distribution.";
100 return "The 'tstep' method needs exponential service; station " + nd.name + ", class " +
101 sn.classes[r].name + " has a non-Markovian " + lang::process_to_text(law.type) +
102 " distribution.";
103 const double rate = sn.rates(ist, r);
104 if (!(std::isfinite(rate) && rate > 0.0))
105 return "The 'tstep' method needs a finite positive exponential rate for every visited "
106 "station and class; station " + nd.name + ", class " + sn.classes[r].name +
107 " has " + std::to_string(rate) + ".";
108 }
109 if (sched == SS::FCFS || sched == SS::SIRO) {
110 if (active.size() > 1)
111 return std::string("The 'tstep' method keeps per-class job counts only, so a ") +
112 (sched == SS::FCFS ? "FCFS" : "SIRO") + " station must serve a single class; station " +
113 nd.name + " serves " + std::to_string(active.size()) +
114 " classes. Use PS or another SSA method.";
115 if (!std::isfinite(sn.stations[ist].nservers))
116 return "The 'tstep' method needs a finite server count at station " + nd.name + ".";
117 } else if (sched == SS::PS) {
118 if (!std::isfinite(sn.stations[ist].nservers))
119 return "The 'tstep' method needs a finite server count at station " + nd.name + ".";
120 }
121 }
122 return std::string();
123}
124
125/** The two gates of `SolverSSA.supportsModelMethod` for 'tstep': the feature set, then the refusal. */
127 const auto support = qn::feature_set_supports(
128 "SolverSSA(method='tstep')", qn::ssa_tstep_feature_set(), qn::used_lang_features(sn));
129 if (!support.ok) throw qn::feature_refusal(support);
130 const std::string why = ssa_tstep_refusal(sn);
131 if (!why.empty()) throw UnsupportedError(ErrorKind{"Structure"}, why);
132}
133
134/**
135 * `ssa_tstep_default_step`: min(0.1, 1/sqrt(cmax ln cmax)) / mumax, with mumax
136 * the largest per-server rate over the active non-Source pairs and cmax the
137 * largest finite server count of a non-Delay station (the paper's
138 * h = 1/sqrt(m log m) in units of the mean service time, capped at a tenth of
139 * the fastest service time). 0.1 when nothing is active.
140 */
141inline double ssa_tstep_default_step(const std::vector<double>& active_rates,
142 const std::vector<double>& queue_servers) {
143 if (active_rates.empty()) return 0.1;
144 const double mumax = *std::max_element(active_rates.begin(), active_rates.end());
145 double cmax = 1.0;
146 for (double c : queue_servers)
147 if (std::isfinite(c)) cmax = std::max(cmax, c);
148 const double scale = cmax > 1.0 ? std::min(0.1, 1.0 / std::sqrt(cmax * std::log(cmax))) : 0.1;
149 return scale / mumax;
150}
151
152/** What the engine reports beside the metric table: the step it used and the step count. */
153struct TstepInfo {
154 double h = 0.0;
155 std::size_t nsteps = 0;
156};
157
158/**
159 * `solver_ssa_analyzer_tstep.m`. `opt.warmupfrac` is read as resolved
160 * (`solver_ssa_engine` resolves it through `ssa_resolve_warmupfrac`; an unset
161 * value reached directly reads as 0), `opt.samples` is the step count and
162 * `opt.timestep` the step (negative = the default step).
163 */
165 TstepInfo* info = nullptr) {
166 using SS = lang::SchedStrategy;
168
169 const std::size_t M = sn.nstations, K = sn.nclasses, MK = M * K;
171 const Matrix<double>& P = rs.rtst;
172
173 std::vector<bool> isSrc(M, false);
174 std::vector<double> c(M, 1.0);
175 for (std::size_t ist = 0; ist < M; ++ist) {
176 isSrc[ist] = sn.nodes[sn.station_to_node[ist] - 1].nodetype == qn::NodeType::Source;
177 c[ist] = sn.stations[ist].nservers;
178 }
179 // mu(ist,r): 0 at an unvisited pair; a Source keeps its arrival rate
180 std::vector<double> mu(MK, 0.0);
181 std::vector<bool> active(MK, false);
182 for (std::size_t ist = 0; ist < M; ++ist)
183 for (std::size_t r = 0; r < K; ++r) {
184 const double rate = sn.rates(ist, r);
185 const double m = std::isfinite(rate) ? rate : 0.0;
186 const bool visited = rs.Vst.rows() > ist && rs.Vst.cols() > r && rs.Vst(ist, r) > 0.0;
187 active[ist * K + r] = visited && !isSrc[ist];
188 mu[ist * K + r] = (isSrc[ist] || active[ist * K + r]) ? m : 0.0;
189 }
190
191 // ---- station kinds ----
192 enum Kind { KSRC, KINF, KALG1, KPS };
193 std::vector<Kind> kind(M, KSRC);
194 for (std::size_t ist = 0; ist < M; ++ist) {
195 if (isSrc[ist]) continue;
196 std::size_t na = 0;
197 for (std::size_t r = 0; r < K; ++r) na += active[ist * K + r] ? 1 : 0;
198 if (sn.stations[ist].sched == SS::INF) kind[ist] = KINF;
199 else if (na <= 1) kind[ist] = KALG1; // FCFS, SIRO or PS serving one class
200 else kind[ist] = KPS; // PS serving several classes
201 }
202
203 // ---- time step ----
204 double h;
205 if (opt.timestep < 0.0 && !std::isnan(opt.timestep)) {
206 std::vector<double> rates, qservers;
207 for (std::size_t ist = 0; ist < M; ++ist) {
208 if (isSrc[ist]) continue;
209 for (std::size_t r = 0; r < K; ++r)
210 if (active[ist * K + r]) rates.push_back(mu[ist * K + r]);
211 if (kind[ist] != KINF) qservers.push_back(c[ist]);
212 }
213 h = ssa_tstep_default_step(rates, qservers);
214 } else {
215 h = opt.timestep;
216 if (!(std::isfinite(h) && h > 0.0))
217 throw InputError("options.timestep must be a finite positive scalar for the 'tstep' method.");
218 }
219 const std::size_t nsteps = std::max<std::size_t>(1, opt.samples);
220 const std::size_t nwarm = ssa_warmup_firings(opt.warmupfrac, nsteps);
221
222 // ---- routing rows: destinations and conditional probabilities ----
223 // row index ist*K+r as in sn_rt_stations; mass sent to a Source column exits.
224 const std::size_t exitIdx = MK;
225 struct Row {
226 std::size_t st, cl;
227 std::vector<std::size_t> dest;
228 std::vector<double> qc; // conditional binomial probabilities
229 double mu, p1, p2, lamh;
230 };
231 std::vector<Row> rows;
232 for (std::size_t ist = 0; ist < M; ++ist)
233 for (std::size_t r = 0; r < K; ++r) {
234 const std::size_t q = ist * K + r;
235 const bool srcRow = isSrc[ist] && std::isfinite(sn.rates(ist, r)) && sn.rates(ist, r) > 0.0;
236 if (!(active[q] || srcRow)) continue;
237 Row row;
238 row.st = ist;
239 row.cl = r;
240 std::vector<double> pj;
241 double pex = 0.0;
242 bool anyExit = false;
243 for (std::size_t j = 0; j < MK; ++j) {
244 const double w = (P.rows() > q && P.cols() > j) ? P(q, j) : 0.0;
245 if (!(w > 0.0)) continue;
246 if (isSrc[j / K]) {
247 pex += w;
248 anyExit = true;
249 } else {
250 row.dest.push_back(j);
251 pj.push_back(w);
252 }
253 }
254 if (anyExit) {
255 row.dest.push_back(exitIdx);
256 pj.push_back(pex);
257 }
258 double tot = 0.0;
259 for (double w : pj) tot += w;
260 if (tot > 0.0)
261 for (double& w : pj) w /= tot; // rows of rt are stochastic; guard round-off
262 double rem = 1.0;
263 row.qc.resize(pj.size());
264 for (std::size_t t = 0; t < pj.size(); ++t) {
265 row.qc[t] = (t + 1 == pj.size()) ? 1.0 : std::min(1.0, std::max(0.0, pj[t] / rem));
266 rem -= pj[t];
267 }
268 row.mu = mu[q];
269 const double x = row.mu * h;
270 row.p1 = -std::expm1(-x);
271 // P(s>=2 | s>=1) for s ~ Poisson(x): (1 - e^-x (1+x)) / (1 - e^-x)
272 row.p2 = x > 0.0 ? std::min(1.0, std::max(0.0, (row.p1 - x * std::exp(-x)) / row.p1)) : 0.0;
273 row.lamh = row.mu * h;
274 rows.push_back(row);
275 }
276 const std::size_t nr = rows.size();
277
278 // ---- initial state: the aggregated default state, as ssa_mlmc_problem obtains it ----
279 std::vector<long long> Nv(MK, 0);
280 {
282 if (!ctmc::analyzer_detail::default_init_state(sn, init))
283 throw InputError("SolverSSA(method='tstep'): the model has no valid initial state");
284 for (std::size_t ist = 0; ist < M; ++ist) {
285 if (isSrc[ist]) continue;
286 const std::size_t node = sn.station_to_node[ist];
287 const std::size_t isf = sn.stateful_index(node);
288 if (isf == 0 || isf > init.local.size()) continue;
289 const std::pair<double, std::vector<double>> a = qn::to_marginal_aggr(sn, node, init.local[isf - 1]);
290 for (std::size_t r = 0; r < K && r < a.second.size(); ++r)
291 Nv[ist * K + r] = static_cast<long long>(std::llround(a.second[r]));
292 }
293 }
294
295 // ---- main loop ----
296 std::mt19937_64 rng(static_cast<std::uint64_t>(opt.seed));
297 auto binom = [&rng](long long n, double p) -> long long {
298 if (n <= 0 || !(p > 0.0)) return 0;
299 if (p >= 1.0) return n;
300 std::binomial_distribution<long long> b(n, p);
301 return b(rng);
302 };
303 auto poiss = [&rng](double m) -> long long {
304 if (!(m > 0.0)) return 0;
305 std::poisson_distribution<long long> p(m);
306 return p(rng);
307 };
308 std::vector<double> Qacc(MK, 0.0), Tacc(nr, 0.0);
309 std::vector<long long> d(nr, 0), inflow(MK + 1, 0);
310 std::vector<long long> ntot(M, 0);
311 for (std::size_t tau = 1; tau <= nsteps; ++tau) {
312 const bool record = tau > nwarm;
313 if (record)
314 for (std::size_t q = 0; q < MK; ++q) Qacc[q] += static_cast<double>(Nv[q]);
315 for (std::size_t ist = 0; ist < M; ++ist) {
316 long long s = 0;
317 for (std::size_t r = 0; r < K; ++r) s += Nv[ist * K + r];
318 ntot[ist] = s;
319 }
320 for (std::size_t q = 0; q < nr; ++q) {
321 const Row& row = rows[q];
322 const long long n = Nv[row.st * K + row.cl];
323 switch (kind[row.st]) {
324 case KSRC:
325 d[q] = poiss(row.lamh);
326 break;
327 case KINF:
328 d[q] = binom(n, row.p1);
329 break;
330 case KALG1: {
331 const double cc = c[row.st];
332 const long long b = static_cast<long long>(std::min(static_cast<double>(n), cc));
333 const long long m1 = binom(b, row.p1);
334 const long long m2 = binom(std::min(m1, n - b), row.p2);
335 d[q] = m1 + m2;
336 break;
337 }
338 case KPS: {
339 const long long nt = ntot[row.st];
340 double share = 0.0;
341 if (nt > 0) share = std::min(static_cast<double>(nt), c[row.st]) / static_cast<double>(nt);
342 d[q] = binom(n, -std::expm1(-row.mu * share * h));
343 break;
344 }
345 }
346 }
347 // route
348 std::fill(inflow.begin(), inflow.end(), 0);
349 for (std::size_t q = 0; q < nr; ++q) {
350 if (record) Tacc[q] += static_cast<double>(d[q]);
351 long long rem = d[q];
352 const Row& row = rows[q];
353 for (std::size_t t = 0; t < row.dest.size() && rem > 0; ++t) {
354 const long long x = binom(rem, row.qc[t]);
355 inflow[row.dest[t]] += x;
356 rem -= x;
357 }
358 }
359 for (std::size_t q = 0; q < nr; ++q)
360 if (!isSrc[rows[q].st]) Nv[rows[q].st * K + rows[q].cl] -= d[q];
361 for (std::size_t q = 0; q < MK; ++q) Nv[q] += inflow[q];
362 }
363
364 // ---- estimators ----
365 const std::size_t nobs = nsteps - nwarm;
366 const double Ttot = static_cast<double>(nobs) * h;
367 SsaSolution out;
368 out.method = "tstep";
369 out.simulated_time = Ttot;
370 out.samples = nsteps;
371 out.QN = Matrix<double>(M, K);
372 out.UN = Matrix<double>(M, K);
373 out.RN = Matrix<double>(M, K);
374 out.TN = Matrix<double>(M, K);
375 out.PreemptN = Matrix<double>(M, K);
376 out.XN.assign(K, 0.0);
377 out.CN.assign(K, 0.0);
378 for (std::size_t ist = 0; ist < M; ++ist)
379 for (std::size_t r = 0; r < K; ++r)
380 out.QN(ist, r) = (isSrc[ist] || nobs == 0) ? 0.0 : Qacc[ist * K + r] / static_cast<double>(nobs);
381 for (std::size_t q = 0; q < nr; ++q)
382 out.TN(rows[q].st, rows[q].cl) = Ttot > 0.0 ? Tacc[q] / Ttot : 0.0;
383 for (std::size_t ist = 0; ist < M; ++ist) {
384 if (isSrc[ist]) continue;
385 for (std::size_t r = 0; r < K; ++r) {
386 const double m = mu[ist * K + r];
387 if (kind[ist] == KINF) out.UN(ist, r) = out.QN(ist, r);
388 else if (m > 0.0) out.UN(ist, r) = out.TN(ist, r) / m / c[ist];
389 if (out.TN(ist, r) > 0.0) out.RN(ist, r) = out.QN(ist, r) / out.TN(ist, r);
390 }
391 }
392 for (std::size_t r = 0; r < K; ++r) {
393 const std::size_t rs1 = sn.classes[r].refstat;
394 if (rs1 >= 1 && rs1 <= M) out.XN[r] = out.TN(rs1 - 1, r);
395 if (out.XN[r] > 0.0) out.CN[r] = sn.classes[r].population / out.XN[r];
396 }
397 // No preemption and no loss: in steady state every departure is a service start.
398 out.StartN = out.TN;
399 if (info) {
400 info->h = h;
401 info->nsteps = nsteps;
402 }
403 return out;
404}
405
406} // namespace ssa
407} // namespace line
408
409#endif // LINE_SOLVERS_SSA_SSA_TSTEP_H
InputError(const std::string &what)
Definition error.h:105
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
The exception types the port throws.
The language-feature gate: what a MODEL uses against what a SOLVER declares.
SnRtStations< T > sn_rt_stations(const qn::NetworkStruct< T > &sn)
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
const char * sched_to_text(SchedStrategy s)
Definition lang_types.h:248
const char * process_to_text(ProcessType p)
The MATLAB ProcessType name, as sn.procid prints it.
Definition lang_types.h:655
bool process_is_markovian(ProcessType p)
ProcessType.isMarkovian: true when sn.proc carries an exact matrix representation of the law,...
Definition lang_types.h:713
FeatureSet ssa_tstep_feature_set()
The envelope of SSA method tstep (fixed-increment time-stepped simulation, Wang-Song-Hong WSC 2023),...
FeatureSet used_lang_features(const NetworkStruct< T > &sn)
UnsupportedError feature_refusal(const SupportResult &r)
The refusal a failed gate raises: LINE:unsupported:<kind>, where the kind is the FIRST missing featur...
SupportResult feature_set_supports(const std::string &solver, const FeatureSet &declared, const FeatureSet &used)
SolverFeatureSet.supports: is every feature the model uses declared?
std::pair< T, std::vector< T > > to_marginal_aggr(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &state_i)
Port of State.toMarginalAggr: the job counts of one node's state row, without the per-phase detail to...
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
void ssa_tstep_check(const qn::NetworkStruct< double > &sn)
The two gates of SolverSSA.supportsModelMethod for 'tstep': the feature set, then the refusal.
Definition ssa_tstep.h:126
double ssa_tstep_default_step(const std::vector< double > &active_rates, const std::vector< double > &queue_servers)
ssa_tstep_default_step: min(0.1, 1/sqrt(cmax ln cmax)) / mumax, with mumax the largest per-server rat...
Definition ssa_tstep.h:141
SsaSolution solver_ssa_analyzer_tstep(const qn::NetworkStruct< double > &sn, const SsaOptions &opt, TstepInfo *info=nullptr)
solver_ssa_analyzer_tstep.m.
Definition ssa_tstep.h:164
std::string ssa_tstep_refusal(const qn::NetworkStruct< double > &sn)
ssa_tstep_refusal.m: the structural rules of tstep that qn::ssa_tstep_feature_set cannot express.
Definition ssa_tstep.h:73
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
Port of matlab/src/api/sn/sn_rt_stations.m.
Port of solver_ctmc_analyzer.m and the parts of @@SolverCTMC/runAnalyzer.m that surround one solve: t...
The DECLARED side of the gate: one feature set per solver.
Controls, results and the random source of SolverSSA.
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
What sn_rt_stations returns: the complemented routing and the station visits.
Matrix< T > rtst
(nstations*nclasses) square, STATION-major rows
Matrix< T > Vst
(nstations x nclasses), cellsum(sn.visits) by station
One network state: the per-stateful-node local rows it is composed of.
Definition state.h:3022
std::vector< std::vector< T > > local
local[isf] is that node's state row
Definition state.h:3023
A node of the network.
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
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
What the engine reports beside the metric table: the step it used and the step count.
Definition ssa_tstep.h:153
std::size_t nsteps
Definition ssa_tstep.h:155