LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_jmt.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_JMT_SOLVER_JMT_H
6#define LINE_SOLVERS_WRAPPERS_JMT_SOLVER_JMT_H
7
8/**
9 * @file
10 * @ingroup line_solvers
11 * Port of `SolverJMT`, the Java Modelling Tools client.
12 *
13 * WHAT A JMT SOLVE IS. The model is written out as a JMT document -- a
14 * `.jsimg` for the discrete-event engine, a `.jmva` for the analytical one --
15 * `jmt.commandline.Jmt` is run on it, and the result document JMT leaves beside
16 * the model is parsed back into the same `AvgResult` every other solver in this
17 * port returns. The translation is `io/jmt_writer.h` and the SHARED
18 * `io/jmva_writer.h`, which SolverLQNS writes through as well; this file is the
19 * dispatch, the parse and the metric mapping.
20 *
21 * THREE WAYS TO REACH JMT, in the order `jmtRun.m` tries them:
22 * 1. `options.rest_url`, a JMT REST server (the imperialqore/jmt-rest image).
23 * Nothing runs locally.
24 * 2. a local JVM plus `common/JMT.jar`, the default.
25 * 3. no JVM, but a usable Docker daemon: the same image, run as a container.
26 * Every one of them leaves the result at `<model>-result.jsim` or
27 * `<model>-result.jmva`, so the parsers do not know which one ran. That
28 * contract is what makes the three interchangeable, and it is why the Docker
29 * arm copies the container's output back beside the model.
30 *
31 * CONSENT IS NOT ASSUMED, FOR EITHER FETCH. The Docker arm is reached only when
32 * `LINE_JMT_DOCKER` opts in, and the jar is downloaded only when
33 * `LINE_JMT_DOWNLOAD` does: this port has no terminal to ask at -- the reference
34 * prompts, and refuses in a `-batch` session -- so an absent variable is a
35 * refusal, exactly as an empty answer is there. Fetching 31 MiB because a solver
36 * was called is not a decision a library may take on its own.
37 *
38 * WHAT THE FETCH ADDS OVER THE REFERENCE, once consented to: the transfer is
39 * https and stays https across redirects, the bytes are checked against a pinned
40 * SHA-256 (`JMT_JAR_SHA256`) before anything is installed, and the file is
41 * renamed into place only after it verifies. MATLAB, the JAR and python all
42 * trust the transport and stop there, so the C++ edition is the only one that
43 * authenticates the jar itself; `LINE_JMT_SHA256` takes a different digest
44 * deliberately and `LINE_JMT_URL` a mirror.
45 *
46 * WHAT IS NOT PORTED, and why it is refused rather than approximated:
47 * getProbAggr / getProbSysAggr Both weigh the simulated trajectory against
48 * `sn.state{isf}`, the model's CURRENT state,
49 * which `qn::NetworkStruct` does not carry --
50 * the same gap that stops `SolverLDES`'s
51 * `getProb` in this port.
52 * the transient ensemble `default` over a finite timespan averages
53 * `sampleSysAggr` over `config.replications`
54 * seeds, and `sampleSysAggr` reads the JMT
55 * arrival/departure LOG files, which requires
56 * a Logger on every station of the model; it is
57 * composed from `jmt_sample_sys_aggr` in
58 * `jmt_logs.h` (`jmt_transient_replications`).
59 */
60
62#include <algorithm>
63#include <cctype>
64#include <cmath>
65#include <cstdio>
66#include <cstdlib>
67#include <fstream>
68#include <limits>
69#include <map>
70#include <set>
71#include <sstream>
72#include <string>
73#include <vector>
74
75#include <sys/stat.h>
76#include <unistd.h>
77
80#include "line/io/jmva_writer.h"
81#include "line/io/jmt_writer.h"
86#include "line/util/error.h"
87#include "line/util/http.h"
89#include "line/util/sha256.h"
91#include "line/util/tempdir.h"
92#include "line/util/xml.h"
94
95namespace line {
96namespace jmt {
97
98/** The default JMT REST/Docker image, MATLAB's `jmtDockerImage` candidate. */
99static const char* JMT_DOCKER_IMAGE = "imperialqore/jmt-rest:latest";
100
101/** Where a missing jar is fetched from; `LINE_JMT_URL` names a mirror instead. */
102static const char* JMT_JAR_URL = "https://line-solver.sourceforge.net/latest/JMT.jar";
103
104/**
105 * The digest a fetched jar must have, and the reason the fetch can be trusted.
106 *
107 * The bytes at `JMT_JAR_URL` are a ROLLING BUILD: the path says `latest`, the
108 * jar's own `META-INF/maven/jmt/jmt-light/pom.properties` says `version=latest`,
109 * and it is republished without a version number changing anywhere. So there is
110 * nothing to pin BY NAME, and this is the digest of the build the port was
111 * tested against (published 2026-07-30, 32772660 bytes).
112 *
113 * WHEN UPSTREAM REPUBLISHES, THE DOWNLOAD FAILS LOUDLY and names both digests.
114 * That is the intended failure: the alternative is a solver that silently picks
115 * up whatever a `latest` URL happens to serve. Set `LINE_JMT_SHA256` to the new
116 * digest to take the new build deliberately, and update this constant when the
117 * suite has been run against it.
118 */
119static const char* JMT_JAR_SHA256 =
120 "932cf6b34b04f9ba5b7c3ba0b07dc6c9fa80aa816ffcad7a39ac5d20a31bb9cd";
121
122/** The options of one JMT solve, `SolverOptions('JMT')` restricted to what is read. */
124 std::string method = "default"; ///< default | jsim | jmva | `jmva.<alg>`
125 double samples = 10000.0; ///< samples per measure; raised to 5000 below
126 long seed = 23000;
127 bool keep = false; ///< keep the scratch directory after the solve
128 double confint = 0.99; ///< 0 disables the confidence interval columns
129 double max_simulated_time = std::numeric_limits<double>::infinity();
130 double max_events = -1.0; ///< JSIM event budget, -1 unlimited; set by the samplers as MATLAB's maxEvents
131 std::string rest_url; ///< a JMT REST server; empty selects the local JVM
132 std::string container; ///< `options.config.container`, an image override
133 /**
134 * Seconds, an EXPLICIT hard bound on the REST and subprocess arms; 0 (the
135 * default) sets none of its own. `options.timeout` reaches JMT through the
136 * armed budget (line/util/line_timeout.h) instead: JSIM gets `-maxtime` and
137 * the child a kill bound of the remaining budget plus 30 s, so an unbudgeted
138 * solve runs to completion however long it takes.
139 */
140 int timeout = 0;
141 bool verbose = false;
142 /**
143 * `options.config.replications`: the independent JSIM runs the transient ensemble of `default`
144 * averages over a finite timespan, seeded `seed`, `seed+1`, ... No effect on steady-state JSIM.
145 */
146 int replications = 10;
147};
148
149namespace detail {
150
151inline bool is_file(const std::string& p) {
152 struct stat st;
153 return !p.empty() && ::stat(p.c_str(), &st) == 0 && S_ISREG(st.st_mode);
154}
155
156inline bool is_exec(const std::string& p) {
157 struct stat st;
158 return !p.empty() && ::stat(p.c_str(), &st) == 0 && ::access(p.c_str(), X_OK) == 0;
159}
160
161inline bool is_dir(const std::string& p) {
162 struct stat st;
163 return !p.empty() && ::stat(p.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
164}
165
166inline std::string env_or_empty(const char* name) {
167 const char* v = std::getenv(name);
168 return v != nullptr ? std::string(v) : std::string();
169}
170
171inline std::string exe_dir() {
172 char buf[4096];
173 const ssize_t n = ::readlink("/proc/self/exe", buf, sizeof(buf) - 1);
174 if (n <= 0) return std::string();
175 std::string p(buf, static_cast<std::size_t>(n));
176 const std::size_t s = p.find_last_of('/');
177 return s == std::string::npos ? std::string() : p.substr(0, s);
178}
179
180inline std::string cwd() {
181 char buf[4096];
182 return ::getcwd(buf, sizeof(buf)) != nullptr ? std::string(buf) : std::string();
183}
184
185/**
186 * The `-Djava.io.tmpdir` switch that keeps one run's JMT scratch private.
187 *
188 * NOT A TIDINESS MEASURE: without it two JMT runs on one host CORRUPT EACH
189 * OTHER. `jmt.commandline.Jmt` hands the engine a copy of the model under
190 * `java.io.tmpdir`, and `XMLSimulationOutput.writeAllMeasures` then writes the
191 * measures to `<that dir>/res_sim_<the sim's name attribute>`, copies that file
192 * to `<model>-result.jsim` and DELETES it. Every LINE-written model carries the
193 * same name attribute -- `model.jsim`, from `jmt_write_jsim` and its
194 * MATLAB/JAR/python twins -- so with a shared /tmp every concurrent run fights
195 * over one path, `/tmp/res_sim_model.jsim`. Two outcomes, both seen in the
196 * 2026-09-11 suite: the other run deletes the file first and this one dies
197 * `FileNotFoundException ... at jmt.commandline.Jmt.copyFile`, or it copies the
198 * OTHER run's measures and reports another model's numbers as its own. The
199 * model already sits in a `util::TempDir` of its own, so pointing the JVM's
200 * temp dir at it makes every scratch file this run creates private to it.
201 */
202inline std::string private_tmpdir_flag(const std::string& model_path) {
203 const std::size_t s = model_path.find_last_of('/');
204 const std::string dir = s == std::string::npos ? cwd() : model_path.substr(0, s);
205 return "-Djava.io.tmpdir=" + (dir.empty() ? cwd() : dir);
206}
207
208/**
209 * Port of `jmtGetPath`'s SEARCH; the download is `jmt_download_jar` below.
210 *
211 * The reference fetches JMT.jar from SourceForge the moment it is missing. This
212 * function never does: it reports what is already on disk and returns empty
213 * otherwise, so a caller that only wants to know where the jar is -- the CLI's
214 * environment report, a test deciding whether to skip -- can ask without the
215 * question installing anything. `jmt_run` is what escalates from the empty
216 * answer to a fetch, and only with consent.
217 *
218 * `$LINE_JMT_DIR` overrides the search, for a jar kept outside the tree.
219 */
220inline std::string jmt_jar_path() {
221 const std::string forced = env_or_empty("LINE_JMT_DIR");
222 if (!forced.empty()) return is_file(forced + "/JMT.jar") ? forced : std::string();
223 const std::string roots[2] = {exe_dir(), cwd()};
224 for (int r = 0; r < 2; ++r) {
225 if (roots[r].empty()) continue;
226 std::string dir = roots[r];
227 for (int k = 0; k < 7; ++k) {
228 if (is_file(dir + "/JMT.jar")) return dir;
229 if (is_file(dir + "/common/JMT.jar")) return dir + "/common";
230 dir += "/..";
231 }
232 }
233 return std::string();
234}
235
236/** The first executable `name` on PATH; empty when there is none. */
237inline std::string which_on_path(const std::string& name) {
238 const std::string path = env_or_empty("PATH");
239 std::size_t b = 0;
240 while (b <= path.size()) {
241 const std::size_t e = path.find(':', b);
242 const std::string dir =
243 path.substr(b, e == std::string::npos ? std::string::npos : e - b);
244 if (!dir.empty() && is_exec(dir + "/" + name)) return dir + "/" + name;
245 if (e == std::string::npos) break;
246 b = e + 1;
247 }
248 return std::string();
249}
250
251/** `$LINE_JAVA`, then `$JAVA_HOME/bin/java`, then PATH; empty when absent. */
252inline std::string find_java() {
253 const std::string forced = env_or_empty("LINE_JAVA");
254 if (!forced.empty()) return is_exec(forced) ? forced : std::string();
255 const std::string home = env_or_empty("JAVA_HOME");
256 if (!home.empty() && is_exec(home + "/bin/java")) return home + "/bin/java";
257 return which_on_path("java");
258}
259
260/** `LINE_JMT_DOCKER` in the affirmative; anything else, including unset, is no. */
261inline bool docker_consented() {
262 const std::string v = env_or_empty("LINE_JMT_DOCKER");
263 return v == "1" || v == "true" || v == "TRUE" || v == "yes" || v == "y" || v == "Y";
264}
265
266/**
267 * `LINE_JMT_DOWNLOAD` in the affirmative; anything else, including unset, is no.
268 *
269 * SAME VARIABLE AS THE OTHER THREE EDITIONS, OPPOSITE DEFAULT. There the jar is
270 * fetched unless `LINE_JMT_DOWNLOAD=0` refuses it; here it is fetched only when
271 * something affirms it. So `=1` and `=0` mean the same thing everywhere and only
272 * the unset case differs, which is the policy difference itself: MATLAB, the JAR
273 * and python prompt at a session and this port has nobody to ask.
274 */
275inline bool download_consented() {
276 const std::string v = env_or_empty("LINE_JMT_DOWNLOAD");
277 return v == "1" || v == "true" || v == "TRUE" || v == "yes" || v == "y" || v == "Y";
278}
279
280/**
281 * Where a downloaded jar is written: `$LINE_JMT_DIR`, else the tree's `common/`,
282 * else the working directory.
283 *
284 * The walk is `jmt_jar_path`'s, looking for the DIRECTORY the jar belongs in
285 * rather than for the jar, so the download lands where the next process's search
286 * will find it. `$LINE_JMT_DIR` wins because it is where the caller has said the
287 * jar lives, and a download that ignored it would be invisible to the search
288 * that runs next.
289 */
290inline std::string jmt_download_dir() {
291 const std::string forced = env_or_empty("LINE_JMT_DIR");
292 if (!forced.empty()) return forced;
293 const std::string roots[2] = {exe_dir(), cwd()};
294 for (int r = 0; r < 2; ++r) {
295 if (roots[r].empty()) continue;
296 std::string dir = roots[r];
297 for (int k = 0; k < 7; ++k) {
298 if (is_dir(dir + "/common")) return dir + "/common";
299 dir += "/..";
300 }
301 }
302 return cwd();
303}
304
305/**
306 * Fetches `url` to `dest` with curl, or wget, whichever is on PATH.
307 *
308 * NEITHER IS A DEPENDENCY OF THE BUILD: this arm runs only when the caller has
309 * opted in, and a host with neither tool simply does not get the download. That
310 * is the whole reason the transfer is delegated rather than written here --
311 * libcurl would be a link-time obligation on every binary in the tree, and the
312 * port's own `util/http.h` has no TLS and refuses `https://` by name, which is
313 * the only scheme SourceForge serves the jar on (plain HTTP answers 301).
314 *
315 * Both are told to stay on https ACROSS REDIRECTS, not merely on the first
316 * request: the published URL is a redirect to begin with, and a downgrade to
317 * plaintext part-way through is exactly what must not pass unnoticed. Both
318 * inherit stdio, so the caller sees the transfer's own progress, as the Docker
319 * arm lets `docker pull` report its own.
320 */
321inline std::string find_fetcher() {
322 const std::string curl = which_on_path("curl");
323 return curl.empty() ? which_on_path("wget") : curl;
324}
325
326inline bool fetch_url(const std::string& tool, const std::string& url, const std::string& dest) {
327 const bool is_curl = tool.size() >= 4 && tool.compare(tool.size() - 4, 4, "curl") == 0;
328 if (is_curl) {
329 std::vector<std::string> argv;
330 argv.push_back(tool);
331 argv.push_back("-fL");
332 argv.push_back("--proto");
333 argv.push_back("=https");
334 argv.push_back("--proto-redir");
335 argv.push_back("=https");
336 argv.push_back("--tlsv1.2");
337 argv.push_back("--connect-timeout");
338 argv.push_back("30");
339 argv.push_back("--max-time");
340 argv.push_back("1800");
341 argv.push_back("-o");
342 argv.push_back(dest);
343 argv.push_back(url);
344 return util::run_inherit(argv) == 0;
345 }
346 if (tool.empty()) return false;
347 std::vector<std::string> argv;
348 argv.push_back(tool);
349 argv.push_back("--https-only");
350 argv.push_back("--timeout=30");
351 argv.push_back("--tries=2");
352 argv.push_back("-O");
353 argv.push_back(dest);
354 argv.push_back(url);
355 return util::run_inherit(argv) == 0;
356}
357
358/** The digest a fetched jar must match: `$LINE_JMT_SHA256`, else the pin. */
359inline std::string expected_jar_sha256() {
360 std::string want = util::trim(env_or_empty("LINE_JMT_SHA256"));
361 if (want.empty()) want = JMT_JAR_SHA256;
362 for (std::size_t i = 0; i < want.size(); ++i)
363 want[i] = static_cast<char>(std::tolower(static_cast<unsigned char>(want[i])));
364 return want;
365}
366
367/**
368 * The download `jmtGetPath` does, with the consent and the verification the
369 * reference has no way to offer.
370 *
371 * @return the directory the jar now sits in, or EMPTY when nothing was fetched
372 * because nothing consented or no fetcher exists. A fetch that was
373 * ATTEMPTED and went wrong throws instead: a half-installed or
374 * unrecognised jar must not read as "JMT is simply not available here".
375 *
376 * The bytes land on a `.part-<pid>` beside the destination and are renamed in
377 * only once the digest matches, so a failed or truncated transfer never leaves
378 * a `JMT.jar` behind for the next run to find and trust, and two processes
379 * fetching at once cannot interleave into one file. The digest is the point of
380 * the exercise: curl and wget authenticate the SERVER, and only this
381 * authenticates the ARTEFACT.
382 */
383inline std::string jmt_download_jar() {
384 if (!download_consented()) return std::string();
385
386 std::string url = env_or_empty("LINE_JMT_URL");
387 if (url.empty()) url = JMT_JAR_URL;
388 if (url.compare(0, 8, "https://") != 0)
389 throw InputError("SolverJMT: refusing to fetch JMT.jar over '" + url +
390 "': the download must be https, so that the transfer is authenticated "
391 "before the digest authenticates the file");
392
393 const std::string dir = jmt_download_dir();
394 if (!is_dir(dir) || ::access(dir.c_str(), W_OK) != 0)
395 throw InputError("SolverJMT: cannot write JMT.jar to '" + dir +
396 "': the directory does not exist or is not writable. Set LINE_JMT_DIR to "
397 "a directory that is");
398
399 const std::string tool = find_fetcher();
400 if (tool.empty())
401 throw InputError("SolverJMT: LINE_JMT_DOWNLOAD is set but neither curl nor wget is on "
402 "PATH, and this port has no TLS client of its own. Install one, or place "
403 "JMT.jar in " +
404 dir + " by hand");
405
406 const std::string dest = dir + "/JMT.jar";
407 const std::string part = dest + ".part-" + std::to_string(static_cast<long>(::getpid()));
408 ::unlink(part.c_str());
409 std::printf("\nJava Modelling Tools cannot be found. Fetching %s (about 31 MiB) into %s\n",
410 url.c_str(), dir.c_str());
411 std::fflush(stdout);
412 if (!fetch_url(tool, url, part)) {
413 ::unlink(part.c_str());
414 throw InputError("SolverJMT: the download of " + url + " failed; see the transfer's own "
415 "message above");
416 }
417
418 const std::string want = expected_jar_sha256();
419 const std::string got = util::sha256_file_hex(part);
420 if (got != want) {
421 struct stat st;
422 const long long bytes = ::stat(part.c_str(), &st) == 0 ? static_cast<long long>(st.st_size)
423 : -1;
424 ::unlink(part.c_str());
425 throw InputError(
426 "SolverJMT: the jar fetched from " + url + " is not the one this port pins.\n" +
427 " expected sha256 " + want + "\n" + " received sha256 " +
428 (got.empty() ? std::string("<unreadable>") : got) + " (" + std::to_string(bytes) +
429 " bytes)\n" +
430 "The file has been discarded. That URL serves a rolling 'latest' build, so an upstream "
431 "republication looks exactly like this: check the digest against the publisher and, if "
432 "it is the build you want, set LINE_JMT_SHA256 to it");
433 }
434
435 if (::rename(part.c_str(), dest.c_str()) != 0) {
436 ::unlink(part.c_str());
437 throw InputError("SolverJMT: could not move the verified jar into place at '" + dest + "'");
438 }
439 std::printf("Verified sha256 %s and installed %s\n", got.c_str(), dest.c_str());
440 std::fflush(stdout);
441 return dir;
442}
443
444inline std::string read_file(const std::string& path) {
445 std::ifstream f(path.c_str(), std::ios::binary);
446 if (!f) throw InputError("SolverJMT: cannot read '" + path + "'");
447 std::ostringstream ss;
448 ss << f.rdbuf();
449 return ss.str();
450}
451
452inline void write_file(const std::string& path, const std::string& text) {
453 std::ofstream f(path.c_str(), std::ios::binary);
454 if (!f) throw InputError("SolverJMT: cannot write '" + path + "'");
455 f.write(text.data(), static_cast<std::streamsize>(text.size()));
456 if (!f) throw InputError("SolverJMT: write failed on '" + path + "'");
457}
458
459/** JSON string escaping, for the REST request body. */
460inline std::string json_escape(const std::string& s) {
461 std::string out;
462 out.reserve(s.size() + 16);
463 for (std::size_t i = 0; i < s.size(); ++i) {
464 const unsigned char c = static_cast<unsigned char>(s[i]);
465 switch (c) {
466 case '"': out += "\\\""; break;
467 case '\\': out += "\\\\"; break;
468 case '\n': out += "\\n"; break;
469 case '\r': out += "\\r"; break;
470 case '\t': out += "\\t"; break;
471 default:
472 if (c < 0x20) {
473 char buf[8];
474 std::snprintf(buf, sizeof(buf), "\\u%04x", c);
475 out += buf;
476 } else {
477 out.push_back(s[i]);
478 }
479 }
480 }
481 return out;
482}
483
484/**
485 * The value of a top-level JSON string field, unescaped.
486 *
487 * The REST response is a small, flat envelope -- `status`, `error`,
488 * `raw_output.result_xml`, `raw_output.stdout` -- and pulling four strings out
489 * of it does not warrant making this header depend on the JSON library that
490 * only the LDES client uses. A malformed response yields an empty string, and
491 * the caller then reports that the server sent no result document.
492 */
493inline std::string json_string_field(const std::string& body, const std::string& key) {
494 const std::string needle = "\"" + key + "\"";
495 std::size_t p = body.find(needle);
496 if (p == std::string::npos) return std::string();
497 p = body.find(':', p + needle.size());
498 if (p == std::string::npos) return std::string();
499 ++p;
500 while (p < body.size() && (body[p] == ' ' || body[p] == '\t' || body[p] == '\n')) ++p;
501 if (p >= body.size() || body[p] != '"') return std::string();
502 ++p;
503 std::string out;
504 while (p < body.size() && body[p] != '"') {
505 if (body[p] == '\\' && p + 1 < body.size()) {
506 ++p;
507 switch (body[p]) {
508 case 'n': out.push_back('\n'); break;
509 case 'r': out.push_back('\r'); break;
510 case 't': out.push_back('\t'); break;
511 case 'u': {
512 if (p + 4 < body.size()) {
513 const long cp = std::strtol(body.substr(p + 1, 4).c_str(), nullptr, 16);
514 if (cp < 0x80) out.push_back(static_cast<char>(cp));
515 p += 4;
516 }
517 break;
518 }
519 default: out.push_back(body[p]);
520 }
521 } else {
522 out.push_back(body[p]);
523 }
524 ++p;
525 }
526 return out;
527}
528
529/**
530 * `options.timeout` as JSIM's own wall-clock stop: `-maxtime ceil(remaining)`,
531 * at least 1, on a simulation run under an armed budget, as MATLAB's jmtRun
532 * passes it. JSIM then stops and WRITES its interim result, which is why the
533 * kill bound sits 30 s beyond it. JMVA has no such knob.
534 */
535inline void jmt_push_maxtime(std::vector<std::string>& argv, const std::string& mode) {
536 if (mode != "sim" || !util::timeout_armed()) return;
537 const double rem = util::timeout_remaining();
538 const double secs = std::ceil(rem);
539 argv.push_back("-maxtime");
540 argv.push_back(std::to_string(secs < 1.0 ? 1L : (secs > 2.0e9 ? 2000000000L : static_cast<long>(secs))));
541}
542
543/**
544 * After a simulation run under a budget: a JSIM that hit its `-maxtime` says so
545 * nowhere in the result, so the budget is read here, which latches it when it
546 * ran out (the interim result is still returned).
547 */
548inline void jmt_latch_maxtime(const std::string& mode) {
549 if (mode == "sim") util::timeout_exceeded();
550}
551
552} // namespace detail
553
554template <class T>
555struct JmtResult;
556
557inline util::ProcResult jmt_run_docker(const std::string& image, const std::string& mode,
558 const std::string& model_path, long seed,
559 const JmtOptions& opt);
560
561/** The suffix `jmt.commandline.Jmt` appends to the model path, per mode. */
562inline const char* jmt_result_ext(const std::string& mode) {
563 if (mode == "sim") return "jsim";
564 if (mode == "mva") return "jmva";
565 throw InputError("SolverJMT: unknown JMT analysis mode '" + mode + "'");
566}
567
568/** True when a local JVM and `common/JMT.jar` are both present. */
569inline bool jmt_available() {
570 return !detail::jmt_jar_path().empty() && !detail::find_java().empty();
571}
572
573/**
574 * Port of `jmtSolveRest`: POST the model document, write the result document
575 * back beside the model so the local parsers are unaffected.
576 */
577inline util::ProcResult jmt_solve_rest(const std::string& rest_url, const std::string& mode,
578 const std::string& model_path, long seed,
579 const JmtOptions& opt) {
580 std::string url = rest_url;
581 while (!url.empty() && url[url.size() - 1] == '/') url.erase(url.size() - 1);
582 // A caller may hand over the full route; anything else gets the default one.
583 if (url.size() < 8 || url.substr(url.size() - 8) != "/solve/" + mode.substr(0, 1))
584 if (url.find("/api/v") == std::string::npos) url += "/api/v1/solve/" + mode;
585
586 std::string body = "{\"model\":{\"content\":\"" +
587 detail::json_escape(detail::read_file(model_path)) +
588 "\",\"base64\":false}";
589 // JMVA takes its algorithm and tolerance from the model document, so the
590 // seed is meaningful only on the simulation route; the server's option
591 // allow-list rejects it on /solve/mva.
592 if (mode == "sim") body += ",\"options\":{\"seed\":" + std::to_string(seed) + "}";
593 body += "}";
594
595 // Read timeout: the explicit bound, else the armed budget plus grace, else none.
596 // The server's option allow-list takes no maxtime, so the budget bounds the
597 // wait only, and a run that outlives it is a Timeout with no result.
598 const int timeout_s = util::timeout_kill_bound(opt.timeout);
599 http::Response resp;
600 try {
601 resp = http::post_json(url, body, timeout_s > 0 && timeout_s < 2000000 ? timeout_s * 1000 : 0);
602 } catch (const http::HttpError&) {
603 util::timeout_raise_if_killed_on_budget("SolverJMT: the JMT REST solve at " + url);
604 throw;
605 }
606 if (resp.status != 200)
607 throw InputError("SolverJMT: the JMT REST server at " + url + " answered HTTP " +
608 std::to_string(resp.status));
609 const std::string status = detail::json_string_field(resp.body, "status");
610 if (status != "completed") {
611 const std::string err = detail::json_string_field(resp.body, "error");
612 throw InputError("SolverJMT: the JMT REST solve failed: " +
613 (err.empty() ? std::string("unspecified error") : err));
614 }
615 const std::string xml = detail::json_string_field(resp.body, "result_xml");
616 if (xml.empty())
617 throw InputError(
618 "SolverJMT: the JMT REST response carries no result document. The server was asked "
619 "to include the raw output; check that include_raw_output is not disabled");
620 detail::write_file(model_path + "-result." + jmt_result_ext(mode), xml);
621 detail::jmt_latch_maxtime(mode);
623 r.exitCode = 0;
624 r.out = detail::json_string_field(resp.body, "stdout");
625 return r;
626}
627
628/**
629 * Port of `jmtRun`: one batch analysis, leaving the result where the JMT CLI
630 * itself would leave it.
631 *
632 * @param mode "sim" or "mva"
633 * @param model_path the document JMT is to read; the result lands beside it
634 */
635inline util::ProcResult jmt_run(const std::string& mode, const std::string& model_path, long seed,
636 const JmtOptions& opt) {
637 if (!opt.rest_url.empty()) return jmt_solve_rest(opt.rest_url, mode, model_path, seed, opt);
638
639 std::string jar_dir = detail::jmt_jar_path();
640 const std::string java = detail::find_java();
641 // A jar is worth fetching only when there is a JVM to run it with: the
642 // Docker arm below needs none, so downloading one for it would be 31 MiB
643 // spent on a file nothing reads. Returns empty unless LINE_JMT_DOWNLOAD
644 // consents; see the header note.
645 if (jar_dir.empty() && !java.empty()) jar_dir = detail::jmt_download_jar();
646 if (!jar_dir.empty() && !java.empty()) {
647 std::vector<std::string> argv;
648 argv.push_back(java);
649 argv.push_back(detail::private_tmpdir_flag(model_path));
650 argv.push_back("-cp");
651 argv.push_back(jar_dir + "/JMT.jar");
652 argv.push_back("jmt.commandline.Jmt");
653 argv.push_back(mode);
654 argv.push_back(model_path);
655 argv.push_back("-seed");
656 argv.push_back(std::to_string(seed));
657 argv.push_back("--illegal-access=permit");
658 detail::jmt_push_maxtime(argv, mode);
659 const util::ProcResult r = util::capture(argv, util::timeout_kill_bound(opt.timeout), true);
660 if (r.timedOut) util::timeout_raise_if_killed_on_budget("SolverJMT: the JMT run");
661 // A KILLED RUN IS NOT A RESULT. Without this the caller falls through to
662 // "no result document", which reads as a solver that refused the model
663 // rather than one whose wall-clock budget expired -- and a jsim that is
664 // merely SLOW on a loaded host is exactly the case that hits it. Same
665 // rule the LQNS, QNS and LDES wrappers already apply to util::capture.
666 if (r.timedOut)
667 throw ExternalError(ErrorKind{"JMT"}, "SolverJMT: the JMT run did not finish within " +
668 std::to_string(opt.timeout) + "s and was killed");
669 detail::jmt_latch_maxtime(mode);
670 return r;
671 }
672
673 // The Docker arm. The image is used only when it is ALREADY PRESENT or the
674 // caller has opted into the pull; see the header note on consent.
675 std::string image = opt.container.empty() ? detail::env_or_empty("LINE_JMT_IMAGE")
676 : opt.container;
677 if (image.empty()) image = JMT_DOCKER_IMAGE;
679 bool have = io::docker_has_local_image(image);
680 if (!have && detail::docker_consented() && io::docker_has_storage_for(image))
681 have = io::docker_pull(image);
682 if (have) return jmt_run_docker(image, mode, model_path, seed, opt);
683 }
684
685 // Say which half was missing: a jar outside the searched roots reads like a missing JVM otherwise.
686 const std::string found =
687 std::string(java.empty() ? "no Java runtime (LINE_JAVA, JAVA_HOME or PATH)" : "a Java runtime") +
688 (jar_dir.empty() ? " and no JMT.jar (LINE_JMT_DIR, else JMT.jar or common/JMT.jar in the "
689 "executable's or working directory or up to 6 levels above)"
690 : " and JMT.jar in " + jar_dir);
691 throw ExternalError(ErrorKind{"JMT"},
692 "SolverJMT: no way to reach JMT: found " + found + ". Install a Java runtime and put "
693 "JMT.jar in common/ (" + std::string(JMT_JAR_URL) +
694 ") or in the directory LINE_JMT_DIR names, or set LINE_JMT_DOWNLOAD=1 to let curl or wget "
695 "fetch and verify that jar for you, or "
696 "point options.rest_url at a JMT REST server, or set LINE_JMT_DOCKER=1 to allow the " +
697 image + " image to be pulled and used");
698}
699
700/**
701 * Run the analysis inside the JMT container and copy the result back beside the
702 * model, so the caller sees the layout a local JVM would have produced.
703 *
704 * The model is STAGED under a fresh directory and the container is given that
705 * directory: in `mva` mode JMT rewrites the model file itself, and a confined
706 * Docker cannot bind-mount the system temp directory the model normally lives
707 * in. The container runs as the calling user so the files it writes are not
708 * left owned by root.
709 */
710inline util::ProcResult jmt_run_docker(const std::string& image, const std::string& mode,
711 const std::string& model_path, long seed,
712 const JmtOptions& opt) {
713 util::TempDir work("jmt-docker", true);
714 const std::size_t slash = model_path.find_last_of('/');
715 const std::string base =
716 slash == std::string::npos ? model_path : model_path.substr(slash + 1);
717 const std::string staged = work.path() + "/" + base;
718 detail::write_file(staged, detail::read_file(model_path));
719
720 const std::string uid = std::to_string(static_cast<long>(::getuid()));
721 const std::string gid = std::to_string(static_cast<long>(::getgid()));
722 std::vector<std::string> argv;
723 argv.push_back("docker");
724 argv.push_back("run");
725 argv.push_back("--rm");
726 // Named, because killing the `docker run` client on a bound leaves the
727 // container itself running; the name is what `docker rm -f` reaps it by.
728 static int jmt_container_seq = 0;
729 const std::string cname = "line-jmt-" + std::to_string(static_cast<long>(::getpid())) + "-" +
730 std::to_string(++jmt_container_seq);
731 argv.push_back("--name");
732 argv.push_back(cname);
733 argv.push_back("--user");
734 argv.push_back(uid + ":" + gid);
735 argv.push_back("-v");
736 argv.push_back(work.path() + ":" + work.path());
737 argv.push_back("-w");
738 argv.push_back(work.path());
739 argv.push_back(image);
740 argv.push_back(mode);
741 argv.push_back(base);
742 argv.push_back("-seed");
743 argv.push_back(std::to_string(seed));
744 detail::jmt_push_maxtime(argv, mode);
745 const util::ProcResult r = util::capture(argv, util::timeout_kill_bound(opt.timeout), true);
746 if (r.timedOut) {
747 std::vector<std::string> rm;
748 rm.push_back("docker");
749 rm.push_back("rm");
750 rm.push_back("-f");
751 rm.push_back(cname);
752 util::capture(rm, 60, true);
753 util::timeout_raise_if_killed_on_budget("SolverJMT: the JMT container run");
754 }
755 if (r.timedOut)
756 throw ExternalError(ErrorKind{"JMT"}, "SolverJMT: the JMT container run did not finish within " +
757 std::to_string(opt.timeout) + "s and was killed");
758
759 detail::jmt_latch_maxtime(mode);
760 const std::string produced = staged + "-result." + jmt_result_ext(mode);
761 if (detail::is_file(produced))
762 detail::write_file(model_path + "-result." + jmt_result_ext(mode),
763 detail::read_file(produced));
764 return r;
765}
766
767/** One `<measure>` of a JMT result document, by its attributes. */
770 double mean = 0.0, lower = 0.0, upper = 0.0;
771 double analyzed_samples = 0.0;
772 double discarded_samples = 0.0;
773 bool successful = false;
774 bool has_bounds = false;
775};
776
777/**
778 * Port of `getResultsJSIM`: every `<measure>` of the result document.
779 *
780 * A MISSING FILE IS A FAILED SIMULATION, not an empty result: JMT writes the
781 * document even when every measure is unsuccessful, so its absence means the
782 * run itself did not complete, and returning zeros would report a solved model.
783 */
784inline std::vector<JmtMeasure> jmt_parse_measures(const std::string& result_path,
785 const std::string& command_output) {
786 if (!detail::is_file(result_path)) {
787 std::string msg =
788 "SolverJMT: JMT did not output a result file, the simulation has likely failed.";
789 if (!command_output.empty()) msg += " JMT output: " + command_output;
790 throw ExternalError(ErrorKind{"JMT"}, msg);
791 }
792 const std::unique_ptr<xml::Element> doc = xml::parse_file(result_path);
793 std::vector<JmtMeasure> out;
794 const std::vector<const xml::Element*> ms = doc->by_tag("measure");
795 for (std::size_t i = 0; i < ms.size(); ++i) {
796 const xml::Element* e = ms[i];
797 JmtMeasure m;
798 m.measure_type = e->attr("measureType");
799 // JMT >= 1.5.0 writes the measure kind of a result as "type"; earlier
800 // releases never write that attribute on a result measure.
801 if (m.measure_type.empty()) m.measure_type = e->attr("type");
802 m.station = e->attr("station");
803 m.job_class = e->attr("class");
804 m.node_type = e->attr("nodeType");
805 m.mean = std::strtod(e->attr("meanValue").c_str(), nullptr);
806 m.analyzed_samples = std::strtod(e->attr("analyzedSamples").c_str(), nullptr);
807 m.discarded_samples = std::strtod(e->attr("discardedSamples").c_str(), nullptr);
808 m.successful = e->attr("successful") == "true";
809 if (e->has_attr("lowerLimit") && e->has_attr("upperLimit")) {
810 m.lower = std::strtod(e->attr("lowerLimit").c_str(), nullptr);
811 m.upper = std::strtod(e->attr("upperLimit").c_str(), nullptr);
812 m.has_bounds = true;
813 }
814 out.push_back(m);
815 }
816 return out;
817}
818
819/**
820 * The result of a JMT solve: the shared `AvgResult` plus what only JMT reports.
821 *
822 * The FCR rows extend the metric matrices past `nstations`, which is the
823 * reference's layout (`getResults.m` allocates `nstations + nregions` rows) and
824 * is what makes a region's measures reachable through the same table as a
825 * station's.
826 */
827template <class T>
828struct JmtResult {
830 Matrix<T> QCI, UCI, RCI, TCI, ACI; ///< confidence half-widths, empty when disabled
831 Matrix<T> Weight, MemOcc; ///< FCR-only: weighted and memory occupation
832 Matrix<T> TNfcr, DropRateNfcr; ///< (nregions x nclasses) carried and lost rate
833 /** getResults.m `result.Avg.Tard` (stations x classes) and `.SysTard` (1 x classes). */
835 Matrix<T> TardCI, SysTardCI; ///< their half-widths, empty when disabled
836 /** Per Cache node (1-based node index), the per-class hit probability. */
837 std::map<std::size_t, std::vector<T>> cache_hit_prob;
838 /**
839 * `result.Prob.logNormConstAggr`, the log normalizing constant JMVA reports.
840 *
841 * NaN on the simulation path and on any JMVA algorithm that does not
842 * compute one -- an AMVA approximation has no G to report -- rather than
843 * zero, which is a legitimate value of a log constant.
844 */
845 T log_norm_const = num_traits<T>::from_double(std::numeric_limits<double>::quiet_NaN());
846};
847
848/**
849 * Port of `getResults.m`: the measures mapped onto the metric matrices.
850 *
851 * THE RECURRENCE TEST IS WHY `analyzedSamples` IS READ. For a CLOSED class JMT
852 * may terminate a measure before it has seen more samples than there are jobs
853 * in the chain, and such a measure is not an estimate of anything; the
854 * reference reports it as 0 for a structurally transient class and NaN
855 * otherwise, and so does this. An OPEN class
856 * has no such bound and is taken as reported.
857 */
858template <class T>
860 const std::vector<JmtMeasure>& measures, bool confint) {
861 const std::size_t M = sn.nstations, K = sn.nclasses, F = sn.regions.size();
862 const T zero = num_traits<T>::from_int(0);
863 const double nan = std::numeric_limits<double>::quiet_NaN();
864 JmtResult<T> res;
865 res.avg.QN = Matrix<T>(M + F, K, zero);
866 res.avg.UN = Matrix<T>(M + F, K, zero);
867 res.avg.RN = Matrix<T>(M + F, K, zero);
868 res.avg.TN = Matrix<T>(M + F, K, zero);
869 res.avg.AN = Matrix<T>(M + F, K, zero);
870 res.avg.WN = Matrix<T>(M + F, K, zero);
871 res.Weight = Matrix<T>(M + F, K, num_traits<T>::from_double(nan));
872 res.MemOcc = Matrix<T>(M + F, K, num_traits<T>::from_double(nan));
873 if (confint) {
874 res.QCI = Matrix<T>(M, K, zero);
875 res.UCI = Matrix<T>(M, K, zero);
876 res.RCI = Matrix<T>(M, K, zero);
877 res.TCI = Matrix<T>(M, K, zero);
878 res.ACI = Matrix<T>(M, K, zero);
879 res.TardCI = Matrix<T>(M, K, zero);
880 res.SysTardCI = Matrix<T>(1, K, zero);
881 }
882 res.Tard = Matrix<T>(M, K, zero);
883 res.SysTard = Matrix<T>(1, K, zero);
884 // JMT reports no utilization and no arrival rate for a region.
885 for (std::size_t f = 0; f < F; ++f)
886 for (std::size_t r = 0; r < K; ++r) {
887 res.avg.UN(M + f, r) = num_traits<T>::from_double(nan);
888 res.avg.AN(M + f, r) = num_traits<T>::from_double(nan);
889 }
890
891 std::map<std::string, std::size_t> station_of, class_of;
892 for (std::size_t i = 1; i <= sn.nodes.size(); ++i) station_of[sn.nodes[i - 1].name] = i;
893 for (std::size_t r = 1; r <= K; ++r) class_of[sn.classes[r - 1].name] = r;
894
895 // The chain population each closed class's recurrence test compares against,
896 // and what a measure failing it reports: exactly 0 for a class with zero
897 // visits in its chain (structurally transient), NaN for any other class,
898 // which is recurrent but unconverged (e.g. starved behind higher priorities,
899 // prio_hol_closed). A 0 there fabricates an empty station; the reference
900 // getResults.m reports the same split since 2026-11-14.
901 std::vector<double> chainpop(K, 0.0);
902 std::vector<double> unmeasured(K, nan);
903 for (std::size_t c = 0; c < sn.inchain.size(); ++c) {
904 double tot = 0.0;
905 for (std::size_t r : sn.inchain[c]) {
906 const double n = sn.classes[r - 1].population;
907 if (std::isfinite(n)) tot += n;
908 }
909 for (std::size_t r : sn.inchain[c]) {
910 chainpop[r - 1] = tot;
911 double vis = 0.0;
912 for (std::size_t i = 0; i < sn.visits[c].rows(); ++i)
913 vis += num_traits<T>::to_double(sn.visits[c](i, r - 1));
914 if (vis == 0.0) unmeasured[r - 1] = 0.0;
915 }
916 }
917
918 // Fork-join section measures, per (fork node, class), see JmtWriter::save_fj_metrics. 1-based keys.
919 std::map<std::pair<std::size_t, std::size_t>, double> fj_respt, fj_qlen;
920
921 // A (station, class) cell that NO measure ever sampled (analyzed + discarded = 0 in
922 // every measure reported for it) never held a job of that class during the run, so
923 // an unmeasured cell there is exactly 0. sn.visits cannot see this under REDUCIBLE
924 // routing (test_CQN_Reduc_2: visits 0.5 in all four cells, yet from the initial state
925 // Class2 never reaches the Delay). A starved class that is PRESENT (prio_hol_closed
926 // HOLQueue Class2, QLen sampled) keeps NaN. getResults.m cellSampled, 2026-11-16.
927 std::set<std::pair<std::size_t, std::size_t>> cell_sampled; // (ist, r), 1-based
928 for (const JmtMeasure& m : measures) {
929 if (m.analyzed_samples + m.discarded_samples <= 0.0) continue;
930 const auto ni = station_of.find(m.station);
931 const auto ci = class_of.find(m.job_class);
932 if (ni == station_of.end() || ci == class_of.end()) continue;
933 const std::size_t ist = sn.nodes[ni->second - 1].station;
934 if (ist == 0) continue;
935 cell_sampled.insert(std::make_pair(ist, ci->second));
936 }
937
938 for (std::size_t i = 0; i < measures.size(); ++i) {
939 const JmtMeasure& m = measures[i];
940 const double half = m.has_bounds ? (m.upper - m.lower) / 2.0 : 0.0;
941
942 if (m.measure_type == "Fork Join Response Time" ||
943 m.measure_type == "Fork Join Number of Customers") {
944 const auto ni = station_of.find(m.station);
945 const auto ci = class_of.find(m.job_class);
946 if (ni != station_of.end() && ci != class_of.end()) {
947 const std::pair<std::size_t, std::size_t> key(ni->second, ci->second);
948 if (m.measure_type == "Fork Join Response Time")
949 fj_respt[key] = m.mean;
950 else
951 fj_qlen[key] = m.mean;
952 }
953 continue;
954 }
955
956 // A region measure is identified by its nodeType, or by the name the
957 // writer gave it -- JMT does not always echo the nodeType back.
958 const bool is_fcr =
959 m.node_type == "region" || m.station.compare(0, 8, "FCRegion") == 0;
960 if (is_fcr && m.station.compare(0, 8, "FCRegion") == 0) {
961 const long f = std::strtol(m.station.substr(8).c_str(), nullptr, 10);
962 if (f < 1 || static_cast<std::size_t>(f) > F) continue;
963 const std::size_t row = M + static_cast<std::size_t>(f) - 1;
964 // A region measure is AGGREGATE, not per class. The reference
965 // spreads the extensive ones (customers, throughput, arrival rate,
966 // weight, memory) evenly over the classes and repeats the intensive
967 // ones (response and residence time) unchanged, so that summing a
968 // column recovers the region total in both cases.
969 const double per_class = m.mean / static_cast<double>(K);
970 for (std::size_t r = 0; r < K; ++r) {
971 if (m.measure_type == "Number of Customers")
972 res.avg.QN(row, r) = num_traits<T>::from_double(per_class);
973 else if (m.measure_type == "Response Time")
974 res.avg.RN(row, r) = num_traits<T>::from_double(m.mean);
975 else if (m.measure_type == "Residence Time")
976 res.avg.WN(row, r) = num_traits<T>::from_double(m.mean);
977 else if (m.measure_type == "Throughput")
978 res.avg.TN(row, r) = num_traits<T>::from_double(per_class);
979 else if (m.measure_type == "Arrival Rate")
980 res.avg.AN(row, r) = num_traits<T>::from_double(per_class);
981 else if (m.measure_type == "FCR Capacity")
982 res.Weight(row, r) = num_traits<T>::from_double(per_class);
983 else if (m.measure_type == "FCR Memory")
984 res.MemOcc(row, r) = num_traits<T>::from_double(per_class);
985 }
986 continue;
987 }
988
989 if (m.measure_type == "Cache Hit Rate") {
990 const auto ni = station_of.find(m.station);
991 const auto ci = class_of.find(m.job_class);
992 if (ni == station_of.end() || ci == class_of.end()) continue;
993 if (sn.nodes[ni->second - 1].nodetype != lang::NodeType::Cache) continue;
994 const auto cp = sn.nodeparam.find(ni->second);
995 if (cp == sn.nodeparam.end()) continue;
996 std::vector<T>& hit = res.cache_hit_prob[ni->second];
997 if (hit.empty()) hit.assign(K, zero);
998 // The measure names the HIT class; the probability belongs to the
999 // read class that switches into it.
1000 for (std::size_t r = 0; r < cp->second.hitclass.size(); ++r)
1001 if (cp->second.hitclass[r] == ci->second)
1002 hit[r] = num_traits<T>::from_double(m.mean);
1003 continue;
1004 }
1005
1006 // A SYSTEM measure names no station (saveMetric.m blanks referenceNode), so it is
1007 // matched on the class alone, with the same recurrence test as a station measure.
1008 if (m.measure_type == "System Tardiness") {
1009 const auto ci = class_of.find(m.job_class);
1010 if (ci == class_of.end()) continue;
1011 const std::size_t r = ci->second;
1012 const bool open = !std::isfinite(sn.classes[r - 1].population);
1013 const bool recurrent = open || m.analyzed_samples > chainpop[r - 1];
1014 res.SysTard(0, r - 1) = num_traits<T>::from_double(recurrent ? m.mean : unmeasured[r - 1]);
1015 if (confint) res.SysTardCI(0, r - 1) = num_traits<T>::from_double(recurrent ? half : 0.0);
1016 continue;
1017 }
1018
1019 const auto ni = station_of.find(m.station);
1020 const auto ci = class_of.find(m.job_class);
1021 if (ni == station_of.end() || ci == class_of.end()) continue;
1022 const std::size_t ist = sn.nodes[ni->second - 1].station;
1023 if (ist == 0) continue;
1024 const std::size_t r = ci->second;
1025 const bool open = !std::isfinite(sn.classes[r - 1].population);
1026 const bool recurrent = open || m.analyzed_samples > chainpop[r - 1];
1027 // Per cell, as getResults.m unmeasuredCell (2026-11-16): a class with zero
1028 // visits AT THIS STATION is structurally absent there, so its unmeasured cell
1029 // is exactly 0 even when the class circulates elsewhere (closed Class2 at the
1030 // Source of test_OQN_1); only a visiting, unconverged class is NaN.
1031 double unm = unmeasured[r - 1];
1032 if (!recurrent && std::isnan(unm) && cell_sampled.count(std::make_pair(ist, r)) == 0)
1033 unm = 0.0;
1034 if (!recurrent && std::isnan(unm)) {
1035 for (std::size_t c = 0; c < sn.inchain.size(); ++c) {
1036 bool in = false;
1037 for (std::size_t q : sn.inchain[c]) in = in || (q == r);
1038 if (!in) continue;
1039 if (ist - 1 < sn.visits[c].rows() &&
1040 num_traits<T>::to_double(sn.visits[c](ist - 1, r - 1)) == 0.0)
1041 unm = 0.0;
1042 break;
1043 }
1044 }
1045 const T v = num_traits<T>::from_double(recurrent ? m.mean : unm);
1046 const T ci_v = num_traits<T>::from_double(recurrent ? half : 0.0);
1047
1048 if (m.measure_type == "Number of Customers") {
1049 res.avg.QN(ist - 1, r - 1) = v;
1050 if (confint) res.QCI(ist - 1, r - 1) = ci_v;
1051 } else if (m.measure_type == "Utilization") {
1052 res.avg.UN(ist - 1, r - 1) = v;
1053 if (confint) res.UCI(ist - 1, r - 1) = ci_v;
1054 } else if (m.measure_type == "Response Time") {
1055 res.avg.RN(ist - 1, r - 1) = v;
1056 if (confint) res.RCI(ist - 1, r - 1) = ci_v;
1057 } else if (m.measure_type == "Throughput") {
1058 res.avg.TN(ist - 1, r - 1) = v;
1059 if (confint) res.TCI(ist - 1, r - 1) = ci_v;
1060 } else if (m.measure_type == "Arrival Rate") {
1061 res.avg.AN(ist - 1, r - 1) = v;
1062 if (confint) res.ACI(ist - 1, r - 1) = ci_v;
1063 } else if (m.measure_type == "Tardiness") {
1064 res.Tard(ist - 1, r - 1) = v;
1065 if (confint) res.TardCI(ist - 1, r - 1) = ci_v;
1066 }
1067 // `Residence Time` is deliberately neither requested nor read: JMT's
1068 // definition disagrees with LINE's on class-switching models, and the
1069 // residence time is recomputed below from the response time.
1070 }
1071 // JMT keeps no utilization at an ORDINARY Place (a storage section with no server). A Place is an
1072 // INF station, so U == Q, the value SolverCTMC, SolverSSA and SolverNC report. A queueing place
1073 // keeps the busy-server utilization JMT measures for its embedded queue.
1074 for (std::size_t i = 0; i < sn.nstations; ++i) {
1075 if (sn.stations[i].nodetype != lang::NodeType::Place || sn.is_queueing_place(i)) continue;
1076 for (std::size_t r = 0; r < K; ++r) {
1077 res.avg.UN(i, r) = res.avg.QN(i, r);
1078 if (confint) res.UCI(i, r) = res.QCI(i, r);
1079 }
1080 }
1081 // getResults.m's FJ block, carried as `avg.fj`: FJRespT and FJQLen as measured at the Fork (FJQLen is an
1082 // independent measurement, so Little holds only up to noise), FJTput the Join's class throughput.
1083 if (!solvers::fj_sorted_pairs(sn).empty()) {
1084 solvers::FjMetrics<T>& fjm = res.avg.fj;
1086 for (std::size_t p = 0; p < fjm.npairs(); ++p) {
1087 const std::size_t jst = sn.nodes[fjm.joins[p] - 1].station;
1088 for (std::size_t r = 1; r <= K; ++r) {
1089 const std::pair<std::size_t, std::size_t> key(fjm.forks[p], r);
1090 const auto rt = fj_respt.find(key);
1091 if (rt == fj_respt.end() || !std::isfinite(rt->second)) continue;
1092 fjm.RespT(p, r - 1) = num_traits<T>::from_double(rt->second);
1093 const auto ql = fj_qlen.find(key);
1094 if (ql != fj_qlen.end() && std::isfinite(ql->second))
1095 fjm.QLen(p, r - 1) = num_traits<T>::from_double(ql->second);
1096 if (jst != 0 && jst <= M) fjm.Tput(p, r - 1) = res.avg.TN(jst - 1, r - 1);
1097 }
1098 }
1099 }
1100 return res;
1101}
1102
1103/**
1104 * The region loss table, port of the `sn.nregions > 0` tail of `getResults.m`.
1105 *
1106 * JMT EXPOSES NO REGION DROP MEASURE, and its region throughput is the CARRIED
1107 * (admitted) rate, so the offered rate is reconstructed by flow balance: the
1108 * rate at which stations outside the region route jobs across its boundary,
1109 * which the drop does not affect. The difference, clamped at zero, is the loss;
1110 * a region whose rule is not DROP loses nothing by construction and is zeroed.
1111 */
1112template <class T>
1114 const std::size_t M = sn.nstations, K = sn.nclasses, F = sn.regions.size();
1115 if (F == 0) return;
1116 const T zero = num_traits<T>::from_int(0);
1117 res.TNfcr = Matrix<T>(F, K, zero);
1118 res.DropRateNfcr = Matrix<T>(F, K, zero);
1119
1120 for (std::size_t f = 0; f < F; ++f) {
1121 const typename qn::NetworkStruct<T>::Region& rg = sn.regions[f];
1122 for (std::size_t r = 1; r <= K; ++r) {
1123 double acc = 0.0;
1124 // JMT's region Throughput is one value for all classes and its even split gave every class
1125 // the same carried rate; the per-class carried rate is the class-r flow LEAVING the region
1126 // (departures to the Sink are routed to the Source in sn.rt).
1127 double carried = 0.0;
1128 for (std::size_t ii = 1; ii <= M; ++ii) {
1129 if (!(ii <= rg.members.size() && rg.members[ii - 1])) continue;
1130 for (std::size_t j = 1; j <= M; ++j) {
1131 if (j <= rg.members.size() && rg.members[j - 1]) continue;
1132 for (std::size_t rp = 1; rp <= K; ++rp) {
1133 const std::size_t a = (j - 1) * K + (rp - 1);
1134 const std::size_t b = (ii - 1) * K + (r - 1);
1135 if (sn.rt.rows() <= a || sn.rt.cols() <= b) continue;
1136 const double w = num_traits<T>::to_double(sn.rt(a, b));
1137 if (w != 0.0)
1138 acc += num_traits<T>::to_double(res.avg.TN(j - 1, rp - 1)) * w;
1139 const std::size_t ao = (ii - 1) * K + (r - 1), bo = (j - 1) * K + (rp - 1);
1140 if (ao < sn.rt.rows() && bo < sn.rt.cols())
1141 carried += num_traits<T>::to_double(res.avg.TN(ii - 1, r - 1)) *
1142 num_traits<T>::to_double(sn.rt(ao, bo));
1143 }
1144 }
1145 }
1146 res.TNfcr(f, r - 1) = num_traits<T>::from_double(carried);
1147 const bool drops = r <= rg.rule.size() && rg.rule[r - 1] == lang::DropStrategy::DROP;
1148 res.DropRateNfcr(f, r - 1) =
1149 num_traits<T>::from_double(drops ? std::max(0.0, acc - carried) : 0.0);
1150 }
1151 }
1152}
1153
1154/**
1155 * Port of `getResultsJMVA.m`: the per-CHAIN answer spread back over the classes.
1156 *
1157 * JMVA answers per chain, and each measure is converted to a per-class one by
1158 * the class's share of its chain at that station: `alpha(i,k)` weighted by the
1159 * ratio of the class service time to the chain's. The conversions are the
1160 * reference's, measure by measure, and the two that are not a bare share are
1161 * the reason this cannot be a generic rescale:
1162 * Utilization is divided by the chain's visits at the REFERENCE station and,
1163 * at a multiserver station, scaled by min(N, c)/c.
1164 * Residence time is JMVA's per-CHAIN residence and is converted to LINE's
1165 * response time per visit by dividing by the class visits.
1166 *
1167 * THE STATION IS RESOLVED BY NAME, not by the position of the `stationresults`
1168 * block. The reference indexes `sn.nservers`, `ST` and `sn.visits` with the
1169 * BLOCK index, but the blocks exclude the Source while those tables do not, so
1170 * on any open model every station's demand is read one row early. Reading the
1171 * `station` attribute is the same lookup on a closed model and the correct one
1172 * on an open model.
1173 */
1174template <class T>
1175JmtResult<T> jmt_parse_jmva(const qn::NetworkStruct<T>& sn, const std::string& result_path,
1176 const std::string& command_output) {
1177 if (!detail::is_file(result_path)) {
1178 std::string msg =
1179 "SolverJMT: JMT did not output a result file, the analysis has likely failed.";
1180 if (!command_output.empty()) msg += " JMT output: " + command_output;
1181 throw ExternalError(ErrorKind{"JMT"}, msg);
1182 }
1183 const std::size_t M = sn.nstations, K = sn.nclasses, C = sn.nchains;
1184 const T zero = num_traits<T>::from_int(0);
1185 JmtResult<T> res;
1186 res.avg.QN = Matrix<T>(M, K, zero);
1187 res.avg.UN = Matrix<T>(M, K, zero);
1188 res.avg.RN = Matrix<T>(M, K, zero);
1189 res.avg.TN = Matrix<T>(M, K, zero);
1190 res.avg.AN = Matrix<T>(M, K, zero);
1191 res.avg.WN = Matrix<T>(M, K, zero);
1192
1194
1195 std::map<std::string, std::size_t> station_of;
1196 for (std::size_t i = 1; i <= M; ++i)
1197 station_of[sn.nodes[sn.station_to_node[i - 1] - 1].name] = i;
1198
1199 const std::unique_ptr<xml::Element> doc = xml::parse_file(result_path);
1200 // The normalizing constant, when the algorithm reports one.
1201 const std::vector<const xml::Element*> nc = doc->by_tag("normconst");
1202 res.log_norm_const = nc.empty()
1204 std::numeric_limits<double>::quiet_NaN())
1206 std::strtod(nc[0]->attr("logValue").c_str(), nullptr));
1207
1208 // A Source reports its own arrival rate as its throughput and holds no
1209 // jobs; JMVA does not model it, so the row is filled from the struct.
1210 if (sn.sourceIdx != 0)
1211 for (std::size_t r = 0; r < K; ++r)
1212 if (!sn.disabled[sn.sourceIdx - 1][r])
1213 res.avg.TN(sn.sourceIdx - 1, r) = sn.rates(sn.sourceIdx - 1, r);
1214
1215 const std::vector<const xml::Element*> blocks = doc->by_tag("stationresults");
1216 for (std::size_t b = 0; b < blocks.size(); ++b) {
1217 const auto si = station_of.find(blocks[b]->attr("station"));
1218 if (si == station_of.end()) continue;
1219 const std::size_t i = si->second;
1220 // The divisor is the capacity `write_jmva` exported, max(nservers, max
1221 // lldscaling): a load-dependent station carries its c in the scaling and
1222 // leaves nservers at 1, so reading nservers alone reports U = c*E[busy]/c.
1223 double ns = sn.stations[i - 1].nservers;
1224 for (const T& s : sn.stations[i - 1].lldscaling)
1225 ns = std::max(ns, num_traits<T>::to_double(s));
1226 const std::vector<const xml::Element*> crs = blocks[b]->by_tag("classresults");
1227 for (std::size_t c = 1; c <= crs.size() && c <= C; ++c) {
1228 const std::vector<const xml::Element*> ms = crs[c - 1]->by_tag("measure");
1229 // A multiserver Queue is written as <ldstation servers="1">, and one
1230 // ldstation switches JMVA to its load-dependent algorithm, whose
1231 // Utilization is 1-p_i(0) at EVERY station, delay ones included. That
1232 // is a different random variable from LINE's E[busy servers], so no
1233 // rescaling recovers it; derive U from the chain throughput instead,
1234 // which both JMVA algorithms report alike.
1235 double chain_tput = std::numeric_limits<double>::quiet_NaN();
1236 for (std::size_t m = 0; m < ms.size(); ++m) {
1237 if (ms[m]->attr("measureType") == "Throughput") {
1238 const std::string traw = ms[m]->attr("meanValue");
1239 chain_tput = traw == "NaN" ? std::numeric_limits<double>::quiet_NaN()
1240 : std::strtod(traw.c_str(), nullptr);
1241 break;
1242 }
1243 }
1244 for (std::size_t m = 0; m < ms.size(); ++m) {
1245 const std::string kind = ms[m]->attr("measureType");
1246 const std::string raw = ms[m]->attr("meanValue");
1247 const double val = raw == "NaN" ? std::numeric_limits<double>::quiet_NaN()
1248 : std::strtod(raw.c_str(), nullptr);
1249 const std::size_t refst = dem.refstatchain[c - 1];
1250 const double vchain_ref =
1251 num_traits<T>::to_double(dem.Vchain(refst - 1, c - 1));
1252 const double stchain = num_traits<T>::to_double(dem.STchain(i - 1, c - 1));
1253 for (std::size_t k : sn.inchain[c - 1]) {
1254 const double stk = num_traits<T>::to_double(dem.ST(i - 1, k - 1));
1255 const double al = num_traits<T>::to_double(dem.alpha(i - 1, k - 1));
1256 double v = val;
1257 if (kind == "Utilization") {
1258 if (vchain_ref == 0.0) continue;
1259 v = stk * chain_tput / vchain_ref * al;
1260 if (std::isfinite(ns)) v /= ns;
1261 res.avg.UN(i - 1, k - 1) = num_traits<T>::from_double(v);
1262 } else if (kind == "Throughput") {
1263 res.avg.TN(i - 1, k - 1) = num_traits<T>::from_double(val * al);
1264 } else if (kind == "Number of Customers") {
1265 if (stchain == 0.0 || vchain_ref == 0.0) continue;
1266 res.avg.QN(i - 1, k - 1) =
1267 num_traits<T>::from_double(val * stk / stchain / vchain_ref * al);
1268 } else if (kind == "Residence time" || kind == "Residence Time") {
1269 if (stchain == 0.0 || vchain_ref == 0.0) continue;
1270 double visits = 0.0;
1271 if (c - 1 < sn.visits.size()) {
1272 const std::size_t sfi = sn.stateful_of_station(i);
1273 if (sfi != 0 && sn.visits[c - 1].rows() >= sfi)
1274 visits = num_traits<T>::to_double(sn.visits[c - 1](sfi - 1, k - 1));
1275 }
1276 if (visits == 0.0) continue;
1277 v = (val / visits) * stk / stchain / vchain_ref * al;
1278 res.avg.RN(i - 1, k - 1) = num_traits<T>::from_double(v);
1279 }
1280 }
1281 }
1282 }
1283 }
1284 return res;
1285}
1286
1287/**
1288 * Port of `SolverJMT.listValidMethods`.
1289 *
1290 * THE TRANSIENT ENSEMBLE IS NOT A METHOD. A single sample path is not E[N](t),
1291 * there being no time-ergodicity at a fixed t, so `default` over a finite
1292 * timespan averages `sampleSysAggr` over `config.replications` seeds. It is
1293 * composed from `jmt_sample_sys_aggr` in `jmt_logs.h`
1294 * (`jmt_transient_replications`) rather than from `solver_jmt_run_analyzer`.
1295 * The former `replication` method was that ensemble under a method name, and
1296 * asking for it now raises `jmt_removed_method_refusal`.
1297 */
1298inline std::vector<std::string> jmt_list_valid_methods() {
1299 // the names and their order are this solver's row of the method registry (doc/line-methods.json)
1300 return ::line::method_registry::methods("JMT");
1301}
1302
1303/**
1304 * The migration sentence for a method name SolverJMT no longer has; empty for any other name.
1305 *
1306 * An ERROR and not an alias, as for the removed `'console'` in `Solver.m`: `replication` became the
1307 * `options.config.replications` knob of `default`, and the sentence says so rather than a bare "unknown".
1308 */
1309inline std::string jmt_removed_method_refusal(const std::string& method) {
1310 if (method == "replication")
1311 return "SolverJMT: the 'replication' method was removed: use a finite timespan with "
1312 "options.config.replications";
1313 return std::string();
1314}
1315
1316/**
1317 * The structural half of SolverJMT's method gate; empty when admissible.
1318 *
1319 * THE RULES A FLAT FEATURE SET CANNOT STATE, and each is named rather than
1320 * reported as a bare no:
1321 * a removed method name 'replication' is refused with its migration
1322 * sentence (`jmt_removed_method_refusal`).
1323 * a single-server station the eight closed-form JMVA algorithms are
1324 * single-server only, which is why `write_jmva`
1325 * refuses the model rather than emitting an
1326 * `<ldstation>` the algorithm cannot read. A server
1327 * count has no feature name; the load-dependent half
1328 * of the same restriction DOES, and rides in
1329 * `jmt_feature_set` as an unset LoadDependence.
1330 * the load-dependent shape JMT carries a scaling only as a server count, so
1331 * alpha(n) = min(n,c) is written exactly and nothing
1332 * else is.
1333 *
1334 * ONE PREDICATE, TWO CALLERS: `solver_jmt_run_analyzer` raises it, so a caller
1335 * naming the method by hand gets the sentence rather than a JMT stack trace, and
1336 * `autosolver::auto_family_refusal` returns it, so findSolver never offers the
1337 * pair. A second copy of any rule is how the gate and the run drift apart.
1338 */
1339/**
1340 * What the JMVA document cannot state; "" otherwise (MATLAB `jmtMethodRefusal`, isJmva arm).
1341 *
1342 * The document carries a station type, a mean demand and a visit count per chain and nothing else.
1343 * A FCFS station whose classes have different mean service times is not BCMP, and the engine answers
1344 * for the PS station with the same demands (3+2 jobs, rates 2 and 0.5: QLen 1.99/1.76 against the
1345 * exact 2.42/1.65). Every caller here names a jmt method, so all three rules key on the jmva* name.
1346 */
1347template <class T>
1348std::string jmva_document_refusal(const qn::NetworkStruct<T>& sn, const std::string& method) {
1349 if (method.compare(0, 4, "jmva") != 0 && method.compare(0, 8, "jmt.jmva") != 0) return std::string();
1351 return method + " requires a product-form model, but a FCFS station serves its classes with "
1352 "different mean service times, and the JMVA engine would answer for the "
1353 "processor-sharing station with the same demands. Use SolverJMT 'jsim', SolverMVA "
1354 "(whose FCFS correction handles it), SolverCTMC or SolverLDES.";
1356 return "The JMVA document has no fork or join element, so the analytical engine would "
1357 "solve the model without the synchronisation. Use a simulator (SolverJMT 'jsim', "
1358 "SolverLDES) or SolverMVA, which approximates fork-join.";
1359 for (std::size_t i = 0; i < sn.nstations; ++i) {
1360 const qn::SchedStrategy sc = sn.stations[i].sched;
1361 const char* sname = sc == qn::SchedStrategy::FCFS ? "FCFS"
1362 : sc == qn::SchedStrategy::SIRO ? "SIRO"
1363 : sc == qn::SchedStrategy::LCFS ? "LCFS" : nullptr;
1364 if (sname == nullptr) continue;
1365 for (std::size_t r = 0; r < sn.nclasses; ++r) {
1366 const double rate = num_traits<T>::to_double(sn.rates(i, r));
1367 const double scv = num_traits<T>::to_double(sn.scv(i, r));
1368 if (!(std::isfinite(rate) && rate > 0.0 && std::isfinite(scv))) continue;
1369 if (std::fabs(scv - 1.0) <= qn::GlobalConstants::FineTol) continue;
1370 char buf[64];
1371 std::snprintf(buf, sizeof(buf), "%.4g", scv);
1372 return "Station " + sn.stations[i].name + " serves class " + sn.classes[r].name + " under " +
1373 sname + " with a non-exponential law (SCV " + buf + "). The JMVA document carries "
1374 "the mean demand only, so the analytical engine would answer for the exponential "
1375 "law. Use a simulator (SolverJMT 'jsim', SolverLDES), SolverMVA, whose AMVA "
1376 "corrections read the SCV, or SolverCTMC or SolverSSA.";
1377 }
1378 }
1379 return std::string();
1380}
1381
1382/**
1383 * The release of a JMT jar: the `jmt.version=` line of
1384 * `jmt/common/globalsettings.conf` inside it, read with `unzip -p`. LINE's own
1385 * patched jar reports `1.3.1-BETA2`; stock JMT 1.5.0 reports `1.5.0`. Empty when
1386 * the jar, the entry or `unzip` is missing, which the caller reads as a release
1387 * before 1.5.0, so the legacy path is the default. Cached by path, size and mtime.
1388 */
1389inline std::string jmt_version(const std::string& jar) {
1390 struct stat st;
1391 if (jar.empty() || ::stat(jar.c_str(), &st) != 0) return std::string();
1392 static std::map<std::string, std::string> cache;
1393 const std::string key = jar + "|" + std::to_string(static_cast<long long>(st.st_size)) + "|" +
1394 std::to_string(static_cast<long long>(st.st_mtime));
1395 const auto hit = cache.find(key);
1396 if (hit != cache.end()) return hit->second;
1397 std::string version;
1398 const std::string unzip = detail::which_on_path("unzip");
1399 if (!unzip.empty()) {
1400 const util::ProcResult r =
1401 util::capture({unzip, "-p", jar, "jmt/common/globalsettings.conf"}, 30, false);
1402 std::istringstream in(r.out);
1403 std::string line;
1404 while (std::getline(in, line)) {
1405 if (line.compare(0, 12, "jmt.version=") == 0) {
1406 version = util::trim(line.substr(12));
1407 break;
1408 }
1409 }
1410 }
1411 cache[key] = version;
1412 return version;
1413}
1414
1415/**
1416 * True for a release at or after 1.5.0, compared numerically on the leading
1417 * `major.minor.patch`; an empty or unparseable version is a legacy release.
1418 */
1419inline bool jmt_is_at_least_150(const std::string& version) {
1420 std::size_t i = 0;
1421 while (i < version.size() && std::isspace(static_cast<unsigned char>(version[i]))) ++i;
1422 int part[3] = {0, 0, 0};
1423 for (int k = 0; k < 3; ++k) {
1424 if (i >= version.size() || !std::isdigit(static_cast<unsigned char>(version[i]))) {
1425 if (k == 0) return false;
1426 break;
1427 }
1428 while (i < version.size() && std::isdigit(static_cast<unsigned char>(version[i])))
1429 part[k] = part[k] * 10 + (version[i++] - '0');
1430 if (k < 2) {
1431 if (i < version.size() && version[i] == '.') ++i;
1432 else break;
1433 }
1434 }
1435 const int ref[3] = {1, 5, 0};
1436 for (int k = 0; k < 3; ++k)
1437 if (part[k] != ref[k]) return part[k] > ref[k];
1438 return true;
1439}
1440
1441/**
1442 * The release of the jar `jmt_run` would launch locally; empty when the run
1443 * goes to a REST service or would fall to the Docker image, both of which carry
1444 * LINE's own JMT.
1445 */
1446inline std::string jmt_local_version(const JmtOptions& opt) {
1447 if (!opt.rest_url.empty()) return std::string();
1448 const std::string dir = detail::jmt_jar_path();
1449 if (dir.empty() || detail::find_java().empty()) return std::string();
1450 return jmt_version(dir + "/JMT.jar");
1451}
1452
1453/** The schedules JMT serves through its PreemptiveServer. */
1467
1468/**
1469 * What JMT 1.5.0 and later simulate WRONGLY, worded as a refusal; empty for a
1470 * release before 1.5.0 and for every jmva method. Twin of the JAR's
1471 * `SolverJMT.jmt150Refusal`, MATLAB's `jmt150Refusal` and Python's
1472 * `jmt150_refusal`. 1.5.0's PreemptiveServer serves the jobs non-preemptively
1473 * and lacks the PI strategies, and its Cache never routes a job to the hit class.
1474 */
1475template <class T>
1476std::string jmt150_refusal(const qn::NetworkStruct<T>& sn, const std::string& method,
1477 const std::string& version) {
1478 if (!jmt_is_at_least_150(version)) return std::string();
1479 if (method.compare(0, 4, "jmva") == 0) return std::string();
1480 for (std::size_t i = 0; i < sn.nstations; ++i) {
1481 if (!jmt_is_preemptive_server_sched(sn.stations[i].sched)) continue;
1482 return "Station " + sn.stations[i].name + " uses " + lang::sched_to_text(sn.stations[i].sched) +
1483 " scheduling, which JMT " + version + " does not simulate correctly: its PreemptiveServer "
1484 "serves the jobs non-preemptively (and the FCFS-PI/LCFS-PI strategies are missing), so the "
1485 "result would describe a different discipline. Use the JMT.jar shipped with LINE "
1486 "(LINE_JMT_DIR), or SolverSSA, SolverLDES or SolverCTMC.";
1487 }
1488 for (const auto& nd : sn.nodes)
1489 if (nd.nodetype == qn::NodeType::Cache)
1490 return "Node " + nd.name + " is a Cache, which JMT " + version + " does not simulate correctly: "
1491 "its cache never routes a job to the hit class, so hit rates and hit/miss throughputs "
1492 "come back as zero, and a closed cache model does not terminate. Use the JMT.jar shipped "
1493 "with LINE (LINE_JMT_DIR), or SolverLDES, SolverSSA, SolverNC or SolverMVA.";
1494 return std::string();
1495}
1496
1497/** The error id of a `jmt150_refusal` sentence: `SchedStrategy_<NAME>` or `Cache`. */
1498template <class T>
1499std::string jmt150_refusal_id(const qn::NetworkStruct<T>& sn, const std::string& reason) {
1500 for (std::size_t i = 0; i < sn.nstations; ++i)
1501 if (jmt_is_preemptive_server_sched(sn.stations[i].sched) &&
1502 reason.compare(0, 8 + sn.stations[i].name.size() + 1, "Station " + sn.stations[i].name + " ") == 0)
1503 return qn::feature_name(qn::feature_of_sched(sn.stations[i].sched));
1504 return "Cache";
1505}
1506
1507template <class T>
1508std::string jmt_method_refusal(const qn::NetworkStruct<T>& sn, const std::string& method,
1509 const JmtOptions& opt) {
1510 (void)opt;
1511 {
1512 const std::string removed = jmt_removed_method_refusal(method);
1513 if (!removed.empty()) return removed;
1514 }
1515 {
1516 const std::string doc = jmva_document_refusal(sn, method);
1517 if (!doc.empty()) return doc;
1518 }
1519 // LINEAR ADMISSION CONSTRAINTS: no JMT region carries A*n <= b, so the writer dropped them.
1520 for (const auto& rg : sn.regions)
1521 if (rg.lincon_A.rows() > 0)
1522 return "SolverJMT does not support linear admission constraints on a finite capacity region (setLinearConstraints): no JMT region carries them, so the region would be simulated without its A*n <= b limit. Use SolverCTMC, SolverNC or SolverLDES.";
1523 // EXHAUSTIVE AND K-LIMITED POLLING. The export is JMT's own, but the engine
1524 // reports a queue length that grows without bound next to a sane response
1525 // time, and a throughput below the arrival rate (QLen 2674, Tput 0.283
1526 // against the exact 0.883 and 0.3 on two classes at 0.3/s, Exp(1.5)
1527 // service, Exp(1) switchover). GATED polling is simulated correctly.
1528 for (std::size_t i = 0; i < sn.nstations; ++i)
1529 for (const lang::PollingType pt : sn.stations[i].polling_type)
1531 return std::string("SolverJMT does not support ") +
1532 (pt == lang::PollingType::EXHAUSTIVE ? "EXHAUSTIVE" : "K-LIMITED") +
1533 " polling: JMT's polling server for it reports a queue length that grows "
1534 "without bound and a throughput below the arrival rate on a stable station. "
1535 "Use SolverMVA, SolverLDES or SolverSSA; JMT simulates GATED polling correctly.";
1537 return std::string("SolverJMT does not support ") +
1538 (pt == lang::PollingType::DECREMENTING ? "DECREMENTING" : "G-LIMITED") +
1539 " polling: JMT has no polling server for this discipline. Use SolverLDES, "
1540 "SolverSSA or SolverCTMC.";
1541 // IMMEDIATE FEEDBACK, which no JMT engine has semantics for: a self-looping
1542 // job KEEPS the server it just used, and both the JSIM routing block and the
1543 // JMVA visit count answer for a job that leaves and re-queues. This lived in
1544 // `solver_jmt_run_analyzer` alone until 2026-09-13, which is exactly how
1545 // `--find-solver-all` came to offer `jmt.*` on a model every JMT run throws
1546 // on.
1547 if (sn.has_immediate_feedback())
1548 return "SolverJMT: JMT has no immediate-feedback semantics (a job re-entering service "
1549 "while HOLDING the server); use SolverCTMC, SolverSSA or SolverLDES";
1550 if (qn::jmva_is_closed_only(method)) {
1551 double maxFinite = 0.0;
1552 for (std::size_t i = 0; i < sn.nstations; ++i) {
1553 const double c = static_cast<double>(sn.stations[i].nservers);
1554 if (std::isfinite(c)) maxFinite = std::max(maxFinite, c);
1555 }
1556 if (maxFinite > 1.0) return "SolverJMT: " + method + " does not support multi-server stations";
1557 }
1558 // JMVA'S MULTICLASS CoMoM ANSWERS A DIFFERENT MODEL EVERY RUN: when its BTF system is singular,
1559 // SolverMultiClosedCoMoM perturbs every demand with an unseeded MersenneTwister, re-solves, and
1560 // reports the result as an exact CoMoM solution. Keyed on the chain count, as in MATLAB
1561 // jmtMethodRefusal, because the singular case cannot be predicted from the demands; a
1562 // single-chain model runs SolverSingleClosedRECAL and stays exact. An open or mixed model is
1563 // left to the OpenClass refusal of jmt_feature_set: the closed-only CoMoM never runs on it.
1564 const std::vector<double> comom_njobs = sn.njobs();
1565 const bool comom_closed = std::all_of(comom_njobs.begin(), comom_njobs.end(),
1566 [](double n) { return std::isfinite(n); });
1567 if ((method == "jmva.comom" || method == "jmt.jmva.comom") && sn.nchains > 1 && comom_closed)
1568 return method + " is refused on a model with " + std::to_string(sn.nchains) +
1569 " chains: JMT's multiclass CoMoM engine silently re-solves a randomly perturbed model "
1570 "whenever its exact linear system is singular, and reports that as an exact CoMoM "
1571 "solution, so the answer is wrong and different on every run. Use 'jmva.recal', which "
1572 "is exact and reproducible on the same document, 'jmva'/'jmva.mva' for exact MVA, or "
1573 "SolverNC for a LINE-native normalizing constant.";
1574 for (std::size_t i = 0; i < sn.nstations; ++i) {
1575 const std::vector<T>& alpha = sn.stations[i].lldscaling;
1576 if (alpha.empty()) continue;
1577 double c = 0.0;
1578 for (const T& s : alpha) c = std::max(c, num_traits<T>::to_double(s));
1579 if (c == 1.0) continue;
1580 bool ok = (c >= 1.0) && (c == std::floor(c));
1581 for (std::size_t n = 0; ok && n < alpha.size(); ++n)
1582 ok = std::abs(num_traits<T>::to_double(alpha[n]) -
1583 std::min(static_cast<double>(n + 1), c)) <= qn::GlobalConstants::Zero;
1584 if (!ok)
1585 return "SolverJMT: station '" + sn.stations[i].name +
1586 "' uses a load-dependent scaling that is not the multiserver encoding alpha(n) "
1587 "= min(n,c): JMT has no representation for it, since both the JSIM and the JMVA "
1588 "writer carry the scaling as a server count, and the model would be solved at "
1589 "the nominal service rate. Use SolverCTMC, SolverNC, SolverMVA or SolverSSA, "
1590 "which read sn.lldscaling directly";
1591 }
1592 // A BINDING FINITE BUFFER, which neither engine can carry -- JSIM because no
1593 // JMT drop strategy reproduces LINE's blocking, JMVA because its document has
1594 // no capacity element at all. The verdict is the WRITER's own
1595 // (`io::JmtWriter::buffer_capacity_refusal`), asked here without letting it
1596 // raise, so the gate binds exactly where the writer binds.
1597 //
1598 // WHICH ENGINE IS ASKED ABOUT: a method that is neither engine's gets no
1599 // verdict rather than JSIM's rule applied to a run JSIM is not going to make.
1600 const bool is_jmva = method.compare(0, 4, "jmva") == 0;
1601 const bool is_jsim = method == "default" || method == "jsim";
1602 if (is_jmva || is_jsim) {
1603 const std::string cap_reason = io::jmt_buffer_capacity_refusal(sn, is_jmva);
1604 if (!cap_reason.empty()) return cap_reason;
1605 }
1606 // A CACHE THE JSIM WRITER REFUSES (FIFO/SFIFO on a list of capacity above 1, HLRU/CLIMB/QLRU, a promotion
1607 // graph JMT cannot carry, a popularity that is neither Zipf nor uniform): the writer's own verdict
1608 // (`io::JmtWriter::cache_refusal`), so the gate stops offering jmt.jsim where the run would raise
1609 // (MATLAB jmtCachePromotion, asked by jmtMethodRefusal and SolverJMT.supports).
1610 // AN EDD OR EDF STATION WHOSE SERVED CLASSES CARRY NO DUE DATE: the JSIM run would abort on it
1611 // (jmtMethodRefusal.m asks jmtDeadlineRefusal on the jsim engine only; JMVA has no such discipline).
1612 if (is_jsim) {
1613 const std::string deadline_reason = io::jmt_deadline_refusal(sn);
1614 if (!deadline_reason.empty()) return deadline_reason;
1615 }
1616 if (is_jsim) {
1617 const std::string cache_reason = io::jmt_cache_refusal(sn);
1618 if (!cache_reason.empty()) return cache_reason;
1619 }
1620 // JMT 1.5.0 AND LATER. Empty for any earlier release, for the Docker and
1621 // REST arms (they run LINE's own JMT) and for the jmva methods.
1622 {
1623 const std::string v150 = jmt150_refusal(sn, method, jmt_local_version(opt));
1624 if (!v150.empty()) return v150;
1625 }
1626 return std::string();
1627}
1628
1629/**
1630 * Port of `@@SolverJMT/runAnalyzer.m`, the `jsim` and `jmva` arms.
1631 *
1632 * The sample count is RAISED to 5000 when the caller asks for less, as the
1633 * reference does: JMT terminates a measure on its own precision target and
1634 * needs that many samples per measure before it will report one, so a smaller
1635 * request silently yields unsuccessful measures rather than a faster run.
1636 */
1637template <class T>
1639 JmtOptions opt = opt_in;
1640 if (opt.samples < 5000.0) opt.samples = 5000.0;
1641 {
1642 const std::string removed = jmt_removed_method_refusal(opt.method);
1643 if (!removed.empty()) throw UnsupportedError(ErrorKind{"Method"}, removed);
1644 }
1645 const std::vector<std::string> valid = jmt_list_valid_methods();
1646 if (std::find(valid.begin(), valid.end(), opt.method) == valid.end())
1647 throw UnsupportedError(ErrorKind{"Method"}, "SolverJMT: unknown method '" + opt.method + "'");
1648 // runAnalyzerChecks, as MATLAB/JAR/Python ask it: without it a closed-only jmva.* algorithm on an open model
1649 // reached JMT and came back as "[LINE:external:JMT] ... UnsupportedModelException" instead of a refusal.
1650 qn::feature_gate("SolverJMT", qn::jmt_feature_set(opt.method), sn);
1651 // The structural half of the gate, which `auto_family_refusal` also asks:
1652 // the single-server restriction of the closed-form JMVA algorithms and the
1653 // load-dependent shape JMT can carry. A second copy of either rule is how
1654 // the report and the run come to disagree.
1655 {
1656 // The id follows the sentence, as in the JAR (jmtStructuralRefusalId), MATLAB and Python: a JSIM writer
1657 // cache refusal keeps the writer's own LINE:unsupported:Cache, any other structural refusal is Structure.
1658 const std::string refusal = jmt_method_refusal(sn, opt.method, opt);
1659 if (!refusal.empty()) {
1660 const std::string v150 = jmt150_refusal(sn, opt.method, jmt_local_version(opt));
1661 throw UnsupportedError(ErrorKind{refusal == io::jmt_cache_refusal(sn) ? "Cache"
1662 : (!v150.empty() && refusal == v150) ? jmt150_refusal_id(sn, v150)
1663 : "Structure"},
1664 refusal);
1665 }
1666 }
1667 const bool jmt150 = jmt_is_at_least_150(jmt_local_version(opt));
1668
1669 const bool is_mva = opt.method.compare(0, 4, "jmva") == 0;
1670 const std::string mode = is_mva ? "mva" : "sim";
1671 util::TempDir work(is_mva ? "jmva" : "jsim");
1672 if (opt.keep) work.keep();
1673 const std::string model_path = work.path() + "/model." + (is_mva ? "jmva" : "jsim");
1674
1675 if (is_mva) {
1676 // `io/jmva_writer.h` is the shared port of `writeJMVA`: SolverLQNS reads
1677 // the same grammar through `qnsolver`, and a second copy of the writer
1678 // here would be a second place for the chain aggregation to drift.
1679 io::write_jmva(sn, model_path, opt.method, static_cast<std::size_t>(opt.samples));
1680 } else {
1682 wopt.file_name = "model";
1683 wopt.log_path = sn.log_path;
1684 wopt.seed = opt.seed;
1685 wopt.max_samples = opt.samples;
1686 wopt.max_simulated_time = opt.max_simulated_time;
1687 wopt.max_events = opt.max_events;
1688 wopt.sim_conf_int = opt.confint > 0.0 ? opt.confint : 0.99;
1689 wopt.jmt150 = jmt150;
1690 line::util::LineConsole::step("writing the JSIM model file");
1691 detail::write_file(model_path, io::jmt_write_jsim(sn, wopt));
1692 line::util::LineConsole::substep("model written to %s", model_path.c_str());
1693 }
1694
1695 line::util::LineConsole::step("running the JMT simulation engine as a subprocess");
1696 const util::ProcResult run = jmt_run(mode, model_path, opt.seed, opt);
1697 const std::string result_path = model_path + "-result." + jmt_result_ext(mode);
1698
1699 line::util::LineConsole::step("parsing the JMT result files");
1700 JmtResult<T> res;
1701 if (is_mva) {
1702 res = jmt_parse_jmva(sn, result_path, run.out);
1703 } else {
1704 res = jmt_map_measures(sn, jmt_parse_measures(result_path, run.out), opt.confint > 0.0);
1705 jmt_region_losses(sn, res);
1706 // JMT >= 1.5.0 counts a job's arrival twice at a station inside a finite
1707 // capacity region, so its "Arrival Rate" measure is not the station's.
1708 // Derive it by flow balance from the throughputs, as MATLAB's
1709 // runAnalyzer, the JAR and Python do on that release.
1710 if (jmt150) {
1711 Matrix<T> TNst(sn.nstations, sn.nclasses, num_traits<T>::from_int(0));
1712 for (std::size_t i = 0; i < sn.nstations; ++i)
1713 for (std::size_t r = 0; r < sn.nclasses; ++r) TNst(i, r) = res.avg.TN(i, r);
1714 const Matrix<T> ANst = mva::sn_get_arvr_from_tput(sn, TNst);
1715 for (std::size_t i = 0; i < sn.nstations; ++i)
1716 for (std::size_t r = 0; r < sn.nclasses; ++r) res.avg.AN(i, r) = ANst(i, r);
1717 }
1718 }
1719 // ResidT DERIVED on both arms as getAvg does (JSIM disagrees under class switching, JMVA per-chain); else column zero. Region rows keep JMT total.
1720 {
1721 const Matrix<T> WNst = mva::sn_get_residt_from_respt(sn, res.avg.RN);
1722 for (std::size_t i = 0; i < sn.nstations; ++i)
1723 for (std::size_t r = 0; r < sn.nclasses; ++r) res.avg.WN(i, r) = WNst(i, r);
1724 }
1725 // A SOURCE HAS NO ARRIVALS TO ITSELF. JMT reports an "Arrival Rate" measure
1726 // at every station the model declares, the Source included, where the
1727 // reference reports 0: `getAvg.m:197-199` builds a zeroMask over the Source
1728 // stations and applies it to the ArvR column for EVERY solver. This port's
1729 // analytical arms already leave that entry at zero, so the JMT reader was
1730 // the one path that carried JMT's own measure through -- 0.79526 against 0
1731 // on fcr_mm1kdrop, 0.30214 and 0.4979 on fcr_constraints. Region rows are
1732 // past `nstations` and are left alone, as the residence time above leaves
1733 // them.
1734 for (std::size_t i = 0; i < sn.nstations; ++i) {
1735 if (sn.stations[i].nodetype != qn::NodeType::Source) continue;
1736 for (std::size_t r = 0; r < sn.nclasses; ++r)
1737 res.avg.AN(i, r) = num_traits<T>::from_int(0);
1738 }
1739 // A CELL WITH NO RESPONSE TIME HOLDS NO JOBS AND BUSIES NO SERVER.
1740 // `@@NetworkSolver/getAvg` builds `zeroMask = RN < 10*FineTol` and applies
1741 // it to the queue length and the utilization for EVERY solver; the
1742 // analytical arms of this port take it through `mva::filter_metric`, and
1743 // the JMT reader was the one path that did not. JMT keeps sampling a
1744 // starved class's utilization long after its response time has been
1745 // discarded as non-recurrent, so the cell arrives as a small positive
1746 // number where every other codebase reports 0: 0.0010617 against 0 on
1747 // prio_hol_closed (PSQueue, Class2), on an otherwise IDENTICAL sample path.
1748 // Region rows past `nstations` are left alone, as the two rules above are.
1749 {
1750 for (std::size_t i = 0; i < sn.nstations; ++i)
1751 for (std::size_t r = 0; r < sn.nclasses; ++r)
1752 if (num_traits<T>::to_double(res.avg.RN(i, r)) <
1754 res.avg.QN(i, r) = num_traits<T>::from_int(0);
1755 res.avg.UN(i, r) = num_traits<T>::from_int(0);
1756 }
1757 }
1758 res.avg.method = opt_in.method;
1759 res.avg.actualmethod = opt.method;
1760 res.avg.iter = 1;
1761 return res;
1762}
1763
1764} // namespace jmt
1765} // namespace line
1766
1767#endif // LINE_SOLVERS_WRAPPERS_JMT_SOLVER_JMT_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
Transport-level failure: unresolvable host, refused connection, timeout.
Definition http.h:54
A network plus its refreshed NetworkStruct.
static void substep(const char *fmt,...)
Write one indented progress line.
static void step(const char *fmt,...)
Write one progress line.
void keep()
Leave the directory in place, for a caller that wants to inspect it.
Definition tempdir.h:130
const std::string & path() const
The directory itself, with no trailing separator.
Definition tempdir.h:124
Docker primitives for the backends that legitimately ship an image.
The exception types the port throws.
Minimal HTTP/1.1 client, enough to talk to a line-*-rest service.
Port of @@JMTIO: a refreshed NetworkStruct written out as a JMT .jsimg simulation model.
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.
The method names of each solver, in listing order.
bool sn_has_multi_class_heter_fcfs(const qn::NetworkStruct< T > &sn)
sn_has_multi_class_heter_fcfs: an FCFS station whose per-class rates differ.
bool sn_has_fork_join(const qn::NetworkStruct< T > &sn)
any(sn.fj(:) > 0): the model has a Fork closed by a Join.
Response post_json(const std::string &url, const std::string &json, int timeoutMillis)
POST a JSON document.
Definition http.h:360
bool docker_has_storage_for(const std::string &image)
std::string jmt_write_jsim(const qn::NetworkStruct< T > &sn, const JmtWriteOptions &opt)
Port of @@JMTIO/writeJSIM.m: serialize sn as a JMT .jsimg document.
std::string jmt_buffer_capacity_refusal(const qn::NetworkStruct< T > &sn, bool jmva_engine)
JmtWriter::buffer_capacity_refusal without a document: the writer's own binding-buffer verdict,...
bool docker_daemon_available()
True if the Docker daemon is reachable.
bool docker_has_local_image(const std::string &image)
std::string jmt_cache_refusal(const qn::NetworkStruct< T > &sn)
JmtWriter::cache_refusal over every Cache node, without a document: the writer's own cache verdict,...
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).
std::string jmt_deadline_refusal(const qn::NetworkStruct< T > &sn)
Port of jmtDeadlineRefusal.m: the due date an EDD or EDF station needs and the model does not carry,...
Definition jmt_writer.h:375
bool docker_pull(const std::string &image)
Pulls an image, streaming Docker's progress to stdout and stderr.
std::string jmt150_refusal(const qn::NetworkStruct< T > &sn, const std::string &method, const std::string &version)
What JMT 1.5.0 and later simulate WRONGLY, worded as a refusal; empty for a release before 1....
static const char * JMT_DOCKER_IMAGE
The default JMT REST/Docker image, MATLAB's jmtDockerImage candidate.
Definition solver_jmt.h:99
void jmt_region_losses(const qn::NetworkStruct< T > &sn, JmtResult< T > &res)
The region loss table, port of the sn.nregions > 0 tail of getResults.m.
std::string jmt_local_version(const JmtOptions &opt)
The release of the jar jmt_run would launch locally; empty when the run goes to a REST service or wou...
util::ProcResult jmt_run(const std::string &mode, const std::string &model_path, long seed, const JmtOptions &opt)
Port of jmtRun: one batch analysis, leaving the result where the JMT CLI itself would leave it.
Definition solver_jmt.h:635
JmtResult< T > jmt_parse_jmva(const qn::NetworkStruct< T > &sn, const std::string &result_path, const std::string &command_output)
Port of getResultsJMVA.m: the per-CHAIN answer spread back over the classes.
util::ProcResult jmt_run_docker(const std::string &image, const std::string &mode, const std::string &model_path, long seed, const JmtOptions &opt)
Run the analysis inside the JMT container and copy the result back beside the model,...
Definition solver_jmt.h:710
util::ProcResult jmt_solve_rest(const std::string &rest_url, const std::string &mode, const std::string &model_path, long seed, const JmtOptions &opt)
Port of jmtSolveRest: POST the model document, write the result document back beside the model so the...
Definition solver_jmt.h:577
bool jmt_is_preemptive_server_sched(lang::SchedStrategy s)
The schedules JMT serves through its PreemptiveServer.
std::string jmt150_refusal_id(const qn::NetworkStruct< T > &sn, const std::string &reason)
The error id of a jmt150_refusal sentence: SchedStrategy_<NAME> or Cache.
std::vector< std::string > jmt_list_valid_methods()
Port of SolverJMT.listValidMethods.
JmtResult< T > solver_jmt_run_analyzer(const qn::NetworkStruct< T > &sn, const JmtOptions &opt_in)
Port of @@SolverJMT/runAnalyzer.m, the jsim and jmva arms.
std::string jmva_document_refusal(const qn::NetworkStruct< T > &sn, const std::string &method)
The structural half of SolverJMT's method gate; empty when admissible.
JmtResult< T > jmt_map_measures(const qn::NetworkStruct< T > &sn, const std::vector< JmtMeasure > &measures, bool confint)
Port of getResults.m: the measures mapped onto the metric matrices.
Definition solver_jmt.h:859
bool jmt_available()
True when a local JVM and common/JMT.jar are both present.
Definition solver_jmt.h:569
std::string jmt_removed_method_refusal(const std::string &method)
The migration sentence for a method name SolverJMT no longer has; empty for any other name.
bool jmt_is_at_least_150(const std::string &version)
True for a release at or after 1.5.0, compared numerically on the leading major.minor....
static const char * JMT_JAR_URL
Where a missing jar is fetched from; LINE_JMT_URL names a mirror instead.
Definition solver_jmt.h:102
std::vector< JmtMeasure > jmt_parse_measures(const std::string &result_path, const std::string &command_output)
Port of getResultsJSIM: every <measure> of the result document.
Definition solver_jmt.h:784
const char * jmt_result_ext(const std::string &mode)
The suffix jmt.commandline.Jmt appends to the model path, per mode.
Definition solver_jmt.h:562
static const char * JMT_JAR_SHA256
The digest a fetched jar must have, and the reason the fetch can be trusted.
Definition solver_jmt.h:119
std::string jmt_version(const std::string &jar)
The release of a JMT jar: the jmt.version= line of jmt/common/globalsettings.conf inside it,...
std::string jmt_method_refusal(const qn::NetworkStruct< T > &sn, const std::string &method, const JmtOptions &opt)
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
PollingType
Polling service disciplines, with the values of MATLAB PollingType.
Definition lang_types.h:391
@ KLIMITED
serve at most K per visit (K in pollingPar)
Definition lang_types.h:394
@ EXHAUSTIVE
serve until the queue empties
Definition lang_types.h:393
@ GLIMITED
serve at most K of the jobs present at the polling instant
Definition lang_types.h:396
@ DECREMENTING
serve until the queue is one shorter than at arrival
Definition lang_types.h:395
const char * sched_to_text(SchedStrategy s)
Definition lang_types.h:248
std::string name(const Element *el, const std::string &key="name")
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 > 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
FeatureSet jmt_feature_set(const std::string &method)
Port of SolverJMT.getFeatureSet (@@SolverJMT/SolverJMT.m:180-290).
void feature_gate(const std::string &solver, const FeatureSet &declared, const NetworkStruct< T > &sn, const std::string &requested_method="", const std::string &resolved_method="")
runAnalyzerChecks: refuse a model the solver does not declare, by name.
Feature feature_of_sched(SchedStrategy s)
SchedStrategy.toFeature.
const char * feature_name(Feature f)
The canonical registry name, byte for byte the MATLAB field name.
bool jmva_is_closed_only(const std::string &method)
True for the JMVA algorithms that solve a CLOSED product-form network only.
std::vector< double > stat(const Matrix< double > &A)
Stationary distribution of a stochastic matrix: the left eigenvector for eigenvalue 1,...
Definition mg1.h:221
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
int run_inherit(const std::vector< std::string > &argv)
Runs a command with the parent's stdout and stderr, e.g.
Definition subprocess.h:170
bool timeout_exceeded()
The checkpoint: true when the innermost budget has run out, marking it tripped.
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...
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.
std::string sha256_file_hex(const std::string &path)
The digest of a file's contents, streamed.
Definition sha256.h:188
bool timeout_armed()
Whether any budget is armed on this thread.
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 > parse_file(const std::string &path)
Read and parse a file.
Definition xml.h:290
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
SHA-256 (FIPS 180-4), for verifying a file the port did not build.
Chain aggregation and de-aggregation.
Ports of the sn_has_* / sn_is_* predicate family of matlab/src/api/sn.
The DECLARED side of the gate: one feature set per solver.
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
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
The simulation controls the JSIM header carries, MATLAB's JMTIO properties.
Definition jmt_writer.h:69
bool jmt150
JMT 1.5.0 or later runs the document: its Server takes a switchover argument ahead of delayOff/setUp,...
Definition jmt_writer.h:80
std::string log_path
model.getLogPath, the logPath attribute
Definition jmt_writer.h:71
std::string file_name
base name; the header echoes it plus .jsimg
Definition jmt_writer.h:70
One <measure> of a JMT result document, by its attributes.
Definition solver_jmt.h:768
std::string measure_type
Definition solver_jmt.h:769
std::string job_class
Definition solver_jmt.h:769
std::string node_type
Definition solver_jmt.h:769
The options of one JMT solve, SolverOptions('JMT') restricted to what is read.
Definition solver_jmt.h:123
int timeout
Seconds, an EXPLICIT hard bound on the REST and subprocess arms; 0 (the default) sets none of its own...
Definition solver_jmt.h:140
int replications
options.config.replications: the independent JSIM runs the transient ensemble of default averages ove...
Definition solver_jmt.h:146
std::string method
default | jsim | jmva | jmva.<alg>
Definition solver_jmt.h:124
std::string container
options.config.container, an image override
Definition solver_jmt.h:132
std::string rest_url
a JMT REST server; empty selects the local JVM
Definition solver_jmt.h:131
bool keep
keep the scratch directory after the solve
Definition solver_jmt.h:127
double confint
0 disables the confidence interval columns
Definition solver_jmt.h:128
double max_events
JSIM event budget, -1 unlimited; set by the samplers as MATLAB's maxEvents.
Definition solver_jmt.h:130
double samples
samples per measure; raised to 5000 below
Definition solver_jmt.h:125
The result of a JMT solve: the shared AvgResult plus what only JMT reports.
Definition solver_jmt.h:828
Matrix< T > Tard
getResults.m result.Avg.Tard (stations x classes) and .SysTard (1 x classes).
Definition solver_jmt.h:834
Matrix< T > SysTardCI
their half-widths, empty when disabled
Definition solver_jmt.h:835
std::map< std::size_t, std::vector< T > > cache_hit_prob
Per Cache node (1-based node index), the per-class hit probability.
Definition solver_jmt.h:837
Matrix< T > MemOcc
FCR-only: weighted and memory occupation.
Definition solver_jmt.h:831
mva::AvgResult< T > avg
Definition solver_jmt.h:829
Matrix< T > SysTard
Definition solver_jmt.h:834
Matrix< T > ACI
confidence half-widths, empty when disabled
Definition solver_jmt.h:830
T log_norm_const
result.Prob.logNormConstAggr, the log normalizing constant JMVA reports.
Definition solver_jmt.h:845
Matrix< T > DropRateNfcr
(nregions x nclasses) carried and lost rate
Definition solver_jmt.h:832
static constexpr double FineTol
Definition lang_types.h:823
The metrics getAvg returns, after filtering.
The chain-level view of a layer, as sn_get_demands_chain returns it.
Definition sn_chain.h:46
Matrix< T > ST
(M x K) class-level mean service time, 0 where disabled
Definition sn_chain.h:54
std::vector< std::size_t > refstatchain
(C) 1-based reference station
Definition sn_chain.h:53
Matrix< T > alpha
(M x K) class share of its chain's visits at a station
Definition sn_chain.h:50
Matrix< T > STchain
(M x C) mean service time
Definition sn_chain.h:48
Matrix< T > Vchain
(M x C) visits
Definition sn_chain.h:49
static constexpr double FineTol
Definition lang_types.h:823
static constexpr double Zero
Definition lang_types.h:825
FINITE CAPACITY REGIONS, MATLAB's refreshRegions output.
std::vector< DropStrategy > rule
per class
std::vector< bool > members
membership, independent of the caps
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
bool has_attr(const std::string &key) const
Definition xml.h:69
std::string attr(const std::string &key) const
Attribute value, or the empty string when absent (org.w3c.dom semantics).
Definition xml.h:63
Running an external command and capturing its output, with a deadline.
A scratch directory for the subprocess wrappers, the port's lineTempName.
A minimal XML DOM: read for the .lqnx interchange format, write for the JMT .jsimg and ....