LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
lqns_qnsolver.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 */
5#ifndef LINE_SOLVERS_WRAPPERS_LQNS_LQNS_QNSOLVER_H
6#define LINE_SOLVERS_WRAPPERS_LQNS_LQNS_QNSOLVER_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * The flat-Network path of `@@SolverLQNS`: its qns methods, served by `qnsolver`
12 * of the RADS/LQNS distribution, the way SolverJMT reaches JMVA. MATLAB keeps
13 * it in `@@SolverLQNS/runAnalyzerNetwork.m` and `solver_qns.m`.
14 *
15 * `lqns::SolverLQNS<T>` remains the LqnModel solver; a flat Network reaches
16 * the same solver name through the free functions here
17 * (`solve_network_run_analyzer`, `qns_methods`, `qns_method_refusal`).
18 *
19 * WHY A WRAPPER IS PORTED AT ALL. Every other solver in `cpp/` computes its own
20 * answer; this one marshals the model to an external binary and reads the
21 * numbers back. It earns its place for the same reason it does in the other
22 * three codebases: `qnsolver` is an INDEPENDENT implementation of the multiserver
23 * AMVA lineage that `solver_mva` also implements, so it is the cross-check that
24 * catches an error common to the port and its reference. It is the only external
25 * tool in `cpp/`: LINE ships no copy of it, and every path here refuses by name
26 * when the binary is absent rather than answering natively under the LQNS label.
27 *
28 * WHAT THE PORT COVERS. The reference dispatches two ways (`runAnalyzerNetwork.m`):
29 *
30 * - product-form, or any model with open classes -> marshal to JMVA, run
31 * `qnsolver`, parse and de-aggregate. THIS IS PORTED, in full.
32 * - non-product-form closed -> convert with `QN2LQN` and delegate to
33 * `SolverLQNS`. This is the same layered path as MATLAB and the JAR; LINE
34 * still ships no LQNS binary, so its ordinary availability diagnostic is
35 * preserved when the external tool is absent.
36 *
37 * METHODS. On a Network the method names are `default` and `qns` (the default
38 * approximation, rolia) and `qns.NAME`, which selects approximation NAME; the
39 * engine below speaks the bare NAME. `conway`, `reiser`, `rolia` and `zhou` are
40 * what `qnsolver -m` accepts, and they only take effect on a model that HAS a
41 * multiserver station -- the reference passes no `-m` otherwise, and so does
42 * this. `suri` and `schmidt` reach the tool through the LQNS branch on a
43 * non-product-form closed model.
44 *
45 * REFERENCES, per method:
46 * - `conway`: Conway (1989), extending the multinomial all-servers-busy probability of de Souza e Silva and Muntz (Perform. Eval. 7(3), 1987).
47 * - `rolia`: Rolia (PhD thesis, Toronto, 1992) as used in the method of layers (Rolia and Sevcik, IEEE TSE 21(8), 1995), in the per-class Rolia-Franks form of Franks (PhD thesis, Carleton, 1999).
48 * - `zhou`: arrival-theorem binomial (AB) approximation, S. Zhou (M.A.Sc. thesis, Carleton, 2021) and Zhou and Woodside (ICPE Companion 2022).
49 * - `suri`: Suri, Sahu and Vernon (IERC 2007).
50 * - `reiser`: Reiser and Lavenberg (J. ACM 27(2), 1980) load-dependent MVA, see also Reiser (Perform. Eval. 1, 1981).
51 * - `schmidt`: Schmidt (Perform. Eval. 29(4), 1997).
52 */
53
55#include <algorithm>
56#include <cctype>
57#include <cmath>
58#include <cstdlib>
59#include <fstream>
60#include <limits>
61#include <sstream>
62#include <string>
63#include <vector>
64
65#include "line/io/jmva_writer.h"
66#include "line/io/qn2lqn.h"
72#include "line/util/error.h"
75#include "line/util/tempdir.h"
76
77namespace line {
78namespace lqns {
79
80/** `SolverLQNS.defaultOptions` on a flat Network plus the knobs the JMVA document carries. */
81struct QnsOptions {
82 /** `default`, `qns` or `qns.NAME`; see qns_methods(). */
83 std::string method = "default";
84 /**
85 * `options.config.multiserver`. Kept separate from `method` because the
86 * reference lets either name the approximation: `method` sets it, and a
87 * caller may set it directly while leaving the method at 'default'.
88 */
89 std::string multiserver;
90 std::size_t samples = 10000; ///< `options.samples`, the JMVA maxSamples
91 /** Seconds before a hung `qnsolver` is killed; not positive waits forever. */
92 int timeout = 0;
93 /** `options.keep`: leave the scratch directory behind, to inspect what was sent. */
94 bool keep = false;
95};
96
97/** Port of `SolverLQNS.listValidMethods` on a flat Network. */
98inline std::vector<std::string> qns_methods() {
99 return {"default", "qns", "qns.conway", "qns.rolia",
100 "qns.zhou", "qns.suri", "qns.reiser", "qns.schmidt"};
101}
102
103/** True for `qns` and every `qns.NAME`. */
104inline bool is_qns_method(const std::string& method) {
105 std::string m = method;
106 std::transform(m.begin(), m.end(), m.begin(),
107 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
108 return m == "qns" || m.compare(0, 4, "qns.") == 0;
109}
110
111/**
112 * The multiserver approximation a Network method selects: the part after
113 * `qns.`, or `default` for `default` and `qns`. This bare name is what the
114 * engine speaks, and what the JMVA document and the `-m` switch carry.
115 */
116inline std::string qns_multiserver(const std::string& method) {
117 std::string m = method;
118 std::transform(m.begin(), m.end(), m.begin(),
119 [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
120 return m.compare(0, 4, "qns.") == 0 ? m.substr(4) : std::string("default");
121}
122
123/** The approximations `qnsolver -m` accepts; the rest reach it only via LQNS. */
124inline bool is_qnsolver_multiserver(const std::string& m) {
125 return m == "conway" || m == "reiser" || m == "rolia" || m == "zhou";
126}
127
128/**
129 * `SolverLQNS.supportsModelMethod`'s structural rules on a Network, as the REASON they refuse,
130 * empty when the pair is served.
131 *
132 * A STRING RATHER THAN A THROW, the shape `ba::method_refusal` and
133 * `ag::runner_detail::method_refusal` already carry: the AUTO report has to ASK
134 * the question without raising, so that a pair it offers is a pair the run
135 * accepts. `solve_network_run_analyzer` keeps the throws, which are the same two
136 * rules stated where the run reaches them.
137 *
138 * Mirrors matlab/src/solvers/wrappers/LQNS/qns_immfeed_refusal.m and
139 * qns_multiserver_refusal.m, and the JAR's qnsImmfeedRefusal /
140 * qnsMultiserverRefusal.
141 */
142template <class T>
143std::string qns_method_refusal(const qn::NetworkStruct<T>& L, const std::string& method) {
145 return "SolverLQNS does not support immediate feedback (sn.immfeed): neither the JMVA "
146 "document qnsolver reads nor the LQN QN2LQN writes can keep a self-looping job on "
147 "its server. Use SolverCTMC or SolverSSA, whose state space carries the self-loop.";
148
149 // THE RULE IS INSIDE THE MULTISERVER BRANCH: without a multiserver station
150 // no -m is emitted and every method name is served by the plain invocation.
151 bool has_multiserver = false;
152 for (std::size_t i = 0; i < L.nstations && !has_multiserver; ++i) {
153 const double c = L.stations[i].nservers;
154 if (std::isfinite(c) && c > 1.0) has_multiserver = true;
155 }
156 if (!has_multiserver) return std::string();
157 const std::string ms = qns_multiserver(method);
158 if (ms == "default" || is_qnsolver_multiserver(ms)) return std::string();
159 return "SolverLQNS: the multiserver approximation '" + ms +
160 "' is one LQNS offers and qnsolver does not: 'qnsolver -m' accepts conway, reiser, "
161 "rolia and zhou only; suri and schmidt are available only on the non-product-form "
162 "closed SolverLQNS branch.";
163}
164
165namespace detail {
166
167/**
168 * The argv prefix every invocation uses.
169 *
170 * LD_LIBRARY_PATH IS STRIPPED, as `solver_qns.m` does on unix: the binaries of
171 * the LQNS distribution are linked against the system libstdc++, and a
172 * LD_LIBRARY_PATH inherited from a host that ships its own (MATLAB does) makes
173 * them fail to load on a GLIBCXX version symbol. Doing it through `env -u`
174 * rather than by editing this process's environment keeps the change confined to
175 * the child.
176 */
177inline std::vector<std::string> qnsolver_argv() {
178 return {"env", "-u", "LD_LIBRARY_PATH", "qnsolver"};
179}
180
181} // namespace detail
182
183/**
184 * Port of `SolverLQNS.hasQnsolver`: a native `qnsolver` binary on the PATH.
185 *
186 * There is no container fallback, here as in the other three codebases: qnsolver
187 * ships with LQNS, whose licence forbids providing the software to another
188 * party, so no LINE code path resolves or runs an image carrying it.
189 */
191 std::vector<std::string> argv = detail::qnsolver_argv();
192 argv.push_back("--help");
193 const util::ProcResult r = util::capture(argv, 30);
194 return r.exitCode == 0;
195}
196
197/** Port of `runAnalyzerNetwork`'s method gate. */
198inline void check_qns_method(const std::string& method) {
199 const std::vector<std::string> valid = qns_methods();
200 if (std::find(valid.begin(), valid.end(), method) == valid.end())
201 throw InputError("SolverLQNS: unknown method '" + method +
202 "' on a Network; valid methods are default, qns, qns.conway, qns.rolia, "
203 "qns.zhou, qns.suri, qns.reiser, qns.schmidt");
204}
205
206/**
207 * Port of the method -> `options.config.multiserver` map of `runAnalyzerNetwork.m`.
208 * Either spelling of the method is taken: the qns name or the bare name the
209 * engine speaks.
210 *
211 * `default` resolves to `rolia`, as `runAnalyzerNetwork.m` does. THE REFERENCE HAS TWO
212 * ENTRY POINTS AND THEY DISAGREE on an explicit config: `runAnalyzerNetwork.m`
213 * overwrites `options.config.multiserver` unconditionally at method `default`,
214 * so a MATLAB caller who sets it through the solver constructor is silently
215 * ignored, while `solver_qns.m` called directly honours it and maps its own
216 * `default` to CONWAY. This resolves the pair the only way that is a superset of
217 * neither: the method wins when named, an explicit config is honoured (the
218 * low-level reference's behaviour, and the only way a caller can express the
219 * choice at all), and an unset one gives rolia (the high-level reference's).
220 * Native Python currently leaves `default` at CONWAY here, which is a genuine
221 * divergence from MATLAB and the JAR; see the report accompanying this audit.
222 */
223inline std::string resolve_multiserver(const QnsOptions& opt) {
224 const std::string bare = is_qns_method(opt.method) ? qns_multiserver(opt.method) : opt.method;
225 if (bare != "default") return bare;
226 if (!opt.multiserver.empty()) return opt.multiserver;
227 return "rolia";
228}
229
230namespace detail {
231
232/** One parsed data row of the `qnsolver` CSV output. */
233struct ParsedRow {
234 std::string station;
235 std::vector<double> Q, W, U, Tp;
236};
237
238inline double parse_double_or_zero(const std::string& s) {
239 if (s.empty()) return 0.0;
240 char* end = nullptr;
241 const double v = std::strtod(s.c_str(), &end);
242 if (end == s.c_str()) return 0.0;
243 return v;
244}
245
246/**
247 * Split a `qnsolver` result row into its four metric blocks.
248 *
249 * THE STRIDE IS DECIDED BY THE CHAIN COUNT, not the class count. `qnsolver`
250 * writes a per-chain column followed by an aggregate one for each of Q, R, U and
251 * X when there is more than one chain, and drops the aggregate entirely at one
252 * chain -- confirmed against the binary: one chain gives
253 * `Station, $Q, $R, $U, $X` and two give `$Q(Chain01), $Q(Chain02), $Q, ...`.
254 * MATLAB and the JAR both switch on `sn.nclasses == 1`, which agrees only while
255 * classes and chains are in bijection: a class-switching model with two classes
256 * folded into ONE chain takes their multi-class branch against a single-chain
257 * document, and reads the $U column as the residence time (the JAR's length
258 * guard turns the same case into an all-zero table instead).
259 */
260inline bool parse_row(const std::string& line, std::size_t nchains, ParsedRow* out) {
261 if (line.find(',') == std::string::npos) return false;
262 if (line.find('$') != std::string::npos) return false; // the header
263 std::string s;
264 for (std::size_t i = 0; i < line.size(); ++i)
265 if (line[i] != ' ' && line[i] != '\t' && line[i] != '\r') s += line[i];
266
267 std::vector<std::string> parts;
268 std::size_t b = 0;
269 while (true) {
270 const std::size_t j = s.find(',', b);
271 parts.push_back(s.substr(b, j == std::string::npos ? j : j - b));
272 if (j == std::string::npos) break;
273 b = j + 1;
274 }
275 const std::size_t stride = nchains == 1 ? 1 : nchains + 1;
276 if (parts.size() < 1 + 4 * stride) return false;
277
278 out->station = parts[0];
279 out->Q.assign(nchains, 0.0);
280 out->W.assign(nchains, 0.0);
281 out->U.assign(nchains, 0.0);
282 out->Tp.assign(nchains, 0.0);
283 std::size_t ptr = 1;
284 for (std::size_t c = 0; c < nchains; ++c) out->Q[c] = parse_double_or_zero(parts[ptr + c]);
285 ptr += stride;
286 for (std::size_t c = 0; c < nchains; ++c) out->W[c] = parse_double_or_zero(parts[ptr + c]);
287 ptr += stride;
288 for (std::size_t c = 0; c < nchains; ++c) out->U[c] = parse_double_or_zero(parts[ptr + c]);
289 ptr += stride;
290 for (std::size_t c = 0; c < nchains; ++c) out->Tp[c] = parse_double_or_zero(parts[ptr + c]);
291 return true;
292}
293
294} // namespace detail
295
296/**
297 * The gate `runAnalyzer.m` reaches through `runAnalyzerChecks`, narrowed to what
298 * the JMVA document can actually carry.
299 *
300 * The reference's feature set admits nodes -- a Cache, a Place, a Transition --
301 * that `writeJMVA` then drops on the floor, and the tool answers a SMALLER model
302 * than the caller handed it with no indication that it did. A station the
303 * document cannot express is refused by name here instead.
304 */
305template <class T>
307 for (std::size_t i = 0; i < L.nstations; ++i) {
308 const qn::NodeType nt = L.stations[i].nodetype;
309 if (nt == qn::NodeType::Queue || nt == qn::NodeType::Delay ||
310 nt == qn::NodeType::Source)
311 continue;
312 throw UnsupportedError(ErrorKind{"NodeType"},
313 "SolverLQNS: station '" + L.nodes[L.station_to_node[i] - 1].name +
314 "' is not a Queue, a Delay or a Source, and the JMVA document qnsolver reads "
315 "carries no other station type");
316 }
317 if (L.has_priorities())
318 throw UnsupportedError(ErrorKind{"Priority"},
319 "SolverLQNS: class priorities are outside the product-form envelope qnsolver "
320 "evaluates");
321}
322
323namespace detail {
324
325/**
326 * The engine of `solve_network_run_analyzer`: `solver_qns.m` and the QN2LQN
327 * branch of `runAnalyzerNetwork.m`, speaking the BARE approximation name in
328 * `opt.method` (`default`, `conway`, ...), which is what reaches the JMVA
329 * document and the `-m` switch.
330 */
331template <class T>
332mva::AvgResult<T> qnsolver_engine(const qn::NetworkStruct<T>& L, const QnsOptions& opt) {
333 // NOTHING under the qns path reads `sn.cap` or `sn.classcap`, on EITHER of
334 // the two routes below: the JMVA document is read by `qnsolver`, whose
335 // MVA-family algorithms have no representation of a finite buffer, and the
336 // QN2LQN route hands the model to LQNS, which has none either. A capped
337 // station was therefore solved as an unbounded one and the table reported
338 // the unconstrained answer under this solver's name. There is no
339 // feature-registry name for plain capacity, hence the structural test --
340 // `SolverMVA`, `SolverNC`, `SolverAG` and `SolverFLD` gate the same way,
341 // through this same helper. It sits HERE rather than in `check_supported`,
342 // which is deliberately the narrower JMVA-document gate and is skipped on
343 // the layered route.
344 qn::check_binding_capacity("SolverLQNS", L);
345
346 // IMMEDIATE FEEDBACK keeps a self-looping job on its server instead of
347 // re-queueing it, and neither path below can state that: the JMVA document
348 // `qnsolver` reads carries a mean demand and a visit count per chain, and
349 // the LQN `qn2lqn` writes turns the routing into OR-fork precedences of
350 // pseudo-activities on the reference task, where a repeated visit is a NEW
351 // CALL. Either would answer for re-queueing under this solver's name.
352 // SolverMVA warns and solves on the same property; here it is a refusal
353 // because the two conversions cannot represent the self-loop at all.
354 // Mirrors matlab/src/solvers/wrappers/LQNS/qns_immfeed_refusal.m.
356 throw UnsupportedError(ErrorKind{"ImmediateFeedback"},
357 "SolverLQNS does not support immediate feedback (sn.immfeed): neither the JMVA "
358 "document qnsolver reads nor the LQN QN2LQN writes can keep a self-looping job on "
359 "its server. Use SolverCTMC or SolverSSA, whose state space carries the self-loop.");
360
361 const std::size_t M = L.nstations, K = L.nclasses, C = L.nchains;
362
363 bool has_open = false;
364 for (std::size_t k = 0; k < K; ++k)
365 if (!std::isfinite(L.classes[k].population)) has_open = true;
366
367 if (!L.has_product_form() && !has_open) {
368 if (L.has_priorities())
369 throw UnsupportedError(ErrorKind{"Priority"},
370 "SolverLQNS: class priorities are outside the QN2LQN conversion envelope");
371
372 const lqn::LqnModel<T> layered = io::qn2lqn(L);
373 LqnsOptions lo;
374 lo.multiserver = resolve_multiserver(opt);
375 lo.samples = static_cast<double>(opt.samples);
376 lo.keep = opt.keep;
377 lo.timeout_seconds = opt.timeout;
378 SolverLQNS<T> solver(layered, lo);
379 const LqnsSolution<T> ls = solver.get_ensemble_avg();
380 const lqn::LqnStruct<T>& lsn = solver.get_struct();
381 const T zero = num_traits<T>::from_int(0);
382 Matrix<T> Q(M, K, zero), U(M, K, zero), R(M, K, zero), Tp(M, K, zero);
383
384 const auto element = [&](const std::string& name, lqn::LqnElement kind) {
385 for (std::size_t idx = 1; idx <= lsn.nidx; ++idx)
386 if (lsn.type[idx] == kind && lsn.names[idx] == name) return idx;
387 return std::size_t(0);
388 };
389 for (std::size_t i = 0; i < M; ++i) {
390 const std::size_t node = L.station_to_node[i] - 1;
391 const qn::NodeType type = L.nodes[node].nodetype;
392 if (type != qn::NodeType::Queue && type != qn::NodeType::Delay) continue;
393 for (std::size_t r = 0; r < K; ++r) {
394 const std::string suffix = std::to_string(node + 1) + "_" +
395 std::to_string(r + 1);
396 const std::size_t a = element("Q" + suffix, lqn::LqnElement::ACTIVITY);
397 if (a == 0) continue; // the class does not visit this station
398 if (ls.defined_Q[a]) Q(i, r) = ls.QN[a];
399 if (ls.defined_U[a]) U(i, r) = ls.UN[a];
400 if (ls.defined_R[a]) R(i, r) = ls.RN[a];
401 if (ls.defined_T[a]) Tp(i, r) = ls.TN[a];
402
403 // Some LQNS releases omit activity utilization/throughput but
404 // report the bound entry phase. The JAR carries the same
405 // fallback, and it changes no value when the activity row is
406 // present.
407 const std::size_t e = element("E" + suffix, lqn::LqnElement::ENTRY);
408 if (e != 0 && !ls.defined_U[a] && ls.defined_U[e]) U(i, r) = ls.UN[e];
409 if (e != 0 && !ls.defined_T[a] && ls.defined_T[e]) Tp(i, r) = ls.TN[e];
410
411 // SolverLQNS reports busy servers over the host servers the work can
412 // reach (host_reach_mult), a Network station reports it per server.
413 U(i, r) = T(U(i, r) * num_traits<T>::from_double(lsn.host_reach_mult(a)));
414 const double servers = L.stations[i].nservers;
415 if (std::isfinite(servers) && servers > 0.0)
416 U(i, r) = T(U(i, r) / num_traits<T>::from_double(servers));
417 }
418 }
419
420 mva::AvgResult<T> out;
421 out.QN = mva::filter_metric(L, Q, mva::MetricKind::QLen, nullptr);
422 out.UN = mva::filter_metric(L, U, mva::MetricKind::Util, nullptr);
423 out.RN = mva::filter_metric(L, R, mva::MetricKind::RespT, nullptr);
424 out.TN = mva::filter_metric(L, Tp, mva::MetricKind::Tput, nullptr);
425 out.AN = mva::filter_metric(L, mva::sn_get_arvr_from_tput(L, out.TN),
426 mva::MetricKind::ArvR, nullptr);
427 // runAnalyzer.m ultimately passes an empty residence-time table to
428 // setAvgResults, which derives it from response time and visits.
430 mva::MetricKind::ResidT, nullptr);
431 out.CN.clear();
432 out.XN.clear();
433 out.method = opt.method;
434 const std::string actual = resolve_multiserver(opt);
435 out.actualmethod = opt.method == "default" ? ("default/" + actual) : actual;
436 out.iter = ls.iterations;
437 return out;
438 }
439
440 // This is the narrower capability gate of the JMVA document. The layered
441 // path above legitimately contains routing and Join nodes that JMVA cannot
442 // encode, so applying it before dispatch would reject the very models
443 // QN2LQN exists to convert.
445
446 const std::string ms = resolve_multiserver(opt);
447
448 // The reference passes -m only when a multiserver station is present, so a
449 // single-server model answers identically under every method name.
450 bool has_multiserver = false;
451 for (std::size_t i = 0; i < M; ++i) {
452 const double c = L.stations[i].nservers;
453 if (std::isfinite(c) && c > 1.0) has_multiserver = true;
454 }
455
456 // THE GATE BELONGS INSIDE THE MULTISERVER BRANCH, because that is the only
457 // branch the approximation reaches. Without a multiserver station the
458 // reference emits no -m at all and answers under the caller's method name,
459 // so refusing 'suri' there would refuse a model the reference solves; with
460 // one, `solver_qns.m` falls off its switch and leaves `cmd` unassigned,
461 // which is an undefined-variable error rather than a diagnosis.
462 if (has_multiserver && !is_qnsolver_multiserver(ms))
463 throw UnsupportedError(ErrorKind{"Method"},
464 "SolverLQNS: the multiserver approximation '" + ms +
465 "' is one LQNS offers and qnsolver does not: 'qnsolver -m' accepts conway, reiser, "
466 "rolia and zhou only; suri and schmidt are available only on the non-product-form "
467 "closed SolverLQNS branch");
468
470 throw UnsupportedError(ErrorKind{"LQNS"},
471 "SolverLQNS needs the external 'qnsolver' binary on the PATH. It ships with LQNS "
472 "(http://www.sce.carleton.ca/rads/lqns/); LINE distributes no copy and runs none "
473 "from a container image, because that licence forbids redistribution");
474
475 util::TempDir tmp("qns");
476 if (opt.keep) tmp.keep();
477 const std::string model_file = tmp.file("model.jmva");
478 const std::string result_file = tmp.file("result.jmva");
479 line::util::LineConsole::step("writing the JMVA model file");
480 io::write_jmva(L, model_file, opt.method, opt.samples);
481
482 std::vector<std::string> argv = detail::qnsolver_argv();
483 // `-l` IS `--linearizer`, AND IT TAKES NO ARGUMENT: `qnsolver --help` lists
484 // it beside `-e, --exact-mva` and `-s, --schweitzer` as a solver selector,
485 // and the input file is POSITIONAL. So this line does not mean "load the
486 // model" -- it selects Linearizer and lets the model file fall through as
487 // the positional argument. All four codebases emit it, so they agree, and
488 // that agreement is on LINEARIZER results rather than on the exact MVA
489 // qnsolver runs by default. Left as it is deliberately: changing it changes
490 // every qnsolver number in every codebase at once, which is the user's call.
491 argv.push_back("-l");
492 argv.push_back(model_file);
493 if (has_multiserver) argv.push_back("-m" + ms);
494 argv.push_back("-o");
495 argv.push_back(result_file);
496
497 line::util::LineConsole::step("running the qnsolver binary as a subprocess");
498 const util::ProcResult pr = util::capture(argv, util::timeout_kill_bound(opt.timeout));
499 if (pr.timedOut) util::timeout_raise_if_killed_on_budget("SolverLQNS: qnsolver");
500 if (pr.timedOut)
501 throw ExternalError(ErrorKind{"LQNS"}, "SolverLQNS: qnsolver did not finish within " +
502 std::to_string(opt.timeout) + "s and was killed");
503 if (pr.exitCode != 0)
504 throw ExternalError(ErrorKind{"LQNS"}, "SolverLQNS: qnsolver exited with code " +
505 std::to_string(pr.exitCode) +
506 (pr.out.empty() ? std::string() : ("\n" + pr.out)));
507
508 // ---- parse the chain-level table -------------------------------------
509 line::util::LineConsole::step("parsing the qnsolver output");
510 const T zero = num_traits<T>::from_int(0);
511 Matrix<T> Qchain(M, C, zero), Uchain(M, C, zero), Wchain(M, C, zero), Tchain(M, C, zero);
512 std::ifstream in(result_file.c_str());
513 if (!in)
514 // qnsolver exits 0 on a parse error, so the exit-code branch above never fires and its
515 // own message is the only evidence of what it rejected. Carry it here or a build that
516 // cannot read an <ldstation> reads as an unexplained missing file.
517 throw ExternalError(ErrorKind{"LQNS"}, "SolverLQNS: qnsolver wrote no result file at '" + result_file + "'" +
518 (pr.out.empty() ? std::string() : ("\nqnsolver said: " + pr.out)));
519 std::string line;
520 std::size_t nrows = 0;
521 while (std::getline(in, line)) {
522 detail::ParsedRow row;
523 if (!detail::parse_row(line, C, &row)) continue;
524 std::size_t idx = M;
525 for (std::size_t i = 0; i < M; ++i)
526 if (L.nodes[L.station_to_node[i] - 1].name == row.station) {
527 idx = i;
528 break;
529 }
530 if (idx == M) continue; // a station qnsolver names and the model does not
531 for (std::size_t c = 0; c < C; ++c) {
532 Qchain(idx, c) = num_traits<T>::from_double(row.Q[c]);
533 Wchain(idx, c) = num_traits<T>::from_double(row.W[c]);
534 Uchain(idx, c) = num_traits<T>::from_double(row.U[c]);
535 Tchain(idx, c) = num_traits<T>::from_double(row.Tp[c]);
536 }
537 ++nrows;
538 }
539 if (nrows == 0)
540 throw ExternalError(ErrorKind{"LQNS"},
541 "SolverLQNS: qnsolver produced no station rows this model recognises; its output "
542 "names no station of the model");
543
544 const mva::ChainDemands<T> d = mva::sn_get_demands_chain(L);
545
546 // ---- chain throughput at the reference station -----------------------
547 // THE REFERENCE STATION IS READ PER CHAIN, through the chain's first class.
548 // MATLAB and the JAR index `sn.refstat` -- a per-CLASS array -- with the
549 // chain number, which lands on an unrelated class's reference station as
550 // soon as class switching makes the two index spaces differ.
551 std::vector<T> Xchain(C, zero);
552 for (std::size_t c = 0; c < C; ++c) {
553 const std::size_t rstat = L.classes[L.inchain[c][0] - 1].refstat;
554 if (Tchain(rstat - 1, c) > zero) {
555 Xchain[c] = Tchain(rstat - 1, c);
556 continue;
557 }
558 // An open chain's reference station is the Source, which the JMVA
559 // document does not carry, so its row is zero; recover X from any
560 // station whose visit count is known.
561 for (std::size_t i = 0; i < M; ++i)
562 if (d.Vchain(i, c) > zero && Tchain(i, c) > zero) {
563 Xchain[c] = T(Tchain(i, c) / d.Vchain(i, c));
564 break;
565 }
566 }
567
568 // The Source is not written to the JMVA file, so qnsolver reports no row for it and its
569 // chain throughput read 0: the Source row vanished and every ArvR derived from it was 0.
570 for (std::size_t c = 0; c < C; ++c)
571 for (std::size_t i = 0; i < M; ++i)
572 if (Tchain(i, c) == zero && d.Vchain(i, c) > zero)
573 Tchain(i, c) = T(Xchain[c] * d.Vchain(i, c));
574
575 // `Rchain = Wchain` of solver_qns.m: qnsolver's $R column is already the
576 // per-visit residence at the station, so it is not divided by the visits.
577 Matrix<T> Rchain = Wchain;
578 for (std::size_t i = 0; i < M; ++i)
579 for (std::size_t c = 0; c < C; ++c)
580 if (std::isnan(num_traits<T>::to_double(Rchain(i, c)))) Rchain(i, c) = zero;
581
582 // Utilization comes back summed over the servers of a multiserver station,
583 // which the ld encoding of writeJMVA turns it into; LINE reports it per
584 // server.
585 for (std::size_t i = 0; i < M; ++i) {
586 const double c = L.stations[i].nservers;
587 if (!std::isfinite(c)) continue;
588 for (std::size_t j = 0; j < C; ++j)
589 Uchain(i, j) = T(Uchain(i, j) / num_traits<T>::from_double(c));
590 }
591
592 const mva::ClassResults<T> cr =
593 mva::sn_deaggregate_chain_results(L, d, Qchain, Uchain, Rchain, Tchain, Xchain);
594
595 mva::AvgResult<T> out;
596 out.QN = mva::filter_metric(L, cr.Q, mva::MetricKind::QLen, nullptr);
597 out.UN = mva::filter_metric(L, cr.U, mva::MetricKind::Util, nullptr);
598 out.RN = mva::filter_metric(L, cr.R, mva::MetricKind::RespT, nullptr);
599 out.TN = mva::filter_metric(L, cr.Tp, mva::MetricKind::Tput, nullptr);
600 std::vector<std::vector<bool>> srcmask(M, std::vector<bool>(K, false));
601 for (std::size_t i = 0; i < M; ++i)
602 if (L.stations[i].nodetype == qn::NodeType::Source)
603 for (std::size_t k = 0; k < K; ++k) srcmask[i][k] = true;
605 &srcmask);
606 // MATLAB passes [] for the residence time and lets `getAvg` derive it from
607 // the response time and the visits, which is what this helper is; the JAR
608 // instead sets WN = RN, and the two agree only where the visit count is one.
610 mva::MetricKind::ResidT, nullptr);
611 out.CN = cr.C;
612 out.XN = cr.X;
613 out.method = opt.method;
614 // `default` is reported as 'default/<what ran>', the convention of
615 // runAnalyzer.m. Without a multiserver station no -m flag is passed, and the
616 // reference then leaves the label at the tool's own default.
617 const std::string ran = has_multiserver ? ms : std::string("default");
618 out.actualmethod = opt.method == "default" ? ("default/" + ran) : ran;
619 out.iter = 0;
620 return out;
621}
622
623} // namespace detail
624
625/**
626 * Port of `@@SolverLQNS/runAnalyzerNetwork.m` and `solver_qns.m`: SolverLQNS on
627 * a flat Network.
628 *
629 * The caller's qns method name is translated to the bare approximation name
630 * the engine speaks, and the engine's label is reported back under the qns
631 * names: `qns.NAME`, `default/qns.NAME` (a bare `default` stays as it is).
632 *
633 * @param L the refreshed struct
634 * @param opt the method, the multiserver rule and the JMVA sample cap
635 */
636template <class T>
638 check_qns_method(opt.method);
639 QnsOptions bare = opt;
640 bare.method = qns_multiserver(opt.method);
641 mva::AvgResult<T> out = detail::qnsolver_engine(L, bare);
642 out.method = opt.method;
643 std::string label = out.actualmethod;
644 std::string prefix;
645 if (label.compare(0, 8, "default/") == 0) {
646 prefix = "default/";
647 label = label.substr(prefix.size());
648 }
649 if (label != "default") label = "qns." + label;
650 out.actualmethod = prefix + label;
651 return out;
652}
653
654} // namespace lqns
655} // namespace line
656
657#endif // LINE_SOLVERS_WRAPPERS_LQNS_LQNS_QNSOLVER_H
ExternalError(const std::string &what)
Definition error.h:126
InputError(const std::string &what)
Definition error.h:105
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
bool has_immediate_feedback() const
Whether immediate feedback is EFFECTIVE anywhere in the model.
std::vector< JobClass > classes
std::vector< Station< T > > stations
stations[k-1] is the k-th station
std::vector< std::vector< std::size_t > > inchain
1-based class indices per chain
std::vector< NodeDef > nodes
every node, in creation order
bool has_product_form() const
sn_has_product_form, conjunct for conjunct.
std::vector< std::size_t > station_to_node
(nstations) 1-based node index
static void step(const char *fmt,...)
Write one progress line.
The exception types the port throws.
The language-feature gate: what a MODEL uses against what a SOLVER declares.
Port of @@JMTIO/writeJMVA.m: the CHAIN-level product-form model in the JMVA interchange format.
Running progress log of a LINE solver run (the "solver console").
options.timeout: one wall-clock budget per top-level solve, on a per-THREAD deadline stack.
lqn::LqnModel< T > qn2lqn(const qn::NetworkStruct< T > &sn)
Port of MATLAB QN2LQN(model), over the refreshed C++ NetworkStruct.
Definition qn2lqn.h:67
std::string write_jmva(const qn::NetworkStruct< T > &L, const std::string &path, const std::string &method, std::size_t samples)
Port of writeJMVA(sn, outputFileName, options).
LqnElement
LQN element kinds, with the values of MATLAB LayeredNetworkElement.
Definition lang_types.h:505
NodeType
Node kinds, with the values of MATLAB NodeType.
Definition lang_types.h:345
bool in(const std::string &s, std::initializer_list< const char * > set)
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.
void check_qnsolver_supported(const qn::NetworkStruct< T > &L)
The gate runAnalyzer.m reaches through runAnalyzerChecks, narrowed to what the JMVA document can actu...
std::vector< std::string > qns_methods()
Port of SolverLQNS.listValidMethods on a flat Network.
bool is_qnsolver_multiserver(const std::string &m)
The approximations qnsolver -m accepts; the rest reach it only via LQNS.
std::string qns_multiserver(const std::string &method)
The multiserver approximation a Network method selects: the part after qns.
std::string qns_method_refusal(const qn::NetworkStruct< T > &L, const std::string &method)
SolverLQNS.supportsModelMethod's structural rules on a Network, as the REASON they refuse,...
std::string resolve_multiserver(const QnsOptions &opt)
Port of the method -> options.config.multiserver map of runAnalyzerNetwork.m.
bool is_qns_method(const std::string &method)
True for qns and every qns.NAME.
void check_qns_method(const std::string &method)
Port of runAnalyzerNetwork's method gate.
bool qnsolver_is_available()
Port of SolverLQNS.hasQnsolver: a native qnsolver binary on the PATH.
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.
Matrix< T > filter_metric(const qn::NetworkStruct< T > &L, const Matrix< T > &metric, MetricKind kind, const std::vector< std::vector< bool > > *zero_mask)
Port of filterMetric: what @@NetworkSolver/getAvg does between the analyzer and the caller.
ClassResults< T > sn_deaggregate_chain_results(const qn::NetworkStruct< T > &L, const ChainDemands< T > &d, const Matrix< T > &Qchain, const Matrix< T > &Uchain, const Matrix< T > &Rchain, const Matrix< T > &Tchain, const std::vector< T > &Xchain)
Port of sn_deaggregate_chain_results.
Definition sn_chain.h:227
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...
ChainDemands< T > sn_get_demands_chain(const qn::NetworkStruct< T > &L)
Port of sn_get_demands_chain.
Definition sn_chain.h:63
void check_binding_capacity(const std::string &solver, const NetworkStruct< T > &sn)
NetworkSolver.checkBindingCapacity (NetworkSolver.m:1172-1228): the shared structural gate for finite...
ProcResult capture(const std::vector< std::string > &argv, int timeoutSeconds, bool mergeStderr=false)
Runs a command, capturing stdout and discarding stderr.
Definition subprocess.h:82
int timeout_kill_bound(int explicit_seconds, double grace=30.0)
The kill bound of a child that also has a bound of its OWN (explicit_seconds, not positive = none): t...
void timeout_raise_if_killed_on_budget(const std::string &who)
A child process was killed on its bound: raise LINE:numerical:Timeout when the armed budget is what r...
std::unique_ptr< Element > element(const std::string &tag)
A fresh detached element, the createElement of the write side.
Definition xml.h:299
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
Convert a closed queueing network into the layered model used by SolverLQNS.
Chain aggregation and de-aggregation.
SolverLQNS: the layered model solved by the external lqns / lqsim binaries.
The SolverMVA class surface: @@SolverMVA/runAnalyzer.m and the gates around it.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
SolverLQNS.defaultOptions on a flat Network plus the knobs the JMVA document carries.
std::size_t samples
options.samples, the JMVA maxSamples
int timeout
Seconds before a hung qnsolver is killed; not positive waits forever.
bool keep
options.keep: leave the scratch directory behind, to inspect what was sent.
std::string multiserver
options.config.multiserver.
std::string method
default, qns or qns.NAME; see qns_methods().
The metrics getAvg returns, after filtering.
std::string method
the method asked for
std::string actualmethod
the algorithm that ran
Outcome of a captured command.
Definition subprocess.h:42
int exitCode
Exit status, or -1 when the command could not run.
Definition subprocess.h:43
Running an external command and capturing its output, with a deadline.
A scratch directory for the subprocess wrappers, the port's lineTempName.