LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_facade.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 */
5
6/**
7 * @file
8 * The one translation unit that instantiates the solver stack for the facade.
9 *
10 * `line/solvers/solver.h` declares a `double`-only, non-template solver API so
11 * that this file can carry every body: a caller including that header pays for
12 * none of the template instantiation below, and `line_mp_api` pays for it once
13 * for the CLI, the tests and the examples together.
14 *
15 * Every entry point forwards to the runner the CLI calls, so a program written
16 * against the facade and `line-cli -s <solver>` on the same model produce the
17 * same numbers by construction. Nothing is computed here beyond the reshaping
18 * the tables need.
19 */
20
21#include "line/solvers/solver.h"
22
23#include <algorithm>
24#include <cctype>
25#include <cmath>
26#include <cstdio>
27#include <iomanip>
28#include <iostream>
29#include <limits>
30#include <map>
31#include <set>
32#include <sstream>
33#include <utility>
34
40#include "line/lang/qn/nodes.h"
64#include "line/lang/qn/state.h"
72
73namespace line {
74
75// ---------------------------------------------------------------------------
76// AvgTable
77// ---------------------------------------------------------------------------
78
79double AvgTable::get(const std::string& col, const std::string& station,
80 const std::string& jobclass) const {
81 for (std::size_t i = 0; i < Station.size(); ++i) {
82 if (Station[i] != station || JobClass[i] != jobclass) continue;
83 if (col == "QLen") return QLen[i];
84 if (col == "Util") return Util[i];
85 if (col == "RespT") return RespT[i];
86 if (col == "ResidT") return ResidT[i];
87 if (col == "ArvR") return ArvR[i];
88 if (col == "Tput") return Tput[i];
89 const std::vector<double>& ci = column(col);
90 return i < ci.size() ? ci[i] : std::numeric_limits<double>::quiet_NaN();
91 }
92 return std::numeric_limits<double>::quiet_NaN();
93}
94
95std::vector<double> AvgTable::column(const std::string& col) const {
96 if (col == "QLen") return QLen;
97 if (col == "Util") return Util;
98 if (col == "RespT") return RespT;
99 if (col == "ResidT") return ResidT;
100 if (col == "ArvR") return ArvR;
101 if (col == "Tput") return Tput;
102 if (col == "QLenCI") return QLenCI;
103 if (col == "UtilCI") return UtilCI;
104 if (col == "RespTCI") return RespTCI;
105 if (col == "ResidTCI") return ResidTCI;
106 if (col == "ArvRCI") return ArvRCI;
107 if (col == "TputCI") return TputCI;
108 throw InputError("AvgTable::column: unknown column '" + col + "'");
109}
110
111namespace {
112
113template <class Keep>
114AvgTable filter_avg_table(const AvgTable& source, Keep keep) {
115 AvgTable out;
116 out.solver = source.solver;
117 out.method = source.method;
118 out.iter = source.iter;
120 out.lognormconst = source.lognormconst;
121 out.ListCost = source.ListCost;
122 out.warning = source.warning;
123 out.SysClass = source.SysClass;
124 out.SysRespT = source.SysRespT;
125 out.SysTput = source.SysTput;
126 for (std::size_t i = 0; i < source.Station.size(); ++i) {
127 if (!keep(i)) continue;
128 out.Station.push_back(source.Station[i]);
129 out.JobClass.push_back(source.JobClass[i]);
130 out.QLen.push_back(source.QLen[i]);
131 out.Util.push_back(source.Util[i]);
132 out.RespT.push_back(source.RespT[i]);
133 out.ResidT.push_back(source.ResidT[i]);
134 out.ArvR.push_back(source.ArvR[i]);
135 out.Tput.push_back(source.Tput[i]);
136 if (!source.has_ci()) continue;
137 out.QLenCI.push_back(source.QLenCI[i]);
138 out.UtilCI.push_back(source.UtilCI[i]);
139 out.RespTCI.push_back(source.RespTCI[i]);
140 out.ResidTCI.push_back(source.ResidTCI[i]);
141 out.ArvRCI.push_back(source.ArvRCI[i]);
142 out.TputCI.push_back(source.TputCI[i]);
143 }
144 return out;
145}
146
147} // namespace
148
149AvgTable AvgTable::filter_by(const std::string& name) const {
150 return filter_avg_table(*this, [&](std::size_t i) {
151 return Station[i] == name || JobClass[i] == name;
152 });
153}
154
155AvgTable AvgTable::filter_by(const std::string& station, const std::string& jobclass) const {
156 return filter_avg_table(*this, [&](std::size_t i) {
157 return Station[i] == station && JobClass[i] == jobclass;
158 });
159}
160
162 return filter_avg_table(*this, [&](std::size_t i) {
163 return Station[i] == node.get_name();
164 });
165}
166
167AvgTable AvgTable::filter_by(const ::line::JobClass& jobclass) const {
168 return filter_avg_table(*this, [&](std::size_t i) {
169 return JobClass[i] == jobclass.get_name();
170 });
171}
172
173AvgTable AvgTable::filter_by(const Node& node, const ::line::JobClass& jobclass) const {
174 return filter_by(node.get_name(), jobclass.get_name());
175}
176
177AvgTable AvgTable::filter_by(const ::line::JobClass& jobclass, const Node& node) const {
178 return filter_by(node, jobclass);
179}
180
181AvgTable AvgTable::get(const Node& node) const { return filter_by(node); }
182AvgTable AvgTable::get(const ::line::JobClass& jobclass) const { return filter_by(jobclass); }
183AvgTable AvgTable::get(const Node& node, const ::line::JobClass& jobclass) const {
184 return filter_by(node, jobclass);
185}
186AvgTable AvgTable::get(const ::line::JobClass& jobclass, const Node& node) const {
187 return filter_by(node, jobclass);
188}
189AvgTable AvgTable::tget(const Node& node) const { return filter_by(node); }
190AvgTable AvgTable::tget(const ::line::JobClass& jobclass) const { return filter_by(jobclass); }
191AvgTable AvgTable::tget(const Node& node, const ::line::JobClass& jobclass) const {
192 return filter_by(node, jobclass);
193}
194AvgTable AvgTable::tget(const ::line::JobClass& jobclass, const Node& node) const {
195 return filter_by(node, jobclass);
196}
197AvgTable AvgTable::operator()(const Node& node) const { return filter_by(node); }
198AvgTable AvgTable::operator()(const ::line::JobClass& jobclass) const {
199 return filter_by(jobclass);
200}
201AvgTable AvgTable::operator()(const Node& node, const ::line::JobClass& jobclass) const {
202 return filter_by(node, jobclass);
203}
204AvgTable AvgTable::operator()(const ::line::JobClass& jobclass, const Node& node) const {
205 return filter_by(node, jobclass);
206}
207
208void AvgTable::print(std::ostream& out) const {
209 const std::ios::fmtflags flags = out.flags();
210 const std::streamsize precision = out.precision();
211 if (has_ci()) {
212 // MATLAB's getAvgTable under options.confint: every cell reads `mean +- half-width`.
213 const auto cell = [](double m, double h) {
214 std::ostringstream c;
215 c << std::setprecision(6) << m << " +- " << std::setprecision(3) << h;
216 return c.str();
217 };
218 out << std::left << std::setw(16) << "Station" << std::setw(14) << "JobClass" << std::right;
219 for (const char* h : {"QLen", "Util", "RespT", "ResidT", "ArvR", "Tput"}) out << std::setw(22) << h;
220 out << '\n';
221 for (std::size_t i = 0; i < Station.size(); ++i)
222 out << std::left << std::setw(16) << Station[i] << std::setw(14) << JobClass[i]
223 << std::right << std::setw(22) << cell(QLen[i], QLenCI[i])
224 << std::setw(22) << cell(Util[i], UtilCI[i]) << std::setw(22) << cell(RespT[i], RespTCI[i])
225 << std::setw(22) << cell(ResidT[i], ResidTCI[i]) << std::setw(22) << cell(ArvR[i], ArvRCI[i])
226 << std::setw(22) << cell(Tput[i], TputCI[i]) << '\n';
227 out.flags(flags);
228 return;
229 }
230 out << std::left << std::setw(16) << "Station" << std::setw(14) << "JobClass"
231 << std::right << std::setw(12) << "QLen" << std::setw(12) << "Util"
232 << std::setw(12) << "RespT" << std::setw(12) << "ResidT"
233 << std::setw(12) << "ArvR" << std::setw(12) << "Tput" << '\n';
234 out << std::setprecision(6);
235 for (std::size_t i = 0; i < Station.size(); ++i)
236 out << std::left << std::setw(16) << Station[i] << std::setw(14) << JobClass[i]
237 << std::right << std::setw(12) << QLen[i] << std::setw(12) << Util[i]
238 << std::setw(12) << RespT[i] << std::setw(12) << ResidT[i]
239 << std::setw(12) << ArvR[i] << std::setw(12) << Tput[i] << '\n';
240 out.flags(flags);
241 out.precision(precision);
242}
243
244void AvgTable::print() const { print(std::cout); }
245
246std::ostream& operator<<(std::ostream& out, const AvgTable& table) {
247 table.print(out);
248 return out;
249}
250
251void AvgSysTable::print(std::ostream& out) const {
252 const std::ios::fmtflags flags = out.flags();
253 const std::streamsize precision = out.precision();
254 std::size_t w = 12;
255 for (const std::string& s : JobClasses) w = std::max(w, s.size() + 2);
256 out << std::left << std::setw(10) << "Chain" << std::setw(int(w)) << "JobClasses" << std::right
257 << std::setw(12) << "SysRespT" << std::setw(12) << "SysTput" << '\n';
258 out << std::setprecision(6);
259 for (std::size_t c = 0; c < Chain.size(); ++c)
260 out << std::left << std::setw(10) << Chain[c] << std::setw(int(w)) << JobClasses[c] << std::right
261 << std::setw(12) << SysRespT[c] << std::setw(12) << SysTput[c] << '\n';
262 out.flags(flags);
263 out.precision(precision);
264}
265
266void AvgSysTable::print() const { print(std::cout); }
267
268std::ostream& operator<<(std::ostream& out, const AvgSysTable& table) {
269 table.print(out);
270 return out;
271}
272
273void AvgChainTable::print(std::ostream& out) const {
274 const std::ios::fmtflags flags = out.flags();
275 const std::streamsize precision = out.precision();
276 std::size_t ws = 10, wj = 12;
277 for (std::size_t i = 0; i < Station.size(); ++i) {
278 ws = std::max(ws, Station[i].size() + 2);
279 wj = std::max(wj, JobClasses[i].size() + 2);
280 }
281 out << std::left << std::setw(int(ws)) << "Station" << std::setw(10) << "Chain" << std::setw(int(wj))
282 << "JobClasses" << std::right;
283 for (const char* c : {"QLen", "Util", "RespT", "ResidT", "ArvR", "Tput"}) out << std::setw(12) << c;
284 out << '\n' << std::setprecision(6);
285 for (std::size_t i = 0; i < Station.size(); ++i)
286 out << std::left << std::setw(int(ws)) << Station[i] << std::setw(10) << Chain[i] << std::setw(int(wj))
287 << JobClasses[i] << std::right << std::setw(12) << QLen[i] << std::setw(12) << Util[i]
288 << std::setw(12) << RespT[i] << std::setw(12) << ResidT[i] << std::setw(12) << ArvR[i]
289 << std::setw(12) << Tput[i] << '\n';
290 out.flags(flags);
291 out.precision(precision);
292}
293
294void AvgChainTable::print() const { print(std::cout); }
295
296std::ostream& operator<<(std::ostream& out, const AvgChainTable& table) {
297 table.print(out);
298 return out;
299}
300
301void AvgFJTable::print(std::ostream& out) const {
302 const std::ios::fmtflags flags = out.flags();
303 const std::streamsize precision = out.precision();
304 std::size_t wf = 6, wj = 6, wc = 10;
305 for (std::size_t i = 0; i < Fork.size(); ++i) {
306 wf = std::max(wf, Fork[i].size() + 2);
307 wj = std::max(wj, Join[i].size() + 2);
308 wc = std::max(wc, JobClass[i].size() + 2);
309 }
310 out << std::left << std::setw(int(wf)) << "Fork" << std::setw(int(wj)) << "Join" << std::setw(int(wc))
311 << "JobClass" << std::right << std::setw(14) << "FJQLen" << std::setw(14) << "FJRespT" << std::setw(14)
312 << "FJTput" << '\n';
313 out << std::setprecision(6);
314 for (std::size_t i = 0; i < Fork.size(); ++i)
315 out << std::left << std::setw(int(wf)) << Fork[i] << std::setw(int(wj)) << Join[i] << std::setw(int(wc))
316 << JobClass[i] << std::right << std::setw(14) << FJQLen[i] << std::setw(14) << FJRespT[i]
317 << std::setw(14) << FJTput[i] << '\n';
318 out.flags(flags);
319 out.precision(precision);
320}
321
322void AvgFJTable::print() const { print(std::cout); }
323
324std::ostream& operator<<(std::ostream& out, const AvgFJTable& table) {
325 table.print(out);
326 return out;
327}
328
329void AvgLinkTable::print(std::ostream& out) const {
330 const std::ios::fmtflags flags = out.flags();
331 const std::streamsize precision = out.precision();
332 std::size_t wl = 6, wc = 10;
333 for (std::size_t i = 0; i < Link.size(); ++i) {
334 wl = std::max(wl, Link[i].size() + 2);
335 wc = std::max(wc, JobClass[i].size() + 2);
336 }
337 out << std::left << std::setw(int(wl)) << "Link" << std::setw(int(wc)) << "JobClass" << std::right
338 << std::setw(14) << "Capacity" << std::setw(14) << "Demand" << std::setw(14) << "Occupancy"
339 << std::setw(14) << "LinkBlocking" << std::setw(14) << "RouteLoss" << '\n';
340 out << std::setprecision(6);
341 for (std::size_t i = 0; i < Link.size(); ++i)
342 out << std::left << std::setw(int(wl)) << Link[i] << std::setw(int(wc)) << JobClass[i] << std::right
343 << std::setw(14) << Capacity[i] << std::setw(14) << Demand[i] << std::setw(14) << Occupancy[i]
344 << std::setw(14) << LinkBlocking[i] << std::setw(14) << RouteLoss[i] << '\n';
345 out.flags(flags);
346 out.precision(precision);
347}
348
349void AvgLinkTable::print() const { print(std::cout); }
350
351std::ostream& operator<<(std::ostream& out, const AvgLinkTable& table) {
352 table.print(out);
353 return out;
354}
355
356namespace {
357
358/** Fill the label columns and the per-class system metrics of a table. */
359void fill_table(AvgTable& t, const qn::NetworkStruct<double>& sn, const mva::AvgResult<double>& r) {
360 for (std::size_t i = 0; i < sn.nstations; ++i)
361 for (std::size_t c = 0; c < sn.nclasses; ++c) {
362 const double q = r.QN(i, c), u = r.UN(i, c), rt = r.RN(i, c);
363 const double w = r.WN(i, c), a = r.AN(i, c), x = r.TN(i, c);
364 if (q == 0.0 && u == 0.0 && rt == 0.0 && w == 0.0 && a == 0.0 && x == 0.0) continue;
365 t.Station.push_back(sn.stations[i].name);
366 t.JobClass.push_back(sn.classes[c].name);
367 t.QLen.push_back(q);
368 t.Util.push_back(u);
369 t.RespT.push_back(rt);
370 t.ResidT.push_back(w);
371 t.ArvR.push_back(a);
372 t.Tput.push_back(x);
373 }
374 for (std::size_t c = 0; c < sn.nclasses && c < r.CN.size(); ++c) {
375 t.SysClass.push_back(sn.classes[c].name);
376 t.SysRespT.push_back(r.CN[c]);
377 t.SysTput.push_back(c < r.XN.size() ? r.XN[c] : 0.0);
378 }
379 t.iter = r.iter;
380 t.warning = r.warning;
381 t.ListCost = r.listcost;
382 if (r.lognormconst.has_value()) {
383 t.has_lognormconst = true;
384 t.lognormconst = r.lognormconst.value();
385 }
386}
387
388/**
389 * The same fill for a solver whose solution type is not `mva::AvgResult`.
390 *
391 * THE SSA AND FLUID ARMS OWE BOTH DERIVED COLUMNS. Neither analyzer reports a
392 * residence time or an arrival rate of its own, and neither is a copy of its
393 * neighbour: ResidT is the per-JOB time and RespT the per-VISIT one, and they
394 * agree only where every station is visited once per cycle. ArvR is a FLOW and
395 * parts from the throughput at any station a job leaves by another route.
396 * `sn_get_residt_from_respt` and `sn_get_arvr_from_tput` are the reference's own
397 * conversions and are what the CLI's `-s fluid` and `-s ssa` arms apply. A
398 * Source's ArvR stays zero: nothing arrives TO it.
399 */
400template <class Sol>
401void fill_table_sim(AvgTable& t, const qn::NetworkStruct<double>& sn, const Sol& r) {
402 const std::size_t M = sn.nstations, K = sn.nclasses;
403 Matrix<double> RN(M, K), TN(M, K);
404 for (std::size_t i = 0; i < M; ++i)
405 for (std::size_t c = 0; c < K; ++c) {
406 RN(i, c) = r.RN(i, c);
407 TN(i, c) = r.TN(i, c);
408 }
411 for (std::size_t i = 0; i < M; ++i)
412 for (std::size_t c = 0; c < K; ++c) {
413 const double q = r.QN(i, c), u = r.UN(i, c), rt = r.RN(i, c), x = r.TN(i, c);
414 const bool is_source = sn.stations[i].sched == lang::SchedStrategy::EXT;
415 const double w = WN(i, c), a = is_source ? 0.0 : AN(i, c);
416 // The all-zero row test over ALL SIX columns, as `avg_rows` and the
417 // reference make it: a station only ARRIVALS reach still has a row.
418 if (q == 0.0 && u == 0.0 && rt == 0.0 && w == 0.0 && a == 0.0 && x == 0.0) continue;
419 t.Station.push_back(sn.stations[i].name);
420 t.JobClass.push_back(sn.classes[c].name);
421 t.QLen.push_back(q);
422 t.Util.push_back(u);
423 t.RespT.push_back(rt);
424 t.ResidT.push_back(w);
425 t.ArvR.push_back(a);
426 t.Tput.push_back(x);
427 }
428 for (std::size_t c = 0; c < sn.nclasses && c < r.CN.size(); ++c) {
429 t.SysClass.push_back(sn.classes[c].name);
430 t.SysRespT.push_back(r.CN[c]);
431 t.SysTput.push_back(c < r.XN.size() ? r.XN[c] : 0.0);
432 }
433}
434
435/**
436 * The LDES fill. Its solution type carries the six metrics separately and its
437 * per-class CN/XN are (1 x nclasses) MATRICES rather than vectors, so neither
438 * `fill_table` nor `fill_table_sim` can read it.
439 *
440 * ResidT IS RECOMPUTED RATHER THAN TAKEN, which is what the CLI's `-a avg` LDES
441 * arm does and for the same reason: the engine counts ONE VISIT PER STATION, so
442 * the residence time it reports is its response time wherever a visit ratio is
443 * not 1.
444 */
445void fill_table_ldes(AvgTable& t, const qn::NetworkStruct<double>& sn,
446 const ldes::LdesResult& r) {
448 for (std::size_t i = 0; i < sn.nstations; ++i)
449 for (std::size_t c = 0; c < sn.nclasses; ++c) {
450 const double q = r.QN(i, c), u = r.UN(i, c), rt = r.RN(i, c);
451 const double w = WNfix(i, c), a = r.AN(i, c), x = r.TN(i, c);
452 if (q == 0.0 && u == 0.0 && rt == 0.0 && w == 0.0 && a == 0.0 && x == 0.0) continue;
453 t.Station.push_back(sn.stations[i].name);
454 t.JobClass.push_back(sn.classes[c].name);
455 t.QLen.push_back(q);
456 t.Util.push_back(u);
457 t.RespT.push_back(rt);
458 t.ResidT.push_back(w);
459 t.ArvR.push_back(a);
460 t.Tput.push_back(x);
461 }
462 for (std::size_t c = 0; c < sn.nclasses && c < r.CN.cols(); ++c) {
463 t.SysClass.push_back(sn.classes[c].name);
464 t.SysRespT.push_back(r.CN(0, c));
465 t.SysTput.push_back(c < r.XN.cols() ? r.XN(0, c) : 0.0);
466 }
467}
468
469/**
470 * Append the confidence half-widths of the rows a fill just kept.
471 *
472 * The rows are re-selected by the SAME all-zero test over the six means, so row k here is row k
473 * of the table. The ResidT half-width is the RespT one scaled by W/R: the residence time is the
474 * response time times a constant visit ratio, so the interval scales with it.
475 */
476void fill_table_ci(AvgTable& t, const qn::NetworkStruct<double>& sn, const Matrix<double>& QN,
477 const Matrix<double>& UN, const Matrix<double>& RN, const Matrix<double>& WN,
478 const Matrix<double>& AN, const Matrix<double>& TN, const Matrix<double>& QCI,
479 const Matrix<double>& UCI, const Matrix<double>& RCI, const Matrix<double>& ACI,
480 const Matrix<double>& TCI) {
481 const auto at = [](const Matrix<double>& m, std::size_t i, std::size_t c) {
482 return i < m.rows() && c < m.cols() ? m(i, c) : 0.0;
483 };
484 for (std::size_t i = 0; i < sn.nstations; ++i)
485 for (std::size_t c = 0; c < sn.nclasses; ++c) {
486 const double q = QN(i, c), u = UN(i, c), rt = RN(i, c), w = WN(i, c), a = AN(i, c), x = TN(i, c);
487 if (q == 0.0 && u == 0.0 && rt == 0.0 && w == 0.0 && a == 0.0 && x == 0.0) continue;
488 t.QLenCI.push_back(at(QCI, i, c));
489 t.UtilCI.push_back(at(UCI, i, c));
490 t.RespTCI.push_back(at(RCI, i, c));
491 t.ResidTCI.push_back(rt > 0.0 ? at(RCI, i, c) * w / rt : 0.0);
492 t.ArvRCI.push_back(at(ACI, i, c));
493 t.TputCI.push_back(at(TCI, i, c));
494 }
495}
496
497/**
498 * The caller-facing `map_env` knobs, as the gate wants them.
499 *
500 * They live on `SolverOptions` and NOT on `MvaOptions`/`NcSolverOptions`/
501 * `FluidOptions`, because no `runAnalyzer` in the reference reads them: the
502 * fallback is decided one level ABOVE the runner, in `getAvg`, which is what
503 * this facade's `avg_table` plays the part of here.
504 */
505solvers::MapEnvConfig map_env_config(const SolverOptions& o) {
507 if (!o.map_env.empty()) c.mode = o.map_env;
508 if (!o.map_env_method.empty()) c.method = o.map_env_method;
509 if (o.map_env_maxstages) c.max_stages = o.map_env_maxstages;
510 return c;
511}
512
513ctmc::CtmcOptions ctmc_options(const SolverOptions& o) {
515 if (!o.method.empty()) c.method = o.method;
516 if (o.cutoff > 0.0) c.cutoff = o.cutoff;
517 if (!o.cutoff_vec.empty()) c.cutoff_vec = o.cutoff_vec;
518 if (o.state_max) c.state_max = o.state_max;
519 if (o.timestep > 0.0) c.timestep = o.timestep;
520 c.force = o.force;
521 return c;
522}
523
524/**
525 * The symbolic knobs, which live on their own struct rather than on
526 * CtmcOptions: the backend and its timeout configure the computer-algebra
527 * request, not the generator build. An empty or non-positive field keeps the
528 * engine default, as everywhere else here.
529 */
530ctmc::CtmcSymbolicOptions ctmc_symbolic_options(const SolverOptions& o) {
532 if (!o.symbolic.empty()) s.backend = o.symbolic;
533 if (o.symbolic_timeout > 0) s.timeout_s = o.symbolic_timeout;
534 return s;
535}
536
537fluid::FluidOptions fluid_options(const SolverOptions& o) {
539 if (!o.method.empty()) f.method = o.method;
540 if (o.tol >= 0.0) f.tol = o.tol;
541 if (o.iter_tol >= 0.0) f.iter_tol = o.iter_tol;
542 if (o.iter_max >= 0) f.iter_max = static_cast<std::size_t>(o.iter_max);
543 if (o.timespan_end > 0.0) f.timespan_end = o.timespan_end;
544 if (!o.init_sol.empty()) f.init_sol = o.init_sol;
545 if (o.seed) f.seed = o.seed;
546 if (!o.highvar.empty()) f.highvar = o.highvar;
547 if (o.timestep > 0.0) f.timestep = o.timestep;
548 f.stiff = o.stiff;
549 return f;
550}
551
552/**
553 * The JMT client's options.
554 *
555 * `timespan_end` becomes `max_simulated_time`, which is the finite horizon the
556 * replicated arms REQUIRE, and `replications` is `options.config.replications`, the
557 * size of their ensemble. `iter_max` means nothing to JMT and is not read.
558 */
559jmt::JmtOptions jmt_options(const SolverOptions& o) {
561 if (!o.method.empty()) j.method = o.method;
562 if (o.samples) j.samples = static_cast<double>(o.samples);
563 if (o.seed) j.seed = static_cast<long>(o.seed);
564 if (o.replications > 0) j.replications = o.replications;
565 if (o.timespan_end > 0.0) j.max_simulated_time = o.timespan_end;
566 j.confint = o.confint;
567 j.keep = o.keep;
568 j.verbose = o.verbose;
569 return j;
570}
571
572/** The LDES engine's options, shared by the average solve and `cdf_respt`. */
573ldes::LdesOptions ldes_options(const SolverOptions& o) {
575 if (!o.method.empty()) opt.method = o.method;
576 if (o.samples) opt.samples = o.samples;
577 if (o.events) opt.events = o.events;
578 if (o.seed) opt.seed = static_cast<long>(o.seed);
579 if (o.timeout > 0.0) opt.timeout = o.timeout;
580 // `options.replications` is the LDES replication count in the reference (solveCli.m emits
581 // --replications from it), so the facade forwards it rather than leaving it to JMT alone.
582 if (o.replications > 1) opt.replications = o.replications;
583 if (o.confint > 0.0) opt.confint = o.confint;
584 if (!o.cimethod.empty()) opt.cimethod = o.cimethod;
585 if (o.ciminbatch >= 0) opt.ciminbatch = o.ciminbatch;
586 if (o.ciminobs >= 0) opt.ciminobs = o.ciminobs;
587 if (o.obmoverlap >= 0.0) opt.obmoverlap = o.obmoverlap;
588 if (o.spectral_low_freq_frac > 0.0) opt.spectral_low_freq_frac = o.spectral_low_freq_frac;
589 if (!o.tranfilter.empty()) opt.tranfilter = o.tranfilter;
590 if (o.mserbatch > 0) opt.mserbatch = o.mserbatch;
591 if (o.warmupfrac >= 0.0) opt.warmupfrac = o.warmupfrac;
592 opt.cnvgon = o.cnvgon;
593 if (o.cnvgtol > 0.0) opt.cnvgtol = o.cnvgtol;
594 if (o.cnvgbatch > 0) opt.cnvgbatch = o.cnvgbatch;
595 if (o.cnvgchk >= 0) opt.cnvgchk = o.cnvgchk;
596 if (!o.init_sol.empty()) opt.init_sol = o.init_sol;
597 if (o.init_jobs.rows() > 0) opt.init_jobs = o.init_jobs;
598 opt.track_jobs = o.track_jobs;
599 opt.verbose = o.verbose;
600 return opt;
601}
602
603/**
604 * The facade name of an AUTO method family, or a refusal naming what the family needs.
605 *
606 * Mirrors the CLI's `auto_cli_token_of_family`: a family names its engine outright. ln, env and
607 * uq take a LayeredNetwork, an Environment or a sweep, none of which a Network facade holds.
608 */
609std::string facade_name_of_family(const std::string& fam) {
610 if (fam == "mva" || fam == "nc" || fam == "ctmc" || fam == "mam" || fam == "ag" ||
611 fam == "ba" || fam == "ssa" || fam == "jmt" || fam == "lqns") {
612 std::string up = fam;
613 std::transform(up.begin(), up.end(), up.begin(), ::toupper);
614 return up;
615 }
616 if (fam == "fld") return "FLD";
617 if (fam == "ldes") {
619 throw ExternalError(ErrorKind{"LDES"},
620 "SolverAUTO: method family 'ldes' names the discrete-event engine, and none was "
621 "found (common/ldes or common/ldes.jar, or $LINE_LDES_DIR); 'ssa' is the simulator "
622 "this port builds in process");
623 return "LDES";
624 }
625 if (fam == "ln")
626 throw UnsupportedError(ErrorKind{"Option"},
627 "SolverAUTO: method family 'ln' names the layered solver, which takes a "
628 "LayeredNetwork rather than a Network");
629 if (fam == "env")
630 throw UnsupportedError(ErrorKind{"Option"},
631 "SolverAUTO: method family 'env' names the random-environment solver, which takes an "
632 "Environment rather than a Network");
633 if (fam == "uq")
634 throw UnsupportedError(ErrorKind{"Option"},
635 "SolverAUTO: method family 'uq' names the uncertainty-quantification solver, which "
636 "this facade does not wrap");
637 throw InputError("SolverAUTO: no engine stands behind method family '" + fam + "'");
638}
639
640/** A row matrix as a vector; empty stays empty, meaning not computed. */
641std::vector<double> row_of(const Matrix<double>& m) {
642 std::vector<double> v;
643 if (m.rows() > 0)
644 for (std::size_t c = 0; c < m.cols(); ++c) v.push_back(m(0, c));
645 return v;
646}
647
648/** The model's Cache nodes with nothing measured yet: caps, item counts and item sizes only. */
650 return solvers::cache_metrics_of(sn, std::vector<double>(), std::vector<double>(),
651 std::vector<double>(), std::vector<double>(), Matrix<double>(),
652 Matrix<double>(), std::vector<double>());
653}
654
655/** JMT's per-node hit probabilities; the miss is 1 - hit, as SolverJMT/runAnalyzer.m derives it. */
657 const std::map<std::size_t, std::vector<double> >& hit) {
658 solvers::CacheMetrics<double> out = empty_cache_metrics(sn);
659 for (std::size_t c = 0; c < out.caches.size(); ++c) {
660 solvers::CacheNodeMetrics<double>& m = out.caches[c];
661 const std::map<std::size_t, std::vector<double> >::const_iterator it = hit.find(m.node);
662 if (it == hit.end()) continue;
663 m.hitprob = it->second;
664 for (std::size_t r = 0; r < m.hitprob.size(); ++r) m.missprob.push_back(1.0 - m.hitprob[r]);
666 }
667 return out;
668}
669
670/** The LDES `cacheMetrics` block, keyed by Cache NAME (see `CacheNodeMetrics::name`). */
672 const std::map<std::string, ldes::LdesCacheMetrics>& cm) {
673 solvers::CacheMetrics<double> out = empty_cache_metrics(sn);
674 for (std::size_t c = 0; c < out.caches.size(); ++c) {
675 solvers::CacheNodeMetrics<double>& m = out.caches[c];
676 const std::map<std::string, ldes::LdesCacheMetrics>::const_iterator it = cm.find(m.name);
677 if (it == cm.end()) continue;
678 m.hitprob = row_of(it->second.hit);
679 m.missprob = row_of(it->second.miss);
680 m.delayedprob = row_of(it->second.delayed);
681 m.latency = row_of(it->second.latency);
682 m.hitproblist = it->second.hitList;
683 m.itemprob = it->second.itemProb;
684 m.listcost = row_of(it->second.listCost);
686 }
687 return out;
688}
689
690/**
691 * One engine's average table, by facade name. `o.method` is that engine's own method name.
692 * `cache` receives what the engine observed at the Cache nodes, empty where it analyzes none.
693 */
694void solve_named(const std::string& name, const SolverOptions& o,
697 solvers::LossnInfo* lossn = nullptr) {
701 t.solver = name;
702 if (o.confint < 0.0 || o.confint >= 1.0)
703 throw InputError("SolverOptions: confint must be a confidence level in (0,1), or 0 to disable; got " +
704 std::to_string(o.confint));
705 if (name == "MVA") {
707 if (!o.method.empty()) opt.method = o.method;
708 if (o.tol >= 0.0) opt.tol = o.tol;
709 if (o.iter_tol >= 0.0) opt.iter_tol = o.iter_tol;
710 if (o.iter_max >= 0) opt.iter_max = o.iter_max;
711 if (!o.multiserver.empty()) opt.multiserver = o.multiserver;
712 if (!o.highvar.empty()) opt.highvar = o.highvar;
713 if (!o.np_priority.empty()) opt.np_priority = o.np_priority;
714 if (!o.fork_join.empty()) opt.fork_join = o.fork_join;
715 Matrix<double> init;
717 sn, "SolverMVA", qn::mva_feature_set(mva::resolve_method(sn, opt.method), sn),
718 map_env_config(o),
719 [&opt, &init](const qn::NetworkStruct<double>& m) {
720 return mva::solver_mva_run_analyzer(m, opt, init);
721 },
722 solvers::mva_stage_fn(opt), opt.method);
723 t.method = r.actualmethod;
724 fill_table(t, sn, r);
725 cache = r.cache;
726 if (fj) *fj = r.fj;
727 } else if (name == "NC") {
729 if (!o.method.empty()) opt.method = o.method;
730 if (o.tol >= 0.0) opt.tol = o.tol;
731 if (o.iter_tol >= 0.0) opt.iter_tol = o.iter_tol;
732 if (o.iter_max >= 0) opt.iter_max = o.iter_max;
733 if (!o.highvar.empty()) opt.highvar = o.highvar;
734 if (!o.multiserver.empty()) opt.multiserver = o.multiserver;
735 if (!o.fork_join.empty()) opt.fork_join = o.fork_join;
736 if (o.samples) opt.samples = o.samples;
737 if (o.seed) opt.seed = o.seed;
739 sn, "SolverNC", qn::nc_feature_set(opt.method), map_env_config(o),
740 [&opt](const qn::NetworkStruct<double>& m) { return nc::solver_nc_run_analyzer(m, opt); },
741 solvers::nc_stage_fn(opt), opt.method);
742 t.method = r.actualmethod;
743 fill_table(t, sn, r);
744 cache = r.cache;
745 if (fj) *fj = r.fj;
746 if (lossn) *lossn = r.lossn;
747 } else if (name == "CTMC") {
748 const ctmc::CtmcOptions opt = ctmc_options(o);
749 // `mdd` never forms the generator, so it has its own analyzer, as the CLI's `-s ctmc` arm routes it.
753 t.method = r.actualmethod;
754 fill_table(t, sn, r);
755 cache = r.cache;
756 } else if (name == "MAM") {
758 if (!o.method.empty()) opt.method = o.method;
759 if (o.tol >= 0.0) opt.tol = o.tol;
760 if (o.iter_max >= 0) opt.iter_max = o.iter_max;
762 t.method = r.actualmethod;
763 fill_table(t, sn, r);
764 cache = r.cache;
765 } else if (name == "BA") {
766 // DELIBERATELY NOT WRAPPED IN `run_avg`. A bound request must be answered
767 // with a bound, and the environment image is an APPROXIMATION of the
768 // model, so bounds computed on it do not bracket the original. The
769 // reference refuses SolverBA inside `needsMapEnv` itself; here the
770 // exclusion is the absence of the wrapper, so do not "fix" the
771 // inconsistency with the arms above.
773 if (!o.method.empty()) opt.method = o.method;
774 opt.level = o.level;
776 t.method = r.actualmethod;
777 fill_table(t, sn, r);
778 cache = r.cache;
779 } else if (name == "SSA") {
781 if (!o.method.empty()) opt.method = o.method;
782 if (o.samples) opt.samples = o.samples;
783 if (o.events) opt.samples = o.events;
784 if (o.seed) opt.seed = o.seed;
785 if (o.cutoff > 0.0) opt.cutoff = o.cutoff;
786 if (o.warmupfrac >= 0.0) opt.warmupfrac = o.warmupfrac;
787 if (o.timestep > 0.0) opt.timestep = o.timestep; // the fixed step of method 'tstep'
788 if (!o.state_space_gen.empty()) opt.state_space_gen = o.state_space_gen;
789 opt.verbose = o.verbose;
790 // The derived columns are taken on the MEASURED cache split, as the
791 // CLI's `-s ssa` arm does: the base struct carries `link()`'s even
792 // hit/miss offer, so ArvR and ResidT read off it are not the model's.
793 std::vector<ssa::SsaCacheRatio> cacheratio;
794 const ssa::SsaSolution r = ssa::solver_ssa(sn, opt, &cacheratio);
795 t.method = r.method;
796 fill_table_sim(t, ssa::sn_with_ssa_cache_split<double>(sn, cacheratio), r);
798 } else if (name == "FLD" || name == "FLUID") {
799 const fluid::FluidOptions opt = fluid_options(o);
800 // The fluid arm cannot go through `run_avg`: its runner reports a
801 // `FluidSolution` and the driver an `AvgResult`, so the two halves fill
802 // the table through different helpers. The DECISION is the same one
803 // `run_avg` makes, asked here directly rather than duplicated.
804 const solvers::MapEnvConfig mecfg = map_env_config(o);
807 if (d.needed) {
809 sn, "SolverFLD", mecfg, solvers::fluid_stage_fn(opt), opt.method);
810 t.method = r.actualmethod;
811 fill_table(t, sn, r);
812 cache = r.cache;
813 if (fj) *fj = r.fj;
814 } else {
815 // The refreshed struct carries the CONVERGED cache split; ArvR read off `sn` would report
816 // link()'s offered one instead (cache_replc_routing: 0.5/0.5 for 0.4/0.6), as in `-s fluid`.
819 sn, opt, static_cast<qn::NetworkStruct<double>*>(nullptr), &refreshed, &cache);
820 t.method = r.method;
821 t.iter = static_cast<int>(r.iters);
822 t.warning = r.warning;
823 if (fj) *fj = r.fj;
824 const bool has_ref = refreshed.nstations == sn.nstations && refreshed.nclasses == sn.nclasses;
825 fill_table_sim(t, has_ref ? refreshed : sn, r);
826 }
827 } else if (name == "JMT") {
828 const jmt::JmtOptions opt = jmt_options(o);
830 t.method = r.avg.actualmethod;
831 fill_table(t, sn, r.avg);
832 cache = r.cache_hit_prob.empty() ? r.avg.cache : cache_metrics_of_jmt(sn, r.cache_hit_prob);
833 if (fj) *fj = r.avg.fj;
834 if (o.confint > 0.0 && !r.QCI.empty())
835 fill_table_ci(t, sn, r.avg.QN, r.avg.UN, r.avg.RN, r.avg.WN, r.avg.AN, r.avg.TN, r.QCI,
836 r.UCI, r.RCI, r.ACI, r.TCI);
837 } else if (name == "LDES") {
838 const ldes::LdesOptions opt = ldes_options(o);
840 t.method = opt.method;
841 fill_table_ldes(t, sn, r);
842 cache = cache_metrics_of_ldes(sn, r.cache_metrics);
843 if (fj) *fj = ldes::ldes_fj_metrics(sn, r);
844 if (o.confint > 0.0 && !r.QNCI.empty())
845 fill_table_ci(t, sn, r.QN, r.UN, r.RN, mva::sn_get_residt_from_respt<double>(sn, r.RN), r.AN,
846 r.TN, r.QNCI, r.UNCI, r.RNCI, r.ANCI, r.TNCI);
847 } else if (name == "AG") {
849 if (!o.method.empty() && o.method != "default") opt.method = o.method;
850 if (o.tol >= 0.0) opt.tol = o.tol;
851 if (o.iter_max >= 0) opt.iter_max = o.iter_max;
853 t.method = r.actualmethod;
854 fill_table(t, sn, r);
855 cache = r.cache;
856 } else if (name == "LQNS") {
857 // On a flat Network the lqns family's methods are the qns ones, served by `qnsolver`.
859 if (!o.method.empty()) opt.method = o.method;
860 if (!o.multiserver.empty()) opt.multiserver = o.multiserver;
861 opt.keep = o.keep;
863 t.method = r.actualmethod;
864 fill_table(t, sn, r);
865 cache = r.cache;
866 } else {
867 throw UnsupportedError(ErrorKind{"Solver"}, "avg_table: unknown solver '" + name + "'");
868 }
869}
870
871/**
872 * SolverAUTO's average table, as `-s auto` computes it (line_cli.cpp, `choose_auto_plan`).
873 *
874 * `o.method` is resolved first: a method FAMILY ('nc', 'nc.comom', 'bound') names the engine and
875 * passes the submethod to it; an INTENT ('default', 'sim', 'exact', 'fast', 'accurate', 'heur')
876 * picks the ranking, whose proposed order is a RETRY LIST. Only the first attempt carries the
877 * method the ranking gated on. Input and internal errors propagate; the other categories move on,
878 * and when every candidate fails the chosen engine's error is reported.
879 */
880void solve_auto(const SolverOptions& o, const qn::NetworkStruct<double>& sn, AvgTable& t,
883 SolverOptions oo = o;
884 if (!tok.is_intent) {
885 oo.method = tok.submethod;
886 solve_named(facade_name_of_family(tok.family), oo, sn, t, cache, fj);
887 return;
888 }
889 const autosolver::AutoChoice c = autosolver::auto_choose_solver_mode(sn, "getAvgTable", tok.mode);
890 const std::vector<autosolver::AutoSolver> order =
891 autosolver::auto_proposed_solvers(sn, "getAvgTable", tok.mode);
892 std::string first_error, first_category, first_kind;
893 for (std::size_t i = 0; i < order.size(); ++i) {
894 std::string name = autosolver::auto_solver_name(order[i]);
895 std::transform(name.begin(), name.end(), name.begin(), ::toupper);
896 if (name == "FLUID") name = "FLD";
897 oo.method = (i == 0 && !c.method.empty()) ? c.method : std::string("default");
898 try {
899 AvgTable attempt;
900 solvers::CacheMetrics<double> attempt_cache;
902 solve_named(name, oo, sn, attempt, attempt_cache, &attempt_fj);
903 t = attempt;
904 cache = attempt_cache;
905 if (fj) *fj = attempt_fj;
906 return;
907 } catch (const Error& e) {
908 const std::string cat = e.category();
909 if (cat == "input" || cat == "internal") throw;
910 // A candidate that ran out of the wall-clock budget is FINAL: the
911 // budget covers the whole top-level solve, so the next candidate
912 // would start with none of it left.
913 if (cat == "numerical" && e.kind() == "Timeout") throw;
914 if (first_error.empty()) {
915 first_error = name + ": " + e.what();
916 first_category = cat;
917 first_kind = e.kind();
918 }
919 } catch (const std::exception& e) {
920 if (first_error.empty()) first_error = name + ": " + e.what();
921 }
922 }
923 const std::string all_failed =
924 "SolverAUTO: every candidate refused this run. The chosen engine reported -- " + first_error;
925 if (first_category == "numerical") throw NumericError(ErrorKind{first_kind}, all_failed);
926 if (first_category == "external") throw ExternalError(ErrorKind{first_kind}, all_failed);
927 throw UnsupportedError(ErrorKind{first_kind.empty() ? std::string("Solver") : first_kind},
928 all_failed);
929}
930
931/** Defined below `avg_result_of_table`, which it reads its solve back through. */
932void solve_zero_capacity(const std::string& name, const SolverOptions& o,
936
937} // namespace
938
939// ---------------------------------------------------------------------------
940// NetworkSolver
941// ---------------------------------------------------------------------------
942
944 // options.cache: a stored result is reused only while caching is on, as getAvg does.
945 if (solved_ && opts_.cache) return table_;
946 AvgTable t;
948 // a pairwise switchover at a non-polling queue is kept in the model but no solver simulates it, as the reference warns
949 for (const auto& st : sn.stations)
950 for (const auto& row : st.switchover_pair)
951 if (std::any_of(row.begin(), row.end(), [](const lang::Distrib<double>& d) {
952 return !d.disabled && d.type != lang::ProcessType::IMMEDIATE;
953 })) {
954 std::cerr << "[LINE] Warning: Station " << st.name << " declares class-to-class switchover "
955 << "times, which no LINE solver simulates at a non-polling queue: every solver "
956 << "answers as if they were zero. Only POLLING switchovers are solved." << std::endl;
957 break;
958 }
962 // A closed chain visiting a station with zero servers is trapped there;
963 // see sn_zero_capacity. This is `@NetworkSolver/getAvg`'s hook, ahead of the
964 // map_env funnel each engine applies, so every Network solver takes it.
966 if (!zc.reason.empty()) throw UnsupportedError(ErrorKind{"Structure"}, zc.reason);
967 {
968 // options.timeout: one budget for the whole solve, capped by any budget
969 // a caller already armed; the flag is the scope's TRIPPED latch, read
970 // before the scope pops, and is set afresh by every solve.
971 // An unbudgeted solve under a caller's budget reads the caller's frame,
972 // so a latch that frame already carried is not this solve's.
973 const bool tripped_before = util::timeout_tripped();
975 if (zc.any())
976 solve_zero_capacity(name_, opts_, sn, zc, t, cache, &fj);
977 else if (name_ == "AUTO")
978 solve_auto(opts_, sn, t, cache, &fj);
979 else
980 solve_named(name_, opts_, sn, t, cache, &fj, &lossn);
981 t.timed_out = util::timeout_tripped() && (budget.active() || !tripped_before);
982 // the caller that armed an outer budget (line-cli) warns with its own value
983 if (t.timed_out && budget.active()) util::timeout_warn("Solver" + name_, opts_.timeout);
984 }
985 table_ = t;
986 cache_ = cache;
987 fj_ = fj;
988 lossn_ = lossn;
989 solved_ = true;
990 return table_;
991}
992
993std::string NetworkSolver::method_used() { return avg_table().method; }
994
995namespace {
996
997/**
998 * The solved table laid back onto the station x class matrices that getAvgSys and getAvgChain read;
999 * a row the table dropped was all-zero, which is what the fresh matrices already hold.
1000 */
1001mva::AvgResult<double> avg_result_of_table(const qn::NetworkStruct<double>& sn, const AvgTable& t) {
1002 const std::size_t M = sn.nstations, K = sn.nclasses;
1004 r.QN = Matrix<double>(M, K);
1005 r.UN = Matrix<double>(M, K);
1006 r.RN = Matrix<double>(M, K);
1007 r.TN = Matrix<double>(M, K);
1008 r.AN = Matrix<double>(M, K);
1009 r.WN = Matrix<double>(M, K);
1010 for (std::size_t row = 0; row < t.size(); ++row)
1011 for (std::size_t i = 0; i < M; ++i) {
1012 if (sn.stations[i].name != t.Station[row]) continue;
1013 for (std::size_t c = 0; c < K; ++c) {
1014 if (sn.classes[c].name != t.JobClass[row]) continue;
1015 r.QN(i, c) = t.QLen[row];
1016 r.UN(i, c) = t.Util[row];
1017 r.RN(i, c) = t.RespT[row];
1018 r.TN(i, c) = t.Tput[row];
1019 r.AN(i, c) = t.ArvR[row];
1020 r.WN(i, c) = t.ResidT[row];
1021 }
1022 }
1023 return r;
1024}
1025
1026/**
1027 * `getAvgZeroCapacity`: solve the model without the chains trapped at a
1028 * zero-capacity station, whose jobs hold no other resource, then park each
1029 * trapped population there.
1030 *
1031 * The reduced model is a COPY of the struct, refreshed as `get_struct` does,
1032 * where the reference edits the model and restores it on cleanup: the user's
1033 * model is never touched, so there is nothing to restore. The trapped classes
1034 * have population 0 and a zero-server station one server (no remaining chain
1035 * visits it); a rate-zero station keeps its servers. When every class is
1036 * trapped nothing is solved. At the dead station the trapped chain holds its
1037 * whole population, split by visits, with RespT = ResidT = Inf for the classes
1038 * that visit it; every other metric of the chain is 0, its system response
1039 * time Inf and its system throughput 0.
1040 */
1041void solve_zero_capacity(const std::string& name, const SolverOptions& o,
1045 const std::size_t M = sn.nstations, K = sn.nclasses;
1046 const double inf = std::numeric_limits<double>::infinity();
1047 std::vector<bool> trappedcls(K, false);
1048 std::size_t ntrapped = 0;
1049 for (std::size_t c = 0; c < sn.nchains; ++c)
1050 if (zc.deadstat[c] > 0)
1051 for (std::size_t r = 0; r < K; ++r)
1052 if (sn.chains[c][r] && !trappedcls[r]) {
1053 trappedcls[r] = true;
1054 ++ntrapped;
1055 }
1057 AvgTable solved;
1058 if (ntrapped == K) {
1059 r.QN = Matrix<double>(M, K, 0.0);
1060 r.UN = r.QN;
1061 r.RN = r.QN;
1062 r.TN = r.QN;
1063 r.AN = r.QN;
1064 r.WN = r.QN;
1065 solved.solver = name;
1066 solved.method = o.method.empty() ? std::string("default") : o.method;
1069 } else {
1070 qn::NetworkStruct<double> reduced = sn;
1071 for (std::size_t k = 0; k < K; ++k)
1072 if (trappedcls[k]) reduced.classes[k].population = 0.0;
1073 for (std::size_t c = 0; c < sn.nchains; ++c) {
1074 const std::size_t i = zc.deadstat[c];
1075 if (i > 0 && sn.stations[i - 1].nservers == 0.0) reduced.stations[i - 1].nservers = 1.0;
1076 }
1077 reduced.refresh_struct();
1079 if (name == "AUTO")
1080 solve_auto(o, reduced, solved, cache, fj);
1081 else
1082 solve_named(name, o, reduced, solved, cache, fj);
1083 r = avg_result_of_table(sn, solved);
1084 }
1085 std::vector<double> CN(K, 0.0), XN(K, 0.0);
1086 for (std::size_t row = 0; row < solved.SysClass.size(); ++row)
1087 for (std::size_t k = 0; k < K; ++k)
1088 if (sn.classes[k].name == solved.SysClass[row]) {
1089 CN[k] = solved.SysRespT[row];
1090 XN[k] = solved.SysTput[row];
1091 }
1092 const std::vector<double> st2sf = sn.station_to_stateful();
1093 const std::vector<double> njobs = sn.njobs();
1094 for (std::size_t c = 0; c < sn.nchains; ++c) {
1095 if (zc.deadstat[c] == 0) continue;
1096 const std::size_t i = zc.deadstat[c] - 1;
1097 const std::size_t sf = static_cast<std::size_t>(st2sf[i]) - 1;
1098 double pop = 0.0, vtot = 0.0;
1099 for (std::size_t k = 0; k < K; ++k)
1100 if (sn.chains[c][k]) {
1101 pop += njobs[k];
1102 vtot += sn.visits[c](sf, k);
1103 }
1104 for (std::size_t k = 0; k < K; ++k) {
1105 if (!sn.chains[c][k]) continue;
1106 for (std::size_t j = 0; j < M; ++j) {
1107 r.QN(j, k) = 0.0;
1108 r.UN(j, k) = 0.0;
1109 r.RN(j, k) = 0.0;
1110 r.TN(j, k) = 0.0;
1111 r.AN(j, k) = 0.0;
1112 r.WN(j, k) = 0.0;
1113 }
1114 const double v = sn.visits[c](sf, k);
1115 r.QN(i, k) = pop * v / vtot;
1116 if (v > 0.0) {
1117 r.RN(i, k) = inf;
1118 r.WN(i, k) = inf;
1119 }
1120 XN[k] = 0.0;
1121 CN[k] = inf;
1122 }
1123 }
1124 r.CN = CN;
1125 r.XN = XN;
1126 r.iter = solved.iter;
1127 r.warning = solved.warning;
1128 r.listcost = solved.ListCost;
1129 if (solved.has_lognormconst) r.lognormconst = solved.lognormconst;
1130 t = AvgTable();
1131 t.solver = solved.solver;
1132 t.method = solved.method;
1133 fill_table(t, sn, r);
1134}
1135
1136} // namespace
1137
1139 const AvgTable& t = avg_table();
1141 const mva::AvgResult<double> r = avg_result_of_table(sn, t);
1143 AvgSysTable out;
1144 out.Chain = solvers::chain_names(sn.nchains);
1146 out.SysRespT = sys.CN;
1147 out.SysTput = sys.XN;
1148 return out;
1149}
1150
1152 const AvgTable& t = avg_table();
1154 const solvers::ChainResult<double> c = solvers::solver_get_avg_chain<double>(sn, avg_result_of_table(sn, t));
1155 AvgChain out;
1156 out.QN = c.QN;
1157 out.UN = c.UN;
1158 out.RN = c.RN;
1159 out.WN = c.WN;
1160 out.AN = c.AN;
1161 out.TN = c.TN;
1162 return out;
1163}
1164
1166 // getAvgChainTable.m: row-major over (station, chain), every row kept.
1167 const AvgChain c = avg_chain();
1169 const std::vector<std::string> chains = solvers::chain_names(sn.nchains);
1170 const std::vector<std::string> labels = solvers::chain_class_labels<double>(sn);
1171 AvgChainTable out;
1172 for (std::size_t i = 0; i < sn.nstations; ++i)
1173 for (std::size_t k = 0; k < sn.nchains; ++k) {
1174 out.Station.push_back(sn.stations[i].name);
1175 out.Chain.push_back(chains[k]);
1176 out.JobClasses.push_back(labels[k]);
1177 out.QLen.push_back(c.QN(i, k));
1178 out.Util.push_back(c.UN(i, k));
1179 out.RespT.push_back(c.RN(i, k));
1180 out.ResidT.push_back(c.WN(i, k));
1181 out.ArvR.push_back(c.AN(i, k));
1182 out.Tput.push_back(c.TN(i, k));
1183 }
1184 return out;
1185}
1186
1191
1196
1197std::vector<Matrix<double>> NetworkSolver::avg_tard() {
1198 const std::string used = method_used();
1199 if (name_ != "MVA") return {Matrix<double>(), Matrix<double>()};
1200 // the reference's runAnalyzer computes it after the solve from actualmethod
1202 return {t.Tard, t.SysTard};
1203}
1204
1207 AvgFJTable out;
1208 if (fj.empty()) return out;
1210 for (std::size_t p = 0; p < fj.npairs(); ++p)
1211 for (std::size_t r = 0; r < fj.QLen.cols(); ++r) {
1212 const double q = fj.QLen(p, r), rt = fj.RespT(p, r), x = fj.Tput(p, r);
1213 if (!(q > 0.0 || rt > 0.0 || x > 0.0)) continue; // getAvgFJTable keeps a row when any value is > 0
1214 out.Fork.push_back(sn.nodes[fj.forks[p] - 1].name);
1215 out.Join.push_back(sn.nodes[fj.joins[p] - 1].name);
1216 out.JobClass.push_back(sn.classes[r].name);
1217 out.FJQLen.push_back(q);
1218 out.FJRespT.push_back(rt);
1219 out.FJTput.push_back(x);
1220 }
1221 return out;
1222}
1223
1224// ---------------------------------------------------------------------------
1225// SolverNC
1226// ---------------------------------------------------------------------------
1227
1229 avg_table();
1230 return lossn_;
1231}
1232
1234 const solvers::LossnInfo& info = lossn_info();
1235 AvgLinkTable out;
1236 if (info.empty()) return out;
1238 if (info.samples) mciopt.samples = info.samples;
1240 lossn::lossn_links<double>(info.nu, info.A, info.C, info.method, mciopt, info.seed);
1242 for (std::size_t j = 0; j < info.A.rows(); ++j)
1243 for (std::size_t r = 0; r < info.A.cols(); ++r) {
1244 if (!(info.A(j, r) > 0.0)) continue;
1245 out.Link.push_back(j < info.links.size() ? info.links[j] : std::string());
1246 out.JobClass.push_back(sn.classes[r].name);
1247 out.Capacity.push_back(info.C[j]);
1248 out.Demand.push_back(info.A(j, r));
1249 out.Occupancy.push_back(lk.Occ[j]);
1250 out.LinkBlocking.push_back(lk.E(j, r));
1251 out.RouteLoss.push_back(lk.Loss[r]);
1252 }
1253 return out;
1254}
1255
1256namespace {
1257
1258/** The named Cache's per-class hit (or miss) vector, refused when the solve measured none. */
1259std::vector<double> cache_ratio(const solvers::CacheMetrics<double>& cm, const std::string& solver,
1260 const std::string& cache, bool hit) {
1261 for (std::size_t c = 0; c < cm.caches.size(); ++c) {
1262 if (cm.caches[c].name != cache) continue;
1263 const std::vector<double>& v = hit ? cm.caches[c].hitprob : cm.caches[c].missprob;
1264 if (v.empty())
1265 throw UnsupportedError(ErrorKind{"Analysis"},
1266 "Solver" + solver + " measured no " + (hit ? "hit" : "miss") +
1267 " ratio at Cache '" + cache + "' with this method");
1268 return v;
1269 }
1270 throw InputError("'" + cache + "' is not a Cache node of this model");
1271}
1272
1273} // namespace
1274
1275std::vector<double> NetworkSolver::hit_ratio(const std::string& cache) {
1276 return cache_ratio(cache_metrics(), name_, cache, true);
1277}
1278
1279std::vector<double> NetworkSolver::miss_ratio(const std::string& cache) {
1280 return cache_ratio(cache_metrics(), name_, cache, false);
1281}
1282
1283std::vector<double> NetworkSolver::hit_ratio(const Node& cache) { return hit_ratio(cache.get_name()); }
1284
1285std::vector<double> NetworkSolver::miss_ratio(const Node& cache) { return miss_ratio(cache.get_name()); }
1286
1287std::vector<std::string> NetworkSolver::list_valid_methods() const {
1289 if (name_ == "MVA") return mva::list_valid_methods(sn);
1290 if (name_ == "NC") return nc::list_valid_methods();
1291 if (name_ == "CTMC") return ctmc::list_valid_methods();
1292 if (name_ == "MAM") return mam::list_valid_methods();
1293 // The model-aware overload, not the bare one: the reduction bounds are
1294 // derived for a single-class closed network of single servers and the three
1295 // open-network bounds for its mirror image, so the list a caller may act on
1296 // depends on the model. `SolverBA` gates on exactly this list.
1297 if (name_ == "BA") return ba::list_valid_methods(sn);
1298 if (name_ == "FLD") return fluid::fluid_list_valid_methods();
1299 if (name_ == "SSA") return ssa::list_valid_methods();
1300 if (name_ == "JMT") return jmt::jmt_list_valid_methods();
1301 if (name_ == "LDES") return ldes::list_valid_methods();
1302 // AUTO answers about every family it can delegate to, gated by each one's
1303 // feature set on this model; see `auto_methods.h`.
1304 if (name_ == "AUTO") return autosolver::auto_list_valid_methods(sn);
1305 throw UnsupportedError(ErrorKind{"Solver"}, "list_valid_methods: unknown solver '" + name_ + "'");
1306}
1307
1308// ---------------------------------------------------------------------------
1309// SolverCTMC
1310// ---------------------------------------------------------------------------
1311
1317
1320 ctmc::CtmcOptions opt = ctmc_options(opts_);
1321 opt.keep_filtration = true;
1323 return ctmc::ctmc_get_infgen(sn, d).Q;
1324}
1325
1326double SolverCTMC::prob_aggr(std::size_t node, const std::vector<double>& state) {
1330 const std::size_t ist = sn.nodes[node - 1].station;
1331 if (ist == 0) throw InputError("prob_aggr: the node is not a station");
1332 const std::size_t K = sn.nclasses;
1333 if (state.size() != K) throw InputError("prob_aggr: the state must have one entry per class");
1334 double p = 0.0;
1335 for (std::size_t s = 0; s < A.rows(); ++s) {
1336 bool hit = true;
1337 for (std::size_t k = 0; k < K && hit; ++k) hit = A(s, (ist - 1) * K + k) == state[k];
1338 if (hit) p += d.pi[s];
1339 }
1340 return p;
1341}
1342
1343std::vector<double> SolverCTMC::marg_aggr(std::size_t node) {
1347 const std::size_t ist = sn.nodes[node - 1].station;
1348 if (ist == 0) throw InputError("marg_aggr: the node is not a station");
1349 const std::size_t K = sn.nclasses;
1350 std::size_t nmax = 0;
1351 for (std::size_t s = 0; s < A.rows(); ++s) {
1352 double tot = 0.0;
1353 for (std::size_t k = 0; k < K; ++k) tot += A(s, (ist - 1) * K + k);
1354 nmax = std::max(nmax, static_cast<std::size_t>(tot));
1355 }
1356 std::vector<double> pmf(nmax + 1, 0.0);
1357 for (std::size_t s = 0; s < A.rows(); ++s) {
1358 double tot = 0.0;
1359 for (std::size_t k = 0; k < K; ++k) tot += A(s, (ist - 1) * K + k);
1360 pmf[static_cast<std::size_t>(tot)] += d.pi[s];
1361 }
1362 return pmf;
1363}
1364
1365std::vector<std::vector<CdfCurve> > SolverCTMC::cdf_respt() {
1367 std::vector<std::vector<CdfCurve> > out(sn.nstations, std::vector<CdfCurve>(sn.nclasses));
1368 const std::vector<std::vector<ctmc::CdfCurve<double> > > R =
1369 ctmc::solver_ctmc_cdf_respt(sn, ctmc_options(opts_));
1370 for (std::size_t i = 0; i < R.size() && i < out.size(); ++i)
1371 for (std::size_t c = 0; c < R[i].size() && c < out[i].size(); ++c) {
1372 out[i][c].t = R[i][c].t;
1373 out[i][c].F = R[i][c].F;
1374 }
1375 return out;
1376}
1377
1378AccReward SolverCTMC::acc_reward(const std::string& name) {
1379 if (!(opts_.timespan_end > 0.0) || !std::isfinite(opts_.timespan_end))
1380 throw InputError("acc_reward: a finite positive options.timespan_end is required");
1381 return acc_reward(name, 0.0, opts_.timespan_end);
1382}
1383
1384AccReward SolverCTMC::acc_reward(const std::string& name, double t0, double t1) {
1386 const ctmc::CtmcAccReward<double> r = ctmc::solver_ctmc_acc_reward(sn, ctmc_options(opts_), t0, t1);
1387 AccReward out;
1388 out.t = r.t;
1389 for (std::size_t i = 0; i < r.names.size(); ++i) {
1390 if (!name.empty() && r.names[i] != name) continue;
1391 out.names.push_back(r.names[i]);
1392 out.metric.push_back(r.metric[i]);
1393 out.avg.push_back(r.avg[i]);
1394 }
1395 if (out.names.empty()) throw InputError("acc_reward: no reward named '" + name + "'");
1396 return out;
1397}
1398
1404
1405std::size_t StateView::column(std::size_t node, std::size_t cls) const {
1406 if (node == 0 || node > sn_->nodes.size())
1407 throw InputError("StateView: node index " + std::to_string(node) + " does not exist");
1408 const std::size_t ist = sn_->nodes[node - 1].station;
1409 if (ist == 0)
1410 throw InputError("StateView: node '" + sn_->nodes[node - 1].name +
1411 "' is not a station, so the aggregate state holds no count for it");
1412 if (cls == 0 || cls > sn_->nclasses)
1413 throw InputError("StateView: class index " + std::to_string(cls) + " does not exist");
1414 return (ist - 1) * sn_->nclasses + (cls - 1);
1415}
1416
1417double StateView::at(std::size_t node, std::size_t cls) const {
1418 return (*row_)[column(node, cls)];
1419}
1420
1421double StateView::total(std::size_t node) const {
1422 double tot = 0.0;
1423 for (std::size_t k = 1; k <= sn_->nclasses; ++k) tot += (*row_)[column(node, k)];
1424 return tot;
1425}
1426
1427namespace {
1428
1429/**
1430 * The 1-based rows on which `fn` holds, as the n x 1 index matrix the CTMC
1431 * getters resolve; empty for an empty predicate or when no state satisfies it,
1432 * as the reference's `ctmc_predicate_states` returns `[]`.
1433 */
1434Matrix<double> predicate_states(const StatePredicate& fn, const qn::NetworkStruct<double>& sn,
1435 const Matrix<double>& aggr, std::size_t n, const char* name) {
1436 if (!fn) return Matrix<double>();
1437 if (aggr.rows() != n)
1438 throw InputError(std::string("The aggregated state space has ") +
1439 std::to_string(aggr.rows()) + " rows where the generator has " +
1440 std::to_string(n) + ", so the predicate for set " + name +
1441 " cannot be resolved state by state.");
1442 std::vector<double> hit;
1443 std::vector<double> row(aggr.cols());
1444 for (std::size_t s = 0; s < n; ++s) {
1445 for (std::size_t c = 0; c < aggr.cols(); ++c) row[c] = aggr(s, c);
1446 if (fn(StateView(row, sn))) hit.push_back(static_cast<double>(s + 1));
1447 }
1448 Matrix<double> out(hit.size(), hit.empty() ? 0 : 1);
1449 for (std::size_t i = 0; i < hit.size(); ++i) out(i, 0) = hit[i];
1450 return out;
1451}
1452
1453FirstPassage to_first_passage(const ctmc::CtmcFirstPassage& r) {
1454 FirstPassage out;
1455 out.t = r.t;
1456 out.F = r.F;
1457 out.f = r.f;
1458 out.reachprob = r.reachprob;
1459 out.tabooprob = r.tabooprob;
1460 out.source = r.source;
1461 out.target = r.target;
1462 out.taboo = r.taboo;
1463 return out;
1464}
1465
1466FirstPassageMoments to_first_passage_moments(const ctmc::CtmcFirstPassageMoments<double>& r) {
1468 out.m = r.m;
1469 out.mall = r.mall;
1470 out.p = r.p;
1471 out.source = r.source;
1472 out.target = r.target;
1473 out.taboo = r.taboo;
1474 return out;
1475}
1476
1477} // namespace
1478
1480 const Matrix<double>& C,
1481 const std::vector<double>& tset) {
1484 return to_first_passage(ctmc::ctmc_cdf_firstpasst(sn, d, A, B, C, tset));
1485}
1486
1488 const StatePredicate& C,
1489 const std::vector<double>& tset) {
1492 const qn::NetworkStruct<double>& ssn = d.solved_sn ? *d.solved_sn : sn;
1494 const std::size_t n = d.chain.Q.rows();
1495 return to_first_passage(ctmc::ctmc_cdf_firstpasst(
1496 sn, d, predicate_states(A, ssn, aggr, n, "A"), predicate_states(B, ssn, aggr, n, "B"),
1497 predicate_states(C, ssn, aggr, n, "C"), tset));
1498}
1499
1501 const Matrix<double>& B, std::size_t nmax,
1502 const Matrix<double>& C) {
1505 return to_first_passage_moments(ctmc::ctmc_firstpasst_moments(sn, d, A, B, nmax, C));
1506}
1507
1509 const StatePredicate& B, std::size_t nmax,
1510 const StatePredicate& C) {
1513 const qn::NetworkStruct<double>& ssn = d.solved_sn ? *d.solved_sn : sn;
1515 const std::size_t n = d.chain.Q.rows();
1516 return to_first_passage_moments(ctmc::ctmc_firstpasst_moments(
1517 sn, d, predicate_states(A, ssn, aggr, n, "A"), predicate_states(B, ssn, aggr, n, "B"),
1518 nmax, predicate_states(C, ssn, aggr, n, "C")));
1519}
1520
1524 ctmc::ctmc_symbolic_solution(sn, ctmc_options(opts_), ctmc_symbolic_options(opts_));
1525 SymbolicSolution out;
1526 out.pi = r.pi;
1527 out.num = r.num;
1528 out.den = r.den;
1529 out.engine = r.engine;
1530 out.symbols = r.symbols;
1531 out.rate0 = r.rate0;
1532 return out;
1533}
1534
1536 std::printf("%8s %-28s %s\n", "State", "Marking", "Rates (to: rate)");
1537 for (std::size_t i = 0; i < Q.rows(); ++i) {
1538 std::string mark;
1539 if (i < space.rows()) {
1540 std::ostringstream os;
1541 os << "[";
1542 for (std::size_t c = 0; c < space.cols(); ++c) os << (c ? " " : "") << space(i, c);
1543 os << "]";
1544 mark = os.str();
1545 }
1546 std::printf("%8zu %-28s", i + 1, mark.c_str());
1547 for (std::size_t j = 0; j < Q.cols(); ++j)
1548 if (i != j && Q(i, j) != 0.0) std::printf(" %zu: %.6g", j + 1, Q(i, j));
1549 std::printf("\n");
1550 }
1551}
1552
1553// ---------------------------------------------------------------------------
1554// SolverFLD
1555// ---------------------------------------------------------------------------
1556
1559 const std::vector<fluid::FluidTranPoint> pts =
1560 fluid::solver_fluid_tran_avg(sn, fluid_options(opts_), 100);
1561 TranAvg out;
1562 for (std::size_t i = 0; i < sn.nstations; ++i)
1563 for (std::size_t c = 0; c < sn.nclasses; ++c)
1564 out.label.push_back(sn.stations[i].name + "/" + sn.classes[c].name);
1565 for (std::size_t s = 0; s < pts.size(); ++s) {
1566 out.t.push_back(pts[s].t);
1567 std::vector<double> row;
1568 for (std::size_t i = 0; i < sn.nstations; ++i)
1569 for (std::size_t c = 0; c < sn.nclasses; ++c) row.push_back(pts[s].QN(i, c));
1570 out.QNt.push_back(row);
1571 }
1572 return out;
1573}
1574
1575std::vector<std::vector<CdfCurve> > SolverFLD::cdf_respt() {
1577 std::vector<std::vector<CdfCurve> > out(sn.nstations, std::vector<CdfCurve>(sn.nclasses));
1578 const std::vector<std::vector<fluid::FluidPassage> > R =
1579 fluid::solver_fluid_cdf_respt(sn, fluid_options(opts_));
1580 for (std::size_t i = 0; i < R.size() && i < out.size(); ++i)
1581 for (std::size_t c = 0; c < R[i].size() && c < out[i].size(); ++c) {
1582 out[i][c].t = R[i][c].t;
1583 out[i][c].F = R[i][c].cdf;
1584 }
1585 return out;
1586}
1587
1588// ---------------------------------------------------------------------------
1589// SolverLDES
1590// ---------------------------------------------------------------------------
1591
1592std::vector<std::vector<CdfCurve> > SolverLDES::cdf_respt() {
1594 const ldes::LdesResult r =
1595 ldes::solver_ldes(sn, ldes_options(opts_), std::vector<std::string>(1, "--respt-samples"));
1596 if (r.respTimeSamples.empty())
1597 throw ExternalError(ErrorKind{"LDES"},
1598 "SolverLDES::cdf_respt needs the per-job response times the engine records under "
1599 "--respt-samples and the run returned none; raise the samples so completions are observed");
1600 std::vector<std::vector<CdfCurve> > out(sn.nstations, std::vector<CdfCurve>(sn.nclasses));
1601 for (std::size_t i = 0; i < sn.nstations; ++i)
1602 for (std::size_t c = 0; c < sn.nclasses; ++c) {
1603 const Matrix<double> m = ldes::ldes_cdf_respt(r, i, c);
1604 for (std::size_t j = 0; j < m.rows(); ++j) {
1605 out[i][c].F.push_back(m(j, 0));
1606 out[i][c].t.push_back(m(j, 1));
1607 }
1608 }
1609 return out;
1610}
1611
1612std::vector<PerctRespTCI> SolverLDES::perct_respt(const std::vector<double>& percentiles, long job_class,
1613 const std::string& method) {
1615 const std::vector<ldes::LdesPercentileResult> rows =
1616 ldes::ldes_perct_respt(sn, ldes_options(opts_), percentiles, method, job_class);
1617 std::vector<PerctRespTCI> out;
1618 out.reserve(rows.size());
1619 for (std::size_t n = 0; n < rows.size(); ++n) {
1620 PerctRespTCI e;
1621 e.station = rows[n].station;
1622 e.job_class = rows[n].job_class;
1623 e.percentiles = rows[n].percentiles;
1624 e.values = rows[n].values;
1625 e.lower = rows[n].lower;
1626 e.upper = rows[n].upper;
1627 e.halfwidth = rows[n].halfwidth;
1628 e.heuristic = rows[n].heuristic;
1629 e.level = rows[n].level;
1630 e.method = rows[n].method;
1631 e.samples = rows[n].samples;
1632 out.push_back(e);
1633 }
1634 last_perct_method_ = ldes::ldes_perct_method(ldes::ldes_replications(ldes_options(opts_)), method);
1635 return out;
1636}
1637
1638std::vector<PerctRespTCI> SolverLDES::perct_respt(const std::vector<double>& percentiles,
1639 const std::string& job_class, const std::string& method) {
1641 for (std::size_t c = 0; c < sn.nclasses; ++c)
1642 if (sn.classes[c].name == job_class) return perct_respt(percentiles, static_cast<long>(c), method);
1643 throw InputError("SolverLDES::perct_respt: no job class named '" + job_class + "'");
1644}
1645
1648 const std::size_t M = sn.nstations, K = sn.nclasses;
1650 if (aux.get_name() == "CTMC") {
1651 P = ldes::warm_start_placement_from_ctmc(sn, ctmc_options(aux.options()));
1652 } else {
1653 // The table drops all-zero rows, so the means are matched back by name.
1654 const AvgTable& t = aux.avg_table();
1655 Matrix<double> QN(M, K, 0.0);
1656 for (std::size_t row = 0; row < t.QLen.size(); ++row)
1657 for (std::size_t i = 0; i < M; ++i)
1658 for (std::size_t c = 0; c < K; ++c)
1659 if (sn.stations[i].name == t.Station[row] && sn.classes[c].name == t.JobClass[row])
1660 QN(i, c) = t.QLen[row];
1662 }
1663 // `initFromMarginal`: every state of each station with that many jobs, the first one
1664 // weighed, declared as the model initial state every state-driven solver starts from.
1665 for (std::size_t i = 1; i <= M; ++i) {
1666 if (sn.stations[i - 1].nodetype == lang::NodeType::Source) continue;
1667 std::vector<std::size_t> n(K, 0), ph(K, 1);
1668 for (std::size_t c = 0; c < K; ++c) {
1669 n[c] = static_cast<std::size_t>(P(i - 1, c) + 0.5);
1670 ph[c] = sn.phases_of(i, c + 1);
1671 }
1672 const std::vector<std::vector<double> > rows = qn::from_marginal(sn, i, n, ph);
1673 if (rows.empty())
1674 throw InputError("SolverLDES::init_from_solver: station '" + sn.stations[i - 1].name +
1675 "' admits no state with the warm-start placement");
1676 Matrix<double> space(rows.size(), rows[0].size());
1677 for (std::size_t r = 0; r < rows.size(); ++r)
1678 for (std::size_t c = 0; c < rows[r].size(); ++c) space(r, c) = rows[r][c];
1679 std::vector<double> prior(rows.size(), 0.0);
1680 prior[0] = 1.0;
1681 model_->set_state_prior(sn.node_of_station(i), space, prior);
1682 }
1683 opts_.tranfilter = "fixed";
1684 opts_.warmupfrac = 0.0;
1685 reset();
1686 jobs_ready_ = false;
1687 return *this;
1688}
1689
1691 if (jobs.rows() == 0 || jobs.cols() < 7)
1692 throw InputError("SolverLDES::init_from_jobs needs one row per job with the columns [station, class, "
1693 "remaining, elapsed, qage, sage, order, id], id optional");
1694 opts_.init_jobs = jobs;
1695 opts_.track_jobs = true;
1696 reset();
1697 jobs_ready_ = false;
1698 return *this;
1699}
1700
1701void SolverLDES::run_tracked() {
1702 if (jobs_ready_ && opts_.cache) return;
1704 ldes::LdesOptions opt = ldes_options(opts_);
1705 opt.track_jobs = true;
1707 final_jobs_ = r.finalJobs;
1708 job_departures_ = r.jobDepartures;
1709 jobs_ready_ = true;
1710}
1711
1713 run_tracked();
1714 return final_jobs_;
1715}
1716
1718 run_tracked();
1719 return job_departures_;
1720}
1721
1722namespace {
1723
1724/** An engine sample as the facade's `SamplePath`: labelled columns, 1-based events. */
1725SamplePath ldes_sample_path(const qn::NetworkStruct<double>& sn, const ldes::LdesSample& s) {
1726 SamplePath out;
1727 out.aggregate = s.aggregate;
1728 out.t = s.t;
1729 for (std::size_t b = 0; b < s.block.size(); ++b) {
1730 const std::size_t ind = s.nodes[b];
1731 const std::string& nm = sn.nodes[ind - 1].name;
1732 for (std::size_t j = 0; j < s.block[b].cols(); ++j) {
1733 out.column_node.push_back(ind);
1734 out.label.push_back(s.aggregate && j < sn.nclasses
1735 ? nm + "/" + sn.classes[j].name
1736 : nm + "/" + std::to_string(j + 1));
1737 }
1738 }
1739 out.state.assign(s.t.size(), std::vector<double>(s.state.cols(), 0.0));
1740 for (std::size_t i = 0; i < s.t.size() && i < s.state.rows(); ++i)
1741 for (std::size_t j = 0; j < s.state.cols(); ++j) out.state[i][j] = s.state(i, j);
1742 for (std::size_t k = 0; k < s.event.rows(); ++k) {
1743 std::vector<double> e(6);
1744 for (std::size_t j = 0; j < 6; ++j) e[j] = s.event(k, j);
1745 e[1] += 1.0; // node, 0-based on the wire
1746 e[3] += 1.0; // class
1747 out.event.push_back(e);
1748 }
1749 return out;
1750}
1751
1752} // namespace
1753
1754SamplePath SolverLDES::sample(std::size_t node, std::size_t events) {
1756 return ldes_sample_path(sn, ldes::ldes_sample(sn, ldes_options(opts_), node, events));
1757}
1758
1759SamplePath SolverLDES::sample_aggr(std::size_t node, std::size_t events) {
1761 return ldes_sample_path(sn, ldes::ldes_sample_aggr(sn, ldes_options(opts_), node, events));
1762}
1763
1766 return ldes_sample_path(sn, ldes::ldes_sample_sys(sn, ldes_options(opts_), events));
1767}
1768
1771 return ldes_sample_path(sn, ldes::ldes_sample_sys_aggr(sn, ldes_options(opts_), events));
1772}
1773
1774namespace {
1775
1776/** One `--export-histogram` run of the facade's model with its options; the histogram must be present. */
1777ldes::LdesResult ldes_histogram_run(const qn::NetworkStruct<double>& sn, const SolverOptions& opts,
1778 const char* who, bool trajectory = false) {
1779 std::vector<std::string> flags(1, "--export-histogram");
1780 if (trajectory) flags.push_back("--trajectory");
1781 const ldes::LdesResult r = ldes::solver_ldes(sn, ldes_options(opts), flags);
1782 if (r.histogram_space.rows() == 0 || r.histogram_time.rows() == 0)
1783 throw UnsupportedError(ErrorKind{"Analysis"},
1784 std::string("SolverLDES::") + who + ": the engine returned no state histogram, so no "
1785 "state probability can be read from this run");
1786 return r;
1787}
1788
1789/** The 1-based station of a 1-based node, or `LINE:input:Argument` when it is none. */
1790std::size_t ldes_station_of(const qn::NetworkStruct<double>& sn, std::size_t node, const char* who) {
1791 if (node == 0 || node > sn.nodes.size())
1792 throw InputError(ErrorKind{"Argument"}, std::string("SolverLDES::") + who + ": node index " +
1793 std::to_string(node) + " is out of range");
1794 const std::size_t ist = sn.nodes[node - 1].station;
1795 if (ist == 0)
1796 throw InputError(ErrorKind{"Argument"},
1797 std::string("SolverLDES::") + who + ": node " + sn.nodes[node - 1].name +
1798 " is not a station; the LDES state histogram records station queue lengths only");
1799 return ist;
1800}
1801
1802/** The current (declared, else default) per-class counts of one 1-based station. */
1803std::vector<double> ldes_current_counts(const qn::NetworkStruct<double>& sn, std::size_t ist) {
1805 std::vector<double> c(sn.nclasses, 0.0);
1806 for (std::size_t k = 0; k < sn.nclasses && ist - 1 < nir.rows() && k < nir.cols(); ++k)
1807 c[k] = nir(ist - 1, k);
1808 return c;
1809}
1810
1811/** A reward's value at one aggregate histogram row. */
1812double ldes_reward_at(const qn::NetworkStruct<double>& sn, std::size_t l, const Matrix<double>& space,
1813 std::size_t s) {
1814 std::vector<double> row(space.cols());
1815 for (std::size_t c = 0; c < space.cols(); ++c) row[c] = space(s, c);
1816 return sn.reward[l].fn(row);
1817}
1818
1819} // namespace
1820
1821double SolverLDES::prob(std::size_t node, const Matrix<double>& state) {
1823 const std::size_t ist = ldes_station_of(sn, node, "prob");
1824 std::vector<std::vector<double> > targets;
1825 if (state.rows() == 0 || state.cols() == 0) {
1826 targets.push_back(ldes_current_counts(sn, ist));
1827 } else {
1828 // State.toMarginal on each detailed row: the histogram resolves per-class counts only.
1829 const std::size_t K = sn.nclasses;
1830 std::vector<std::size_t> ph(K, 1), shift(K, 0);
1831 std::size_t w = 0;
1832 for (std::size_t k = 0; k < K; ++k) {
1833 ph[k] = sn.phasessz_of(ist, k + 1);
1834 shift[k] = w;
1835 w += ph[k];
1836 }
1837 const std::size_t nvars = sn.nvars_of(sn.node_of_station(ist));
1838 for (std::size_t r = 0; r < state.rows(); ++r) {
1839 std::vector<double> row(state.cols());
1840 for (std::size_t c = 0; c < state.cols(); ++c) row[c] = state(r, c);
1841 const qn::Marginal<double> m = qn::to_marginal(sn, ist, row, ph, shift, nvars);
1842 targets.push_back(m.nir);
1843 }
1844 }
1845 const ldes::LdesResult res = ldes_histogram_run(sn, opts_, "prob");
1846 double p = 0.0;
1847 for (std::size_t t = 0; t < targets.size(); ++t) {
1848 std::vector<ldes::LdesStateQuery> q(1);
1849 q[0].station = ist;
1850 q[0].counts = targets[t];
1851 p += ldes::ldes_prob_from_histogram(res, sn.nclasses, q);
1852 }
1853 return p;
1854}
1855
1856double SolverLDES::prob_aggr(std::size_t node, const std::vector<double>& counts) {
1858 const std::size_t ist = ldes_station_of(sn, node, "prob_aggr");
1859 std::vector<ldes::LdesStateQuery> q(1);
1860 q[0].station = ist;
1861 q[0].counts = counts.empty() ? ldes_current_counts(sn, ist) : counts;
1862 const ldes::LdesResult res = ldes_histogram_run(sn, opts_, "prob_aggr");
1863 return ldes::ldes_prob_from_histogram(res, sn.nclasses, q);
1864}
1865
1868 std::vector<ldes::LdesStateQuery> q;
1869 for (std::size_t ist = 1; ist <= sn.nstations; ++ist) {
1870 if (sn.stations[ist - 1].nodetype == lang::NodeType::Source) continue;
1872 e.station = ist;
1873 e.counts = ldes_current_counts(sn, ist);
1874 q.push_back(e);
1875 }
1876 if (q.empty()) return 0.0;
1877 const ldes::LdesResult res = ldes_histogram_run(sn, opts_, "prob_sys");
1878 return ldes::ldes_prob_from_histogram(res, sn.nclasses, q);
1879}
1880
1882
1883std::vector<std::vector<CdfCurve> > SolverLDES::tran_cdf_respt() { return cdf_respt(); }
1884
1885std::vector<std::vector<CdfCurve> > SolverLDES::tran_cdf_passt() { return cdf_respt(); }
1886
1889 if (!(opts_.timespan_end > 0.0) || !std::isfinite(opts_.timespan_end))
1890 throw InputError(ErrorKind{"Option"},
1891 "SolverLDES::tran_avg needs a finite positive options.timespan_end: a transient mean "
1892 "over an unstated horizon is not a quantity");
1893 ldes::LdesOptions o = ldes_options(opts_);
1894 o.has_timespan = true;
1895 o.t0 = 0.0;
1896 o.t1 = opts_.timespan_end;
1897 const ldes::LdesResult r = ldes::solver_ldes(sn, o, std::vector<std::string>(1, "--trajectory"));
1898 if (r.t.empty() || r.QNt.empty())
1899 throw ExternalError(ErrorKind{"LDES"},
1900 "SolverLDES::tran_avg: the engine ran but recorded no trajectory over [0, " +
1901 ldes::detail::shortest(opts_.timespan_end) + "]");
1902 TranAvg out;
1903 for (std::size_t i = 0; i < sn.nstations; ++i)
1904 for (std::size_t c = 0; c < sn.nclasses; ++c)
1905 out.label.push_back(sn.stations[i].name + "/" + sn.classes[c].name);
1906 out.t = r.t;
1907 // QNt is indexed by STATION (BUG-95), each series (npoints x 2) as [value, time].
1908 for (std::size_t g = 0; g < r.t.size(); ++g) {
1909 std::vector<double> row;
1910 for (std::size_t i = 0; i < sn.nstations; ++i)
1911 for (std::size_t c = 0; c < sn.nclasses; ++c)
1912 row.push_back(i < r.QNt.size() && c < r.QNt[i].size() && g < r.QNt[i][c].rows()
1913 ? r.QNt[i][c](g, 0)
1914 : 0.0);
1915 out.QNt.push_back(row);
1916 }
1917 return out;
1918}
1919
1920std::vector<double> SolverLDES::avg_reward(std::vector<std::string>* names) {
1922 if (sn.reward.empty())
1923 throw InputError(ErrorKind{"Argument"},
1924 "No rewards defined. Use set_reward(name, fn) before calling avg_reward.");
1925 std::vector<double> E(sn.reward.size(), 0.0);
1926 if (names) {
1927 names->clear();
1928 for (std::size_t l = 0; l < sn.reward.size(); ++l) names->push_back(sn.reward[l].name);
1929 }
1930 std::vector<std::string> flags(1, "--export-histogram");
1931 const ldes::LdesResult r = ldes::solver_ldes(sn, ldes_options(opts_), flags);
1932 const Matrix<double>& space = r.histogram_space;
1933 const Matrix<double>& tm = r.histogram_time;
1934 double total = 0.0;
1935 for (std::size_t s = 0; s < tm.rows(); ++s) total += tm(s, 0);
1936 // No histogram, or no residence time: zeros, as the reference returns.
1937 if (space.rows() == 0 || tm.rows() == 0 || !(total > 0.0)) return E;
1938 for (std::size_t l = 0; l < sn.reward.size(); ++l)
1939 for (std::size_t s = 0; s < space.rows() && s < tm.rows(); ++s)
1940 E[l] += (tm(s, 0) / total) * ldes_reward_at(sn, l, space, s);
1941 return E;
1942}
1943
1944TranReward SolverLDES::tran_reward(const std::string& name) {
1946 if (sn.reward.empty())
1947 throw InputError(ErrorKind{"Argument"},
1948 "No rewards defined. Use set_reward(name, fn) before calling tran_reward.");
1949 std::vector<std::size_t> which;
1950 for (std::size_t l = 0; l < sn.reward.size(); ++l)
1951 if (name.empty() || sn.reward[l].name == name) {
1952 which.push_back(l);
1953 if (!name.empty()) break;
1954 }
1955 if (which.empty())
1956 throw InputError(ErrorKind{"Argument"}, "Reward '" + name + "' not found.");
1957 std::vector<std::string> flags(1, "--export-histogram");
1958 flags.push_back("--trajectory");
1959 const ldes::LdesResult r = ldes::solver_ldes(sn, ldes_options(opts_), flags);
1960 TranReward out;
1961 for (std::size_t s = 0; s < r.traj_time.rows(); ++s)
1962 for (std::size_t c = 0; c < r.traj_time.cols(); ++c) out.t.push_back(r.traj_time(s, c));
1963 const std::size_t np = r.traj_space.rows();
1964 for (std::size_t w = 0; w < which.size(); ++w) {
1965 out.names.push_back(sn.reward[which[w]].name);
1966 std::vector<double> m(np, 0.0);
1967 for (std::size_t s = 0; s < np; ++s) m[s] = ldes_reward_at(sn, which[w], r.traj_space, s);
1968 out.metric.push_back(m);
1969 }
1970 return out;
1971}
1972
1973BusyPeriodTable SolverLDES::avg_busy_period(const std::vector<std::size_t>& stations, long job_class,
1974 const std::vector<std::size_t>& orders) {
1976 std::vector<std::size_t> ord = orders.empty() ? std::vector<std::size_t>(1, 1) : orders;
1977 std::size_t nmax = 0;
1978 for (std::size_t j = 0; j < ord.size(); ++j) {
1979 if (ord[j] == 0)
1980 throw InputError(ErrorKind{"Argument"},
1981 "SolverLDES::avg_busy_period: busy period orders are 1-based");
1982 nmax = std::max(nmax, ord[j]);
1983 }
1984 for (std::size_t t = 0; t < stations.size(); ++t)
1985 if (stations[t] == 0 || stations[t] > sn.nstations)
1986 throw InputError(ErrorKind{"Argument"}, "SolverLDES::avg_busy_period: station index " +
1987 std::to_string(stations[t]) + " is out of range");
1988 if (job_class >= static_cast<long>(sn.nclasses))
1989 throw InputError(ErrorKind{"Argument"}, "SolverLDES::avg_busy_period: job class index " +
1990 std::to_string(job_class) + " is out of range");
1991 const long cls = job_class < 0 ? -1 : job_class;
1992
1993 ldes::LdesOptions o = ldes_options(opts_);
1994 o.busy_period_orders = static_cast<int>(nmax);
1995 if (stations.size() > 1) {
1996 std::vector<std::size_t> sub;
1997 for (std::size_t t = 0; t < stations.size(); ++t) sub.push_back(stations[t] - 1);
1998 o.busy_period_subnets.push_back(sub);
1999 }
2001 if (r.busy_periods.empty())
2002 throw ExternalError(ErrorKind{"LDES"}, "The LDES engine returned no busy period measurement.");
2003
2004 const double nan = std::numeric_limits<double>::quiet_NaN();
2005 auto fill_row = [&](BusyPeriodTable& out, std::size_t row, const ldes::LdesResult::BusyPeriodTarget& tg,
2006 const std::vector<std::size_t>& cols) {
2007 for (std::size_t j = 0; j < cols.size(); ++j) {
2008 const std::size_t k = cols[j] - 1;
2009 const double cnt = k < tg.count.size() ? tg.count[k] : 0.0;
2010 out.count(row, j) = cnt;
2011 out.mean(row, j) = cnt == 0.0 || k >= tg.mean.size() ? nan : tg.mean[k];
2012 }
2013 };
2014
2015 BusyPeriodTable out;
2016 if (stations.empty()) {
2017 // Every target, at every order 1..max(n), as the reference's no-station form returns.
2018 for (std::size_t j = 1; j <= nmax; ++j) out.orders.push_back(j);
2019 out.mean = Matrix<double>(r.busy_periods.size(), nmax);
2020 out.count = Matrix<double>(r.busy_periods.size(), nmax);
2021 for (std::size_t t = 0; t < r.busy_periods.size(); ++t) {
2022 out.names.push_back(r.busy_periods[t].name);
2023 fill_row(out, t, r.busy_periods[t], out.orders);
2024 }
2025 return out;
2026 }
2027 std::vector<std::size_t> wanted;
2028 for (std::size_t t = 0; t < stations.size(); ++t) wanted.push_back(stations[t] - 1);
2029 std::sort(wanted.begin(), wanted.end());
2030 for (std::size_t t = 0; t < r.busy_periods.size(); ++t) {
2032 std::vector<std::size_t> st = tg.stations;
2033 std::sort(st.begin(), st.end());
2034 if (st == wanted && static_cast<long>(tg.job_class) == cls) {
2035 out.names.push_back(tg.name);
2036 out.orders = ord;
2037 out.mean = Matrix<double>(1, ord.size());
2038 out.count = Matrix<double>(1, ord.size());
2039 fill_row(out, 0, tg, ord);
2040 return out;
2041 }
2042 }
2043 throw InputError(ErrorKind{"Argument"},
2044 "No busy period target matches the requested stations and class.");
2045}
2046
2052
2053std::vector<CdfCurve> SolverLDES::cdf_respt_ln(const lqn::LqnStruct<double>& lsn, const SolverOptions& o) {
2054 const ldes::engine::LnResult r = ldes::ldes_ln_engine_solve(lsn, ldes_options(o));
2055 const std::vector<ldes::engine::LnEntryCdf> c = ldes::engine::ldes_ln_cdf_respt(r, lsn.nentries);
2056 std::vector<CdfCurve> out(c.size());
2057 for (std::size_t e = 0; e < c.size(); ++e) {
2058 out[e].F = c[e].F;
2059 out[e].t = c[e].t;
2060 }
2061 return out;
2062}
2063
2064std::vector<std::string> SolverLDES::feature_set() {
2065 const std::vector<qn::Feature> fs = qn::ldes_feature_set("default").list();
2066 std::vector<std::string> out;
2067 for (std::size_t i = 0; i < fs.size(); ++i) out.push_back(qn::feature_name(fs[i]));
2068 return out;
2069}
2070
2071std::vector<std::string> SolverLDES::ln_feature_set() {
2072 // The mirror of MATLAB's and the JAR's getLNFeatureSet, in their declaration order.
2073 using qn::Feature;
2074 static const Feature fs[] = {
2075 Feature::Host, Feature::Processor, Feature::Task, Feature::Entry, Feature::Activity,
2076 Feature::SyncCall, Feature::AsyncCall,
2077 Feature::ActivityPrecedence_PRE_SEQ, Feature::ActivityPrecedence_POST_SEQ,
2078 Feature::ActivityPrecedence_PRE_AND, Feature::ActivityPrecedence_POST_AND,
2079 Feature::ActivityPrecedence_PRE_OR, Feature::ActivityPrecedence_POST_OR,
2080 Feature::SchedStrategy_REF, Feature::SchedStrategy_FCFS, Feature::SchedStrategy_PS,
2081 Feature::SchedStrategy_INF, Feature::SchedStrategy_LCFS, Feature::SchedStrategy_SIRO,
2082 Feature::SchedStrategy_HOL,
2083 Feature::SetupDelayOff, Feature::HeteroServers,
2084 Feature::CacheTask, Feature::ItemEntry, Feature::Cache, Feature::ActivityPrecedence_POST_CACHE,
2085 Feature::ReplacementStrategy_RR, Feature::ReplacementStrategy_FIFO,
2086 Feature::ReplacementStrategy_SFIFO, Feature::ReplacementStrategy_LRU,
2087 Feature::ReplacementStrategy_HLRU, Feature::ReplacementStrategy_CLIMB,
2088 Feature::ReplacementStrategy_QLRU,
2089 Feature::Exp, Feature::Erlang, Feature::HyperExp, Feature::PH, Feature::APH, Feature::Coxian,
2090 Feature::Cox2, Feature::Det, Feature::Uniform, Feature::Gamma, Feature::Lognormal,
2091 Feature::Weibull, Feature::LogLogistic, Feature::MassAtOrigin, Feature::Pareto,
2092 Feature::Immediate,
2093 Feature::Geometric, Feature::Bernoulli, Feature::Binomial, Feature::Poisson,
2094 Feature::ME,
2095 Feature::MAP, Feature::MMPP2, Feature::RAP,
2096 Feature::Replayer, Feature::Trace};
2097 std::vector<std::string> out;
2098 for (std::size_t i = 0; i < sizeof(fs) / sizeof(*fs); ++i) out.push_back(qn::feature_name(fs[i]));
2099 return out;
2100}
2101
2107
2109
2110// ---------------------------------------------------------------------------
2111// SolverJMT
2112// ---------------------------------------------------------------------------
2113
2114std::vector<std::vector<CdfCurve> > SolverJMT::cdf_respt() {
2116 std::vector<std::vector<CdfCurve> > out(sn.nstations, std::vector<CdfCurve>(sn.nclasses));
2117 // `true` is the getCdfRespT contract: the model is first solved for its
2118 // steady-state queue lengths and the logged run starts preloaded at their
2119 // rounded values, which is what makes the seeded curve comparable to the
2120 // reference's for the same seed.
2121 const std::map<std::pair<std::size_t, std::size_t>, std::vector<std::pair<double, double> > >
2122 rd = jmt::jmt_get_cdf_resp_t(sn, jmt_options(opts_), true);
2123 for (std::map<std::pair<std::size_t, std::size_t>,
2124 std::vector<std::pair<double, double> > >::const_iterator it = rd.begin();
2125 it != rd.end(); ++it) {
2126 const std::size_t i = it->first.first, c = it->first.second;
2127 if (i == 0 || i > out.size() || c == 0 || c > sn.nclasses) continue;
2128 // THE PAIRS ARE (F, X), as `ecdf` returns them, and the curve stores
2129 // the two apart: reading them the other way round would report a
2130 // probability as a time.
2131 for (std::size_t j = 0; j < it->second.size(); ++j) {
2132 out[i - 1][c - 1].F.push_back(it->second[j].first);
2133 out[i - 1][c - 1].t.push_back(it->second[j].second);
2134 }
2135 }
2136 return out;
2137}
2138
2142 TranAvg out;
2143 for (std::size_t i = 0; i < sn.nstations; ++i)
2144 for (std::size_t c = 0; c < sn.nclasses; ++c)
2145 out.label.push_back(sn.stations[i].name + "/" + sn.classes[c].name);
2146 out.t = r.t;
2147 for (std::size_t g = 0; g < r.t.size(); ++g) {
2148 std::vector<double> row;
2149 for (std::size_t i = 0; i < sn.nstations; ++i)
2150 for (std::size_t c = 0; c < sn.nclasses; ++c)
2151 row.push_back(i < r.QNt.size() && c < r.QNt[i].size() && g < r.QNt[i][c].size()
2152 ? r.QNt[i][c][g]
2153 : 0.0);
2154 out.QNt.push_back(row);
2155 }
2156 return out;
2157}
2158
2159double SolverJMT::prob_aggr(std::size_t node, const std::vector<double>& state) {
2161 if (node == 0 || node > sn.nodes.size()) throw InputError("prob_aggr: node index out of range");
2162 const std::size_t ist = sn.nodes[node - 1].station;
2163 if (ist == 0) throw InputError("prob_aggr: the node is not a station");
2164 const jmt::JmtProbAggr r = jmt::jmt_prob_aggr(sn, jmt_options(opts_), ist, state);
2165 return r.station[ist - 1];
2166}
2167
2168SamplePath SolverJMT::sample(std::size_t events, std::size_t node) {
2170 const jmt::JmtOptions opt = jmt_options(opts_);
2171 SamplePath out;
2172 if (node) {
2173 if (node > sn.nodes.size() || sn.nodes[node - 1].station == 0)
2174 throw InputError("sample: the node is not a station, so nothing is logged for it");
2175 const jmt::JmtNodeTrace<double> tr = jmt::jmt_sample_aggr(sn, node, events, opt);
2176 for (std::size_t c = 0; c < sn.nclasses; ++c) out.label.push_back(sn.classes[c].name);
2177 out.t = tr.t;
2178 out.state = tr.qlen;
2179 return out;
2180 }
2182 for (std::size_t i = 0; i < sn.nstations; ++i)
2183 for (std::size_t c = 0; c < sn.nclasses; ++c)
2184 out.label.push_back(sn.stations[i].name + "/" + sn.classes[c].name);
2185 out.t = tr.t;
2186 for (std::size_t g = 0; g < tr.t.size(); ++g) {
2187 std::vector<double> row;
2188 for (std::size_t i = 0; i < sn.nstations; ++i)
2189 for (std::size_t c = 0; c < sn.nclasses; ++c)
2190 row.push_back(i < tr.state.size() && g < tr.state[i].size() &&
2191 c < tr.state[i][g].size()
2192 ? tr.state[i][g][c]
2193 : 0.0);
2194 out.state.push_back(row);
2195 }
2196 return out;
2197}
2198
2199// ---------------------------------------------------------------------------
2200// SolverBA
2201// ---------------------------------------------------------------------------
2202
2206 if (!opts_.method.empty()) opt.method = opts_.method;
2207 opt.level = opts_.level;
2209 BoundsTable t;
2210 t.method = opt.method;
2211 for (std::size_t i = 0; i < sn.nstations; ++i)
2212 for (std::size_t c = 0; c < sn.nclasses; ++c) {
2213 if (i < b.keep.size() && c < b.keep[i].size() && !b.keep[i][c]) continue;
2214 t.Station.push_back(sn.stations[i].name);
2215 t.JobClass.push_back(sn.classes[c].name);
2216 t.Qlower.push_back(b.Qlower(i, c));
2217 t.Qupper.push_back(b.Qupper(i, c));
2218 t.Tlower.push_back(b.Tlower(i, c));
2219 t.Tupper.push_back(b.Tupper(i, c));
2220 }
2221 return t;
2222}
2223
2224// ---------------------------------------------------------------------------
2225// SolverAUTO
2226// ---------------------------------------------------------------------------
2227
2228namespace {
2229
2230/** A ranking slot's facade name: "fld" is SolverFLD, the rest are their upper-case selves. */
2231std::string facade_name_of_slot(autosolver::AutoSolver s) {
2232 std::string name = autosolver::auto_solver_name(s);
2233 std::transform(name.begin(), name.end(), name.begin(), ::toupper);
2234 return name;
2235}
2236
2237/** The facade name's method family, the inverse of `facade_name_of_family`. */
2238std::string family_of_facade_name(const std::string& tag) {
2239 std::string fam = tag;
2240 std::transform(fam.begin(), fam.end(), fam.begin(), ::tolower);
2241 return fam;
2242}
2243
2244/**
2245 * Who answers `getter` under the configured method, in `delegate.m`'s order. A family names its
2246 * engine outright and is the whole list; an intent names a ranking, whose first slot alone is asked
2247 * with the method the ranking gated on ('exact' under the exact intent).
2248 */
2249struct AutoDelegatePlan {
2250 bool family = false;
2251 std::string family_name;
2252 std::vector<std::string> tags;
2253 std::string first_method;
2254};
2255
2256AutoDelegatePlan auto_delegate_plan(const qn::NetworkStruct<double>& sn, const std::string& method,
2257 const std::string& getter) {
2258 AutoDelegatePlan plan;
2260 if (!tok.is_intent) {
2261 plan.family = true;
2262 plan.family_name = tok.family;
2263 plan.tags.push_back(facade_name_of_family(tok.family));
2264 plan.first_method = tok.submethod;
2265 return plan;
2266 }
2268 const std::vector<autosolver::AutoSolver> order = autosolver::auto_proposed_solvers(sn, getter, tok.mode);
2269 for (std::size_t i = 0; i < order.size(); ++i) plan.tags.push_back(facade_name_of_slot(order[i]));
2270 plan.first_method = c.method.empty() ? std::string("default") : c.method;
2271 return plan;
2272}
2273
2274/**
2275 * `delegate.m` for a getter the facade answers on some solvers only. `answers` names the facades
2276 * that expose the call; a proposed solver outside it is passed over, since this port has nothing to
2277 * ask it. Input and internal errors propagate; any other moves on to the next candidate, and when
2278 * all fail the LAST error is reported under its own category, as the reference does.
2279 */
2280template <class R, class Call>
2281R auto_delegate(Network& model, const SolverOptions& o, const std::string& getter,
2282 const std::set<std::string>& answers, Call call, std::string& last) {
2283 const qn::NetworkStruct<double>& sn = model.get_struct();
2284 const AutoDelegatePlan plan = auto_delegate_plan(sn, o.method, getter);
2285 std::string last_error, last_cat, last_kind, proposed;
2286 bool tried = false;
2287 for (std::size_t i = 0; i < plan.tags.size(); ++i) {
2288 const std::string& tag = plan.tags[i];
2289 proposed += (proposed.empty() ? "" : ", ") + tag;
2290 if (!answers.count(tag)) continue;
2291 tried = true;
2292 SolverOptions oo = o;
2293 oo.method = i == 0 ? plan.first_method : std::string("default");
2294 try {
2295 R r = call(tag, model, oo);
2296 last = tag;
2297 return r;
2298 } catch (const Error& e) {
2299 const std::string cat = e.category();
2300 if (cat == "input" || cat == "internal") throw;
2301 if (cat == "numerical" && e.kind() == "Timeout") throw; // final, as in solve_auto
2302 last_error = tag + ": " + e.what();
2303 last_cat = cat;
2304 last_kind = e.kind();
2305 }
2306 }
2307 if (!tried) {
2308 if (plan.family)
2309 throw UnsupportedError(ErrorKind{"Method"},
2310 "SolverAUTO: method family '" + plan.family_name + "' does not answer " + getter +
2311 " in this port");
2312 throw UnsupportedError(ErrorKind{"Method"},
2313 "SolverAUTO: none of the solvers proposed for " + getter + " (" + proposed +
2314 ") answers it in this port");
2315 }
2316 const std::string msg = "SolverAUTO: All candidate solvers failed to execute method '" + getter +
2317 "'. Last error: " + last_error;
2318 if (last_cat == "numerical") throw NumericError(ErrorKind{last_kind}, msg);
2319 if (last_cat == "external") throw ExternalError(ErrorKind{last_kind}, msg);
2320 throw UnsupportedError(ErrorKind{last_kind.empty() ? std::string("Solver") : last_kind}, msg);
2321}
2322
2323/** True for a facade whose answer is an estimate from a simulated run under this method. */
2324bool facade_is_stochastic(const std::string& tag, const std::string& method) {
2325 if (tag == "SSA" || tag == "LDES") return true;
2326 if (tag == "JMT") return method.compare(0, 4, "jmva") != 0;
2327 return false;
2328}
2329
2330} // namespace
2331
2333 // The constructor resolves the method as the reference's does, so an unknown name fails here
2334 // and not at the first getter. A bare method name needs the model to resolve, and is checked
2335 // against it only when the model-free resolution cannot place it.
2336 try {
2338 } catch (const InputError&) {
2340 }
2341}
2342
2343SolverAUTO::SolverAUTO(Network& m, const std::string& method)
2344 : SolverAUTO(m, SolverOptions().set_method(method)) {}
2345
2347 if (!last_.empty()) return last_;
2348 if (solved_) return table_.solver;
2349 try {
2350 return choose_solver("getAvg");
2351 } catch (const Error&) {
2352 // No feasible delegate: the caller learns this from the analysis itself.
2353 return std::string();
2354 }
2355}
2356
2358 const std::string tag = selected_solver_name();
2359 return tag.empty() ? std::string() : family_of_facade_name(tag);
2360}
2361
2362std::vector<std::string> SolverAUTO::candidate_solver_names() const {
2363 std::vector<std::string> out;
2364 const std::vector<autosolver::AutoSolver> c = autosolver::auto_candidates(model_->get_struct());
2365 for (std::size_t i = 0; i < c.size(); ++i) out.push_back(facade_name_of_slot(c[i]));
2366 return out;
2367}
2368
2369std::string SolverAUTO::choose_solver(const std::string& getter) const {
2370 return auto_delegate_plan(model_->get_struct(), opts_.method, getter).tags.front();
2371}
2372
2373std::vector<std::string> SolverAUTO::proposed_solver_names(const std::string& getter) const {
2374 return auto_delegate_plan(model_->get_struct(), opts_.method, getter).tags;
2375}
2376
2378 if (!last_.empty()) return facade_is_stochastic(last_, std::string());
2379 if (solved_) return facade_is_stochastic(table_.solver, table_.method);
2380 const std::vector<std::string> c = candidate_solver_names();
2381 for (std::size_t i = 0; i < c.size(); ++i)
2382 if (facade_is_stochastic(c[i], std::string())) return true;
2383 return false;
2384}
2385
2386std::vector<std::string> SolverAUTO::list_all_methods() const {
2387 std::vector<std::string> out = selection_intents();
2388 out.push_back("auto");
2389 const std::vector<std::string> fams = family_names();
2390 for (std::size_t f = 0; f < fams.size(); ++f) {
2391 // A family contributes only when it can be instantiated on a Network here: ln, env and uq
2392 // take another model class, ldes needs its engine and lqns its qnsolver binary.
2393 std::string tag;
2394 try {
2395 tag = facade_name_of_family(fams[f]);
2396 } catch (const Error&) {
2397 continue;
2398 }
2399 if (tag == "LQNS" && !lqns::qnsolver_is_available()) continue;
2400 out.push_back(fams[f]);
2401 std::string key = fams[f];
2402 std::transform(key.begin(), key.end(), key.begin(), ::toupper);
2403 const std::vector<std::string> declared = method_registry::methods(key);
2404 for (std::size_t m = 0; m < declared.size(); ++m) out.push_back(fams[f] + "." + declared[m]);
2405 }
2406 std::sort(out.begin(), out.end());
2407 out.erase(std::unique(out.begin(), out.end()), out.end());
2408 return out;
2409}
2410
2411std::vector<AutoCandidate> SolverAUTO::find_solver(const std::string& metric, bool show_all) const {
2412 const std::vector<autosolver::SolverCandidate> rows =
2413 autosolver::auto_find_solver(model_->get_struct(), metric, show_all);
2414 std::vector<AutoCandidate> out;
2415 for (std::size_t i = 0; i < rows.size(); ++i) {
2416 AutoCandidate c;
2417 c.solver = rows[i].solver;
2418 c.method = rows[i].method;
2419 c.runnable = rows[i].runnable;
2420 c.method_class = rows[i].method_class;
2421 c.metrics = rows[i].metrics;
2422 c.reason = rows[i].reason;
2423 out.push_back(c);
2424 }
2425 return out;
2426}
2427
2428std::vector<std::vector<CdfCurve> > SolverAUTO::cdf_respt() {
2429 std::set<std::string> answers;
2430 answers.insert("CTMC");
2431 answers.insert("FLD");
2432 answers.insert("LDES");
2433 answers.insert("JMT");
2434 return auto_delegate<std::vector<std::vector<CdfCurve> > >(
2435 *model_, opts_, "getCdfRespT", answers,
2436 [](const std::string& tag, Network& m, const SolverOptions& oo) {
2437 if (tag == "CTMC") return SolverCTMC(m, oo).cdf_respt();
2438 if (tag == "FLD") return SolverFLD(m, oo).cdf_respt();
2439 if (tag == "LDES") return SolverLDES(m, oo).cdf_respt();
2440 return SolverJMT(m, oo).cdf_respt();
2441 },
2442 last_);
2443}
2444
2446 std::set<std::string> answers;
2447 answers.insert("FLD");
2448 answers.insert("JMT");
2449 return auto_delegate<TranAvg>(
2450 *model_, opts_, "getTranAvg", answers,
2451 [](const std::string& tag, Network& m, const SolverOptions& oo) {
2452 if (tag == "FLD") return SolverFLD(m, oo).tran_avg();
2453 return SolverJMT(m, oo).tran_avg();
2454 },
2455 last_);
2456}
2457
2458double SolverAUTO::prob_aggr(std::size_t node, const std::vector<double>& state) {
2459 std::set<std::string> answers;
2460 answers.insert("CTMC");
2461 answers.insert("JMT");
2462 return auto_delegate<double>(
2463 *model_, opts_, "getProbAggr", answers,
2464 [node, &state](const std::string& tag, Network& m, const SolverOptions& oo) {
2465 if (tag == "CTMC") return SolverCTMC(m, oo).prob_aggr(node, state);
2466 return SolverJMT(m, oo).prob_aggr(node, state);
2467 },
2468 last_);
2469}
2470
2471namespace {
2472
2473/**
2474 * The options a `ctmcSolver()`-style accessor builds its solver with: the family's submethod when
2475 * the method names that family, its default otherwise (an intent names no CTMC method).
2476 */
2477SolverOptions family_solver_options(const SolverOptions& o, const std::string& family,
2478 const std::string& fallback) {
2479 SolverOptions oo = o;
2480 const std::size_t dot = o.method.find('.');
2481 const std::string head = dot == std::string::npos ? o.method : o.method.substr(0, dot);
2482 if (autosolver::auto_family_alias(head) == family && dot != std::string::npos)
2483 oo.method = o.method.substr(dot + 1);
2484 else
2485 oo.method = fallback;
2486 return oo;
2487}
2488
2489} // namespace
2490
2492 return SolverCTMC(*model_, family_solver_options(opts_, "ctmc", "default"));
2493}
2494
2496 return SolverFLD(*model_, family_solver_options(opts_, "fld", "default"));
2497}
2498
2500 return SolverNC(*model_, family_solver_options(opts_, "nc", "default"));
2501}
2502
2504 // baSolver(): a bound method named outright is kept, every other name asks SolverBA for 'auto'.
2505 return SolverBA(*model_, family_solver_options(opts_, "ba", "auto"));
2506}
2507
2508std::vector<std::string> SolverAUTO::selection_intents() {
2509 return {"default", "heur", "sim", "exact", "fast", "accurate", "bound"};
2510}
2511
2512std::vector<std::string> SolverAUTO::family_names() {
2513 return {"mva", "nc", "ctmc", "fld", "mam", "ag", "ba", "ssa", "ldes", "jmt", "ln", "env", "lqns", "uq"};
2514}
2515
2516std::vector<std::string> SolverAUTO::metric_groups() { return autosolver::auto_metric_groups(); }
2517
2518std::string SolverAUTO::metric_group_of(const std::string& name) {
2520}
2521
2522std::vector<std::string> SolverAUTO::family_metrics(const std::string& family) {
2523 return autosolver::auto_family_metrics(family);
2524}
2525
2526namespace {
2527
2528qn::FeatureSet auto_feature_union() {
2529 const qn::FeatureSet sets[] = {qn::mva_feature_set("default"), qn::nc_feature_set("default"),
2531 qn::mam_feature_set("default"), qn::ssa_feature_set("default"),
2532 qn::ldes_feature_set("default"), qn::jmt_feature_set("default")};
2533 qn::FeatureSet out;
2534 for (std::size_t s = 0; s < sizeof(sets) / sizeof(*sets); ++s) {
2535 const std::vector<qn::Feature> fs = sets[s].list();
2536 for (std::size_t i = 0; i < fs.size(); ++i) out.set(fs[i]);
2537 }
2538 return out;
2539}
2540
2541} // namespace
2542
2543std::vector<std::string> SolverAUTO::feature_set() {
2544 const std::vector<qn::Feature> fs = auto_feature_union().list();
2545 std::vector<std::string> out;
2546 for (std::size_t i = 0; i < fs.size(); ++i) out.push_back(qn::feature_name(fs[i]));
2547 return out;
2548}
2549
2551 return qn::feature_set_supports("SolverAUTO", auto_feature_union(),
2553 .ok;
2554}
2555
2556} // namespace line
The -s ag entry point: gates, fixed point, mean measures.
SolverAUTO.listValidMethods: the method names THIS MODEL can actually run.
Base error for the multiprecision C++ port.
Definition error.h:73
ExternalError(const std::string &what)
Definition error.h:126
Malformed or inconsistent input (dimensions, negative populations, ...): LINE:input:<kind>.
Definition error.h:103
InputError(const std::string &what)
Definition error.h:105
std::size_t size() const
Definition matrix.h:91
std::size_t cols() const
Definition matrix.h:90
std::size_t rows() const
Definition matrix.h:89
AvgTable table_
Definition solver.h:242
const SolverOptions & options() const
The options this solver was built with.
Definition solver.h:148
const solvers::CacheMetrics< double > & cache_metrics()
What the same solve observed at each Cache node, the data behind getAvgCacheTable() and getAvgItemTab...
std::vector< double > miss_ratio(const std::string &cache)
cache.getMissRatio() after the solve, with hit_ratio's conventions.
AvgFJTable avg_fj_table()
getAvgFJTable() (aliases getAvgFJT, fjAvgT, aFJT): the same metrics as a labelled table.
const solvers::FjMetrics< double > & avg_fj()
getAvgFJ(): the fork-join section metrics of the same solve, one row per Fork/Join pair (fj_sorted_pa...
solvers::FjMetrics< double > fj_
Definition solver.h:244
const std::string & get_name() const
getName(): the solver's own name, e.g.
Definition solver.h:146
AvgChain avg_chain()
getAvgChain(): the station table of the same solve aggregated by chain, (nstations x nchains).
solvers::CacheMetrics< double > cache_
Definition solver.h:243
SolverOptions opts_
Definition solver.h:241
std::string method_used()
getMethodUsed(): the method the solve actually resolved to.
AvgSysTable avg_sys_table()
getAvgSysTable(): per-chain system response time and throughput of the same solve.
std::vector< Matrix< double > > avg_tard()
getAvgTard(): mean class tardiness E[(R - D)^+] against the JobClass deadlines, as {Tard (stations x ...
Network * model_
Definition solver.h:239
std::vector< std::string > list_valid_methods() const
listValidMethods(): the methods this solver advertises on this model.
const AvgTable & avg_table()
getAvgTable(): the average table, solving on first demand.
std::vector< double > hit_ratio(const std::string &cache)
cache.getHitRatio() after the solve: the per-class hit probability at the named Cache,...
Network & model() const
The model this solver was built on.
Definition solver.h:150
void reset()
reset(): discard the cached solve.
Definition solver.h:193
NetworkSolver(Network &m, const std::string &name, const SolverOptions &o)
Definition solver.h:236
AvgChainTable avg_chain_table()
getAvgChainTable(): avg_chain() as a labelled table, one row per (station, chain).
std::string name_
Definition solver.h:240
solvers::LossnInfo lossn_
result.LossN: loss-network inputs of the last NC solve, else empty
Definition solver.h:245
A node of the model: the index it was given, and the model that owns it.
Definition nodes.h:59
const std::string & get_name() const
getName().
Definition nodes.h:64
NumericError(const std::string &what)
Definition error.h:112
std::vector< std::string > proposed_solver_names(const std::string &getter="getAvg") const
delegate's retry order for that getter, as facade names; the chosen solver comes first.
static std::vector< std::string > family_names()
familyNames(): the method families, in the order a bare method name is looked up.
std::string choose_solver(const std::string &getter="getAvg") const
chooseSolver(getter): the facade name the configured method picks for that getter.
SolverBA ba_solver() const
baSolver(): the SolverBA the bound calls go to, method 'auto' unless a bound method was named.
static std::vector< std::string > metric_groups()
metricGroups(), metricGroupOf(name) and familyMetrics(family).
std::vector< std::string > list_all_methods() const
listAllMethods(): every method name the constructor accepts, independent of the model.
std::vector< std::vector< CdfCurve > > cdf_respt()
getCdfRespT(), delegated through the 'getCdfRespT' ranking.
static bool supports(Network &model)
supports(model): whether the model uses only features some family declares.
std::vector< std::string > candidate_solver_names() const
getCandidateSolverNames(): the facade names of the feasible candidates, in slot order.
SolverNC nc_solver() const
ncSolver(): the SolverNC the normalizing-constant calls go to.
SolverFLD fld_solver() const
fldSolver(): the SolverFLD the fluid-only calls go to.
std::string selected_solver_name()
getSelectedSolverName(): the facade name ("MVA", "FLD", ...) of the delegate that answered the last r...
SolverCTMC ctmc_solver() const
ctmcSolver(): the SolverCTMC the generator and state-space calls go to, with these options.
static std::vector< std::string > family_metrics(const std::string &family)
static std::string metric_group_of(const std::string &name)
static std::vector< std::string > feature_set()
getFeatureSet(): the union of the feature sets of SolverMVA, NC, CTMC, FLD, MAM, SSA,...
std::vector< AutoCandidate > find_solver(const std::string &metric=std::string(), bool show_all=false) const
findSolver(metric, showAll): which (family, method) pairs answer metric on this model.
std::string selected_method()
getSelectedMethod(): the method FAMILY of that delegate, lowercase ("mva", "fld").
bool is_stochastic()
isStochastic(): by the delegate that ran, else whether any candidate is a simulator.
TranAvg tran_avg()
getTranAvg(), delegated through the 'getTranAvg' ranking.
SolverAUTO(Network &m, const SolverOptions &o=SolverOptions())
double prob_aggr(std::size_t node, const std::vector< double > &state)
getProbAggr(node, state), delegated through the 'getProbAggr' ranking.
static std::vector< std::string > selection_intents()
selectionIntents().
SolverBA: the bounding solver, whose result is a bounds table.
Definition solver.h:632
BoundsTable bounds_table()
getBoundsTable(): the per-class queue-length and throughput bounds.
SolverBA(Network &m, const SolverOptions &o=SolverOptions())
Definition solver.h:634
SolverCTMC: the average table plus the chain it was computed from.
Definition solver.h:339
static void print_inf_gen(const Matrix< double > &Q, const Matrix< double > &space)
CTMC.printInfGen(Q, SS): the generator beside the state it belongs to.
Matrix< double > generator()
getGenerator(): the infinitesimal generator over that space.
double prob_aggr(std::size_t node, const std::vector< double > &state)
getProbAggr(node, state): the aggregate marginal of one state.
Matrix< double > state_space()
getStateSpace(): the aggregate state space, one row per state.
FirstPassage cdf_first_passt(const Matrix< double > &A, const Matrix< double > &B, const Matrix< double > &C=Matrix< double >(), const std::vector< double > &tset=std::vector< double >())
getCdfFirstPassT(A, B, C, tset): the FIRST PASSAGE TIME from the state set A into the state set B.
SolverCTMC(Network &m, const SolverOptions &o=SolverOptions())
Definition solver.h:341
SymbolicSolution symbolic_solution()
getSymbolicSolution(): the stationary law over the rate symbols x1..xE.
AccReward acc_reward(const std::string &name=std::string())
getAccReward(name): the reward accumulated over [0, options.timespan_end] by uniformisation (mc::ctmc...
FirstPassageMoments first_passt_moments(const Matrix< double > &A, const Matrix< double > &B, std::size_t nmax=3, const Matrix< double > &C=Matrix< double >())
getFirstPassTMoments(A, B, nmax, C): moments of order 1..nmax of the same passage,...
std::vector< double > marg_aggr(std::size_t node)
getProbStateAggr(node): the marginal over every state of one station.
std::vector< std::vector< CdfCurve > > cdf_respt()
getCdfRespT(): the response-time CDF per (station, class).
Matrix< double > state_space_aggr()
getStateSpaceAggr(): per-(station, class) job counts of every state, in (ist-1)*K + k column order,...
SolverFLD: the fluid solver, which also answers a transient.
Definition solver.h:618
std::vector< std::vector< CdfCurve > > cdf_respt()
getCdfRespT(): the response-time CDF per (station, class).
TranAvg tran_avg()
getTranAvg(): the transient mean queue length per station.
SolverFLD(Network &m, const SolverOptions &o=SolverOptions())
Definition solver.h:620
TranAvg tran_avg()
getTranAvg(): E[N](t), averaged over options.config.replications (SolverOptions::replications,...
SolverJMT(Network &m, const SolverOptions &o=SolverOptions())
Definition solver.h:305
SamplePath sample(std::size_t events=0, std::size_t node=0)
sampleSysAggr(events), or sampleAggr(node, events) when node is given: one logged trajectory.
std::vector< std::vector< CdfCurve > > cdf_respt()
getCdfRespT(): the EMPIRICAL response-time CDF per (station, class).
double prob_aggr(std::size_t node, const std::vector< double > &state)
getProbAggr(node, state): the time the declared state is held for.
TranReward tran_reward(const std::string &name=std::string())
getTranReward(name): the rewards along the sampled path; an empty name gives all of them.
SolverLDES(Network &m, const SolverOptions &o=SolverOptions())
Definition solver.h:456
SamplePath sample(std::size_t node, std::size_t events)
sample(node, events): the EXACT sample path of one stateful node (1-based node), from one unaveraged ...
const qn::NetworkStruct< double > & get_struct()
getStruct(): the model's struct, after the named refusal of an uncapped PAS buffer.
double prob_aggr(std::size_t node, const std::vector< double > &counts=std::vector< double >())
getProbAggr(node, counts): the probability of per-class counts at a station node.
SamplePath sample_sys(std::size_t events)
sampleSys(events): the LINE State of every stateful node per step, and every event.
SolverLDES & init_from_jobs(const Matrix< double > &jobs)
initFromJobs(jobs): start from a job-level initial state, one row per job [station,...
static std::vector< std::string > ln_feature_set()
getLNFeatureSet(): the features the layered LDES engine accepts.
std::vector< std::vector< CdfCurve > > tran_cdf_passt()
getTranCdfPassT(): the same measurement under the name the reference gives it.
std::vector< std::vector< CdfCurve > > cdf_respt()
getCdfRespT(): the EMPIRICAL response-time CDF per (station, class), from the per-job samples.
static std::vector< CdfCurve > cdf_respt_ln(const lqn::LqnStruct< double > &lsn, const SolverOptions &o=SolverOptions())
getCdfRespTLN(): the empirical response-time CDF of every entry of a layered model,...
SamplePath sample_aggr(std::size_t node, std::size_t events)
sampleAggr(node, events): the same path as per-class job counts.
const Matrix< double > & job_departures()
The [id, station, class, time] of every departure of a tagged job, from the same run.
SamplePath sample_sys_aggr(std::size_t events)
sampleSysAggr(events): the per-class counts of every stateful node per step.
static std::vector< std::string > feature_set()
getFeatureSet(): the features the LDES engine declares for a Network.
const Matrix< double > & final_jobs()
getFinalJobs(): the jobs present at the end of the run, in the init_from_jobs layout.
double prob_sys_aggr()
getProbSysAggr(): the same quantity, the histogram being aggregate already.
std::vector< PerctRespTCI > perct_respt(const std::vector< double > &percentiles=std::vector< double >(), long job_class=-1, const std::string &method=std::string())
getPerctRespT(percentiles, jobclass, method): steady-state response-time percentiles with confidence ...
TranAvg tran_avg()
getTranAvg(): the transient E[N](t) per (station, class) over [0, options.timespan_end],...
double prob(std::size_t node, const Matrix< double > &state=Matrix< double >())
getProb(node, state): the probability of a DETAILED state of one station node (1-based node),...
SolverLDES & init_from_solver(NetworkSolver &aux)
initFromSolver(initSolver): warm-start from an auxiliary solver's steady state.
BusyPeriodTable avg_busy_period(const std::vector< std::size_t > &stations=std::vector< std::size_t >(), long job_class=-1, const std::vector< std::size_t > &orders=std::vector< std::size_t >())
getAvgBusyPeriod(stations, jobclass, n): the mean busy periods of the given orders.
double prob_sys()
getProbSys(): the joint probability that every station holds its current-state counts.
static bool supports(Network &model)
supports(model): whether the Network uses only features the engine declares.
std::vector< std::vector< CdfCurve > > tran_cdf_respt()
getTranCdfRespT(): the empirical passage law, which is the same ECDF as cdf_respt.
std::vector< double > avg_reward(std::vector< std::string > *names=0)
getAvgReward(): E[r] for every declared reward, exact on the joint-state histogram,...
SolverNC: the normalizing-constant solver.
Definition solver.h:272
const solvers::LossnInfo & lossn_info()
The loss-network inputs (nu, A, C, link names, method) of the last solve, the reference's result....
SolverNC(Network &m, const SolverOptions &o=SolverOptions())
Definition solver.h:274
AvgLinkTable avg_link_table()
getAvgLinkTable(): per-link Capacity, Demand, Occupancy, LinkBlocking and RouteLoss of a loss network...
double total(std::size_t node) const
s.at(node).total(): jobs of every class at a station node; a handle converts.
double at(std::size_t node, std::size_t cls) const
s.at(node, cls): jobs of class cls (1-based; a handle converts) at a station node.
StateView(const std::vector< double > &row, const qn::NetworkStruct< double > &sn)
Definition solver.h:79
UnsupportedError(const std::string &what)
Definition error.h:119
std::vector< NodeDef > nodes
every node, in creation order
A subset of the registry: MATLAB's SolverFeatureSet, whose list is a flag per field.
std::vector< Feature > list() const
The features held, in registry order.
A network plus its refreshed NetworkStruct.
void set_state_prior(std::size_t node, const Matrix< T > &space, const std::vector< T > &prior)
StatefulNode.setStatePrior(space, prior): a distribution over the rows of a DECLARED state space.
const NetworkStruct< T > & get_struct()
The refreshed struct, MATLAB's model.getStruct().
The RAII frame timeout_arm returns.
bool active() const
Whether this scope pushed a frame.
The fluid solver's outermost entry point: @@SolverFLD/runAnalyzer.m's method resolution over solver_f...
The log-driven half of SolverJMT: linkAndLog, parseLogs, parseTranState, parseTranRespT,...
The NATIVE LDES engine for LAYERED (LQN) models, the C++ twin of jline/solvers/ldes/handlers/Solver_s...
The LDES warm start: SolverLDES(model, initSolver) / initFromSolver.
options.timeout: one wall-clock budget per top-level solve, on a per-THREAD deadline stack.
LayeredNetworkStruct, the flattened description of a layered queueing network.
The flat-Network path of @@SolverLQNS: its qns methods, served by qnsolver of the RADS/LQNS distribut...
Port of @NetworkSolver/mapEnvApprox.m: the solver-agnostic random-environment approximation of a netw...
The stage solvers map_env_approx injects, one per runner that can be a caller.
The method names of each solver, in listing order.
mva::AvgResult< T > solver_ag_run_analyzer(const qn::NetworkStruct< T > &L, const AgOptions &opt)
SolverAG.runAnalyzer: the converged agents as mean measures.
Definition ag_dispatch.h:34
Matrix< T > sn_declared_marginal(const qn::NetworkStruct< T > &sn)
The (nstations x nclasses) per-class job counts of the model's OWN state.
Definition sn_state.h:85
void sn_fj_nodevisits_mmt(qn::NetworkStruct< T > &sn)
Rewrite sn.nodevisits with the MMT correction.
ZeroCapacity sn_zero_capacity(const qn::NetworkStruct< T > &sn)
AutoSolver
The Network candidate slots, in the reference's slot order (SolverAUTO.m:41-50), which is also the or...
std::string auto_metric_group_of(const std::string &name)
The measure group an accessor belongs to, "" when the name belongs to none.
std::string auto_family_alias(const std::string &name)
SolverAUTO.familyAlias: the canonical family of a method name, or "" when the method name names none.
std::vector< std::string > auto_family_metrics(const std::string &family)
The measure groups a method family can answer.
std::vector< std::string > auto_metric_groups()
The measure groups auto_find_solver reports on, in report order.
const char * auto_solver_name(AutoSolver s)
AutoToken auto_resolve_token(const std::string &raw, const qn::NetworkStruct< T > &sn)
resolveMethodToken with its third arm: an intent, a family[.submethod], or else a BARE method name,...
std::vector< AutoSolver > auto_candidates(const qn::NetworkStruct< T > &sn)
The candidate pool in slot order, filtered by supports: what the delegate retries through after the c...
std::vector< AutoSolver > auto_proposed_solvers(const qn::NetworkStruct< T > &sn, const std::string &method, AutoMode mode)
delegate's proposed order: the chosen solver, then every feasible candidate in slot order.
AutoChoice auto_choose_solver_mode(const qn::NetworkStruct< T > &sn, const std::string &method, AutoMode mode)
chooseSolver: the selection mode picks the ranking, and every mode but the two learned ones keeps the...
std::vector< SolverCandidate > auto_find_solver(const qn::NetworkStruct< T > &sn, const std::string &metric=std::string(), bool show_all=false)
SolverAUTO.findSolver: which solvers and solver methods can analyze this model, and for the ones that...
std::vector< std::string > auto_list_valid_methods(const qn::NetworkStruct< T > &sn)
SolverAUTO.listValidMethods: every method name this model can be asked for.
BaBounds< T > ba_bounds(const qn::NetworkStruct< T > &L, const BaOptions &opt)
Port of SolverBA.getBounds.
mva::AvgResult< T > solver_ba_run_analyzer(const qn::NetworkStruct< T > &L, const BaOptions &opt_in)
Port of @@SolverBA/runAnalyzer.m for the lang='matlab' path.
std::vector< std::string > list_valid_methods()
Port of SolverBA.listValidMethods.
CtmcSolution< T > solver_ctmc_analyzer(const NetworkStruct< T > &sn_in, const CtmcOptions &opt, const CtmcStationaryHook< T > &stationary=CtmcStationaryHook< T >())
Port of solver_ctmc_analyzer.m plus the fork-join wrapper of @@SolverCTMC/runAnalyzer....
std::vector< std::string > list_valid_methods()
Port of SolverCTMC.listValidMethods.
CtmcGenerator< T > ctmc_get_infgen(const NetworkStruct< T > &sn, const CtmcSolution< T > &d)
@@SolverCTMC/getInfGen.m, a pure alias of getGenerator in the reference.
std::vector< std::vector< CdfCurve< T > > > solver_ctmc_cdf_respt(const NetworkStruct< T > &sn, const CtmcOptions &opt)
Port of @@SolverCTMC/getCdfRespT.m: the per-(station, class) response-time CDF, indexed [ist-1][r-1].
CtmcStateSpace< T > ctmc_get_state_space(const NetworkStruct< T > &, const CtmcSolution< T > &d)
Port of @@SolverCTMC/getStateSpace.m.
CtmcAccReward< T > solver_ctmc_acc_reward(const NetworkStruct< T > &sn_arg, const CtmcOptions &opt, const T &t0, const T &t1)
Port of @@SolverCTMC/getAccReward: the reward ACCUMULATED over [t0, t], E[int_{t0}...
CtmcFirstPassageMoments< T > ctmc_firstpasst_moments(const NetworkStruct< T > &, const CtmcSolution< T > &d, const Matrix< double > &A, const Matrix< double > &B, std::size_t nmax, const Matrix< double > &C)
Port of @@SolverCTMC/getFirstPassTMoments.m: moments of order 1..nmax of the first passage time from ...
Matrix< T > ctmc_get_state_space_aggr(const NetworkStruct< T > &sn, const CtmcOptions &opt)
Port of @@SolverCTMC/getStateSpaceAggr.m: the per-(station, class) job counts of every state,...
CtmcFirstPassage ctmc_cdf_firstpasst(const NetworkStruct< T > &, const CtmcSolution< T > &d, const Matrix< double > &A, const Matrix< double > &B, const Matrix< double > &C, std::vector< double > tset, const std::string &method="expm")
Port of @@SolverCTMC/getCdfFirstPassT.m: the distribution of the FIRST PASSAGE TIME from state set A ...
mva::AvgResult< T > solver_ctmc_mdd_run_analyzer(const NetworkStruct< T > &sn, const CtmcOptions &opt, const mdd::MddMcdOptions &mcdopt=mdd::MddMcdOptions())
Solve with mdd and format, so a caller with no use for the diagram has one call.
CtmcSymbolicSolution< T > ctmc_symbolic_solution(const NetworkStruct< T > &sn, const CtmcOptions &opt, const CtmcSymbolicOptions &symopt=CtmcSymbolicOptions())
Port of @@SolverCTMC/getSymbolicSolution.m: pi Q = 0 with sum(pi) = 1 over the field of rational func...
bool is_stateless_method(const std::string &method)
True for a method whose analyzer is not the explicit-generator one.
mva::AvgResult< T > solver_ctmc_run_analyzer_any(const NetworkStruct< T > &sn, const CtmcOptions &opt)
Solve on whichever path applies and format, mirroring solver_ctmc_run_analyzer.
std::vector< std::string > fluid_list_valid_methods()
Port of SolverFLD.listValidMethods.
FluidSolution solver_fluid_run_analyzer(const qn::NetworkStruct< T > &sn, const FluidOptions &opt, qn::NetworkStruct< T > *sn_out=nullptr, qn::NetworkStruct< T > *refreshed_out=nullptr, solvers::CacheMetrics< T > *cache_out=nullptr, const qn::NetworkStruct< T > *gate_sn=nullptr)
Port of @@SolverFLD/runAnalyzer.m: resolve the method, route to the function the reference routes to,...
std::vector< FluidTranPoint > solver_fluid_tran_avg(const qn::NetworkStruct< T > &sn, const FluidOptions &opt, std::size_t points=101)
getTranAvg on the first-order closing drift, over that horizon.
std::vector< std::vector< FluidPassage > > solver_fluid_cdf_respt(const qn::NetworkStruct< T > &sn, const FluidOptions &opt, std::size_t points=201)
Port of @@SolverFLD/getCdfRespT: the response-time law of every (station, class) pair,...
void require_finite_pas_buffers(const qn::NetworkStruct< T > &sn)
Refuse an OI/PAS station with no finite buffer before it reaches LDES.
JmtReplication< T > jmt_transient_replications(const qn::NetworkStruct< T > &sn, const JmtOptions &opt)
Port of the transient ensemble of @@SolverJMT/runAnalyzer.m (default over a finite timespan).
Definition jmt_logs.h:912
JmtSysTrace< T > jmt_sample_sys_aggr(const qn::NetworkStruct< T > &sn, std::size_t num_events, const JmtOptions &opt)
Port of sampleSysAggr: every station's trajectory on one time grid.
Definition jmt_logs.h:501
JmtNodeTrace< T > jmt_sample_aggr(const qn::NetworkStruct< T > &sn, std::size_t node, std::size_t num_events, const JmtOptions &opt)
Port of sampleAggr: the queue-length trajectory of one node.
Definition jmt_logs.h:450
std::vector< std::string > jmt_list_valid_methods()
Port of SolverJMT.listValidMethods.
JmtResult< T > solver_jmt_run_analyzer(const qn::NetworkStruct< T > &sn, const JmtOptions &opt_in)
Port of @@SolverJMT/runAnalyzer.m, the jsim and jmva arms.
std::map< std::pair< std::size_t, std::size_t >, std::vector< std::pair< double, double > > > jmt_get_cdf_resp_t(const qn::NetworkStruct< T > &sn, const JmtOptions &opt, bool seed_from_steady=true)
Port of getCdfRespT: the empirical response-time distribution per (station, class),...
Definition jmt_logs.h:573
JmtProbAggr jmt_prob_aggr(const qn::NetworkStruct< T > &sn, const JmtOptions &opt, std::size_t target_station=0, const std::vector< double > &target=std::vector< double >())
Port of getProbAggr and getProbSysAggr, both off ONE instrumented run.
Definition jmt_logs.h:816
std::vector< LnEntryCdf > ldes_ln_cdf_respt(const LnResult &r, std::size_t nentries)
The empirical response time CDF of every ENTRY, the getCdfRespTLN of the other codebases: one [F(t),...
LdesSample ldes_sample_aggr(const qn::NetworkStruct< T > &sn, const LdesOptions &o, std::size_t ind, std::size_t events)
sampleAggr(node, events): the same path as per-class counts, always available.
std::vector< LdesPercentileResult > ldes_perct_respt(const LdesResult &r, const std::vector< double > &percentiles, int replications, const std::string &method=std::string(), double level=0.95, long job_class=-1)
Port of @SolverLDES/getPerctRespT: steady-state response-time p-quantiles with confidence intervals,...
solvers::FjMetrics< double > ldes_fj_metrics(const qn::NetworkStruct< T > &sn, const LdesResult &r)
ldesParseForkJoin: the engine's "forkJoin" rows mapped onto the Fork/Join pairs of sn by (fork name,...
LdesSample ldes_sample_sys(const qn::NetworkStruct< T > &sn, const LdesOptions &o, std::size_t events)
sampleSys(events): the LINE State of every stateful node at each step, and every event of the run.
double ldes_prob_from_histogram(const LdesResult &r, std::size_t nclasses, const std::vector< LdesStateQuery > &query)
Residence-time probability of an aggregate joint state, from a parsed result.
engine::LnResult ldes_ln_engine_solve(const lqn::LqnStruct< T > &lsn, const LdesOptions &o)
Simulate a layered model in process.
bool ldes_is_available()
True when this machine can run the engine at all, by either image.
Definition ldes_probe.h:253
std::vector< std::string > list_valid_methods()
Port of SolverLDES.listValidMethods.
Matrix< double > warm_start_placement_from_qlen(const qn::NetworkStruct< T > &sn, const Matrix< T > &QN)
Port of placementFromMeanQLen: an integer placement from mean queue lengths.
LdesSample ldes_sample_sys_aggr(const qn::NetworkStruct< T > &sn, const LdesOptions &o, std::size_t events)
sampleSysAggr(events): the per-class counts of every stateful node at each step.
Matrix< double > ldes_cdf_respt(const LdesResult &r, std::size_t station, std::size_t job_class)
Port of getCdfRespT: the EMPIRICAL response time CDF of one (station, class) pair,...
LdesSample ldes_sample(const qn::NetworkStruct< T > &sn, const LdesOptions &o, std::size_t ind, std::size_t events)
sample(node, events): the exact path of one stateful node (1-based ind), one LINE State row per step ...
std::string ldes_ln_refusal(const lqn::LqnStruct< T > &lsn)
Port of ldes_ln_refusal: why SolverLDES.supports declines a layered model, or an empty string when it...
Matrix< double > warm_start_placement_from_ctmc(const qn::NetworkStruct< T > &sn, const ctmc::CtmcOptions &opt)
Port of placementFromCtmcSteadyState: the mode of the aggregate stationary law.
int ldes_replications(const LdesOptions &o)
The replication count a run asks the engine for: replications when it is above one,...
LdesResult solver_ldes(const qn::NetworkStruct< T > &sn, const LdesOptions &o, const std::vector< std::string > &extra_flags=std::vector< std::string >())
std::string ldes_perct_method(int replications, const std::string &method)
The quantile procedure a replication count calls for: 'fquest' on one path (R <= 1),...
LossnLinksResult< T > lossn_links(const std::vector< T > &nu, const Matrix< T > &A, const std::vector< T > &C, const std::string &method="exact", const LossnMciOptions< T > &mciopt=LossnMciOptions< T >(), std::uint64_t seed=0)
Per-link blocking and occupancy of a loss network.
std::string name(const Element *el, const std::string &key="name")
mva::AvgResult< T > solve_network_run_analyzer(const qn::NetworkStruct< T > &L, const QnsOptions &opt)
Port of @@SolverLQNS/runAnalyzerNetwork.m and solver_qns.m: SolverLQNS on a flat Network.
bool qnsolver_is_available()
Port of SolverLQNS.hasQnsolver: a native qnsolver binary on the PATH.
std::vector< std::string > list_valid_methods()
Port of SolverMAM.listValidMethods.
mva::AvgResult< T > solver_mam_run_analyzer(const qn::NetworkStruct< T > &L, const MamOptions &opt)
Port of @@SolverMAM/runAnalyzer.m for the lang='matlab' path: solve, then apply the metric filter @@N...
std::vector< std::string > methods(const std::string &solver)
Every method name the solver can be asked for, in listing order.
Matrix< T > sn_get_residt_from_respt(const qn::NetworkStruct< T > &L, const Matrix< T > &RN)
Port of sn_get_residt_from_respt: the per-JOB residence time.
QsysPrioTardiness solver_mva_qsys_prio_tardiness(const qn::NetworkStruct< double > &L, std::string actualmethod)
std::string resolve_method(const qn::NetworkStruct< T > &L, const std::string &method)
Port of SolverMVA.resolveMethod: the feature-driven default -> rqna upgrade for a bursty single-class...
std::vector< std::string > list_valid_methods(const qn::NetworkStruct< T > &L)
Port of SolverMVA.listValidMethods.
Matrix< T > sn_get_arvr_from_tput(const qn::NetworkStruct< T > &L, const Matrix< T > &TN)
Port of sn_get_arvr_from_tput: the arrival rate each station sees, from the throughputs and the class...
AvgResult< T > solver_mva_run_analyzer(const qn::NetworkStruct< T > &L, const MvaOptions &opt_in, const Matrix< T > &init_sol)
Port of @@SolverMVA/runAnalyzer.m for the lang='matlab' path: gate, solve, convert,...
mva::AvgResult< T > solver_nc_run_analyzer(const qn::NetworkStruct< T > &L_in, const NcSolverOptions &opt_in)
std::vector< std::string > list_valid_methods()
Port of SolverNC.listValidMethods.
std::vector< std::vector< T > > from_marginal(const NetworkStruct< T > &sn, std::size_t ist, const std::vector< std::size_t > &n, const std::vector< std::size_t > &phases)
Definition state.h:1712
FeatureSet ldes_feature_set(const std::string &)
SolverLDES.getFeatureSet, transcribed WHOLE.
FeatureSet fluid_feature_set(const std::string &method)
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
FeatureSet ssa_feature_set(const std::string &method)
FeatureSet jmt_feature_set(const std::string &method)
Port of SolverJMT.getFeatureSet (@@SolverJMT/SolverJMT.m:180-290).
FeatureSet used_lang_features(const NetworkStruct< T > &sn)
FeatureSet nc_feature_set(const std::string &method)
SolverNC.getFeatureSet, 48 names, transcribed unchanged.
Feature
One language feature.
FeatureSet fluid_class_feature_set()
SolverFLD.getFeatureSet, transcribed, MINUS what the requested method cannot evaluate – the port of @...
FeatureSet ctmc_feature_set(const std::string &method)
SolverCTMC.getFeatureSet, the reference's 104 MATLAB names in full.
SupportResult feature_set_supports(const std::string &solver, const FeatureSet &declared, const FeatureSet &used)
SolverFeatureSet.supports: is every feature the model uses declared?
FeatureSet mam_feature_set(const std::string &method)
SolverMAM.getFeatureSet, the union of its four setTrue calls: 55 MATLAB names, WIDENED for 'default'/...
FeatureSet mva_feature_set(const std::string &raw_method)
SolverMVA.getFeatureSet, plus getMethodFeatureSet's per-method deltas.
const char * feature_name(Feature f)
The canonical registry name, byte for byte the MATLAB field name.
MapEnvDecision needs_map_env(const qn::FeatureSet &declared, const qn::NetworkStruct< T > &sn, const MapEnvConfig &cfg=MapEnvConfig())
needsMapEnv: does this model need the environment image, and would the image make it solvable?
CacheMetrics< T > cache_metrics_of(const qn::NetworkStruct< T > &sn, const std::vector< T > &hitprob, const std::vector< T > &missprob, const std::vector< T > &delayedprob, const std::vector< T > &latency, const Matrix< T > &hitproblist, const Matrix< T > &itemprob, const std::vector< T > &listcost)
Assemble CacheMetrics from what a cache analyzer returned.
void cache_mark_nonreading(const qn::NetworkStruct< T > &sn, CacheNodeMetrics< T > &m)
A CLASS THAT DOES NOT READ THE CACHE READS NaN, in every solver and every codebase (BUG-101): NaN is ...
std::vector< std::string > chain_class_labels(const qn::NetworkStruct< T > &sn)
(ClassA ClassB), the JobClasses column: which classes a chain holds.
env::EnvStageAvgFn< double > nc_stage_fn(const nc::NcSolverOptions &opt)
NC stages, bound to the caller's own NcSolverOptions.
SysResult< T > solver_get_avg_sys(const qn::NetworkStruct< T > &sn, const mva::AvgResult< T > &r)
Port of @@NetworkSolver/getAvgSys.m.
mva::AvgResult< T > run_avg(const qn::NetworkStruct< T > &sn, const std::string &solver, const qn::FeatureSet &declared, const MapEnvConfig &cfg, Run run, StageFn stage_fn, const std::string &requested_method="default")
The getAvg funnel: run the model, or its environment image when the ONLY thing in the way is a non-re...
Definition map_env.h:332
ChainResult< T > solver_get_avg_chain(const qn::NetworkStruct< T > &sn, const mva::AvgResult< T > &r)
Port of @@NetworkSolver/getAvgChain.m: the station table aggregated by chain.
mva::AvgResult< T > map_env_approx(const qn::NetworkStruct< T > &sn, const std::string &solver, const MapEnvConfig &cfg, StageFn stage_fn, const std::string &requested_method="default")
mapEnvApprox: solve the model through the random-environment image of its non-renewal processes.
Definition map_env.h:186
std::vector< std::string > chain_names(std::size_t nchains)
Chain1, Chain2, ... – the reference's own chain labels.
env::EnvStageAvgFn< double > fluid_stage_fn(const fluid::FluidOptions &opt)
Fluid stages, bound to the caller's own FluidOptions.
env::EnvStageAvgFn< double > mva_stage_fn(const mva::MvaOptions &opt)
MVA stages, bound to the caller's own MvaOptions.
std::vector< std::string > list_valid_methods()
Port of SolverSSA.listValidMethods.
SsaSolution solver_ssa(const qn::NetworkStruct< T > &sn, const SsaOptions &opt, std::vector< SsaCacheRatio > *cache=nullptr)
qn::NetworkStruct< T > sn_with_ssa_cache_split(const qn::NetworkStruct< T > &base, const std::vector< SsaCacheRatio > &cache)
@@SolverSSA/runAnalyzer itself: the engine the method selects, then the result assembly the reference...
solvers::CacheMetrics< T > cache_metrics_of_ssa(const qn::NetworkStruct< T > &sn, const std::vector< SsaCacheRatio > &cache)
CacheMetrics from the serial engine's cache write-back.
TimeoutScope timeout_arm(double budget)
Arm budget seconds for the scope's lifetime, capped by the outer frame's remaining time.
bool timeout_tripped()
Whether the innermost budget was tripped by a checkpoint or by timeout_trip.
void timeout_warn(const std::string &solver, double budget)
The one warning a solve that stopped on its budget prints, MATLAB's flagTimeout text,...
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
qn::Network< double > Network
Network as a user names it: the double model, Python's Network.
Definition solver.h:63
std::ostream & operator<<(std::ostream &out, const AvgTable &table)
std::function< bool(const StateView &)> StatePredicate
A STATE SET named by a predicate, the reference's function-handle form, e.g.
Definition solver.h:99
The model API a user writes, spelled as its Python twin.
Post-MMT node visits of a fork-join model.
Ports of matlab/src/api/sn/sn_get_state_aggr.m and sn_is_state_valid.m.
Port of matlab/src/api/sn/sn_zero_capacity.m: the closed chains trapped at a zero-capacity station.
The solver API a user writes, spelled as its Python twin.
The SolverAUTO chooser: which solver a model is handed to.
The SolverBA class surface: @@SolverBA/runAnalyzer.m, listValidMethods, getBounds and getBoundsTable.
The CHAIN-level and SYSTEM-level views of a solved model.
Port of solver_ctmc_analyzer.m and the parts of @@SolverCTMC/runAnalyzer.m that surround one solve: t...
Port of @@SolverCTMC/getCdfRespT.m and @@SolverCTMC/getCdfSysRespT.m: the exact distribution of the r...
The remaining @@SolverCTMC accessors: getGenerator / getInfGen, getStateSpace / getStateSpaceAggr and...
The mdd method of SolverCTMC: stationary analysis of a closed single-class network whose state space ...
The SolverCTMC probability family: solver_ctmc_joint, _jointaggr, _marg, _margaggr,...
Port of solver_ctmc_reward.m and the @@SolverCTMC reward surface (runRewardAnalyzer,...
Port of @@SolverCTMC/getSymbolicGenerator and getSymbolicSolution.
Port of solver_ctmc_fcr_waitq.m: the reachability-built generator of a model whose finite capacity re...
SolverFluid: the closing method, a port of solver_fluid.m, solver_fluid_iteration....
Port of SolverJMT, the Java Modelling Tools client.
Port of SolverLDES, the discrete-event simulator, as its C++ client.
The SolverMAM class surface: @@SolverMAM/runAnalyzer.m and the gates around it.
Port of solver_mva_qsys_prio_tardiness.m: the exact class-deadline tardiness E[(R - D)^+] of the sing...
The SolverMVA class surface: @@SolverMVA/runAnalyzer.m and the gates around it.
The SolverNC class surface: @@SolverNC/runAnalyzer.m and the gates around it.
The SolverSSA entry surface: a port of @@SolverSSA/runAnalyzer.m's method whitelist,...
Port of the MATLAB +State package: the encoding that turns a station's state row into marginal job co...
getAccReward(name): the reward accumulated over [t0, t], one row per reward.
Definition solver.h:128
std::vector< double > t
the absolute time grid, t[0] = t0
Definition solver.h:130
std::vector< std::vector< double > > avg
(nrewards x nt) time-averaged reward
Definition solver.h:132
std::vector< std::vector< double > > metric
(nrewards x nt) accumulated reward
Definition solver.h:131
std::vector< std::string > names
the reward names, in declaration order
Definition solver.h:129
One row of SolverAUTO::find_solver: a (family, method) pair and whether this model can run it.
Definition solver.h:644
bool runnable
the model passes this method's own support gate
Definition solver.h:647
std::string solver
the method family: "mva", "ctmc", "ldes", ...
Definition solver.h:645
std::string method
the qualified method name to pass, "mva.exact"
Definition solver.h:646
std::string method_class
"exact", "approx", "bound" or "simulation"
Definition solver.h:648
std::string reason
why a refused pair was refused, "" when runnable
Definition solver.h:650
std::string metrics
the measure groups the family answers, comma-joined
Definition solver.h:649
getAvgChainTable: the station table aggregated by CHAIN, one row per (station, chain),...
Definition avg_table.h:150
std::vector< double > QLen
Definition avg_table.h:152
std::vector< double > ArvR
Definition avg_table.h:152
std::vector< double > RespT
Definition avg_table.h:152
std::vector< double > Util
Definition avg_table.h:152
std::vector< double > ResidT
Definition avg_table.h:152
std::size_t size() const
Definition avg_table.h:156
void print(std::ostream &out) const
Print the station-chain table.
std::vector< std::string > Chain
Definition avg_table.h:151
std::vector< std::string > JobClasses
Definition avg_table.h:151
std::vector< std::string > Station
Definition avg_table.h:151
std::vector< double > Tput
Definition avg_table.h:152
getAvgChain(): the station x chain matrices, @NetworkSolver/getAvgChain.m's outputs.
Definition solver.h:68
Matrix< double > QN
Definition solver.h:69
Matrix< double > TN
Definition solver.h:69
Matrix< double > RN
Definition solver.h:69
Matrix< double > AN
Definition solver.h:69
Matrix< double > UN
Definition solver.h:69
Matrix< double > WN
Definition solver.h:69
getAvgFJTable(): one row per (Fork/Join pair, class) with a nonzero metric, the fork-join SECTION met...
Definition avg_table.h:168
std::vector< std::string > Fork
Definition avg_table.h:169
std::size_t size() const
Definition avg_table.h:174
void print(std::ostream &out) const
Print the labelled pair-class table.
std::vector< double > FJTput
Definition avg_table.h:170
std::vector< std::string > JobClass
Definition avg_table.h:169
std::vector< double > FJRespT
Definition avg_table.h:170
std::vector< double > FJQLen
Definition avg_table.h:170
std::vector< std::string > Join
Definition avg_table.h:169
SolverNC.getAvgLinkTable(): the per-link measures of a loss network (an open model whose single Delay...
Definition avg_table.h:189
std::vector< double > LinkBlocking
Definition avg_table.h:191
std::vector< double > Capacity
Definition avg_table.h:191
void print(std::ostream &out) const
Print the labelled link-class table.
std::vector< double > Occupancy
Definition avg_table.h:191
std::size_t size() const
Definition avg_table.h:195
std::vector< std::string > JobClass
Definition avg_table.h:190
std::vector< std::string > Link
Definition avg_table.h:190
std::vector< double > Demand
Definition avg_table.h:191
std::vector< double > RouteLoss
Definition avg_table.h:191
getAvgSysTable(): one row per CHAIN, the cycle time and the completing throughput at the chain's refe...
Definition avg_table.h:134
std::vector< double > SysRespT
Definition avg_table.h:136
void print(std::ostream &out) const
Print the chain table.
std::vector< std::string > JobClasses
Definition avg_table.h:135
std::vector< double > SysTput
Definition avg_table.h:136
std::vector< std::string > Chain
Definition avg_table.h:135
getAvgTable, one row per (station, class) that carries a metric.
Definition avg_table.h:38
std::vector< double > ArvR
Definition avg_table.h:40
bool timed_out
Whether the solve stopped early on SolverOptions::timeout, read from the budget's TRIPPED latch (line...
Definition avg_table.h:57
std::vector< double > TputCI
Definition avg_table.h:62
std::vector< double > UtilCI
Definition avg_table.h:62
std::vector< double > Tput
Definition avg_table.h:40
std::vector< double > ResidT
Definition avg_table.h:40
void print(std::ostream &out) const
Print the labelled station-class table.
std::vector< double > RespT
Definition avg_table.h:40
std::size_t size() const
The number of rows the table carries.
Definition avg_table.h:101
double lognormconst
Definition avg_table.h:47
std::vector< double > Util
Definition avg_table.h:40
void print() const
std::vector< std::string > Station
Definition avg_table.h:39
std::vector< double > column(const std::string &column) const
A complete metric column.
std::vector< double > SysTput
Definition avg_table.h:43
bool has_ci() const
Whether the half-width columns are filled.
Definition avg_table.h:64
std::vector< double > ResidTCI
Definition avg_table.h:62
std::vector< std::string > JobClass
Definition avg_table.h:39
std::string warning
The reference's own warning text, empty when it did not warn.
Definition avg_table.h:51
double get(const std::string &column, const std::string &station, const std::string &jobclass) const
One cell of the table, by station and class NAME; NaN when absent.
std::string solver
Definition avg_table.h:44
std::vector< double > QLenCI
Confidence half-widths of the six metric columns, row for row; EMPTY unless SolverOptions::confint as...
Definition avg_table.h:62
AvgTable tget(const Node &node) const
AvgTable filter_by(const std::string &name) const
Rows whose station or class has name, MATLAB's one-argument filterBy.
std::vector< double > RespTCI
Definition avg_table.h:62
std::string method
Definition avg_table.h:44
std::vector< double > ArvRCI
Definition avg_table.h:62
AvgTable operator()(const Node &node) const
Direct object indexing: table(queue, jobs).
bool has_lognormconst
Definition avg_table.h:46
std::vector< double > ListCost
getAvgCacheTable's ListCost column; empty on a model without item sizes.
Definition avg_table.h:49
std::vector< double > SysRespT
Definition avg_table.h:43
std::vector< std::string > SysClass
getAvgSysTable: system response time and throughput, per class.
Definition avg_table.h:42
std::vector< double > QLen
Definition avg_table.h:40
SolverBA(model, method).getBoundsTable().
Definition avg_table.h:202
std::vector< double > Tlower
Definition avg_table.h:204
std::string method
Definition avg_table.h:205
std::vector< double > Qupper
Definition avg_table.h:204
std::vector< std::string > Station
Definition avg_table.h:203
std::vector< double > Qlower
Definition avg_table.h:204
std::vector< std::string > JobClass
Definition avg_table.h:203
std::vector< double > Tupper
Definition avg_table.h:204
SolverLDES: the discrete-event simulator, which also answers the empirical response-time law.
Definition solver.h:441
std::vector< std::size_t > orders
the busy period order of each column, 1-based
Definition solver.h:443
Matrix< double > count
Definition solver.h:444
Matrix< double > mean
Definition solver.h:444
std::vector< std::string > names
Definition solver.h:442
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
getFirstPassTMoments(A, B, nmax, C): [m, mall, p] with the resolved sets.
Definition solver.h:114
std::vector< double > m
moments 1..nmax from A (conditional on B before C)
Definition solver.h:115
getCdfFirstPassT(A, B, C, tset): the curve, the reach probabilities and the resolved sets.
Definition solver.h:102
std::vector< double > t
the grid: the caller's, else 1000 points to the horizon
Definition solver.h:103
One (station, class) row of SolverLDES::perct_respt: steady-state response-time percentiles with conf...
Definition solver.h:426
std::vector< double > values
Definition solver.h:428
std::vector< double > halfwidth
Definition solver.h:428
std::vector< bool > heuristic
Definition solver.h:429
std::string job_class
Definition solver.h:427
std::string method
Definition solver.h:431
std::vector< double > upper
Definition solver.h:428
std::vector< double > percentiles
Definition solver.h:428
std::size_t samples
Definition solver.h:432
std::vector< double > lower
Definition solver.h:428
std::string station
Definition solver.h:427
sampleSysAggr / sampleAggr: ONE simulated trajectory, not a mean.
Definition avg_table.h:245
std::vector< std::vector< double > > state
[step][column]
Definition avg_table.h:247
std::vector< std::string > label
what each column counts
Definition avg_table.h:248
std::vector< double > t
event times, ascending
Definition avg_table.h:246
bool aggregate
Per-class counts (true) or LINE State rows (false, SolverLDES sample/sample_sys).
Definition avg_table.h:261
std::vector< std::size_t > column_node
The 1-based node each column of state belongs to (SolverLDES only).
Definition avg_table.h:259
std::vector< std::vector< double > > event
The events of the path, one row each, [time, node, type, class, jobId, phase]: node and class 1-based...
Definition avg_table.h:257
The knobs a solver reads; a negative or empty field keeps the engine default.
double warmupfrac
options.warmupfrac, in [0,1): LDES under tranfilter=fixed, and SSA's discarded prefix.
Matrix< double > init_jobs
LDES options.init_jobs: one row per job, [station, class, remaining, elapsed, qage,...
double timeout
options.timeout, seconds: the wall-clock budget of the whole top-level solve (line/util/line_timeout....
int level
SolverBA options.level.
double timespan_end
Fluid options.timespan(2) and warm start.
bool track_jobs
LDES options.track_jobs: return the end-of-run job state; implied by init_jobs.
bool cache
options.cache: reuse the solved tables on later calls to the same solver object.
std::string tranfilter
LDES options.tranfilter: mser5 | fixed | none; empty keeps mser5.
getSymbolicSolution: the stationary law as a function of the rate symbols.
Definition avg_table.h:221
std::vector< double > rate0
nominal value of each symbol
Definition avg_table.h:226
std::string den
common denominator of the vector
Definition avg_table.h:224
std::vector< std::string > pi
stationary probability of each state
Definition avg_table.h:222
std::vector< std::string > symbols
x1..xE, empty where an event has no positive rate
Definition avg_table.h:225
std::string engine
backend that answered, e.g. "sage"
Definition avg_table.h:227
std::vector< std::string > num
numerator of each entry over den
Definition avg_table.h:223
getTranAvg: the transient mean queue length per (station, class).
Definition avg_table.h:231
std::vector< std::string > label
the (station, class) of each column
Definition avg_table.h:234
std::vector< std::vector< double > > QNt
[step][station*class]
Definition avg_table.h:233
std::vector< double > t
the time axis
Definition avg_table.h:232
getTranReward(name): each reward evaluated along the sampled state path, one row per reward.
Definition solver.h:448
std::vector< double > t
the time of each path point
Definition solver.h:450
std::vector< std::vector< double > > metric
(nrewards x nt) the reward at each point
Definition solver.h:451
std::vector< std::string > names
the reward names, in declaration order
Definition solver.h:449
What sn_zero_capacity reports.
std::string reason
Non-empty when the model has no steady state of this form: an open class reaches a zero-capacity stat...
bool any() const
True when some chain is trapped.
What a ranking resolved to, and what it had to skip to get there.
resolveMethodToken, minus the unqualified-algorithm-name arm.
Port of SolverBA.getBounds: the {lower,upper} bracket of a family.
std::vector< std::vector< bool > > keep
getBoundsTable's row filter, (M x K): whether the (station, class) pair earns a row.
Matrix< T > Qupper
(M x K), all-NaN on a side the family lacks
The options SolverBA reads.
What solver_ctmc_acc_reward produces.
std::vector< T > t
absolute time points, t[0] = t0
std::vector< std::string > names
std::vector< std::vector< T > > metric
metric[r][i] = E[int_{t0}^{t_i} r(X(s)) ds]
std::vector< std::vector< T > > avg
metric / (t_i - t0); E[r(X(t0))] at t_i = t0
The answer of @@SolverCTMC/getFirstPassTMoments.m.
The answer of @@SolverCTMC/getCdfFirstPassT.m: the [F(t), t] curve with its grid, density and resolve...
The SolverCTMC knobs this port honours.
Everything one CTMC solve produces.
std::shared_ptr< const NetworkStruct< T > > solved_sn
The struct the chain was built on, when it differs from the caller's in its state LAYOUT: set when he...
std::vector< T > pi
stationary distribution over chain.space
Backend selection, mirroring options.config.symbolic and its timeout.
std::string backend
auto to search, a URL, an image name, or none to stay local.
What @@SolverCTMC/getSymbolicSolution.m returns, plus the engine that answered.
std::string engine
backend that solved it, e.g. sage
std::vector< T > rate0
Nominal value of each symbol, i.e.
std::vector< std::string > symbols
x1..xE, empty for an event with no positive rate.
std::vector< std::string > num
numerator of each entry over den
std::vector< std::string > pi
stationary probability of each state
std::string den
common denominator of the vector
Controls, defaulting to SolverOptions('Fluid') in the reference.
What the analyzer returns, in the same shape as the MVA solver's result.
The per-class queue-length trajectory of one node, plus its event stream.
Definition jmt_logs.h:227
The options of one JMT solve, SolverOptions('JMT') restricted to what is read.
Definition solver_jmt.h:123
std::string method
default | jsim | jmva | jmva.<alg>
Definition solver_jmt.h:124
What jmt_prob_aggr reports: the system probability and the per-station ones.
Definition jmt_logs.h:779
std::vector< double > station
P(station i holds its declared per-class counts).
Definition jmt_logs.h:781
Transient averages over independent replications, on one time grid.
Definition jmt_logs.h:880
std::vector< double > t
Definition jmt_logs.h:881
std::vector< std::vector< std::vector< double > > > QNt
QNt[ist-1][r] over t.
Definition jmt_logs.h:883
The result of a JMT solve: the shared AvgResult plus what only JMT reports.
Definition solver_jmt.h:828
The system trajectory: one per-class block per station, on a common grid.
Definition jmt_logs.h:483
The knobs of one LDES run.
std::vector< std::vector< std::size_t > > busy_period_subnets
–busyperiod-subnet, zero-based station indexes, one flag per set.
int busy_period_orders
–busyperiod: highest busy period order measured, 0 disabling the measurement.
One measured busy period target (–busyperiod): a station, a station-class pair, or a declared station...
std::vector< std::size_t > stations
station indexes, zero-based
One ldes-result document, parsed.
std::vector< std::vector< Matrix< double > > > QNt
[STATION][class] -> (npoints x 2), columns [value, time].
std::vector< std::vector< std::vector< double > > > respTimeSamples
[station][class] -> the per-job response times the engine recorded, in departure order.
Matrix< double > traj_space
Matrix< double > histogram_space
The exact joint-state residence-time histogram (–export-histogram).
Matrix< double > traj_time
std::vector< BusyPeriodTarget > busy_periods
Matrix< double > jobDepartures
[id, station, class, time] of every departure of a tagged init_jobs job (track_jobs).
Matrix< double > histogram_time
std::vector< double > t
the time vector, empty on a steady-state run
Matrix< double > finalJobs
The jobs present at the end of the run, in the init_jobs layout (track_jobs).
One exact sample path as sample, sampleAggr, sampleSys and sampleSysAggr return it,...
Matrix< double > state
The blocks side by side, the single matrix ssa::SsaSamplePath::state is.
std::vector< Matrix< double > > block
per node, rows aligned with t
std::vector< std::size_t > nodes
1-based node index of each block of state
Matrix< double > event
One row per event, [time, node, type, class, jobId, phase]: node and class 0-based as on the wire,...
bool aggregate
per-class counts rather than LINE State rows
std::vector< double > t
the step times, one per row
One constraint of a joint-state query: a station and the per-class job counts it is required to hold.
std::vector< double > counts
The layered result: per element, the mean measures.
Result of lossn_links.
Definition lossn_links.h:62
std::vector< T > Loss
(R) route loss probability, as the chosen method gives it
Definition lossn_links.h:65
Matrix< T > E
(J x R) blocking of route r by link j alone; 0 where A(j,r) = 0
Definition lossn_links.h:63
std::vector< T > Occ
(J) mean number of busy units on link j
Definition lossn_links.h:64
Options of lossn_mci, MATLAB's options struct.
Definition lossn_mci.h:77
SolverLQNS.defaultOptions on a flat Network plus the knobs the JMVA document carries.
The options SolverMAM reads.
Definition mam_types.h:30
The metrics getAvg returns, after filtering.
Matrix< T > TN
throughput
Matrix< T > RN
response time, per visit
Matrix< T > UN
utilization
Matrix< T > WN
residence time, per job
std::string method
the method asked for
Matrix< T > QN
queue length
Matrix< T > AN
arrival rate
The options SolverMVA reads.
Definition mva_types.h:32
Avg.Tard (stations x classes, queue row filled) and Avg.SysTard (1 x classes).
Controls, defaulting to SolverOptions('NC') in the reference.
Definition nc_types.h:35
What State.toMarginal returns for one station and one state row.
Definition state.h:56
std::vector< T > nir
jobs per class
Definition state.h:58
Every Cache node of the model, in node order; empty on a model with none.
std::vector< CacheNodeMetrics< T > > caches
One Cache node's measured behaviour.
std::vector< T > hitprob
(K) TRUE hit fraction, EMPTY = not computed
The station- or node-level table aggregated by chain.
Matrix< T > TN
(rows x nchains), rows = stations or nodes
self.result.FJ: one row per Fork/Join pair, one column per class.
Definition fj_metrics.h:43
self.result.LossN.
Definition lossn_info.h:39
std::string method
chosen method: exact, rec, erlangfp, asy or mci
Definition lossn_info.h:45
std::uint64_t seed
mci seed of the run
Definition lossn_info.h:47
std::vector< std::string > links
(J) link names, in row order
Definition lossn_info.h:44
Matrix< double > A
(J x K) rows of the admission rule
Definition lossn_info.h:42
std::vector< double > C
(J) capacities
Definition lossn_info.h:43
std::size_t samples
mci sample count of the run (0 = not mci)
Definition lossn_info.h:46
std::vector< double > nu
(K) offered load per class
Definition lossn_info.h:41
The caller-facing map_env knobs, options.config.map_env and friends.
What the gate decided, and what it decided it about.
@@NetworkSolver/getAvgSys: one response time and one throughput per chain.
std::vector< T > XN
(nchains) system throughput at the reference station
std::vector< T > CN
(nchains) system response time, i.e. the cycle time
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