LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_ldes.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_LDES_SOLVER_LDES_H
6#define LINE_SOLVERS_WRAPPERS_LDES_SOLVER_LDES_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * Port of `SolverLDES`, the discrete-event simulator, as its C++ client.
12 *
13 * WHAT IS PORTED, AND WHY IT IS A CLIENT AND NOT AN ENGINE. LDES has ONE
14 * implementation, `jar/src/main/java/jline/solvers/wrappers/ldes/` (~25 kLOC on SSJ),
15 * and every codebase that is not the JAR reaches it the same way: MATLAB
16 * (`@@SolverLDES/solveCli.m`) and native Python
17 * (`wrappers/solver_ldes/solver_ldes.py`) serialize the model to `model.json`,
18 * run `solve model.json -o result.json` as a subprocess and parse the result
19 * document back. Nothing is marshalled in process. This file is the third such
20 * client, and it is the port of SolverLDES for the same reason those two are:
21 * a second simulator would answer with different numbers under the same name,
22 * and "LDES agrees across the codebases" -- which the parity harness checks and
23 * `CLAUDE.md` states as an invariant -- is a property of there being ONE engine.
24 *
25 * THE PRIMARY ENTRY IS A DOCUMENT, not a model object, and that is a deliberate
26 * difference from the two other clients. They hold a live model and serialize
27 * it; `solver_ldes_text` / `solver_ldes_file` are given the `model.json`
28 * DOCUMENT and forward its bytes UNCHANGED. There is a writer
29 * (`io/network_writer.h`), so a round trip through `qn::NetworkStruct<T>` is
30 * possible -- `solver_ldes` below is exactly that, for a caller who built the
31 * model in C++ -- but the reader that would have to parse the document first is
32 * deliberately scoped to the subset the analytical solvers read, so making the
33 * trip MANDATORY would degrade exactly the models LDES exists for (a cache with
34 * retrieval, an SPN, a polling server, a G-network signal). Forwarding the bytes
35 * keeps the client lossless on every model the engine accepts, including those
36 * this port cannot itself represent.
37 *
38 * WHICH BINARY RUNS. `ldes_runners` reproduces `getLdesRunners` and
39 * `_build_cli_runners`: the AOT GraalVM binary `common/ldes` first, for its
40 * startup time, then `<java> -jar common/ldes.jar`, and each is tried in turn
41 * because the AOT image lacks reflective features the JVM has (the fork-join
42 * MMT transform deep-copies the model by Java serialization). THE ORDER IS
43 * REVERSED, not merely extended, when the run uses something the prebuilt image
44 * predates -- `--respt-samples`, `--initsol`, a cache cost cap, a marked class,
45 * a load/class-dependent scaling -- because on that image the flag is not
46 * refused but IGNORED, and an ignored cost cap silently simulates the uncapped
47 * cache. The two other clients inspect the live model object for those; this
48 * one inspects the document, which is the same information at the point where
49 * it actually crosses.
50 *
51 * STATE PROBABILITIES ARE READ FROM THE HISTOGRAM, not from the trajectory.
52 * `ldes_prob_aggr` / `ldes_prob_sys_aggr` take the target state as an ARGUMENT
53 * and weigh it against `stateHistogram`, the exact residence time of every
54 * integer joint state the run visited. The no-argument form the reference also
55 * offers -- "the probability of the model's CURRENT state" -- has no counterpart
56 * here because `qn::NetworkStruct` carries no current state row (only a Cache's
57 * `initstate`, a Place's `initmarking` and the `stateprior`/`statespace` pair).
58 * The DEFAULT INITIAL state is a different thing and is derivable, by the same
59 * `ctmc::analyzer_detail::default_init_state` the `-a prob` arms of CTMC, MVA
60 * and NC already answer over; the LDES arm of the CLI still refuses `-a prob`
61 * on the older premise that no state exists at all, which is a reachability gap
62 * in `cpp/src/cli/line_cli.cpp` rather than a gap in this client.
63 * The three other clients answer BOTH forms off the transient `QNt` series,
64 * which is a trajectory of interval MEANS, and so report a near-zero
65 * probability for a state the chain mostly occupies; see BUG-96 and the note on
66 * `LdesResult::QNt`.
67 *
68 * WHAT THIS CLIENT DOES NOT PORT, and why it refuses instead of approximating:
69 * LayeredNetwork MATLAB simulates an LQN through the Java ensemble
70 * backend (`self.obj`), an in-process path with no JSON
71 * interface. Both `common/ldes` (since 2026-10-31) and
72 * `LdesCLI` now solve a LayeredNetwork document, so this
73 * is a client gap, not an engine one: `line-cli -s ldes`
74 * reaches the C++ LN engine in process instead.
75 * server breakdowns `linemodel_save` does not serialize `setBreakdown` at
76 * all, so a breakdown cannot reach this client: the
77 * refusal the Python client performs is on the OBJECT,
78 * before serialization, and has no wire counterpart.
79 *
80 * WHERE THE ENGINE IS, and whether there is one, lives in `ldes_probe.h`:
81 * SolverAUTO needs that answer -- LDES leads several of the reference's
82 * rankings, and a chooser that named it on a host without the engine would be
83 * proposing something that cannot run -- and must not take on this file's HTTP
84 * transport and result parser to get it.
85 */
86
88#include <algorithm>
89#include <cctype>
90#include <cmath>
91#include <cstddef>
92#include <cstdio>
93#include <cstdlib>
94#include <cstring>
95#include <fstream>
96#include <limits>
97#include <sstream>
98#include <string>
99#include <utility>
100#include <vector>
101
102#include <sys/stat.h>
103#include <sys/utsname.h>
104#include <unistd.h>
105
106#include "json.hpp"
113#include "line/util/error.h"
114#include "line/util/http.h"
116#include "line/util/matrix.h"
117#include "line/util/subprocess.h"
118#include "line/util/tempdir.h"
119
120namespace line {
121namespace ldes {
122
123namespace detail {
124
125using Json = nlohmann::json;
126
127/**
128 * The shortest decimal that reads back as `v`, which is what Python's `repr`
129 * emits on the same flag. A fixed `%.10g`, as `solveCli.m` uses, would round a
130 * tolerance the caller set exactly, and the engine parses whatever it is given.
131 */
132inline std::string shortest(double v) {
133 char buf[64];
134 for (int prec = 15; prec <= 17; ++prec) {
135 std::snprintf(buf, sizeof(buf), "%.*g", prec, v);
136 if (std::strtod(buf, nullptr) == v) return std::string(buf);
137 }
138 return std::string(buf);
139}
140
141/** A JSON array of arrays as a matrix, with `null` read back as NaN. */
142inline Matrix<double> mat(const Json& v) {
143 if (v.is_null() || !v.is_array() || v.empty()) return Matrix<double>();
144 if (!v[0].is_array()) {
145 Matrix<double> m(1, v.size());
146 for (std::size_t j = 0; j < v.size(); ++j)
147 m(0, j) = v[j].is_null() ? std::numeric_limits<double>::quiet_NaN()
148 : v[j].get<double>();
149 return m;
150 }
151 std::size_t cols = 0;
152 for (std::size_t i = 0; i < v.size(); ++i)
153 if (v[i].is_array() && v[i].size() > cols) cols = v[i].size();
154 Matrix<double> m(v.size(), cols, std::numeric_limits<double>::quiet_NaN());
155 for (std::size_t i = 0; i < v.size(); ++i) {
156 if (!v[i].is_array()) continue;
157 for (std::size_t j = 0; j < v[i].size(); ++j)
158 if (!v[i][j].is_null()) m(i, j) = v[i][j].get<double>();
159 }
160 return m;
161}
162
163/** A JSON array as a vector of doubles, `null` read back as NaN. */
164inline std::vector<double> vec(const Json& v) {
165 std::vector<double> out;
166 if (!v.is_array()) return out;
167 out.reserve(v.size());
168 for (std::size_t i = 0; i < v.size(); ++i)
169 out.push_back(v[i].is_null() ? std::numeric_limits<double>::quiet_NaN()
170 : v[i].get<double>());
171 return out;
172}
173
174/** The `samplePath` infinities read back; parse_result_json already maps them, so this is idempotent. */
175inline Matrix<double> sp_unclamp(Matrix<double> m) {
176 for (std::size_t i = 0; i < m.rows(); ++i)
177 for (std::size_t j = 0; j < m.cols(); ++j) {
178 if (m(i, j) >= 1e308) m(i, j) = std::numeric_limits<double>::infinity();
179 else if (m(i, j) <= -1e308) m(i, j) = -std::numeric_limits<double>::infinity();
180 }
181 return m;
182}
183
184/** Maps every number with |x| >= 1e308 in a parsed result to +-infinity (see parse_result_json). */
185inline void unclamp_tree(Json& j) {
186 if (j.is_number_float()) {
187 const double v = j.get<double>();
188 if (v >= 1e308) j = std::numeric_limits<double>::infinity();
189 else if (v <= -1e308) j = -std::numeric_limits<double>::infinity();
190 } else if (j.is_array() || j.is_object()) {
191 for (Json& x : j) unclamp_tree(x);
192 }
193}
194
195/**
196 * Parses an `ldes-result` document (or the REST envelope around one), returning
197 * a discarded value when it is malformed.
198 *
199 * Both engines spell +-Infinity as the JSON number +-1e999 (`ldes_cli.cpp`
200 * `num`, `LDESResultIO.JSON_POS_INF`), which Gson, Python and MATLAB read as an
201 * infinity. nlohmann does not: it refuses a non-finite number ("number overflow
202 * parsing '1e999'"), so `parse(.., false)` discarded the WHOLE document and any
203 * result carrying an infinity (the Source row of every sample path, the QN of
204 * an unstable station) read as "not JSON". Outside strings the token is read as
205 * 1e308 and every |x| >= 1e308 then mapped back to +-infinity, which is also
206 * how the 1.0E308 written by a JAR before 2026-11-17 is read.
207 */
208inline Json parse_result_json(const std::string& text) {
209 std::string t;
210 t.reserve(text.size());
211 bool in_string = false, escaped = false;
212 for (std::size_t i = 0; i < text.size(); ++i) {
213 const char c = text[i];
214 if (in_string) {
215 t += c;
216 if (escaped) escaped = false;
217 else if (c == '\\') escaped = true;
218 else if (c == '"') in_string = false;
219 continue;
220 }
221 if (c == '"') {
222 in_string = true;
223 } else if (c == '1' && text.compare(i, 5, "1e999") == 0 &&
224 (i == 0 || !(std::isdigit(static_cast<unsigned char>(text[i - 1])) || text[i - 1] == '.')) &&
225 (i + 5 == text.size() || !std::isdigit(static_cast<unsigned char>(text[i + 5])))) {
226 t += "1e308";
227 i += 4;
228 continue;
229 }
230 t += c;
231 }
232 Json j = Json::parse(t, nullptr, false);
233 if (!j.is_discarded()) unclamp_tree(j);
234 return j;
235}
236
237inline const Json& field(const Json& o, const char* key) {
238 static const Json null_value;
239 return o.is_object() && o.contains(key) ? o[key] : null_value;
240}
241
242/** Reads a whole file, or throws naming it. */
243inline std::string read_file(const std::string& path) {
244 std::ifstream in(path.c_str(), std::ios::binary);
245 if (!in) throw InputError("SolverLDES: cannot open the model document '" + path + "'");
246 std::ostringstream ss;
247 ss << in.rdbuf();
248 return ss.str();
249}
250
251inline void write_file(const std::string& path, const std::string& text) {
252 std::ofstream out(path.c_str(), std::ios::binary);
253 if (!out) throw InputError("SolverLDES: cannot write '" + path + "'");
254 out << text;
255}
256
257/**
258 * True when the DOCUMENT uses something the native engine would MIS-SERVE.
259 *
260 * The scan is on the bytes that actually cross rather than on a live model, and
261 * a substring test is deliberate: every key is unique enough that a false
262 * positive only reorders the runners, which costs startup time and changes no
263 * number, while a false negative would silently simulate a different model.
264 *
265 * THE BAR IS "SILENTLY IGNORED", NOT "DIFFERS". A key belongs here only while
266 * the native engine would accept it and then not honour it, because that is the
267 * failure this guard exists to prevent: an ignored cost cap simulates the
268 * uncapped cache and says nothing. A feature the native engine REFUSES by name
269 * needs no entry -- the runner list falls through to the jar on failure -- and
270 * neither does one it honours.
271 *
272 * `markedClasses` was removed on 2026-09-12, for three reasons together. The
273 * native engine has routed marks since 2026-09-11 and released batches since
274 * 2026-09-12, so it no longer ignores them. `common/ldes` is no longer the
275 * retired GraalVM image of the jar but a C++ binary built from this same tree
276 * (`add_executable(ldes src/cli/ldes_cli.cpp)`), so it cannot predate a document
277 * this tree emits. And neither other client ever carried the entry -- MATLAB's
278 * `getLdesRunners` reverses for nothing and python's `_build_cli_runners` only
279 * for `--respt-samples` -- so keeping it meant
280 * one marked model ran on TWO different engines depending on which codebase's
281 * client was asked, which is the one thing "there is one LDES" is supposed to
282 * rule out.
283 *
284 * `costCaps` was removed on 2026-10-31: the native engine enforces the caps and
285 * now also reports `hitList`, `itemProb` and `listCost` for them.
286 *
287 * Note that digit-for-digit agreement is NOT the bar, and could not be: the two
288 * engines part company on any model whose routing consumes extra draws, which
289 * `CLAUDE.md` states outright. `--initsol` and `--busyperiod` happened to clear
290 * that higher bar when they were pruned; marks do not have to.
291 */
292inline bool document_postdates_native(const std::string& doc) {
293 static const char* keys[] = {"\"classDependence\"",
294 "\"loadDependence\"", "\"jointDependence\""};
295 for (std::size_t i = 0; i < sizeof(keys) / sizeof(keys[0]); ++i)
296 if (doc.find(keys[i]) != std::string::npos) return true;
297 return false;
298}
299
300} // namespace detail
301
302/**
303 * The replication count a run asks the engine for: `replications` when it is
304 * above one, else 8 under method='parallel' (alias 'para'), else 1 (one path).
305 *
306 * ONE RESOLUTION for the flag and for every reader of the result: `ldes_flags`
307 * emits `--replications` from it, and `ldes_perct_respt` picks FQUEST or
308 * FIRQUEST from it, so the two can never disagree on how many paths ran. It is
309 * `solveCli.m`'s, which takes options.replications when set and 8 otherwise.
310 */
311inline int ldes_replications(const LdesOptions& o) {
312 int reps = o.replications;
313 if ((o.method == "parallel" || o.method == "para") && reps <= 1) reps = 8;
314 return reps > 1 ? reps : 1;
315}
316
317/**
318 * The engine flags of one run, after `solve <model> -o <result>`.
319 *
320 * ONE MAPPING for the subprocess and the REST paths, as in both other clients:
321 * the server takes the same long-form flags verbatim, and deriving them twice
322 * is how the two transports start disagreeing. A knob is emitted only when it
323 * differs from the engine default, so a default run yields the minimal command
324 * line an older AOT image still parses -- except `-s` and `--seed`, which are
325 * always emitted: the CLI's seed default is -1 (random), so a silent seed makes
326 * the run irreproducible and unlike the MATLAB and Python clients.
327 */
328inline std::vector<std::string> ldes_flags(const LdesOptions& o,
329 const std::vector<std::string>& extra) {
330 std::vector<std::string> f;
331 const std::size_t budget = o.events ? o.events : o.samples;
332 f.push_back("-s");
333 f.push_back(std::to_string(budget));
334 f.push_back("--seed");
335 f.push_back(std::to_string(o.seed));
336 if (!o.method.empty() && o.method != "default") {
337 f.push_back("--method");
338 f.push_back(o.method);
339 }
340 if (o.cnvgon) {
341 f.push_back("--cnvgon");
342 if (o.cnvgtol != 0.05) {
343 f.push_back("--cnvgtol");
344 f.push_back(detail::shortest(o.cnvgtol));
345 }
346 if (o.cnvgbatch != 20) {
347 f.push_back("--cnvgbatch");
348 f.push_back(std::to_string(o.cnvgbatch));
349 }
350 if (o.cnvgchk != 0) {
351 f.push_back("--cnvgchk");
352 f.push_back(std::to_string(o.cnvgchk));
353 }
354 }
355 if (o.tranfilter != "mser5") {
356 f.push_back("--tranfilter");
357 f.push_back(o.tranfilter);
358 }
359 if (o.warmupfrac != 0.2) {
360 f.push_back("--warmupfrac");
361 f.push_back(detail::shortest(o.warmupfrac));
362 }
363 if (o.tranobs > 0) {
364 f.push_back("--tranobs");
365 f.push_back(std::to_string(o.tranobs));
366 }
367 if (o.mserbatch != 5) {
368 f.push_back("--mserbatch");
369 f.push_back(std::to_string(o.mserbatch));
370 }
371 if (o.cimethod != "obm") {
372 f.push_back("--cimethod");
373 f.push_back(o.cimethod);
374 }
375 if (o.obmoverlap != 0.5) {
376 f.push_back("--obmoverlap");
377 f.push_back(detail::shortest(o.obmoverlap));
378 }
379 if (o.ciminbatch != 10) {
380 f.push_back("--ciminbatch");
381 f.push_back(std::to_string(o.ciminbatch));
382 }
383 if (o.ciminobs != 100) {
384 f.push_back("--ciminobs");
385 f.push_back(std::to_string(o.ciminobs));
386 }
387 if (o.spectral_low_freq_frac != 0.25) {
388 f.push_back("--spectrallowfreqfrac");
389 f.push_back(detail::shortest(o.spectral_low_freq_frac));
390 }
391 // --slotlength implies --slotted on the CLI side; both are emitted when the
392 // length is non-default so the command line states the intent explicitly.
393 if (o.slotted) {
394 f.push_back("--slotted");
395 if (o.slot_length != 1.0) {
396 f.push_back("--slotlength");
397 f.push_back(detail::shortest(o.slot_length));
398 }
399 }
400 // method='parallel' (alias 'para') is a replication count, not a second engine: the caller's
401 // count when set, 8 otherwise, as solveCli.m resolves it. The native engine reads only --replications.
402 const int reps = ldes_replications(o);
403 if (reps > 1) {
404 f.push_back("--replications");
405 f.push_back(std::to_string(reps));
406 if (o.numthreads > 0) {
407 f.push_back("--numthreads");
408 f.push_back(std::to_string(o.numthreads));
409 }
410 }
411 if (o.has_timespan) {
412 f.push_back("--timespan");
413 f.push_back(detail::shortest(o.t0) + "," + detail::shortest(o.t1));
414 }
415 if (o.timeout > 0.0 && std::isfinite(o.timeout)) {
416 f.push_back("--maxtime");
417 f.push_back(detail::shortest(o.timeout));
418 }
419 if (o.busy_period_orders > 0) {
420 f.push_back("--busyperiod");
421 f.push_back(std::to_string(o.busy_period_orders));
422 for (std::size_t i = 0; i < o.busy_period_subnets.size(); ++i) {
423 // station indexes cross the wire zero-based, as the engine holds them
424 std::string v;
425 for (std::size_t t = 0; t < o.busy_period_subnets[i].size(); ++t)
426 v += (t ? "," : "") + std::to_string(o.busy_period_subnets[i][t]);
427 f.push_back("--busyperiod-subnet");
428 f.push_back(v);
429 }
430 }
431 if (!o.init_sol.empty()) {
432 std::string v;
433 for (std::size_t i = 0; i < o.init_sol.size(); ++i)
434 v += (i ? "," : "") + detail::shortest(o.init_sol[i]);
435 f.push_back("--initsol");
436 f.push_back(v);
437 }
438 if (o.init_jobs.rows() > 0) {
439 std::string v;
440 for (std::size_t r = 0; r < o.init_jobs.rows(); ++r)
441 for (std::size_t c = 0; c < o.init_jobs.cols(); ++c)
442 v += (r && !c ? ";" : (c ? "," : "")) + detail::shortest(o.init_jobs(r, c));
443 f.push_back("--initjobs");
444 f.push_back(v);
445 }
446 if (o.track_jobs) f.push_back("--trackjobs");
447 if (o.sample_path_events > 0) {
448 f.push_back("--sample-path");
449 f.push_back(std::to_string(o.sample_path_events));
450 }
451 for (std::size_t i = 0; i < extra.size(); ++i) f.push_back(extra[i]);
452 return f;
453}
454
455/** One runner: the argv prefix that runs the engine, and the name of its image. */
457 std::vector<std::string> argv; ///< up to and including "solve"
458 std::string engine; ///< "native" or "jar"
459};
460
461/**
462 * The runners to try, in order (see the file header for why there are two and
463 * when the order flips).
464 *
465 * @param doc the model document, scanned for features the AOT image predates
466 * @param flags the resolved flags, scanned for the same reason
467 * @throws UnsupportedError when no engine can run on this host
468 */
469inline std::vector<LdesRunner> ldes_runners(const std::string& doc,
470 const std::vector<std::string>& flags) {
471 const std::string& dir = ldes_engine_dir();
472 std::vector<LdesRunner> out;
473 const std::string native = detail::native_ldes_path(dir);
474 if (!native.empty()) {
475 LdesRunner r;
476 r.argv.push_back(native);
477 r.argv.push_back("solve");
478 r.engine = "native";
479 out.push_back(r);
480 }
481 const std::string java = detail::find_java();
482 const std::string jar = dir.empty() ? std::string() : dir + "/ldes.jar";
483 if (!java.empty() && detail::is_file(jar)) {
484 LdesRunner r;
485 r.argv.push_back(java);
486 r.argv.push_back("-jar");
487 r.argv.push_back(jar);
488 r.argv.push_back("solve");
489 r.engine = "jar";
490 out.push_back(r);
491 }
492 if (out.empty()) throw ExternalError(ErrorKind{"LDES"}, detail::no_backend_message(dir));
493 if (out.size() > 1) {
494 // --initsol and --busyperiod used to be here, because the retired
495 // GraalVM image predated them; the C++ engine honours both and agrees
496 // with the jar to the last digit, so only --respt-samples remains.
497 bool prefer_jar = detail::document_postdates_native(doc);
498 for (std::size_t i = 0; i < flags.size() && !prefer_jar; ++i)
499 prefer_jar = flags[i] == "--respt-samples";
500 if (prefer_jar) std::swap(out[0], out[1]);
501 }
502 return out;
503}
504
505/**
506 * Solves through an LDES REST server and returns its `result` document.
507 *
508 * The payload is the model text plus the same flag vector the subprocess would
509 * have been given, so a fixed seed gives the same numbers on both transports.
510 */
511inline detail::Json ldes_solve_rest(const std::string& base_url, const std::string& doc,
512 const std::vector<std::string>& flags, double timeout) {
513 std::string url = base_url;
514 while (!url.empty() && url[url.size() - 1] == '/') url.erase(url.size() - 1);
515 if (url.size() < 6 || url.compare(url.size() - 6, 6, "/solve") != 0) url += "/api/v1/solve";
516
517 detail::Json payload = detail::Json::object();
518 detail::Json model = detail::Json::object();
519 model["content"] = doc;
520 model["base64"] = false;
521 payload["model"] = model;
522 detail::Json fl = detail::Json::array();
523 for (std::size_t i = 0; i < flags.size(); ++i) fl.push_back(flags[i]);
524 payload["flags"] = fl;
525
526 // The budget plus 30 s of grace for the engine to write its result; an
527 // unbudgeted solve waits as long as it takes, as a local one does.
528 const int millis = (timeout > 0.0 && std::isfinite(timeout) && timeout < 2.0e6)
529 ? static_cast<int>((timeout + 30.0) * 1000.0)
530 : 0;
531 http::Response resp;
532 try {
533 resp = http::post_json(url, payload.dump(), millis);
534 } catch (const http::HttpError&) {
535 util::timeout_raise_if_killed_on_budget("SolverLDES: the REST solve at " + url);
536 throw;
537 }
538 if (resp.body.empty())
539 throw ExternalError(ErrorKind{"LDES"}, "SolverLDES: the REST server at " + url + " returned HTTP " +
540 std::to_string(resp.status) + " with no body");
541 detail::Json out = detail::parse_result_json(resp.body);
542 if (out.is_discarded() || !out.is_object())
543 throw ExternalError(ErrorKind{"LDES"}, "SolverLDES: the REST server at " + url +
544 " returned a non-JSON body: " + resp.body);
545 if (!out.contains("status") || out["status"].get<std::string>() != "ok") {
546 const std::string msg = out.contains("message") ? out["message"].get<std::string>()
547 : std::string("unspecified error");
548 const std::string err = out.contains("stderr") ? out["stderr"].get<std::string>()
549 : std::string();
550 throw ExternalError(ErrorKind{"LDES"}, "SolverLDES: the REST solve failed: " + msg +
551 (err.empty() ? "" : " (engine stderr: " + err + ")"));
552 }
553 return out["result"];
554}
555
556/**
557 * Parses one `ldes-result` document.
558 *
559 * `format` is CHECKED, not assumed: the runner falls through on failure, and a
560 * runner that wrote some other JSON to the output path would otherwise be read
561 * as a result full of absent metrics rather than as the failure it is.
562 */
563inline LdesResult parse_ldes_result(const detail::Json& d) {
564 if (d.is_object() && d.contains("error"))
565 throw NumericError(ErrorKind{"InvalidResult"}, "SolverLDES: the engine reported an error: " +
566 d["error"].get<std::string>());
567 if (!d.is_object() || !d.contains("format") || d["format"].get<std::string>() != "ldes-result")
568 throw NumericError(ErrorKind{"InvalidResult"},
569 "SolverLDES: the engine wrote a document that is not an ldes-result; the run did not "
570 "produce metrics");
571
572 LdesResult r;
573 r.method = d.contains("method") && !d["method"].is_null() ? d["method"].get<std::string>()
574 : std::string("default");
575 if (d.contains("runtime")) r.runtime = d["runtime"].get<double>();
576 if (d.contains("converged")) r.converged = d["converged"].get<bool>();
577 if (d.contains("stoppingReason") && !d["stoppingReason"].is_null())
578 r.stopping_reason = d["stoppingReason"].get<std::string>();
579 // The engine stopped on its --maxtime: the budget is spent, latch it.
580 if (r.stopping_reason == "max_time") util::timeout_trip();
581 // The engine's console is not shown, so its warnings are re-raised here.
582 if (d.contains("warnings") && d["warnings"].is_array())
583 for (const auto& w : d["warnings"]) {
584 r.warnings.push_back(w.get<std::string>());
585 std::fprintf(stderr, "[SolverLDES] Warning: %s\n", r.warnings.back().c_str());
586 }
587 if (d.contains("convergenceBatches")) r.convergence_batches = d["convergenceBatches"].get<long>();
588 if (d.contains("totalSimulatedEvents"))
589 r.total_simulated_events = d["totalSimulatedEvents"].get<long long>();
590
591 const detail::Json& dim = detail::field(d, "dimensions");
592 if (dim.is_object()) {
593 if (dim.contains("nstations")) r.nstations = dim["nstations"].get<std::size_t>();
594 if (dim.contains("nclasses")) r.nclasses = dim["nclasses"].get<std::size_t>();
595 if (dim.contains("nchains")) r.nchains = dim["nchains"].get<std::size_t>();
596 if (dim.contains("stationNames"))
597 for (std::size_t i = 0; i < dim["stationNames"].size(); ++i)
598 r.station_names.push_back(dim["stationNames"][i].get<std::string>());
599 if (dim.contains("classNames"))
600 for (std::size_t i = 0; i < dim["classNames"].size(); ++i)
601 r.class_names.push_back(dim["classNames"][i].get<std::string>());
602 }
603
604 const detail::Json& m = detail::field(d, "metrics");
605 r.QN = detail::mat(detail::field(m, "QN"));
606 r.UN = detail::mat(detail::field(m, "UN"));
607 r.RN = detail::mat(detail::field(m, "RN"));
608 r.TN = detail::mat(detail::field(m, "TN"));
609 r.AN = detail::mat(detail::field(m, "AN"));
610 r.WN = detail::mat(detail::field(m, "WN"));
611 r.CN = detail::mat(detail::field(m, "CN"));
612 r.XN = detail::mat(detail::field(m, "XN"));
613 r.DropRateJoin = detail::mat(detail::field(m, "DropRateJoin"));
614
615 const detail::Json& ci = detail::field(d, "confidenceIntervals");
616 r.QNCI = detail::mat(detail::field(ci, "QNCI"));
617 r.UNCI = detail::mat(detail::field(ci, "UNCI"));
618 r.RNCI = detail::mat(detail::field(ci, "RNCI"));
619 r.TNCI = detail::mat(detail::field(ci, "TNCI"));
620 r.ANCI = detail::mat(detail::field(ci, "ANCI"));
621 r.WNCI = detail::mat(detail::field(ci, "WNCI"));
622
623 const detail::Json& rp = detail::field(d, "relativePrecision");
624 r.QNRelPrec = detail::mat(detail::field(rp, "QNRelPrec"));
625 r.UNRelPrec = detail::mat(detail::field(rp, "UNRelPrec"));
626 r.RNRelPrec = detail::mat(detail::field(rp, "RNRelPrec"));
627 r.TNRelPrec = detail::mat(detail::field(rp, "TNRelPrec"));
628
629 const detail::Json& sc = detail::field(d, "sampleCounts");
630 r.QNSamples = detail::mat(detail::field(sc, "QNSamples"));
631 r.UNSamples = detail::mat(detail::field(sc, "UNSamples"));
632 r.RNSamples = detail::mat(detail::field(sc, "RNSamples"));
633 r.TNSamples = detail::mat(detail::field(sc, "TNSamples"));
634
635 const detail::Json& fcr = detail::field(d, "fcr");
636 if (fcr.is_object()) {
637 if (fcr.contains("nregions")) r.nregions = fcr["nregions"].get<std::size_t>();
638 r.QNfcr = detail::mat(detail::field(fcr, "QNfcr"));
639 r.UNfcr = detail::mat(detail::field(fcr, "UNfcr"));
640 r.RNfcr = detail::mat(detail::field(fcr, "RNfcr"));
641 r.TNfcr = detail::mat(detail::field(fcr, "TNfcr"));
642 r.ANfcr = detail::mat(detail::field(fcr, "ANfcr"));
643 r.WNfcr = detail::mat(detail::field(fcr, "WNfcr"));
644 r.WeightNfcr = detail::mat(detail::field(fcr, "WeightNfcr"));
645 r.MemOccNfcr = detail::mat(detail::field(fcr, "MemOccNfcr"));
646 r.DropRateNfcr = detail::mat(detail::field(fcr, "DropRateNfcr"));
647 }
648
649 // Fork-join section metrics: rows named by "forks"/"joins", mapped onto the model's pairs by ldes_fj_metrics.
650 const detail::Json& fjb = detail::field(d, "forkJoin");
651 if (fjb.is_object()) {
652 const detail::Json& fk = detail::field(fjb, "forks");
653 const detail::Json& jn = detail::field(fjb, "joins");
654 for (std::size_t p = 0; fk.is_array() && p < fk.size(); ++p)
655 r.fj_forks.push_back(fk[p].is_string() ? fk[p].get<std::string>() : std::string());
656 for (std::size_t p = 0; jn.is_array() && p < jn.size(); ++p)
657 r.fj_joins.push_back(jn[p].is_string() ? jn[p].get<std::string>() : std::string());
658 r.FJQLen = detail::mat(detail::field(fjb, "FJQLen"));
659 r.FJRespT = detail::mat(detail::field(fjb, "FJRespT"));
660 r.FJTput = detail::mat(detail::field(fjb, "FJTput"));
661 }
662
663 const detail::Json& imp = detail::field(d, "impatience");
664 if (imp.is_object()) {
665 r.renegedCustomers = detail::mat(detail::field(imp, "renegedCustomers"));
666 r.avgRenegingWaitTime = detail::mat(detail::field(imp, "avgRenegingWaitTime"));
667 r.renegingRate = detail::mat(detail::field(imp, "renegingRate"));
668 r.balkedCustomers = detail::mat(detail::field(imp, "balkedCustomers"));
669 r.balkingProbability = detail::mat(detail::field(imp, "balkingProbability"));
670 r.retriedCustomers = detail::mat(detail::field(imp, "retriedCustomers"));
671 r.retrialDropped = detail::mat(detail::field(imp, "retrialDropped"));
672 r.avgOrbitSize = detail::mat(detail::field(imp, "avgOrbitSize"));
673 }
674
675 const detail::Json& cm = detail::field(d, "cacheMetrics");
676 if (cm.is_object())
677 for (detail::Json::const_iterator it = cm.begin(); it != cm.end(); ++it) {
679 c.hit = detail::mat(detail::field(it.value(), "hit"));
680 c.delayed = detail::mat(detail::field(it.value(), "delayed"));
681 c.miss = detail::mat(detail::field(it.value(), "miss"));
682 c.latency = detail::mat(detail::field(it.value(), "latency"));
683 c.hitList = detail::mat(detail::field(it.value(), "hitList"));
684 c.itemProb = detail::mat(detail::field(it.value(), "itemProb"));
685 c.listCost = detail::mat(detail::field(it.value(), "listCost"));
686 r.cache_metrics[it.key()] = c;
687 }
688
689 const detail::Json& bp = detail::field(d, "busyPeriods");
690 if (bp.is_object()) {
691 const detail::Json& targets = detail::field(bp, "targets");
692 for (std::size_t i = 0; i < targets.size(); ++i) {
694 const detail::Json& tj = targets[i];
695 if (tj.contains("name") && tj["name"].is_string())
696 t.name = tj["name"].get<std::string>();
697 const detail::Json& st = detail::field(tj, "stations");
698 for (std::size_t k = 0; k < st.size(); ++k)
699 t.stations.push_back(static_cast<std::size_t>(st[k].get<double>()));
700 if (tj.contains("class") && tj["class"].is_number())
701 t.job_class = static_cast<int>(tj["class"].get<double>());
702 t.mean = detail::vec(detail::field(tj, "mean"));
703 t.count = detail::vec(detail::field(tj, "count"));
704 r.busy_periods.push_back(t);
705 }
706 }
707
708 const detail::Json& js = detail::field(d, "jobState");
709 if (js.is_object()) {
710 r.finalJobs = detail::mat(detail::field(js, "finalJobs"));
711 r.jobDepartures = detail::mat(detail::field(js, "jobDepartures"));
712 }
713
714 // `samplePath` (--sample-path N). Infinities (a Source row's leading entry
715 // and its aggregate) cross the wire as +-1e999 and parse_result_json reads
716 // them as infinities, as LDESResultIO.samplePathMatrix does; a refused node's
717 // detailed rows are `null` and stay empty, with the reason in `refusals`.
718 const detail::Json& spj = detail::field(d, "samplePath");
719 if (spj.is_object()) {
720 LdesSamplePath& sp = r.sample_path;
721 sp.t = detail::vec(detail::field(spj, "t"));
722 const detail::Json& ev = detail::field(spj, "events");
723 for (std::size_t k = 0; ev.is_array() && k < ev.size(); ++k)
724 sp.events.push_back(detail::vec(ev[k]));
725 const detail::Json& nodes = detail::field(spj, "statefulNodes");
726 const detail::Json& state = detail::field(spj, "state");
727 const detail::Json& aggr = detail::field(spj, "aggr");
728 const detail::Json& refusals = detail::field(spj, "refusals");
729 const std::size_t nsf = nodes.is_array() ? nodes.size() : 0;
730 sp.stateful_nodes.resize(nsf);
731 sp.state.resize(nsf);
732 sp.aggr.resize(nsf);
733 sp.refusals.resize(nsf);
734 for (std::size_t f = 0; f < nsf; ++f) {
735 sp.stateful_nodes[f] = static_cast<int>(nodes[f].get<double>());
736 if (state.is_array() && f < state.size()) sp.state[f] = detail::sp_unclamp(detail::mat(state[f]));
737 if (aggr.is_array() && f < aggr.size()) sp.aggr[f] = detail::sp_unclamp(detail::mat(aggr[f]));
738 if (refusals.is_array() && f < refusals.size() && refusals[f].is_string())
739 sp.refusals[f] = refusals[f].get<std::string>();
740 }
741 const detail::Json& ph = detail::field(spj, "phases");
742 for (std::size_t f = 0; ph.is_array() && f < ph.size(); ++f) {
743 std::vector<int> row;
744 for (std::size_t k = 0; ph[f].is_array() && k < ph[f].size(); ++k)
745 row.push_back(static_cast<int>(ph[f][k].get<double>()));
746 sp.phases.push_back(row);
747 }
748 if (spj.contains("unboundScripts") && spj["unboundScripts"].is_number())
749 sp.unbound_scripts = spj["unboundScripts"].get<long long>();
750 if (spj.contains("simTime") && spj["simTime"].is_number())
751 sp.sim_time = spj["simTime"].get<double>();
752 r.has_sample_path = true;
753 }
754
755 const detail::Json& hist = detail::field(d, "stateHistogram");
756 if (hist.is_object()) {
757 r.histogram_space = detail::mat(detail::field(hist, "space"));
758 r.histogram_time = detail::mat(detail::field(hist, "time"));
759 r.traj_space = detail::mat(detail::field(hist, "trajSpace"));
760 r.traj_time = detail::mat(detail::field(hist, "trajTime"));
761 }
762
763 // `respTimeSamples` appears at TOP LEVEL under --respt-samples and inside
764 // `transient` under --trajectory; the two are the same measurement and
765 // whichever is present is read.
766 const detail::Json& tran = detail::field(d, "transient");
767 if (tran.is_object()) {
768 r.t = detail::vec(detail::field(tran, "t"));
769 const char* keys[3] = {"QNt", "UNt", "TNt"};
770 std::vector<std::vector<Matrix<double>>>* dst[3] = {&r.QNt, &r.UNt, &r.TNt};
771 for (int q = 0; q < 3; ++q) {
772 const detail::Json& blk = detail::field(tran, keys[q]);
773 if (!blk.is_array()) continue;
774 for (std::size_t i = 0; i < blk.size(); ++i) {
775 std::vector<Matrix<double>> row;
776 for (std::size_t k = 0; k < blk[i].size(); ++k)
777 row.push_back(detail::mat(blk[i][k]));
778 dst[q]->push_back(row);
779 }
780 }
781 }
782 const detail::Json& rts = tran.is_object() && tran.contains("respTimeSamples")
783 ? tran["respTimeSamples"]
784 : detail::field(d, "respTimeSamples");
785 if (rts.is_array())
786 for (std::size_t i = 0; i < rts.size(); ++i) {
787 std::vector<std::vector<double>> row;
788 for (std::size_t k = 0; k < rts[i].size(); ++k) row.push_back(detail::vec(rts[i][k]));
789 r.respTimeSamples.push_back(row);
790 }
791 // `respTimeSamplesRep`, [rep][station][class][sample]: written at top level under --respt-samples
792 // by a replicated steady-state run (replications >= 2) only, absent otherwise.
793 const detail::Json& rtr = detail::field(d, "respTimeSamplesRep");
794 if (rtr.is_array())
795 for (std::size_t q = 0; q < rtr.size(); ++q) {
796 std::vector<std::vector<std::vector<double>>> blk;
797 for (std::size_t i = 0; rtr[q].is_array() && i < rtr[q].size(); ++i) {
798 std::vector<std::vector<double>> row;
799 for (std::size_t k = 0; k < rtr[q][i].size(); ++k) row.push_back(detail::vec(rtr[q][i][k]));
800 blk.push_back(row);
801 }
802 r.respTimeSamplesRep.push_back(blk);
803 }
804 return r;
805}
806
807/**
808 * Runs one LDES simulation on a `model.json` DOCUMENT and parses its result.
809 *
810 * The document is written into a private scratch directory, the engine is run
811 * there, and the directory is removed on both the success and the failure path
812 * (`TempDir`'s destructor), because a wrapper that leaks one directory per
813 * failed solve leaks silently.
814 *
815 * THE RUNNERS ARE TRIED IN ORDER and the LAST failure is reported in full,
816 * merged stdout and stderr, because the engine states why it refused there and
817 * an exit code alone is not a diagnosis.
818 *
819 * @param doc the model.json text, forwarded byte for byte
820 * @param o the run's knobs
821 * @param extra_flags flags an analysis adds (--trajectory, --export-histogram,
822 * --respt-samples)
823 * @return the parsed result, carrying which image produced it
824 */
825inline LdesResult solver_ldes_text(const std::string& doc, const LdesOptions& o,
826 const std::vector<std::string>& extra_flags =
827 std::vector<std::string>()) {
828 // The run's budget: its own `timeout`, capped by any `options.timeout`
829 // armed around it. The engine is handed what is LEFT as --maxtime, and the
830 // latch of this frame is what `timed_out` reports.
832 LdesOptions ob = o;
834 const std::vector<std::string> flags = ldes_flags(ob, extra_flags);
835 util::TempDir tmp("ldes");
836 const std::string model_path = tmp.file("model.json");
837 const std::string result_path = tmp.file("result.json");
838 line::util::LineConsole::step("serializing the model to JSON for the LDES engine");
839 detail::write_file(model_path, doc);
840
841 if (!o.rest_url.empty()) {
843 r.engine = "rest";
845 return r;
846 }
847
848 const std::vector<LdesRunner> runners = ldes_runners(doc, flags);
849 // The cooperative --maxtime stops the event loop; this is the HARD bound and
850 // leaves the engine 30 s of grace to write its result and exit, else no
851 // result file is produced at all. No budget, no bound: an unbudgeted run is
852 // never killed.
853 const int hard = util::timeout_kill_seconds(30.0);
854 std::string last_err;
855 for (std::size_t i = 0; i < runners.size(); ++i) {
856 std::vector<std::string> argv = runners[i].argv;
857 argv.push_back(model_path);
858 argv.push_back("-o");
859 argv.push_back(result_path);
860 for (std::size_t j = 0; j < flags.size(); ++j) argv.push_back(flags[j]);
861 std::remove(result_path.c_str());
862 if (o.verbose) {
863 std::string line;
864 for (std::size_t j = 0; j < argv.size(); ++j) line += (j ? " " : "") + argv[j];
865 std::fprintf(stderr, "SolverLDES command: %s\n", line.c_str());
866 }
867 line::util::LineConsole::step("running the LDES engine (%s) as a subprocess",
868 runners[i].engine.c_str());
869 const util::ProcResult p = util::capture(argv, hard, true);
870 // Killed on the hard bound: no result file, so no partial solution.
871 if (p.timedOut) {
873 util::timeout_raise_if_killed_on_budget("SolverLDES: the " + runners[i].engine +
874 " engine");
875 }
876 if (p.exitCode == 0 && detail::is_file(result_path)) {
877 line::util::LineConsole::step("parsing the LDES result document");
878 const std::string text = detail::read_file(result_path);
879 detail::Json parsed = detail::parse_result_json(text);
880 if (parsed.is_discarded())
881 throw ExternalError(ErrorKind{"LDES"}, "SolverLDES: the engine wrote a result that is not JSON");
882 LdesResult r = parse_ldes_result(parsed);
883 r.engine = runners[i].engine;
884 r.timed_out = util::timeout_tripped();
885 return r;
886 }
887 last_err = "exit code " + std::to_string(p.exitCode) + ": " + util::trim(p.out);
888 }
889 throw ExternalError(ErrorKind{"LDES"}, "SolverLDES: the engine failed on all " +
890 std::to_string(runners.size()) + " runner(s); " + last_err);
891}
892
893/** The same, reading the document from a file. */
894inline LdesResult solver_ldes_file(const std::string& path, const LdesOptions& o,
895 const std::vector<std::string>& extra_flags =
896 std::vector<std::string>()) {
897 return solver_ldes_text(detail::read_file(path), o, extra_flags);
898}
899
900/**
901 * One constraint of a joint-state query: a station and the per-class job counts
902 * it is required to hold.
903 *
904 * `station` is 1-BASED, matching `sn.nodeToStation`. `counts` is read up to
905 * `nclasses` entries; a shorter vector constrains only the classes it names,
906 * which is how a caller asks for "two class-1 jobs here, any number of the
907 * rest" without enumerating the remainder.
908 */
910 std::size_t station = 0;
911 std::vector<double> counts;
912};
913
914/**
915 * Residence-time probability of an aggregate joint state, from a parsed result.
916 *
917 * WHY THE HISTOGRAM AND NOT THE TRAJECTORY. `stateHistogram` is the exact
918 * residence time of every integer joint state the run visited, keyed on the
919 * state itself (`Solver_ssj.updateRewardStats` accumulates it per marking), so
920 * P(state) = t(state) / sum(t) is an unbiased estimate that is exact on the
921 * sampled path. The transient `QNt` series is a sequence of INTERVAL MEANS of
922 * the queue length; comparing one against an integer state matches only where a
923 * bucket mean happens to land on an integer, which is why the three clients
924 * that estimated a probability that way reported a near-zero number for a state
925 * the chain occupies most of the time (BUG-96).
926 *
927 * The layout is the aggregated station-major, class-minor one
928 * `ctmc_state_space_aggr` builds: column `(i-1)*nclasses + k` is the number of
929 * class-k jobs at station i. THE RESOLUTION IS PER CLASS, not per phase: the
930 * engine records the integer queue lengths, so a phase-resolved query cannot be
931 * answered from this document and the caller must aggregate first.
932 *
933 * @param r a result produced with `--export-histogram`
934 * @param nclasses the model's class count, which fixes the column stride
935 * @param query the stations to constrain, and to what
936 * @return the residence-time fraction, 0 when the state was never visited
937 * @throws NumericError when the run carried no histogram (the flag was omitted)
938 */
939inline double ldes_prob_from_histogram(const LdesResult& r, std::size_t nclasses,
940 const std::vector<LdesStateQuery>& query) {
941 if (r.histogram_space.rows() == 0 || r.histogram_time.rows() == 0)
942 throw NumericError(ErrorKind{"Degenerate"},
943 "SolverLDES: this result carries no state histogram, so no state probability can be "
944 "read from it; the run has to pass --export-histogram");
945 if (nclasses == 0)
946 throw InputError("SolverLDES: a state probability needs the model's class count");
947 const std::size_t nstates = r.histogram_space.rows();
948 double total = 0.0;
949 for (std::size_t s = 0; s < nstates; ++s) total += r.histogram_time(s, 0);
950 if (!(total > 0.0)) return 0.0;
951
952 const std::size_t ncols = r.histogram_space.cols();
953 for (std::size_t q = 0; q < query.size(); ++q) {
954 if (query[q].station == 0)
955 throw InputError("SolverLDES: a state query names station 0; stations are 1-based");
956 const std::size_t last = (query[q].station - 1) * nclasses + nclasses;
957 if (last > ncols)
958 throw InputError(
959 "SolverLDES: station " + std::to_string(query[q].station) +
960 " is past the end of the state histogram, which holds " + std::to_string(ncols) +
961 " columns for " + std::to_string(nclasses) + " classes");
962 }
963
964 double matched = 0.0;
965 for (std::size_t s = 0; s < nstates; ++s) {
966 bool ok = true;
967 for (std::size_t q = 0; q < query.size() && ok; ++q) {
968 const std::size_t base = (query[q].station - 1) * nclasses;
969 const std::size_t n = std::min(nclasses, query[q].counts.size());
970 for (std::size_t k = 0; k < n; ++k)
971 if (std::fabs(r.histogram_space(s, base + k) - query[q].counts[k]) > 1e-9) {
972 ok = false;
973 break;
974 }
975 }
976 if (ok) matched += r.histogram_time(s, 0);
977 }
978 return matched / total;
979}
980
981/**
982 * Port of `getCdfRespT`: the EMPIRICAL response time CDF of one (station,
983 * class) pair, built from the per-job samples the engine exports under
984 * `--respt-samples`.
985 *
986 * The returned matrix is (n x 2) with columns [F(t), t], NOT [t, F(t)]. That
987 * order is the convention every `getCdfRespT` follows across the codebases
988 * (MATLAB `@SolverLDES/getCdfRespT.m`, Python `SolverJMT.getCdfRespT`), and it
989 * is the REVERSE of the transient `getTranCdfRespT`, which is a different
990 * method with a different contract. Swapping them yields a CDF that reads as a
991 * time axis and vice versa, with no error anywhere.
992 *
993 * A pair the run observed nothing at returns an EMPTY matrix rather than a
994 * fabricated law: an analytical fallback carrying the right mean says nothing
995 * about the tail, which is the whole reason to ask a simulator for a CDF.
996 * Repeated observations are collapsed, keeping the largest CDF value at each
997 * distinct time, or the ecdf is multivalued and an interpolating consumer
998 * reads a quantile off whichever duplicate it happens to hit.
999 */
1000inline Matrix<double> ldes_cdf_respt(const LdesResult& r, std::size_t station,
1001 std::size_t job_class) {
1002 if (station >= r.respTimeSamples.size() ||
1003 job_class >= r.respTimeSamples[station].size())
1004 return Matrix<double>();
1005 std::vector<double> x = r.respTimeSamples[station][job_class];
1006 if (x.empty()) return Matrix<double>();
1007 std::sort(x.begin(), x.end());
1008 const std::size_t n = x.size();
1009 std::vector<double> tu, fu;
1010 for (std::size_t i = 0; i < n; ++i) {
1011 const double f = static_cast<double>(i + 1) / static_cast<double>(n);
1012 if (i + 1 < n && x[i + 1] == x[i]) continue; // keep the LAST of a tie
1013 tu.push_back(x[i]);
1014 fu.push_back(f);
1015 }
1016 Matrix<double> out(tu.size(), 2, 0.0);
1017 for (std::size_t i = 0; i < tu.size(); ++i) {
1018 out(i, 0) = fu[i];
1019 out(i, 1) = tu[i];
1020 }
1021 return out;
1022}
1023
1024/**
1025 * One (station, class) row of `getPerctRespT` on SolverLDES: the steady-state
1026 * response-time p-quantiles with their confidence intervals.
1027 *
1028 * The per-percentile vectors share the order of `percentiles`. `heuristic[j]` is
1029 * true when the procedure delivered its fallback interval at `percentiles[j]`
1030 * (a stage test failed), which is to be read before the half-width is quoted as
1031 * an asymptotically justified one. When the pair had too few observations for
1032 * the procedure at all, `values` is the empirical quantile of its samples and
1033 * `lower`, `upper`, `halfwidth` are NaN with `heuristic` false.
1034 */
1036 std::string station; ///< node name of the station
1037 std::string job_class; ///< class name (`class` in MATLAB / Python)
1038 std::size_t station_index = 0; ///< 0-based station index in the result
1039 std::size_t class_index = 0; ///< 0-based class index in the result
1040 std::vector<double> percentiles; ///< fractions in (0,1)
1041 std::vector<double> values; ///< point estimates (QuestResult::estimate)
1042 std::vector<double> lower; ///< lower confidence limits
1043 std::vector<double> upper; ///< upper confidence limits
1044 std::vector<double> halfwidth; ///< halfwidths
1045 std::vector<bool> heuristic; ///< true where the fallback interval was used
1046 double level = 0.95; ///< confidence level
1047 std::string method; ///< "fquest" or "firquest"
1048 std::size_t samples = 0; ///< observations used (per replication after trimming, times R)
1049};
1050
1051/**
1052 * The percentile levels as fractions: any entry above 1 makes the whole vector
1053 * PERCENT, as the base `getPerctRespT` reads it. Empty gives the default
1054 * {10, 25, 50, 75, 90, 95, 99} percent.
1055 *
1056 * @throws InputError when a level is not in (0,1) after the conversion
1057 */
1058inline std::vector<double> ldes_perct_levels(const std::vector<double>& percentiles) {
1059 std::vector<double> p = percentiles;
1060 if (p.empty()) p = {10, 25, 50, 75, 90, 95, 99};
1061 bool percent = false;
1062 for (std::size_t j = 0; j < p.size(); ++j)
1063 if (p[j] > 1.0) percent = true;
1064 for (std::size_t j = 0; j < p.size(); ++j) {
1065 if (percent) p[j] /= 100.0;
1066 if (!(p[j] > 0.0) || !(p[j] < 1.0))
1067 throw InputError(ErrorKind{"Percentile"},
1068 "SolverLDES.getPerctRespT: percentiles must be fractions in (0,1) or "
1069 "percentages in (0,100)");
1070 }
1071 return p;
1072}
1073
1074/**
1075 * The quantile procedure a replication count calls for: 'fquest' on one path
1076 * (R <= 1), 'firquest' over R >= 2 independent replications. `method` empty or
1077 * 'default' resolves to that; 'fquest' / 'firquest' are accepted only when they
1078 * match R. 'forktail' is the base NetworkSolver's analytical method, which the
1079 * C++ port does not carry on the solver (it lives in `fj::fj_tail_forktail`),
1080 * so it is refused by name rather than silently answered by simulation.
1081 *
1082 * @throws InputError (`LINE:input:Method`) on a method that does not match R
1083 * @throws UnsupportedError on 'forktail'
1084 */
1085inline std::string ldes_perct_method(int replications, const std::string& method) {
1086 const int R = replications > 1 ? replications : 1;
1087 const std::string want = R >= 2 ? "firquest" : "fquest";
1088 std::string m = method;
1089 std::transform(m.begin(), m.end(), m.begin(), [](unsigned char c) { return std::tolower(c); });
1090 if (m.empty() || m == "default") return want;
1091 if (m == "forktail")
1092 throw UnsupportedError(ErrorKind{"Method"},
1093 "SolverLDES.getPerctRespT: method 'forktail' is the base NetworkSolver percentile "
1094 "approximation, which the C++ solver facade does not carry; call "
1095 "fj::fj_tail_forktail directly for it");
1096 if (m == "fquest" || m == "firquest") {
1097 if (m != want)
1098 throw InputError(ErrorKind{"Method"},
1099 "SolverLDES.getPerctRespT: method '" + m + "' does not match the replication count " +
1100 std::to_string(R) + "; use 'fquest' with replications <= 1 and 'firquest' with "
1101 "replications >= 2 (or 'default')");
1102 return m;
1103 }
1104 throw InputError(ErrorKind{"Method"},
1105 "SolverLDES.getPerctRespT: unknown method '" + method +
1106 "'; expected 'default', 'fquest', 'firquest' or 'forktail'");
1107}
1108
1109namespace detail {
1110
1111/** The order-statistic p-quantile x_(ceil(n p)) the sim API's point estimate uses. */
1112inline double ldes_empirical_quantile(std::vector<double> x, double p) {
1113 std::sort(x.begin(), x.end());
1114 std::size_t k = static_cast<std::size_t>(std::ceil(static_cast<double>(x.size()) * p));
1115 if (k < 1) k = 1;
1116 return x[k - 1];
1117}
1118
1119/** True for the procedures' "not enough observations" refusals, as opposed to any other input error. */
1120inline bool ldes_quest_too_short(const InputError& e) {
1121 const std::string w = e.what();
1122 return w.find("too short") != std::string::npos || w.find("exhausts") != std::string::npos;
1123}
1124
1125} // namespace detail
1126
1127/**
1128 * Port of `@SolverLDES/getPerctRespT`: steady-state response-time p-quantiles
1129 * with confidence intervals, from the per-job samples of a `--respt-samples` run.
1130 *
1131 * THE PROCEDURE FOLLOWS THE REPLICATION COUNT. On one path it is FQUEST
1132 * (`sim::sim_fquest`, Lolos et al., WSC 2023) on the departure-ordered series of
1133 * each (station, class); over R >= 2 replications it is FIRQUEST
1134 * (`sim::sim_firquest`, Lolos et al., WSC 2025) on the R per-replication series
1135 * of `respTimeSamplesRep`, each trimmed at its END to the shortest of the R:
1136 * FIRQUEST needs equal lengths, and cutting the end keeps the replications
1137 * independent while leaving the start, where warmup is detected, untouched.
1138 * The series are the RAW departure-ordered samples, warmup included and never
1139 * sorted, because both procedures detect and delete the warmup themselves.
1140 *
1141 * Pairs with no samples (a Source, a station a class never visits) are skipped.
1142 * A pair too short for the procedure is NOT dropped: it reports the empirical
1143 * quantile with NaN limits and one warning naming it; any other error propagates.
1144 *
1145 * @param r a result carrying `respTimeSamples` (and, for R >= 2, `respTimeSamplesRep`)
1146 * @param percentiles fractions in (0,1) or percentages; empty for the default levels
1147 * @param replications the run's replication count (`ldes_replications(options)`)
1148 * @param method "" / "default", "fquest" or "firquest" (see `ldes_perct_method`)
1149 * @param level confidence level in (0,1)
1150 * @param job_class 0-based class to restrict to, or -1 for every class
1151 */
1152inline std::vector<LdesPercentileResult> ldes_perct_respt(const LdesResult& r,
1153 const std::vector<double>& percentiles,
1154 int replications,
1155 const std::string& method = std::string(),
1156 double level = 0.95, long job_class = -1) {
1157 const std::vector<double> p = ldes_perct_levels(percentiles);
1158 const std::string used = ldes_perct_method(replications, method);
1159 if (!(level > 0.0) || !(level < 1.0))
1160 throw InputError("SolverLDES.getPerctRespT: the confidence level must be in (0,1)");
1161 const double alpha = 1.0 - level;
1162 if (r.respTimeSamples.empty())
1163 throw ExternalError(ErrorKind{"LDES"},
1164 "SolverLDES.getPerctRespT needs the per-job response times the engine records under "
1165 "--respt-samples and the run returned none; raise the samples so completions are observed");
1166 const bool rep = used == "firquest";
1167 const std::size_t R = rep ? r.respTimeSamplesRep.size() : 1;
1168 if (rep && R < 2)
1169 throw ExternalError(ErrorKind{"LDES"},
1170 "SolverLDES.getPerctRespT: FIRQUEST needs the per-replication samples "
1171 "(respTimeSamplesRep) of a replicated run, and this result carries none; the engine "
1172 "that produced it predates them or ran a single path");
1173 if (job_class >= 0 && !r.respTimeSamples.empty() &&
1174 static_cast<std::size_t>(job_class) >= r.respTimeSamples[0].size())
1175 throw InputError("SolverLDES.getPerctRespT: job class index " + std::to_string(job_class) +
1176 " is out of range");
1178
1179 std::vector<LdesPercentileResult> out;
1180 for (std::size_t i = 0; i < r.respTimeSamples.size(); ++i)
1181 for (std::size_t k = 0; k < r.respTimeSamples[i].size(); ++k) {
1182 if (job_class >= 0 && k != static_cast<std::size_t>(job_class)) continue;
1183 const std::vector<double>& pooled = r.respTimeSamples[i][k];
1184 if (pooled.empty()) continue;
1186 e.station = i < r.station_names.size() ? r.station_names[i] : "Station" + std::to_string(i + 1);
1187 e.job_class = k < r.class_names.size() ? r.class_names[k] : "Class" + std::to_string(k + 1);
1188 e.station_index = i;
1189 e.class_index = k;
1190 e.percentiles = p;
1191 e.level = level;
1192 e.method = used;
1193 const std::size_t np = p.size();
1194 e.values.assign(np, 0.0);
1195 e.lower.assign(np, 0.0);
1196 e.upper.assign(np, 0.0);
1197 e.halfwidth.assign(np, 0.0);
1198 e.heuristic.assign(np, false);
1199
1200 std::vector<std::vector<double>> Y;
1201 if (rep) {
1202 std::size_t nmin = std::numeric_limits<std::size_t>::max();
1203 for (std::size_t q = 0; q < R; ++q) {
1204 const std::vector<std::vector<std::vector<double>>>& blk = r.respTimeSamplesRep[q];
1205 const std::size_t len = (i < blk.size() && k < blk[i].size()) ? blk[i][k].size() : 0;
1206 nmin = std::min(nmin, len);
1207 }
1208 Y.resize(R);
1209 for (std::size_t q = 0; q < R; ++q)
1210 if (nmin > 0)
1211 Y[q].assign(r.respTimeSamplesRep[q][i][k].begin(),
1212 r.respTimeSamplesRep[q][i][k].begin() + static_cast<std::ptrdiff_t>(nmin));
1213 e.samples = nmin * R;
1214 } else {
1215 e.samples = pooled.size();
1216 }
1217
1218 bool too_short = rep && e.samples == 0;
1219 for (std::size_t j = 0; j < np && !too_short; ++j) {
1220 try {
1221 const sim::QuestResult<double> qr =
1222 rep ? sim::sim_firquest<double>(Y, p[j], alpha) : sim::sim_fquest<double>(pooled, p[j], alpha);
1223 e.values[j] = qr.estimate;
1224 e.lower[j] = qr.lower;
1225 e.upper[j] = qr.upper;
1226 e.halfwidth[j] = qr.halfwidth;
1227 e.heuristic[j] = qr.heuristic;
1228 } catch (const InputError& ex) {
1229 if (!detail::ldes_quest_too_short(ex)) throw;
1230 too_short = true;
1231 }
1232 }
1233 if (too_short) {
1234 const double nan = std::numeric_limits<double>::quiet_NaN();
1235 for (std::size_t j = 0; j < np; ++j) {
1236 e.values[j] = detail::ldes_empirical_quantile(pooled, p[j]);
1237 e.lower[j] = nan;
1238 e.upper[j] = nan;
1239 e.halfwidth[j] = nan;
1240 e.heuristic[j] = false;
1241 }
1242 if (!quiet)
1243 std::fprintf(stderr,
1244 "[SolverLDES] Warning: getPerctRespT: station %s, class %s has %zu response-time "
1245 "samples, too few for %s; reporting the empirical quantile without a "
1246 "confidence interval\n",
1247 e.station.c_str(), e.job_class.c_str(), e.samples, used.c_str());
1248 }
1249 out.push_back(e);
1250 }
1251 return out;
1252}
1253
1254/** The same, restricted to the class named `job_class` (looked up in the result's class names). */
1255inline std::vector<LdesPercentileResult> ldes_perct_respt(const LdesResult& r,
1256 const std::vector<double>& percentiles,
1257 int replications, const std::string& method,
1258 double level, const std::string& job_class) {
1259 for (std::size_t k = 0; k < r.class_names.size(); ++k)
1260 if (r.class_names[k] == job_class)
1261 return ldes_perct_respt(r, percentiles, replications, method, level, static_cast<long>(k));
1262 throw InputError("SolverLDES.getPerctRespT: no job class named '" + job_class + "'");
1263}
1264
1265/**
1266 * The confidence level `getPerctRespT` uses: `confint` when intervals are on
1267 * (a level in (0,1) and a cimethod other than 'none'), else 0.95.
1268 */
1269inline double ldes_perct_level(const LdesOptions& o) {
1270 if (o.cimethod != "none" && o.confint > 0.0 && o.confint < 1.0) return o.confint;
1271 return 0.95;
1272}
1273
1274/**
1275 * Port of `getProbAggr`: the marginal probability of a per-class job count at
1276 * one station.
1277 *
1278 * The run is a plain steady-state solve with `--export-histogram` added, which
1279 * is what `getAvgReward` already does, so the estimate is over the same
1280 * post-warmup path the mean metrics come from.
1281 *
1282 * @param doc the model.json document, forwarded byte for byte
1283 * @param o the run's knobs
1284 * @param station 1-based station index
1285 * @param counts per-class job counts to test at that station
1286 * @param nclasses the model's class count
1287 */
1288inline double ldes_prob_aggr(const std::string& doc, const LdesOptions& o, std::size_t station,
1289 const std::vector<double>& counts, std::size_t nclasses) {
1290 std::vector<std::string> flags;
1291 flags.push_back("--export-histogram");
1292 const LdesResult r = solver_ldes_text(doc, o, flags);
1293 std::vector<LdesStateQuery> q(1);
1294 q[0].station = station;
1295 q[0].counts = counts;
1296 return ldes_prob_from_histogram(r, nclasses, q);
1297}
1298
1299/**
1300 * Port of `getProbSysAggr`: the joint probability of a whole aggregate state.
1301 *
1302 * @param target (nstations x nclasses) job counts, EVERY station constrained
1303 */
1304inline double ldes_prob_sys_aggr(const std::string& doc, const LdesOptions& o,
1305 const Matrix<double>& target) {
1306 if (target.rows() == 0 || target.cols() == 0)
1307 throw InputError("SolverLDES: getProbSysAggr needs an (nstations x nclasses) target state");
1308 std::vector<std::string> flags;
1309 flags.push_back("--export-histogram");
1310 const LdesResult r = solver_ldes_text(doc, o, flags);
1311 const std::size_t K = target.cols();
1312 std::vector<LdesStateQuery> q(target.rows());
1313 for (std::size_t i = 0; i < target.rows(); ++i) {
1314 q[i].station = i + 1;
1315 q[i].counts.resize(K);
1316 for (std::size_t k = 0; k < K; ++k) q[i].counts[k] = target(i, k);
1317 }
1318 return ldes_prob_from_histogram(r, K, q);
1319}
1320
1321/**
1322 * `ldesParseForkJoin`: the engine's "forkJoin" rows mapped onto the Fork/Join pairs of `sn` by (fork name,
1323 * join name), in fork-then-join node order. A pair the engine did not report, and a non-finite entry, read
1324 * zero. EMPTY when the model has no pair or the engine wrote no block.
1325 */
1326template <class T>
1328 if (solvers::fj_sorted_pairs(sn).empty() || r.fj_forks.empty()) return solvers::FjMetrics<double>();
1329 const std::size_t R = sn.nclasses;
1331 const Matrix<double>* src[3] = {&r.FJQLen, &r.FJRespT, &r.FJTput};
1332 Matrix<double>* dst[3] = {&out.QLen, &out.RespT, &out.Tput};
1333 for (std::size_t p = 0; p < out.npairs(); ++p) {
1334 const std::string& fname = sn.nodes[out.forks[p] - 1].name;
1335 const std::string& jname = sn.nodes[out.joins[p] - 1].name;
1336 std::size_t e = r.fj_forks.size();
1337 for (std::size_t k = 0; k < r.fj_forks.size() && k < r.fj_joins.size(); ++k)
1338 if (r.fj_forks[k] == fname && r.fj_joins[k] == jname) {
1339 e = k;
1340 break;
1341 }
1342 if (e == r.fj_forks.size()) continue;
1343 for (int m = 0; m < 3; ++m)
1344 for (std::size_t c = 0; c < R; ++c) {
1345 std::size_t cc = c; // the engine's column of class c, matched by name when it reports names
1346 for (std::size_t k = 0; k < r.class_names.size(); ++k)
1347 if (r.class_names[k] == sn.classes[c].name) {
1348 cc = k;
1349 break;
1350 }
1351 const double v =
1352 (e < src[m]->rows() && cc < src[m]->cols()) ? (*src[m])(e, cc) : 0.0;
1353 (*dst[m])(p, c) = std::isfinite(v) ? v : 0.0;
1354 }
1355 }
1356 return out;
1357}
1358
1359/**
1360 * The same, for a model built through the C++ API.
1361 *
1362 * The struct is serialized with `io::network_json_envelope`, the writer whose
1363 * output the reference readers consume, and the document then takes the same
1364 * path as any other. WHAT THE STRUCT CANNOT CARRY DOES NOT CROSS: a reward built
1365 * from a lambda and any construct outside the writer's schema are dropped by the
1366 * writer, with its own warning, which is why a caller holding a `model.json`
1367 * should pass the DOCUMENT rather than a struct parsed from it -- the round trip
1368 * can only lose.
1369 *
1370 * An OI/PAS station with no finite buffer is refused here, by name, before the
1371 * document is written: its mu(c) crosses as a table and the engine needs a
1372 * finite buffer to bound the state (`io::require_finite_pas_buffers`, the
1373 * Python `save_model` refusal). The in-process engine, which holds mu itself,
1374 * is not gated.
1375 */
1376/**
1377 * Closed-chain population conservation check on a steady-state QN, ported from MATLAB's parseSteady.
1378 *
1379 * A closed chain must conserve its population in the reported queue lengths. Engine builds that drop
1380 * blocked closed jobs at a finite-capacity station (pre-guard ldes.jar) leak population silently, and
1381 * the reported means then describe a different model. FCR models are excluded (a WAITQ waiter is
1382 * parked outside the station rows), and so are fork-join models (a forked job is counted once per
1383 * sibling task, so the rows sum to more than the population by construction). A chain is flagged when
1384 * |sum(QN) - N| > max(0.05*N, 0.05), NaN entries being omitted from the sum.
1385 *
1386 * @return one message per failing chain, empty when none fails
1387 */
1388template <class T>
1390 const Matrix<double>& QN) {
1391 std::vector<std::string> out;
1392 if (QN.empty() || !sn.regions.empty()) return out;
1393 for (std::size_t i = 0; i < sn.nodes.size(); ++i)
1394 if (sn.nodes[i].nodetype == qn::NodeType::Fork) return out;
1395 const std::vector<double> njobs = sn.njobs();
1396 for (std::size_t nc = 0; nc < sn.nchains && nc < sn.chains.size(); ++nc) {
1397 double njobs_chain = 0.0;
1398 std::vector<std::size_t> inchain;
1399 for (std::size_t r = 0; r < sn.chains[nc].size() && r < njobs.size(); ++r)
1400 if (sn.chains[nc][r]) {
1401 inchain.push_back(r);
1402 njobs_chain += njobs[r];
1403 }
1404 if (!(std::isfinite(njobs_chain) && njobs_chain > 0.0)) continue;
1405 double qtot = 0.0;
1406 for (std::size_t i = 0; i < QN.rows(); ++i)
1407 for (std::size_t k = 0; k < inchain.size(); ++k)
1408 if (inchain[k] < QN.cols() && !std::isnan(QN(i, inchain[k]))) qtot += QN(i, inchain[k]);
1409 if (std::fabs(qtot - njobs_chain) > std::max(0.05 * njobs_chain, 0.05)) {
1410 char buf[512];
1411 std::snprintf(buf, sizeof(buf),
1412 "LDES returned %.3f jobs for closed chain %zu, whose population is %g: the engine "
1413 "dropped blocked jobs at a finite-capacity station, so these averages describe a "
1414 "different model. Use SolverCTMC/SolverSSA for capped closed networks, or rebuild "
1415 "common/ldes.jar.",
1416 qtot, nc + 1, njobs_chain);
1417 out.push_back(buf);
1418 }
1419 }
1420 return out;
1421}
1422
1423template <class T>
1425 const std::vector<std::string>& extra_flags =
1426 std::vector<std::string>()) {
1428 LdesResult r = solver_ldes_text(io::network_json_envelope(sn).dump(), o, extra_flags);
1429 // Steady state only, as MATLAB's parseSteady runs it; SILENT mutes it as line_warning does.
1430 if (!o.has_timespan && !r.timed_out &&
1432 const std::vector<std::string> w = ldes_closed_population_warnings(sn, r.QN);
1433 for (std::size_t k = 0; k < w.size(); ++k)
1434 std::fprintf(stderr, "[SolverLDES] Warning: %s\n", w[k].c_str());
1435 }
1436 return r;
1437}
1438
1439/**
1440 * `getPerctRespT` on a model built in C++: one `--respt-samples` run with the
1441 * caller's knobs (replications included), then `ldes_perct_respt` on it, with the
1442 * procedure picked from `ldes_replications(o)` and the level from `ldes_perct_level(o)`.
1443 */
1444template <class T>
1445std::vector<LdesPercentileResult> ldes_perct_respt(const qn::NetworkStruct<T>& sn, const LdesOptions& o,
1446 const std::vector<double>& percentiles,
1447 const std::string& method = std::string(),
1448 long job_class = -1) {
1449 const int R = ldes_replications(o);
1450 // Resolve (and refuse) the method before paying for the simulation.
1451 ldes_perct_method(R, method);
1452 const LdesResult r = solver_ldes(sn, o, std::vector<std::string>(1, "--respt-samples"));
1453 return ldes_perct_respt(r, percentiles, R, method, ldes_perct_level(o), job_class);
1454}
1455
1456/**
1457 * One exact sample path as `sample`, `sampleAggr`, `sampleSys` and
1458 * `sampleSysAggr` return it, read off the engine's `samplePath` block.
1459 *
1460 * THE ROW CONVENTION IS SolverSSA's (`ssa::SsaSamplePath`): row k is the state
1461 * OCCUPIED UNTIL `t[k]`, and the events that end it happen at `t[k]`. Unlike the
1462 * SSA path, several events can share a row (a departure that starts the next
1463 * service is DEP plus START at one epoch), so the events are a matrix keyed by
1464 * time and not one synchronization index per row.
1465 */
1467 std::vector<double> t; ///< the step times, one per row
1468 /**
1469 * One row per event, [time, node, type, class, jobId, phase]: node and class
1470 * 0-based as on the wire, type an `EventType` value (ARV 1, DEP 2, PHASE 3,
1471 * START 15, PREEMPT 16, DROP 17), jobId -1 when untracked, phase 1-based
1472 * with 0 = none.
1473 */
1475 std::vector<std::size_t> nodes; ///< 1-based node index of each block of `state`
1476 std::vector<Matrix<double> > block; ///< per node, rows aligned with `t`
1477 /** The blocks side by side, the single matrix `ssa::SsaSamplePath::state` is. */
1479 bool aggregate = false; ///< per-class counts rather than LINE State rows
1480 double sim_time = 0.0; ///< the simulated clock at the stop
1481 long long unbound_scripts = 0; ///< drawn intervals recorded as a single phase
1482};
1483
1484namespace sample_detail {
1485
1486/** Runs the engine with `--sample-path events` and returns its block. */
1487template <class T>
1488LdesSamplePath run(const qn::NetworkStruct<T>& sn, const LdesOptions& o_in, std::size_t events) {
1489 if (events == 0)
1490 throw InputError("SolverLDES: a sample path needs a positive number of rows (events)");
1491 LdesOptions o = o_in;
1492 o.sample_path_events = static_cast<int>(events);
1493 const LdesResult r = solver_ldes(sn, o);
1494 if (!r.has_sample_path)
1495 throw NumericError(ErrorKind{"InvalidResult"},
1496 "SolverLDES: the engine (" + r.engine + ") returned no samplePath block for "
1497 "--sample-path; it predates the export, so rebuild common/ldes or common/ldes.jar");
1498 return r.sample_path;
1499}
1500
1501/** The event rows of node `node0` (0-based), or of every node when it is negative. */
1502inline Matrix<double> events(const LdesSamplePath& sp, long node0) {
1503 std::size_t n = 0;
1504 for (std::size_t k = 0; k < sp.events.size(); ++k)
1505 if (sp.events[k].size() >= 7 &&
1506 (node0 < 0 || static_cast<long>(sp.events[k][3]) == node0))
1507 ++n;
1508 Matrix<double> m(n, 6, 0.0);
1509 std::size_t i = 0;
1510 for (std::size_t k = 0; k < sp.events.size(); ++k) {
1511 const std::vector<double>& e = sp.events[k];
1512 if (e.size() < 7 || (node0 >= 0 && static_cast<long>(e[3]) != node0)) continue;
1513 m(i, 0) = e[1];
1514 m(i, 1) = e[3];
1515 m(i, 2) = e[2];
1516 m(i, 3) = e[4];
1517 m(i, 4) = e[5];
1518 m(i, 5) = e[6];
1519 ++i;
1520 }
1521 return m;
1522}
1523
1524/** The stateful position of 1-based node `ind` in the block, or a refusal naming it. */
1525template <class T>
1526std::size_t stateful_of(const qn::NetworkStruct<T>& sn, const LdesSamplePath& sp, std::size_t ind) {
1527 for (std::size_t f = 0; f < sp.stateful_nodes.size(); ++f)
1528 if (static_cast<std::size_t>(sp.stateful_nodes[f]) + 1 == ind) return f;
1529 const std::string name = (ind >= 1 && ind <= sn.nodes.size()) ? sn.nodes[ind - 1].name
1530 : "#" + std::to_string(ind);
1531 throw InputError("SolverLDES: node '" + name + "' is not stateful and has no sample path");
1532}
1533
1534/** The detailed rows of stateful position `f`, or the engine's refusal by name. */
1535template <class T>
1537 std::size_t f) {
1538 if (!sp.refusals[f].empty()) {
1539 const std::size_t ind = static_cast<std::size_t>(sp.stateful_nodes[f]) + 1;
1540 const std::string name = ind <= sn.nodes.size() ? sn.nodes[ind - 1].name
1541 : "#" + std::to_string(ind);
1542 throw UnsupportedError(ErrorKind{"SamplePath"},
1543 "SolverLDES: detailed sample-path rows are not available at node '" + name + "' (" +
1544 sp.refusals[f] + "); sampleAggr and sampleSysAggr still apply.");
1545 }
1546 return sp.state[f];
1547}
1548
1549/** Fills t, the provenance fields and the joined `state` of an assembled sample. */
1550inline void finish(const LdesSamplePath& sp, LdesSample& out) {
1551 out.t = sp.t;
1552 out.sim_time = sp.sim_time;
1554 std::size_t width = 0;
1555 for (std::size_t b = 0; b < out.block.size(); ++b) width += out.block[b].cols();
1556 out.state = Matrix<double>(sp.t.size(), width, 0.0);
1557 std::size_t col = 0;
1558 for (std::size_t b = 0; b < out.block.size(); ++b) {
1559 const Matrix<double>& m = out.block[b];
1560 for (std::size_t i = 0; i < m.rows() && i < sp.t.size(); ++i)
1561 for (std::size_t j = 0; j < m.cols(); ++j) out.state(i, col + j) = m(i, j);
1562 col += m.cols();
1563 }
1564}
1565
1566} // namespace sample_detail
1567
1568/**
1569 * `sample(node, events)`: the exact path of one stateful node (1-based `ind`),
1570 * one LINE State row per step and the node's own events.
1571 *
1572 * Refused by name (`LINE:unsupported:SamplePath`) at a node whose detailed rows
1573 * the engine could not encode; `ldes_sample_aggr` still answers there.
1574 */
1575template <class T>
1577 std::size_t events) {
1578 const LdesSamplePath sp = sample_detail::run(sn, o, events);
1579 const std::size_t f = sample_detail::stateful_of(sn, sp, ind);
1580 LdesSample out;
1581 out.nodes.push_back(ind);
1582 out.block.push_back(sample_detail::detail_rows(sn, sp, f));
1583 out.event = sample_detail::events(sp, static_cast<long>(ind) - 1);
1584 sample_detail::finish(sp, out);
1585 return out;
1586}
1587
1588/** `sampleAggr(node, events)`: the same path as per-class counts, always available. */
1589template <class T>
1591 std::size_t events) {
1592 const LdesSamplePath sp = sample_detail::run(sn, o, events);
1593 const std::size_t f = sample_detail::stateful_of(sn, sp, ind);
1594 LdesSample out;
1595 out.aggregate = true;
1596 out.nodes.push_back(ind);
1597 out.block.push_back(sp.aggr[f]);
1598 out.event = sample_detail::events(sp, static_cast<long>(ind) - 1);
1599 sample_detail::finish(sp, out);
1600 return out;
1601}
1602
1603/**
1604 * `sampleSys(events)`: the LINE State of every stateful node at each step, and
1605 * every event of the run. Refused when any node's detailed rows are.
1606 */
1607template <class T>
1609 std::size_t events) {
1610 const LdesSamplePath sp = sample_detail::run(sn, o, events);
1611 LdesSample out;
1612 for (std::size_t f = 0; f < sp.stateful_nodes.size(); ++f) {
1613 out.nodes.push_back(static_cast<std::size_t>(sp.stateful_nodes[f]) + 1);
1614 out.block.push_back(sample_detail::detail_rows(sn, sp, f));
1615 }
1616 out.event = sample_detail::events(sp, -1);
1617 sample_detail::finish(sp, out);
1618 return out;
1619}
1620
1621/** `sampleSysAggr(events)`: the per-class counts of every stateful node at each step. */
1622template <class T>
1624 std::size_t events) {
1625 const LdesSamplePath sp = sample_detail::run(sn, o, events);
1626 LdesSample out;
1627 out.aggregate = true;
1628 for (std::size_t f = 0; f < sp.stateful_nodes.size(); ++f) {
1629 out.nodes.push_back(static_cast<std::size_t>(sp.stateful_nodes[f]) + 1);
1630 out.block.push_back(sp.aggr[f]);
1631 }
1632 out.event = sample_detail::events(sp, -1);
1633 sample_detail::finish(sp, out);
1634 return out;
1635}
1636
1637} // namespace ldes
1638} // namespace line
1639
1640#endif // LINE_SOLVERS_WRAPPERS_LDES_SOLVER_LDES_H
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
NumericError(const std::string &what)
Definition error.h:112
UnsupportedError(const std::string &what)
Definition error.h:119
Transport-level failure: unresolvable host, refused connection, timeout.
Definition http.h:54
A network plus its refreshed NetworkStruct.
static VerboseLevel get_verbose()
The session verbosity.
static void step(const char *fmt,...)
Write one progress line.
std::string file(const std::string &name) const
A file inside it.
Definition tempdir.h:127
The RAII frame timeout_arm returns.
The exception types the port throws.
Fork-join section metrics: FJQLen, FJRespT and FJTput of every Fork/Join pair.
Minimal HTTP/1.1 client, enough to talk to a line-*-rest service.
The option and result records of SolverLDES, the discrete-event simulator.
Where the LDES engine is, and whether this machine can run it.
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.
Dense matrix and non-owning view.
Response post_json(const std::string &url, const std::string &json, int timeoutMillis)
POST a JSON document.
Definition http.h:360
void require_finite_pas_buffers(const qn::NetworkStruct< T > &sn)
Refuse an OI/PAS station with no finite buffer before it reaches LDES.
detail::json network_json_envelope(const qn::NetworkStruct< T > &sn)
The complete model.json envelope: {format, version, model}.
std::size_t stateful_of(const qn::NetworkStruct< T > &sn, const LdesSamplePath &sp, std::size_t ind)
The stateful position of 1-based node ind in the block, or a refusal naming it.
Matrix< double > events(const LdesSamplePath &sp, long node0)
The event rows of node node0 (0-based), or of every node when it is negative.
const Matrix< double > & detail_rows(const qn::NetworkStruct< T > &sn, const LdesSamplePath &sp, std::size_t f)
The detailed rows of stateful position f, or the engine's refusal by name.
void finish(const LdesSamplePath &sp, LdesSample &out)
Fills t, the provenance fields and the joined state of an assembled sample.
LdesSamplePath run(const qn::NetworkStruct< T > &sn, const LdesOptions &o_in, std::size_t events)
Runs the engine with --sample-path events and returns its block.
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.
LdesResult solver_ldes_text(const std::string &doc, const LdesOptions &o, const std::vector< std::string > &extra_flags=std::vector< std::string >())
Runs one LDES simulation on a model.json DOCUMENT and parses its result.
double ldes_prob_sys_aggr(const std::string &doc, const LdesOptions &o, const Matrix< double > &target)
Port of getProbSysAggr: the joint probability of a whole aggregate state.
LdesResult solver_ldes_file(const std::string &path, const LdesOptions &o, const std::vector< std::string > &extra_flags=std::vector< std::string >())
The same, reading the document from a file.
const std::string & ldes_engine_dir()
The directory holding the engine, or empty when there is none.
Definition ldes_probe.h:247
std::vector< std::string > ldes_flags(const LdesOptions &o, const std::vector< std::string > &extra)
The engine flags of one run, after solve <model> -o <result>.
double ldes_perct_level(const LdesOptions &o)
The confidence level getPerctRespT uses: confint when intervals are on (a level in (0,...
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::vector< double > ldes_perct_levels(const std::vector< double > &percentiles)
The percentile levels as fractions: any entry above 1 makes the whole vector PERCENT,...
LdesResult parse_ldes_result(const detail::Json &d)
Parses one ldes-result document.
double ldes_prob_aggr(const std::string &doc, const LdesOptions &o, std::size_t station, const std::vector< double > &counts, std::size_t nclasses)
Port of getProbAggr: the marginal probability of a per-class job count at one station.
detail::Json ldes_solve_rest(const std::string &base_url, const std::string &doc, const std::vector< std::string > &flags, double timeout)
Solves through an LDES REST server and returns its result document.
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::vector< LdesRunner > ldes_runners(const std::string &doc, const std::vector< std::string > &flags)
The runners to try, in order (see the file header for why there are two and when the order flips).
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),...
std::vector< std::string > ldes_closed_population_warnings(const qn::NetworkStruct< T > &sn, const Matrix< double > &QN)
The same, for a model built through the C++ API.
bool in(const std::string &s, std::initializer_list< const char * > set)
const std::string * get(const Element *el, const std::string &key)
el.get(key), with Python's None as a null pointer.
Definition srvn_writer.h:62
QuestResult< T > sim_fquest(const std::vector< T > &Y, double p, double alpha=0.05, const QuestOptions &options=QuestOptions())
Fixed-sample-size confidence interval for a steady-state quantile.
Definition sim_fquest.h:130
QuestResult< T > sim_firquest(const std::vector< std::vector< T > > &Y, double p, double alpha=0.05, const QuestOptions *options=nullptr)
Fixed-sample-size quantile interval from independent replications.
std::vector< std::pair< std::size_t, std::size_t > > fj_sorted_pairs(const S &sn)
The Fork/Join pairs of a struct, sortrows([forks joins]) over find(sn.fj): ascending in fork node,...
Definition fj_metrics.h:62
FjMetrics< T > fj_metrics_zero(const S &sn, std::size_t nclasses)
An empty-but-shaped result: every pair of sn, all three matrices zero.
Definition fj_metrics.h:73
void timeout_trip()
Mark the innermost budget tripped without reading the clock: for an external engine that REPORTS it s...
TimeoutScope timeout_arm(double budget)
Arm budget seconds for the scope's lifetime, capped by the outer frame's remaining time.
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
std::string trim(const std::string &s)
Trims ASCII whitespace from both ends, as Java's String.trim() does.
Definition subprocess.h:181
double timeout_remaining()
Seconds left on the innermost armed budget; +Inf when none is armed.
int timeout_kill_seconds(double grace=30.0)
The hard kill bound of a child process under the armed budget: the remaining seconds plus grace,...
bool timeout_tripped()
Whether the innermost budget was tripped by a checkpoint or by timeout_trip.
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...
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
qn::NetworkStruct -> model.json, the inverse of network_reader.h.
Fixed-sample-size quantile interval from independent replications.
Fixed-sample-size confidence interval for a steady-state quantile.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
An HTTP response, with the body already de-chunked.
Definition http.h:60
std::string body
Response body, decoded.
Definition http.h:62
int status
HTTP status code.
Definition http.h:61
Per-cache hit/miss/latency, as the cacheMetrics block carries them.
Matrix< double > listCost
(1 x nlists) mean storage cost held per list
Matrix< double > latency
(1 x nclasses) expected retrieval latency
Matrix< double > hitList
(nclasses x nlists) hit probability by list
Matrix< double > itemProb
(nitems x nlists+1) item position law
Matrix< double > delayed
(1 x nclasses) delayed-hit probability
Matrix< double > miss
(1 x nclasses) miss probability
Matrix< double > hit
(1 x nclasses) hit probability
The knobs of one LDES run.
double warmupfrac
–warmupfrac, only for tranfilter=fixed
int ciminbatch
–ciminbatch
double spectral_low_freq_frac
–spectrallowfreqfrac
bool verbose
echo the resolved command line before running it
double cnvgtol
–cnvgtol
double confint
Confidence level of the reported half-widths.
std::string rest_url
Base URL of an LDES REST server (the imperialqore/ldes container).
double obmoverlap
–obmoverlap; 0 reduces OBM to plain batch means
std::vector< std::vector< std::size_t > > busy_period_subnets
–busyperiod-subnet, zero-based station indexes, one flag per set.
long seed
–seed; -1 requests a random stream
bool slotted
–slotted, run on the slot lattice
int mserbatch
–mserbatch, MSER batch size
std::string cimethod
–cimethod: obm | bm | spectral | none
double slot_length
–slotlength
Matrix< double > init_jobs
–initjobs, the JOB-LEVEL initial state, one row per job: [station, class, remaining,...
int tranobs
–tranobs, equally spaced transient observation points over [t0,t1]; fixes the time grid only.
int cnvgchk
–cnvgchk, events between checks; 0 = samples/50
int replications
–replications; 0 = not given (one path)
int sample_path_events
–sample-path N: record the exact sample path, N rows of SolverSSA-style events plus LINE State,...
bool track_jobs
–trackjobs: fill finalJobs and jobDepartures; implied by init_jobs.
int ciminobs
–ciminobs, below which no CI is reported
std::size_t events
0 = not given; overrides samples when set
int cnvgbatch
–cnvgbatch, batches before the first check
std::string tranfilter
–tranfilter: mser5 | fixed | none
std::vector< double > init_sol
–initsol, the warm-start placement as a STATION-MAJOR vector [st0_cl0, st0_cl1, .....
int numthreads
–numthreads; 0 = not given
std::size_t samples
-s, service-completion budget
double timeout
–maxtime, a COOPERATIVE wall-clock budget the event loop polls; the wrapper caps it by any options....
bool has_timespan
true when [t0,t1] was set: a TRANSIENT run
int busy_period_orders
–busyperiod: highest busy period order measured, 0 disabling the measurement.
One (station, class) row of getPerctRespT on SolverLDES: the steady-state response-time p-quantiles w...
std::vector< bool > heuristic
true where the fallback interval was used
std::string station
node name of the station
double level
confidence level
std::vector< double > halfwidth
halfwidths
std::vector< double > lower
lower confidence limits
std::size_t station_index
0-based station index in the result
std::vector< double > upper
upper confidence limits
std::vector< double > percentiles
fractions in (0,1)
std::size_t class_index
0-based class index in the result
std::string job_class
class name (class in MATLAB / Python)
std::size_t samples
observations used (per replication after trimming, times R)
std::vector< double > values
point estimates (QuestResult::estimate)
std::string method
"fquest" or "firquest"
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::string > fj_forks
Fork and Join node NAMES of each pair, ordered by fork node then join node; empty without a pair.
Matrix< double > FJTput
getAvgFJ, FJQLen = FJTput * FJRespT
std::vector< std::vector< std::vector< double > > > respTimeSamples
[station][class] -> the per-job response times the engine recorded, in departure order.
Matrix< double > FJQLen
Matrix< double > FJRespT
bool has_sample_path
–sample-path: the recorded path; meaningful when has_sample_path.
std::vector< std::vector< std::vector< std::vector< double > > > > respTimeSamplesRep
[rep][station][class][j] -> the same samples kept PER REPLICATION, each in departure order with the w...
Matrix< double > histogram_space
The exact joint-state residence-time histogram (–export-histogram).
std::vector< std::string > class_names
std::string engine
"native" or "jar": which runner produced these numbers.
std::vector< std::string > station_names
std::vector< std::string > fj_joins
bool timed_out
True when the run stopped early on its wall-clock budget (timeout, or the options....
Matrix< double > histogram_time
LdesSamplePath sample_path
Matrix< double > QN
One runner: the argv prefix that runs the engine, and the name of its image.
std::vector< std::string > argv
up to and including "solve"
std::string engine
"native" or "jar"
The samplePath block (--sample-path N): one simulated path in SolverSSA's row convention.
std::vector< Matrix< double > > aggr
[stateful] per-class counts per row (Inf at a source).
std::vector< std::vector< double > > events
Rows {step, time, type, node, class, jobId, phase}.
std::vector< int > stateful_nodes
0-based node index of each stateful node, in stateful order.
std::vector< std::vector< int > > phases
[stateful][class] phase count used for the state layout.
std::vector< Matrix< double > > state
[stateful] detailed rows (empty when refused), left-padded to equal width.
std::vector< std::string > refusals
[stateful] why the detailed state is not recorded, empty when it is.
std::vector< double > t
long long unbound_scripts
Drawn intervals no phase script could be bound to (recorded as one phase).
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
double sim_time
the simulated clock at the stop
std::vector< std::size_t > nodes
1-based node index of each block of state
long long unbound_scripts
drawn intervals recorded as a single phase
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
Point estimate and interval delivered by the QUEST procedures.
Definition sim_fquest.h:84
T halfwidth
(upper-lower)/2, attained only on average when asymmetric
Definition sim_fquest.h:88
T estimate
Full-sample empirical p-quantile of the truncated path.
Definition sim_fquest.h:85
T upper
Upper confidence limit, NaN if refused.
Definition sim_fquest.h:87
bool heuristic
True when a stage test failed.
Definition sim_fquest.h:97
T lower
Lower confidence limit, NaN if refused.
Definition sim_fquest.h:86
self.result.FJ: one row per Fork/Join pair, one column per class.
Definition fj_metrics.h:43
std::vector< std::size_t > forks
1-based fork node of each pair
Definition fj_metrics.h:44
Matrix< T > Tput
FJTput, P x R.
Definition fj_metrics.h:48
Matrix< T > QLen
FJQLen, P x R.
Definition fj_metrics.h:46
std::size_t npairs() const
Definition fj_metrics.h:53
std::vector< std::size_t > joins
1-based join node of each pair
Definition fj_metrics.h:45
Matrix< T > RespT
FJRespT, P x R.
Definition fj_metrics.h:47
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
bool timedOut
True when the deadline expired and the child was killed.
Definition subprocess.h:45
std::string out
Everything the command wrote to stdout.
Definition subprocess.h:44
Running an external command and capturing its output, with a deadline.
A scratch directory for the subprocess wrappers, the port's lineTempName.