LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
line_cli.cpp
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 *
5 * line-cli: multiprecision C++ front end, flag-compatible with
6 * jar/src/main/java/jline/cli/LineCLI.java.
7 *
8 * The flag surface is the Java one plus --arith and --list-api. Anything not
9 * yet ported is refused explicitly, naming what is missing; nothing is
10 * silently approximated or answered from a partial implementation.
11 *
12 * ONE BINARY FOR BOTH MODEL KINDS, as the Java reference is: a Network model
13 * (-i json) reaches solve_model_dispatch and a layered one (-i lqnx|xml)
14 * reaches solve_lqn_dispatch. They were two executables until the LQN path was
15 * folded in here; the split had no user-visible justification, since the Java
16 * CLI has always taken both from one entry point.
17 */
18#include <algorithm>
19#include <exception>
20#include <chrono>
21#include <cctype>
22#include <cmath>
23#include <cstdio>
24#include <cstdlib>
25#include <cstring>
26#include <fstream>
27#include <iostream>
28#include <iterator>
29#include <limits>
30#include <map>
31#include <optional>
32#include <sstream>
33#include <string>
34#include <vector>
35
44#include "line/io/jmt_writer.h"
45#include "line/io/jsim_reader.h"
47#include "line/io/pnml.h"
54#include "line/num/number.h"
56#include "line/reg/registry.h"
99#include "line/cli/cli_run.h"
100#include "line/io/marshal.h"
101#include "line/util/error.h"
102#include "line/util/websocket.h"
103
104namespace {
105
106// THE PRODUCT VERSION, and it must track the other six sites. `-V`, the help banner
107// and `--install` all print it, so a stale value here makes the tree report two
108// different versions depending on which entry point is asked. It sat at 0.1.0
109// while everything else said 3.0.8, because `release/post-release.sh` bumped a
110// list this file was not on; it is on that list now, and on its straggler scan.
111const char* kVersion = "3.0.10";
112
113/**
114 * Whether `-a avg` prints its table as JSON, i.e. `-o json`.
115 *
116 * A FILE-SCOPE FLAG, and the one place in this port that has one. The library
117 * under `include/line/` keeps no global mutable state, deliberately, so a
118 * pybind11 or MEX host can call it reentrantly; `line_cli.cpp` is a `main()`
119 * translation unit and the output format is a property of ONE process
120 * invocation, decided before any solve begins and never changed after. The
121 * alternative is threading a bool through `solve_model_{mva,nc,mam,ba}`,
122 * `solve_ctmc_avg`, `solve_fluid_avg` and `solve_ssa_avg`, three of which do
123 * not take the `Knobs` struct at all, to carry a value none of them varies.
124 */
125bool g_json_output = false;
126
127/**
128 * Where a JSON document goes when a host is collecting them, and nothing when
129 * no host is.
130 *
131 * IT HOLDS STRINGS AND NOT PARSED VALUES, which is the whole reason the sink
132 * sits at the emission sites rather than around them. The eleven sites use
133 * three different indents (`dump()`, `dump(1)`, `dump(2)`) and print their
134 * numbers at full precision precisely so a cross-codebase diff is not capped;
135 * parsing here and re-dumping in the host would silently reformat both, and the
136 * reformatting would stay invisible until someone diffed a golden. Storing the
137 * bytes the CLI printed is also what makes the byte-identity test possible: a
138 * host's document must appear VERBATIM in the binary's stdout.
139 */
140std::vector<std::string>* g_json_sink = nullptr;
141
142/** A host asked, through the C ABI, for the run to stop. */
143struct InterruptRequested : line::ExternalError {
144 explicit InterruptRequested(const std::string& what) : line::ExternalError(line::ErrorKind{"Interrupted"}, what) {}
145};
146
147int (*g_interrupt_cb)(void*) = nullptr;
148void* g_interrupt_user = nullptr;
149
150/**
151 * Poll the host's interrupt, if one was installed.
152 *
153 * Called where the CLI is between two units of work and holds nothing that a
154 * throw would leak: after a document is emitted, and between the analyses of a
155 * comma-separated `-a` list. It deliberately does NOT reach inside a solve.
156 */
157void poll_interrupt() {
158 if (g_interrupt_cb != nullptr && g_interrupt_cb(g_interrupt_user) != 0)
159 throw InterruptRequested("the run was interrupted by the host");
160}
161
162/**
163 * Print one JSON document, and record it when a host is collecting.
164 *
165 * The printf is unchanged and unconditional, so `line-cli` prints exactly what
166 * it printed before this sink existed. That is the acceptance test for this
167 * whole change: with `g_json_sink == nullptr` the binary must be byte-identical.
168 */
169void emit_document(const std::string& text) {
170 if (g_json_sink != nullptr) g_json_sink->push_back(text);
171 std::printf("%s\n", text.c_str());
172 poll_interrupt();
173}
174
175/**
176 * Replace every non-finite number in a document with the spelling this wire
177 * gives one.
178 *
179 * JSON HAS NO INFINITE LITERAL, and nlohmann serialises any non-finite double
180 * as `null`. That is correct for a NaN -- `null` is how this wire says "no
181 * value", and it is what the readable table's `nan` means -- and wrong for an
182 * infinity, which is an ANSWER rather than the absence of one. A queue at or
183 * past its stability boundary has an infinite mean queue length and response
184 * time; a host that reads that `null` as "not computed", or as zero, inverts
185 * the conclusion it draws from it.
186 *
187 * The spelling is the JAR's (`LineCLI.appendDoubleArray`): an infinity rides as
188 * the STRING "Infinity" / "-Infinity", which MATLAB `linemodel_load`, Python
189 * `linemodel_io` and the R `from_wire_num` all accept.
190 *
191 * It walks the document immediately before the dump rather than at each push
192 * site because there are dozens of the latter, spread across every analysis,
193 * and a rule applied at some of them is a rule that holds for some answers.
194 */
195void finitize_document(line::reg::Json& j) {
196 if (j.is_object() || j.is_array()) {
197 for (line::reg::Json& child : j) finitize_document(child);
198 return;
199 }
200 if (!j.is_number_float()) return;
201 const double v = j.get<double>();
202 if (std::isinf(v)) j = (v > 0.0 ? "Infinity" : "-Infinity");
203}
204
205/**
206 * `dump()` with the rule above applied. Takes its document BY VALUE: emission
207 * is not the end of a document's life here (the `-a` comma list emits one per
208 * analysis and several arms read their own back), so rewriting the caller's
209 * copy would change what it sees after printing.
210 */
211std::string dump_document(line::reg::Json j, int indent = -1) {
212 finitize_document(j);
213 // --timeout: a solve the budget cut short says so at the TOP LEVEL of every
214 // document it emits, `"timedOut": true`, read from the budget's tripped
215 // latch. Absent otherwise, so an unbudgeted document is byte-identical to
216 // what it always was.
217 if (j.is_object() && line::util::timeout_tripped()) j["timedOut"] = true;
218 return indent < 0 ? j.dump() : j.dump(indent);
219}
220
221/**
222 * The solver knobs the CLI exposes, gathered so the dispatcher can check them
223 * against the solver actually chosen.
224 *
225 * A sentinel means "not given" rather than a default, because the distinction
226 * is what lets an option be REFUSED for a solver that has no such setting
227 * instead of being accepted and dropped. That silent acceptance is the defect
228 * this struct exists to prevent: `--samples 1e6` was previously taken without
229 * complaint and the run still used 10000.
230 */
231struct Knobs {
232 std::string method;
233 double tol = -1.0; // < 0 = not given
234 double iter_tol = -1.0;
235 int iter_max = -1;
236 // --stiff, `options.stiff` of a CTMC transient (and of the CTMC stages of
237 // -s env): < 0 = not given, 0 = false (ode23), 1 = true (the default).
238 int stiff = -1;
239 // --max-states, `options.config.maxStates`: the truncation level of an OPEN
240 // agent's queue-length dimension in SolverAG. < 0 = not given, so AgOptions
241 // keeps its own 100. It is a TRUNCATION and therefore part of the ANSWER,
242 // not a budget: a run truncated at 100 that the caller asked to truncate at
243 // 500 is a different number reported as theirs, which is why it travels
244 // rather than being dropped the way the execution backends are.
245 long long max_states = -1;
246 // --multiserver, the AMVA rule that decides WHICH algorithm serves a
247 // multiserver model. Empty = not given, so the solver keeps its default:
248 // a rule this CLI silently dropped made every delegated solve answer under
249 // 'default' while reporting the caller's choice.
250 std::string multiserver;
251 // --fork-join, `options.config.fork_join`: WHICH fork-join arm the shared
252 // fixed point takes on a model with a Fork. Empty = not given, so the solver
253 // keeps 'default' (the MMT transform); 'ht' is Heidelberger-Trivedi, which
254 // is a different answer to the same model rather than a faster one.
255 std::string fork_join;
256 // The solver console has NO knob of its own: it IS VerboseLevel::DEBUG,
257 // so `-v debug` is what asks for the running progress log.
258 std::size_t samples = 0; // 0 = not given
259 unsigned long seed = 0;
260 double cutoff = -1.0; // < 0 = not given
261 // --cutoff AS A MATRIX, `r1c1,r1c2;r2c1,r2c2`: the reference's
262 // `options.cutoff` is a (station x class) table wherever a model needs a
263 // different truncation per station, and reading only the scalar form left
264 // `atof` silently taking the first number, i.e. truncating every station at
265 // the first station's first class. Empty = not given.
266 std::vector<std::vector<std::size_t>> cutoff_mat;
267 /** True when `--cutoff` was given in EITHER spelling. */
268 bool has_cutoff() const { return cutoff >= 0.0 || !cutoff_mat.empty(); }
269 // --force, `options.force`: downgrade SolverCTMC's memory pre-gate from a
270 // refusal to a warning. The gate exists because the alternative to refusing
271 // is the OOM killer, so this is opt-in and never a default.
272 bool force = false;
273 // --fj-accuracy / --fj-tmode, `options.config.fj_accuracy` and
274 // `options.config.fj_tmode` of solver_mam_fj.m. The first is the FJ_codes
275 // truncation C of the queue-length difference between the two branches and
276 // is the accuracy knob of that approximation; the second picks the route to
277 // the T matrix. Kept apart from --tol/--iter_max for the same reason
278 // --mdd-tol is: C is a STATE-SPACE bound, not a convergence threshold.
279 int fj_accuracy = 0; // 0 = not given
280 std::string fj_tmode; // empty = not given
281 // --sync-phases, `options.config.sync_phases` of the MAM 'sync.faster' /
282 // 'sync.slower' methods: the synchronous phase expansion, 0 = none.
283 int sync_phases = -1; // -1 = not given
284 // --ispn-place / --ispn-maxlevel, `options.config.ispn_place` and
285 // `ispn_maxlevel` of the MAM 'ispn' method (also reached by 'default' on a
286 // stochastic Petri net): the unbounded level and the level-window cap.
287 std::string ispn_place; // empty = not given
288 int ispn_maxlevel = -1; // -1 = not given
289 // --censor-level, `options.config.censor_level` of the MAM 'censor' method:
290 // the level station, by name or as a 1-based station index. A value that
291 // reads wholly as a number is the index (kept as written, so the solver
292 // refuses a non-integer or out-of-range one as the reference does).
293 std::string censor_level; // empty = not given
294 std::optional<double> censor_level_index; // unset = not given
295 // --mapmsg-quantization, `options.config.mapmsg_quantization` of the MAM
296 // MAP/M/s+G reneging analyzer: the regime count of the patience CDF.
297 int mapmsg_quantization = -1; // -1 = not given
298 // --timescale, `options.config.timescale` of sn_is_discrete_time.m. "auto"
299 // lets the distributions decide whether the model is slotted; "discrete"
300 // and "continuous" force the reading, the first raising when the model
301 // mixes lattice and non-lattice laws rather than solving the wrong time
302 // scale. The slot itself comes from the SHARED `--slotlength` below, the
303 // same one SolverNC's discrete product form reads.
304 std::string timescale; // empty = not given
305 // --mdd-tol / --mdd-maxiter, the level iteration of `-s ctmc --method mdd`.
306 // They are DELIBERATELY not --tol / --iter_tol: that iteration is an INNER
307 // numerical solve whose fixed point is verified against the model's
308 // population invariant at 1e-6, so an AMVA-sized tolerance converges short
309 // of it and trips the guard. The reference keeps them apart for the same
310 // reason (options.config.mdd_tol, not options.iter_tol).
311 double mdd_tol = -1.0; // < 0 = not given
312 int mdd_maxiter = 0; // 0 = not given
313 // --level, the hierarchy level of the pbh/bjbh/cbh/sib families.
314 // 0 = not given, so BaOptions keeps its 2.
315 int level = 0;
316 // --busyperiod / --busyperiod-subnet, the orders and the subnetwork of
317 // `-a busyperiod`. The flag names are `ldes_cli`'s, so ONE spelling drives
318 // the transform (solver_nc_busyp) and the simulation. The subnetwork has no
319 // default -- a busy period is defined for a named set of stations and
320 // choosing one here would answer about a subnetwork the caller never
321 // named -- while the orders default to the ordinary busy period, 1.
322 std::vector<std::size_t> busy_orders;
323 std::vector<std::size_t> busy_subnet;
324 // --qrf-params / --qrf-alpha, the blocking parameterisation and the
325 // load-dependent scaling of the QRF arms of SolverBA. Both are JSON, given
326 // inline or as a path; empty = not given.
327 std::string qrf_params;
328 std::string qrf_alpha;
329 // --tspan, the horizon the transient CTMC analyses integrate over. There is
330 // no default: pi(t) on an unstated horizon is not a quantity, and picking
331 // one here would answer a question the caller did not ask.
332 double t0 = 0.0, t1 = -1.0; // t1 < 0 = not given
333 std::size_t node = 0; // --node, 1-based; 0 = not given
334 // --class and --marg-states, the second and third arguments of
335 // `@@SolverMVA/getProbMarg`. The class is 1-based and 0 = not given, i.e.
336 // every class; the state list is the reference's `state_m` and empty = not
337 // given, i.e. the default range each of the three laws picks for itself.
338 // They are NOT folded into --node: a marginal is indexed by a PAIR, and one
339 // flag carrying both would make "station 2" and "class 2" the same token.
340 std::size_t jobclass = 0; // --class, 1-based; 0 = not given
341 std::vector<long> marg_states; // --marg-states; empty = not given
342 // --warmupfrac, `options.config.warmupfrac`: the leading fraction of an SSA
343 // path discarded before the means are taken. The JAR CLI has carried it
344 // since the SSA branch existed and this port did not, so a delegated solve
345 // asking for a warmup discard silently kept the whole transient.
346 // < 0 = not given, left unset: `ssa_resolve_warmupfrac` then picks 0.2 for a
347 // model with an open class and 0 otherwise.
348 double warmupfrac = -1.0;
349 // --pstar, `options.config.pstar`: the exponent of the fluid p-norm
350 // smoothing (Ruuskanen et al., PEVA 151 (2021), eq. (26)). It selects the
351 // DRIFT the matrix method integrates, so a solve that never receives it
352 // returns the unsmoothed mean-field fixed point under the caller's choice.
353 // < 0 = not given.
354 double pstar = -1.0;
355 // --fluid-boundary, `options.config.fluid_boundary`: how the fluid Petri `dae` route reports a fluid place
356 // (FSPN) level held at a bound, 'reflect' (the bound) or 'diffusion' (a reflected Brownian motion's mean).
357 // Empty = not given.
358 std::string fluid_boundary;
359 // --nonmkv, `options.config.nonmkv`: 'bernstein' fits a phase-type surrogate to a non-Markovian
360 // law before -s ctmc, mam, fluid and ag solve, 'none' skips the fit. Empty = not given.
361 std::string nonmkv;
362 // --notation, which form of the exported ODE document is wanted; empty = not
363 // given, and only `-a odes` has one.
364 std::string notation;
365 // --cdf-algorithm, `options.config.algorithm` of `@@SolverNC/getCdfRespT`:
366 // 'exact' is the pfqn_stdf sojourn-time inversion, 'rd' the pfqn_stdf_heur
367 // reduction. Empty = not given, so the solver keeps the reference's 'exact'.
368 // It is NOT --method: the ladder that computes the constants and the
369 // algorithm that inverts the sojourn law are separate choices, and folding
370 // them would make one name silently select the other.
371 std::string cdf_algorithm;
372 // -s ctmc -a firstpasst: the two state sets of `getCdfFirstPassT(A, B)`.
373 // Each is either a 1-based index list into the state space ("3,5") or
374 // semicolon-separated state rows ("0,2;1,1"), resolved against the space
375 // the engine enumerates -- rows travel across the boundary because the two
376 // enumerations need not order (or even purge) states identically.
377 std::string passage_from;
378 std::string passage_into;
379 // "expm" (default) or "lt", `options.config.passage_method` of the reference
380 std::string passage_method;
381 // -s ctmc -a firstpasstmom: the highest moment order, `nmax` of
382 // `getFirstPassTMoments(A, B, nmax)`. 0 means the reference's default of 3.
383 std::size_t passage_orders = 0;
384 // --passage-taboo: the TABOO set C of `getCdfFirstPassT(A, B, C)` and
385 // `getFirstPassTMoments(A, B, nmax, C)`, in the --passage-into syntax. A
386 // passage entering C before B is lost. Empty = no taboo set.
387 std::string passage_taboo;
388 // --passage-tset: the time grid of `getCdfFirstPassT(A, B, C, tset)`, comma
389 // separated, 'inf' allowed. Empty = not given, the default horizon grid.
390 std::string passage_tset;
391 // --perm-engine, the permanent estimator of `@@SolverNC/getProbSysMarg.m`:
392 // 'exact' is Ryser's expansion with column multiplicities, and 'spm',
393 // 'bethe', 'heur', 'huberlaw', 'adapart' are the five approximations. It is
394 // NOT --method: the ladder that computes the normalizing constant and the
395 // estimator that evaluates the permanent are separate choices. The five
396 // approximations REFUSE a demand matrix with a structural zero rather than
397 // flooring it, since they need full support. 'spm' is the only one that does
398 // not expand the matrix to order sum(N), so it is the one whose cost does
399 // not grow with the population and whose error falls as it grows.
400 std::string method_perm = "exact";
401 // --symbolic, `options.config.symbolic` of `@@SolverFLD/getJacobian`: auto
402 // to search for a line-sage-rest backend, a URL, an image name, or none to
403 // stay with the locally differentiated Jacobian. Empty = not given, i.e.
404 // auto. --equilibria is the reference's fourth output, which is REQUESTED
405 // and not implied: solving f(x) = 0 needs the backend, so implying it would
406 // turn a Jacobian this port answers on its own into one that fails without
407 // a container.
408 std::string symbolic;
409 bool equilibria = false;
410 // ---- the layered path's own knobs, on the same not-given discipline ----
411 // They are refused on the Network path rather than dropped, exactly as the
412 // ones above are refused for a solver that has no such setting.
413 bool no_interlocking = false; // --no-interlocking was passed
414 // --interlock-method / --interlock-maxpaths / --interlock-refpath-scope, the
415 // config.interlock_* of SolverLN. Empty / negative = not given.
416 std::string interlock_method;
417 double interlock_maxpaths = -1.0;
418 std::string interlock_refpath_scope;
419 bool interlock_knobs_given() const {
420 return !interlock_method.empty() || interlock_maxpaths >= 0.0 ||
421 !interlock_refpath_scope.empty();
422 }
423 // --lld STATION=EXPR (repeatable), --nlp-alpha, --nlp-warm, --nlp-maxiter,
424 // --nlp-fork, --warmstart, --mol-iter-max, --mol-iter-tol,
425 // --mol-relax-factor: config.lld / nlp_* / warmstart / mol_* of SolverLN.
426 // Empty / negative = not given.
427 std::map<std::string, std::string> lld;
428 double nlp_alpha = -1.0;
429 long nlp_warm = -1;
430 long nlp_maxiter = -1;
431 std::string nlp_fork;
432 std::string warmstart;
433 long mol_iter_max = -1;
434 double mol_iter_tol = -1.0;
435 double mol_relax_factor = -1.0;
436 bool nlp_knobs_given() const {
437 return !lld.empty() || nlp_alpha >= 0.0 || nlp_warm >= 0 || nlp_maxiter >= 0 || !nlp_fork.empty() ||
438 !warmstart.empty() || mol_iter_max >= 0 || mol_iter_tol >= 0.0 || mol_relax_factor >= 0.0;
439 }
440 int repeat = 0; // --repeat; 0 = not given, i.e. one run
441 std::string layer_solver; // --layer-solver; empty = not given
442 /**
443 * `--stage-solver`, which solver runs each stage of an ENVIRONMENT.
444 *
445 * IT IS NOT `--layer-solver`, and folding the two would be wrong: a LAYER of
446 * an LQN is solved in STEADY STATE and a STAGE of a random environment is
447 * solved TRANSIENTLY, so their admissible solver sets are different sets for
448 * different reasons. Empty = not given, i.e. the coupling's own default
449 * (fluid for the mean-field one, ctmc for the state-vector one). `mva` and
450 * `nc` have no transient and serve the 'avg'/'dec' limits only.
451 */
452 std::string stage_solver;
453 /*
454 * --env-init: `options.config.env_init` of SolverENV method 'occupation',
455 * the initial probability of each stage as a comma-separated list. Empty =
456 * not given, i.e. the first stage.
457 */
458 std::string env_init;
459 /*
460 * --map-env / --map-env-method / --map-env-maxstages: the random-environment
461 * FALLBACK for a model whose only unsupported feature is a non-renewal
462 * process. Unlike `--stage-solver` these are not `-s env` knobs: they apply
463 * to whichever solver was asked for, because the fallback is decided above
464 * the runner, in the `getAvg` funnel that `run_avg_engine` plays here.
465 * Empty / 0 = not given.
466 */
467 std::string map_env;
468 std::string map_env_method;
469 std::size_t map_env_maxstages = 0;
470 // --ln-transient / --ln-transient-channels, the coupling of the layered
471 // transient and which inter-layer channels it injects. Empty = not given.
472 std::string ln_transient;
473 std::string ln_transient_channels;
474 // --sens-method / --sens-scheme / --sens-step, the name-value contract of
475 // getSensitivityTable. They are NOT --method: --method names the LN update
476 // (default / moment3 / mw.*), and the branch that differentiates it is a
477 // separate choice. Empty / <= 0 = not given.
478 std::string sens_method;
479 std::string sens_scheme;
480 double sens_step = -1.0;
481 // --uq-solver, the engine SolverUQ runs at each design point. Empty is not
482 // a default here but a missing argument: UQ computes nothing itself, so
483 // there is no engine to fall back to, and `-s uq` without it is refused.
484 std::string uq_solver;
485 // --tran-points, the resolution of the uniform transient grid the ENV
486 // mean-field coupling sums its exit metrics over. It is that coupling's
487 // accuracy knob, not a cosmetic one: the sum is a Riemann-Stieltjes
488 // quadrature against the holding-time CDF, so the answer moves with the
489 // grid. 0 = not given, i.e. EnvOptions' own default.
490 std::size_t tran_points = 0;
491 // ---- the LQNS wrapper's own knobs -------------------------------------
492 // `options.keep` and `options.verbose` of the reference wrapper, plus the
493 // two that pick a REMOTE lqns. They apply to `-s lqns` alone and are
494 // refused elsewhere: nothing else in this CLI runs a child process whose
495 // working directory a caller might want to inspect.
496 bool keep = false;
497 bool verbose = false;
498 bool remote = false;
499 std::string remote_url; // empty = not given, i.e. the wrapper's default
500 // `options.timeout`, the wall-clock budget of the whole solve, any solver;
501 // 0 = not given, +Inf = given as no budget. Armed in run_invocation.
502 double timeout_seconds = 0.0;
503 // ---- the simulator's own knobs, all `--ldes-*` -------------------------
504 // They are PREFIXED rather than folded into the shared names because they
505 // are an external engine's settings and not this port's: --ldes-tranfilter
506 // is the warmup filter of a simulation run and has nothing to do with
507 // --tol, and an unprefixed --warmupfrac would read as a knob every solver
508 // has. Same not-given discipline as the rest -- empty, <= 0 or false means
509 // not given -- so the engine keeps its own default and the command line
510 // stays minimal, which is what an older AOT native binary can still parse.
511 std::string ldes_tranfilter; // mser5 | fixed | none
512 double ldes_warmupfrac = -1.0;
513 std::string ldes_cimethod; // obm | bm | spectral | none
514 bool ldes_cnvgon = false;
515 double ldes_cnvgtol = -1.0;
516 bool ldes_slotted = false;
517 double ldes_slotlength = -1.0;
518 /**
519 * `--slotted` / `--slotlength`: the discrete time scale for the
520 * ANALYTICAL solvers, distinct from the `--ldes-*` pair above, which
521 * configures the simulator. SolverNC reads it and routes to the
522 * discrete-time product form.
523 */
524 bool slotted = false;
525 double slotlength = -1.0;
526 int ldes_replications = 0;
527 int ldes_numthreads = 0;
528 double ldes_maxtime = -1.0;
529 std::vector<double> ldes_initsol; // station-major warm-start placement
530 std::string ldes_rest_url;
531 /**
532 * `--jmt-replications`, SolverJMT's `options.config.replications`: the JSIM runs the transient
533 * ensemble of -a tran / -a tranprob averages over. 0 keeps the engine default of 10.
534 */
535 int jmt_replications = 0;
536 // ---- the JAR CLI's own five, ported so `line-cli` answers every question
537 // `jline.cli.LineCLI` answers ------------------------------------------
538 /**
539 * `--state`, the state vector `-a prob` asks about.
540 *
541 * WITHOUT IT THE QUERY IS ABOUT THE MODEL'S DEFAULT INITIAL STATE, which is
542 * what this CLI reported before and remains the default. The JAR takes an
543 * explicit one because `getProb(node, state)` is a different question from
544 * `getProb(node)`: the second names a state the model already holds, the
545 * first names any state of the node's own space, and a caller sweeping a
546 * marginal law needs the first. Empty = not given.
547 */
548 std::vector<long> state;
549 /**
550 * `--events`, the length of a sampled trajectory, `options.samples` of
551 * `@@SolverSSA/sample`. It is NOT `--samples`: the JAR keeps them apart
552 * because `--samples` is a simulation run length or a Monte Carlo draw
553 * count and reaches a solver's options, while this is the number of EVENTS
554 * one `sample` call walks. Folding them would make `-s ssa -a avg --events`
555 * silently lengthen the run. 0 = not given, i.e. the reference's 1000.
556 */
557 std::size_t events = 0;
558 /**
559 * `--timestep`, the fixed output step of a transient analysis. Without it
560 * the grid is whatever the integrator chose, which is the reference's
561 * adaptive default; with it the trajectory is resampled onto a uniform
562 * lattice of that step, which is what a caller diffing two transients needs.
563 * <= 0 = not given.
564 */
565 double timestep = -1.0;
566 /**
567 * `--transient-method`, `options.config.transient_method` of
568 * `solver_ctmc_transient_analyzer.m`: "ode" integrates the forward
569 * equation, "fau" marches fast adaptive uniformization over the output
570 * grid. Empty = not given, so the solver keeps the reference's "ode".
571 *
572 * It is NOT `--method`: the state-space path and the way the forward
573 * equation is advanced on it are separate choices, and the reference keeps
574 * this one out of its valid-method list because it changes no stationary
575 * answer.
576 */
577 std::string transient_method;
578 /**
579 * `--fau-epsilon` and `--fau-delta`, the two tolerances of the "fau"
580 * transient: the total probability mass the grid may discard, and the
581 * occupancy below which a state is dropped from the support. <= 0 = not
582 * given, i.e. the reference's 1e-6 and 1e-12.
583 */
584 double fau_epsilon = -1.0;
585 double fau_delta = -1.0;
586 /**
587 * `--rate-sched`, `options.config.rate_sched` of
588 * `solver_ctmc_transient_analyzer.m`: a JSON array (inline, or the path of a
589 * file holding it) of {station, class, tgrid, rates[, nominal]} objects,
590 * with station and class given by name or 1-based index. Empty = not given.
591 */
592 std::string rate_sched;
593 /// `--ctmc-tv-ngrid`, `options.config.ctmc_tv_ngrid`; 0 = not given (100).
594 std::size_t ctmc_tv_ngrid = 0;
595 /**
596 * `--percentiles`, the levels `getPerctRespT` is read at. Empty = not
597 * given, i.e. the reference's `pers_stored` {0.50, 0.90, 0.95, 0.99}.
598 * Accepted as fractions (0.9) or as percents (90), told apart by magnitude:
599 * a level above 1 cannot be a probability.
600 */
601 std::vector<double> percentiles;
602 /**
603 * `-v/--verbosity`: silent | standard | debug.
604 *
605 * IT WAS ACCEPTED AND DISCARDED, which is the silent-acceptance defect this
606 * struct exists to prevent one layer up: a caller who asked for `silent`
607 * still received every warning the arms print on stderr. It gates them now,
608 * and nothing else -- the tables on stdout are the answer and are printed
609 * whatever the level, exactly as the JAR prints them.
610 */
611 std::string verbosity;
612 /**
613 * `--reward-name`, which declared reward `-a reward-value` returns the
614 * value function of. Empty = not given, and `-a reward-value` without it is
615 * refused rather than defaulted to the first reward: the value functions of
616 * two rewards are different objects, and picking one silently would label
617 * the wrong matrix with the caller's question.
618 */
619 std::string reward_name;
620};
621
622/**
623 * The three `--map-env*` knobs, as the gate wants them.
624 *
625 * One helper rather than three assignments per arm, for the reason the Knobs
626 * struct itself exists: the fallback is decided in every `-a avg` ladder and in
627 * `run_avg_engine`, and an arm that read a different subset of the three would
628 * accept a different model for the same command line.
629 */
630inline line::solvers::MapEnvConfig map_env_config(const Knobs& k) {
632 if (!k.map_env.empty()) c.mode = k.map_env;
633 if (!k.map_env_method.empty()) c.method = k.map_env_method;
634 if (k.map_env_maxstages) c.max_stages = k.map_env_maxstages;
635 return c;
636}
637
638/**
639 * `--cutoff` written as a per-(station,class) matrix, `';'`-separated rows of
640 * `','`-separated non-negative counts. Empty on anything that is not one.
641 *
642 * The spelling is the JAR CLI's, so one example pins one string for both
643 * engines. A zero entry is legal and means the station may not hold that class
644 * at all, which is how the reference bounds a queue in the classes it does not
645 * serve.
646 */
647std::vector<std::vector<std::size_t>> parse_cutoff_matrix(const std::string& s) {
648 std::vector<std::vector<std::size_t>> out;
649 std::string::size_type pos = 0;
650 while (pos <= s.size()) {
651 const std::string::size_type semi = s.find(';', pos);
652 const std::string row = s.substr(pos, semi == std::string::npos ? std::string::npos
653 : semi - pos);
654 std::vector<std::size_t> cells;
655 std::string::size_type cp = 0;
656 while (cp <= row.size()) {
657 const std::string::size_type comma = row.find(',', cp);
658 const std::string cell = row.substr(cp, comma == std::string::npos ? std::string::npos
659 : comma - cp);
660 if (cell.empty()) return std::vector<std::vector<std::size_t>>();
661 for (std::string::size_type i = 0; i < cell.size(); ++i)
662 if (!std::isdigit(static_cast<unsigned char>(cell[i])))
663 return std::vector<std::vector<std::size_t>>();
664 cells.push_back(static_cast<std::size_t>(std::atol(cell.c_str())));
665 if (comma == std::string::npos) break;
666 cp = comma + 1;
667 }
668 if (cells.empty()) return std::vector<std::vector<std::size_t>>();
669 if (!out.empty() && cells.size() != out[0].size())
670 return std::vector<std::vector<std::size_t>>();
671 out.push_back(cells);
672 if (semi == std::string::npos) break;
673 pos = semi + 1;
674 }
675 return out;
676}
677
678/**
679 * The model text piped on stdin, drained ONCE and kept.
680 *
681 * `-s auto` parses the model twice: once to choose an engine and once for the
682 * engine to solve. A stream can only be drained once, so without this buffer the
683 * second parse would see nothing and the chooser would be unusable on a piped
684 * model. It is deliberately not a function template -- a static local inside one
685 * would be per-instantiation, and the two parses need not share an arithmetic.
686 */
687std::string g_stdin_buf;
688bool g_stdin_loaded = false;
689
690/**
691 * The model text a host supplied INSTEAD of the process's standard input.
692 *
693 * A library has no standard input worth reading: R's is the user's terminal,
694 * and draining it would hang the session. When a host passes a document it is
695 * installed here, and `stdin_model_text` returns it without touching std::cin.
696 */
697void set_stdin_override(const std::string& text) {
698 g_stdin_buf = text;
699 g_stdin_loaded = true;
700}
701
702const std::string& stdin_model_text() {
703 if (!g_stdin_loaded) {
704 g_stdin_buf.assign(std::istreambuf_iterator<char>(std::cin),
705 std::istreambuf_iterator<char>());
706 g_stdin_loaded = true;
707 }
708 return g_stdin_buf;
709}
710
711/**
712 * Whether `-i` selected a JMT document rather than a model.json.
713 *
714 * A FILE-SCOPE FLAG AND NOT A PARAMETER, because `read_model` is called from
715 * every solver arm and threading the format through all of them would touch
716 * fifty signatures to carry one bit that main already knows. It is set once,
717 * before any arm runs, and never again.
718 */
719bool g_jsim_input = false;
720
721/**
722 * Whether `-i` selected a PNML place/transition net.
723 *
724 * A second flag rather than a format string for the same reason `g_jsim_input`
725 * is one: `read_model` is called from every solver arm, and the three input
726 * kinds it can be handed are mutually exclusive, so two booleans say what a
727 * threaded enum would and touch no signature. Set once in main.
728 */
729bool g_pnml_input = false;
730
731/**
732 * `-v/--verbosity`, hoisted to file scope for the same reason as `g_jsim_input`.
733 *
734 * The knobs carry it too, but the priority warning below is raised where the
735 * model is READ rather than inside a solver arm, and that function receives no
736 * knobs. Set once in main, before any arm runs.
737 */
738std::string g_verbosity = "standard";
739
740/**
741 * Put every piece of process state back where a fresh process would have it.
742 *
743 * THESE ARE DEFECTS AND NOT HYGIENE, and one of them is live in shipped code:
744 * `run_invocation_captured` serves one request per connection on the same
745 * process, so a request carrying `-i jsimg` used to set `g_jsim_input` and
746 * every later request on that server took the JSIM reader for a model.json.
747 * The header on `g_jsim_input` states the assumption exactly -- "It is set
748 * once, before any arm runs, and never again" -- which is true of a process
749 * that runs one invocation and exits, and false of every other caller.
750 *
751 * The stdin buffer is reset only when no host override is pending, because a
752 * host that just supplied a document means it for the call about to run.
753 */
754void reset_invocation_state(bool keep_stdin_override) {
755 g_json_output = false;
756 g_jsim_input = false;
757 g_pnml_input = false;
758 g_verbosity = "standard";
759 if (!keep_stdin_override) {
760 g_stdin_buf.clear();
761 g_stdin_loaded = false;
762 }
763 // The console keeps the level of the LAST run, so a `-v debug` call would
764 // narrate the one after it. LineConsole::reset() drops any open run; the
765 // level is set again from g_verbosity by every entry point below.
767}
768
769/**
770 * Say so when class priorities were declared and no station will read them.
771 *
772 * The twin of the block at the tail of MATLAB's `@MNetwork/refreshStruct.m` and
773 * of `Network.refreshStruct` in the JAR. It is a WARNING and not a refusal: a
774 * priority at a station whose discipline ignores one is a legitimate model --
775 * `prio_hol_open` is built on it -- and only becomes a defect when NO station
776 * reads it, at which point the metrics are not the priority ones the caller is
777 * about to read them as. Priority-awareness is a property of the declared
778 * policy and is never inferred from the data; see network_struct.h.
779 */
780template <class T>
781void warn_priorities_ignored(line::qn::Network<T>& net) {
782 if (g_verbosity == "silent") return;
783 // `raw_struct` and not `get_struct`: the priorities and the disciplines are
784 // written when the classes and stations are added, and nothing in the
785 // refresh chain touches either, so reading them here costs no refresh.
786 if (!net.raw_struct().priorities_ignored()) return;
787 std::fprintf(stderr,
788 "Warning: Priority classes are specified but no priority-aware scheduling "
789 "policy (PSPRIO, DPSPRIO, GPSPRIO, HOL, FCFSPRIO, FCFSPRPRIO, FCFSPIPRIO, "
790 "LCFSPRIO, LCFSPRPRIO, LCFSPIPRIO, SRPTPRIO) is used in the model. "
791 "Priorities will be ignored.\n");
792}
793
794/** Read the model named by `file`, or stdin when it is empty. */
795template <class T>
796line::qn::Network<T> read_model(const std::string& file) {
797 if (g_pnml_input) {
798 // The PNML reader walks a DOM and has no stdin form, so a piped document
799 // is staged to a temporary file, as the JSIM arm below does.
800 if (!file.empty()) {
802 warn_priorities_ignored(net);
803 return net;
804 }
805 const std::string tmp = line::io::jsim_stage_stdin(stdin_model_text());
807 std::remove(tmp.c_str());
808 warn_priorities_ignored(net);
809 return net;
810 }
811 if (g_jsim_input) {
812 // The JSIM reader walks a DOM and has no stdin form, so a piped JMT
813 // document is staged to a temporary file rather than refused: `cat
814 // model.jsimg | line-cli -i jsimg` is how the JAR CLI is used and the
815 // Docker image documents it.
816 if (!file.empty()) {
818 warn_priorities_ignored(net);
819 return net;
820 }
821 const std::string tmp = line::io::jsim_stage_stdin(stdin_model_text());
823 std::remove(tmp.c_str());
824 warn_priorities_ignored(net);
825 return net;
826 }
827 if (!file.empty()) {
829 warn_priorities_ignored(net);
830 return net;
831 }
832 std::istringstream in(stdin_model_text());
833 line::io::detail::json root;
834 in >> root;
836 warn_priorities_ignored(net);
837 return net;
838}
839
840/** Read the Environment model.json named by `file`, or stdin when it is empty. */
841template <class T>
842line::env::Environment<T> read_env_model(const std::string& file) {
843 if (!file.empty()) return line::io::read_environment_json<T>(file);
844 std::istringstream in(stdin_model_text());
845 line::io::detail::json root;
846 in >> root;
848}
849
850/** One row of an average table, already reduced to double. */
851struct AvgRow {
852 double q, u, r, w, a, t;
853};
854
855/**
856 * Render an average table, as text or as the JSON the hosts parse.
857 *
858 * THE ONE PLACE `-o json` IS HONOURED, reached by every solver arm through a
859 * per-(station,class) accessor. Do not give a solution type its own printer: a
860 * per-solver printer is how `-o json` came to be accepted and ignored.
861 *
862 * THE JSON FORM IS THE JAR's, key for key. `jline.cli.LineCLI -a avg -o json`
863 * emits {"avg": {"type": "AvgTable", "Station": [...], "JobClass": [...],
864 * "QLen": [...], ...}}, column-oriented, and the Python wrapper's
865 * `station_matrices_via_jar` parses exactly that shape. Emitting anything else
866 * would force a second parser into the wrapper for a table that is the same
867 * table, so the host can treat `lang='cpp'` and `lang='java'` as one transport
868 * with two binaries. The JAR's `data` key (the rendered text) is NOT reproduced:
869 * no caller reads it, and a second rendering of the same numbers is one more
870 * thing that can disagree with the first.
871 *
872 * The rows are also byte-identical across the solvers that share it, which
873 * matters more than it looks: `parity/compare_parity.py` diffs these tables
874 * column by column, and a solver whose printer drifted by a space would read as
875 * a parity failure in a harness that is supposed to be measuring the numbers.
876 */
877template <class Get>
878void emit_avg_table_named(const std::vector<std::string>& stations,
879 const std::vector<std::string>& classes, const char* arith,
880 const std::string& method, Get get, const line::reg::Json& extra,
881 const line::reg::Json& envelope) {
882 line::reg::Json rows = line::reg::Json::object();
883 for (const char* key : {"Station", "JobClass", "QLen", "Util", "RespT", "ResidT", "ArvR",
884 "Tput"})
885 rows[key] = line::reg::Json::array();
886 rows["type"] = "AvgTable";
887
888 if (!g_json_output)
889 std::printf("%-16s %-14s %12s %12s %12s %12s %12s %12s\n", "Station", "JobClass", "QLen",
890 "Util", "RespT", "ResidT", "ArvR", "Tput");
891 for (std::size_t i = 0; i < stations.size(); ++i) {
892 for (std::size_t c = 0; c < classes.size(); ++c) {
893 const AvgRow v = get(i, c);
894 if (v.q == 0.0 && v.u == 0.0 && v.r == 0.0 && v.w == 0.0 && v.a == 0.0 && v.t == 0.0)
895 continue;
896 if (!g_json_output) {
897 std::printf("%-16s %-14s %12.6g %12.6g %12.6g %12.6g %12.6g %12.6g\n",
898 stations[i].c_str(), classes[c].c_str(), v.q, v.u, v.r, v.w, v.a, v.t);
899 continue;
900 }
901 // FULL PRECISION on the JSON path, against the readable path's
902 // %12.6g. The table is for a human to read; the JSON is for a host
903 // to compare against another codebase's answer, and six digits
904 // would cap any parity check at six digits.
905 rows["Station"].push_back(stations[i]);
906 rows["JobClass"].push_back(classes[c]);
907 rows["QLen"].push_back(v.q);
908 rows["Util"].push_back(v.u);
909 rows["RespT"].push_back(v.r);
910 rows["ResidT"].push_back(v.w);
911 rows["ArvR"].push_back(v.a);
912 rows["Tput"].push_back(v.t);
913 }
914 }
915 if (g_json_output) {
916 // `extra` NESTS INSIDE the "avg" payload, for emit_analysis's reason: a
917 // solver-specific key at envelope level can collide with an analysis's
918 // own name, and a per-list cost qualifies THIS answer.
919 for (line::reg::Json::const_iterator it = extra.begin(); it != extra.end(); ++it)
920 rows[it.key()] = it.value();
921 line::reg::Json out = line::reg::Json::object();
922 out["avg"] = rows;
923 out["arith"] = arith;
924 out["method"] = method;
925 // `envelope`, unlike `extra`, sits BESIDE "avg" rather than inside it.
926 // Provenance of the solve as a whole belongs there: the iteration count
927 // and the convergence flag qualify the answer, not any one row, and a
928 // host reads them where the JAR CLI puts them.
929 for (line::reg::Json::const_iterator it = envelope.begin(); it != envelope.end(); ++it)
930 out[it.key()] = it.value();
931 emit_document(dump_document(out));
932 }
933}
934
935/**
936 * The same table, labelled from a struct.
937 *
938 * THE NAMES, NOT THE STRUCT, are what the printer needs, and one solver has no
939 * struct to give it: `-s ldes` forwards the model document to an external engine
940 * and is labelled from the names that engine reports, precisely so a model this
941 * port cannot itself parse still prints the same table. Everything else calls
942 * this overload and nothing about those rows changes.
943 */
944template <class T, class Get>
945void emit_avg_table(const line::qn::NetworkStruct<T>& sn, const std::string& method, Get get,
946 const line::reg::Json& extra = line::reg::Json::object(),
947 const line::reg::Json& envelope = line::reg::Json::object()) {
948 std::vector<std::string> stations, classes;
949 stations.reserve(sn.nstations);
950 classes.reserve(sn.nclasses);
951 for (std::size_t i = 0; i < sn.nstations; ++i) stations.push_back(sn.stations[i].name);
952 for (std::size_t c = 0; c < sn.nclasses; ++c) classes.push_back(sn.classes[c].name);
953 emit_avg_table_named(stations, classes, line::num_traits<T>::name(), method, get, extra,
954 envelope);
955}
956
957/** NaN as this arithmetic spells it, the reference's "not computed" marker. */
958template <class T>
959T cache_nan() {
960 return line::num_traits<T>::from_double(std::numeric_limits<double>::quiet_NaN());
961}
962
963/** `v[r]` when the vector reaches r, NaN otherwise -- the reference's nanGetAt. */
964template <class T>
965double cache_at(const std::vector<T>& v, std::size_t r) {
966 if (r >= v.size()) return std::numeric_limits<double>::quiet_NaN();
968}
969
970/**
971 * The readable cache rows of a solve that reports beside the AvgTable.
972 *
973 * A Cache answers in (node, read class) and in (node, read class, list), which
974 * the AvgTable cannot carry, so a caller that only got the AvgTable was told
975 * nothing about the cache it asked about. `-a cache` has its own richer table
976 * built from the model's Source rates; this one reports the surface alone and
977 * is what the `-s env` arm uses, where there is no single model whose Source
978 * rate describes the blend.
979 *
980 * ABSENT PRINTS NaN, NEVER 0: an empty field is a coupling that did not measure
981 * the quantity, and a zero would read as a cache that never hits.
982 */
983template <class T>
984void print_cache_rows(const line::qn::NetworkStruct<T>& sn,
985 const line::solvers::CacheMetrics<T>& cache) {
986 if (cache.empty()) return;
987 const double dnan = std::numeric_limits<double>::quiet_NaN();
988 std::printf("\n%-12s %-12s %5s %12s %12s %12s\n", "Cache", "JobClass", "List", "HitProb",
989 "DelayedHitP", "MissProb");
990 for (std::size_t c = 0; c < cache.caches.size(); ++c) {
991 const line::solvers::CacheNodeMetrics<T>& m = cache.caches[c];
992 const typename std::map<std::size_t, line::qn::CacheParam<T> >::const_iterator it =
993 sn.nodeparam.find(m.node);
994 if (it == sn.nodeparam.end()) continue;
995 const std::vector<std::size_t>& hitclass = it->second.hitclass;
996 for (std::size_t cl = 0; cl < sn.nclasses; ++cl) {
997 // A READ CLASS IS ONE WITH A HIT CLASS DEFINED, the same rule the
998 // `-a cache` table applies; every other class has no ratio of its
999 // own and gets no row rather than a row of zeros.
1000 if (cl >= hitclass.size() || hitclass[cl] == 0) continue;
1001 const double ph = cache_at(m.hitprob, cl), pm = cache_at(m.missprob, cl),
1002 pd = cache_at(m.delayedprob, cl);
1003 std::printf("%-12s %-12s %5d %12.6g %12.6g %12.6g\n", m.name.c_str(),
1004 sn.classes[cl].name.c_str(), 0, ph, pd, pm);
1005 for (std::size_t l = 0; l < m.hitproblist.cols() && cl < m.hitproblist.rows(); ++l)
1006 std::printf("%-12s %-12s %5d %12.6g %12.6g %12.6g\n", m.name.c_str(),
1007 sn.classes[cl].name.c_str(), static_cast<int>(l + 1),
1008 line::num_traits<T>::to_double(m.hitproblist(cl, l)), dnan, dnan);
1009 }
1010 }
1011}
1012
1013/**
1014 * Print one analysis that is NOT the average table, as the JSON a host parses.
1015 *
1016 * ONE ENVELOPE FOR EVERY ANALYSIS: the payload sits under a key named after the
1017 * `-a` it answers, and the arithmetic and the resolved method sit beside it,
1018 * exactly as `emit_avg_table` places them beside "avg". A host therefore reads
1019 * the provenance the same way whatever it asked for, and a caller that asked for
1020 * `-a cdf` and received a "states" key knows the answer is not its own instead of
1021 * misreading the numbers as its own.
1022 *
1023 * `method` MAY BE EMPTY, in which case the key is omitted rather than filled
1024 * with the requested name: `-a reward` returns rewards and no solved chain, so
1025 * there is no resolved method to report, and echoing back "default" would claim
1026 * a resolution that never happened.
1027 *
1028 * EVERY INDEX IN A PAYLOAD IS 0-BASED, against the readable tables' 1-based
1029 * columns, and each payload carries `indexBase` so a host cannot get it wrong
1030 * silently. The two conventions are deliberate: the table is read by a human
1031 * diffing it against MATLAB, whose indices start at 1, while the JSON is
1032 * consumed by code that will index a numpy array or a std::vector with it.
1033 */
1034template <class T>
1035void emit_analysis(const char* key, const line::reg::Json& payload, const std::string& method,
1036 const line::reg::Json& extra = line::reg::Json::object()) {
1037 line::reg::Json body = payload;
1038 // `extra` GOES INSIDE THE PAYLOAD, not beside it. At envelope level a
1039 // solver-specific key can collide with the analysis's own name -- the CTMC
1040 // state count is "states" and so is the `-a states` payload, and the merge
1041 // silently replaced the whole answer with the integer 3. Nesting it makes
1042 // that class of collision unrepresentable, and it is where the value belongs
1043 // anyway: a cutoff qualifies THIS answer.
1044 for (line::reg::Json::const_iterator it = extra.begin(); it != extra.end(); ++it)
1045 body[it.key()] = it.value();
1046 line::reg::Json out = line::reg::Json::object();
1047 out[key] = body;
1048 out["arith"] = line::num_traits<T>::name();
1049 if (!method.empty()) out["method"] = method;
1050 emit_document(dump_document(out));
1051}
1052
1053/** A Matrix as a row-major array of arrays, each entry reduced to double. */
1054template <class T>
1055line::reg::Json matrix_json(const line::Matrix<T>& M) {
1056 line::reg::Json rows = line::reg::Json::array();
1057 for (std::size_t i = 0; i < M.rows(); ++i) {
1058 line::reg::Json row = line::reg::Json::array();
1059 for (std::size_t j = 0; j < M.cols(); ++j)
1060 row.push_back(line::num_traits<T>::to_double(M(i, j)));
1061 rows.push_back(row);
1062 }
1063 return rows;
1064}
1065
1066/** A vector of field elements as a JSON array of doubles. */
1067template <class T>
1068line::reg::Json vector_json(const std::vector<T>& v) {
1069 line::reg::Json a = line::reg::Json::array();
1070 for (std::size_t i = 0; i < v.size(); ++i) a.push_back(line::num_traits<T>::to_double(v[i]));
1071 return a;
1072}
1073
1074/** A vector of sizes as a JSON array, unchanged: a width is not a measurement. */
1075line::reg::Json index_json(const std::vector<std::size_t>& v) {
1076 line::reg::Json a = line::reg::Json::array();
1077 for (std::size_t i = 0; i < v.size(); ++i) a.push_back(v[i]);
1078 return a;
1079}
1080
1081/**
1082 * The per-Cache result block, as `-a avg` carries it inside the "avg" payload.
1083 *
1084 * PER-CACHE RESULTS RIDE WITH THE AVG TABLE, because a cache's hit, miss and
1085 * delayed-hit fractions are a SOLVER RESULT and a host that solves through this
1086 * CLI has no other way to get them back onto its own Cache node. Emitted per
1087 * node, and each vector is OMITTED when the solver computed none: absent must
1088 * CLEAR the host's copy, and a zero-filled vector would instead assert that
1089 * nothing hits.
1090 *
1091 * FACTORED OUT of `print_avg_table` because the SSA and Fluid arms build the
1092 * table themselves rather than through it, and so carried no block at all:
1093 * `CPPLINE.restoreCacheResults` then cleared MATLAB's Cache node, refreshed the
1094 * visits, and reported link()'s offered 1/2-1/2 for a split both engines had
1095 * measured. On cache_replc_rr that is hit 1.0 against 1.1246 (fluid) and
1096 * 1.1460 (ssa). A second copy of this serialization here would be free to drop
1097 * a field again, so there is one.
1098 */
1099template <class T>
1100line::reg::Json cache_extra_json(const line::solvers::CacheMetrics<T>& cache) {
1101 line::reg::Json caches = line::reg::Json::array();
1102 for (std::size_t c = 0; c < cache.caches.size(); ++c) {
1103 const line::solvers::CacheNodeMetrics<T>& m = cache.caches[c];
1104 line::reg::Json e = line::reg::Json::object();
1105 // NAME FIRST, because the index is not portable. `node` is an index
1106 // into THIS process's node order, which is not the model.json
1107 // declaration order: on retrieval_simple the JSON declares Source,
1108 // Cache, Queue, Sink and this struct holds Source, Queue, Sink,
1109 // Cache, so the Cache is 2 to the host and 4 here. A host matching
1110 // on the index wrote onto its Sink, found no Cache and silently kept
1111 // the PREVIOUS solver's numbers. `node` stays for provenance.
1112 e["name"] = m.name;
1113 e["node"] = m.node;
1114 if (!m.hitprob.empty()) e["HitProb"] = vector_json(m.hitprob);
1115 if (!m.missprob.empty()) e["MissProb"] = vector_json(m.missprob);
1116 if (!m.delayedprob.empty()) e["DelayedHitProb"] = vector_json(m.delayedprob);
1117 if (!m.latency.empty()) e["ResidT"] = vector_json(m.latency);
1118 if (!m.listcost.empty()) e["ListCost"] = vector_json(m.listcost);
1119 // The per-list breakdown, (K x h). Carried because it is an ANSWER a
1120 // host cannot rebuild from HitProb: only the row SUM is HitProb, and
1121 // which list served the hit is what a replacement policy is judged on.
1122 if (m.hitproblist.rows() > 0) e["HitProbList"] = matrix_json(m.hitproblist);
1123 if (!m.delayedhitqlen.empty()) {
1124 e["DelayedHitQLen"] = vector_json(m.delayedhitqlen);
1125 e["DelayedHitQLenFull"] = vector_json(m.delayedhitqlenfull);
1126 }
1127 caches.push_back(e);
1128 }
1129 return caches;
1130}
1131
1132/**
1133 * The fork-join section block, `getAvgFJTable` keyed as the JAR CLI keys `-a fj` (Fork, Join, JobClass,
1134 * FJQLen, FJRespT, FJTput), one entry per (pair, class) with a value > 0. JSON only: the readable avg
1135 * table is what the parity harness diffs, so it is left as it was. Null when there is no row.
1136 */
1137inline line::reg::Json fj_extra_json(const std::vector<std::string>& forks, const std::vector<std::string>& joins,
1138 const std::vector<std::string>& classes, const line::Matrix<double>& Q,
1139 const line::Matrix<double>& R, const line::Matrix<double>& X) {
1140 line::reg::Json t = line::reg::Json::object();
1141 for (const char* key : {"Fork", "Join", "JobClass", "FJQLen", "FJRespT", "FJTput"})
1142 t[key] = line::reg::Json::array();
1143 t["type"] = "AvgFJTable";
1144 bool any = false;
1145 for (std::size_t p = 0; p < forks.size() && p < joins.size(); ++p)
1146 for (std::size_t c = 0; c < classes.size(); ++c) {
1147 const double q = (p < Q.rows() && c < Q.cols()) ? Q(p, c) : 0.0;
1148 const double r = (p < R.rows() && c < R.cols()) ? R(p, c) : 0.0;
1149 const double x = (p < X.rows() && c < X.cols()) ? X(p, c) : 0.0;
1150 if (!(q > 0.0 || r > 0.0 || x > 0.0)) continue;
1151 t["Fork"].push_back(forks[p]);
1152 t["Join"].push_back(joins[p]);
1153 t["JobClass"].push_back(classes[c]);
1154 t["FJQLen"].push_back(q);
1155 t["FJRespT"].push_back(r);
1156 t["FJTput"].push_back(x);
1157 any = true;
1158 }
1159 return any ? t : line::reg::Json();
1160}
1161
1162/** The same block from a struct-indexed result (MVA, NC, Fluid, JMT). */
1163template <class T, class U>
1165 if (fj.empty()) return line::reg::Json();
1167 std::vector<std::string> forks, joins, classes;
1168 for (std::size_t p = 0; p < d.npairs(); ++p) {
1169 forks.push_back(sn.nodes[d.forks[p] - 1].name);
1170 joins.push_back(sn.nodes[d.joins[p] - 1].name);
1171 }
1172 for (std::size_t c = 0; c < sn.nclasses; ++c) classes.push_back(sn.classes[c].name);
1173 return fj_extra_json(forks, joins, classes, d.QLen, d.RespT, d.Tput);
1174}
1175
1176/**
1177 * Print an AvgResult as the parity table.
1178 *
1179 * Shared by every solver that returns `mva::AvgResult` -- MVA, NC, MAM and BA
1180 * -- so the rows stay byte-identical across them.
1181 */
1182template <class T>
1183void print_avg_table(const line::qn::NetworkStruct<T>& sn, const line::mva::AvgResult<T>& r,
1184 const line::reg::Json& extra_in = line::reg::Json::object()) {
1185 // THE JSON FORM IS THE JAR's, key for key. `jline.cli.LineCLI -a avg -o json`
1186 // emits {"avg": {"type": "AvgTable", "Station": [...], "JobClass": [...],
1187 // "QLen": [...], ...}}, column-oriented, and the Python wrapper's
1188 // `station_matrices_via_jar` parses exactly that shape. Emitting anything
1189 // else here would force a second parser into the wrapper for a table that is
1190 // the same table, so the host can treat `lang='cpp'` and `lang='java'` as one
1191 // transport with two binaries. The JAR's `data` key (the rendered text) is
1192 // NOT reproduced: no caller reads it, and a second rendering of the same
1193 // numbers is one more thing that can disagree with the first.
1194 // A CARRIED WARNING IS ONLY A WARNING IF SOMEONE SEES IT. `AvgResult`
1195 // carries the reference's text verbatim for the cases where the answer is
1196 // usable but not one the reference stands behind (the SJN starvation cap,
1197 // immediate feedback approximated as re-queueing), and until now no CLI
1198 // path printed it -- so the table looked authoritative exactly where the
1199 // reference declines. On STDERR, not stdout: stdout is the table a parity
1200 // harness diffs and the JSON a wrapper parses, and a warning line in either
1201 // would be read as data. Python's `lang='cpp'` bridge re-raises anything on
1202 // stderr as a Python warning, so it reaches that caller too.
1203 if (!r.warning.empty())
1204 std::fprintf(stderr, "Warning: %s\n", r.warning.c_str());
1205
1206 // Mean per-list cache storage cost, the ListCost column of getAvgCacheTable.
1207 // Present only on a cache model carrying item sizes, and omitted entirely
1208 // otherwise rather than emitted empty, so a host can test for the key.
1209 line::reg::Json extra = line::reg::Json::object();
1210 if (!r.listcost.empty()) {
1211 line::reg::Json lc = line::reg::Json::array();
1212 for (std::size_t j = 0; j < r.listcost.size(); ++j)
1213 lc.push_back(line::num_traits<T>::to_double(r.listcost[j]));
1214 extra["ListCost"] = lc;
1215 }
1216
1217 // WHAT THE CALLER ADDS, merged rather than replaced. The JMT arm carries the
1218 // finite-capacity-region rows this way: they are metric rows past the last
1219 // station, and the station table drops them, so without a channel of their
1220 // own a host reading `-a avg` cannot see a region at all (MATLAB's
1221 // `getAvgNodeTable` then filtered the FCR node out for having no numbers).
1222 if (extra_in.is_object())
1223 for (line::reg::Json::const_iterator it = extra_in.begin(); it != extra_in.end(); ++it)
1224 extra[it.key()] = it.value();
1225
1226 // See `cache_extra_json`: the split is a solver result and the host has no
1227 // other channel back to its own Cache node.
1228 if (!r.cache.empty()) extra["Cache"] = cache_extra_json<T>(r.cache);
1229 // getAvgFJTable's rows, for the reason the Cache block rides here: no other channel back to the host.
1230 {
1231 const line::reg::Json fjb = fj_extra_json(sn, r.fj);
1232 if (!fjb.is_null()) extra["FJ"] = fjb;
1233 }
1234
1235 // Provenance of the solve, beside "avg" and keyed as the JAR CLI keys it, so
1236 // one host-side reduction reads both backends. `converged` is OMITTED when
1237 // the handler reports none: absent is not false, and there the count is the
1238 // signal a caller may fall back on.
1239 line::reg::Json envelope = line::reg::Json::object();
1240 envelope["iter"] = r.iter;
1241 if (r.converged.has_value()) envelope["converged"] = r.converged.value();
1242 // `@SolverNC/getProbNormConstAggr`, keyed as the reference names the field it
1243 // stores it in. OMITTED for every solver that computes no constant: log G = 0
1244 // is the constant of an empty network, so a zero here would be a claim.
1245 if (r.lognormconst.has_value()) envelope["logNormConstAggr"] = r.lognormconst.value();
1246
1247 emit_avg_table<T>(sn, r.actualmethod, [&](std::size_t i, std::size_t c) {
1248 AvgRow row;
1249 row.q = line::num_traits<T>::to_double(r.QN(i, c));
1250 row.u = line::num_traits<T>::to_double(r.UN(i, c));
1251 row.r = line::num_traits<T>::to_double(r.RN(i, c));
1252 row.w = line::num_traits<T>::to_double(r.WN(i, c));
1253 row.a = line::num_traits<T>::to_double(r.AN(i, c));
1254 row.t = line::num_traits<T>::to_double(r.TN(i, c));
1255 return row;
1256 }, extra, envelope);
1257}
1258
1259/**
1260 * Solve a Network model.json with SolverMVA and print its AvgTable.
1261 *
1262 * The columns and their order -- Station, JobClass, then QLen, Util, RespT,
1263 * ResidT, ArvR, Tput -- are the ones `parity/compare_parity.py` parses, so the
1264 * printed table is directly diffable against the MATLAB and Python rows. A
1265 * (station, class) pair with no presence at all (every metric zero) is dropped,
1266 * as `getAvgTable` drops its unvisited rows.
1267 */
1268template <class T>
1269int solve_model_mva(const std::string& file, const Knobs& k) {
1270 line::qn::Network<T> net = read_model<T>(file);
1272 if (!k.method.empty() && k.method != "default") opt.method = k.method;
1273 if (k.tol >= 0.0) opt.tol = k.tol;
1274 if (k.iter_tol >= 0.0) opt.iter_tol = k.iter_tol;
1275 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
1276 if (!k.multiserver.empty()) opt.multiserver = k.multiserver;
1277 if (!k.fork_join.empty()) opt.fork_join = k.fork_join;
1278 line::Matrix<T> init;
1279 // The map_env funnel, the same one `run_avg_engine` applies to the node,
1280 // sys, chain and nodechain views: `-a avg` and `-a node` must accept the
1281 // same models for the same command line. Compile-time because the driver is
1282 // double-only -- see the note on the nc arm of `run_avg_engine`.
1284 if constexpr (std::is_same_v<T, double>) {
1286 net.get_struct(), "SolverMVA",
1288 net.get_struct()),
1289 map_env_config(k),
1290 [&opt, &init](const line::qn::NetworkStruct<double>& m) {
1291 return line::mva::solver_mva_run_analyzer(m, opt, init);
1292 },
1294 } else {
1295 r = line::mva::solver_mva_run_analyzer(net.get_struct(), opt, init);
1296 }
1297 const line::qn::NetworkStruct<T>& sn = net.get_struct();
1298
1299 std::printf("SolverMVA arith=%s method=%s type=%s\n", line::num_traits<T>::name(),
1300 r.actualmethod.c_str(),
1301 line::util::method_type("MVA", r.actualmethod).c_str());
1302 print_avg_table<T>(sn, r);
1303 return 0;
1304}
1305
1306
1307/**
1308 * `-s jmt -a tran`: `getTranAvg`, the transient ensemble of `default` over a finite timespan.
1309 *
1310 * A SINGLE SAMPLE PATH IS NOT E[N](t). There is no time ergodicity at a fixed
1311 * t, so the mean is estimated over independent replications -- `--jmt-replications`
1312 * of them, which is what `options.config.replications` names in the reference --
1313 * replication k seeded `seed + k - 1` and resampled onto the union of their event
1314 * grids. An explicit `--method jsim` is ONE run. `jmt_transient_replications`
1315 * states the horizon and method rules itself, so they are not restated here.
1316 *
1317 * The payload is the SAME `TranAvgTable` the CTMC, fluid, MAM and LDES
1318 * transients emit, key for key, so one host reader serves every solver that
1319 * answers `-a tran`.
1320 */
1321int solve_model_jmt_tran(const line::qn::NetworkStruct<double>& sn,
1322 const line::jmt::JmtOptions& o, const Knobs& k) {
1324 const std::size_t reps = line::jmt::jmt_transient_replication_count(o, "getTranAvg");
1325 const std::size_t M = sn.nstations, K = sn.nclasses, nt = r.t.size();
1326
1327 if (g_json_output) {
1328 line::reg::Json p = line::reg::Json::object();
1329 p["type"] = "TranAvgTable";
1330 p["indexBase"] = 0;
1331 p["t0"] = k.t0 >= 0.0 ? k.t0 : 0.0;
1332 p["t1"] = o.max_simulated_time;
1333 // HOW MANY PATHS THE MEAN IS OVER is part of the answer on a simulated
1334 // transient: a replication that produced no log contributes nothing, so
1335 // the count asked for and the count averaged are not the same number.
1336 p["replications"] = r.valid;
1337 p["replicationsRequested"] = reps;
1338 line::reg::Json curves = line::reg::Json::array();
1339 for (std::size_t i = 0; i < M && i < r.QNt.size(); ++i)
1340 for (std::size_t c = 0; c < K && c < r.QNt[i].size(); ++c) {
1341 // A disabled pair is OMITTED, not sent as zeros, as on the CTMC
1342 // arm: the host turns an absent curve into the disabled
1343 // handle's NaN, where zeros would read as a genuinely idle
1344 // station.
1345 if (sn.disabled[i][c]) continue;
1346 line::reg::Json e = line::reg::Json::object();
1347 e["Station"] = sn.stations[i].name;
1348 e["JobClass"] = sn.classes[c].name;
1349 e["station"] = i;
1350 e["jobclass"] = c;
1351 line::reg::Json tt = line::reg::Json::array(), q = line::reg::Json::array(),
1352 u = line::reg::Json::array(), x = line::reg::Json::array();
1353 for (std::size_t j = 0; j < nt; ++j) {
1354 tt.push_back(r.t[j]);
1355 q.push_back(r.QNt[i][c][j]);
1356 u.push_back(r.UNt[i][c][j]);
1357 x.push_back(r.TNt[i][c][j]);
1358 }
1359 e["t"] = tt;
1360 e["QLen"] = q;
1361 e["Util"] = u;
1362 e["Tput"] = x;
1363 curves.push_back(e);
1364 }
1365 p["curves"] = curves;
1366 // ALWAYS jsim: every replication is a simulated path, and JMVA computes
1367 // means from a product form and logs no trajectory at all, so naming the
1368 // requested method would name an engine that never ran.
1369 emit_analysis<double>("tran", p, std::string("jsim"));
1370 return 0;
1371 }
1372 std::printf("SolverJMT arith=double method=jsim\n");
1373 std::printf("TranAvg times=%zu replications=%zu/%zu\n", nt, r.valid, reps);
1374 std::printf("%-16s %-14s %12s %12s %12s %12s\n", "Station", "JobClass", "Time", "QLen", "Util",
1375 "Tput");
1376 for (std::size_t i = 0; i < M && i < r.QNt.size(); ++i)
1377 for (std::size_t c = 0; c < K && c < r.QNt[i].size(); ++c) {
1378 if (sn.disabled[i][c]) continue;
1379 for (std::size_t j = 0; j < nt; ++j)
1380 std::printf("%-16s %-14s %12.6g %12.6g %12.6g %12.6g\n",
1381 sn.stations[i].name.c_str(), sn.classes[c].name.c_str(), r.t[j],
1382 r.QNt[i][c][j], r.UNt[i][c][j], r.TNt[i][c][j]);
1383 }
1384 return 0;
1385}
1386
1387/**
1388 * `-s jmt -a tranprob`: `getTranProbAggr`, pi(t) over ONE station's aggregate
1389 * state, estimated over independent replications.
1390 *
1391 * THE AGGREGATE LAW ONLY, and refused rather than aliased for the detailed one:
1392 * a JMT log records per-class job counts at a node and nothing about the buffer
1393 * order or the service phase, so the encoding `getTranProb` is a law over is
1394 * not observed at all -- the same rule the `-a prob` arm states.
1395 *
1396 * `--node` names the station, defaulting to the first one: the estimate is
1397 * over one station's own state, not over the network's, so there is no system
1398 * view to fall back to here.
1399 */
1400int solve_model_jmt_tranprob(const line::qn::NetworkStruct<double>& sn,
1401 const line::jmt::JmtOptions& o, const Knobs& k) {
1402 std::size_t station = 1;
1403 if (k.node) {
1404 // OUT OF RANGE IS REFUSED, not silently folded onto station 1: falling
1405 // back to the default would answer a question about a different node
1406 // than the one named, which is the silent-wrong-answer failure the
1407 // whole Knobs struct exists to prevent.
1408 if (k.node > sn.nodes.size() || sn.nodes[k.node - 1].station == 0)
1409 throw line::InputError(
1410 "--node " + std::to_string(k.node) +
1411 " is not a station, so it holds no per-class job count to take a law over");
1412 station = sn.nodes[k.node - 1].station;
1413 }
1414 const std::size_t reps = line::jmt::jmt_transient_replication_count(o, "getTranProbAggr");
1415 std::vector<std::vector<double> > states;
1416 const std::pair<std::vector<double>, std::vector<std::vector<double> > > r =
1417 line::jmt::jmt_get_tran_prob_aggr(sn, station, o, states);
1418 const std::vector<double>& t = r.first;
1419 const std::vector<std::vector<double> >& pit = r.second;
1420
1421 if (g_json_output) {
1422 line::reg::Json p = line::reg::Json::object();
1423 p["type"] = "TranProb";
1424 p["indexBase"] = 0;
1425 p["scope"] = sn.stations[station - 1].name;
1426 p["node"] = sn.station_to_node[station - 1] - 1;
1427 p["station"] = station - 1;
1428 p["replications"] = reps;
1429 line::reg::Json span = line::reg::Json::array();
1430 // THE HORIZON IS PART OF THE ANSWER, as on the CTMC arm: pi(t) over an
1431 // unstated span is not a quantity, and here it is also what makes the
1432 // replications' grids commensurable in the first place.
1433 span.push_back(k.t0 >= 0.0 ? k.t0 : 0.0);
1434 span.push_back(o.max_simulated_time);
1435 p["tspan"] = span;
1436 p["t"] = vector_json(t);
1437 // ONLY THE AGGREGATE LABELS, and the key says so: a host reading
1438 // `labels` here would be reading the detailed law of another solver.
1439 line::reg::Json labels = line::reg::Json::array();
1440 for (std::size_t s = 0; s < states.size(); ++s) labels.push_back(vector_json(states[s]));
1441 p["labelsAggr"] = labels;
1442 line::reg::Json rows = line::reg::Json::array();
1443 for (std::size_t g = 0; g < pit.size(); ++g) rows.push_back(vector_json(pit[g]));
1444 p["pitAggr"] = rows;
1445 emit_analysis<double>("tranprob", p, std::string("jsim"));
1446 return 0;
1447 }
1448 std::printf("SolverJMT arith=double method=jsim\n");
1449 std::printf("TranProb times=%zu tspan=%g:%g scope=%s replications=%zu\n", t.size(),
1450 k.t0 >= 0.0 ? k.t0 : 0.0, o.max_simulated_time,
1451 sn.stations[station - 1].name.c_str(), reps);
1452 // The labels come FIRST and the occupancy after, as on the CTMC arm: pi(t)
1453 // is a row per time over columns that mean nothing until the state they
1454 // index is named.
1455 std::printf("%8s %s\n", "State", "Aggregate");
1456 for (std::size_t s = 0; s < states.size(); ++s) {
1457 std::printf("%8zu ", s + 1);
1458 for (std::size_t c = 0; c < states[s].size(); ++c) std::printf(" %g", states[s][c]);
1459 std::printf("\n");
1460 }
1461 std::printf("%14s", "Time");
1462 for (std::size_t s = 0; s < states.size(); ++s) std::printf(" %12zu", s + 1);
1463 std::printf("\n");
1464 for (std::size_t g = 0; g < t.size(); ++g) {
1465 std::printf("%14.8g", t[g]);
1466 for (std::size_t s = 0; s < states.size(); ++s)
1467 std::printf(" %12.6g", s < pit[g].size() ? pit[g][s] : 0.0);
1468 std::printf("\n");
1469 }
1470 return 0;
1471}
1472
1473/**
1474 * `-s jmt -a sample`: `sampleSysAggr`, one simulated trajectory; with `--node`,
1475 * that node's own block (`sampleAggr`) instead.
1476 *
1477 * `--events` NAMES THE TRUNCATION, and it is a truncation rather than a
1478 * stopping rule: JMT's `maxEvents` is global and cannot be asked for a count at
1479 * one node, so what comes back is a prefix of the run the engine produced --
1480 * exactly the caveat `jmt_sample_aggr` carries. `--samples` stands in when
1481 * `--events` is absent, as on the CTMC arm, and neither bounds the engine.
1482 */
1483int solve_model_jmt_sample(const line::qn::NetworkStruct<double>& sn,
1484 const line::jmt::JmtOptions& o, const Knobs& k) {
1485 const std::size_t nevents = k.events ? k.events : 0;
1486 const std::size_t K = sn.nclasses;
1487
1488 if (k.node) {
1489 if (k.node > sn.nodes.size() || sn.nodes[k.node - 1].station == 0)
1490 throw line::InputError(
1491 "--node " + std::to_string(k.node) +
1492 " is not a station, so no per-class job count is logged for it");
1494 line::jmt::jmt_sample_aggr(sn, k.node, nevents, o);
1495 if (g_json_output) {
1496 line::reg::Json p = line::reg::Json::object();
1497 p["type"] = "SamplePath";
1498 p["indexBase"] = 0;
1499 p["scope"] = sn.nodes[k.node - 1].name;
1500 p["node"] = k.node - 1;
1501 p["events"] = nevents;
1502 p["seed"] = o.seed;
1503 p["drawn"] = tr.t.size();
1504 p["t"] = vector_json(tr.t);
1505 line::reg::Json st = line::reg::Json::array();
1506 for (std::size_t j = 0; j < tr.qlen.size(); ++j) st.push_back(vector_json(tr.qlen[j]));
1507 p["state"] = st;
1508 line::reg::Json cols = line::reg::Json::array();
1509 for (std::size_t c = 0; c < K; ++c) cols.push_back(sn.classes[c].name);
1510 p["columns"] = cols;
1511 emit_analysis<double>("sample", p, std::string("jsim"));
1512 return 0;
1513 }
1514 std::printf("SolverJMT arith=double method=jsim\n");
1515 std::printf("%14s %s\n", "Time", ("NodeState (" + sn.nodes[k.node - 1].name +
1516 ", per class)").c_str());
1517 for (std::size_t j = 0; j < tr.t.size(); ++j) {
1518 std::printf("%14.8g ", tr.t[j]);
1519 for (std::size_t c = 0; c < K && c < tr.qlen[j].size(); ++c)
1520 std::printf(" %g", tr.qlen[j][c]);
1521 std::printf("\n");
1522 }
1523 return 0;
1524 }
1525
1527 const std::size_t M = sn.nstations, n = tr.t.size();
1528 if (g_json_output) {
1529 line::reg::Json p = line::reg::Json::object();
1530 p["type"] = "SamplePath";
1531 p["indexBase"] = 0;
1532 p["scope"] = "(system)";
1533 p["events"] = nevents;
1534 p["seed"] = o.seed;
1535 p["drawn"] = n;
1536 p["t"] = vector_json(tr.t);
1537 line::reg::Json st = line::reg::Json::array();
1538 for (std::size_t j = 0; j < n; ++j) {
1539 line::reg::Json row = line::reg::Json::array();
1540 for (std::size_t i = 0; i < M; ++i)
1541 for (std::size_t c = 0; c < K; ++c)
1542 row.push_back(i < tr.state.size() && j < tr.state[i].size() &&
1543 c < tr.state[i][j].size()
1544 ? tr.state[i][j][c]
1545 : 0.0);
1546 st.push_back(row);
1547 }
1548 p["state"] = st;
1549 line::reg::Json cols = line::reg::Json::array();
1550 for (std::size_t i = 0; i < M; ++i)
1551 for (std::size_t c = 0; c < K; ++c)
1552 cols.push_back(sn.stations[i].name + "," + sn.classes[c].name);
1553 p["columns"] = cols;
1554 emit_analysis<double>("sample", p, std::string("jsim"));
1555 return 0;
1556 }
1557 std::printf("SolverJMT arith=double method=jsim\n");
1558 std::printf("%14s %s\n", "Time", "SysState (station-major, per class)");
1559 for (std::size_t j = 0; j < n; ++j) {
1560 std::printf("%14.8g ", tr.t[j]);
1561 for (std::size_t i = 0; i < M; ++i)
1562 for (std::size_t c = 0; c < K; ++c)
1563 std::printf(" %g", i < tr.state.size() && j < tr.state[i].size() &&
1564 c < tr.state[i][j].size()
1565 ? tr.state[i][j][c]
1566 : 0.0);
1567 std::printf("\n");
1568 }
1569 return 0;
1570}
1571
1572/**
1573 * Solve a Network model.json with SolverJMT: write the JMT document, run the
1574 * external engine, print the same table every other solver prints.
1575 *
1576 * DOUBLE ONLY, and refused rather than relabelled under another arithmetic:
1577 * JMT simulates in double and reports in double, so an answer tagged
1578 * `real:128` would name a precision that never touched the computation. The
1579 * same rule the LDES arm applies, for the same reason.
1580 */
1581int solve_model_jmt(const std::string& file, const Knobs& k, const std::string& analysis) {
1582 line::qn::Network<double> net = read_model<double>(file);
1584
1586 if (!k.method.empty() && k.method != "default") o.method = k.method;
1587 if (k.samples > 0) o.samples = static_cast<double>(k.samples);
1588 if (k.seed != 0) o.seed = static_cast<long>(k.seed);
1589 o.keep = k.keep;
1590 if (k.t1 >= 0.0) o.max_simulated_time = k.t1;
1591 // `--jmt-replications` IS THE ENSEMBLE SIZE of the two arms that average over independent
1592 // runs, `options.config.replications`; the gate above accepts it for `-a tran` and `-a tranprob`.
1593 if (k.jmt_replications > 0) o.replications = k.jmt_replications;
1594 // AN EXPLICIT `jsim` IS ONE RUN, not the ensemble, so a count given with it would be dropped.
1595 if (k.jmt_replications > 0 && o.method == "jsim")
1597 "--jmt-replications sizes the transient ensemble of --method default; --method jsim "
1598 "is a single JSIM run, so the count would be ignored rather than honoured");
1599 o.verbose = k.verbose;
1600
1601 if (analysis == "tran") return solve_model_jmt_tran(sn, o, k);
1602 if (analysis == "tranprob") return solve_model_jmt_tranprob(sn, o, k);
1603 if (analysis == "sample") return solve_model_jmt_sample(sn, o, k);
1604
1605 // `-a prob`: `getProbAggr` per station and `getProbSysAggr`, weighed off ONE
1606 // instrumented run. The DETAILED pair -- `getProb` and `getProbSys` -- has
1607 // no counterpart here and is OMITTED rather than aliased to the aggregate:
1608 // a JMT log records per-class job counts at a node and nothing about the
1609 // buffer order or the service phase, so the encoding those two are
1610 // probabilities of is not observed at all.
1611 if (analysis == "prob") {
1612 std::size_t target = 0;
1613 if (k.node) {
1614 if (k.node <= sn.nodes.size()) target = sn.nodes[k.node - 1].station;
1615 if (target == 0)
1616 throw line::InputError(
1617 "--node " + std::to_string(k.node) +
1618 " is not a station, so it holds no per-class job count to ask about");
1619 }
1621 sn, o, target, std::vector<double>(k.state.begin(), k.state.end()));
1622 if (g_json_output) {
1623 line::reg::Json p = line::reg::Json::object();
1624 p["type"] = "ProbAggr";
1625 p["indexBase"] = 0;
1626 p["ProbSysAggr"] = r.sys;
1627 // WHETHER THE STATE OCCURRED AT ALL, beside the number. On an exact
1628 // solver a zero probability is a property of the model; on a
1629 // simulation it is far more often a property of the run length, and
1630 // a caller cannot tell the two apart from the zero alone.
1631 p["SysStateSeen"] = r.sys_seen;
1632 line::reg::Json st = line::reg::Json::array(), pa = line::reg::Json::array(),
1633 sv = line::reg::Json::array();
1634 for (std::size_t i = 0; i < sn.nstations; ++i) {
1635 st.push_back(sn.stations[i].name);
1636 pa.push_back(r.station[i]);
1637 sv.push_back(static_cast<bool>(r.station_seen[i]));
1638 }
1639 p["Station"] = st;
1640 p["ProbAggr"] = pa;
1641 p["StateSeen"] = sv;
1642 // ALWAYS jsim, whatever `--method` asked for: this answer is read
1643 // off a simulated trajectory, and JMVA computes means from a
1644 // product form and logs nothing, so labelling it with the
1645 // requested method would name an engine that never ran.
1646 emit_analysis<double>("prob", p, std::string("jsim"));
1647 return 0;
1648 }
1649 std::printf("SolverJMT arith=double method=jsim\n");
1650 std::printf("ProbSysAggr %.10g%s\n", r.sys, r.sys_seen ? "" : " (state never observed)");
1651 std::printf("%-16s %14s\n", "Station", "ProbAggr");
1652 for (std::size_t i = 0; i < sn.nstations; ++i)
1653 std::printf("%-16s %14.10g%s\n", sn.stations[i].name.c_str(), r.station[i],
1654 r.station_seen[i] ? "" : " (state never observed)");
1655 return 0;
1656 }
1657
1658 if (analysis == "cdf" || analysis == "trancdf" || analysis == "trancdfpasst") {
1659 // -a cdf preloads the rounded steady-state queue lengths, the seeded
1660 // getCdfRespT pipeline; the transient names start from the default
1661 // initial state, getTranCdfRespT's contract
1662 const std::map<std::pair<std::size_t, std::size_t>,
1663 std::vector<std::pair<double, double> > >
1664 rd = line::jmt::jmt_get_cdf_resp_t(sn, o, analysis == "cdf");
1665 line::reg::Json cdf = line::reg::Json::object();
1666 for (std::map<std::pair<std::size_t, std::size_t>,
1667 std::vector<std::pair<double, double> > >::const_iterator it = rd.begin();
1668 it != rd.end(); ++it) {
1669 line::reg::Json rows = line::reg::Json::array();
1670 for (std::size_t i = 0; i < it->second.size(); ++i) {
1671 line::reg::Json row = line::reg::Json::array();
1672 row.push_back(it->second[i].first);
1673 row.push_back(it->second[i].second);
1674 rows.push_back(row);
1675 }
1676 const std::string key =
1677 sn.nodes[sn.station_to_node[it->first.first - 1] - 1].name + "/" +
1678 sn.classes[it->first.second - 1].name;
1679 cdf[key] = rows;
1680 if (!g_json_output)
1681 std::printf("%-24s %8zu points respT(max)=%.6g\n", key.c_str(),
1682 it->second.size(), it->second.back().second);
1683 }
1684 if (g_json_output) {
1685 line::reg::Json out = line::reg::Json::object();
1686 out["cdf"] = cdf;
1687 emit_document(dump_document(out, 2));
1688 }
1689 return 0;
1690 }
1691
1693 std::printf("SolverJMT arith=double method=%s\n", r.avg.actualmethod.c_str());
1694
1695 // The metric matrices carry `nregions` EXTRA rows past the stations; the
1696 // station table takes the first `nstations` of them and the regions are
1697 // reported separately, as the LDES arm reports its own FCR block.
1699 if (table.QN.rows() > sn.nstations) {
1700 const std::size_t M = sn.nstations, K = sn.nclasses;
1701 line::Matrix<double>* dst[6] = {&table.QN, &table.UN, &table.RN,
1702 &table.TN, &table.AN, &table.WN};
1703 const line::Matrix<double>* src[6] = {&r.avg.QN, &r.avg.UN, &r.avg.RN,
1704 &r.avg.TN, &r.avg.AN, &r.avg.WN};
1705 for (int m = 0; m < 6; ++m) {
1706 line::Matrix<double> t(M, K, 0.0);
1707 for (std::size_t i = 0; i < M; ++i)
1708 for (std::size_t c = 0; c < K; ++c) t(i, c) = (*src[m])(i, c);
1709 *dst[m] = t;
1710 }
1711 }
1712 // THE REGION ROWS TRAVEL BESIDE THE STATION TABLE, in the same shape the
1713 // node view prints them: a host solving through `-a avg` has no other way to
1714 // reach them, and MATLAB's `getAvgNodeTable` needs `result.Avg` to carry
1715 // `nstations + nregions` rows or it filters the FCR node out for having no
1716 // numbers at all (fcr_mm1waitq[M2C], 'row FCR1 missing').
1717 line::reg::Json fcr_extra = line::reg::Json::object();
1718 if (r.avg.QN.rows() > sn.nstations && sn.regions.size() > 0) {
1719 const std::size_t M = sn.nstations, K = sn.nclasses;
1720 line::reg::Json names = line::reg::Json::array();
1721 line::reg::Json q = line::reg::Json::array(), u = line::reg::Json::array();
1722 line::reg::Json rt = line::reg::Json::array(), w = line::reg::Json::array();
1723 line::reg::Json a = line::reg::Json::array(), t = line::reg::Json::array();
1724 for (std::size_t f = 0; f < sn.regions.size() && M + f < r.avg.QN.rows(); ++f) {
1725 names.push_back(f < sn.regions.size() && !sn.regions[f].name.empty()
1726 ? sn.regions[f].name
1727 : "FCR" + std::to_string(f + 1));
1728 for (std::size_t c = 0; c < K; ++c) {
1729 q.push_back(r.avg.QN(M + f, c));
1730 u.push_back(r.avg.UN(M + f, c));
1731 rt.push_back(r.avg.RN(M + f, c));
1732 w.push_back(r.avg.WN(M + f, c));
1733 a.push_back(r.avg.AN(M + f, c));
1734 t.push_back(r.avg.TN(M + f, c));
1735 }
1736 }
1737 fcr_extra["Region"] = names;
1738 fcr_extra["QLen"] = q;
1739 fcr_extra["Util"] = u;
1740 fcr_extra["RespT"] = rt;
1741 fcr_extra["ResidT"] = w;
1742 fcr_extra["ArvR"] = a;
1743 fcr_extra["Tput"] = t;
1744 }
1745 line::reg::Json avg_extra = line::reg::Json::object();
1746 if (!fcr_extra.empty()) avg_extra["FCR"] = fcr_extra;
1747 // THE CONFIDENCE INTERVALS ARE PART OF A SIMULATED MEAN. JMT reports a
1748 // half-width per measure at `--confint`, `JmtResult` carries them, and both
1749 // consumers used to take `r.avg` and drop them -- so the one solver here
1750 // whose answer is an estimate was the one quoting a point estimate as if it
1751 // were exact. Same block, same keys and same reason as
1752 // `solve_model_ldes_avg`'s, so one host reader serves both simulators.
1753 line::reg::Json ci = line::reg::Json::object();
1754 if (!r.QCI.empty()) ci["QNCI"] = matrix_json<double>(r.QCI);
1755 if (!r.UCI.empty()) ci["UNCI"] = matrix_json<double>(r.UCI);
1756 if (!r.RCI.empty()) ci["RNCI"] = matrix_json<double>(r.RCI);
1757 if (!r.TCI.empty()) ci["TNCI"] = matrix_json<double>(r.TCI);
1758 if (!r.ACI.empty()) ci["ANCI"] = matrix_json<double>(r.ACI);
1759 if (!ci.empty()) avg_extra["CI"] = ci;
1760 print_avg_table<double>(sn, table, avg_extra);
1761
1762 // The readable rendering prints the half-widths beside the table rather
1763 // than inside it: the columns are the same six every solver prints, and a
1764 // JMVA run (which computes no interval) would leave them blank.
1765 if (!g_json_output && !r.QCI.empty()) {
1766 std::printf("%-16s %-14s %12s %12s %12s %12s %12s\n", "Station", "JobClass", "QLenCI",
1767 "UtilCI", "RespTCI", "TputCI", "ArvRCI");
1768 for (std::size_t i = 0; i < sn.nstations && i < r.QCI.rows(); ++i)
1769 for (std::size_t c = 0; c < sn.nclasses; ++c)
1770 std::printf("%-16s %-14s %12.6g %12.6g %12.6g %12.6g %12.6g\n",
1771 sn.stations[i].name.c_str(), sn.classes[c].name.c_str(), r.QCI(i, c),
1772 r.UCI.empty() ? 0.0 : r.UCI(i, c), r.RCI.empty() ? 0.0 : r.RCI(i, c),
1773 r.TCI.empty() ? 0.0 : r.TCI(i, c),
1774 r.ACI.empty() ? 0.0 : r.ACI(i, c));
1775 }
1776
1777 if (!g_json_output && r.TNfcr.rows() > 0) {
1778 std::printf("%-16s %-14s %12s %12s\n", "Region", "JobClass", "Tput", "DropRate");
1779 for (std::size_t f = 0; f < r.TNfcr.rows(); ++f)
1780 for (std::size_t c = 0; c < sn.nclasses; ++c)
1781 // THE REGION'S DECLARED NAME, not the JSIM document's internal
1782 // `FCRegion<n>` label: that spelling is what the writer puts in
1783 // the exported model, and reporting it back renamed the user's
1784 // own region (`FCR1` in every other codebase's node table).
1785 std::printf("%-16s %-14s %12.6g %12.6g\n",
1786 (f < sn.regions.size() && !sn.regions[f].name.empty()
1787 ? sn.regions[f].name
1788 : "FCR" + std::to_string(f + 1))
1789 .c_str(),
1790 sn.classes[c].name.c_str(), r.TNfcr(f, c), r.DropRateNfcr(f, c));
1791 }
1792 if (!g_json_output && !r.cache_hit_prob.empty())
1793 for (std::map<std::size_t, std::vector<double> >::const_iterator it =
1794 r.cache_hit_prob.begin();
1795 it != r.cache_hit_prob.end(); ++it)
1796 for (std::size_t c = 0; c < it->second.size(); ++c)
1797 std::printf("%-16s %-14s hitProb=%12.6g\n", sn.nodes[it->first - 1].name.c_str(),
1798 sn.classes[c].name.c_str(), it->second[c]);
1799 return 0;
1800}
1801
1802/**
1803 * `-s nc -a avg` under `--method cftp` / `cftp.approx`: the AvgTable from
1804 * perfect sampling.
1805 *
1806 * THE BANNER NAMES THE RUN LENGTH because these numbers carry Monte Carlo error
1807 * and are not comparable to an exact solver's at solver tolerance. The mean
1808 * coalescence horizon travels with it: it is the cost the exact sampler paid,
1809 * has no a-priori bound, and is the one number that says whether the draw was
1810 * cheap or the model is nearly saturated. No `lognormconst=`: the sampler
1811 * yields no normalizing constant.
1812 */
1813template <class T>
1814int solve_nc_cftp_avg(const line::qn::NetworkStruct<T>& sn, const line::nc::NcSolverOptions& opt,
1815 const line::nc::NcCftpOptions& cftpopt) {
1817 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
1818 "the cftp methods draw random states and form the station balance functions in the "
1819 "log domain, neither of which exists in exact rational arithmetic; rerun with --arith "
1820 "double or --arith real");
1821 } else {
1822 // The run's own gates, in the run's order: the structural predicate
1823 // first, then the declared feature set.
1824 const std::string why = line::nc::solver_nc_cftp_supports(sn);
1825 if (!why.empty()) throw line::UnsupportedError(line::ErrorKind{"Model"}, why);
1827 const line::nc::NcCftpSolution<T> s = line::nc::solver_nc_cftp(sn, opt, cftpopt);
1828 const line::mva::AvgResult<T> r =
1830 double horizon = 0.0;
1831 for (std::size_t i = 0; i < s.horizon.size(); ++i)
1832 horizon += static_cast<double>(s.horizon[i]);
1833 if (!s.horizon.empty()) horizon /= static_cast<double>(s.horizon.size());
1834 std::printf(
1835 "SolverNC arith=%s method=%s type=%s samples=%zu seed=%lu distinct=%zu "
1836 "meanhorizon=%.6g\n",
1838 line::util::method_type("NC", s.actualmethod).c_str(), cftpopt.samples,
1839 cftpopt.seed, s.distinct_states.size(), horizon);
1840 print_avg_table<T>(sn, r);
1841 return 0;
1842 }
1843}
1844
1845/**
1846 * Solve a Network model.json with SolverNC and print the same table.
1847 *
1848 * `--samples` and `--seed` are wired because NC has stochastic methods that read
1849 * them ('mci', 'imci', 'ls', 'is', 'sampling' and 'mcmc'), and a run length nobody
1850 * can set is a method nobody can drive. `highvar` still has no flag and keeps its
1851 * SolverOptions('NC') default rather than being invented here.
1852 */
1853template <class T>
1854int solve_model_nc(const std::string& file, const Knobs& k) {
1855 line::qn::Network<T> net = read_model<T>(file);
1857 if (!k.method.empty() && k.method != "default") opt.method = k.method;
1858 if (k.tol >= 0.0) opt.tol = k.tol;
1859 if (k.iter_tol >= 0.0) opt.iter_tol = k.iter_tol;
1860 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
1861 if (k.samples) opt.samples = k.samples;
1862 if (k.seed) opt.seed = k.seed;
1863 if (!k.multiserver.empty()) opt.multiserver = k.multiserver;
1864 if (!k.fork_join.empty()) opt.fork_join = k.fork_join;
1865 if (k.slotted) opt.slotted = true;
1866 if (k.slotlength > 0.0) {
1867 opt.slotted = true;
1868 opt.slotlength = k.slotlength;
1869 }
1870 // The perfect sampler reports its run length beside the table, so it is
1871 // served by its own arm. The dispatcher has already refused every analysis
1872 // but `avg` for it.
1873 if (opt.method == "cftp" || opt.method == "cftp.approx") {
1875 cftpopt.samples = opt.samples;
1876 cftpopt.seed = opt.seed;
1877 return solve_nc_cftp_avg<T>(net.get_struct(), opt, cftpopt);
1878 }
1879 // The map_env funnel, as on the mva arm above and for the same reason.
1881 if constexpr (std::is_same_v<T, double>) {
1883 net.get_struct(), "SolverNC", line::qn::nc_feature_set(opt.method), map_env_config(k),
1884 [&opt](const line::qn::NetworkStruct<double>& m) {
1885 return line::nc::solver_nc_run_analyzer(m, opt);
1886 },
1888 } else {
1890 }
1891 const line::qn::NetworkStruct<T>& sn = net.get_struct();
1892
1893 // `lognormconst=` rides ON THE BANNER LINE rather than on one of its own,
1894 // as the fluid arm's `iters=` does: the banner is provenance and a new line
1895 // between it and the table is one more thing a table parser has to skip.
1896 // It is `getProbNormConstAggr`, which no other `-a` reports.
1897 std::printf("SolverNC arith=%s method=%s type=%s lognormconst=%.10g\n",
1899 line::util::method_type("NC", r.actualmethod).c_str(),
1900 r.lognormconst.has_value() ? r.lognormconst.value() : 0.0);
1901 print_avg_table<T>(sn, r);
1902 return 0;
1903}
1904
1905/**
1906 * Solve a Network model.json with SolverMAM and print the same table.
1907 *
1908 * DOUBLE ONLY, and refused by name otherwise in the dispatcher: the analyzer
1909 * fits phase-type representations (aph_fit), which static_asserts on
1910 * transcendental arithmetic, so an exact instantiation would fail to COMPILE
1911 * rather than refuse at run time. `MamOptions`' tol, iter_max, space_max and
1912 * preserveDet keep their SolverOptions('MAM') defaults.
1913 */
1914line::mam::MamOptions mam_options(const Knobs& k);
1915
1916template <class T>
1917int solve_model_mam(const std::string& file, const Knobs& k) {
1918 line::qn::Network<T> net = read_model<T>(file);
1919 // the shared builder, so --timescale/--slotlength and the fork-join knobs reach -a avg
1920 const line::mam::MamOptions opt = mam_options(k);
1922 const line::qn::NetworkStruct<T>& sn = net.get_struct();
1923
1924 std::printf("SolverMAM arith=%s method=%s type=%s\n", line::num_traits<T>::name(),
1925 r.actualmethod.c_str(),
1926 line::util::method_type("MAM", r.actualmethod).c_str());
1927 print_avg_table<T>(sn, r);
1928 return 0;
1929}
1930
1931/**
1932 * The AgOptions a command line asks for.
1933 *
1934 * ONE PLACE, because there are three call sites (-a avg, -a cdf and the
1935 * run_avg_engine views) and a knob added to only some of them is a knob that
1936 * works or not depending on which view was asked for.
1937 */
1938void apply_ag_knobs(const Knobs& k, line::ag::AgOptions& opt) {
1939 if (!k.method.empty() && k.method != "default") opt.method = k.method;
1940 if (k.tol >= 0.0) opt.tol = k.tol;
1941 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
1942 if (k.max_states > 0) opt.max_states = static_cast<std::size_t>(k.max_states);
1943 if (!k.nonmkv.empty()) opt.nonmkv = k.nonmkv;
1944}
1945
1946/**
1947 * Solve a Network model.json with SolverAG and print the same table.
1948 *
1949 * The RCAT/INAP arm, reachable from the CLI rather than API-only. It was the
1950 * one engine `run_avg_engine` already served for `-a node` and its three
1951 * sibling views while `-a avg` -- the view every parity row and every wrapper
1952 * asks for first -- refused the token outright, so `-s ag` reported an argument
1953 * error where the solver was present and working.
1954 *
1955 * `--method` picks between inap, inaprc, inapinf and exact; `default`
1956 * resolves to inap inside the analyzer, as it does in every codebase. `--tol`
1957 * and `--iter_max` are the fixed point's, matching -s mam.
1958 */
1959template <class T>
1960int solve_model_ag(const std::string& file, const Knobs& k) {
1961 line::qn::Network<T> net = read_model<T>(file);
1963 apply_ag_knobs(k, opt);
1965 const line::qn::NetworkStruct<T>& sn = net.get_struct();
1966
1967 std::printf("SolverAG arith=%s method=%s type=%s\n", line::num_traits<T>::name(),
1968 r.actualmethod.c_str(),
1969 line::util::method_type("AG", r.actualmethod).c_str());
1970 print_avg_table<T>(sn, r);
1971 return 0;
1972}
1973
1974/**
1975 * The station a per-node MAM query is about: `--node` when given, and otherwise
1976 * the model's only Queue.
1977 *
1978 * Defaulting is legitimate here and nowhere else: `getProb`, `getProbMarg` and
1979 * `getMAMResult` all run `require_single_queue`, so a model that reaches them
1980 * has exactly ONE queue and there is nothing to choose. `--node` is still
1981 * accepted, because naming the node one means is clearer than relying on that.
1982 */
1983template <class T>
1984std::size_t mam_query_node(const line::qn::NetworkStruct<T>& sn, const Knobs& k) {
1985 if (k.node) return k.node;
1986 for (std::size_t a = 0; a < sn.nof_nodes(); ++a)
1987 if (sn.nodes[a].nodetype == line::qn::NodeType::Queue) return a + 1;
1988 throw line::InputError(
1989 "the MAM per-node analyses report a queue's internals and this model has no Queue node");
1990}
1991
1992/** The MamOptions every `-s mam` entry point builds from the CLI knobs. */
1993line::mam::MamOptions mam_options(const Knobs& k) {
1995 if (!k.method.empty() && k.method != "default") opt.method = k.method;
1996 if (k.tol >= 0.0) opt.tol = k.tol;
1997 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
1998 if (k.cutoff >= 0.0) opt.cutoff = static_cast<std::size_t>(k.cutoff);
1999 if (!k.nonmkv.empty()) opt.nonmkv = k.nonmkv;
2000 if (k.fj_accuracy > 0) opt.fj_accuracy = static_cast<std::size_t>(k.fj_accuracy);
2001 if (!k.fj_tmode.empty()) opt.fj_tmode = k.fj_tmode;
2002 if (k.sync_phases >= 0) opt.sync_phases = static_cast<std::size_t>(k.sync_phases);
2003 if (!k.ispn_place.empty()) opt.ispn_place = k.ispn_place;
2004 if (k.ispn_maxlevel >= 0) opt.ispn_maxlevel = static_cast<std::size_t>(k.ispn_maxlevel);
2005 if (!k.censor_level.empty()) opt.censor_level = k.censor_level;
2006 if (k.censor_level_index.has_value()) opt.censor_level_index = k.censor_level_index;
2007 if (k.mapmsg_quantization >= 0)
2008 opt.mapmsg_quantization = static_cast<std::size_t>(k.mapmsg_quantization);
2009 if (!k.timescale.empty()) opt.timescale = k.timescale;
2010 if (k.slotlength > 0.0) opt.slotlength = k.slotlength;
2011 if (k.t1 >= 0.0) {
2012 opt.timespan_start = k.t0;
2013 opt.timespan_end = k.t1;
2014 }
2015 return opt;
2016}
2017
2018/**
2019 * `-s mam -a prob`: `@@SolverMAM/getProb` and `@@SolverMAM/getProbMarg`.
2020 *
2021 * BOTH, in one answer, because they are two views of the same queue-length law:
2022 * the joint (level, phase) table the first returns, and the per-class marginal
2023 * P(n jobs of class r) the second does. Reporting only one would leave the other
2024 * unreachable again, which is the state this wiring closes.
2025 *
2026 * `--cutoff` is the level truncation an OPEN model needs -- its queue length is
2027 * unbounded, so the table has to stop somewhere -- and is passed straight
2028 * through as `options.cutoff`; a closed model bounds itself by its population
2029 * and ignores it.
2030 */
2031template <class T>
2032int solve_model_mam_prob(const std::string& file, const Knobs& k) {
2033 line::qn::Network<T> net = read_model<T>(file);
2034 const line::qn::NetworkStruct<T>& sn = net.get_struct();
2035 const line::mam::MamOptions opt = mam_options(k);
2036 // The reference's getters read `self.getAvg()` first, so the solve comes
2037 // before the query and a caller cannot reach them on an unsolved model.
2039 const std::size_t node = mam_query_node<T>(sn, k);
2040 const std::size_t ist = sn.nodes[node - 1].station;
2041 const line::mam::ProbTable<T> P = line::mam::solver_mam_get_prob(sn, opt, node, avg);
2042 std::vector<std::vector<T> > marg(sn.nclasses);
2043 for (std::size_t r = 0; r < sn.nclasses; ++r)
2044 marg[r] = line::mam::solver_mam_get_prob_marg(sn, opt, ist, r + 1, avg);
2045
2046 if (g_json_output) {
2047 line::reg::Json p = line::reg::Json::object();
2048 p["type"] = "ProbTable";
2049 p["indexBase"] = 0;
2050 p["node"] = node - 1;
2051 p["Node"] = sn.nodes[node - 1].name;
2052 p["levels"] = P.P.rows();
2053 p["phases"] = P.P.cols();
2054 line::reg::Json joint = line::reg::Json::array();
2055 for (std::size_t n = 0; n < P.P.rows(); ++n) {
2056 line::reg::Json row = line::reg::Json::array();
2057 for (std::size_t j = 0; j < P.P.cols(); ++j)
2058 row.push_back(line::num_traits<T>::to_double(P.P(n, j)));
2059 joint.push_back(row);
2060 }
2061 p["joint"] = joint;
2062 line::reg::Json mj = line::reg::Json::array();
2063 for (std::size_t r = 0; r < sn.nclasses; ++r) {
2064 line::reg::Json e = line::reg::Json::object();
2065 e["JobClass"] = sn.classes[r].name;
2066 e["jobclass"] = r;
2067 e["P"] = vector_json(marg[r]);
2068 mj.push_back(e);
2069 }
2070 p["marginal"] = mj;
2071 emit_analysis<T>("prob", p, avg.actualmethod);
2072 return 0;
2073 }
2074 std::printf("SolverMAM arith=%s method=%s node=%s levels=%zu phases=%zu\n",
2076 sn.nodes[node - 1].name.c_str(), P.P.rows(), P.P.cols());
2077 std::printf("%-8s %-8s %16s\n", "Level", "Phase", "Prob");
2078 for (std::size_t n = 0; n < P.P.rows(); ++n)
2079 for (std::size_t j = 0; j < P.P.cols(); ++j)
2080 std::printf("%-8zu %-8zu %16.10g\n", n, j + 1,
2082 std::printf("%-14s %-8s %16s\n", "JobClass", "Jobs", "Prob");
2083 for (std::size_t r = 0; r < sn.nclasses; ++r)
2084 for (std::size_t n = 0; n < marg[r].size(); ++n)
2085 std::printf("%-14s %-8zu %16.10g\n", sn.classes[r].name.c_str(), n,
2086 line::num_traits<T>::to_double(marg[r][n]));
2087 return 0;
2088}
2089
2090/**
2091 * The levels `getPerctRespT` is read at: `--percentiles`, or the reference's
2092 * `pers_stored` when the caller named none.
2093 */
2094std::vector<double> percentile_levels(const Knobs& k) {
2095 if (!k.percentiles.empty()) return k.percentiles;
2096 std::vector<double> pcts;
2097 pcts.push_back(0.50);
2098 pcts.push_back(0.90);
2099 pcts.push_back(0.95);
2100 pcts.push_back(0.99);
2101 return pcts;
2102}
2103
2104/**
2105 * `-s mam -a cdf`: `@@SolverMAM/getCdfRespT` (and its aliases getSjrnT / sjrnT),
2106 * with `@@SolverMAM/getPerctRespT` beside it.
2107 *
2108 * THE PERCENTILE LEVELS COME FROM `--percentiles`, defaulting to the
2109 * {0.50, 0.90, 0.95, 0.99} that `solver_mam_fj.m` stores as `pers_stored`: the
2110 * reference takes them as an argument to `getPerctRespT`, and the flag is that
2111 * argument. On the CDF path they are a READING of the same curve --
2112 * `mam_percentiles_from_cdf` inverts the CDF that is printed above them -- so a
2113 * level the caller names costs nothing beyond the inversion.
2114 *
2115 * A FORK-JOIN MODEL HAS NO CDF HERE, and that is the reference's structure
2116 * rather than a gap in this port: `getPerctRespT.m` reads the table
2117 * `solver_mam_fj.m` stored, and its own fallback comment records that
2118 * `getCdfRespT` is "not available for this model". The two are separate methods
2119 * in MATLAB and only this CLI bundles them, so the fork-join case prints the
2120 * percentiles alone and says why. The condition is tested explicitly, not
2121 * discovered by catching the CDF's refusal: a caught exception cannot tell "no
2122 * fork-join route exists" from "the passage-time engine failed on this model".
2123 */
2124template <class T>
2125int solve_model_mam_cdf(const std::string& file, const Knobs& k, const char* key,
2126 const char* type) {
2127 line::qn::Network<T> net = read_model<T>(file);
2128 const line::qn::NetworkStruct<T>& sn = net.get_struct();
2129 const line::mam::MamOptions opt = mam_options(k);
2130 const std::vector<double> pcts = percentile_levels(k);
2131
2132 if (line::mam::mam_has_fj_percentiles(sn, opt)) {
2133 const std::vector<std::vector<T> > perc =
2135 if (g_json_output) {
2136 line::reg::Json p = line::reg::Json::object();
2137 p["type"] = "PerctRespT";
2138 p["indexBase"] = 0;
2139 p["source"] = "fjcodes";
2140 line::reg::Json arr = line::reg::Json::array();
2141 for (std::size_t r = 0; r < perc.size(); ++r) {
2142 line::reg::Json e = line::reg::Json::object();
2143 e["JobClass"] = sn.classes[r].name;
2144 e["jobclass"] = r;
2145 e["percentileLevels"] = pcts;
2146 e["percentiles"] = vector_json(perc[r]);
2147 arr.push_back(e);
2148 }
2149 p["respt"] = arr;
2150 emit_analysis<T>(key, p, opt.method);
2151 return 0;
2152 }
2153 std::printf("SolverMAM arith=%s method=%s classes=%zu\n", line::num_traits<T>::name(),
2154 opt.method.c_str(), sn.nclasses);
2155 std::printf("# the response-time CDF has no fork-join route in the reference; these are "
2156 "the FJ_codes percentiles getPerctRespT reads\n");
2157 std::printf("%-14s %14s %14s\n", "JobClass", "Percentile", "RespT");
2158 for (std::size_t r = 0; r < perc.size(); ++r)
2159 for (std::size_t j = 0; j < perc[r].size(); ++j)
2160 std::printf("%-14s %14.4g %14.10g\n", sn.classes[r].name.c_str(), pcts[j],
2161 line::num_traits<T>::to_double(perc[r][j]));
2162 return 0;
2163 }
2164
2165 const std::vector<line::mam::RespTCdf<T> > rd = line::mam::solver_mam_get_cdf_respt(sn, opt);
2166 std::vector<std::vector<T> > perc;
2167 for (std::size_t r = 0; r < rd.size(); ++r)
2168 perc.push_back(line::mam::mam_percentiles_from_cdf(rd[r], pcts));
2169
2170 if (g_json_output) {
2171 line::reg::Json p = line::reg::Json::object();
2172 p["type"] = type;
2173 p["indexBase"] = 0;
2174 line::reg::Json arr = line::reg::Json::array();
2175 for (std::size_t r = 0; r < rd.size(); ++r) {
2176 // An empty curve is not a degenerate one: the class has no passage
2177 // through a queue here, and it is OMITTED rather than sent as a flat
2178 // zero law.
2179 if (rd[r].X.empty()) continue;
2180 line::reg::Json e = line::reg::Json::object();
2181 e["JobClass"] = sn.classes[r].name;
2182 e["jobclass"] = r;
2183 e["t"] = vector_json(rd[r].X);
2184 e["F"] = vector_json(rd[r].F);
2185 e["percentileLevels"] = pcts;
2186 e["percentiles"] = vector_json(perc[r]);
2187 arr.push_back(e);
2188 }
2189 p["respt"] = arr;
2190 emit_analysis<T>(key, p, opt.method);
2191 return 0;
2192 }
2193 std::printf("SolverMAM arith=%s method=%s classes=%zu\n", line::num_traits<T>::name(),
2194 opt.method.c_str(), sn.nclasses);
2195 std::printf("%-14s %14s %14s\n", "JobClass", "Time", "F(t)");
2196 for (std::size_t r = 0; r < rd.size(); ++r)
2197 for (std::size_t j = 0; j < rd[r].X.size(); ++j)
2198 std::printf("%-14s %14.8g %14.10g\n", sn.classes[r].name.c_str(),
2200 line::num_traits<T>::to_double(rd[r].F[j]));
2201 std::printf("%-14s %14s %14s\n", "JobClass", "Percentile", "RespT");
2202 for (std::size_t r = 0; r < perc.size(); ++r)
2203 for (std::size_t j = 0; j < perc[r].size(); ++j)
2204 std::printf("%-14s %14.4g %14.10g\n", sn.classes[r].name.c_str(), pcts[j],
2205 line::num_traits<T>::to_double(perc[r][j]));
2206 return 0;
2207}
2208
2209/**
2210 * `-s mam -a perct-respt`: `@@SolverMAM/getPerctRespT` ALONE.
2211 *
2212 * The percentiles ride beside the curve under `-a cdf` as well, and this arm
2213 * exists because they are a separate METHOD in the reference and a separate
2214 * answer to a caller: a service-level question ("what is the 99th percentile")
2215 * wants four numbers, not the whole law printed above them. On a fork-join
2216 * model it is the only route -- `getCdfRespT` has none there -- and on every
2217 * other model the levels are inverted from the CDF the other arm prints, so
2218 * the two never disagree.
2219 */
2220template <class T>
2221int solve_model_mam_perct(const std::string& file, const Knobs& k) {
2222 line::qn::Network<T> net = read_model<T>(file);
2223 const line::qn::NetworkStruct<T>& sn = net.get_struct();
2224 const line::mam::MamOptions opt = mam_options(k);
2225 const std::vector<double> pcts = percentile_levels(k);
2226
2227 std::vector<std::vector<T> > perc;
2228 const bool fj = line::mam::mam_has_fj_percentiles(sn, opt);
2229 if (fj) {
2230 perc = line::mam::solver_mam_get_perct_respt(sn, opt, pcts);
2231 } else {
2232 const std::vector<line::mam::RespTCdf<T> > rd =
2234 for (std::size_t r = 0; r < rd.size(); ++r)
2235 perc.push_back(line::mam::mam_percentiles_from_cdf(rd[r], pcts));
2236 }
2237
2238 if (g_json_output) {
2239 line::reg::Json p = line::reg::Json::object();
2240 p["type"] = "PerctRespT";
2241 p["indexBase"] = 0;
2242 p["source"] = fj ? "fjcodes" : "cdf";
2243 line::reg::Json arr = line::reg::Json::array();
2244 for (std::size_t r = 0; r < perc.size(); ++r) {
2245 if (perc[r].empty()) continue;
2246 line::reg::Json e = line::reg::Json::object();
2247 e["JobClass"] = sn.classes[r].name;
2248 e["jobclass"] = r;
2249 e["percentileLevels"] = pcts;
2250 e["percentiles"] = vector_json(perc[r]);
2251 arr.push_back(e);
2252 }
2253 p["respt"] = arr;
2254 emit_analysis<T>("perct", p, opt.method);
2255 return 0;
2256 }
2257 std::printf("SolverMAM arith=%s method=%s classes=%zu source=%s\n",
2258 line::num_traits<T>::name(), opt.method.c_str(), sn.nclasses,
2259 fj ? "fjcodes" : "cdf");
2260 std::printf("%-14s %14s %14s\n", "JobClass", "Percentile", "RespT");
2261 for (std::size_t r = 0; r < perc.size(); ++r)
2262 for (std::size_t j = 0; j < perc[r].size(); ++j)
2263 std::printf("%-14s %14.4g %14.10g\n", sn.classes[r].name.c_str(), pcts[j],
2264 line::num_traits<T>::to_double(perc[r][j]));
2265 return 0;
2266}
2267
2268/**
2269 * `-s mam -a tran`: `@@SolverMAM/getTranAvg`.
2270 *
2271 * The reference FORCES `options.method = 'ldqbd'` before delegating, so the
2272 * transient path is not the caller's method and `--method` does not select it;
2273 * which engine runs -- the Laplace-domain transient QBD or the QBD fast path --
2274 * is decided from the model by `mam_transient_qbd_applicable`. `--tspan` is
2275 * required: a transient curve on an unstated horizon is not a quantity.
2276 */
2277template <class T>
2278int solve_model_mam_tran(const std::string& file, const Knobs& k) {
2279 line::qn::Network<T> net = read_model<T>(file);
2280 const line::qn::NetworkStruct<T>& sn = net.get_struct();
2281 const line::mam::MamOptions opt = mam_options(k);
2283
2284 if (g_json_output) {
2285 line::reg::Json p = line::reg::Json::object();
2286 p["type"] = "TranAvgTable";
2287 p["indexBase"] = 0;
2288 p["t0"] = opt.timespan_start;
2289 p["t1"] = opt.timespan_end;
2290 line::reg::Json arr = line::reg::Json::array();
2291 for (std::size_t i = 0; i < tr.Qt.size(); ++i)
2292 for (std::size_t r = 0; r < tr.Qt[i].size(); ++r) {
2293 if (tr.Qt[i][r].times.empty()) continue;
2294 line::reg::Json e = line::reg::Json::object();
2295 e["Station"] = sn.stations[i].name;
2296 e["JobClass"] = sn.classes[r].name;
2297 e["station"] = i;
2298 e["jobclass"] = r;
2299 e["t"] = tr.Qt[i][r].times;
2300 e["QLen"] = vector_json(tr.Qt[i][r].values);
2301 e["Util"] = vector_json(tr.Ut[i][r].values);
2302 e["Tput"] = vector_json(tr.Tt[i][r].values);
2303 arr.push_back(e);
2304 }
2305 p["curves"] = arr;
2306 emit_analysis<T>("tran", p, "ldqbd");
2307 return 0;
2308 }
2309 std::printf("SolverMAM arith=%s method=ldqbd tspan=[%g,%g]\n", line::num_traits<T>::name(),
2310 opt.timespan_start, opt.timespan_end);
2311 std::printf("%-16s %-14s %12s %12s %12s %12s\n", "Station", "JobClass", "Time", "QLen", "Util",
2312 "Tput");
2313 for (std::size_t i = 0; i < tr.Qt.size(); ++i)
2314 for (std::size_t r = 0; r < tr.Qt[i].size(); ++r)
2315 for (std::size_t j = 0; j < tr.Qt[i][r].times.size(); ++j)
2316 std::printf("%-16s %-14s %12.6g %12.6g %12.6g %12.6g\n",
2317 sn.stations[i].name.c_str(), sn.classes[r].name.c_str(),
2318 tr.Qt[i][r].times[j],
2319 line::num_traits<T>::to_double(tr.Qt[i][r].values[j]),
2320 line::num_traits<T>::to_double(tr.Ut[i][r].values[j]),
2321 line::num_traits<T>::to_double(tr.Tt[i][r].values[j]));
2322 return 0;
2323}
2324
2325/**
2326 * `-s mam -a internals`: `@@SolverMAM/getMAMResult`, the M/G/1-type internals of
2327 * a single queue.
2328 *
2329 * It is NOT a metric table and is deliberately not folded into `-a avg`: the
2330 * answer is the matrix-analytic machinery itself -- the randomized blocks, the
2331 * G matrix, the drift, the decay rate, the level probabilities -- which is what
2332 * a caller checking a queue's stability or tail decay asks for, and what a
2333 * cross-codebase comparison of the QBD assembly needs to see.
2334 */
2335template <class T>
2336int solve_model_mam_internals(const std::string& file, const Knobs& k) {
2337 line::qn::Network<T> net = read_model<T>(file);
2338 const line::qn::NetworkStruct<T>& sn = net.get_struct();
2339 (void)k;
2341 const double q = line::num_traits<T>::to_double(r.q);
2342
2343 if (g_json_output) {
2344 line::reg::Json p = line::reg::Json::object();
2345 p["type"] = "MAMResult";
2346 p["indexBase"] = 0;
2347 p["lambda"] = line::num_traits<T>::to_double(r.lambda);
2348 p["rho"] = line::num_traits<T>::to_double(r.rho);
2349 p["uniformization"] = q;
2350 p["drift"] = line::num_traits<T>::to_double(r.drift);
2351 p["decayRate"] = r.decayRate;
2352 p["pi0"] = line::num_traits<T>::to_double(r.pi0);
2356 p["truncLevel"] = r.truncLevel;
2357 p["truncError"] = r.truncError;
2358 p["gConverged"] = r.gConverged;
2359 p["theta"] = vector_json(r.theta);
2360 p["alpha"] = vector_json(r.alpha);
2361 line::reg::Json lv = line::reg::Json::array();
2362 for (std::size_t n = 0; n < r.levelProb.rows(); ++n) {
2363 line::reg::Json row = line::reg::Json::array();
2364 for (std::size_t j = 0; j < r.levelProb.cols(); ++j)
2365 row.push_back(line::num_traits<T>::to_double(r.levelProb(n, j)));
2366 lv.push_back(row);
2367 }
2368 p["levelProb"] = lv;
2369 emit_analysis<T>("internals", p, std::string());
2370 return 0;
2371 }
2372 std::printf("SolverMAM arith=%s stations=%zu\n", line::num_traits<T>::name(), sn.nstations);
2373 std::printf("lambda=%.10g rho=%.10g q=%.10g drift=%.10g decayRate=%.10g\n",
2376 std::printf("pi0=%.10g QLen=%.10g Util=%.10g Tput=%.10g truncLevel=%zu truncError=%.3g "
2377 "gConverged=%s\n",
2382 r.gConverged ? "yes" : "no");
2383 std::printf("%-8s %16s\n", "Level", "Prob");
2384 for (std::size_t n = 0; n < r.levelProb.rows(); ++n) {
2385 double s = 0.0;
2386 for (std::size_t j = 0; j < r.levelProb.cols(); ++j)
2388 std::printf("%-8zu %16.10g\n", n, s);
2389 }
2390 return 0;
2391}
2392
2393/** A JSON flag value, given inline or as the path of a file holding it. */
2394line::reg::Json read_json_arg(const std::string& spec, const char* flag) {
2395 std::string text = spec;
2396 const std::size_t at = spec.find_first_not_of(" \t\r\n");
2397 if (at == std::string::npos || (spec[at] != '{' && spec[at] != '[')) {
2398 std::ifstream in(spec.c_str());
2399 if (!in)
2400 throw line::InputError(std::string(flag) + " is neither inline JSON nor a readable "
2401 "file (got '" + spec + "')");
2402 text.assign(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
2403 }
2404 try {
2405 return line::reg::Json::parse(text);
2406 } catch (const line::reg::Json::parse_error& e) {
2407 throw line::InputError(std::string("malformed ") + flag + " JSON: " + e.what());
2408 }
2409}
2410
2411/** A JSON array of arrays as an integer table. */
2412std::vector<std::vector<int> > json_int_table(const line::reg::Json& j, const char* name) {
2413 if (!j.is_array())
2414 throw line::InputError(std::string("--qrf-params ") + name + " must be an array of rows");
2415 std::vector<std::vector<int> > out;
2416 for (std::size_t m = 0; m < j.size(); ++m) {
2417 if (!j[m].is_array())
2418 throw line::InputError(std::string("--qrf-params ") + name + " must be an array of "
2419 "rows");
2420 std::vector<int> row;
2421 for (std::size_t c = 0; c < j[m].size(); ++c) row.push_back(j[m][c].get<int>());
2422 out.push_back(row);
2423 }
2424 return out;
2425}
2426
2427/**
2428 * Decode `--qrf-params` into `BaOptions::qrf_params`.
2429 *
2430 * Required: f, MR, BB, MM, MM1, ZZ, exactly what `sn_to_qrf_params` demands.
2431 * F is optional and falls back to sn.cap. ZM is DERIVED from ZZ and a supplied
2432 * one is ignored: it is max(ZZ) by definition, and a larger one empties the
2433 * polytope through THM3I instead of failing cleanly.
2434 */
2435void decode_qrf_params(const std::string& spec, line::ba::BaOptions& opt) {
2436 const line::reg::Json j = read_json_arg(spec, "--qrf-params");
2437 if (!j.is_object()) throw line::InputError("--qrf-params must be a JSON object");
2438 const char* required[] = {"f", "MR", "BB", "MM", "MM1", "ZZ"};
2439 std::string missing;
2440 for (std::size_t i = 0; i < 6; ++i)
2441 if (!j.contains(required[i]))
2442 missing += (missing.empty() ? "" : ", ") + std::string(required[i]);
2443 if (!missing.empty())
2444 throw line::InputError("--qrf-params is missing the field(s) " + missing +
2445 "; required are f, MR, BB, MM, MM1, ZZ (F is optional, ZM is "
2446 "derived from ZZ)");
2448 p.supplied = true;
2449 p.f = j["f"].get<int>();
2450 p.MR = j["MR"].get<int>();
2451 p.BB = json_int_table(j["BB"], "BB");
2452 p.MM = json_int_table(j["MM"], "MM");
2453 p.MM1 = json_int_table(j["MM1"], "MM1");
2454 if (!j["ZZ"].is_array()) throw line::InputError("--qrf-params ZZ must be an array");
2455 for (std::size_t i = 0; i < j["ZZ"].size(); ++i) p.ZZ.push_back(j["ZZ"][i].get<int>());
2456 if (j.contains("F"))
2457 for (std::size_t i = 0; i < j["F"].size(); ++i) p.F.push_back(j["F"][i].get<int>());
2458 opt.qrf_params = p;
2459}
2460
2461/** Decode `--qrf-alpha`, the (nstations x N) load-dependent scaling. */
2462void decode_qrf_alpha(const std::string& spec, line::ba::BaOptions& opt) {
2463 const line::reg::Json j = read_json_arg(spec, "--qrf-alpha");
2464 if (!j.is_array() || j.empty() || !j[0].is_array())
2465 throw line::InputError("--qrf-alpha must be a JSON array of rows, one per station");
2466 line::Matrix<double> a(j.size(), j[0].size(), 0.0);
2467 for (std::size_t i = 0; i < j.size(); ++i) {
2468 if (!j[i].is_array() || j[i].size() != j[0].size())
2469 throw line::InputError("--qrf-alpha rows must all have the same length");
2470 for (std::size_t n = 0; n < j[i].size(); ++n) a(i, n) = j[i][n].get<double>();
2471 }
2472 opt.qrf_alpha = a;
2473}
2474
2475/** The knobs the two SolverBA arms share. */
2476void apply_ba_knobs(const Knobs& k, line::ba::BaOptions& opt) {
2477 if (!k.method.empty() && k.method != "default") opt.method = k.method;
2478 if (k.level > 0) opt.level = k.level;
2479 if (!k.qrf_params.empty()) decode_qrf_params(k.qrf_params, opt);
2480 if (!k.qrf_alpha.empty()) decode_qrf_alpha(k.qrf_alpha, opt);
2481}
2482
2483/**
2484 * Solve a Network model.json with SolverBA and print the same table.
2485 *
2486 * A BOUND, not an estimate: `--method` names which side of which hierarchy is
2487 * wanted (`aba.upper`, `gb.lower`, ...) and `default` resolves to `gb.upper`,
2488 * as in the reference. `options.level` keeps its default of 2. The table is
2489 * therefore not comparable with an exact solver's row except as a bracket,
2490 * which is why the parity row is separate.
2491 */
2492template <class T>
2493int solve_model_ba(const std::string& file, const Knobs& k) {
2494 line::qn::Network<T> net = read_model<T>(file);
2496 apply_ba_knobs(k, opt);
2498 const line::qn::NetworkStruct<T>& sn = net.get_struct();
2499
2500 std::printf("SolverBA arith=%s method=%s type=%s\n", line::num_traits<T>::name(),
2501 r.actualmethod.c_str(),
2502 line::util::method_type("BA", r.actualmethod).c_str());
2503 print_avg_table<T>(sn, r);
2504 return 0;
2505}
2506
2507/**
2508 * `-s ba -a bounds`: `SolverBA.getBounds` and its `getBoundsTable` row filter.
2509 *
2510 * NOT THE SAME ANSWER AS `-a avg`, which is why it is its own analysis. `-a avg`
2511 * reports ONE side of ONE family -- whichever `--method` named -- so a caller who
2512 * wants the bracket has to run the solver twice and know which two method names
2513 * pair up. `getBounds` takes the family (the method's prefix before the first
2514 * dot) and re-runs both sides under the caller's FULL option set, so a
2515 * hierarchical family tightens with `--level` as it should.
2516 *
2517 * A ONE-SIDED FAMILY REPORTS NaN ON THE SIDE IT LACKS, never zero: `cub` is
2518 * upper-only and `mbjb`/`ldac` are lower-only, and a zero there would read as
2519 * a lower bound of zero rather than as the absence of one.
2520 */
2521template <class T>
2522int solve_model_ba_bounds(const std::string& file, const Knobs& k) {
2523 line::qn::Network<T> net = read_model<T>(file);
2525 apply_ba_knobs(k, opt);
2526 const line::qn::NetworkStruct<T>& sn = net.get_struct();
2527 const line::ba::BaBounds<T> b = line::ba::ba_bounds(sn, opt);
2528 const std::string am = line::ba::resolve_method(opt.method);
2529
2530 auto d = [](const T& v) { return line::num_traits<T>::to_double(v); };
2531 if (g_json_output) {
2532 line::reg::Json p = line::reg::Json::object();
2533 p["type"] = "BoundsTable";
2534 p["indexBase"] = 0;
2535 p["family"] = am.substr(0, am.find('.'));
2536 p["hasLower"] = b.has_lower;
2537 p["hasUpper"] = b.has_upper;
2538 for (const char* key : {"Station", "JobClass", "QLower", "QUpper", "TLower", "TUpper"})
2539 p[key] = line::reg::Json::array();
2540 for (std::size_t i = 0; i < sn.nstations; ++i)
2541 for (std::size_t c = 0; c < sn.nclasses; ++c) {
2542 if (!b.keep[i][c]) continue;
2543 p["Station"].push_back(sn.stations[i].name);
2544 p["JobClass"].push_back(sn.classes[c].name);
2545 p["QLower"].push_back(d(b.Qlower(i, c)));
2546 p["QUpper"].push_back(d(b.Qupper(i, c)));
2547 p["TLower"].push_back(d(b.Tlower(i, c)));
2548 p["TUpper"].push_back(d(b.Tupper(i, c)));
2549 }
2550 emit_analysis<T>("bounds", p, am);
2551 return 0;
2552 }
2553 std::printf("SolverBA arith=%s method=%s type=%s family=%s sides=%s\n",
2554 line::num_traits<T>::name(), am.c_str(),
2555 line::util::method_type("BA", am).c_str(), am.substr(0, am.find('.')).c_str(),
2556 b.has_lower ? (b.has_upper ? "lower,upper" : "lower") : "upper");
2557 std::printf("%-16s %-14s %12s %12s %12s %12s\n", "Station", "JobClass", "QLower", "QUpper",
2558 "TLower", "TUpper");
2559 for (std::size_t i = 0; i < sn.nstations; ++i)
2560 for (std::size_t c = 0; c < sn.nclasses; ++c) {
2561 if (!b.keep[i][c]) continue;
2562 std::printf("%-16s %-14s %12.6g %12.6g %12.6g %12.6g\n", sn.stations[i].name.c_str(),
2563 sn.classes[c].name.c_str(), d(b.Qlower(i, c)), d(b.Qupper(i, c)),
2564 d(b.Tlower(i, c)), d(b.Tupper(i, c)));
2565 }
2566 return 0;
2567}
2568
2569/**
2570 * `-s lqns` on a flat Network: its qns methods, the model handed to the external
2571 * `qnsolver` binary (or, closed and not product-form, through QN2LQN to lqns).
2572 *
2573 * The only wrapper on the model-solving path. The banner names it separately
2574 * from the table so a reader can tell an independent tool's numbers from the
2575 * port's own -- which is the whole reason the wrapper exists.
2576 */
2577template <class T>
2578int solve_model_lqns_network(const std::string& file, const Knobs& k) {
2579 line::qn::Network<T> net = read_model<T>(file);
2581 if (!k.method.empty()) opt.method = k.method;
2582 if (!k.multiserver.empty()) opt.multiserver = k.multiserver;
2583 // --samples is deliberately NOT forwarded: `options.samples` reaches the
2584 // JMVA document as `maxSamples`, which is JMT's Monte Carlo cap and which
2585 // qnsolver reads past. The shared knob ladder below refuses it for every
2586 // solver that draws nothing, and this path is one of them.
2587 opt.keep = k.keep;
2589 const line::qn::NetworkStruct<T>& sn = net.get_struct();
2590
2591 if (!g_json_output)
2592 std::printf("SolverLQNS arith=%s method=%s type=%s\n", line::num_traits<T>::name(),
2593 r.actualmethod.c_str(),
2594 line::util::method_type("LQNS", r.actualmethod).c_str());
2595 print_avg_table<T>(sn, r);
2596 return 0;
2597}
2598
2599/**
2600 * Emit the base-class exponential response-time CDF fallback, the same
2601 * `CdfRespT` document every real distributional arm emits.
2602 *
2603 * This is `@@NetworkSolver/getCdfRespT.m`: the solvers without a
2604 * distributional result of their own (MVA, LQNS, BA, AG) inherit an exponential
2605 * law with the right mean in the reference, and refusing `-a cdf` for them
2606 * diverged from it. The curve says nothing about the tail; the banner names
2607 * the solver so the caller knows which mean it wraps.
2608 */
2609template <class T>
2610int emit_default_cdf(const char* solver_name, const line::qn::NetworkStruct<T>& sn,
2611 const line::mva::AvgResult<T>& r) {
2612 const std::vector<std::vector<line::solvers::DefaultCdfCurve>> RD =
2614 if (g_json_output) {
2615 line::reg::Json p = line::reg::Json::object();
2616 p["type"] = "CdfRespT";
2617 p["indexBase"] = 0;
2618 line::reg::Json arr = line::reg::Json::array();
2619 for (std::size_t i = 0; i < RD.size(); ++i)
2620 for (std::size_t c = 0; c < RD[i].size(); ++c) {
2621 if (RD[i][c].t.empty()) continue;
2622 line::reg::Json e = line::reg::Json::object();
2623 e["Station"] = sn.stations[i].name;
2624 e["JobClass"] = sn.classes[c].name;
2625 e["station"] = i;
2626 e["jobclass"] = c;
2627 e["t"] = line::reg::Json(RD[i][c].t);
2628 e["F"] = line::reg::Json(RD[i][c].F);
2629 arr.push_back(e);
2630 }
2631 p["respt"] = arr;
2632 emit_analysis<T>("cdf", p, std::string());
2633 return 0;
2634 }
2635 std::printf("%s arith=%s method=%s (exponential fallback with the solver's mean)\n",
2636 solver_name, line::num_traits<T>::name(), r.actualmethod.c_str());
2637 std::printf("%-16s %-14s %14s %14s\n", "Station", "JobClass", "Time", "F(t)");
2638 for (std::size_t i = 0; i < RD.size(); ++i)
2639 for (std::size_t c = 0; c < RD[i].size(); ++c)
2640 for (std::size_t j = 0; j < RD[i][c].t.size(); ++j)
2641 std::printf("%-16s %-14s %14.8g %14.10g\n", sn.stations[i].name.c_str(),
2642 sn.classes[c].name.c_str(), RD[i][c].t[j], RD[i][c].F[j]);
2643 return 0;
2644}
2645
2646/** `-s mva -a cdf`: the inherited exponential fallback over the MVA means. */
2647template <class T>
2648int solve_model_mva_cdf(const std::string& file, const Knobs& k) {
2649 line::qn::Network<T> net = read_model<T>(file);
2651 if (!k.method.empty() && k.method != "default") opt.method = k.method;
2652 if (k.tol >= 0.0) opt.tol = k.tol;
2653 if (k.iter_tol >= 0.0) opt.iter_tol = k.iter_tol;
2654 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
2655 if (!k.multiserver.empty()) opt.multiserver = k.multiserver;
2656 if (!k.fork_join.empty()) opt.fork_join = k.fork_join;
2657 line::Matrix<T> init;
2659 return emit_default_cdf<T>("SolverMVA", net.get_struct(), r);
2660}
2661
2662/** `-s ag -a cdf`: the inherited exponential fallback over the RCAT means. */
2663template <class T>
2664int solve_model_ag_cdf(const std::string& file, const Knobs& k) {
2665 line::qn::Network<T> net = read_model<T>(file);
2667 apply_ag_knobs(k, opt);
2669 return emit_default_cdf<T>("SolverAG", net.get_struct(), r);
2670}
2671
2672/** `-s ba -a cdf`: the inherited exponential fallback over the bound means. */
2673template <class T>
2674int solve_model_ba_cdf(const std::string& file, const Knobs& k) {
2675 line::qn::Network<T> net = read_model<T>(file);
2677 apply_ba_knobs(k, opt);
2679 return emit_default_cdf<T>("SolverBA", net.get_struct(), r);
2680}
2681
2682/** `-s lqns -a cdf` on a flat Network: the inherited exponential fallback over qnsolver's means. */
2683int solve_model_lqns_network_cdf(const std::string& file, const Knobs& k) {
2684 line::qn::Network<double> net = read_model<double>(file);
2686 if (!k.method.empty()) opt.method = k.method;
2687 if (!k.multiserver.empty()) opt.multiserver = k.multiserver;
2688 opt.keep = k.keep;
2691 return emit_default_cdf<double>("SolverLQNS", net.get_struct(), r);
2692}
2693
2694
2695/**
2696 * `-a interval`: the support-only range, the reference's `getIntervalTable`.
2697 *
2698 * A SEPARATE FUNCTION because it is printed before the ensemble exists: on the
2699 * exact path there is no design to solve, so the interval arrives without a
2700 * `UqSolution` beside it.
2701 */
2702template <class T>
2703int print_uq_interval(const line::qn::NetworkStruct<T>& sn, const line::uq::UqInterval<T>& iv,
2704 const std::string& stage, std::size_t npriors) {
2705 auto v = [](const line::Matrix<T>& M, std::size_t i, std::size_t c) {
2706 return M.empty() ? 0.0 : line::num_traits<T>::to_double(M(i, c));
2707 };
2708 line::reg::Json p = line::reg::Json::object();
2709 p["type"] = "IntervalTable";
2710 p["indexBase"] = 0;
2711 p["exact"] = iv.exact;
2712 p["intervalMethod"] = iv.method;
2713 if (!iv.why.empty()) p["why"] = iv.why;
2714 if (iv.has_totals) {
2715 p["X"] = {line::num_traits<T>::to_double(iv.Xlo),
2717 p["Rtot"] = {line::num_traits<T>::to_double(iv.Rtot_lo),
2719 }
2720 for (const char* key : {"Station", "JobClass", "QLen_lo", "QLen_up", "Util_lo", "Util_up",
2721 "RespT_lo", "RespT_up", "Tput_lo", "Tput_up"})
2722 p[key] = line::reg::Json::array();
2723 if (!g_json_output) {
2724 std::printf("SolverUQ arith=%s interval=%s exact=%s priors=%zu stage=%s\n",
2725 line::num_traits<T>::name(), iv.method.c_str(), iv.exact ? "yes" : "no",
2726 npriors, stage.c_str());
2727 // A RANGE THAT IS NOT AN ENCLOSURE MUST SAY SO. The sampled path
2728 // spans the design points only, so on a continuous Prior it lies
2729 // strictly inside the true range; printing it beside an exact hull
2730 // without the reason would make the two indistinguishable.
2731 if (!iv.exact)
2732 std::fprintf(stderr,
2733 "Warning: exact interval MVA does not apply (%s); the range below is "
2734 "over the solved design points and is not an enclosure.\n",
2735 iv.why.c_str());
2736 std::printf("%-16s %-14s %12s %12s %12s %12s %12s %12s %12s %12s\n", "Station",
2737 "JobClass", "QLen_lo", "QLen_up", "Util_lo", "Util_up", "RespT_lo",
2738 "RespT_up", "Tput_lo", "Tput_up");
2739 }
2740 for (std::size_t i = 0; i < sn.nstations; ++i)
2741 for (std::size_t c = 0; c < sn.nclasses; ++c) {
2742 // The reference's row filter: an upper endpoint of zero on every
2743 // presence metric means the class never visits the station.
2744 if (v(iv.Qup, i, c) <= 0.0 && v(iv.Uup, i, c) <= 0.0 && v(iv.Tup, i, c) <= 0.0)
2745 continue;
2746 if (!g_json_output) {
2747 std::printf(
2748 "%-16s %-14s %12.6g %12.6g %12.6g %12.6g %12.6g %12.6g %12.6g %12.6g\n",
2749 sn.stations[i].name.c_str(), sn.classes[c].name.c_str(), v(iv.Qlo, i, c),
2750 v(iv.Qup, i, c), v(iv.Ulo, i, c), v(iv.Uup, i, c), v(iv.Rlo, i, c),
2751 v(iv.Rup, i, c), v(iv.Tlo, i, c), v(iv.Tup, i, c));
2752 continue;
2753 }
2754 p["Station"].push_back(sn.stations[i].name);
2755 p["JobClass"].push_back(sn.classes[c].name);
2756 p["QLen_lo"].push_back(v(iv.Qlo, i, c));
2757 p["QLen_up"].push_back(v(iv.Qup, i, c));
2758 p["Util_lo"].push_back(v(iv.Ulo, i, c));
2759 p["Util_up"].push_back(v(iv.Uup, i, c));
2760 p["RespT_lo"].push_back(v(iv.Rlo, i, c));
2761 p["RespT_up"].push_back(v(iv.Rup, i, c));
2762 p["Tput_lo"].push_back(v(iv.Tlo, i, c));
2763 p["Tput_up"].push_back(v(iv.Tup, i, c));
2764 }
2765 if (g_json_output) emit_analysis<T>("interval", p, iv.method);
2766 return 0;
2767}
2768
2769/**
2770 * Solve a Network model.json carrying a Prior with SolverUQ.
2771 *
2772 * TWO FLAGS MEAN SOMETHING ELSE HERE, and both are UQ's own rather than the
2773 * stage solver's: `--method` names the DESIGN (quad or mc, the
2774 * reference's `options.method`), and `--samples` the number of nodes per
2775 * continuous Prior (`options.samples`, 11 by default and not the simulation
2776 * default, since each node is a full solver run). The engine that runs at each
2777 * point is `--uq-solver`, and it keeps its own defaults for everything except
2778 * the convergence knobs, which UQ does not have and therefore passes through.
2779 * A caller who wants an SSA run length AND a UQ design cannot state both, so
2780 * the SSA stage keeps its default sample count; that is stated in --help rather
2781 * than resolved by giving one flag two meanings.
2782 *
2783 * `-a posterior` prints the design itself -- every point, its weight and its
2784 * metrics -- because the expectation alone hides whether it averaged two nearby
2785 * models or two wildly different ones, and that spread IS the answer to an
2786 * uncertainty question.
2787 */
2788template <class T>
2789int solve_model_uq(const std::string& file, const Knobs& k, const std::string& analysis) {
2790 line::qn::Network<T> net = read_model<T>(file);
2792 if (!k.method.empty()) opt.method = k.method;
2793 if (k.samples) opt.samples = k.samples;
2794 if (k.seed) opt.seed = k.seed;
2796 so.solver = k.uq_solver;
2797 so.tol = k.tol;
2798 so.iter_tol = k.iter_tol;
2799 so.iter_max = k.iter_max;
2800 so.cutoff = k.cutoff;
2801
2802 if (analysis == "interval") {
2803 // BEFORE THE ENSEMBLE, because the exact path does not need one: it is
2804 // 2*(m+2) MVA calls over the demand box, and the reference's
2805 // `getInterval` likewise reaches `intervalByMVA` without touching
2806 // `self.results`. Only the sampling fallback solves the design.
2807 const line::uq::UqInterval<T> iv =
2809 const line::qn::NetworkStruct<T>& isn = net.get_struct();
2810 return print_uq_interval<T>(isn, iv, so.solver, line::uq::uq_detect_priors(isn).size());
2811 }
2812
2813 const line::uq::UqSolution<T> r =
2815 const line::qn::NetworkStruct<T>& sn = net.get_struct();
2816
2817 if (analysis == "avg") {
2818 if (!g_json_output)
2819 std::printf("SolverUQ arith=%s design=%s points=%zu priors=%zu stage=%s method=%s\n",
2820 line::num_traits<T>::name(), r.method.c_str(), r.points.size(),
2821 r.sites.size(), so.solver.c_str(), r.avg.actualmethod.c_str());
2822 print_avg_table<T>(sn, r.avg);
2823 return 0;
2824 }
2825
2826 // -a posterior: the per-design-point table, the reference's getPosteriorTable.
2827 line::reg::Json p = line::reg::Json::object();
2828 p["type"] = "PosteriorTable";
2829 p["indexBase"] = 0;
2830 p["design"] = r.method;
2831 p["stage"] = so.solver;
2832 line::reg::Json sites = line::reg::Json::array();
2833 for (std::size_t l = 0; l < r.sites.size(); ++l) {
2834 line::reg::Json s = line::reg::Json::object();
2835 s["node"] = sn.nodes[r.sites[l].node - 1].name;
2836 s["class"] = sn.classes[r.sites[l].cls - 1].name;
2837 s["kind"] = r.sites[l].arrival ? "arrival" : "service";
2838 sites.push_back(s);
2839 }
2840 p["priors"] = sites;
2841 for (const char* key : {"Point", "Weight", "Station", "JobClass", "QLen", "Util", "RespT",
2842 "Tput"})
2843 p[key] = line::reg::Json::array();
2844 line::reg::Json means = line::reg::Json::array();
2845
2846 if (!g_json_output) {
2847 std::printf("SolverUQ arith=%s design=%s points=%zu priors=%zu stage=%s\n",
2848 line::num_traits<T>::name(), r.method.c_str(), r.points.size(), r.sites.size(),
2849 so.solver.c_str());
2850 // THE SUBSTITUTED MEANS ARE PROVENANCE, not decoration: a design point
2851 // is a model, and this line is what says which one.
2852 std::printf("%-6s %12s substituted means\n", "Point", "Weight");
2853 for (std::size_t e = 0; e < r.points.size(); ++e) {
2854 std::printf("%-6zu %12.6g ", e + 1, line::num_traits<T>::to_double(r.weights[e]));
2855 for (std::size_t l = 0; l < r.sites.size(); ++l)
2856 std::printf(" %s@%s=%.6g", sn.nodes[r.sites[l].node - 1].name.c_str(),
2857 sn.classes[r.sites[l].cls - 1].name.c_str(),
2858 line::num_traits<T>::to_double(r.design[e].dists[l].mean));
2859 std::printf("\n");
2860 }
2861 std::printf("%-6s %12s %-16s %-14s %12s %12s %12s %12s\n", "Point", "Weight", "Station",
2862 "JobClass", "QLen", "Util", "RespT", "Tput");
2863 }
2864 for (std::size_t e = 0; e < r.points.size(); ++e) {
2865 line::reg::Json row = line::reg::Json::array();
2866 for (std::size_t l = 0; l < r.sites.size(); ++l)
2867 row.push_back(line::num_traits<T>::to_double(r.design[e].dists[l].mean));
2868 means.push_back(row);
2869 const line::mva::AvgResult<T>& a = r.points[e];
2870 for (std::size_t i = 0; i < sn.nstations; ++i)
2871 for (std::size_t c = 0; c < sn.nclasses; ++c) {
2872 const double q = line::num_traits<T>::to_double(a.QN(i, c));
2873 const double u = line::num_traits<T>::to_double(a.UN(i, c));
2874 const double rr = line::num_traits<T>::to_double(a.RN(i, c));
2875 const double t = line::num_traits<T>::to_double(a.TN(i, c));
2876 // getPosteriorTable's row filter, the PRESENCE metrics only: a
2877 // response time alone does not put a class at a station, and
2878 // reading it as presence kept rows the reference drops.
2879 if (q <= 0.0 && u <= 0.0 && t <= 0.0) continue;
2880 if (!g_json_output) {
2881 std::printf("%-6zu %12.6g %-16s %-14s %12.6g %12.6g %12.6g %12.6g\n", e + 1,
2883 sn.stations[i].name.c_str(), sn.classes[c].name.c_str(), q, u, rr,
2884 t);
2885 continue;
2886 }
2887 p["Point"].push_back(e);
2888 p["Weight"].push_back(line::num_traits<T>::to_double(r.weights[e]));
2889 p["Station"].push_back(sn.stations[i].name);
2890 p["JobClass"].push_back(sn.classes[c].name);
2891 p["QLen"].push_back(q);
2892 p["Util"].push_back(u);
2893 p["RespT"].push_back(rr);
2894 p["Tput"].push_back(t);
2895 }
2896 }
2897 if (g_json_output) {
2898 p["substitutedMean"] = means;
2899 emit_analysis<T>("posterior", p, r.avg.actualmethod);
2900 }
2901 return 0;
2902}
2903
2904/**
2905 * The banner every `-s ctmc` analysis opens with.
2906 *
2907 * It carries the state count and the cutoff because a CTMC number is not the
2908 * model's number without them: the space is what was enumerated, and on an open
2909 * model the cutoff is what truncated it.
2910 */
2911template <class T>
2912void print_ctmc_banner(const line::ctmc::CtmcSolution<T>& d) {
2913 std::size_t cut = 0;
2914 for (std::size_t i = 0; i < d.cutoff.size(); ++i) cut = std::max(cut, d.cutoff[i]);
2915 if (cut)
2916 std::printf("SolverCTMC arith=%s method=%s type=%s states=%zu cutoff=%zu\n",
2918 line::util::method_type("CTMC", d.actualmethod).c_str(), d.chain.space.size(),
2919 cut);
2920 else
2921 std::printf("SolverCTMC arith=%s method=%s type=%s states=%zu\n",
2923 line::util::method_type("CTMC", d.actualmethod).c_str(), d.chain.space.size());
2924 // The library never writes to stderr, so an unseeded reducible mixture is
2925 // reported here or not at all -- and it is the one case where the printed
2926 // distribution is not the model's.
2927 if (!d.warning.empty()) std::fprintf(stderr, "warning: %s\n", d.warning.c_str());
2928}
2929
2930/**
2931 * The banner's own content as JSON, added to every `-s ctmc` payload.
2932 *
2933 * A CTMC number is not the model's number without them, which is why the
2934 * readable banner carries them: the space is what was actually enumerated, and
2935 * on an open model the cutoff is what truncated it. A host that reported the
2936 * occupancy of a truncated chain as the model's would be reporting a different
2937 * model's answer, so the two travel with the payload rather than only above it.
2938 */
2939template <class T>
2940line::reg::Json ctmc_meta(const line::ctmc::CtmcSolution<T>& d) {
2941 line::reg::Json m = line::reg::Json::object();
2942 m["states"] = d.chain.space.size();
2943 std::size_t cut = 0;
2944 for (std::size_t i = 0; i < d.cutoff.size(); ++i) cut = std::max(cut, d.cutoff[i]);
2945 if (cut) m["cutoff"] = cut;
2946 return m;
2947}
2948
2949/**
2950 * `-a avg`: the AvgTable, on whichever path the model's regions require.
2951 *
2952 * `solver_ctmc_analyzer_any` and not `solver_ctmc_analyzer`, so a WAITQ region
2953 * reaches the augmented walk that carries its token FIFO instead of the
2954 * lattice analyzer, which refuses it. Every other region rule keeps refusing.
2955 */
2956template <class T>
2957int solve_ctmc_avg(const line::qn::NetworkStruct<T>& sn, const line::ctmc::CtmcOptions& opt) {
2960 print_ctmc_banner<T>(a.sol);
2961 print_avg_table<T>(sn, r);
2962 // A PARKED JOB IS IN NO QLen COLUMN: it left its station and sits in the
2963 // region's FIFO, so the model's population balances only once this is read
2964 // alongside the table rather than instead of it.
2965 if (a.waitq) {
2966 std::printf("%-16s %-14s %12s\n", "Region", "JobClass", "Parked");
2967 for (std::size_t c = 0; c < sn.nclasses && c < a.parked.size(); ++c)
2968 std::printf("%-16s %-14s %12.6g\n", "(all)", sn.classes[c].name.c_str(),
2970 }
2971 return 0;
2972}
2973
2974/**
2975 * `-a avg` under `--method mdd`: the AvgTable from the level aggregation.
2976 *
2977 * A SEPARATE ARM, and not a branch inside `solve_ctmc_avg`, because the method
2978 * never forms the |S|-state generator: there is no state space to print a state
2979 * count from and no cutoff to report, so the banner is the diagram's own -- the
2980 * cardinality it counts symbolically, what the levels actually hold, and whether
2981 * the answer is certified exact. Reporting the generator banner here would name
2982 * a chain that was never built.
2983 */
2984template <class T>
2985int solve_ctmc_mdd_avg(const line::qn::NetworkStruct<T>& sn, const line::ctmc::CtmcOptions& opt,
2986 const line::mdd::MddMcdOptions& mcdopt) {
2987 // EVERY BACKEND, `exact` included: the level solve picks Householder QR in
2988 // floating point and `line::lstsq` under exact arithmetic, so nothing here
2989 // takes a square root that a rational field has no answer for.
2992 d.avg = s.avg;
2995 std::size_t held = 0;
2996 for (std::size_t k = 0; k < s.level_sizes.size(); ++k) held += s.level_sizes[k];
2997 std::printf(
2998 "SolverCTMC arith=%s method=%s type=%s states=%lld held=%zu levels=%zu iters=%d "
2999 "encoding=%s exact=%s\n",
3001 line::util::method_type("CTMC", s.actualmethod).c_str(), s.num_states, held,
3002 s.level_sizes.size(), s.iters, s.encoding.c_str(),
3003 // "certified" is not "exact": a product-form model is exact however
3004 // much its diagram shares, so the false case says only that the
3005 // STRUCTURAL test did not fire.
3006 s.no_aggregation ? "certified" : "product-form-only");
3007 print_avg_table<T>(sn, r);
3008 return 0;
3009}
3010
3011/**
3012 * `-a prob`: the four SolverCTMC probability queries over the model's default
3013 * initial state -- `getProbSys`, `getProbSysAggr`, and `getProb`/`getProbAggr`
3014 * per station.
3015 *
3016 * ALL FOUR AND NOT ONE, because the joint and the aggregate answer different
3017 * questions and the pair is what makes either readable: `getProbSys` is the
3018 * probability of exactly that state, phases and buffer arrangement included,
3019 * while `getProbSysAggr` sums over every arrangement realizing the same
3020 * per-class counts. On a single-phase model with no buffer ordering the two
3021 * coincide, and where they do not the ratio is what the encoding added.
3022 *
3023 * NOT THE SAME NUMBERS AS `-s mva -a prob` OR `-s nc -a prob`, and that is the
3024 * point of having all three: MVA fits a binomial to its own means and NC takes a
3025 * ratio of normalizing constants under the product form, whereas these are the
3026 * stationary law of the chain itself and are exact for any model the chain
3027 * represents, product-form or not.
3028 */
3029template <class T>
3030int solve_ctmc_prob(const line::qn::NetworkStruct<T>& sn, const line::ctmc::CtmcOptions& opt,
3031 const Knobs& k) {
3034 if (!line::ctmc::analyzer_detail::default_init_state(sn, init))
3035 throw line::InputError(line::ErrorKind{"Model"},
3036 "-a prob reports the probability of the model's DEFAULT INITIAL STATE, and this "
3037 "model's initial marking admits no state; check the class populations against their "
3038 "reference stations");
3039 // `--state` is `getProb(node, state)`'s second argument: the ENCODED ROW of
3040 // one stateful node's own state space, not a per-class job count. The
3041 // reference substitutes it into `sn.state{node}` and leaves every other
3042 // node at its default, which is what happens here -- so the station
3043 // marginals below are the requested state's, and the two system
3044 // probabilities are that state's joined with the rest of the default
3045 // marking, exactly as `setState` followed by `getProbSys` reports it.
3046 if (!k.state.empty()) {
3047 if (!k.node)
3048 throw line::InputError(
3049 "--state is the state of ONE node and needs --node to say which; a bare state "
3050 "vector cannot be matched against a network whose nodes have different widths");
3051 const std::size_t isf = sn.stateful_index(k.node);
3052 if (isf == 0)
3053 throw line::InputError("--node " + std::to_string(k.node) +
3054 " is not a stateful node, so it holds no state to ask about");
3055 // THE WIDTH MUST MATCH EXACTLY, and a short vector is refused rather
3056 // than padded. Every row of a node's block is stored at the node's
3057 // widest encoding, so a padded row IS a state -- just not the one the
3058 // caller named: on an FCFS queue holding two jobs the encoding is
3059 // (buffer, in-service phase count) = (1,1), and padding `--state 2` to
3060 // (0,2) names a state the chain never visits, which would answer 0
3061 // where the caller expected the marginal. The width is reported so the
3062 // next attempt can be right.
3063 const std::size_t w = d.chain.space.empty() ? k.state.size()
3064 : d.chain.space[0].local[isf - 1].size();
3065 if (k.state.size() != w)
3066 throw line::InputError(
3067 "--state has " + std::to_string(k.state.size()) + " entries but node " +
3068 std::to_string(k.node) + " encodes its state in " + std::to_string(w) +
3069 "; getProb(node, state) takes the node's whole encoded row, and a shorter one "
3070 "padded with zeros is a different state rather than a partial one (use -a marg "
3071 "for a per-class job-count marginal)");
3072 std::vector<T> row(w, line::num_traits<T>::from_int(0));
3073 for (std::size_t i = 0; i < k.state.size(); ++i)
3074 row[i] = line::num_traits<T>::from_int(k.state[i]);
3075 init.local[isf - 1] = row;
3076 }
3077 const T psys = line::ctmc::solver_ctmc_joint(sn, d, init);
3078 const T psysaggr = line::ctmc::solver_ctmc_jointaggr(sn, d, init);
3079 const std::vector<T> pmarg = line::ctmc::solver_ctmc_marg(sn, d, init);
3080 const std::vector<T> pmargaggr = line::ctmc::solver_ctmc_margaggr(sn, d, init);
3081
3082 if (g_json_output) {
3083 line::reg::Json p = line::reg::Json::object();
3084 p["type"] = "ProbAggr";
3085 p["indexBase"] = 0;
3086 p["ProbSys"] = line::num_traits<T>::to_double(psys);
3087 p["ProbSysAggr"] = line::num_traits<T>::to_double(psysaggr);
3088 line::reg::Json st = line::reg::Json::array(), pm = line::reg::Json::array(),
3089 pa = line::reg::Json::array();
3090 for (std::size_t i = 0; i < sn.nstations; ++i) {
3091 st.push_back(sn.stations[i].name);
3092 pm.push_back(line::num_traits<T>::to_double(pmarg[i]));
3093 pa.push_back(line::num_traits<T>::to_double(pmargaggr[i]));
3094 }
3095 p["Station"] = st;
3096 p["Prob"] = pm;
3097 p["ProbAggr"] = pa;
3098 emit_analysis<T>("prob", p, d.actualmethod, ctmc_meta<T>(d));
3099 return 0;
3100 }
3101 print_ctmc_banner<T>(d);
3102 std::printf("ProbSys %.10g\n", line::num_traits<T>::to_double(psys));
3103 std::printf("ProbSysAggr %.10g\n", line::num_traits<T>::to_double(psysaggr));
3104 std::printf("%-16s %14s %14s\n", "Station", "Prob", "ProbAggr");
3105 for (std::size_t i = 0; i < sn.nstations; ++i)
3106 std::printf("%-16s %14.10g %14.10g\n", sn.stations[i].name.c_str(),
3108 line::num_traits<T>::to_double(pmargaggr[i]));
3109 return 0;
3110}
3111
3112/**
3113 * The derived START/PREEMPT filtration as one JSON block per (station, class),
3114 * each carrying its own 0-based Station and Class beside the usual From/To/Rate
3115 * triplets. An all-zero block is omitted: on a model with no preemption that is
3116 * every block of the PREEMPT filtration.
3117 */
3118template <class T>
3119line::reg::Json aux_filt_json(const std::vector<std::vector<line::Matrix<T> > >& filt,
3120 std::size_t n) {
3121 line::reg::Json blocks = line::reg::Json::array();
3122 for (std::size_t i = 0; i < filt.size(); ++i)
3123 for (std::size_t r = 0; r < filt[i].size(); ++r) {
3124 line::reg::Json bfrom = line::reg::Json::array(), bto = line::reg::Json::array(),
3125 brate = line::reg::Json::array();
3126 for (std::size_t a = 0; a < n; ++a)
3127 for (std::size_t b = 0; b < n; ++b) {
3128 const double q = line::num_traits<T>::to_double(filt[i][r](a, b));
3129 if (q == 0.0) continue;
3130 bfrom.push_back(a);
3131 bto.push_back(b);
3132 brate.push_back(q);
3133 }
3134 if (bfrom.empty()) continue;
3135 line::reg::Json e = line::reg::Json::object();
3136 e["Station"] = i;
3137 e["Class"] = r;
3138 e["From"] = bfrom;
3139 e["To"] = bto;
3140 e["Rate"] = brate;
3141 blocks.push_back(e);
3142 }
3143 return blocks;
3144}
3145
3146/**
3147 * `-a gen`: `getInfGen`, as Q in sparse triplets plus the synchronization list
3148 * its event filtration is indexed by.
3149 *
3150 * Q IS PRINTED SPARSELY. A generator's rows hold one entry per enabled
3151 * transition and the space can run to thousands of states, so the dense form
3152 * would be quadratic in a quantity that is linear in the model.
3153 */
3154template <class T>
3155int solve_ctmc_gen(const line::qn::NetworkStruct<T>& sn, const line::ctmc::CtmcOptions& opt) {
3157 o.keep_filtration = true; // the filtration is half of what getInfGen returns
3160 const std::size_t n = g.Q.rows();
3161 std::size_t nnz = 0;
3162 for (std::size_t i = 0; i < n; ++i)
3163 for (std::size_t j = 0; j < n; ++j)
3164 if (line::num_traits<T>::to_double(g.Q(i, j)) != 0.0) ++nnz;
3165 if (g_json_output) {
3166 line::reg::Json p = line::reg::Json::object();
3167 p["type"] = "InfGen";
3168 p["indexBase"] = 0;
3169 p["size"] = n;
3170 p["nnz"] = nnz;
3171 // SPARSE HERE TOO, for the reason the table is: a generator has one entry
3172 // per enabled transition, so the dense form is quadratic in a quantity
3173 // that is linear in the model. A host rebuilds Q with one scatter.
3174 line::reg::Json from = line::reg::Json::array(), to = line::reg::Json::array(),
3175 rate = line::reg::Json::array();
3176 for (std::size_t i = 0; i < n; ++i)
3177 for (std::size_t j = 0; j < n; ++j) {
3178 const double q = line::num_traits<T>::to_double(g.Q(i, j));
3179 if (q == 0.0) continue;
3180 from.push_back(i);
3181 to.push_back(j);
3182 rate.push_back(q);
3183 }
3184 p["From"] = from;
3185 p["To"] = to;
3186 p["Rate"] = rate;
3187 // The synchronization list is HALF of what getInfGen returns: without it
3188 // the filtration's index has no meaning, so it travels with Q. Its node
3189 // and class are the port's own 1-BASED indices, with 0 the LOCAL dummy
3190 // -- `indexBase` above governs the state indices, which is where a host
3191 // would otherwise be indexing a chain by an off-by-one.
3192 line::reg::Json sync = line::reg::Json::array();
3193 for (std::size_t a = 0; a < g.sync.size() && a < g.filt.size(); ++a) {
3194 // THE FILTER ITSELF, not only its nnz as the readable table reports:
3195 // `eventFilt` is half of what getInfGen returns, and a host handed
3196 // only Q cannot recover which synchronization contributed a rate --
3197 // Q's entries have already summed every one of them.
3198 std::size_t fnz = 0;
3199 line::reg::Json ffrom = line::reg::Json::array(), fto = line::reg::Json::array(),
3200 frate = line::reg::Json::array();
3201 for (std::size_t i = 0; i < n; ++i)
3202 for (std::size_t j = 0; j < n; ++j) {
3203 const double q = line::num_traits<T>::to_double(g.filt[a](i, j));
3204 if (q == 0.0) continue;
3205 ++fnz;
3206 ffrom.push_back(i);
3207 fto.push_back(j);
3208 frate.push_back(q);
3209 }
3210 line::reg::Json e = line::reg::Json::object();
3211 e["From"] = ffrom;
3212 e["To"] = fto;
3213 e["Rate"] = frate;
3214 e["activeEvent"] = line::lang::event_to_text(g.sync[a].active.event);
3215 e["activeNode"] = g.sync[a].active.node;
3216 e["activeClass"] = g.sync[a].active.cls;
3217 e["passiveEvent"] = line::lang::event_to_text(g.sync[a].passive.event);
3218 e["passiveNode"] = g.sync[a].passive.node;
3219 e["passiveClass"] = g.sync[a].passive.cls;
3220 e["nnz"] = fnz;
3221 sync.push_back(e);
3222 }
3223 p["sync"] = sync;
3224 // The DERIVED filtrations travel under their own keys, one block per
3225 // (station, class), because they are NOT synchronizations: a START
3226 // rides on an arc `sync` already carries, so folding them in would make
3227 // a host summing the filtration double-count the generator.
3228 p["startFilt"] = aux_filt_json<T>(g.start_filt, n);
3229 p["preemptFilt"] = aux_filt_json<T>(g.preempt_filt, n);
3230 emit_analysis<T>("gen", p, d.actualmethod, ctmc_meta<T>(d));
3231 return 0;
3232 }
3233 print_ctmc_banner<T>(d);
3234 std::printf("InfGen events=%zu nnz=%zu\n", g.sync.size(), nnz);
3235 std::printf("%8s %8s %16s\n", "From", "To", "Rate");
3236 for (std::size_t i = 0; i < n; ++i)
3237 for (std::size_t j = 0; j < n; ++j) {
3238 const double q = line::num_traits<T>::to_double(g.Q(i, j));
3239 if (q != 0.0) std::printf("%8zu %8zu %16.10g\n", i + 1, j + 1, q);
3240 }
3241 std::printf("%6s %-10s %6s %6s %-10s %6s %6s %8s\n", "Event", "ActEvent", "ActNode", "ActCls",
3242 "PasEvent", "PasNode", "PasCls", "Nnz");
3243 for (std::size_t a = 0; a < g.sync.size() && a < g.filt.size(); ++a) {
3244 std::size_t fnz = 0;
3245 for (std::size_t i = 0; i < n; ++i)
3246 for (std::size_t j = 0; j < n; ++j)
3247 if (line::num_traits<T>::to_double(g.filt[a](i, j)) != 0.0) ++fnz;
3248 std::printf("%6zu %-10s %6zu %6zu %-10s %6zu %6zu %8zu\n", a + 1,
3249 line::lang::event_to_text(g.sync[a].active.event), g.sync[a].active.node,
3250 g.sync[a].active.cls, line::lang::event_to_text(g.sync[a].passive.event),
3251 g.sync[a].passive.node, g.sync[a].passive.cls, fnz);
3252 }
3253 return 0;
3254}
3255
3256/** `-a states`: `getStateSpace` and `getStateSpaceAggr`, side by side. */
3257template <class T>
3258int solve_ctmc_states(const line::qn::NetworkStruct<T>& sn, const line::ctmc::CtmcOptions& opt) {
3262 if (g_json_output) {
3263 line::reg::Json p = line::reg::Json::object();
3264 p["type"] = "StateSpace";
3265 p["indexBase"] = 0;
3266 // The per-node widths are the ONLY thing that makes a flat row decodable:
3267 // they are where one stateful node's block ends and the next begins.
3268 p["NodeWidths"] = index_json(s.node_width);
3269 p["space"] = matrix_json(s.flat);
3270 p["spaceAggr"] = matrix_json(A);
3271 // `localStateSpace` of `[stateSpace, localStateSpace] = getStateSpace`.
3272 // One entry per stateful node, in stateful-node order, holding that
3273 // node's distinct local rows. A host with only the flat space can
3274 // return the second output as a SINGLE cell holding the whole space,
3275 // which is what `getStateSpace.m` does under `lang='cpp'`, and a caller
3276 // indexing it per node then reads the global space for every node.
3277 line::reg::Json loc = line::reg::Json::array();
3278 for (std::size_t f = 0; f < s.local.size(); ++f) loc.push_back(matrix_json(s.local[f]));
3279 p["localSpace"] = loc;
3280 // pi travels with the space because a row of the space is not an answer:
3281 // the pair (state, probability) is, and reading them from two invocations
3282 // would risk pairing one solve's states with another solve's law.
3283 p["pi"] = vector_json(d.pi);
3284 emit_analysis<T>("states", p, d.actualmethod, ctmc_meta<T>(d));
3285 return 0;
3286 }
3287 print_ctmc_banner<T>(d);
3288 // The per-node widths are printed because the flat row is only decodable
3289 // with them: they are where one node's block ends and the next begins.
3290 std::printf("NodeWidths");
3291 for (std::size_t f = 0; f < s.node_width.size(); ++f) std::printf(" %zu", s.node_width[f]);
3292 std::printf("\n");
3293 std::printf("%8s %12s %s\n", "State", "Prob", "Detailed | Aggregate");
3294 for (std::size_t i = 0; i < s.flat.rows(); ++i) {
3295 std::printf("%8zu %12.6g ", i + 1, line::num_traits<T>::to_double(d.pi[i]));
3296 for (std::size_t c = 0; c < s.flat.cols(); ++c)
3297 std::printf(" %g", line::num_traits<T>::to_double(s.flat(i, c)));
3298 std::printf(" |");
3299 for (std::size_t c = 0; c < A.cols(); ++c)
3300 std::printf(" %g", line::num_traits<T>::to_double(A(i, c)));
3301 std::printf("\n");
3302 }
3303 return 0;
3304}
3305
3306/**
3307 * `-a sens`: `getSensitivityRanking` over the exponential service rates.
3308 *
3309 * THE REWARD IS STATED, NOT INFERRED. The reference makes the caller supply one,
3310 * and a model.json carries no reward function, so the CLI has to name the reward
3311 * it ranks against or the numbers mean nothing: it is the mean number of jobs at
3312 * the QUEUEING stations, which excludes the Source (whose column is the infinite
3313 * reservoir) and the Delay stations (whose population is think time, not work).
3314 *
3315 * Only an exponential service pair becomes a parameter. Perturbing any other
3316 * distribution would mean replacing it with an exponential of the new rate,
3317 * which changes the model's shape rather than one of its parameters; those pairs
3318 * are listed as skipped rather than silently differenced.
3319 */
3320template <class T>
3321int solve_ctmc_sens(const line::qn::NetworkStruct<T>& sn, const line::ctmc::CtmcOptions& opt) {
3322 const std::size_t M = sn.nstations, K = sn.nclasses;
3325
3326 std::vector<bool> queueing(M, false);
3327 for (std::size_t i = 0; i < M; ++i)
3328 queueing[i] = sn.stations[i].nodetype != line::lang::NodeType::Source &&
3331
3332 std::vector<T> reward(d.chain.space.size(), line::num_traits<T>::from_int(0));
3333 for (std::size_t s = 0; s < reward.size(); ++s)
3334 for (std::size_t i = 0; i < M; ++i)
3335 if (queueing[i])
3336 for (std::size_t c = 0; c < K; ++c) reward[s] += A(s, i * K + c);
3337
3338 std::vector<line::ctmc::CtmcSensParam<T> > params;
3339 std::vector<std::string> skipped;
3340 for (std::size_t i = 0; i < M; ++i) {
3341 if (sn.stations[i].nodetype == line::lang::NodeType::Source) continue;
3342 for (std::size_t c = 0; c < K; ++c) {
3343 if (sn.disabled[i][c]) continue;
3344 const double mu = line::num_traits<T>::to_double(sn.rates(i, c));
3345 if (!(mu > 0.0)) continue;
3346 const std::string nm =
3347 "mu(" + sn.stations[i].name + "," + sn.classes[c].name + ")";
3348 if (sn.service[i][c].type != line::lang::ProcessType::EXP) {
3349 skipped.push_back(nm);
3350 continue;
3351 }
3353 p.name = nm;
3354 p.value = mu;
3355 p.set = [i, c](line::qn::NetworkStruct<T>& s, double v) {
3357 s.refresh_rates();
3358 };
3359 params.push_back(p);
3360 }
3361 }
3362 if (params.empty())
3363 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
3364 "-a sens found no exponential service rate to differentiate: every enabled "
3365 "(station, class) pair carries a non-exponential distribution, and replacing one with "
3366 "an exponential of the perturbed rate would change the model rather than a parameter "
3367 "of it");
3368
3369 const std::vector<line::ctmc::CtmcSensRank<T> > rank =
3370 line::ctmc::solver_ctmc_sensitivity_ranking(sn, opt, params, reward);
3371 if (g_json_output) {
3372 line::reg::Json p = line::reg::Json::object();
3373 p["type"] = "SensRanking";
3374 // THE REWARD IS STATED, NOT INFERRED, on this path too: a ranking is a
3375 // ranking against something, and a host that read these numbers without
3376 // knowing what was differentiated would be reading a sensitivity of an
3377 // unnamed functional.
3378 p["reward"] = "mean number of jobs at the queueing stations";
3379 line::reg::Json par = line::reg::Json::array(), val = line::reg::Json::array(),
3380 S = line::reg::Json::array(), SS = line::reg::Json::array();
3381 for (std::size_t l = 0; l < rank.size(); ++l) {
3382 par.push_back(rank[l].parameter);
3383 val.push_back(rank[l].value);
3384 S.push_back(line::num_traits<T>::to_double(rank[l].S));
3385 // null, not NaN and not 0: a zero mean reward makes the scaled form
3386 // undefined, which is a property of the model, and JSON has no NaN.
3387 if (rank[l].scaled_valid)
3388 SS.push_back(line::num_traits<T>::to_double(rank[l].SS));
3389 else
3390 SS.push_back(line::reg::Json());
3391 }
3392 p["Parameter"] = par;
3393 p["Value"] = val;
3394 p["Sens"] = S;
3395 p["ScaledSens"] = SS;
3396 line::reg::Json sk = line::reg::Json::array();
3397 for (std::size_t l = 0; l < skipped.size(); ++l) sk.push_back(skipped[l]);
3398 p["Skipped"] = sk;
3399 emit_analysis<T>("sens", p, d.actualmethod, ctmc_meta<T>(d));
3400 return 0;
3401 }
3402 print_ctmc_banner<T>(d);
3403 std::printf("Reward mean number of jobs at the queueing stations\n");
3404 std::printf("%-28s %14s %16s %16s\n", "Parameter", "Value", "Sens", "ScaledSens");
3405 for (std::size_t l = 0; l < rank.size(); ++l) {
3406 if (rank[l].scaled_valid)
3407 std::printf("%-28s %14.6g %16.8g %16.8g\n", rank[l].parameter.c_str(), rank[l].value,
3409 line::num_traits<T>::to_double(rank[l].SS));
3410 else
3411 // MATLAB reports NaN here; the reason is printed instead, since a
3412 // zero mean reward is a property of the model and not a failure.
3413 std::printf("%-28s %14.6g %16.8g %16s\n", rank[l].parameter.c_str(), rank[l].value,
3414 line::num_traits<T>::to_double(rank[l].S), "undefined(E[r]=0)");
3415 }
3416 for (std::size_t l = 0; l < skipped.size(); ++l)
3417 std::printf("Skipped %s: service is not exponential\n", skipped[l].c_str());
3418 return 0;
3419}
3420
3421/** `-a reward`: `getAvgReward`, the steady-state expectation of each reward. */
3422template <class T>
3423int solve_ctmc_reward(const line::qn::NetworkStruct<T>& sn, const line::ctmc::CtmcOptions& opt) {
3424 std::vector<std::string> names;
3425 const std::vector<T> r = line::ctmc::solver_ctmc_avg_reward(sn, opt, &names);
3426 if (g_json_output) {
3427 line::reg::Json p = line::reg::Json::object();
3428 p["type"] = "AvgReward";
3429 line::reg::Json nm = line::reg::Json::array();
3430 for (std::size_t l = 0; l < names.size(); ++l) nm.push_back(names[l]);
3431 p["Reward"] = nm;
3432 p["E"] = vector_json(r);
3433 // NO "method": this arm returns the expectations and no solved chain, so
3434 // there is no resolved method to report and none is invented.
3435 emit_analysis<T>("reward", p, std::string());
3436 return 0;
3437 }
3438 std::printf("SolverCTMC arith=%s rewards=%zu\n", line::num_traits<T>::name(), r.size());
3439 std::printf("%-28s %16s\n", "Reward", "E[r]");
3440 for (std::size_t l = 0; l < r.size(); ++l)
3441 std::printf("%-28s %16.10g\n", names[l].c_str(), line::num_traits<T>::to_double(r[l]));
3442 return 0;
3443}
3444
3445/**
3446 * `-a reward-value`: `@@SolverCTMC/getRewardValueFunction`, V^k(s).
3447 *
3448 * A DIFFERENT OBJECT FROM BOTH `-a reward` AND `-a tranreward`. `-a reward`
3449 * returns one number per reward, the steady-state E[r]; `-a tranreward` the
3450 * expected rate along a horizon; this returns the VALUE FUNCTION of ONE named
3451 * reward -- the reward accumulated over k uniformized steps, from every state
3452 * of the chain, as a (Tmax+1 x nstates) matrix. It is the object a policy
3453 * evaluation reads, and it is indexed by state, not by station.
3454 *
3455 * `--reward-name` IS REQUIRED and not defaulted to the first declared reward:
3456 * the value functions of two rewards are different matrices, and labelling one
3457 * with the caller's question would be a wrong answer rather than a missing one.
3458 */
3459template <class T>
3460int solve_ctmc_reward_value(const line::qn::NetworkStruct<T>& sn,
3461 const line::ctmc::CtmcOptions& opt, const Knobs& k) {
3462 if (k.reward_name.empty())
3463 throw line::InputError(
3464 "-a reward-value returns the value function of ONE reward and needs --reward-name to "
3465 "say which; -a reward returns the steady-state expectation of every declared reward");
3467 std::size_t which = rr.names.size();
3468 for (std::size_t l = 0; l < rr.names.size(); ++l)
3469 if (rr.names[l] == k.reward_name) which = l;
3470 if (which == rr.names.size()) {
3471 std::string avail;
3472 for (std::size_t l = 0; l < rr.names.size(); ++l)
3473 avail += (l ? ", " : "") + rr.names[l];
3474 throw line::InputError("--reward-name '" + k.reward_name +
3475 "' is not declared by this model; it declares: " +
3476 (avail.empty() ? std::string("(none)") : avail));
3477 }
3478 const line::Matrix<T>& V = rr.V[which];
3479
3480 if (g_json_output) {
3481 line::reg::Json p = line::reg::Json::object();
3482 p["type"] = "RewardValueFunction";
3483 p["indexBase"] = 0;
3484 p["Reward"] = rr.names[which];
3485 p["steps"] = V.rows();
3486 p["states"] = V.cols();
3487 p["t"] = vector_json(rr.t);
3488 p["V"] = matrix_json(V);
3489 p["stateSpaceAggr"] = matrix_json(rr.state_space_aggr);
3490 emit_analysis<T>("rewardvalue", p, std::string());
3491 return 0;
3492 }
3493 std::printf("SolverCTMC arith=%s reward=%s steps=%zu states=%zu\n",
3494 line::num_traits<T>::name(), rr.names[which].c_str(), V.rows(), V.cols());
3495 std::printf("%-10s %-10s %20s\n", "Step", "State", "V");
3496 for (std::size_t i = 0; i < V.rows(); ++i)
3497 for (std::size_t j = 0; j < V.cols(); ++j)
3498 std::printf("%-10zu %-10zu %20.10g\n", i, j, line::num_traits<T>::to_double(V(i, j)));
3499 return 0;
3500}
3501
3502/**
3503 * `-a tranreward`: `getTranReward`, E[r(X(t))] over the --tspan horizon.
3504 *
3505 * A DIFFERENT QUANTITY FROM `-a reward`, not a formatting of it. `-a reward`
3506 * returns the steady-state expectation, one number per reward; this returns the
3507 * expected reward RATE along the trajectory, which converges to that number but
3508 * is not it at any finite t. It is also not the accumulated reward `V`, which
3509 * the same header computes and which diverges -- the header calls that the
3510 * easiest mistake to make here, so the two are kept on separate flags.
3511 *
3512 * THE HORIZON IS REQUIRED, as it is for `-a tranprob`: E[r(X(t))] on an
3513 * unstated horizon is not a quantity, and the reference refuses an infinite one
3514 * rather than picking a bound.
3515 */
3516template <class T>
3517int solve_ctmc_tran_reward(const line::qn::NetworkStruct<T>& sn,
3518 const line::ctmc::CtmcOptions& opt, const Knobs& k) {
3520 (void)sn; (void)opt; (void)k;
3521 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
3522 "-a tranreward integrates the forward equation, which needs transcendental "
3523 "arithmetic; rerun with --arith double or --arith real");
3524 } else {
3525 if (k.t1 < 0.0)
3526 throw line::InputError(
3527 "-a tranreward integrates E[r(X(t))] and needs a horizon: pass --tspan <t0>:<t1>");
3528 std::vector<std::string> names;
3529 std::vector<T> t;
3530 const std::vector<std::vector<T> > r = line::ctmc::solver_ctmc_tran_reward(
3531 sn, opt, line::num_traits<T>::from_double(k.t0),
3532 line::num_traits<T>::from_double(k.t1), &t, &names);
3533 if (g_json_output) {
3534 line::reg::Json p = line::reg::Json::object();
3535 p["type"] = "TranReward";
3536 p["indexBase"] = 0;
3537 line::reg::Json nm = line::reg::Json::array();
3538 for (std::size_t l = 0; l < names.size(); ++l) nm.push_back(names[l]);
3539 p["Reward"] = nm;
3540 p["t"] = vector_json<T>(t);
3541 line::reg::Json e = line::reg::Json::array();
3542 for (std::size_t l = 0; l < r.size(); ++l) e.push_back(vector_json<T>(r[l]));
3543 p["E"] = e;
3544 emit_analysis<T>("tranreward", p, std::string());
3545 return 0;
3546 }
3547 std::printf("SolverCTMC arith=%s rewards=%zu points=%zu tspan=[%g,%g]\n",
3548 line::num_traits<T>::name(), r.size(), t.size(), k.t0, k.t1);
3549 std::printf("%-16s", "t");
3550 for (std::size_t l = 0; l < names.size(); ++l) std::printf(" %16s", names[l].c_str());
3551 std::printf("\n");
3552 for (std::size_t i = 0; i < t.size(); ++i) {
3553 std::printf("%-16.10g", line::num_traits<T>::to_double(t[i]));
3554 for (std::size_t l = 0; l < r.size(); ++l)
3555 std::printf(" %16.10g", line::num_traits<T>::to_double(r[l][i]));
3556 std::printf("\n");
3557 }
3558 return 0;
3559 }
3560}
3561
3562/**
3563 * `-a tranprob`: pi(t) over the --tspan horizon, labelled by the whole network
3564 * (`getTranProbSys` / `getTranProbSysAggr`) or by one node when `--node` names
3565 * it (`getTranProb` / `getTranProbAggr`).
3566 *
3567 * The forward equation is integrated ONCE and both label sets are taken off the
3568 * same `CtmcTransient`. Calling the (sn, opt, ...) overloads twice would solve
3569 * and integrate the chain twice for two views of one answer.
3570 */
3571template <class T>
3572int solve_ctmc_tranprob(const line::qn::NetworkStruct<T>& sn, const line::ctmc::CtmcOptions& opt,
3573 const Knobs& k) {
3574 if (k.t1 < 0.0)
3575 throw line::InputError(
3576 "-a tranprob integrates pi(t) and needs a horizon: pass --tspan <t0>:<t1>");
3579 const line::ctmc::CtmcTranProb<T> det =
3580 k.node ? line::ctmc::ctmc_get_tran_prob(sn, tr, k.node)
3581 : line::ctmc::ctmc_get_tran_prob_sys(sn, tr);
3582 const line::ctmc::CtmcTranProb<T> agg =
3583 k.node ? line::ctmc::ctmc_get_tran_prob_aggr(sn, tr, k.node)
3584 : line::ctmc::ctmc_get_tran_prob_sys_aggr(sn, tr);
3585 if (g_json_output) {
3586 line::reg::Json p = line::reg::Json::object();
3587 p["type"] = "TranProb";
3588 p["indexBase"] = 0;
3589 p["scope"] = k.node ? sn.nodes[k.node - 1].name : std::string("(system)");
3590 if (k.node) p["node"] = k.node - 1;
3591 line::reg::Json span = line::reg::Json::array();
3592 span.push_back(k.t0);
3593 span.push_back(k.t1);
3594 // THE HORIZON IS PART OF THE ANSWER: pi(t) on an unstated span is not a
3595 // quantity, and a host that took the last row for "the" occupancy without
3596 // it would be quoting a time it does not know.
3597 p["tspan"] = span;
3598 p["t"] = vector_json(det.t);
3599 // BOTH VIEWS COME OFF ONE INTEGRATION, as on the readable path: the
3600 // detailed labels answer getTranProb(Sys) and the aggregate ones
3601 // getTranProb(Sys)Aggr, and a host asking for both would otherwise
3602 // integrate the same forward equation twice for one answer.
3603 p["labels"] = matrix_json(det.labels);
3604 p["labelsAggr"] = matrix_json(agg.labels);
3605 p["pit"] = matrix_json(det.pit);
3606 p["pitAggr"] = matrix_json(agg.pit);
3607 emit_analysis<T>("tranprob", p, tr.chain.actualmethod, ctmc_meta<T>(tr.chain));
3608 return 0;
3609 }
3610 print_ctmc_banner<T>(tr.chain);
3611 std::printf("TranProb times=%zu tspan=%g:%g scope=%s\n", det.t.size(), k.t0, k.t1,
3612 k.node ? sn.nodes[k.node - 1].name.c_str() : "(system)");
3613 // The labels come FIRST and the occupancy after, because pi(t) is a row per
3614 // time over columns that mean nothing until the state they index is named.
3615 std::printf("%8s %s\n", "State", "Detailed | Aggregate");
3616 for (std::size_t s = 0; s < det.labels.rows(); ++s) {
3617 std::printf("%8zu ", s + 1);
3618 for (std::size_t c = 0; c < det.labels.cols(); ++c)
3619 std::printf(" %g", line::num_traits<T>::to_double(det.labels(s, c)));
3620 std::printf(" |");
3621 for (std::size_t c = 0; c < agg.labels.cols(); ++c)
3622 std::printf(" %g", line::num_traits<T>::to_double(agg.labels(s, c)));
3623 std::printf("\n");
3624 }
3625 std::printf("%14s", "Time");
3626 for (std::size_t s = 0; s < det.pit.cols(); ++s) std::printf(" %12zu", s + 1);
3627 std::printf("\n");
3628 for (std::size_t i = 0; i < det.t.size(); ++i) {
3629 std::printf("%14.8g", line::num_traits<T>::to_double(det.t[i]));
3630 for (std::size_t s = 0; s < det.pit.cols(); ++s)
3631 std::printf(" %12.6g", line::num_traits<T>::to_double(det.pit(i, s)));
3632 std::printf("\n");
3633 }
3634 return 0;
3635}
3636
3637/**
3638 * `-s ctmc -a tran`: `getTranAvg`, the transient MEANS Q(t), U(t) and X(t) over
3639 * the --tspan horizon.
3640 *
3641 * NOT `-a tranprob`, AND THE TWO ARE NOT REDUCIBLE TO ONE ANOTHER FOR A CALLER.
3642 * `tranprob` sends pi(t) with the labels that index it, from which a host COULD
3643 * form these means -- and that is exactly the computation that must not happen
3644 * in a host: the utilization is not a linear functional of the labels (the PS
3645 * and DPS shares divide by the state's own total, and every other discipline
3646 * takes min(n_k, c)/c with the reference's warning attached), so a host folding
3647 * pi(t) itself would be reimplementing `solver_ctmc_transient_analyzer`'s
3648 * discipline switch and would diverge from it silently. The analyzer already
3649 * computes all three trajectories on the way to pi(t); this arm reports them.
3650 *
3651 * The payload is the SAME `TranAvgTable` the fluid and MAM transients emit, key
3652 * for key, so one host reader serves every solver that answers `-a tran`.
3653 */
3654template <class T>
3655int solve_ctmc_tran(const line::qn::NetworkStruct<T>& sn, const line::ctmc::CtmcOptions& opt,
3656 const Knobs& k) {
3657 if (k.t1 < 0.0)
3658 throw line::InputError(
3659 "-a tran integrates the forward equation and needs a horizon: pass --tspan <t0>:<t1>");
3662 const std::size_t M = sn.nstations, K = sn.nclasses, nt = tr.t.size();
3663
3664 if (g_json_output) {
3665 line::reg::Json p = line::reg::Json::object();
3666 p["type"] = "TranAvgTable";
3667 p["indexBase"] = 0;
3668 p["t0"] = k.t0;
3669 p["t1"] = k.t1;
3670 line::reg::Json ts = line::reg::Json::array();
3671 for (std::size_t j = 0; j < nt; ++j) ts.push_back(line::num_traits<T>::to_double(tr.t[j]));
3672 line::reg::Json arr = line::reg::Json::array();
3673 for (std::size_t i = 0; i < M; ++i)
3674 for (std::size_t c = 0; c < K; ++c) {
3675 // A DISABLED PAIR IS OMITTED, not sent as zeros: the reference
3676 // leaves its cell empty and the host turns an absent curve into
3677 // the disabled handle's NaN. Zeros would read as a station that
3678 // is genuinely idle for that class.
3679 if (sn.disabled[i][c]) continue;
3680 line::reg::Json e = line::reg::Json::object();
3681 e["Station"] = sn.stations[i].name;
3682 e["JobClass"] = sn.classes[c].name;
3683 e["station"] = i;
3684 e["jobclass"] = c;
3685 e["t"] = ts;
3686 line::reg::Json q = line::reg::Json::array(), u = line::reg::Json::array(),
3687 x = line::reg::Json::array();
3688 for (std::size_t j = 0; j < nt; ++j) {
3689 q.push_back(line::num_traits<T>::to_double(tr.QNt[i][c][j]));
3690 u.push_back(line::num_traits<T>::to_double(tr.UNt[i][c][j]));
3691 x.push_back(line::num_traits<T>::to_double(tr.TNt[i][c][j]));
3692 }
3693 e["QLen"] = q;
3694 e["Util"] = u;
3695 e["Tput"] = x;
3696 arr.push_back(e);
3697 }
3698 p["curves"] = arr;
3699 emit_analysis<T>("tran", p, tr.chain.actualmethod, ctmc_meta<T>(tr.chain));
3700 return 0;
3701 }
3702 print_ctmc_banner<T>(tr.chain);
3703 std::printf("TranAvg times=%zu tspan=%g:%g\n", nt, k.t0, k.t1);
3704 std::printf("%-16s %-14s %12s %12s %12s %12s\n", "Station", "JobClass", "Time", "QLen", "Util",
3705 "Tput");
3706 for (std::size_t i = 0; i < M; ++i)
3707 for (std::size_t c = 0; c < K; ++c) {
3708 if (sn.disabled[i][c]) continue;
3709 for (std::size_t j = 0; j < nt; ++j)
3710 std::printf("%-16s %-14s %12.6g %12.6g %12.6g %12.6g\n",
3711 sn.stations[i].name.c_str(), sn.classes[c].name.c_str(),
3713 line::num_traits<T>::to_double(tr.QNt[i][c][j]),
3714 line::num_traits<T>::to_double(tr.UNt[i][c][j]),
3715 line::num_traits<T>::to_double(tr.TNt[i][c][j]));
3716 }
3717 return 0;
3718}
3719
3720/**
3721 * `-a sample`: `sampleSys` and `sampleSysAggr`, one marked trajectory; with
3722 * `--node`, also that node's own block (`sample`) and per-class counts
3723 * (`sampleAggr`), which is the view MATLAB's per-node sampler returns.
3724 */
3725template <class T>
3726int solve_ctmc_sample(const line::qn::NetworkStruct<T>& sn, const line::ctmc::CtmcOptions& opt,
3727 const Knobs& k) {
3728 // `--events` NAMES THIS NUMBER, `--samples` only stands in for it. The
3729 // JAR keeps the two apart because a sampled trajectory is walked for a
3730 // number of EVENTS while `--samples` is a solver-wide run length, so a
3731 // caller who set the run length and then asked for a trajectory would
3732 // silently get one of that length. Both are honoured, --events first,
3733 // and the reference default of 1000 stands when neither is given.
3734 const std::size_t nevents = k.events ? k.events : (k.samples ? k.samples : 1000);
3735 const unsigned long seed = k.seed ? k.seed : 23000;
3737 line::ctmc::solver_ctmc_sample_sys<T>(sn, opt, nevents, seed);
3739 line::Matrix<T> L, LA;
3740 if (k.node) {
3741 L = line::ctmc::solver_ctmc_sample(sn, path, k.node);
3742 LA = line::ctmc::solver_ctmc_sample_aggr(sn, path, k.node);
3743 }
3744 if (g_json_output) {
3745 line::reg::Json p = line::reg::Json::object();
3746 p["type"] = "SamplePath";
3747 p["indexBase"] = 0;
3748 // The seed and the requested length are part of the ANSWER, as on the SSA
3749 // path: two runs are the same trace only if both are stated.
3750 p["events"] = nevents;
3751 p["seed"] = seed;
3752 p["drawn"] = path.state.size();
3753 p["scope"] = k.node ? sn.nodes[k.node - 1].name : std::string("(system)");
3754 if (k.node) p["node"] = k.node - 1;
3755 p["t"] = vector_json(path.t);
3756 p["state"] = index_json(path.state);
3757 line::reg::Json ev = line::reg::Json::array();
3758 for (std::size_t i = 0; i < path.state.size(); ++i) {
3759 // null where the readable table prints "absorb": the walk left no
3760 // state, so there is no synchronization index, and any integer here
3761 // would name an event that did not fire.
3762 if (i < path.event.size() && path.event[i] != static_cast<std::size_t>(-1))
3763 ev.push_back(path.event[i]);
3764 else
3765 ev.push_back(line::reg::Json());
3766 }
3767 p["event"] = ev;
3768 p["sysAggr"] = matrix_json(A);
3769 // THE STATE SPACE TRAVELS WITH THE TRAJECTORY, so a host can turn the
3770 // visited indices into the states themselves without enumerating the
3771 // chain a second time in another process -- which would also be a second
3772 // chance for the two enumerations to disagree while looking paired.
3773 {
3776 p["space"] = matrix_json(s.flat);
3777 p["NodeWidths"] = index_json(s.node_width);
3778 }
3779 if (k.node) {
3780 p["nodeState"] = matrix_json(L);
3781 p["nodeAggr"] = matrix_json(LA);
3782 }
3783 emit_analysis<T>("sample", p, path.chain.actualmethod, ctmc_meta<T>(path.chain));
3784 return 0;
3785 }
3786 // The seed and the requested length are part of the ANSWER, as on the SSA
3787 // path: two runs are the same trace only if both are stated.
3788 std::printf("SolverCTMC arith=%s states=%zu events=%zu seed=%lu drawn=%zu scope=%s\n",
3789 line::num_traits<T>::name(), path.chain.chain.space.size(), nevents, seed,
3790 path.state.size(), k.node ? sn.nodes[k.node - 1].name.c_str() : "(system)");
3791 std::printf("%14s %8s %8s %s\n", "Time", "State", "Event",
3792 k.node ? "SysAggregate | NodeState | NodeAggregate" : "SysAggregate");
3793 for (std::size_t i = 0; i < path.state.size(); ++i) {
3794 const std::size_t ev = i < path.event.size() ? path.event[i] : static_cast<std::size_t>(-1);
3795 std::printf("%14.8g %8zu ", line::num_traits<T>::to_double(path.t[i]), path.state[i] + 1);
3796 if (ev == static_cast<std::size_t>(-1))
3797 std::printf("%8s ", "absorb");
3798 else
3799 std::printf("%8zu ", ev + 1);
3800 for (std::size_t c = 0; c < A.cols(); ++c)
3801 std::printf(" %g", line::num_traits<T>::to_double(A(i, c)));
3802 if (k.node) {
3803 std::printf(" |");
3804 for (std::size_t c = 0; c < L.cols(); ++c)
3805 std::printf(" %g", line::num_traits<T>::to_double(L(i, c)));
3806 std::printf(" |");
3807 for (std::size_t c = 0; c < LA.cols(); ++c)
3808 std::printf(" %g", line::num_traits<T>::to_double(LA(i, c)));
3809 }
3810 std::printf("\n");
3811 }
3812 return 0;
3813}
3814
3815/** `-a cdf`: `getCdfRespT` per (station, class), and `getCdfSysRespT` per chain. */
3816template <class T>
3817int solve_ctmc_cdf(const line::qn::NetworkStruct<T>& sn, const line::ctmc::CtmcOptions& opt) {
3818 const std::vector<std::vector<line::ctmc::CdfCurve<T> > > RD =
3820 const std::vector<line::ctmc::CdfCurve<T> > RS = line::ctmc::solver_ctmc_cdf_sys_respt(sn, opt);
3821 if (g_json_output) {
3822 line::reg::Json p = line::reg::Json::object();
3823 p["type"] = "CdfRespT";
3824 p["chains"] = sn.nchains;
3825 // ONE OBJECT PER CURVE rather than four parallel columns: the grids are
3826 // per-pair and of different lengths, so a column-oriented form would have
3827 // to repeat the station and the class on every sample and leave the host
3828 // to re-group them.
3829 line::reg::Json rd = line::reg::Json::array();
3830 for (std::size_t i = 0; i < RD.size(); ++i)
3831 for (std::size_t c = 0; c < RD[i].size(); ++c) {
3832 // An empty curve is not a degenerate one: the chain never visits
3833 // that pair, so there is no arrival event to condition on, and it
3834 // is OMITTED rather than sent as a flat zero law.
3835 if (RD[i][c].empty()) continue;
3836 line::reg::Json e = line::reg::Json::object();
3837 e["Station"] = sn.stations[i].name;
3838 e["JobClass"] = sn.classes[c].name;
3839 e["station"] = i;
3840 e["jobclass"] = c;
3841 e["t"] = vector_json(RD[i][c].t);
3842 e["F"] = vector_json(RD[i][c].F);
3843 rd.push_back(e);
3844 }
3845 p["respt"] = rd;
3846 line::reg::Json rs = line::reg::Json::array();
3847 for (std::size_t c = 0; c < RS.size(); ++c) {
3848 if (RS[c].empty()) continue;
3849 line::reg::Json e = line::reg::Json::object();
3850 e["chain"] = c;
3851 e["t"] = vector_json(RS[c].t);
3852 e["F"] = vector_json(RS[c].F);
3853 rs.push_back(e);
3854 }
3855 p["sysrespt"] = rs;
3856 p["indexBase"] = 0;
3857 // NO "method", as on the reward arm: the response-time laws are computed
3858 // from tagged chains this function does not return, so there is no
3859 // resolved method to report and the requested one is not it.
3860 emit_analysis<T>("cdf", p, std::string());
3861 return 0;
3862 }
3863 std::printf("SolverCTMC arith=%s chains=%zu\n", line::num_traits<T>::name(), sn.nchains);
3864 std::printf("%-16s %-14s %14s %14s\n", "Station", "JobClass", "Time", "F(t)");
3865 for (std::size_t i = 0; i < RD.size(); ++i)
3866 for (std::size_t c = 0; c < RD[i].size(); ++c) {
3867 // An empty curve is not a degenerate one: the chain never visits
3868 // that pair, so there is no arrival event to condition on.
3869 if (RD[i][c].empty()) continue;
3870 for (std::size_t j = 0; j < RD[i][c].t.size(); ++j)
3871 std::printf("%-16s %-14s %14.8g %14.10g\n", sn.stations[i].name.c_str(),
3872 sn.classes[c].name.c_str(),
3873 line::num_traits<T>::to_double(RD[i][c].t[j]),
3874 line::num_traits<T>::to_double(RD[i][c].F[j]));
3875 }
3876 std::printf("%-16s %-14s %14s %14s\n", "System", "Chain", "Time", "F(t)");
3877 for (std::size_t c = 0; c < RS.size(); ++c) {
3878 if (RS[c].empty()) continue;
3879 for (std::size_t j = 0; j < RS[c].t.size(); ++j)
3880 std::printf("%-16s %-14zu %14.8g %14.10g\n", "(system)", c + 1,
3882 line::num_traits<T>::to_double(RS[c].F[j]));
3883 }
3884 return 0;
3885}
3886
3887/**
3888 * A `--passage-from`/`--passage-into` spec as a Matrix<double>: either a flat
3889 * comma list ("3,5", one row the resolver reads as 1-based indices when every
3890 * entry is one) or semicolon-separated state rows ("0,2;1,1"), which resolve
3891 * against the enumerated space by content.
3892 */
3893inline line::Matrix<double> parse_passage_set(const std::string& spec, const char* flag) {
3894 if (spec.empty()) return line::Matrix<double>(0, 0);
3895 std::vector<std::vector<double>> rows;
3896 std::size_t pos = 0;
3897 while (pos <= spec.size()) {
3898 std::size_t semi = spec.find(';', pos);
3899 if (semi == std::string::npos) semi = spec.size();
3900 std::string rowtxt = spec.substr(pos, semi - pos);
3901 std::vector<double> row;
3902 std::size_t p2 = 0;
3903 while (p2 <= rowtxt.size()) {
3904 std::size_t comma = rowtxt.find(',', p2);
3905 if (comma == std::string::npos) comma = rowtxt.size();
3906 std::string cell = rowtxt.substr(p2, comma - p2);
3907 if (!cell.empty()) {
3908 char* endp = 0;
3909 const double v = std::strtod(cell.c_str(), &endp);
3910 if (endp == cell.c_str() || *endp != '\0')
3911 throw line::InputError(std::string(flag) + ": '" + cell +
3912 "' is not a number");
3913 row.push_back(v);
3914 }
3915 p2 = comma + 1;
3916 }
3917 if (!row.empty()) rows.push_back(row);
3918 pos = semi + 1;
3919 }
3920 if (rows.empty()) return line::Matrix<double>(0, 0);
3921 for (std::size_t i = 1; i < rows.size(); ++i)
3922 if (rows[i].size() != rows[0].size())
3923 throw line::InputError(std::string(flag) +
3924 ": every state row must have the same width");
3925 line::Matrix<double> out(rows.size(), rows[0].size());
3926 for (std::size_t i = 0; i < rows.size(); ++i)
3927 for (std::size_t j = 0; j < rows[i].size(); ++j) out(i, j) = rows[i][j];
3928 return out;
3929}
3930
3931/**
3932 * A `--passage-tset` list as a grid: comma-separated numbers, each as strtod
3933 * reads it, so 'inf' names the ultimate probability. A NaN or an empty list is
3934 * refused: neither is a time.
3935 */
3936std::vector<double> parse_passage_tset(const std::string& spec) {
3937 std::vector<double> t;
3938 std::size_t pos = 0;
3939 while (pos <= spec.size()) {
3940 std::size_t comma = spec.find(',', pos);
3941 if (comma == std::string::npos) comma = spec.size();
3942 std::string cell = spec.substr(pos, comma - pos);
3943 const std::size_t b = cell.find_first_not_of(" \t");
3944 const std::size_t e = cell.find_last_not_of(" \t");
3945 cell = (b == std::string::npos) ? std::string() : cell.substr(b, e - b + 1);
3946 if (cell.empty())
3947 throw line::InputError("--passage-tset: an empty entry in '" + spec +
3948 "'; give the times as 't1,t2,...', 'inf' allowed");
3949 char* endp = nullptr;
3950 const double v = std::strtod(cell.c_str(), &endp);
3951 if (endp == cell.c_str() || *endp != '\0' || std::isnan(v))
3952 throw line::InputError("--passage-tset: '" + cell + "' is not a time");
3953 t.push_back(v);
3954 pos = comma + 1;
3955 }
3956 return t;
3957}
3958
3959/**
3960 * `-s ctmc -a firstpasst`: `@@SolverCTMC/getCdfFirstPassT(A, B, C, tset)`, the
3961 * first passage time between two state sets the caller names, optionally under
3962 * a taboo set C (`--passage-taboo`) and on a grid of its own (`--passage-tset`). `--passage-into` is
3963 * required; an empty `--passage-from` starts from the conditional stationary
3964 * law on the complement of the target, as the reference does.
3965 */
3966template <class T>
3967int solve_ctmc_firstpasst(const line::qn::NetworkStruct<T>& sn,
3968 const line::ctmc::CtmcOptions& opt, const Knobs& k) {
3969 if (k.passage_into.empty())
3970 throw line::InputError(
3971 "-a firstpasst times the passage INTO a state set and needs --passage-into; name it "
3972 "as 1-based rows of the state space ('3,5') or as state rows ('0,2;1,1')");
3973 const line::Matrix<double> A = parse_passage_set(k.passage_from, "--passage-from");
3974 const line::Matrix<double> B = parse_passage_set(k.passage_into, "--passage-into");
3975 const line::Matrix<double> C = parse_passage_set(k.passage_taboo, "--passage-taboo");
3976 const std::vector<double> tset =
3977 k.passage_tset.empty() ? std::vector<double>() : parse_passage_tset(k.passage_tset);
3978 const std::string method = k.passage_method.empty() ? "expm" : k.passage_method;
3979
3981 line::ctmc::ctmc_cdf_firstpasst<T>(sn, opt, A, B, C, tset, method);
3982
3983 if (g_json_output) {
3984 line::reg::Json p = line::reg::Json::object();
3985 p["type"] = "CdfFirstPassT";
3986 p["indexBase"] = 0;
3987 p["t"] = line::reg::Json(fp.t);
3988 p["F"] = line::reg::Json(fp.F);
3989 p["f"] = line::reg::Json(fp.f);
3990 line::reg::Json src = line::reg::Json::array(), tgt = line::reg::Json::array();
3991 for (std::size_t i : fp.source) src.push_back(static_cast<double>(i));
3992 for (std::size_t i : fp.target) tgt.push_back(static_cast<double>(i));
3993 p["source"] = src;
3994 p["target"] = tgt;
3995 line::reg::Json tab = line::reg::Json::array();
3996 for (std::size_t i : fp.taboo) tab.push_back(static_cast<double>(i));
3997 p["taboo"] = tab;
3998 p["reachprob"] = fp.reachprob;
3999 p["tabooprob"] = fp.tabooprob;
4000 emit_analysis<T>("firstpasst", p, method);
4001 return 0;
4002 }
4003 std::printf("SolverCTMC arith=%s method=%s getCdfFirstPassT\n",
4004 line::num_traits<T>::name(), method.c_str());
4005 std::printf("source states: %zu%s, target states: %zu, taboo states: %zu\n",
4006 fp.source.size(), fp.source.empty() ? " (conditional stationary law)" : "",
4007 fp.target.size(), fp.taboo.size());
4008 std::printf("P(target first) = %.10g, P(taboo first) = %.10g\n", fp.reachprob,
4009 fp.tabooprob);
4010 std::printf("%14s %14s %14s\n", "Time", "F(t)", "f(t)");
4011 for (std::size_t j = 0; j < fp.t.size(); j += 111)
4012 std::printf("%14.8g %14.10g %14.10g\n", fp.t[j], fp.F[j], fp.f[j]);
4013 std::printf("%14.8g %14.10g %14.10g\n", fp.t.back(), fp.F.back(), fp.f.back());
4014 return 0;
4015}
4016
4017/**
4018 * `-s ctmc -a firstpasstmom`: `@@SolverCTMC/getFirstPassTMoments(A, B, nmax)`,
4019 * the moments of the same passage `firstpasst` gives the curve of.
4020 *
4021 * These are EXACT and cost one linear solve per order, so a caller who wants a
4022 * variance or a skewness should ask for them here rather than integrate the
4023 * truncated curve the other arm returns. `--passage-orders` is the nmax; it
4024 * defaults to the reference's 3.
4025 */
4026template <class T>
4027int solve_ctmc_firstpasst_moments(const line::qn::NetworkStruct<T>& sn,
4028 const line::ctmc::CtmcOptions& opt, const Knobs& k) {
4029 if (k.passage_into.empty())
4030 throw line::InputError(
4031 "-a firstpasstmom times the passage INTO a state set and needs --passage-into; name "
4032 "it as 1-based rows of the state space ('3,5') or as state rows ('0,2;1,1')");
4033 const line::Matrix<double> A = parse_passage_set(k.passage_from, "--passage-from");
4034 const line::Matrix<double> B = parse_passage_set(k.passage_into, "--passage-into");
4035 const line::Matrix<double> C = parse_passage_set(k.passage_taboo, "--passage-taboo");
4036 const std::size_t nmax = (k.passage_orders > 0) ? k.passage_orders : 3;
4037
4039 line::ctmc::ctmc_firstpasst_moments<T>(sn, opt, A, B, nmax, C);
4040
4041 if (g_json_output) {
4042 line::reg::Json p = line::reg::Json::object();
4043 p["type"] = "FirstPassTMoments";
4044 p["indexBase"] = 0;
4045 line::reg::Json m = line::reg::Json::array();
4046 for (std::size_t i = 0; i < fm.m.size(); ++i)
4047 m.push_back(line::num_traits<T>::to_double(fm.m[i]));
4048 p["m"] = m;
4049 line::reg::Json mall = line::reg::Json::array();
4050 for (std::size_t i = 0; i < fm.mall.rows(); ++i) {
4051 line::reg::Json row = line::reg::Json::array();
4052 for (std::size_t j = 0; j < fm.mall.cols(); ++j)
4053 row.push_back(line::num_traits<T>::to_double(fm.mall(i, j)));
4054 mall.push_back(row);
4055 }
4056 p["mall"] = mall;
4057 line::reg::Json src = line::reg::Json::array(), tgt = line::reg::Json::array();
4058 for (std::size_t i : fm.source) src.push_back(static_cast<double>(i));
4059 for (std::size_t i : fm.target) tgt.push_back(static_cast<double>(i));
4060 p["source"] = src;
4061 p["target"] = tgt;
4062 line::reg::Json tab = line::reg::Json::array(), pr = line::reg::Json::array();
4063 for (std::size_t i : fm.taboo) tab.push_back(static_cast<double>(i));
4064 for (std::size_t i = 0; i < fm.p.size(); ++i)
4065 pr.push_back(line::num_traits<T>::to_double(fm.p[i]));
4066 p["taboo"] = tab;
4067 p["p"] = pr;
4068 emit_analysis<T>("firstpasstmom", p, "moments");
4069 return 0;
4070 }
4071 std::printf("SolverCTMC arith=%s getFirstPassTMoments\n", line::num_traits<T>::name());
4072 std::printf("source states: %zu%s, target states: %zu, taboo states: %zu\n",
4073 fm.source.size(), fm.source.empty() ? " (conditional stationary law)" : "",
4074 fm.target.size(), fm.taboo.size());
4075 if (!fm.taboo.empty())
4076 std::printf("moments are CONDITIONAL on entering the target before the taboo set\n");
4077 std::printf("%8s %20s\n", "Order", "Moment");
4078 for (std::size_t i = 0; i < fm.m.size(); ++i)
4079 std::printf("%8zu %20.10g\n", i + 1, line::num_traits<T>::to_double(fm.m[i]));
4080 return 0;
4081}
4082
4083/**
4084 * `--rate-sched`: the JSON schedule, inline or from a file, resolved against the
4085 * model so that a station or class may be named rather than numbered.
4086 */
4087template <class T>
4088std::vector<line::ctmc::CtmcRateSched> parse_rate_sched(const std::string& arg,
4089 const line::qn::NetworkStruct<T>& sn) {
4090 std::string text = arg;
4091 const std::size_t first = arg.find_first_not_of(" \t\r\n");
4092 if (first == std::string::npos || (arg[first] != '[' && arg[first] != '{')) {
4093 std::ifstream in(arg.c_str());
4094 if (!in)
4095 throw line::InputError("--rate-sched: '" + arg +
4096 "' is neither inline JSON nor a readable file");
4097 std::ostringstream ss;
4098 ss << in.rdbuf();
4099 text = ss.str();
4100 }
4101 line::io::detail::json root;
4102 try {
4103 root = line::io::detail::json::parse(text);
4104 } catch (const std::exception& e) {
4105 throw line::InputError(std::string("--rate-sched: not valid JSON: ") + e.what());
4106 }
4107 if (root.is_object()) root = line::io::detail::json::array({root});
4108 if (!root.is_array() || root.empty())
4109 throw line::InputError("--rate-sched: expected a non-empty array of schedule objects");
4110
4111 const auto resolve = [](const line::io::detail::json& v, const std::vector<std::string>& names,
4112 const char* what) -> std::size_t {
4113 if (v.is_number_integer()) {
4114 const long long i = v.get<long long>();
4115 if (i < 1 || static_cast<std::size_t>(i) > names.size())
4116 throw line::InputError(std::string("--rate-sched: ") + what + " index " +
4117 std::to_string(i) + " is out of range (1-based)");
4118 return static_cast<std::size_t>(i);
4119 }
4120 if (v.is_string()) {
4121 const std::string nm = v.get<std::string>();
4122 for (std::size_t i = 0; i < names.size(); ++i)
4123 if (names[i] == nm) return i + 1;
4124 throw line::InputError(std::string("--rate-sched: no ") + what + " named '" + nm + "'");
4125 }
4126 throw line::InputError(std::string("--rate-sched: ") + what +
4127 " must be a name or a 1-based index");
4128 };
4129 std::vector<std::string> stations, classes;
4130 for (std::size_t i = 0; i < sn.stations.size(); ++i)
4131 stations.push_back(sn.nodes[sn.station_to_node[i] - 1].name);
4132 for (const auto& c : sn.classes) classes.push_back(c.name);
4133
4134 std::vector<line::ctmc::CtmcRateSched> out;
4135 for (const auto& e : root) {
4136 if (!e.is_object() || !e.contains("station") || !e.contains("class") ||
4137 !e.contains("tgrid") || !e.contains("rates"))
4138 throw line::InputError(
4139 "--rate-sched: every entry needs station, class, tgrid and rates");
4141 rs.station = resolve(e.at("station"), stations, "station");
4142 rs.cls = resolve(e.at("class"), classes, "class");
4143 rs.tgrid = e.at("tgrid").get<std::vector<double>>();
4144 rs.rates = e.at("rates").get<std::vector<double>>();
4145 if (e.contains("nominal") && !e.at("nominal").is_null())
4146 rs.nominal = e.at("nominal").get<double>();
4147 out.push_back(rs);
4148 }
4149 return out;
4150}
4151
4152/**
4153 * Solve a Network model.json with SolverCTMC and print what `-a` asked for.
4154 *
4155 * EXACT, and the only ported solver that is exact on a non-product-form model:
4156 * it enumerates the state space and solves pi Q = 0, so the numbers are the
4157 * chain's own and not an approximation of them. The price is the state space,
4158 * which is why an OPEN model needs `--cutoff`: without a bound on the open
4159 * population the chain is infinite. The banner reports the cutoff that was used,
4160 * because a truncated chain's answer is not the model's answer without it.
4161 *
4162 * Every arithmetic backend runs the stationary analyses: the generator assembly
4163 * and the stationary solve are field operations throughout, so `--arith exact`
4164 * returns the exact rational stationary law of a chain with rational rates. The
4165 * transient ones refuse by name under exact, since a forward integration, an
4166 * exponential clock and a matrix exponential are all transcendental.
4167 */
4168template <class T>
4169int solve_model_ctmc(const std::string& file, const Knobs& k, const std::string& analysis) {
4170 line::qn::Network<T> net = read_model<T>(file);
4172 if (!k.method.empty()) opt.method = k.method;
4173 if (k.cutoff >= 0.0) opt.cutoff = k.cutoff;
4174 opt.cutoff_mat = k.cutoff_mat;
4175 opt.force = k.force;
4176 if (!k.nonmkv.empty()) opt.nonmkv = k.nonmkv;
4177 if (k.timestep > 0.0) opt.timestep = k.timestep; // `--timestep`, the fixed output grid
4178 if (k.stiff >= 0) opt.stiff = k.stiff == 1; // `--stiff`, the transient integrator
4179 // `--transient-method` and its two tolerances, `options.config` of the
4180 // reference's transient analyzer. The analyzer validates the name.
4181 if (!k.transient_method.empty()) opt.transient_method = k.transient_method;
4182 if (k.fau_epsilon > 0.0) opt.fau_epsilon = k.fau_epsilon;
4183 if (k.fau_delta >= 0.0) opt.fau_delta = k.fau_delta;
4184 if (k.ctmc_tv_ngrid > 0) opt.ctmc_tv_ngrid = k.ctmc_tv_ngrid;
4185 const line::qn::NetworkStruct<T>& sn = net.get_struct();
4186 if (!k.rate_sched.empty()) opt.rate_sched = parse_rate_sched(k.rate_sched, sn);
4187
4188 // The method that never builds the generator is served by its own analyzer,
4189 // ahead of every state-space path below. The dispatcher has already refused
4190 // every analysis but `avg` for it, since it produces no state space, no
4191 // filtration and no trajectory to answer one from.
4192 if (opt.method == "mdd") {
4194 if (k.mdd_tol > 0.0) mcdopt.tol = k.mdd_tol;
4195 if (k.mdd_maxiter > 0) mcdopt.maxiter = k.mdd_maxiter;
4196 return solve_ctmc_mdd_avg<T>(sn, opt, mcdopt);
4197 }
4198
4199 // The field-arithmetic analyses: every step from the generator to the answer
4200 // is a ring operation, so exact returns the exact rational quantity.
4201 if (analysis == "avg") return solve_ctmc_avg<T>(sn, opt);
4202 if (analysis == "prob") return solve_ctmc_prob<T>(sn, opt, k);
4203 if (analysis == "gen") return solve_ctmc_gen<T>(sn, opt);
4204 if (analysis == "states") return solve_ctmc_states<T>(sn, opt);
4205 if (analysis == "sens") return solve_ctmc_sens<T>(sn, opt);
4206 if (analysis == "reward") return solve_ctmc_reward<T>(sn, opt);
4207 if (analysis == "rewardvalue") return solve_ctmc_reward_value<T>(sn, opt, k);
4208
4209 // The rest integrate a forward equation, draw an exponential clock or take a
4210 // matrix exponential, none of which exists in a rational field. Their
4211 // static_asserts are behind if-constexpr so the refusal is a message rather
4212 // than a compile error in the exact instantiation.
4214 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
4215 "the -a " + analysis +
4216 " analysis integrates the forward equation, draws exponential clocks or takes a matrix "
4217 "exponential, none of which exists in exact rational arithmetic; rerun with --arith "
4218 "double or --arith real");
4219 } else {
4220 if (analysis == "tran") return solve_ctmc_tran<T>(sn, opt, k);
4221 if (analysis == "tranprob") return solve_ctmc_tranprob<T>(sn, opt, k);
4222 if (analysis == "tranreward") return solve_ctmc_tran_reward<T>(sn, opt, k);
4223 if (analysis == "sample") return solve_ctmc_sample<T>(sn, opt, k);
4224 if (analysis == "firstpasst") return solve_ctmc_firstpasst<T>(sn, opt, k);
4225 if (analysis == "firstpasstmom") return solve_ctmc_firstpasst_moments<T>(sn, opt, k);
4226 return solve_ctmc_cdf<T>(sn, opt); // the dispatcher admitted no other name
4227 }
4228}
4229
4230/**
4231 * `-s ssa -a prob`: the four SolverSSA probability queries over the model's
4232 * DEFAULT INITIAL STATE, the same state `-s ctmc -a prob` reports on.
4233 *
4234 * THE PAIR IS THE POINT. The CTMC answer is the stationary law of the chain and
4235 * this one is a time average of a finite sample path, so running both on a model
4236 * small enough for the chain measures the simulation error directly instead of
4237 * inferring it. The banner therefore carries the run length and the seed, as
4238 * every simulated number on this CLI does.
4239 *
4240 * `seen` TRAVELS WITH EACH PROBABILITY because a zero here has two meanings: the
4241 * path visited the state and left immediately, or it never got there at all. The
4242 * reference warns on the second; a machine-readable answer has to carry the
4243 * distinction rather than print it.
4244 */
4245template <class T>
4246int solve_model_ssa_prob(const std::string& file, const Knobs& k) {
4247 line::qn::Network<T> net = read_model<T>(file);
4248 const line::qn::NetworkStruct<T>& sn = net.get_struct();
4250 // `serial`, whatever `-m` said, and for the reference's own reason: the NRM
4251 // simulates per-(node, class, phase) counts rather than the state ENCODING,
4252 // so it has no row to compare a requested state against.
4253 // `@@SolverSSA/getProb.m` rewrites the method the same way.
4254 opt.method = "serial";
4255 if (k.samples) opt.samples = k.samples;
4256 if (k.seed) opt.seed = k.seed;
4257 if (k.warmupfrac >= 0.0) opt.warmupfrac = k.warmupfrac;
4258 if (k.cutoff >= 0.0) opt.cutoff = k.cutoff;
4260
4261 if (g_json_output) {
4262 line::reg::Json p = line::reg::Json::object();
4263 p["type"] = "ProbAggr";
4264 p["indexBase"] = 0;
4265 p["samples"] = r.samples;
4266 p["seed"] = r.seed;
4267 p["ProbSys"] = r.sys.prob;
4268 p["ProbSysAggr"] = r.sys_aggr.prob;
4269 p["ProbSysSeen"] = r.sys.seen;
4270 p["ProbSysAggrSeen"] = r.sys_aggr.seen;
4271 line::reg::Json st = line::reg::Json::array(), pm = line::reg::Json::array(),
4272 pa = line::reg::Json::array(), sm = line::reg::Json::array();
4273 for (std::size_t i = 0; i < sn.nstations; ++i) {
4274 st.push_back(sn.stations[i].name);
4275 pm.push_back(r.marg[i].prob);
4276 pa.push_back(r.aggr[i].prob);
4277 sm.push_back(r.marg[i].seen);
4278 }
4279 p["Station"] = st;
4280 p["Prob"] = pm;
4281 p["ProbAggr"] = pa;
4282 p["Seen"] = sm;
4283 emit_analysis<T>("prob", p, "serial");
4284 return 0;
4285 }
4286 std::printf("SolverSSA arith=%s method=serial samples=%zu seed=%lu time=%.6g\n",
4288 std::printf("ProbSys = %.8g%s\n", r.sys.prob, r.sys.seen ? "" : " (state never visited)");
4289 std::printf("ProbSysAggr = %.8g%s\n", r.sys_aggr.prob,
4290 r.sys_aggr.seen ? "" : " (state never visited)");
4291 std::printf("%-20s %14s %14s\n", "Station", "Prob", "ProbAggr");
4292 for (std::size_t i = 0; i < sn.nstations; ++i)
4293 std::printf("%-20s %14.8g %14.8g\n", sn.stations[i].name.c_str(), r.marg[i].prob,
4294 r.aggr[i].prob);
4295 return 0;
4296}
4297
4298/**
4299 * `-s ssa -a sample`: `sampleSys` and `sampleSysAggr`, one simulated trajectory;
4300 * with `--node`, also that node's own block (`sample`) and per-class counts
4301 * (`sampleAggr`).
4302 *
4303 * The SAME shape `-s ctmc -a sample` emits, deliberately: the CTMC sampler walks
4304 * the jump chain of an enumerated generator and this one walks the network's own
4305 * encoding, and a host that can read one trajectory should be able to read the
4306 * other. The event column indexes the synchronization list, so the two are
4307 * comparable only within a solver -- which is why it is printed and not
4308 * interpreted here.
4309 */
4310template <class T>
4311int solve_model_ssa_sample(const std::string& file, const Knobs& k) {
4312 line::qn::Network<T> net = read_model<T>(file);
4313 const line::qn::NetworkStruct<T>& sn_model = net.get_struct();
4315 opt.method = "serial";
4316 opt.samples = k.events ? k.events : (k.samples ? k.samples : 1000); // see -a sample above
4317 if (k.seed) opt.seed = k.seed;
4318 if (k.warmupfrac >= 0.0) opt.warmupfrac = k.warmupfrac;
4319 if (k.cutoff >= 0.0) opt.cutoff = k.cutoff;
4321 // the path's rows are in the layout of the struct it ran on (pair form, `ctmc_mapc`)
4322 const line::qn::NetworkStruct<T>& sn = sim.solved_sn ? *sim.solved_sn : sn_model;
4325 if (k.node) nodep = line::ssa::ssa_sample_node(sn, sim.run, k.node);
4326
4327 if (g_json_output) {
4328 line::reg::Json p = line::reg::Json::object();
4329 p["type"] = "SamplePath";
4330 p["indexBase"] = 0;
4331 p["events"] = opt.samples;
4332 p["seed"] = sys.seed;
4333 p["drawn"] = sys.t.size();
4334 p["scope"] = k.node ? sn.nodes[k.node - 1].name : std::string("(system)");
4335 if (k.node) p["node"] = k.node - 1;
4336 p["t"] = vector_json(sys.t);
4337 p["event"] = index_json(sys.event);
4338 p["state"] = matrix_json(sys.state);
4339 // THE BLOCK BOUNDARIES TRAVEL, as under `-s ctmc -a sample`. A row of
4340 // `state` is the stateful nodes' local encodings laid end to end, and
4341 // `sampleSys` reports them one node at a time; a host that had to guess
4342 // the widths would cut the row at the wrong columns on any model with a
4343 // phase-type service, and read a phase index as a job count.
4344 {
4345 line::reg::Json w = line::reg::Json::array();
4346 for (std::size_t f = 0; f < sn.stateful_nodes.size(); ++f)
4347 w.push_back(sim.run.space.empty() ? 0 : sim.run.space[0].local[f].size());
4348 p["NodeWidths"] = w;
4349 }
4350 p["sysAggr"] = matrix_json(sys.aggr);
4351 if (k.node) {
4352 p["nodeState"] = matrix_json(nodep.state);
4353 p["nodeAggr"] = matrix_json(nodep.aggr);
4354 }
4355 emit_analysis<T>("sample", p, "serial");
4356 return 0;
4357 }
4358 std::printf("SolverSSA arith=%s method=serial events=%zu seed=%lu drawn=%zu scope=%s\n",
4359 line::num_traits<T>::name(), opt.samples, sys.seed, sys.t.size(),
4360 k.node ? sn.nodes[k.node - 1].name.c_str() : "(system)");
4361 std::printf("%14s %8s %s\n", "Time", "Event",
4362 k.node ? "SysAggregate | NodeState | NodeAggregate" : "SysAggregate");
4363 for (std::size_t i = 0; i < sys.t.size(); ++i) {
4364 std::printf("%14.8g %8zu ", sys.t[i], sys.event[i]);
4365 for (std::size_t c = 0; c < sys.aggr.cols(); ++c)
4366 std::printf(" %g", line::num_traits<T>::to_double(sys.aggr(i, c)));
4367 if (k.node) {
4368 std::printf(" |");
4369 for (std::size_t c = 0; c < nodep.state.cols(); ++c)
4370 std::printf(" %g", line::num_traits<T>::to_double(nodep.state(i, c)));
4371 std::printf(" |");
4372 for (std::size_t c = 0; c < nodep.aggr.cols(); ++c)
4373 std::printf(" %g", line::num_traits<T>::to_double(nodep.aggr(i, c)));
4374 }
4375 std::printf("\n");
4376 }
4377 return 0;
4378}
4379
4380/**
4381 * A `Matrix<double>` read as this arithmetic's matrix.
4382 *
4383 * SSA and Fluid return plain-double solutions whatever `T` the CLI was asked
4384 * for, so every shared routine that takes a `Matrix<T>` -- the residence-time
4385 * conversion, the chain aggregation -- needs this one lift. Both are refused
4386 * outside `--arith double` anyway, so it is a type bridge and not a precision
4387 * claim.
4388 */
4389template <class T>
4392 for (std::size_t i = 0; i < m.rows(); ++i)
4393 for (std::size_t j = 0; j < m.cols(); ++j)
4394 out(i, j) = line::num_traits<T>::from_double(m(i, j));
4395 return out;
4396}
4397
4398/**
4399 * Solve a Network model.json with SolverSSA and print the same table.
4400 *
4401 * A SIMULATION: its numbers carry Monte Carlo error, so the row is compared
4402 * against the other codebases' SSA rows and not against an exact solver's.
4403 *
4404 * `--samples` and `--seed` set the run length and the stream; without them the
4405 * defaults are 10000 firings and seed 23000, which on a two-station model is
4406 * roughly 3300 job cycles and lands a few percent from the analytical answer.
4407 * Diffing THAT against an exact solver reads as a defect and is not one: a
4408 * measured -3.12% at 1e4 on an M/M/1 falls to +0.06% at 2.56e6. The banner
4409 * therefore carries both numbers, so a row quoting an SSA figure carries the
4410 * conditions that produced it. Double only, refused by name in the dispatcher.
4411 *
4412 * `-m` REACHES THE SOLVER'S OWN DISPATCHER, `ssa::solver_ssa`, and not one
4413 * engine's entry. Calling `solver_ssa_nrm_analyzer` here would run the NRM
4414 * whatever `-m` said, so `-m serial` would silently answer with a different
4415 * estimator than the one asked for -- and the three names the NRM entry cannot
4416 * serve (`serial`, `para`, `parallel`) are all methods the library honours.
4417 */
4418template <class T>
4419int solve_model_ssa(const std::string& file, const Knobs& k) {
4420 line::qn::Network<T> net = read_model<T>(file);
4422 if (!k.method.empty() && k.method != "default") opt.method = k.method;
4423 if (k.samples) opt.samples = k.samples;
4424 if (k.seed) opt.seed = k.seed;
4425 if (k.warmupfrac >= 0.0) opt.warmupfrac = k.warmupfrac;
4426 if (k.cutoff >= 0.0) opt.cutoff = k.cutoff;
4427 if (k.timestep > 0.0) opt.timestep = k.timestep; // `--timestep`, the fixed step of -m tstep
4428 // The cache write-back is COLLECTED HERE, not only on the `-a node` path:
4429 // the realized hit and miss shares are what the sample path measured, and
4430 // `-a avg` is the arm MATLAB's lang='cpp' bridge calls. Without it
4431 // `CPPLINE.restoreCacheResults` found no block, cleared the Cache node and
4432 // refreshed the visits back to link()'s offered 1/2-1/2.
4433 std::vector<line::ssa::SsaCacheRatio> cacheratio;
4434 const line::ssa::SsaSolution r = line::ssa::solver_ssa(net.get_struct(), opt, &cacheratio);
4435 const line::qn::NetworkStruct<T>& sn = net.get_struct();
4436
4437 // The seed and the sample count are part of the ANSWER, not of the
4438 // invocation: two runs of a simulation are the same measurement only if
4439 // both are stated, so the banner carries them and a parity row that quotes
4440 // an SSA number carries them with it.
4441 //
4442 // `r.method` is the engine that ACTUALLY ran, never `k.method`: `-m
4443 // parallel` on an NRM-eligible model reports `nrm`, because that is what
4444 // produced the numbers below and the banner may not claim otherwise.
4445 std::printf("SolverSSA arith=%s method=%s type=%s samples=%zu seed=%lu time=%.6g\n",
4446 line::num_traits<T>::name(), r.method.c_str(),
4447 line::util::method_type("SSA", r.method).c_str(), r.samples, opt.seed,
4448 r.simulated_time);
4449 // ResidT IS NOT RespT UNLESS EVERY STATION IS VISITED ONCE PER CYCLE.
4450 // `sn_get_residt_from_respt` is the reference's own per-visit -> per-job
4451 // conversion and a pure function of `sn` and RN, so a solver that reports no
4452 // residence time of its own still owes the caller this one: reporting RespT
4453 // in its place was a factor of 3 out on sdroute_closed and 17 on Queue1 of
4454 // init_state_ps, both multi-visit closed models.
4455 //
4456 // TAKEN ON THE MEASURED CACHE SPLIT, not on the offered one: the visits this
4457 // conversion divides by are a function of the routing, and a cache's routing
4458 // is a RESULT. On tut06_cache_lru_zipf the base struct still carried
4459 // `link()`'s even hit/miss share, so both classes came back at exactly half
4460 // their response time (0.1 and 0.5 against 0.16475 and 0.17625) -- a number
4461 // that is not the residence time of any model.
4463 const line::Matrix<T> WN = line::mva::sn_get_residt_from_respt<T>(snw, to_matrix<T>(r.RN));
4464 line::reg::Json extra = line::reg::Json::object();
4466 if (!cache.empty()) extra["Cache"] = cache_extra_json<T>(cache);
4467 // ArvR IS NOT Tput, and reading it off the throughput column was wrong
4468 // wherever the two differ -- most visibly at a JOIN, which takes in one
4469 // sibling per branch and fires once per parent, so its arrival rate is the
4470 // fork degree times its throughput. `ssa_fj_foldback` already divides the
4471 // Join's QLen by the DERIVED rate to get its response time, so reporting
4472 // Tput in the ArvR column left the printed row self-inconsistent
4473 // (0.62372/1.02229 is 0.610, not the 0.3038 beside it). Taken on the
4474 // measured-cache-split struct for the same reason ResidT is.
4475 const line::Matrix<T> AN = line::mva::sn_get_arvr_from_tput<T>(snw, to_matrix<T>(r.TN));
4476 emit_avg_table<T>(sn, r.method, [&](std::size_t i, std::size_t c) {
4477 AvgRow row;
4478 row.q = r.QN(i, c);
4479 row.u = r.UN(i, c);
4480 row.r = r.RN(i, c);
4481 row.w = line::num_traits<T>::to_double(WN(i, c));
4482 row.t = r.TN(i, c);
4483 // A Source has no arrivals TO ITSELF, so its ArvR is 0 while its Tput is
4484 // the arrival rate.
4485 row.a = sn.stations[i].sched == line::lang::SchedStrategy::EXT
4486 ? 0.0
4487 : line::num_traits<T>::to_double(AN(i, c));
4488 return row;
4489 }, extra);
4490 return 0;
4491}
4492
4493/** The knobs the fluid solver reads, in one place so every fluid arm reads the
4494 * same set: an arm that quietly dropped one would answer a different model. */
4495inline line::fluid::FluidOptions fluid_options(const Knobs& k) {
4497 if (!k.method.empty()) opt.method = k.method;
4498 if (k.tol >= 0.0) opt.tol = k.tol;
4499 if (k.iter_tol >= 0.0) opt.iter_tol = k.iter_tol;
4500 if (k.iter_max >= 0) opt.iter_max = static_cast<std::size_t>(k.iter_max);
4501 if (k.t1 >= 0.0) opt.timespan_end = k.t1;
4502 if (!k.nonmkv.empty()) opt.nonmkv = k.nonmkv;
4503 // `pstar_set` is what makes the smoothing active under a method that did
4504 // not ask for it by name, exactly as `options.config.pstar` does in the
4505 // reference: setting the exponent alone would leave `-a avg` integrating
4506 // the hard-min drift while reporting the caller's choice.
4507 if (k.pstar > 0.0) {
4508 opt.pstar = k.pstar;
4509 opt.pstar_set = true;
4510 }
4511 if (!k.fluid_boundary.empty()) opt.fluid_boundary = k.fluid_boundary;
4512 return opt;
4513}
4514
4515/**
4516 * Solve a Network model.json with the fluid solver and print the same table as
4517 * the MVA path, so the parity harness can diff the two rows unchanged.
4518 *
4519 * ResidT and ArvR are reported as the per-visit response time and the
4520 * throughput: the fluid analyzer works at station level and, unlike the MVA
4521 * runner, has no chain-visit conversion behind it. That is what MATLAB's
4522 * fluid `getAvgTable` shows for these columns on a single-visit model.
4523 *
4524 * Only `double` reaches here -- the drift is integrated by LSODA -- so the
4525 * other backends are refused by name in `solve_model_dispatch` rather than
4526 * being narrowed silently.
4527 */
4528template <class T>
4529int solve_model_fluid(const std::string& file, const Knobs& k) {
4530 line::qn::Network<T> net = read_model<T>(file);
4531 const line::fluid::FluidOptions opt = fluid_options(k);
4532 // THE map_env FUNNEL, asked directly rather than through `run_avg`: this
4533 // runner returns a `FluidSolution` and not an `AvgResult`, so the arm cannot
4534 // pass itself as the `Run` callable. The decision and the config are the
4535 // ones `run_avg` would have used, so `-a avg` and the four
4536 // `run_avg_engine` views accept the same models for the same command line.
4537 // No arithmetic guard is needed here: this arm is instantiated at `double`
4538 // alone, the dispatcher having refused the other backends by name.
4539 {
4540 const line::solvers::MapEnvConfig mecfg = map_env_config(k);
4542 net.get_struct(), mecfg)
4543 .needed) {
4545 net.get_struct(), "SolverFluid", mecfg, line::solvers::fluid_stage_fn(opt),
4546 opt.method);
4547 std::printf("SolverFluid arith=%s method=%s type=%s iters=%d\n",
4549 line::util::method_type("FLD", rme.actualmethod).c_str(), rme.iter);
4550 print_avg_table<T>(net.get_struct(), rme);
4551 return 0;
4552 }
4553 }
4554 // `solver_fluid_run_analyzer` is runAnalyzer's resolution over the analyzer, so a
4555 // Cache model reaches the rmf branch, a DPS model the closing drift, and
4556 // anything the moment closure accepts reaches `minnormal`.
4557 // The converged hit/miss split is COLLECTED, for the reason the SSA arm
4558 // above collects its own: `-a avg` is what MATLAB's lang='cpp' bridge calls,
4559 // and a missing block there CLEARS the host's Cache node.
4561 // THE REFRESHED STRUCT IS TAKEN, not dropped: on a cache model the routing
4562 // the analyzer converged to carries the ACTUAL hit/miss split, where
4563 // `net.get_struct()` still carries link()'s offered one. The arrival rates
4564 // below are read off that routing, so the offered split reported 0.5/0.5
4565 // where the model converged to 0.4/0.6 (cache_replc_routing).
4568 net.get_struct(), opt, static_cast<line::qn::NetworkStruct<T>*>(nullptr),
4569 &refreshed, &cache);
4570 const line::qn::NetworkStruct<T>& sn = net.get_struct();
4571 const line::qn::NetworkStruct<T>& snflow =
4572 refreshed.nstations == sn.nstations && refreshed.nclasses == sn.nclasses ? refreshed : sn;
4573
4574 std::printf("SolverFluid arith=%s method=%s type=%s iters=%zu\n", line::num_traits<T>::name(),
4575 r.method.c_str(),
4576 line::util::method_type("FLD", r.method).c_str(), r.iters);
4577 // On stderr, for the reason the AvgResult printer gives (print_avg_table).
4578 if (!r.warning.empty()) std::fprintf(stderr, "Warning: %s\n", r.warning.c_str());
4579 // The residence-time conversion the SSA arm above applies, for the same
4580 // reason: neither analyzer produces a per-job residence time, and
4581 // `sn_get_residt_from_respt` derives one from RN and the visit ratios.
4582 const line::Matrix<T> WN = line::mva::sn_get_residt_from_respt<T>(sn, to_matrix<T>(r.RN));
4583 // THE ARRIVAL RATE IS A FLOW, NOT A COPY OF THE THROUGHPUT. `runAnalyzer`
4584 // takes it from `sn_get_arvr_from_tput`, i.e. from the class-expanded
4585 // routing, and the two agree only where every job a station serves it also
4586 // completes. They part on a station a job LEAVES by another route: on
4587 // cache_replc_routing the fluid solution puts zero throughput on the two
4588 // Delay stations while 0.4 and 0.6 arrive at them, so copying the
4589 // throughput made both rows all-zero and the table dropped them.
4590 const line::Matrix<T> AN = line::mva::sn_get_arvr_from_tput<T>(snflow, to_matrix<T>(r.TN));
4591 line::reg::Json extra = line::reg::Json::object();
4592 if (!cache.empty()) extra["Cache"] = cache_extra_json<T>(cache);
4593 if (!r.fj.empty()) {
4594 const line::reg::Json fjb = fj_extra_json(sn, r.fj);
4595 if (!fjb.is_null()) extra["FJ"] = fjb;
4596 }
4597 emit_avg_table<T>(sn, r.method, [&](std::size_t i, std::size_t c) {
4598 AvgRow row;
4599 row.q = r.QN(i, c);
4600 row.u = r.UN(i, c);
4601 row.r = r.RN(i, c);
4602 row.w = line::num_traits<T>::to_double(WN(i, c));
4603 row.t = r.TN(i, c);
4604 // A Source has no arrivals TO ITSELF, so its ArvR is 0 while its Tput is
4605 // the arrival rate -- the same rule the SSA arm above applies. Without it
4606 // the two CLI paths disagreed on one column of the same model:
4607 // gallery_mm1 reported Source ArvR 0 under -s mva and 1 under -s fluid.
4608 row.a = sn.stations[i].sched == line::lang::SchedStrategy::EXT
4609 ? 0.0
4610 : line::num_traits<T>::to_double(AN(i, c));
4611 return row;
4612 }, extra);
4613 return 0;
4614}
4615
4616/**
4617 * `-s fluid -a statevec`: the converged FLUID STATE VECTOR, `result.odeStateVec`.
4618 *
4619 * NOT A METRIC AND NOT INDEXED LIKE ONE. The ODE state carries one coordinate
4620 * per (station, class, PHASE), so a two-phase Erlang service contributes two
4621 * entries where the AvgTable contributes one number, and the sum over a
4622 * station's phases is its mean queue length. It is what a caller needs to
4623 * restart an integration, to seed another solver, or to read the phase
4624 * occupancy the means average away -- which is why the JAR exposes it as its
4625 * own `-a statevec` rather than as a column.
4626 *
4627 * The index layout is `fluid_state_layout`'s and is emitted BESIDE the vector,
4628 * because a bare list of numbers cannot be related back to a station without it.
4629 */
4630template <class T>
4631int solve_model_fluid_statevec(const std::string& file, const Knobs& k) {
4632 line::qn::Network<T> net = read_model<T>(file);
4633 const line::fluid::FluidOptions opt = fluid_options(k);
4635 const line::qn::NetworkStruct<T>& sn = net.get_struct();
4636 if (r.xvec.empty())
4637 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
4638 "-a statevec reports the converged ODE state and this solve produced none; the rmf "
4639 "and closing branches integrate a drift and fill it, so a branch that returns means "
4640 "directly has no state vector to report");
4641
4642 // The (station, class, phase) each coordinate belongs to, in the order the
4643 // ODE state is laid out: station-major, then class, then phase.
4644 std::vector<std::size_t> ist, cls, phs;
4645 for (std::size_t i = 0; i < sn.nstations; ++i)
4646 for (std::size_t c = 0; c < sn.nclasses; ++c) {
4647 const std::size_t np = sn.phases_of(i + 1, c + 1);
4648 for (std::size_t j = 0; j < np; ++j) {
4649 ist.push_back(i);
4650 cls.push_back(c);
4651 phs.push_back(j);
4652 }
4653 }
4654 // The layout is a CLAIM about the solver's state ordering, so it is checked
4655 // rather than asserted in a comment: a mismatch means the labels below would
4656 // name the wrong station, which is worse than no labels at all.
4657 const bool labelled = ist.size() == r.xvec.size();
4658
4659 if (g_json_output) {
4660 line::reg::Json p = line::reg::Json::object();
4661 p["type"] = "FluidStateVec";
4662 p["indexBase"] = 0;
4663 p["xvec"] = vector_json(r.xvec);
4664 p["labelled"] = labelled;
4665 if (labelled) {
4666 line::reg::Json st = line::reg::Json::array(), cl = line::reg::Json::array(),
4667 ph = line::reg::Json::array();
4668 for (std::size_t j = 0; j < ist.size(); ++j) {
4669 st.push_back(sn.stations[ist[j]].name);
4670 cl.push_back(sn.classes[cls[j]].name);
4671 ph.push_back(phs[j]);
4672 }
4673 p["Station"] = st;
4674 p["JobClass"] = cl;
4675 p["Phase"] = ph;
4676 }
4677 emit_analysis<T>("statevec", p, r.method);
4678 return 0;
4679 }
4680 std::printf("SolverFluid arith=%s method=%s coords=%zu\n", line::num_traits<T>::name(),
4681 r.method.c_str(), r.xvec.size());
4682 if (!labelled) {
4683 std::printf("# the ODE state is %zu wide and the (station, class, phase) layout accounts "
4684 "for %zu; the coordinates are printed unlabelled\n",
4685 r.xvec.size(), ist.size());
4686 std::printf("%-10s %20s\n", "Index", "x");
4687 for (std::size_t j = 0; j < r.xvec.size(); ++j)
4688 std::printf("%-10zu %20.10g\n", j, r.xvec[j]);
4689 return 0;
4690 }
4691 std::printf("%-16s %-14s %-8s %20s\n", "Station", "JobClass", "Phase", "x");
4692 for (std::size_t j = 0; j < r.xvec.size(); ++j)
4693 std::printf("%-16s %-14s %-8zu %20.10g\n", sn.stations[ist[j]].name.c_str(),
4694 sn.classes[cls[j]].name.c_str(), phs[j], r.xvec[j]);
4695 return 0;
4696}
4697
4698/** `--env-init`: a comma-separated probability per stage, checked by the coupling. */
4699inline std::vector<double> parse_env_init(const std::string& spec) {
4700 std::vector<double> p;
4701 std::size_t pos = 0;
4702 while (pos <= spec.size()) {
4703 std::size_t comma = spec.find(',', pos);
4704 if (comma == std::string::npos) comma = spec.size();
4705 const std::string cell = spec.substr(pos, comma - pos);
4706 char* endp = nullptr;
4707 const double v = std::strtod(cell.c_str(), &endp);
4708 if (cell.empty() || endp == cell.c_str() || *endp != '\0' || !std::isfinite(v))
4709 throw line::InputError("--env-init: '" + cell + "' in '" + spec +
4710 "' is not a probability; give one per stage, as 'p1,p2,...'");
4711 p.push_back(v);
4712 pos = comma + 1;
4713 }
4714 return p;
4715}
4716
4717/** A per-stage vector on the ENV banner, as `[a b c]` with %g cells. */
4718inline std::string env_vector_text(const std::vector<double>& v) {
4719 std::string s = "[";
4720 char buf[64];
4721 for (std::size_t i = 0; i < v.size(); ++i) {
4722 std::snprintf(buf, sizeof buf, "%s%.6g", i ? " " : "", v[i]);
4723 s += buf;
4724 }
4725 return s + "]";
4726}
4727
4728/**
4729 * Run the coupling `o.method` names, at the arithmetic the caller asked for.
4730 *
4731 * WHY THIS IS NOT JUST `env::solver_env`. That entry instantiates BOTH
4732 * couplings, and the mean-field one solves each stage with the fluid transient
4733 * -- LSODA, hence double. Calling it at `Rational` does not merely give a worse
4734 * answer, it does not compile (`sqrt` on a rational), so the template below
4735 * carries only the state-vector coupling and the double overload beside it
4736 * carries the full dispatch. The dispatcher has already refused `-s env
4737 * --arith exact` without `--method statevec`, so a non-double run reaching here HAS
4738 * asked for the state-vector coupling and gets it, banner included.
4739 */
4740template <class T>
4742 const line::env::EnvOptions& o) {
4744 out.statevec =
4745 line::env::solver_env_statevec(e, line::env::dispatch_detail::env_statevec_options<T>(o));
4746 line::env::dispatch_detail::env_take_statevec(out);
4747 return out;
4748}
4749
4750/** The double case, where both couplings are available. */
4752 const line::env::EnvOptions& o) {
4753 return line::env::solver_env(e, o);
4754}
4755
4756/**
4757 * Solve an ENVIRONMENT model.json with SolverENV and print the same average
4758 * table every other arm prints.
4759 *
4760 * Q, U and T come from the coupling. RespT and ResidT are both the Little's-law
4761 * ratio Q/T of the environment-averaged metrics (since 2026-11-15; RespT was
4762 * NaN before, which left `getAvgTable` hosts with an empty column where every
4763 * other codebase's ENV table reports Q/T). ArvR stays NaN: the coupling blends
4764 * no arrival rate.
4765 *
4766 * The station and class names come from stage 1. The mean-field coupling
4767 * already refuses an environment whose stages disagree on the station or class
4768 * count, so any stage names the same rows.
4769 */
4770template <class T>
4771int solve_model_env(const std::string& file, const Knobs& k) {
4772 line::env::Environment<T> e = read_env_model<T>(file);
4774 // `default` is passed through rather than folded into `meanfield`: on an
4775 // all-CTMC ensemble with no resets it RESOLVES to the exact state-vector
4776 // coupling (env_default_resolves_to_statevec), and `meanfield` by name never
4777 // does. Otherwise SolverEnv reads `default` as the mean-field coupling.
4778 opt.method = k.method.empty() ? "default" : k.method;
4779 if (k.iter_tol >= 0.0) opt.iter_tol = k.iter_tol;
4780 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
4781 if (k.t1 >= 0.0) opt.timespan_end = k.t1;
4782 if (k.tran_points) opt.tran_points = k.tran_points;
4783 if (k.tol >= 0.0) opt.stage.tol = k.tol;
4784 // THE STAGE SOLVER FOLLOWS THE COUPLING, because each coupling has exactly
4785 // one. `EnvOptions::stage_solver` defaults to `fluid`, which is what the
4786 // mean-field coupling needs (a transient mean) and what the state-vector one
4787 // refuses (it needs an enumerated generator and state space, which only
4788 // SolverCTMC exposes). Leaving the default in place made every
4789 // `--method statevec` run die on "stage solver 'fluid' is not available",
4790 // with no flag to fix it. This is not a silent fallback: there is one
4791 // admissible stage solver per coupling, and picking the other would be the
4792 // error.
4793 if (opt.method == "statevec") opt.stage_solver = "ctmc";
4794 // `--stage-solver` OVERRIDES that default, and only the mean-field coupling
4795 // has a choice to make: it needs a transient mean, which both the fluid
4796 // analyzer and the enumerated CTMC produce, and the two are different
4797 // models rather than two routes to one answer (a chain holds whole jobs).
4798 // An ensemble built on SolverCTMC stages therefore has to say so, or the
4799 // engine answers the fluid ensemble under its name -- which is what the
4800 // hosts refused lang='cpp' for.
4801 if (!k.stage_solver.empty()) opt.stage_solver = k.stage_solver;
4802 if (k.cutoff >= 0.0) opt.stage_cutoff = k.cutoff;
4803 // `--stiff`: the CTMC stages' transient integrator. It is part of the
4804 // answer: renv_threestages_repairmen states stiff = false on its stages.
4805 if (k.stiff >= 0) opt.stage_stiff = k.stiff == 1;
4806 // Method 'occupation' reads SolverENV's OWN timespan, unbounded unless
4807 // --tspan names a horizon, and its initial stage law.
4808 if (k.t1 >= 0.0) {
4809 opt.env_timespan_start = k.t0;
4810 opt.env_timespan_end = k.t1;
4811 }
4812 if (!k.env_init.empty()) opt.env_init = parse_env_init(k.env_init);
4813
4814 // UNQUALIFIED, so the double overload above wins for T = double: naming the
4815 // template explicitly would send every arithmetic to the state-vector
4816 // coupling and quietly ignore `--method meanfield`.
4817 const line::env::EnvAnalyzerSolution<T> r = env_run(e, opt);
4818 const line::qn::NetworkStruct<T>& sn = e.stage(0).model;
4819
4820 // The horizon and the grid are part of the ANSWER on this path, for the
4821 // same reason the seed and the sample count are on the SSA one: the
4822 // mean-field exit metrics are a quadrature, and two runs are the same
4823 // measurement only if both knobs are stated.
4824 // `points` is the mean-field quadrature's and is printed only there: the
4825 // state-vector coupling carries the whole joint law across a switch and
4826 // never sums over that grid, so reporting a grid it did not use would
4827 // describe a computation that did not happen.
4828 // A closed-form limit reads neither knob: it solves each stage, or one
4829 // rate-averaged model, in STEADY STATE, so a horizon and an iteration count
4830 // would describe a transient and a fixed point that never ran.
4831 if (r.method == "avg" || r.method == "dec")
4832 std::printf("SolverENV arith=%s method=%s stages=%zu (closed-form limit)\n",
4833 line::num_traits<T>::name(), r.method.c_str(), e.nstages());
4834 else if (r.method == "occupation")
4835 // `getStageOccupation` rides on the banner, one value per stage, as the
4836 // occupation weights are what the table below is blended with.
4837 std::printf("SolverENV arith=%s method=%s stages=%zu occupation=%s weight=%s\n",
4838 line::num_traits<T>::name(), r.method.c_str(), e.nstages(),
4839 env_vector_text(r.limit.occupation).c_str(),
4840 env_vector_text(r.limit.occupation_weight).c_str());
4841 else if (r.method == "statevec")
4842 // No horizon either: the state-vector sojourn is solved in closed form
4843 // on the product of the stage chain and its holding-time MMAP.
4844 std::printf("SolverENV arith=%s method=%s stages=%zu iters=%d%s\n",
4845 line::num_traits<T>::name(), r.method.c_str(), e.nstages(),
4846 r.iterations, r.converged ? "" : " (NOT CONVERGED)");
4847 else
4848 // Every remaining method -- meanfield, and the smp and statedep runs of
4849 // the same analyzer -- sums the same quadrature, so all of them report
4850 // the grid it was summed over.
4851 std::printf("SolverENV arith=%s method=%s stages=%zu horizon=%.6g points=%zu iters=%d%s\n",
4853 opt.tran_points, r.iterations, r.converged ? "" : " (NOT CONVERGED)");
4854 // A Cache answers on the NODE and in three index spaces, none of them
4855 // (station, class), so the AvgTable cannot carry it and an environment
4856 // solve that computed one used to drop it here. It rides in the JSON
4857 // envelope for a host and prints as its own rows for a reader.
4858 line::reg::Json extra = line::reg::Json::object();
4859 if (!r.cache.empty()) extra["Cache"] = cache_extra_json<T>(r.cache);
4860 if (r.method == "occupation") {
4861 // `getStageOccupation`, keyed as the reference stores it in `result`.
4862 extra["Occupation"] = vector_json<double>(r.limit.occupation);
4863 extra["OccupationWeight"] = vector_json<double>(r.limit.occupation_weight);
4864 }
4865 emit_avg_table<T>(
4866 sn, r.method,
4867 [&](std::size_t i, std::size_t c) {
4868 AvgRow row;
4869 row.q = line::num_traits<T>::to_double(r.QN(i, c));
4870 row.u = line::num_traits<T>::to_double(r.UN(i, c));
4871 row.t = line::num_traits<T>::to_double(r.TN(i, c));
4872 row.r = row.q / row.t;
4873 row.a = std::numeric_limits<double>::quiet_NaN();
4874 row.w = row.q / row.t;
4875 return row;
4876 },
4877 extra);
4878 if (!g_json_output) print_cache_rows<T>(sn, r.cache);
4879 return 0;
4880}
4881
4882/**
4883 * `-a var`: the SECOND moment of the queue length, which only the fluid solver
4884 * has and only through two of its methods.
4885 *
4886 * `minnormal` and `mnrefined` report the STATIONARY covariance of the linear noise
4887 * approximation (`@@SolverFLD/getMoments`), `kp` the covariance integrated along
4888 * the trajectory (`@@SolverFLD/getTranAvgVar`); this prints the per-station,
4889 * per-class variance and its standard deviation, plus, on the JSON path, the full
4890 * state covariance so that cross-station terms survive rather than only the
4891 * per-block totals. Every other method carries a first moment only and is refused
4892 * by name -- a variance of zero would be a claim, not an absence.
4893 */
4894template <class T>
4895int solve_model_fluid_var(const std::string& file, const Knobs& k) {
4896 line::qn::Network<T> net = read_model<T>(file);
4897 const line::fluid::FluidOptions opt = fluid_options(k);
4898 const line::qn::NetworkStruct<T>& sn = net.get_struct();
4900 if (!r.has_moments)
4901 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
4902 "-a var needs a fluid method that computes a second moment: 'minnormal', 'mnrefined' or "
4903 "'dae' for the stationary covariance, 'kp' for the covariance along the trajectory. "
4904 "The '" +
4905 r.method + "' method integrates the mean only");
4906
4907 if (g_json_output) {
4908 line::reg::Json p = line::reg::Json::object();
4909 p["type"] = "QueueLengthVariance";
4910 p["indexBase"] = 0;
4911 p["Station"] = line::reg::Json::array();
4912 p["JobClass"] = line::reg::Json::array();
4913 p["QVar"] = line::reg::Json::array();
4914 p["QStd"] = line::reg::Json::array();
4915 for (std::size_t i = 0; i < sn.nstations; ++i)
4916 for (std::size_t c = 0; c < sn.nclasses; ++c) {
4917 if (r.moments.QVar(i, c) == 0.0) continue;
4918 p["Station"].push_back(sn.stations[i].name);
4919 p["JobClass"].push_back(sn.classes[c].name);
4920 p["QVar"].push_back(r.moments.QVar(i, c));
4921 p["QStd"].push_back(r.moments.QStd(i, c));
4922 }
4923 p["Sigma"] = matrix_json<double>(r.moments.Sigma);
4924 emit_analysis<T>("var", p, r.method);
4925 return 0;
4926 }
4927 std::printf("SolverFluid arith=%s method=%s second moment\n", line::num_traits<T>::name(),
4928 r.method.c_str());
4929 std::printf("%-16s %-14s %12s %12s\n", "Station", "JobClass", "QVar", "QStd");
4930 for (std::size_t i = 0; i < sn.nstations; ++i)
4931 for (std::size_t c = 0; c < sn.nclasses; ++c) {
4932 if (r.moments.QVar(i, c) == 0.0) continue;
4933 std::printf("%-16s %-14s %12.6g %12.6g\n", sn.stations[i].name.c_str(),
4934 sn.classes[c].name.c_str(), r.moments.QVar(i, c), r.moments.QStd(i, c));
4935 }
4936 return 0;
4937}
4938
4939/**
4940 * `-a odes`: `@@SolverFLD/exportODEs`, the drift itself rather than its fixed
4941 * point.
4942 *
4943 * The output is the LaTeX document the reference writes, printed to stdout so
4944 * that it can be redirected. It carries a machine-readable comment header
4945 * naming every state variable and every event, which is what makes the document
4946 * diffable against MATLAB's rather than only readable.
4947 */
4948template <class T>
4949int solve_model_fluid_odes(const std::string& file, const Knobs& k) {
4950 line::qn::Network<T> net = read_model<T>(file);
4952 if (!k.method.empty()) opt.method = k.method;
4953 if (k.tol >= 0.0) opt.tol = k.tol;
4954 const line::qn::NetworkStruct<T>& sn = net.get_struct();
4955 // `--notation` REACHES THE EXPORTER, and is not fixed at "scalar" here: the
4956 // matrix form is a different document of the same drift, and hardcoding one
4957 // while accepting a flag naming the other is the silent-acceptance defect
4958 // this CLI refuses everywhere else. An unrecognised name is refused by
4959 // `export_odes_latex` itself rather than defaulted.
4960 const std::string notation = k.notation.empty() ? "scalar" : k.notation;
4961 const std::string tex = line::fluid::solver_fluid_export_odes(sn, opt, notation, sn.name);
4962 if (g_json_output) {
4963 line::reg::Json p = line::reg::Json::object();
4964 p["type"] = "ODEs";
4965 p["notation"] = notation;
4966 // The document goes in a STRING VALUE, escaped by the JSON writer: it is
4967 // LaTeX, so it carries backslashes and newlines that a host reading raw
4968 // stdout would have to re-parse out of the surrounding table.
4969 p["latex"] = tex;
4970 // the exporter reads the method UNRESOLVED (default exports matrix), so report that, not the runner's pick
4971 emit_analysis<T>("odes", p, (opt.method.empty() || opt.method == "default") ? "matrix" : opt.method);
4972 return 0;
4973 }
4974 std::printf("%s\n", tex.c_str());
4975 return 0;
4976}
4977
4978/**
4979 * `-a jacobian`: `@@SolverFLD/getJacobian`, d f_i / d x_j of the mean-field
4980 * drift, with the equilibria beside it when they are asked for.
4981 *
4982 * This is the fixed point's LOCAL BEHAVIOUR, which no integration reports: the
4983 * eigenvalues of J tell a stable fixed point from a limit cycle and give the
4984 * rate at which the fluid approximation converges to it.
4985 *
4986 * The method must be a smooth one. `fluid_symbolic_drift` refuses the min-scaled
4987 * drifts by the factor that carries the kink, before any backend is contacted.
4988 */
4989template <class T>
4990int solve_model_fluid_jacobian(const std::string& file, const Knobs& k) {
4991 line::qn::Network<T> net = read_model<T>(file);
4993 if (!k.method.empty()) opt.method = k.method;
4994 const line::qn::NetworkStruct<T>& sn = net.get_struct();
4995 // pstar REACHES THE SYSTEM ONLY UNDER `pnorm`, which is the rule the
4996 // integrator and the exporter both follow: `matrix` and `default` leave it
4997 // at zero, selecting the hard min. That is why they have no Jacobian here
4998 // and `pnorm` does, and it is the reference's rule too -- MATLAB reads
4999 // options.config.pstar, which is unset unless asked for.
5000 std::string m = opt.method;
5001 if (m.compare(0, 4, "fld.") == 0) m = m.substr(4);
5003 sn, opt.method, (m == "pnorm" || opt.pstar_set) ? opt.pstar : 0.0, std::vector<double>());
5005 if (!k.symbolic.empty()) symopt.backend = k.symbolic;
5006 symopt.equilibria = k.equilibria;
5008
5009 if (g_json_output) {
5010 line::reg::Json p = line::reg::Json::object();
5011 p["type"] = "Jacobian";
5012 p["engine"] = jac.engine;
5013 p["vars"] = line::reg::Json(jac.vars);
5014 p["rhs"] = line::reg::Json(jac.rhs);
5015 line::reg::Json rows = line::reg::Json::array();
5016 for (std::size_t i = 0; i < jac.J.size(); ++i) rows.push_back(line::reg::Json(jac.J[i]));
5017 p["jacobian"] = rows;
5018 // `hasEquilibria` separates "asked and answered with none" from "never
5019 // asked"; an empty list alone would read as "this system has none".
5020 p["hasEquilibria"] = jac.has_equilibria;
5021 line::reg::Json eqs = line::reg::Json::array();
5022 for (std::size_t e = 0; e < jac.equilibria.size(); ++e) {
5023 line::reg::Json one = line::reg::Json::object();
5024 for (std::map<std::string, std::string>::const_iterator it = jac.equilibria[e].begin();
5025 it != jac.equilibria[e].end(); ++it)
5026 one[it->first] = it->second;
5027 eqs.push_back(one);
5028 }
5029 p["equilibria"] = eqs;
5030 emit_analysis<T>("jacobian", p,
5031 line::fluid::detail::fluid_resolve_method(sn, opt.method, opt));
5032 return 0;
5033 }
5034
5035 std::printf("engine=%s states=%zu\n", jac.engine.c_str(), jac.vars.size());
5036 for (std::size_t i = 0; i < jac.rhs.size(); ++i)
5037 std::printf("d%s/dt = %s\n", jac.vars[i].c_str(), jac.rhs[i].c_str());
5038 for (std::size_t i = 0; i < jac.J.size(); ++i)
5039 for (std::size_t j = 0; j < jac.J[i].size(); ++j) {
5040 // A structurally zero entry is printed, not skipped: a reader must be
5041 // able to tell a zero derivative from a row this port never emitted.
5042 std::printf("J[%s,%s] = %s\n", jac.vars[i].c_str(), jac.vars[j].c_str(),
5043 jac.J[i][j].c_str());
5044 }
5045 if (jac.has_equilibria) {
5046 if (jac.equilibria.empty())
5047 std::printf("equilibria: none in closed form (the solve found none, which is not a "
5048 "proof that none exist)\n");
5049 for (std::size_t e = 0; e < jac.equilibria.size(); ++e)
5050 for (std::map<std::string, std::string>::const_iterator it = jac.equilibria[e].begin();
5051 it != jac.equilibria[e].end(); ++it)
5052 std::printf("equilibrium %zu: %s = %s\n", e + 1, it->first.c_str(),
5053 it->second.c_str());
5054 }
5055 return 0;
5056}
5057
5058/**
5059 * `-s fluid -a tranvar`: `@@SolverFLD/getTranAvgVar`, the queue-length VARIANCE
5060 * along the trajectory, plus the full state covariance at each time point.
5061 *
5062 * NOT `-a var`, which reports the STATIONARY covariance of `minnormal` /
5063 * `mnrefined` -- one number per (station, class) at the fixed point. This is the
5064 * diffusion limit of Ko and Pender integrated alongside the fluid limit, so it
5065 * has a value at every t, and only `--method kp` produces it. Asking any other
5066 * method for it is an error rather than a misleading zero, which is the header's
5067 * own rule and is left to the header to enforce so the two flags cannot drift.
5068 */
5069template <class T>
5070int solve_model_fluid_tranvar(const std::string& file, const Knobs& k) {
5071 line::qn::Network<T> net = read_model<T>(file);
5072 const line::fluid::FluidOptions opt = fluid_options(k);
5073 const line::qn::NetworkStruct<T>& sn = net.get_struct();
5075 if (tr.t.empty())
5076 throw line::UnsupportedError(line::ErrorKind{"Analysis"}, "-a tranvar produced no trajectory points");
5077
5078 if (g_json_output) {
5079 line::reg::Json p = line::reg::Json::object();
5080 p["type"] = "TranAvgVarTable";
5081 p["indexBase"] = 0;
5082 p["t0"] = tr.t.front();
5083 p["t1"] = tr.t.back();
5084 line::reg::Json ts = line::reg::Json::array();
5085 for (std::size_t j = 0; j < tr.t.size(); ++j) ts.push_back(tr.t[j]);
5086 p["t"] = ts;
5087 line::reg::Json arr = line::reg::Json::array();
5088 for (std::size_t i = 0; i < sn.nstations; ++i)
5089 for (std::size_t c = 0; c < sn.nclasses; ++c) {
5090 if (sn.disabled[i][c]) continue;
5091 line::reg::Json e = line::reg::Json::object();
5092 e["Station"] = sn.stations[i].name;
5093 e["JobClass"] = sn.classes[c].name;
5094 e["station"] = i;
5095 e["jobclass"] = c;
5096 line::reg::Json v = line::reg::Json::array();
5097 for (std::size_t j = 0; j < tr.QVar.size(); ++j) v.push_back(tr.QVar[j](i, c));
5098 e["QVar"] = v;
5099 arr.push_back(e);
5100 }
5101 p["curves"] = arr;
5102 // The full covariance is the answer's other half: the per-pair variances
5103 // are its diagonal, and a caller asking for the diffusion limit wants the
5104 // off-diagonal correlations the limit is about.
5105 line::reg::Json sig = line::reg::Json::array();
5106 for (std::size_t j = 0; j < tr.Sigma.size(); ++j)
5107 sig.push_back(matrix_json<double>(tr.Sigma[j]));
5108 p["Sigma"] = sig;
5109 emit_analysis<T>("tranvar", p, "kp");
5110 return 0;
5111 }
5112 std::printf("SolverFluid arith=%s method=kp tspan=[%g,%g] points=%zu dim=%zu\n",
5113 line::num_traits<T>::name(), tr.t.front(), tr.t.back(), tr.t.size(),
5114 tr.Sigma.empty() ? std::size_t(0) : tr.Sigma.front().rows());
5115 std::printf("%-16s %-14s %12s %12s %12s\n", "Station", "JobClass", "Time", "QVar", "QStd");
5116 for (std::size_t i = 0; i < sn.nstations; ++i)
5117 for (std::size_t c = 0; c < sn.nclasses; ++c) {
5118 if (sn.disabled[i][c]) continue;
5119 for (std::size_t j = 0; j < tr.QVar.size(); ++j) {
5120 const double var = tr.QVar[j](i, c);
5121 std::printf("%-16s %-14s %12.6g %12.6g %12.6g\n", sn.stations[i].name.c_str(),
5122 sn.classes[c].name.c_str(), tr.t[j], var,
5123 var >= 0.0 ? std::sqrt(var) : std::numeric_limits<double>::quiet_NaN());
5124 }
5125 }
5126 return 0;
5127}
5128
5129/**
5130 * `-s fluid -a tran`: `@@SolverFLD/getTranAvg`, the metrics ALONG the
5131 * trajectory rather than at its fixed point.
5132 *
5133 * `--tspan` is optional here and required on the MAM arm, and the difference is
5134 * the reference's: `options.timespan` defaults to [0, Inf] for the fluid solver,
5135 * which does not mean "integrate forever" but "integrate until the state stops
5136 * moving" -- `solver_fluid_tran_avg` reproduces the horizon that adaptive loop
5137 * converges at. A caller that names a horizon gets exactly that one.
5138 *
5139 * The reference forces `closing` for a transient (the matrix and smoothed
5140 * variants are steady-state devices) and warns when it does; the port forces it
5141 * too, and the banner names the method that actually integrated. `dae` is the
5142 * one exception the reference itself makes -- it has a trajectory of its own,
5143 * with conservation carried as an algebraic equation -- so
5144 * `solver_fluid_run_transient` routes it rather than substituting the
5145 * first-order drift under its name.
5146 */
5147template <class T>
5148int solve_model_fluid_tran(const std::string& file, const Knobs& k) {
5149 line::qn::Network<T> net = read_model<T>(file);
5150 const line::fluid::FluidOptions opt = fluid_options(k);
5151 const line::qn::NetworkStruct<T>& sn = net.get_struct();
5152 const std::vector<line::fluid::FluidTranPoint> tr =
5154 if (tr.empty()) throw line::UnsupportedError(line::ErrorKind{"Analysis"}, "-a tran produced no trajectory points");
5155 // the banner names the method that integrated: 'dae' keeps its own trajectory, every other one is 'closing'
5156 const std::string tran_method =
5157 line::fluid::detail::fluid_unqualify(opt.method) == "dae" ? std::string("dae") : std::string("closing");
5158
5159 if (g_json_output) {
5160 line::reg::Json p = line::reg::Json::object();
5161 p["type"] = "TranAvgTable";
5162 p["indexBase"] = 0;
5163 p["t0"] = 0.0;
5164 p["t1"] = tr.back().t;
5165 line::reg::Json ts = line::reg::Json::array();
5166 for (std::size_t j = 0; j < tr.size(); ++j) ts.push_back(tr[j].t);
5167 line::reg::Json arr = line::reg::Json::array();
5168 for (std::size_t i = 0; i < sn.nstations; ++i)
5169 for (std::size_t c = 0; c < sn.nclasses; ++c) {
5170 if (sn.disabled[i][c]) continue;
5171 line::reg::Json e = line::reg::Json::object();
5172 e["Station"] = sn.stations[i].name;
5173 e["JobClass"] = sn.classes[c].name;
5174 e["station"] = i;
5175 e["jobclass"] = c;
5176 e["t"] = ts;
5177 line::reg::Json q = line::reg::Json::array(), u = line::reg::Json::array(),
5178 x = line::reg::Json::array();
5179 for (std::size_t j = 0; j < tr.size(); ++j) {
5180 q.push_back(tr[j].QN(i, c));
5181 u.push_back(tr[j].UN(i, c));
5182 x.push_back(tr[j].TN(i, c));
5183 }
5184 e["QLen"] = q;
5185 e["Util"] = u;
5186 e["Tput"] = x;
5187 arr.push_back(e);
5188 }
5189 p["curves"] = arr;
5190 emit_analysis<T>("tran", p, tran_method);
5191 return 0;
5192 }
5193 std::printf("SolverFluid arith=%s method=%s tspan=[0,%g] points=%zu\n",
5194 line::num_traits<T>::name(), tran_method.c_str(), tr.back().t, tr.size());
5195 std::printf("%-16s %-14s %12s %12s %12s %12s\n", "Station", "JobClass", "Time", "QLen", "Util",
5196 "Tput");
5197 for (std::size_t i = 0; i < sn.nstations; ++i)
5198 for (std::size_t c = 0; c < sn.nclasses; ++c) {
5199 if (sn.disabled[i][c]) continue;
5200 for (std::size_t j = 0; j < tr.size(); ++j)
5201 std::printf("%-16s %-14s %12.6g %12.6g %12.6g %12.6g\n",
5202 sn.stations[i].name.c_str(), sn.classes[c].name.c_str(), tr[j].t,
5203 tr[j].QN(i, c), tr[j].UN(i, c), tr[j].TN(i, c));
5204 }
5205 return 0;
5206}
5207
5208/**
5209 * `-s fluid -a prob`: `@@SolverFLD/getProbAggr`, the probability that a station
5210 * holds the marginal population of the model's default state.
5211 *
5212 * IT IS NOT THE MVA ARM'S ANSWER AND IS NOT MEANT TO BE. The fluid solver has
5213 * no state space, so the law is fitted to the means it does produce -- a
5214 * binomial per closed class, the BCMP marginal per open one -- and under a
5215 * moment closure it is instead the multivariate normal the closure supplies,
5216 * correlation between the classes included. Two solvers disagreeing here is the
5217 * approximation showing, not a defect.
5218 *
5219 * The log-probability is reported beside it because the fitted law underflows
5220 * on a large population, where the linear value is 0 and the log one is not.
5221 */
5222template <class T>
5223int solve_model_fluid_prob(const std::string& file, const Knobs& k) {
5224 line::qn::Network<T> net = read_model<T>(file);
5225 const line::fluid::FluidOptions opt = fluid_options(k);
5226 const line::qn::NetworkStruct<T>& sn = net.get_struct();
5228
5229 std::vector<double> pr(sn.nstations, 0.0), lg(sn.nstations, 0.0);
5230 for (std::size_t i = 0; i < sn.nstations; ++i)
5231 pr[i] = line::fluid::fluid_prob_aggr(sn, r, i + 1, &lg[i]);
5232
5233 if (g_json_output) {
5234 line::reg::Json p = line::reg::Json::object();
5235 p["type"] = "ProbAggr";
5236 p["indexBase"] = 0;
5237 line::reg::Json st = line::reg::Json::array(), pa = line::reg::Json::array(),
5238 lp = line::reg::Json::array();
5239 for (std::size_t i = 0; i < sn.nstations; ++i) {
5240 st.push_back(sn.stations[i].name);
5241 pa.push_back(pr[i]);
5242 lp.push_back(lg[i]);
5243 }
5244 p["Station"] = st;
5245 p["ProbAggr"] = pa;
5246 p["logProbAggr"] = lp;
5247 emit_analysis<T>("prob", p, r.method);
5248 return 0;
5249 }
5250 std::printf("SolverFluid arith=%s method=%s type=%s\n", line::num_traits<T>::name(),
5251 r.method.c_str(), line::util::method_type("FLD", r.method).c_str());
5252 std::printf("%-16s %14s %14s\n", "Station", "ProbAggr", "logProbAggr");
5253 for (std::size_t i = 0; i < sn.nstations; ++i)
5254 std::printf("%-16s %14.10g %14.10g\n", sn.stations[i].name.c_str(), pr[i], lg[i]);
5255 return 0;
5256}
5257
5258/**
5259 * `-s fluid -a cdf`: `@@SolverFLD/getCdfRespT`, the WHOLE response-time law per
5260 * (station, class) and not only its mean.
5261 *
5262 * The law is read off a second integration in which the jobs present at the
5263 * steady state are MARKED and followed to their departure, so it is the
5264 * stationary response-time distribution of the fluid model. The solve that
5265 * produces the state to mark in is run here, as the reference runs it: its
5266 * `getCdfRespT` clears the cached result and re-runs `getAvg` first.
5267 */
5268template <class T>
5269int solve_model_fluid_cdf(const std::string& file, const Knobs& k) {
5270 line::qn::Network<T> net = read_model<T>(file);
5271 const line::fluid::FluidOptions opt = fluid_options(k);
5272 const line::qn::NetworkStruct<T>& sn = net.get_struct();
5273 const std::vector<std::vector<line::fluid::FluidPassage> > RD =
5275
5276 if (g_json_output) {
5277 line::reg::Json p = line::reg::Json::object();
5278 p["type"] = "CdfRespT";
5279 p["indexBase"] = 0;
5280 line::reg::Json arr = line::reg::Json::array();
5281 for (std::size_t i = 0; i < RD.size(); ++i)
5282 for (std::size_t c = 0; c < RD[i].size(); ++c) {
5283 // An empty curve is an ABSENT law -- a Source, or a class the
5284 // station does not serve -- and is omitted rather than sent as a
5285 // degenerate one.
5286 if (RD[i][c].t.empty()) continue;
5287 line::reg::Json e = line::reg::Json::object();
5288 e["Station"] = sn.stations[i].name;
5289 e["JobClass"] = sn.classes[c].name;
5290 e["station"] = i;
5291 e["jobclass"] = c;
5292 e["t"] = line::reg::Json(RD[i][c].t);
5293 e["F"] = line::reg::Json(RD[i][c].cdf);
5294 arr.push_back(e);
5295 }
5296 p["respt"] = arr;
5297 emit_analysis<T>("cdf", p, std::string());
5298 return 0;
5299 }
5300 std::printf("SolverFluid arith=%s\n", line::num_traits<T>::name());
5301 std::printf("%-16s %-14s %14s %14s\n", "Station", "JobClass", "Time", "F(t)");
5302 for (std::size_t i = 0; i < RD.size(); ++i)
5303 for (std::size_t c = 0; c < RD[i].size(); ++c)
5304 for (std::size_t j = 0; j < RD[i][c].t.size(); ++j)
5305 std::printf("%-16s %-14s %14.8g %14.10g\n", sn.stations[i].name.c_str(),
5306 sn.classes[c].name.c_str(), RD[i][c].t[j], RD[i][c].cdf[j]);
5307 return 0;
5308}
5309
5310/**
5311 * `-s fluid -a aoi`: `@@SolverFLD/getAvgAoI` and `getCdfAoI` in one answer, the
5312 * Age of Information and Peak AoI laws of a status-update system.
5313 *
5314 * ONLY THE `mfq` METHOD HAS THEM, and only on the topology the age laws are
5315 * defined for: one open class through Source -> Queue -> Sink, a single server,
5316 * capacity 1 (bufferless) or 2 (single buffer), FCFS/LCFS/LCFSPR. The topology
5317 * is tested first so a model that is not one is told WHICH condition it fails
5318 * rather than being handed a number computed for a different system.
5319 *
5320 * `--method` may only say `mfq` here: silently overriding a caller who asked for
5321 * another method would report the age laws under a method that does not produce
5322 * them.
5323 */
5324template <class T>
5325int solve_model_fluid_aoi(const std::string& file, const Knobs& k) {
5326 line::qn::Network<T> net = read_model<T>(file);
5327 const line::qn::NetworkStruct<T>& sn = net.get_struct();
5329 if (!top.ok)
5330 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
5331 "-a aoi reports the age of a status-update system and needs the topology the age laws "
5332 "are defined for: " +
5333 (top.error.empty() ? std::string("this model is not one") : top.error));
5334 line::fluid::FluidOptions opt = fluid_options(k);
5335 const std::string requested = line::fluid::detail::fluid_unqualify(opt.method);
5336 if (requested != "default" && requested != "mfq")
5337 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
5338 "-a aoi is the AoI branch of the 'mfq' method; '" + requested +
5339 "' integrates the mean-field drift and carries no age process");
5340 opt.method = "mfq";
5342 if (!r.has_aoi)
5343 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
5344 "-a aoi: the 'mfq' method did not take its AoI branch on this model");
5345
5346 // The grid `getCdfAoI` builds when the caller names no time points: five
5347 // mean ages, which covers the bulk of both laws.
5348 const double base = (std::isfinite(r.aoi.aoi.mean) && r.aoi.aoi.mean > 0.0) ? r.aoi.aoi.mean : 1.0;
5349 const std::size_t np = 200;
5350 std::vector<double> tv(np), fa(np), fp(np);
5351 for (std::size_t j = 0; j < np; ++j) {
5352 tv[j] = 5.0 * base * static_cast<double>(j) / static_cast<double>(np - 1);
5353 fa[j] = line::fluid::aoi_cdf(r.aoi.aoi, tv[j]);
5354 fp[j] = line::fluid::aoi_cdf(r.aoi.paoi, tv[j]);
5355 }
5356 const double asd = std::sqrt(std::max(0.0, r.aoi.aoi.var));
5357 const double psd = std::sqrt(std::max(0.0, r.aoi.paoi.var));
5358
5359 if (g_json_output) {
5360 line::reg::Json p = line::reg::Json::object();
5361 p["type"] = "AoI";
5362 p["systemType"] = r.aoi.system_type;
5363 p["preemption"] = r.aoi.preemption;
5364 p["AoIMean"] = r.aoi.aoi.mean;
5365 p["AoIVar"] = r.aoi.aoi.var;
5366 p["AoIStd"] = asd;
5367 p["PAoIMean"] = r.aoi.paoi.mean;
5368 p["PAoIVar"] = r.aoi.paoi.var;
5369 p["PAoIStd"] = psd;
5370 p["t"] = line::reg::Json(tv);
5371 p["AoICdf"] = line::reg::Json(fa);
5372 p["PAoICdf"] = line::reg::Json(fp);
5373 // The (g, A, h) DENSITY triples, not only the curve evaluated above.
5374 // `getCdfAoI` takes an optional t_values, and a caller who names their
5375 // own grid cannot be served from a fixed 200-point one; with the triple
5376 // they evaluate the same law at their own abscissae. `solve_mfq_aoi`
5377 // normalizes g so that g*expm(A t)*h is the density, so the survival
5378 // function carries an extra inv(A) -- the MATLAB getter's own note.
5379 p["AoI_g"] = line::reg::Json(r.aoi.aoi.g);
5380 p["AoI_A"] = matrix_json(r.aoi.aoi.A);
5381 p["AoI_h"] = line::reg::Json(r.aoi.aoi.h);
5382 p["PAoI_g"] = line::reg::Json(r.aoi.paoi.g);
5383 p["PAoI_A"] = matrix_json(r.aoi.paoi.A);
5384 p["PAoI_h"] = line::reg::Json(r.aoi.paoi.h);
5385 emit_analysis<T>("aoi", p, r.method);
5386 return 0;
5387 }
5388 std::printf("SolverFluid arith=%s method=mfq system=%s preemption=%.6g\n",
5390 std::printf("%-8s %14s %14s %14s\n", "Metric", "Mean", "Var", "Std");
5391 std::printf("%-8s %14.10g %14.10g %14.10g\n", "AoI", r.aoi.aoi.mean, r.aoi.aoi.var, asd);
5392 std::printf("%-8s %14.10g %14.10g %14.10g\n", "PAoI", r.aoi.paoi.mean, r.aoi.paoi.var, psd);
5393 std::printf("%14s %14s %14s\n", "Time", "F_AoI(t)", "F_PAoI(t)");
5394 for (std::size_t j = 0; j < np; ++j)
5395 std::printf("%14.8g %14.10g %14.10g\n", tv[j], fa[j], fp[j]);
5396 return 0;
5397}
5398
5399/**
5400 * Solve a Network model.json and print its aggregate state probabilities:
5401 * getProbSysAggr (the whole-system joint) and getProbAggr per station, over the
5402 * model's default initial state. These fit the MVA means and so need logarithms;
5403 * under exact/Rational they refuse by name.
5404 */
5405template <class T>
5406int solve_model_prob(const std::string& file, const Knobs& k) {
5408 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
5409 "the -a prob analysis fits a binomial/product-form law and needs transcendental "
5410 "arithmetic; rerun with --arith double or --arith real");
5411 } else {
5412 line::qn::Network<T> net = read_model<T>(file);
5414 if (!k.method.empty() && k.method != "default") opt.method = k.method;
5415 if (k.tol >= 0.0) opt.tol = k.tol;
5416 if (k.iter_tol >= 0.0) opt.iter_tol = k.iter_tol;
5417 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
5418 line::Matrix<T> init;
5420 const line::qn::NetworkStruct<T>& sn = net.get_struct();
5421 const line::mva::AggrResult<T> ps =
5423 if (g_json_output) {
5424 line::reg::Json p = line::reg::Json::object();
5425 p["type"] = "ProbAggr";
5426 p["indexBase"] = 0;
5427 p["ProbSysAggr"] = line::num_traits<T>::to_double(ps.P);
5428 line::reg::Json st = line::reg::Json::array(), pa = line::reg::Json::array();
5429 for (std::size_t i = 0; i < sn.nstations; ++i) {
5430 st.push_back(sn.stations[i].name);
5431 pa.push_back(line::num_traits<T>::to_double(
5432 line::mva::solver_mva_get_prob_aggr(sn, r, i + 1, opt.method).P));
5433 }
5434 p["Station"] = st;
5435 p["ProbAggr"] = pa;
5436 emit_analysis<T>("prob", p, r.actualmethod);
5437 return 0;
5438 }
5439 std::printf("SolverMVA arith=%s method=%s type=%s\n", line::num_traits<T>::name(),
5440 r.actualmethod.c_str(),
5441 line::util::method_type("MVA", r.actualmethod).c_str());
5442 std::printf("ProbSysAggr %.10g\n", line::num_traits<T>::to_double(ps.P));
5443 std::printf("%-16s %14s\n", "Station", "ProbAggr");
5444 for (std::size_t i = 0; i < sn.nstations; ++i) {
5445 const line::mva::AggrResult<T> pa =
5447 std::printf("%-16s %14.10g\n", sn.stations[i].name.c_str(),
5449 }
5450 return 0;
5451 }
5452}
5453
5454/**
5455 * `-s mva -a marg`: `@@SolverMVA/getProbMarg`, P(n jobs of class r at station i).
5456 *
5457 * THE WHOLE GRID BY DEFAULT, one curve per (station, class): the reference takes
5458 * the station and the class as arguments and this CLI has no notion of a
5459 * "current" pair, so reporting every pair is the only reading that answers the
5460 * method rather than a choice this file would be making on the caller's behalf.
5461 * `--node` and `--class` narrow it to one node's station and one class, and
5462 * `--marg-states` is the reference's third argument `state_m`: the n values to
5463 * report, in place of the default range each case picks for itself (0..N_r for a
5464 * closed class, mean + 5 sigma for a Poisson, the 1e-10 tail for a geometric).
5465 *
5466 * A NODE THAT IS NOT A STATION IS AN ERROR, not an empty answer: a queue-length
5467 * law at a ClassSwitch is not a quantity, and defaulting to the whole network
5468 * after the caller narrowed it would report more than was asked for.
5469 */
5470template <class T>
5471int solve_model_marg(const std::string& file, const Knobs& k) {
5473 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
5474 "the -a marg analysis fits a binomial / Poisson / geometric law and needs "
5475 "transcendental arithmetic; rerun with --arith double or --arith real");
5476 } else {
5477 line::qn::Network<T> net = read_model<T>(file);
5479 if (!k.method.empty() && k.method != "default") opt.method = k.method;
5480 if (k.tol >= 0.0) opt.tol = k.tol;
5481 if (k.iter_tol >= 0.0) opt.iter_tol = k.iter_tol;
5482 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
5483 line::Matrix<T> init;
5485 const line::qn::NetworkStruct<T>& sn = net.get_struct();
5486
5487 std::vector<std::size_t> ists; // 1-based station indices to report
5488 if (k.node) {
5489 if (k.node > sn.nof_nodes())
5490 throw line::InputError("--node " + std::to_string(k.node) +
5491 " exceeds the number of nodes in the model (" +
5492 std::to_string(sn.nof_nodes()) + ")");
5493 const std::size_t ist = sn.nodes[k.node - 1].station;
5494 if (!ist)
5495 throw line::InputError("--node " + std::to_string(k.node) + " ('" +
5496 sn.nodes[k.node - 1].name +
5497 "') is not a station, and a queue-length distribution is "
5498 "reported per station");
5499 ists.push_back(ist);
5500 } else {
5501 for (std::size_t i = 0; i < sn.nstations; ++i) ists.push_back(i + 1);
5502 }
5503 std::vector<std::size_t> rs; // 1-based class indices to report
5504 if (k.jobclass) {
5505 if (k.jobclass > sn.nclasses)
5506 throw line::InputError("--class " + std::to_string(k.jobclass) +
5507 " exceeds the number of classes in the model");
5508 rs.push_back(k.jobclass);
5509 } else {
5510 for (std::size_t c = 0; c < sn.nclasses; ++c) rs.push_back(c + 1);
5511 }
5512
5513 // Every curve first: a pair the reference refuses must not leave a
5514 // banner and a column header standing above an answer that never came.
5515 std::vector<line::mva::MargResult<T> > curves;
5516 for (std::size_t a = 0; a < ists.size(); ++a)
5517 for (std::size_t b = 0; b < rs.size(); ++b)
5518 curves.push_back(line::mva::solver_mva_get_prob_marg(sn, r, ists[a], rs[b],
5519 k.marg_states, opt.method));
5520
5521 if (g_json_output) {
5522 line::reg::Json p = line::reg::Json::object();
5523 p["type"] = "ProbMarg";
5524 p["indexBase"] = 0;
5525 line::reg::Json arr = line::reg::Json::array();
5526 for (std::size_t a = 0, q = 0; a < ists.size(); ++a)
5527 for (std::size_t b = 0; b < rs.size(); ++b, ++q) {
5528 const line::mva::MargResult<T>& m = curves[q];
5529 line::reg::Json e = line::reg::Json::object();
5530 e["station"] = ists[a] - 1;
5531 e["Station"] = sn.stations[ists[a] - 1].name;
5532 e["jobclass"] = rs[b] - 1;
5533 e["JobClass"] = sn.classes[rs[b] - 1].name;
5534 line::reg::Json jobs = line::reg::Json::array();
5535 for (std::size_t n = 0; n < m.P.size(); ++n)
5536 jobs.push_back(k.marg_states.empty() ? static_cast<long>(n)
5537 : k.marg_states[n]);
5538 e["Jobs"] = jobs;
5539 e["P"] = vector_json(m.P);
5540 e["logP"] = vector_json(m.logP);
5541 arr.push_back(e);
5542 }
5543 p["marginal"] = arr;
5544 emit_analysis<T>("marg", p, r.actualmethod);
5545 return 0;
5546 }
5547 std::printf("SolverMVA arith=%s method=%s type=%s\n", line::num_traits<T>::name(),
5548 r.actualmethod.c_str(),
5549 line::util::method_type("MVA", r.actualmethod).c_str());
5550 std::printf("%-16s %-14s %-8s %16s\n", "Station", "JobClass", "Jobs", "ProbMarg");
5551 for (std::size_t a = 0, q = 0; a < ists.size(); ++a)
5552 for (std::size_t b = 0; b < rs.size(); ++b, ++q) {
5553 const line::mva::MargResult<T>& m = curves[q];
5554 for (std::size_t n = 0; n < m.P.size(); ++n)
5555 std::printf("%-16s %-14s %-8ld %16.10g\n",
5556 sn.stations[ists[a] - 1].name.c_str(),
5557 sn.classes[rs[b] - 1].name.c_str(),
5558 k.marg_states.empty() ? static_cast<long>(n) : k.marg_states[n],
5560 }
5561 return 0;
5562 }
5563}
5564
5565/**
5566 * Mean busy period of a named subnetwork, Daduna (J. ACM 35(3), 1988).
5567 *
5568 * The transform `solver_nc_busyp` has been in the port since it landed, and
5569 * `ldes_cli` has answered `--busyperiod` all along, so the ONLY thing between
5570 * a caller and the analytical form was a `-a` token: asking this CLI for a busy
5571 * period meant simulating a quantity there is a closed form for.
5572 *
5573 * `--busyperiod-subnet` is 1-BASED, as every station index this CLI takes is,
5574 * and is required: a busy period is defined for a NAMED set of stations and
5575 * defaulting it would answer about a subnetwork the caller never chose. The
5576 * orders default to 1, the ordinary busy period.
5577 */
5578template <class T>
5579int solve_model_nc_busyp(const std::string& file, const Knobs& k) {
5580 if (k.busy_subnet.empty())
5581 throw line::InputError(
5582 "-a busyperiod needs --busyperiod-subnet: the busy period is defined for a named "
5583 "subnetwork of stations, and no default can choose one");
5584 line::qn::Network<T> net = read_model<T>(file);
5585 const line::qn::NetworkStruct<T>& sn = net.get_struct();
5586 std::vector<std::size_t> subnet;
5587 for (std::size_t t = 0; t < k.busy_subnet.size(); ++t) {
5588 if (k.busy_subnet[t] > sn.nstations)
5589 throw line::InputError("--busyperiod-subnet names station " +
5590 std::to_string(k.busy_subnet[t]) + ", beyond the model's " +
5591 std::to_string(sn.nstations));
5592 subnet.push_back(k.busy_subnet[t] - 1);
5593 }
5594 std::vector<std::size_t> orders = k.busy_orders;
5595 if (orders.empty()) orders.push_back(1);
5596 const std::vector<double> b = line::nc::solver_nc_busyp(sn, subnet, orders);
5597
5598 if (g_json_output) {
5599 line::reg::Json p = line::reg::Json::object();
5600 p["type"] = "BusyPeriod";
5601 p["indexBase"] = 0;
5602 line::reg::Json sj = line::reg::Json::array();
5603 for (std::size_t t = 0; t < subnet.size(); ++t) sj.push_back(subnet[t]);
5604 line::reg::Json oj = line::reg::Json::array();
5605 for (std::size_t t = 0; t < orders.size(); ++t) oj.push_back(orders[t]);
5606 line::reg::Json bj = line::reg::Json::array();
5607 for (std::size_t t = 0; t < b.size(); ++t) bj.push_back(b[t]);
5608 p["subnet"] = sj;
5609 p["orders"] = oj;
5610 p["b"] = bj;
5611 emit_analysis<T>("busyperiod", p, "daduna");
5612 return 0;
5613 }
5614 std::printf("SolverNC arith=%s busy period, subnetwork {", line::num_traits<T>::name());
5615 for (std::size_t t = 0; t < k.busy_subnet.size(); ++t)
5616 std::printf("%s%zu", t ? "," : "", k.busy_subnet[t]);
5617 std::printf("}\n");
5618 for (std::size_t t = 0; t < orders.size(); ++t)
5619 std::printf(" order %zu %.10g\n", orders[t], b[t]);
5620 return 0;
5621}
5622
5623/**
5624 * `-a normconst`: `@@SolverMVA/getProbNormConstAggr` and `@@SolverNC`'s.
5625 *
5626 * ONE ANALYSIS, TWO SOLVERS, AND THEY DO NOT COMPUTE IT THE SAME WAY. The NC
5627 * arm reads the constant its own solve already formed. The MVA arm RE-ENTERS the
5628 * analyzer at method='exact', as the reference does, because only the exact MVA
5629 * recursion carries a G: an AMVA solve has none, and reporting the requested
5630 * method's number would attribute the constant to an algorithm that never
5631 * produced one. That re-entry is why this is a separate `-a` and not a field on
5632 * the `-s mva` banner, where it would charge every average solve for a second
5633 * exact one.
5634 *
5635 * WHAT A MODEL WITH NO CONSTANT REPORTS IS THE ANALYZER'S OWN ANSWER, not a
5636 * substitution made here, and the two cases differ: the branches that form no G
5637 * at all -- MVAC, the LCFS chain -- set lG to NaN at the source and print nan,
5638 * while the open-queue closed forms report lG = 0 exactly as
5639 * solver_mva_qsys_analyzer.m:54,96,235 does. Neither is edited on the way out.
5640 */
5641template <class T>
5642int solve_model_normconst(const std::string& file, const Knobs& k, const std::string& solver) {
5643 line::qn::Network<T> net = read_model<T>(file);
5644 const line::qn::NetworkStruct<T>& sn = net.get_struct();
5645 double lG = 0.0;
5646 std::string method;
5647 if (solver == "nc") {
5649 if (!k.method.empty() && k.method != "default") opt.method = k.method;
5650 if (k.tol >= 0.0) opt.tol = k.tol;
5651 if (k.iter_tol >= 0.0) opt.iter_tol = k.iter_tol;
5652 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
5654 lG = r.lognormconst.has_value() ? r.lognormconst.value()
5655 : std::numeric_limits<double>::quiet_NaN();
5656 method = r.actualmethod;
5657 } else {
5659 if (!k.method.empty() && k.method != "default") opt.method = k.method;
5660 if (k.tol >= 0.0) opt.tol = k.tol;
5661 if (k.iter_tol >= 0.0) opt.iter_tol = k.iter_tol;
5662 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
5664 method = "exact";
5665 }
5666 if (g_json_output) {
5667 line::reg::Json p = line::reg::Json::object();
5668 p["type"] = "NormConst";
5669 p["indexBase"] = 0;
5670 // A NaN rides as JSON null, which is the table's nan on the wire.
5671 p["logNormConstAggr"] = lG;
5672 emit_analysis<T>("normconst", p, method);
5673 return 0;
5674 }
5675 std::printf("Solver%s arith=%s method=%s lognormconst=%.10g\n",
5676 solver == "nc" ? "NC" : "MVA", line::num_traits<T>::name(), method.c_str(), lG);
5677 return 0;
5678}
5679
5680/** The model's declared per-class placement, in `solver_nc_*`'s own container. */
5681template <class T>
5682line::nc::MarginalState nc_declared_marginal(const line::qn::NetworkStruct<T>& sn) {
5684 line::nc::MarginalState out(sn.nstations, std::vector<int>(sn.nclasses, 0));
5685 for (std::size_t i = 0; i < sn.nstations; ++i)
5686 for (std::size_t r = 0; r < sn.nclasses; ++r)
5687 out[i][r] = static_cast<int>(std::llround(line::num_traits<T>::to_double(nir(i, r))));
5688 return out;
5689}
5690
5691/**
5692 * The same two probabilities under SolverNC: `@@SolverNC/getProbSysAggr.m` and
5693 * `@@SolverNC/getProbAggr.m`, over the model's declared state.
5694 *
5695 * NOT THE SAME NUMBERS AS `-s mva -a prob`, and that is the point of having
5696 * both. SolverMVA fits a binomial to its own means (Schmidt 1997); these are a
5697 * ratio of normalizing constants and are the product-form model's own
5698 * probabilities exactly. A closed model therefore reports different figures
5699 * under the two solvers, and the NC ones are the reference.
5700 */
5701template <class T>
5702int solve_model_nc_prob(const std::string& file, const Knobs& k) {
5704 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
5705 "the -s nc -a prob analysis exponentiates a difference of log normalizing constants "
5706 "and needs transcendental arithmetic; rerun with --arith double or --arith real");
5707 } else {
5708 line::qn::Network<T> net = read_model<T>(file);
5710 if (!k.method.empty() && k.method != "default") opt.method = k.method;
5711 if (k.tol >= 0.0) opt.tol = k.tol;
5712 if (k.iter_tol >= 0.0) opt.iter_tol = k.iter_tol;
5713 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
5714 const line::qn::NetworkStruct<T>& sn = net.get_struct();
5715
5716 // The state is the MODEL'S OWN, which `model.json` now carries: a
5717 // stateful node's declared row is decoded to the per-class counts the
5718 // reference reads with `State.toMarginal(sn, ist, state{isf})`. Where a
5719 // station declares none, the default marking is rebuilt for it -- every
5720 // closed class at its reference station -- which is what `initDefault`
5721 // would have put there.
5722 line::nc::MarginalState nir = nc_declared_marginal<T>(sn);
5723 // `--state` is `getProb(node, state)`'s second argument, decoded the way
5724 // the reference decodes it: it substitutes the row into `sn.state{isf}`
5725 // and takes `State.toMarginal` of the result, so what reaches the
5726 // probability is that node's PER-CLASS COUNTS and every other node's
5727 // declared ones. Passing the row through untouched would treat an
5728 // encoding as a job vector, and on a station with phase-type service the
5729 // two differ in both width and meaning.
5730 if (!k.state.empty()) {
5731 if (!k.node)
5732 throw line::InputError(
5733 "--state is the state of ONE node and needs --node to say which");
5734 const std::size_t ist =
5735 k.node <= sn.nodes.size() ? sn.nodes[k.node - 1].station : 0;
5736 if (ist == 0)
5737 throw line::InputError("--node " + std::to_string(k.node) +
5738 " is not a station, so it has no queue-length state");
5739 std::vector<std::size_t> ph(sn.nclasses, 1), shift(sn.nclasses, 0);
5740 std::size_t w = 0;
5741 for (std::size_t c = 0; c < sn.nclasses; ++c) {
5742 ph[c] = sn.phases_of(ist, c + 1);
5743 shift[c] = w;
5744 w += ph[c];
5745 }
5746 std::vector<T> row(k.state.size());
5747 for (std::size_t i = 0; i < k.state.size(); ++i)
5748 row[i] = line::num_traits<T>::from_int(k.state[i]);
5749 const line::qn::Marginal<T> m =
5750 line::qn::to_marginal(sn, ist, row, ph, shift, sn.nvars_of(k.node));
5751 for (std::size_t c = 0; c < sn.nclasses; ++c)
5752 nir[ist - 1][c] =
5753 static_cast<int>(std::llround(line::num_traits<T>::to_double(m.nir[c])));
5754 }
5755
5756 // THE SOLVE'S lG IS NOT THIS lG. `solver_nc_solve` normalizes the
5757 // SEIDMANN-REDUCED model -- a multiserver station enters as demand/c
5758 // with the residual folded into the delay -- while the probability
5759 // identity F_i G_{-i} / G needs the constant of the load-dependent
5760 // lattice mu(n) = min(n, c) that F_i and G_{-i} are computed on. The two
5761 // coincide only without multiservers. `solver_nc_margaggr` computes its
5762 // own, once, for every station -- which is the reference's
5763 // `logNormConstAggr` caching, not a per-station resolve.
5764 // THREE OF THE FOUR VIEWS NEED A LOAD-DEPENDENT NORMALIZING CONSTANT
5765 // over the WHOLE network, and `pfqn_ncld` computes it with the caller's
5766 // own method (`solver_nc_margaggr.m:53`, `solver_nc_marg.m:35`,
5767 // `solver_nc_joint.m:32`). A method name with no load-dependent
5768 // algorithm behind it -- the stochastic estimators `ls`, `mci`, `imci`,
5769 // `mcmc`, and the load-INDEPENDENT exact ones such as `comom` -- has
5770 // nothing to run there, and MATLAB refuses `getProb`, `getProbSys` and
5771 // `getProbAggr` under such a name with `pfqn_ncld`'s own message
5772 // (`pfqn_ncld.m:210`). `solver_nc_jointaggr` is the one that escapes:
5773 // its lG comes from `solver_nc` and its per-station factors are
5774 // SINGLE-STATION, which `pfqn_ncld` answers from a degenerate return
5775 // before it ever looks at the name. So the three are OMITTED rather
5776 // than faked or allowed to fail the whole analysis, exactly as
5777 // `-s mva -a prob` omits the detailed pair it has no counterpart for;
5778 // `ProbSysAggr` is still reported, which is what the caller asked for.
5780 const bool has_ld = line::pfqn::ncld_method_try(opt.method, ldm);
5781
5783 T pjoint = line::num_traits<T>::from_int(0);
5784 if (has_ld) {
5785 mr = line::nc::solver_nc_margaggr(sn, opt, nir,
5786 std::numeric_limits<double>::quiet_NaN());
5787 // THE DETAILED PAIR TOO, because `getProb` and `getProbSys` are not
5788 // the aggregate ones with rounding: `solver_nc_marg` and
5789 // `solver_nc_joint` carry the class-within-chain split
5790 // `lg0_i - lG0_i` that the aggregate pair sums out, so on a
5791 // multichain model they are different numbers rather than the same
5792 // one to more places.
5793 mdet = line::nc::solver_nc_marg(sn, opt, nir,
5794 std::numeric_limits<double>::quiet_NaN());
5795 pjoint = line::nc::solver_nc_joint<T>(sn, opt, nir, nullptr);
5796 }
5797 const T ps = line::nc::solver_nc_getprob_sys_aggr(sn, opt, nir);
5798
5800 const std::string am = (opt.method == "default" && !d.actualmethod.empty() &&
5801 d.actualmethod != "default")
5802 ? "default/" + d.actualmethod
5803 : d.actualmethod;
5804 if (g_json_output) {
5805 line::reg::Json p = line::reg::Json::object();
5806 p["type"] = "ProbAggr";
5807 p["indexBase"] = 0;
5808 p["ProbSysAggr"] = line::num_traits<T>::to_double(ps);
5809 line::reg::Json st = line::reg::Json::array();
5810 for (std::size_t i = 0; i < sn.nstations; ++i) st.push_back(sn.stations[i].name);
5811 p["Station"] = st;
5812 if (has_ld) {
5813 p["ProbSys"] = line::num_traits<T>::to_double(pjoint);
5814 line::reg::Json pa = line::reg::Json::array(), pm = line::reg::Json::array();
5815 for (std::size_t i = 0; i < sn.nstations; ++i) {
5816 pa.push_back(line::num_traits<T>::to_double(mr.P[i]));
5817 pm.push_back(line::num_traits<T>::to_double(mdet.P[i]));
5818 }
5819 p["ProbAggr"] = pa;
5820 p["Prob"] = pm;
5821 }
5822 emit_analysis<T>("prob", p, am);
5823 return 0;
5824 }
5825 std::printf("SolverNC arith=%s method=%s type=%s\n", line::num_traits<T>::name(),
5826 am.c_str(), line::util::method_type("NC", am).c_str());
5827 std::printf("ProbSysAggr %.10g\n", line::num_traits<T>::to_double(ps));
5828 if (!has_ld) {
5829 std::printf("ProbSys, Prob and ProbAggr need a load-dependent normalizing constant, "
5830 "which method '%s' does not compute\n",
5831 opt.method.c_str());
5832 return 0;
5833 }
5834 std::printf("ProbSys %.10g\n", line::num_traits<T>::to_double(pjoint));
5835 std::printf("%-16s %14s %14s\n", "Station", "Prob", "ProbAggr");
5836 for (std::size_t i = 0; i < sn.nstations; ++i)
5837 std::printf("%-16s %14.10g %14.10g\n", sn.stations[i].name.c_str(),
5840 return 0;
5841 }
5842}
5843
5844/**
5845 * `-s nc -a sysmarg`: `@@SolverNC/getProbSysMarg.m`, the JOINT law of the
5846 * per-station total queue lengths.
5847 *
5848 * NEITHER `-a prob` NOR `-a marg`, and the three are worth telling apart.
5849 * `-a prob` fixes the PER-CLASS population of every station and is a product
5850 * form; `-a marg` is this law marginalized down to ONE station; this arm is the
5851 * joint over all of them, with the classes summed out. Each value is the sum of
5852 * `-a prob` over the whole fibre of per-class tables with these row sums, and
5853 * that fibre grows combinatorially, so it is evaluated as a permanent of the
5854 * demand matrix replicated once per job (Ryser 1963) rather than enumerated.
5855 *
5856 * The whole lattice of total states is swept, so the printed column sums to one
5857 * and the sweep pays for the normalizing constant once.
5858 */
5859template <class T>
5860int solve_model_nc_sysmarg(const std::string& file, const Knobs& k) {
5861 line::qn::Network<T> net = read_model<T>(file);
5863 if (!k.method.empty() && k.method != "default") opt.method = k.method;
5864 if (k.tol >= 0.0) opt.tol = k.tol;
5865 const line::qn::NetworkStruct<T>& sn = net.get_struct();
5866
5867 double Ntot = 0.0;
5868 for (std::size_t r = 0; r < sn.nclasses; ++r) {
5869 const double pop = sn.classes[r].population;
5870 if (!std::isfinite(pop))
5871 throw line::UnsupportedError(line::ErrorKind{"OpenClass"},
5872 "getProbSysMarg requires a closed model: the joint law of the total queue lengths "
5873 "is not defined when a class has an infinite population");
5874 Ntot += pop;
5875 }
5876 const std::vector<std::vector<int> > states = line::pfqn::multichoose_rows(
5877 static_cast<int>(sn.nstations), static_cast<int>(std::llround(Ntot)));
5878
5879 std::vector<double> P(states.size(), 0.0);
5880 for (std::size_t j = 0; j < states.size(); ++j)
5882 line::nc::solver_nc_getprob_sys_marg(sn, opt, states[j], k.method_perm));
5883
5884 if (g_json_output) {
5885 line::reg::Json p = line::reg::Json::object();
5886 p["type"] = "ProbSysMarg";
5887 p["indexBase"] = 0;
5888 p["engine"] = k.method_perm;
5889 line::reg::Json st = line::reg::Json::array(), arr = line::reg::Json::array();
5890 for (std::size_t i = 0; i < sn.nstations; ++i) st.push_back(sn.stations[i].name);
5891 for (std::size_t j = 0; j < states.size(); ++j) {
5892 line::reg::Json e = line::reg::Json::object();
5893 line::reg::Json n = line::reg::Json::array();
5894 for (std::size_t i = 0; i < sn.nstations; ++i) n.push_back(states[j][i]);
5895 e["n"] = n;
5896 e["P"] = P[j];
5897 arr.push_back(e);
5898 }
5899 p["Station"] = st;
5900 p["states"] = arr;
5901 emit_analysis<T>("sysmarg", p, opt.method);
5902 return 0;
5903 }
5904 std::printf("SolverNC arith=%s method=%s engine=%s\n", line::num_traits<T>::name(),
5905 opt.method.c_str(), k.method_perm.c_str());
5906 for (std::size_t i = 0; i < sn.nstations; ++i)
5907 std::printf("%10s", sn.stations[i].name.c_str());
5908 std::printf(" %14s\n", "ProbSysMarg");
5909 double total = 0.0;
5910 for (std::size_t j = 0; j < states.size(); ++j) {
5911 for (std::size_t i = 0; i < sn.nstations; ++i) std::printf("%10d", states[j][i]);
5912 std::printf(" %14.10g\n", P[j]);
5913 total += P[j];
5914 }
5915 std::printf("%*s %14.10g\n", static_cast<int>(10 * sn.nstations), "sum", total);
5916 return 0;
5917}
5918
5919/**
5920 * `-s nc -a marg`: `@@SolverNC/getProbMarg.m`, the TOTAL queue-length law.
5921 *
5922 * NOT THE SAME QUANTITY AS `-s mva -a marg`, although the reference gives both
5923 * methods the same name. SolverMVA's getProbMarg is per (station, CLASS) and is
5924 * a binomial / Poisson / geometric fitted to the solver's own means; SolverNC's
5925 * is the TOTAL number of jobs at a station, summed over classes, and is exact --
5926 * a ratio of normalizing constants, obtained either from one `pfqn_procomom`
5927 * solve (`--method comom`) or by summing the aggregate marginal over the
5928 * per-class partitions of n. `--class` and `--marg-states` are therefore refused
5929 * for it rather than ignored: this law has no class argument and its support is
5930 * 0..sum(N), which the model fixes.
5931 *
5932 * Both P and log P are reported. The log is not a formatting of the other: the
5933 * enumeration forms it first and a probability that underflows to 0 in double
5934 * still has a finite log, so dropping it would lose the only number left.
5935 */
5936template <class T>
5937int solve_model_nc_marg(const std::string& file, const Knobs& k) {
5938 line::qn::Network<T> net = read_model<T>(file);
5940 if (!k.method.empty() && k.method != "default") opt.method = k.method;
5941 if (k.tol >= 0.0) opt.tol = k.tol;
5942 if (k.iter_tol >= 0.0) opt.iter_tol = k.iter_tol;
5943 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
5944 const line::qn::NetworkStruct<T>& sn = net.get_struct();
5945
5946 std::vector<std::size_t> ists; // 1-based station indices to report
5947 if (k.node) {
5948 if (k.node > sn.nof_nodes())
5949 throw line::InputError("--node " + std::to_string(k.node) +
5950 " exceeds the number of nodes in the model (" +
5951 std::to_string(sn.nof_nodes()) + ")");
5952 const std::size_t ist = sn.nodes[k.node - 1].station;
5953 if (!ist)
5954 throw line::InputError("--node " + std::to_string(k.node) + " ('" +
5955 sn.nodes[k.node - 1].name +
5956 "') is not a station, and a queue-length distribution is "
5957 "reported per station");
5958 ists.push_back(ist);
5959 } else {
5960 for (std::size_t i = 0; i < sn.nstations; ++i) ists.push_back(i + 1);
5961 }
5962
5963 // Every curve first, for solve_model_marg's reason: a station the reference
5964 // refuses must not leave a header standing above an answer that never came.
5965 std::vector<line::nc::NcQueueLengthDist<T> > curves;
5966 for (std::size_t a = 0; a < ists.size(); ++a)
5967 curves.push_back(line::nc::solver_nc_getprob_marg(sn, opt, ists[a]));
5968
5969 if (g_json_output) {
5970 line::reg::Json p = line::reg::Json::object();
5971 p["type"] = "ProbMargAggr";
5972 p["indexBase"] = 0;
5973 line::reg::Json arr = line::reg::Json::array();
5974 for (std::size_t a = 0; a < ists.size(); ++a) {
5975 line::reg::Json e = line::reg::Json::object();
5976 e["station"] = ists[a] - 1;
5977 e["Station"] = sn.stations[ists[a] - 1].name;
5978 e["P"] = vector_json<T>(curves[a].P);
5979 e["logP"] = vector_json<T>(curves[a].logP);
5980 arr.push_back(e);
5981 }
5982 p["curves"] = arr;
5983 emit_analysis<T>("marg", p, opt.method);
5984 return 0;
5985 }
5986 std::printf("SolverNC arith=%s method=%s type=%s\n", line::num_traits<T>::name(),
5987 opt.method.c_str(), line::util::method_type("NC", opt.method).c_str());
5988 for (std::size_t a = 0; a < ists.size(); ++a) {
5989 std::printf("%-16s %-8s %14s %14s\n", "Station", "n", "P", "logP");
5990 for (std::size_t n = 0; n < curves[a].P.size(); ++n)
5991 std::printf("%-16s %-8zu %14.10g %14.10g\n", sn.stations[ists[a] - 1].name.c_str(), n,
5992 line::num_traits<T>::to_double(curves[a].P[n]),
5993 line::num_traits<T>::to_double(curves[a].logP[n]));
5994 }
5995 return 0;
5996}
5997
5998/**
5999 * `-s nc -a cdf`: `@@SolverNC/getCdfRespT.m` and its aliases `getSjrnT`/`sjrnT`.
6000 *
6001 * THE WHOLE LAW, NOT ITS MEAN. `-a avg` reports E[R]; this reports F(t) per
6002 * (station, class) on one shared logarithmic grid, so a percentile or a tail
6003 * probability can be read off it. The algorithm is `pfqn_stdf` (`--method-cdf
6004 * exact`, the default) or the `pfqn_stdf_heur` reduction (`rd`), selected
6005 * through `options.config.algorithm` exactly as in the reference.
6006 *
6007 * FCFS ONLY, and the reference says so by WARNING and returning an empty
6008 * result rather than raising: the sojourn law of a processor-sharing or
6009 * infinite-server station is not the one this inversion computes. That warning
6010 * is carried through to stderr here and the analysis reports no curve, which is
6011 * distinguishable from a curve that is flat.
6012 */
6013template <class T>
6014int solve_model_nc_cdf(const std::string& file, const Knobs& k) {
6016 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
6017 "the -s nc -a cdf analysis evaluates the sojourn law on a logarithmic time grid and "
6018 "inverts a generating function; it needs transcendental arithmetic, so rerun with "
6019 "--arith double or --arith real");
6020 } else {
6021 line::qn::Network<T> net = read_model<T>(file);
6023 if (!k.method.empty() && k.method != "default") opt.method = k.method;
6024 if (k.tol >= 0.0) opt.tol = k.tol;
6025 if (k.iter_tol >= 0.0) opt.iter_tol = k.iter_tol;
6026 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
6027 if (!k.cdf_algorithm.empty()) opt.cdf_algorithm = k.cdf_algorithm;
6028 const line::qn::NetworkStruct<T>& sn = net.get_struct();
6030 if (!r.warning.empty()) std::fprintf(stderr, "warning: %s\n", r.warning.c_str());
6031
6032 if (g_json_output) {
6033 line::reg::Json p = line::reg::Json::object();
6034 p["type"] = "CdfRespT";
6035 p["indexBase"] = 0;
6036 p["algorithm"] = opt.cdf_algorithm;
6037 // ONE OBJECT PER CURVE, as on the CTMC arm: the pairs that carry a
6038 // law are a subset of the grid, so a column form would leave the
6039 // host to re-group them.
6040 line::reg::Json rd = line::reg::Json::array();
6041 for (std::size_t i = 0; i < r.RD.size(); ++i)
6042 for (std::size_t c = 0; c < r.RD[i].size(); ++c) {
6043 // An empty entry is an ABSENT law -- the station is not FCFS
6044 // or does not serve the class -- and is omitted rather than
6045 // sent as a degenerate one.
6046 if (r.RD[i][c].empty()) continue;
6047 line::reg::Json e = line::reg::Json::object();
6048 e["Station"] = sn.stations[i].name;
6049 e["JobClass"] = sn.classes[c].name;
6050 e["station"] = i;
6051 e["jobclass"] = c;
6052 line::reg::Json tt = line::reg::Json::array(), ff = line::reg::Json::array();
6053 for (std::size_t j = 0; j < r.RD[i][c].rows(); ++j) {
6054 ff.push_back(line::num_traits<T>::to_double(r.RD[i][c](j, 0)));
6055 tt.push_back(line::num_traits<T>::to_double(r.RD[i][c](j, 1)));
6056 }
6057 e["t"] = tt;
6058 e["F"] = ff;
6059 rd.push_back(e);
6060 }
6061 p["respt"] = rd;
6062 p["tset"] = vector_json(r.tset);
6063 if (!r.warning.empty()) p["warning"] = r.warning;
6064 // NO "method": the law comes from the sojourn-time inversion and not
6065 // from the normalizing-constant ladder, so the requested method name
6066 // would not be the algorithm that produced these numbers.
6067 emit_analysis<T>("cdf", p, std::string());
6068 return 0;
6069 }
6070 std::printf("SolverNC arith=%s algorithm=%s grid=%zu\n", line::num_traits<T>::name(),
6071 opt.cdf_algorithm.c_str(), r.tset.size());
6072 std::printf("%-16s %-14s %14s %14s\n", "Station", "JobClass", "Time", "F(t)");
6073 for (std::size_t i = 0; i < r.RD.size(); ++i)
6074 for (std::size_t c = 0; c < r.RD[i].size(); ++c) {
6075 if (r.RD[i][c].empty()) continue;
6076 for (std::size_t j = 0; j < r.RD[i][c].rows(); ++j)
6077 std::printf("%-16s %-14s %14.8g %14.10g\n", sn.stations[i].name.c_str(),
6078 sn.classes[c].name.c_str(),
6079 line::num_traits<T>::to_double(r.RD[i][c](j, 1)),
6080 line::num_traits<T>::to_double(r.RD[i][c](j, 0)));
6081 }
6082 return 0;
6083 }
6084}
6085
6086/**
6087 * The clean-up a sensitivity table applies before printing, for a quantity that
6088 * may legitimately be NEGATIVE.
6089 *
6090 * `ln_sanitize` below tests `x <= FineTol`, which is right for a queue length or
6091 * a utilization -- every metric it was written for is nonnegative, so that test
6092 * reads as "negligible". A DERIVATIVE is not: raising a service rate lowers the
6093 * response time, the queue length and the utilization, so the whole sensitivity
6094 * table is negative by construction and the unsigned test would print an exact
6095 * zero for every one of those columns. Only the MAGNITUDE decides negligibility
6096 * here. The NC and the layered tables share it, which is why it sits above both.
6097 */
6098double sens_sanitize_signed(double x) {
6099 if (std::fabs(x) <= line::lang::GlobalConstants::FineTol) return 0.0;
6100 return x;
6101}
6102
6103/**
6104 * `-s nc -a sens`: `@@NetworkSolver/getSensitivityTable.m` under SolverNC.
6105 *
6106 * ONE ROW PER (station, class) carrying dTput/dRate, dRespT/dRate, dQLen/dRate
6107 * and dUtil/dRate, i.e. the derivative of that row's means with respect to that
6108 * row's service RATE. Two branches produce them and the banner names the one
6109 * that ran: `exact` differentiates the product-form recursion analytically
6110 * (`pfqn_sens` at chain level for a closed model, the closed-form BCMP
6111 * derivatives for an open one), `fd` re-solves rate-perturbed copies of the
6112 * model with THIS solver and forms the quotient.
6113 *
6114 * NC IS ONE OF THE TWO ENGINES THAT CAN TAKE THE EXACT BRANCH, which is what
6115 * `@@SolverNC/supportsExactSensitivity.m` returns true for, so `auto` resolves
6116 * to `exact` whenever the model is in its scope (single-server queues plus
6117 * delays, not mixed) and only falls back to differences outside it. Asking for
6118 * `--sens-method exact` outside that scope is refused by name rather than
6119 * silently downgraded: the two branches answer to different precision.
6120 *
6121 * The struct is COPIED rather than referenced because the fd branch writes a
6122 * scaled service process into it between solves; `net.get_struct()` hands out a
6123 * const reference to the model's own, which must not move under the caller.
6124 */
6125template <class T>
6126int solve_model_nc_sens(const std::string& file, const Knobs& k) {
6127 line::qn::Network<T> net = read_model<T>(file);
6129 if (!k.method.empty() && k.method != "default") opt.method = k.method;
6130 if (k.tol >= 0.0) opt.tol = k.tol;
6131 if (k.iter_tol >= 0.0) opt.iter_tol = k.iter_tol;
6132 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
6134
6136 if (!k.sens_method.empty()) so.method = k.sens_method;
6137 if (!k.sens_scheme.empty()) so.scheme = k.sens_scheme;
6138 if (k.sens_step > 0.0) so.step = k.sens_step;
6139 so.simulation = false; // the normalizing-constant path is deterministic
6140
6141 // `getAvg`, not the raw analyzer: the reference's difference quotient is
6142 // taken on the metrics the solver reports, which are the filtered ones.
6144 sn, so, /*exact_available=*/true, [&sn, &opt]() {
6147 s.Q = a.QN;
6148 s.U = a.UN;
6149 s.R = a.RN;
6150 s.Tp = a.TN;
6151 s.C = a.CN;
6152 s.X = a.XN;
6153 s.method = a.actualmethod;
6154 s.iter = a.iter;
6155 return s;
6156 });
6157
6158 if (g_json_output) {
6159 line::reg::Json p = line::reg::Json::object();
6160 p["type"] = "SensitivityTable";
6161 p["indexBase"] = 0;
6162 p["branch"] = tbl.method;
6163 line::reg::Json rows = line::reg::Json::array();
6164 for (const line::sens::SensRow<T>& r : tbl.rows) {
6165 line::reg::Json o = line::reg::Json::object();
6166 o["Station"] = r.station;
6167 o["JobClass"] = r.jobclass;
6168 o["dTput_dRate"] = sens_sanitize_signed(line::num_traits<T>::to_double(r.dTput));
6169 o["dRespT_dRate"] = sens_sanitize_signed(line::num_traits<T>::to_double(r.dRespT));
6170 o["dQLen_dRate"] = sens_sanitize_signed(line::num_traits<T>::to_double(r.dQLen));
6171 o["dUtil_dRate"] = sens_sanitize_signed(line::num_traits<T>::to_double(r.dUtil));
6172 rows.push_back(o);
6173 }
6174 p["rows"] = rows;
6175 // The branch rides in "branch" because it is not a normalizing-constant
6176 // method name. The method slot is EMPTY on the exact branch, which
6177 // differentiates the recursion in closed form and never runs a solve:
6178 // naming the NC method there would attribute the numbers to an
6179 // algorithm that did not produce them.
6180 emit_analysis<T>("sens", p, tbl.method == "fd" ? opt.method : std::string());
6181 return 0;
6182 }
6183
6184 std::printf("SolverNC arith=%s branch=%s method=%s rows=%zu\n", line::num_traits<T>::name(),
6185 tbl.method.c_str(), tbl.method == "fd" ? opt.method.c_str() : "-",
6186 tbl.rows.size());
6187 std::printf("%-16s %-14s %14s %14s %14s %14s\n", "Station", "JobClass", "dTput_dRate",
6188 "dRespT_dRate", "dQLen_dRate", "dUtil_dRate");
6189 for (const line::sens::SensRow<T>& r : tbl.rows)
6190 std::printf("%-16s %-14s %14.6g %14.6g %14.6g %14.6g\n", r.station.c_str(),
6191 r.jobclass.c_str(),
6192 sens_sanitize_signed(line::num_traits<T>::to_double(r.dTput)),
6193 sens_sanitize_signed(line::num_traits<T>::to_double(r.dRespT)),
6194 sens_sanitize_signed(line::num_traits<T>::to_double(r.dQLen)),
6195 sens_sanitize_signed(line::num_traits<T>::to_double(r.dUtil)));
6196 return 0;
6197}
6198
6199/** The @@Solver method each `-a` stands for, which is what the chooser keys on. */
6200// ===================== SolverLDES, the simulator ==========================
6201
6202/**
6203 * The knobs one `-s ldes` invocation resolves to.
6204 *
6205 * `--samples` is the SERVICE-COMPLETION budget the engine stops at, `--seed` the
6206 * stream, and both are part of the answer rather than of the invocation, which is
6207 * why the banner carries them. Everything else is `--ldes-*`.
6208 *
6209 * A `--ldes-initsol` placement is NOT accompanied by a forced `fixed` warmup
6210 * filter here, deliberately: `initFromSolver` sets `tranfilter='fixed'` with
6211 * `warmupfrac=0` because the placement it computes IS a steady state, while a
6212 * placement handed in on the command line may equally be the start of a
6213 * transient. Pass `--ldes-tranfilter fixed --ldes-warmupfrac 0` alongside it to
6214 * reproduce `initFromSolver` exactly.
6215 */
6216inline line::ldes::LdesOptions ldes_options(const Knobs& k) {
6218 if (k.samples) o.samples = k.samples;
6219 if (k.seed) o.seed = static_cast<long>(k.seed);
6220 if (!k.method.empty()) o.method = k.method;
6221 if (!k.ldes_tranfilter.empty()) o.tranfilter = k.ldes_tranfilter;
6222 if (k.ldes_warmupfrac >= 0.0) o.warmupfrac = k.ldes_warmupfrac;
6223 if (!k.ldes_cimethod.empty()) o.cimethod = k.ldes_cimethod;
6224 if (k.ldes_cnvgon) o.cnvgon = true;
6225 if (k.ldes_cnvgtol > 0.0) o.cnvgtol = k.ldes_cnvgtol;
6226 if (k.ldes_slotted) o.slotted = true;
6227 if (k.ldes_slotlength > 0.0) {
6228 o.slotted = true;
6229 o.slot_length = k.ldes_slotlength;
6230 }
6231 if (k.ldes_replications > 0) o.replications = k.ldes_replications;
6232 if (k.ldes_numthreads > 0) o.numthreads = k.ldes_numthreads;
6233 if (k.ldes_maxtime > 0.0) o.timeout = k.ldes_maxtime;
6234 if (!k.ldes_initsol.empty()) o.init_sol = k.ldes_initsol;
6235 if (!k.ldes_rest_url.empty()) o.rest_url = k.ldes_rest_url;
6236 o.verbose = k.verbose;
6237 return o;
6238}
6239
6240/**
6241 * The model.json text the engine is handed.
6242 *
6243 * FORWARDED BYTE FOR BYTE, and never through `read_model`: the reader is scoped
6244 * to the subset the analytical solvers need, and a round trip through it would
6245 * degrade exactly the models LDES exists for. `-a reward` is the one arm that
6246 * also parses the document, because a reward DECLARATION is what it needs.
6247 */
6248inline std::string ldes_document(const std::string& file) {
6249 return file.empty() ? stdin_model_text() : line::ldes::detail::read_file(file);
6250}
6251
6252/** A reported entry, or 0 where the engine reported no such row. */
6253inline double ldes_at(const line::Matrix<double>& M, std::size_t i, std::size_t j) {
6254 return i < M.rows() && j < M.cols() ? M(i, j) : 0.0;
6255}
6256
6257/**
6258 * One LDES run.
6259 *
6260 * A HARD TIMEOUT IS A REFUSAL, not an empty result: a run killed before it
6261 * wrote a result raises LINE:numerical:Timeout, since a table of zeros that
6262 * means "the run was killed" is the silent-wrong-number outcome this CLI
6263 * refuses everywhere else.
6264 */
6265inline line::ldes::LdesResult ldes_run(const std::string& file,
6266 const line::ldes::LdesOptions& o,
6267 const std::vector<std::string>& extra) {
6268 // A run KILLED on the hard bound raises LINE:numerical:Timeout inside the
6269 // wrapper; one that stopped on its --maxtime returns its interim result
6270 // with `timed_out` set and the budget latched, which run_invocation reports.
6271 const line::ldes::LdesResult r = line::ldes::solver_ldes_text(ldes_document(file), o, extra);
6272 if (r.station_names.empty())
6274 "SolverLDES: the engine reported no station names, so its metrics cannot be labelled; "
6275 "the run produced no result document");
6276 return r;
6277}
6278
6279/**
6280 * The provenance line every LDES arm prints first.
6281 *
6282 * `engine=` is not decoration: the AOT native image and the jar are two builds of
6283 * one engine and the first can lag the sources, so a number quoted from an LDES
6284 * run has to say which produced it. `stopping=` is the reason the run ended --
6285 * a `max_events` stop at a low `--samples` is a wide confidence interval and a
6286 * `max_time` one is a truncated run, and neither is visible in the means.
6287 */
6288inline void ldes_banner(const line::ldes::LdesResult& r, const line::ldes::LdesOptions& o) {
6289 std::printf("SolverLDES arith=double method=%s type=%s engine=%s samples=%zu seed=%ld "
6290 "time=%.6g events=%lld stopping=%s\n",
6291 r.method.c_str(), line::util::method_type("LDES", r.method).c_str(),
6292 r.engine.c_str(), o.events ? o.events : o.samples, o.seed, r.runtime,
6294}
6295
6296/** The envelope keys that qualify an LDES solve as a whole. */
6297inline line::reg::Json ldes_envelope(const line::ldes::LdesResult& r,
6298 const line::ldes::LdesOptions& o) {
6299 line::reg::Json e = line::reg::Json::object();
6300 e["engine"] = r.engine;
6301 e["samples"] = o.events ? o.events : o.samples;
6302 e["seed"] = o.seed;
6303 e["converged"] = r.converged;
6304 e["stoppingReason"] = r.stopping_reason;
6305 e["totalSimulatedEvents"] = r.total_simulated_events;
6306 e["runtime"] = r.runtime;
6307 return e;
6308}
6309
6310/**
6311 * `-s ldes -a avg`: the steady-state table, the engine's `getAvg`.
6312 *
6313 * THE FINITE-CAPACITY-REGION ROWS DO NOT JOIN THE STATION TABLE, unlike MATLAB's
6314 * `getAvgTable`, which appends them after the stations. A region is not a station
6315 * and the "Station" column of this CLI's table is read by a parity harness that
6316 * pairs rows with another codebase's stations; a region row there would pair with
6317 * nothing. They are printed as their own table and carried under `avg.fcr`, which
6318 * is the same information without the collision.
6319 */
6320int solve_model_ldes_avg(const std::string& file, const Knobs& k) {
6321 const line::ldes::LdesOptions o = ldes_options(k);
6322 const line::ldes::LdesResult r = ldes_run(file, o, std::vector<std::string>());
6323 if (!g_json_output) ldes_banner(r, o);
6324
6325 line::reg::Json extra = line::reg::Json::object();
6326 // The confidence intervals are the half-widths the engine reports, one per
6327 // metric; a simulation that quoted a mean without them would be quoting a
6328 // point estimate as if it were exact.
6329 line::reg::Json ci = line::reg::Json::object();
6330 if (!r.QNCI.empty()) ci["QNCI"] = matrix_json<double>(r.QNCI);
6331 if (!r.UNCI.empty()) ci["UNCI"] = matrix_json<double>(r.UNCI);
6332 if (!r.RNCI.empty()) ci["RNCI"] = matrix_json<double>(r.RNCI);
6333 if (!r.TNCI.empty()) ci["TNCI"] = matrix_json<double>(r.TNCI);
6334 if (!r.ANCI.empty()) ci["ANCI"] = matrix_json<double>(r.ANCI);
6335 if (!r.WNCI.empty()) ci["WNCI"] = matrix_json<double>(r.WNCI);
6336 if (!ci.empty()) extra["CI"] = ci;
6337 if (!r.QNfcr.empty()) {
6338 line::reg::Json f = line::reg::Json::object();
6339 f["nregions"] = r.nregions;
6340 f["QNfcr"] = matrix_json<double>(r.QNfcr);
6341 f["RNfcr"] = matrix_json<double>(r.RNfcr);
6342 f["TNfcr"] = matrix_json<double>(r.TNfcr);
6343 f["WNfcr"] = matrix_json<double>(r.WNfcr);
6344 if (!r.WeightNfcr.empty()) f["WeightNfcr"] = matrix_json<double>(r.WeightNfcr);
6345 if (!r.MemOccNfcr.empty()) f["MemOccNfcr"] = matrix_json<double>(r.MemOccNfcr);
6346 if (!r.DropRateNfcr.empty()) f["DropRateNfcr"] = matrix_json<double>(r.DropRateNfcr);
6347 extra["fcr"] = f;
6348 }
6349 if (!r.DropRateJoin.empty()) extra["DropRateJoin"] = matrix_json<double>(r.DropRateJoin);
6350 if (!r.fj_forks.empty()) {
6351 const line::reg::Json fjb =
6352 fj_extra_json(r.fj_forks, r.fj_joins, r.class_names, r.FJQLen, r.FJRespT, r.FJTput);
6353 if (!fjb.is_null()) extra["FJ"] = fjb;
6354 }
6355 if (!r.cache_metrics.empty()) {
6356 line::reg::Json cm = line::reg::Json::object();
6357 for (std::map<std::string, line::ldes::LdesCacheMetrics>::const_iterator it =
6358 r.cache_metrics.begin();
6359 it != r.cache_metrics.end(); ++it) {
6360 line::reg::Json c = line::reg::Json::object();
6361 if (!it->second.hit.empty()) c["hit"] = matrix_json<double>(it->second.hit);
6362 if (!it->second.delayed.empty()) c["delayed"] = matrix_json<double>(it->second.delayed);
6363 if (!it->second.miss.empty()) c["miss"] = matrix_json<double>(it->second.miss);
6364 if (!it->second.latency.empty()) c["latency"] = matrix_json<double>(it->second.latency);
6365 if (!it->second.hitList.empty()) c["hitList"] = matrix_json<double>(it->second.hitList);
6366 if (!it->second.itemProb.empty())
6367 c["itemProb"] = matrix_json<double>(it->second.itemProb);
6368 if (!it->second.listCost.empty())
6369 c["listCost"] = matrix_json<double>(it->second.listCost);
6370 cm[it->first] = c;
6371 }
6372 extra["cacheMetrics"] = cm;
6373 }
6374
6375 // THE RESIDENCE TIME IS DERIVED HERE, not taken from the engine. The engine
6376 // reports WN = RN because it counts one visit per station, which is only
6377 // true when every visit ratio is 1; `getAvg.m:204` therefore discards the
6378 // WN a solver returned and recomputes `sn_get_residt_from_respt(sn, RN)`,
6379 // and every other C++ solver already routes through the same helper. On
6380 // cqn_repairmen, whose Queue1 is visited 0.3 times per cycle, the engine's
6381 // WN came out 11.8136 against the reference's 3.5205 -- the response time
6382 // reported as if the station were visited once.
6383 //
6384 // MATCHED BY NAME. The engine's station order is its own; a Cache or a
6385 // Source can sit at a different index in the struct, and pairing the two
6386 // off positionally would scale one station's time by another's visits.
6387 line::Matrix<double> WNd(r.station_names.size(), r.class_names.size(), 0.0);
6388 {
6389 line::qn::Network<double> net = read_model<double>(file);
6391 std::vector<std::size_t> st_of(r.station_names.size(), 0); // 1-based, 0 = unmatched
6392 for (std::size_t i = 0; i < r.station_names.size(); ++i)
6393 for (std::size_t j = 0; j < sn.nstations; ++j)
6394 if (sn.stations[j].name == r.station_names[i]) { st_of[i] = j + 1; break; }
6395 std::vector<std::size_t> cl_of(r.class_names.size(), 0);
6396 for (std::size_t c = 0; c < r.class_names.size(); ++c)
6397 for (std::size_t k = 0; k < sn.nclasses; ++k)
6398 if (sn.classes[k].name == r.class_names[c]) { cl_of[c] = k + 1; break; }
6399 line::Matrix<double> RNs(sn.nstations, sn.nclasses, 0.0);
6400 for (std::size_t i = 0; i < r.station_names.size(); ++i)
6401 for (std::size_t c = 0; c < r.class_names.size(); ++c)
6402 if (st_of[i] && cl_of[c]) RNs(st_of[i] - 1, cl_of[c] - 1) = ldes_at(r.RN, i, c);
6404 for (std::size_t i = 0; i < r.station_names.size(); ++i)
6405 for (std::size_t c = 0; c < r.class_names.size(); ++c)
6406 WNd(i, c) = (st_of[i] && cl_of[c]) ? WNs(st_of[i] - 1, cl_of[c] - 1)
6407 : ldes_at(r.WN, i, c);
6408 }
6409
6410 emit_avg_table_named(r.station_names, r.class_names, "double", r.method,
6411 [&](std::size_t i, std::size_t c) {
6412 AvgRow v;
6413 v.q = ldes_at(r.QN, i, c);
6414 v.u = ldes_at(r.UN, i, c);
6415 v.r = ldes_at(r.RN, i, c);
6416 v.w = WNd(i, c);
6417 v.a = ldes_at(r.AN, i, c);
6418 v.t = ldes_at(r.TN, i, c);
6419 return v;
6420 },
6421 extra, ldes_envelope(r, o));
6422
6423 if (!g_json_output && !r.QNfcr.empty()) {
6424 std::printf("%-16s %-14s %12s %12s %12s %12s %12s\n", "Region", "JobClass", "QLen", "RespT",
6425 "Tput", "Weight", "MemOcc");
6426 for (std::size_t i = 0; i < r.QNfcr.rows(); ++i)
6427 for (std::size_t c = 0; c < r.class_names.size(); ++c)
6428 std::printf("%-16s %-14s %12.6g %12.6g %12.6g %12.6g %12.6g\n",
6429 ("Region" + std::to_string(i + 1)).c_str(), r.class_names[c].c_str(),
6430 ldes_at(r.QNfcr, i, c), ldes_at(r.RNfcr, i, c),
6431 ldes_at(r.TNfcr, i, c), ldes_at(r.WeightNfcr, i, c),
6432 ldes_at(r.MemOccNfcr, i, c));
6433 }
6434 if (!g_json_output && !r.cache_metrics.empty()) {
6435 std::printf("%-16s %-14s %12s %12s %12s %12s\n", "Cache", "JobClass", "Hit", "Delayed",
6436 "Miss", "Latency");
6437 for (std::map<std::string, line::ldes::LdesCacheMetrics>::const_iterator it =
6438 r.cache_metrics.begin();
6439 it != r.cache_metrics.end(); ++it)
6440 for (std::size_t c = 0; c < r.class_names.size(); ++c)
6441 std::printf("%-16s %-14s %12.6g %12.6g %12.6g %12.6g\n", it->first.c_str(),
6442 r.class_names[c].c_str(), ldes_at(it->second.hit, 0, c),
6443 ldes_at(it->second.delayed, 0, c), ldes_at(it->second.miss, 0, c),
6444 ldes_at(it->second.latency, 0, c));
6445 }
6446 return 0;
6447}
6448
6449/**
6450 * `-s ldes -a tran`: `getTranAvg`, the per-bucket QNt / UNt / TNt series over
6451 * `--tspan`.
6452 *
6453 * THE HORIZON IS REQUIRED. `options.timespan` is what turns the engine's run into
6454 * a transient one, and there is no default: a trajectory over an unstated horizon
6455 * is not a quantity. A SINGLE PATH IS NOT E[N](t) either -- there is no time
6456 * ergodicity at fixed t -- so `--ldes-replications` is how an ensemble mean is
6457 * asked for, exactly as `runAnalyzer.m` passes `--replications` for the same
6458 * reason.
6459 *
6460 * The series are indexed by STATION, as `LDESResultIO` writes them
6461 * (`result.QNt = new Matrix[numStations][numClasses]`).
6462 */
6463int solve_model_ldes_tran(const std::string& file, const Knobs& k) {
6464 line::ldes::LdesOptions o = ldes_options(k);
6465 o.has_timespan = true;
6466 o.t0 = k.t0;
6467 o.t1 = k.t1;
6468 std::vector<std::string> extra;
6469 extra.push_back("--trajectory");
6470 const line::ldes::LdesResult r = ldes_run(file, o, extra);
6471 if (r.t.empty() || r.QNt.empty())
6473 "SolverLDES -a tran produced no trajectory: the engine ran but recorded no bucket over "
6474 "[" + line::ldes::detail::shortest(k.t0) + "," +
6475 line::ldes::detail::shortest(k.t1) + "]");
6476
6477 if (g_json_output) {
6478 line::reg::Json p = line::reg::Json::object();
6479 p["type"] = "TranAvgTable";
6480 p["indexBase"] = 0;
6481 p["t0"] = k.t0;
6482 p["t1"] = k.t1;
6483 line::reg::Json curves = line::reg::Json::array();
6484 for (std::size_t i = 0; i < r.QNt.size(); ++i)
6485 for (std::size_t c = 0; c < r.QNt[i].size(); ++c) {
6486 // An empty series is an ABSENT one -- the class does not visit
6487 // the station -- and is omitted rather than sent as a flat zero.
6488 if (r.QNt[i][c].empty()) continue;
6489 line::reg::Json e = line::reg::Json::object();
6490 e["Station"] = i < r.station_names.size() ? r.station_names[i]
6491 : "Station" + std::to_string(i);
6492 e["JobClass"] =
6493 c < r.class_names.size() ? r.class_names[c] : "Class" + std::to_string(c);
6494 e["station"] = i;
6495 e["jobclass"] = c;
6496 line::reg::Json tt = line::reg::Json::array(), q = line::reg::Json::array(),
6497 u = line::reg::Json::array(), x = line::reg::Json::array();
6498 for (std::size_t j = 0; j < r.QNt[i][c].rows(); ++j) {
6499 tt.push_back(r.QNt[i][c](j, 1));
6500 q.push_back(r.QNt[i][c](j, 0));
6501 }
6502 if (i < r.UNt.size() && c < r.UNt[i].size())
6503 for (std::size_t j = 0; j < r.UNt[i][c].rows(); ++j)
6504 u.push_back(r.UNt[i][c](j, 0));
6505 if (i < r.TNt.size() && c < r.TNt[i].size())
6506 for (std::size_t j = 0; j < r.TNt[i][c].rows(); ++j)
6507 x.push_back(r.TNt[i][c](j, 0));
6508 e["t"] = tt;
6509 e["QLen"] = q;
6510 e["Util"] = u;
6511 e["Tput"] = x;
6512 curves.push_back(e);
6513 }
6514 p["curves"] = curves;
6515 p["tset"] = vector_json(r.t);
6516 // The envelope is built ONCE into a local: `begin()` and `end()` taken
6517 // from two different temporaries are iterators into two different
6518 // objects, which is undefined behaviour and not a style point.
6519 const line::reg::Json env = ldes_envelope(r, o);
6520 for (line::reg::Json::const_iterator it = env.begin(); it != env.end(); ++it)
6521 p[it.key()] = it.value();
6522 emit_analysis<double>("tran", p, r.method);
6523 return 0;
6524 }
6525 ldes_banner(r, o);
6526 std::printf("%-16s %-14s %12s %12s %12s %12s\n", "Station", "JobClass", "Time", "QLen", "Util",
6527 "Tput");
6528 for (std::size_t i = 0; i < r.QNt.size(); ++i)
6529 for (std::size_t c = 0; c < r.QNt[i].size(); ++c) {
6530 if (r.QNt[i][c].empty()) continue;
6531 for (std::size_t j = 0; j < r.QNt[i][c].rows(); ++j) {
6532 const bool hu = i < r.UNt.size() && c < r.UNt[i].size() &&
6533 j < r.UNt[i][c].rows();
6534 const bool hx = i < r.TNt.size() && c < r.TNt[i].size() &&
6535 j < r.TNt[i][c].rows();
6536 std::printf("%-16s %-14s %12.6g %12.6g %12.6g %12.6g\n",
6537 (i < r.station_names.size() ? r.station_names[i].c_str() : "?"),
6538 (c < r.class_names.size() ? r.class_names[c].c_str() : "?"),
6539 r.QNt[i][c](j, 1), r.QNt[i][c](j, 0),
6540 hu ? r.UNt[i][c](j, 0) : 0.0, hx ? r.TNt[i][c](j, 0) : 0.0);
6541 }
6542 }
6543 return 0;
6544}
6545
6546/**
6547 * `-s ldes -a cdf`: `getCdfRespT`, the EMPIRICAL response-time law.
6548 *
6549 * A SIMULATOR MUST REPORT WHAT IT OBSERVED. The base solver's fallback fabricates
6550 * an exponential law with the right mean, which says nothing about the tail; the
6551 * engine records every per-job response time under `--respt-samples`, and the
6552 * curve here is the ecdf of those samples with repeated observations collapsed to
6553 * their largest F, exactly as `@@SolverLDES/getCdfRespT.m` builds it.
6554 *
6555 * `--respt-samples` POSTDATES the prebuilt AOT image, which is why the runner
6556 * order flips for it (see `ldes_runners`): on that image the flag is accepted and
6557 * ignored, and the arm would refuse for want of samples that were never asked for.
6558 */
6559int solve_model_ldes_cdf(const std::string& file, const Knobs& k, const char* key,
6560 const char* type) {
6561 const line::ldes::LdesOptions o = ldes_options(k);
6562 std::vector<std::string> extra;
6563 extra.push_back("--respt-samples");
6564 const line::ldes::LdesResult r = ldes_run(file, o, extra);
6565 if (r.respTimeSamples.empty())
6567 "SolverLDES -a cdf needs the per-job response times the engine records under "
6568 "--respt-samples and the run returned none; raise --samples so completions are "
6569 "observed at all");
6570
6571 // The ecdf of each (station, class): sorted observations, F = i/n, and one
6572 // pair per DISTINCT value carrying the largest F at it.
6573 std::vector<std::vector<std::vector<double>>> tt(r.respTimeSamples.size()), ff(
6574 r.respTimeSamples.size());
6575 for (std::size_t i = 0; i < r.respTimeSamples.size(); ++i) {
6576 tt[i].resize(r.respTimeSamples[i].size());
6577 ff[i].resize(r.respTimeSamples[i].size());
6578 for (std::size_t c = 0; c < r.respTimeSamples[i].size(); ++c) {
6579 std::vector<double> x = r.respTimeSamples[i][c];
6580 if (x.empty()) continue;
6581 std::sort(x.begin(), x.end());
6582 const double n = static_cast<double>(x.size());
6583 for (std::size_t j = 0; j < x.size(); ++j) {
6584 if (j + 1 < x.size() && x[j + 1] == x[j]) continue;
6585 tt[i][c].push_back(x[j]);
6586 ff[i][c].push_back(static_cast<double>(j + 1) / n);
6587 }
6588 }
6589 }
6590
6591 if (g_json_output) {
6592 line::reg::Json p = line::reg::Json::object();
6593 p["type"] = type;
6594 p["indexBase"] = 0;
6595 p["algorithm"] = "empirical";
6596 line::reg::Json rd = line::reg::Json::array();
6597 for (std::size_t i = 0; i < tt.size(); ++i)
6598 for (std::size_t c = 0; c < tt[i].size(); ++c) {
6599 if (tt[i][c].empty()) continue;
6600 line::reg::Json e = line::reg::Json::object();
6601 e["Station"] = i < r.station_names.size() ? r.station_names[i]
6602 : "Station" + std::to_string(i);
6603 e["JobClass"] =
6604 c < r.class_names.size() ? r.class_names[c] : "Class" + std::to_string(c);
6605 e["station"] = i;
6606 e["jobclass"] = c;
6607 e["t"] = vector_json(tt[i][c]);
6608 e["F"] = vector_json(ff[i][c]);
6609 e["samples"] = r.respTimeSamples[i][c].size();
6610 rd.push_back(e);
6611 }
6612 p["respt"] = rd;
6613 emit_analysis<double>(key, p, std::string());
6614 return 0;
6615 }
6616 ldes_banner(r, o);
6617 std::printf("%-16s %-14s %14s %14s\n", "Station", "JobClass", "Time", "F(t)");
6618 for (std::size_t i = 0; i < tt.size(); ++i)
6619 for (std::size_t c = 0; c < tt[i].size(); ++c)
6620 for (std::size_t j = 0; j < tt[i][c].size(); ++j)
6621 std::printf("%-16s %-14s %14.8g %14.10g\n",
6622 (i < r.station_names.size() ? r.station_names[i].c_str() : "?"),
6623 (c < r.class_names.size() ? r.class_names[c].c_str() : "?"),
6624 tt[i][c][j], ff[i][c][j]);
6625 return 0;
6626}
6627
6628/**
6629 * `-s ldes -a perct-respt`: `@SolverLDES/getPerctRespT`, steady-state response-time
6630 * percentiles WITH confidence intervals.
6631 *
6632 * The run is the `-a cdf` one (`--respt-samples`), and the procedure follows the
6633 * replication count: FQUEST on one path, FIRQUEST over `--ldes-replications` >= 2
6634 * (or `--method parallel`), each fed the raw departure-ordered samples, warmup
6635 * included, since both detect and delete it themselves. `--percentiles` names the
6636 * levels, defaulting to {10, 25, 50, 75, 90, 95, 99} percent as the reference does.
6637 */
6638int solve_model_ldes_perct(const std::string& file, const Knobs& k) {
6639 const line::ldes::LdesOptions o = ldes_options(k);
6640 const int R = line::ldes::ldes_replications(o);
6641 const std::string method = line::ldes::ldes_perct_method(R, std::string());
6642 std::vector<std::string> extra;
6643 extra.push_back("--respt-samples");
6644 const line::ldes::LdesResult r = ldes_run(file, o, extra);
6645 const std::vector<line::ldes::LdesPercentileResult> rows =
6646 line::ldes::ldes_perct_respt(r, k.percentiles, R, method, line::ldes::ldes_perct_level(o));
6647
6648 if (g_json_output) {
6649 line::reg::Json p = line::reg::Json::object();
6650 p["type"] = "PerctRespT";
6651 p["indexBase"] = 0;
6652 p["algorithm"] = method;
6653 line::reg::Json arr = line::reg::Json::array();
6654 for (std::size_t n = 0; n < rows.size(); ++n) {
6655 const line::ldes::LdesPercentileResult& e = rows[n];
6656 line::reg::Json j = line::reg::Json::object();
6657 j["Station"] = e.station;
6658 j["JobClass"] = e.job_class;
6659 j["station"] = e.station_index;
6660 j["jobclass"] = e.class_index;
6661 j["percentileLevels"] = e.percentiles;
6662 j["percentiles"] = vector_json(e.values);
6663 j["lower"] = vector_json(e.lower);
6664 j["upper"] = vector_json(e.upper);
6665 j["halfwidth"] = vector_json(e.halfwidth);
6666 line::reg::Json h = line::reg::Json::array();
6667 for (std::size_t q = 0; q < e.heuristic.size(); ++q) h.push_back(static_cast<bool>(e.heuristic[q]));
6668 j["heuristic"] = h;
6669 j["level"] = e.level;
6670 j["method"] = e.method;
6671 j["samples"] = e.samples;
6672 arr.push_back(j);
6673 }
6674 p["respt"] = arr;
6675 const line::reg::Json env = ldes_envelope(r, o);
6676 for (line::reg::Json::const_iterator it = env.begin(); it != env.end(); ++it)
6677 p[it.key()] = it.value();
6678 emit_analysis<double>("perct", p, r.method);
6679 return 0;
6680 }
6681 ldes_banner(r, o);
6682 std::printf("# getPerctRespT: method=%s replications=%d level=%.6g\n", method.c_str(), R,
6683 rows.empty() ? line::ldes::ldes_perct_level(o) : rows[0].level);
6684 std::printf("%-16s %-14s %10s %14s %14s %14s %9s %10s\n", "Station", "JobClass", "Percentile",
6685 "ResponseTime", "Lower", "Upper", "Heuristic", "Samples");
6686 for (std::size_t n = 0; n < rows.size(); ++n) {
6687 const line::ldes::LdesPercentileResult& e = rows[n];
6688 for (std::size_t q = 0; q < e.percentiles.size(); ++q)
6689 std::printf("%-16s %-14s %10.4g %14.8g %14.8g %14.8g %9s %10zu\n", e.station.c_str(),
6690 e.job_class.c_str(), e.percentiles[q], e.values[q], e.lower[q], e.upper[q],
6691 e.heuristic[q] ? "true" : "false", e.samples);
6692 }
6693 return 0;
6694}
6695
6696/**
6697 * `-s ldes -a sample`: `sampleSys` / `sampleSysAggr`, one simulated trajectory.
6698 *
6699 * The horizon is `[0, --samples]`, which is `runTransientJson`'s: the event budget
6700 * doubles as the transient horizon there because the engine ignores the budget in
6701 * transient mode, so the number the caller gave has to name the horizon or name
6702 * nothing. `--tspan` names a horizon in its own right and belongs to `-a tran`.
6703 *
6704 * The state is the per-class queue length at each station, which is why there is
6705 * no separate `sampleSysAggr` column: an LDES trajectory is ALREADY per class, so
6706 * the aggregate view is the row sum and the reference's two getters return the
6707 * same data with one flag flipped.
6708 */
6709int solve_model_ldes_sample(const std::string& file, const Knobs& k) {
6710 line::ldes::LdesOptions o = ldes_options(k);
6711 o.has_timespan = true;
6712 o.t0 = 0.0;
6713 o.t1 = static_cast<double>(o.events ? o.events : o.samples);
6714 std::vector<std::string> extra;
6715 extra.push_back("--trajectory");
6716 const line::ldes::LdesResult r = ldes_run(file, o, extra);
6717 if (r.t.empty() || r.QNt.empty())
6719 "SolverLDES -a sample produced no trajectory over [0," +
6720 line::ldes::detail::shortest(o.t1) + "]");
6721
6722 const std::size_t M = r.QNt.size(), K = r.class_names.size(), n = r.t.size();
6723 if (g_json_output) {
6724 line::reg::Json p = line::reg::Json::object();
6725 p["type"] = "SamplePath";
6726 p["indexBase"] = 0;
6727 p["scope"] = "(system)";
6728 p["drawn"] = n;
6729 p["t"] = vector_json(r.t);
6730 line::reg::Json st = line::reg::Json::array();
6731 for (std::size_t j = 0; j < n; ++j) {
6732 line::reg::Json row = line::reg::Json::array();
6733 for (std::size_t i = 0; i < M; ++i)
6734 for (std::size_t c = 0; c < K; ++c)
6735 row.push_back(c < r.QNt[i].size() && j < r.QNt[i][c].rows()
6736 ? r.QNt[i][c](j, 0)
6737 : 0.0);
6738 st.push_back(row);
6739 }
6740 p["state"] = st;
6741 line::reg::Json cols = line::reg::Json::array();
6742 for (std::size_t i = 0; i < M; ++i)
6743 for (std::size_t c = 0; c < K; ++c)
6744 cols.push_back((i < r.station_names.size() ? r.station_names[i] : "?") + "," +
6745 (c < K ? r.class_names[c] : "?"));
6746 p["columns"] = cols;
6747 // The envelope is built ONCE into a local: `begin()` and `end()` taken
6748 // from two different temporaries are iterators into two different
6749 // objects, which is undefined behaviour and not a style point.
6750 const line::reg::Json env = ldes_envelope(r, o);
6751 for (line::reg::Json::const_iterator it = env.begin(); it != env.end(); ++it)
6752 p[it.key()] = it.value();
6753 emit_analysis<double>("sample", p, r.method);
6754 return 0;
6755 }
6756 ldes_banner(r, o);
6757 std::printf("%14s %s\n", "Time", "SysState (station-major, per class)");
6758 for (std::size_t j = 0; j < n; ++j) {
6759 std::printf("%14.8g ", r.t[j]);
6760 for (std::size_t i = 0; i < M; ++i)
6761 for (std::size_t c = 0; c < K; ++c)
6762 std::printf(" %g", c < r.QNt[i].size() && j < r.QNt[i][c].rows()
6763 ? r.QNt[i][c](j, 0)
6764 : 0.0);
6765 std::printf("\n");
6766 }
6767 return 0;
6768}
6769
6770/**
6771 * `-s ldes -a reward`: `getAvgReward`, E[r] on the EXACT joint-state histogram.
6772 *
6773 * The engine exports, under `--export-histogram`, the residence time of every
6774 * joint state it visited, in the aggregate layout `ctmc_state_space_aggr` builds.
6775 * The rewards are then evaluated here, state by state, so E[r] = sum_s (t_s /
6776 * sum t) r(state_s) is correct for a NONLINEAR reward too -- which is the whole
6777 * point of the histogram over the means: E[n^2] cannot be recovered from E[n].
6778 *
6779 * THIS IS THE ONE ARM THAT ALSO PARSES THE DOCUMENT, because a reward is a
6780 * DECLARATION and the declarations live in the model, not in the result. A model
6781 * outside this port's reader therefore reaches every other LDES arm and not this
6782 * one, and says so by the reader's own refusal.
6783 */
6784int solve_model_ldes_reward(const std::string& file, const Knobs& k) {
6785 line::qn::Network<double> net = read_model<double>(file);
6787 if (sn.reward.empty())
6788 throw line::InputError(
6789 "-s ldes -a reward needs a reward declared on the model (set_reward(name, fn), the "
6790 "`rewards` block of model.json); there is nothing to average");
6791
6792 const line::ldes::LdesOptions o = ldes_options(k);
6793 std::vector<std::string> extra;
6794 extra.push_back("--export-histogram");
6795 const line::ldes::LdesResult r = ldes_run(file, o, extra);
6798 "SolverLDES -a reward needs the joint-state residence-time histogram the engine "
6799 "exports under --export-histogram and the run returned none");
6800
6801 double total = 0.0;
6802 for (std::size_t s = 0; s < r.histogram_time.rows(); ++s)
6803 for (std::size_t c = 0; c < r.histogram_time.cols(); ++c) total += r.histogram_time(s, c);
6804 if (!(total > 0.0))
6805 throw line::NumericError(line::ErrorKind{"Degenerate"},
6806 "SolverLDES -a reward: the state histogram carries no residence time, so no state "
6807 "distribution can be formed from it");
6808
6809 const std::size_t ns = r.histogram_space.rows(), w = r.histogram_space.cols();
6810 std::vector<double> E(sn.reward.size(), 0.0);
6811 std::vector<std::string> names(sn.reward.size());
6812 for (std::size_t l = 0; l < sn.reward.size(); ++l) {
6813 names[l] = sn.reward[l].name;
6814 for (std::size_t s = 0; s < ns; ++s) {
6815 std::vector<double> row(w);
6816 for (std::size_t c = 0; c < w; ++c) row[c] = r.histogram_space(s, c);
6817 const double t = s < r.histogram_time.rows() && r.histogram_time.cols() > 0
6818 ? r.histogram_time(s, 0)
6819 : 0.0;
6820 E[l] += (t / total) * sn.reward[l].fn(row);
6821 }
6822 }
6823
6824 if (g_json_output) {
6825 line::reg::Json p = line::reg::Json::object();
6826 p["type"] = "AvgReward";
6827 line::reg::Json nm = line::reg::Json::array();
6828 for (std::size_t l = 0; l < names.size(); ++l) nm.push_back(names[l]);
6829 p["Reward"] = nm;
6830 p["E"] = vector_json(E);
6831 p["states"] = ns;
6832 // The envelope is built ONCE into a local: `begin()` and `end()` taken
6833 // from two different temporaries are iterators into two different
6834 // objects, which is undefined behaviour and not a style point.
6835 const line::reg::Json env = ldes_envelope(r, o);
6836 for (line::reg::Json::const_iterator it = env.begin(); it != env.end(); ++it)
6837 p[it.key()] = it.value();
6838 // NO "method": these are expectations over an empirical distribution and
6839 // no chain was solved, so there is no resolved method to report.
6840 emit_analysis<double>("reward", p, std::string());
6841 return 0;
6842 }
6843 ldes_banner(r, o);
6844 std::printf("%-28s %16s\n", "Reward", "E[r]");
6845 for (std::size_t l = 0; l < E.size(); ++l)
6846 std::printf("%-28s %16.10g\n", names[l].c_str(), E[l]);
6847 return 0;
6848}
6849
6850/**
6851 * `-s ldes -a prob`: `getProb`, `getProbAggr`, `getProbSys` and `getProbSysAggr`,
6852 * all four read off the joint-state histogram of ONE run, as
6853 * `@@SolverLDES/getProb*.m` does through `ldesHistProb`.
6854 *
6855 * THE STATE IS THE MODEL'S DECLARED ONE (`api::sn_declared_marginal`, the same
6856 * per-class counts `-s jmt -a prob` weighs against), and `--node` with `--state`
6857 * overrides one station's counts, which is `getProbAggr(node, state)`'s second
6858 * argument. THE DETAILED AND THE AGGREGATE QUERIES COINCIDE HERE, and that is the
6859 * reference's definition rather than a shortcut: the histogram records per-class
6860 * counts per station and nothing about buffer order or phase, so MATLAB's
6861 * `getProb` marginalizes its state with `State.toMarginal` before matching, and
6862 * `getProbSysAggr` is literally `getProbSys`. Each probability is the residence
6863 * time of the matching histogram rows over the total, and `seen` says whether any
6864 * row matched at all, since on a simulation a zero is usually the run length.
6865 *
6866 * A Source holds no jobs, so it takes no part in the system match (its histogram
6867 * columns are zero, as the reference's own match would find them).
6868 */
6869int solve_model_ldes_prob(const std::string& file, const Knobs& k) {
6870 line::qn::Network<double> net = read_model<double>(file);
6872 const std::size_t M = sn.nstations, R = sn.nclasses;
6873
6875 if (!k.state.empty()) {
6876 std::size_t ist = 0;
6877 if (k.node && k.node <= sn.nodes.size()) ist = sn.nodes[k.node - 1].station;
6878 if (ist == 0)
6879 throw line::InputError("--node " + std::to_string(k.node) +
6880 " is not a station; the LDES state histogram records station "
6881 "queue lengths only");
6882 if (k.state.size() != R)
6883 throw line::InputError("-s ldes -a prob takes --state as one job count per class (" +
6884 std::to_string(R) + "), got " + std::to_string(k.state.size()));
6885 for (std::size_t r = 0; r < R; ++r) nir(ist - 1, r) = static_cast<double>(k.state[r]);
6886 }
6887
6888 const line::ldes::LdesOptions o = ldes_options(k);
6889 std::vector<std::string> extra;
6890 extra.push_back("--export-histogram");
6891 const line::ldes::LdesResult res = ldes_run(file, o, extra);
6892 const line::Matrix<double>& space = res.histogram_space;
6893 const line::Matrix<double>& tm = res.histogram_time;
6894 if (space.empty() || tm.empty())
6896 "SolverLDES -a prob needs the joint-state residence-time histogram the engine exports "
6897 "under --export-histogram and the run returned none");
6898 if (space.cols() < M * R)
6899 throw line::ExternalError(line::ErrorKind{"LDES"}, "SolverLDES: the state histogram holds " +
6900 std::to_string(space.cols()) + " columns, fewer than the " +
6901 std::to_string(M * R) + " of " + std::to_string(M) +
6902 " stations by " + std::to_string(R) + " classes");
6903
6904 std::vector<double> dwell(space.rows(), 0.0);
6905 double total = 0.0;
6906 for (std::size_t s = 0; s < space.rows() && s < tm.rows(); ++s)
6907 for (std::size_t c = 0; c < tm.cols(); ++c) dwell[s] += tm(s, c);
6908 for (double d : dwell) total += d;
6909 if (!(total > 0.0))
6910 throw line::NumericError(line::ErrorKind{"Degenerate"},
6911 "SolverLDES -a prob: the state histogram carries no residence time, so no state "
6912 "probability can be formed from it");
6913
6914 // ldesHistProb's match: |space - target| < 1e-9 on the station's R columns.
6915 auto matches = [&](std::size_t s, std::size_t i) {
6916 for (std::size_t r = 0; r < R; ++r)
6917 if (!(std::abs(space(s, i * R + r) - nir(i, r)) < 1e-9)) return false;
6918 return true;
6919 };
6920 std::vector<double> prob(M, 0.0);
6921 std::vector<bool> seen(M, false);
6922 double psys = 0.0;
6923 bool sys_seen = false;
6924 for (std::size_t s = 0; s < space.rows(); ++s) {
6925 bool all = true;
6926 for (std::size_t i = 0; i < M; ++i) {
6927 const bool src = sn.nodes[sn.station_to_node[i] - 1].nodetype == line::lang::NodeType::Source;
6928 if (matches(s, i)) {
6929 prob[i] += dwell[s];
6930 seen[i] = true;
6931 } else if (!src) {
6932 all = false;
6933 }
6934 }
6935 if (all) {
6936 psys += dwell[s];
6937 sys_seen = true;
6938 }
6939 }
6940 for (double& p : prob) p /= total;
6941 psys /= total;
6942
6943 if (g_json_output) {
6944 line::reg::Json p = line::reg::Json::object();
6945 p["type"] = "ProbAggr";
6946 p["indexBase"] = 0;
6947 p["ProbSys"] = psys;
6948 p["ProbSysAggr"] = psys;
6949 p["SysStateSeen"] = sys_seen;
6950 p["states"] = space.rows();
6951 line::reg::Json st = line::reg::Json::array(), pa = line::reg::Json::array(),
6952 sv = line::reg::Json::array();
6953 for (std::size_t i = 0; i < M; ++i) {
6954 st.push_back(sn.stations[i].name);
6955 pa.push_back(prob[i]);
6956 sv.push_back(static_cast<bool>(seen[i]));
6957 }
6958 p["Station"] = st;
6959 p["Prob"] = pa;
6960 p["ProbAggr"] = pa;
6961 p["StateSeen"] = sv;
6962 emit_analysis<double>("prob", p, res.method);
6963 return 0;
6964 }
6965 ldes_banner(res, o);
6966 std::printf("ProbSys = ProbSysAggr %.10g%s\n", psys, sys_seen ? "" : " (state never observed)");
6967 std::printf("%-16s %14s\n", "Station", "Prob=ProbAggr");
6968 for (std::size_t i = 0; i < M; ++i)
6969 std::printf("%-16s %14.10g%s\n", sn.stations[i].name.c_str(), prob[i],
6970 seen[i] ? "" : " (state never observed)");
6971 return 0;
6972}
6973
6974/**
6975 * The `-s ldes` entry: one analysis per getter of the reference's surface.
6976 *
6977 * `-a prob` is `solve_model_ldes_prob`: the four getProb queries read off the
6978 * engine's joint-state histogram at the model's DECLARED state.
6979 */
6980int solve_model_ldes(const std::string& file, const Knobs& k, const std::string& analysis) {
6981 if (analysis == "avg") return solve_model_ldes_avg(file, k);
6982 if (analysis == "tran") return solve_model_ldes_tran(file, k);
6983 // THE SAME ECDF UNDER FOUR NAMES, which is the reference's own structure and
6984 // not a shortcut here: `@@SolverLDES/getCdfRespT`, `getTranCdfRespT` and
6985 // `getTranCdfPassT` all read `respTimeSamples`, and the JAR's
6986 // getTranCdfPassT is literally `return getTranCdfRespT(R)`. A simulator
6987 // observes one per-job passage and there is no second measurement to make;
6988 // emitting the curve under the key the caller asked for is what tells them
6989 // apart, and the payload's `type` says which question it answers.
6990 if (analysis == "cdf") return solve_model_ldes_cdf(file, k, "cdf", "CdfRespT");
6991 if (analysis == "cdfpasst") return solve_model_ldes_cdf(file, k, "cdfpasst", "CdfPassT");
6992 if (analysis == "perct") return solve_model_ldes_perct(file, k);
6993 if (analysis == "trancdf") return solve_model_ldes_cdf(file, k, "trancdf", "TranCdfRespT");
6994 if (analysis == "trancdfpasst")
6995 return solve_model_ldes_cdf(file, k, "trancdfpasst", "TranCdfPassT");
6996 if (analysis == "sample") return solve_model_ldes_sample(file, k);
6997 if (analysis == "reward") return solve_model_ldes_reward(file, k);
6998 if (analysis == "prob") return solve_model_ldes_prob(file, k);
6999 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
7000 "SolverLDES ports -a avg (getAvg) and its four views -a node, -a sys, -a chain and "
7001 "-a nodechain, -a tran (getTranAvg), -a cdf / cdf-passt / "
7002 "tran-cdf-respt / tran-cdf-passt (the empirical passage law, one measurement under the "
7003 "four names the reference gives it), -a perct-respt (getPerctRespT with FQUEST / FIRQUEST "
7004 "confidence intervals), -a sample (sampleSys), -a reward "
7005 "(getAvgReward) and -a prob (getProb, getProbAggr, getProbSys, getProbSysAggr); got '" +
7006 analysis + "'");
7007}
7008
7009std::string auto_getter_of_analysis(const std::string& analysis) {
7010 if (analysis == "prob") return "getProbSysAggr";
7011 if (analysis == "marg") return "getProbMarg";
7012 if (analysis == "sysmarg") return "getProbSysMarg";
7013 if (analysis == "normconst") return "getProbNormConstAggr";
7014 if (analysis == "tranprob") return "getTranProbSysAggr";
7015 if (analysis == "sample") return "sampleSys";
7016 if (analysis == "cdf") return "getCdfRespT";
7017 if (analysis == "gen") return "getInfGen";
7018 if (analysis == "states") return "getStateSpace";
7019 if (analysis == "reward") return "getAvgReward";
7020 if (analysis == "sens") return "getSensitivityTable";
7021 if (analysis == "tran") return "getTranAvg";
7022 if (analysis == "internals") return "getMAMResult";
7023 // `-a bounds` and `-a tranreward` deliberately keep the AvgTable getter:
7024 // `getBoundsTable` and `getTranReward` are absent from chooseSolverHeur's
7025 // own method lists, so naming them here would ask the chooser about a getter
7026 // it does not rank. Each is served by exactly one engine anyway (BA and
7027 // CTMC), which refuses by name when `-s auto` sends the run elsewhere.
7028 if (analysis == "node") return "getAvgNodeTable";
7029 return "getAvgTable";
7030}
7031
7032/**
7033 * What `-s auto` resolved to: the engines to try, in order, and the method the
7034 * first of them runs.
7035 */
7036struct AutoPlan {
7037 std::vector<std::string> order; ///< CLI solver method names, chosen first
7038 std::string method; ///< the method the chosen engine runs, "" for its default
7039 std::string note; ///< what the ranking preferred and this port cannot build
7040 /** Per entry of `order`, the `--stage-solver` of an Environment candidate; "" elsewhere. */
7041 std::vector<std::string> stage;
7042};
7043
7044/** The CLI method name of a method family, or a refusal naming what the family needs. */
7045std::string auto_cli_token_of_family(const std::string& fam) {
7046 if (fam == "mva" || fam == "nc" || fam == "ctmc" || fam == "mam" || fam == "ag" ||
7047 fam == "ssa" || fam == "ba" || fam == "uq" || fam == "env")
7048 return fam;
7049 if (fam == "fld") return "fluid";
7050 if (fam == "ldes") {
7051 // The engine is not built here, it is RUN here, so the family resolves
7052 // whenever the machine has one and refuses -- naming what is missing --
7053 // when it does not, rather than diverting to a different simulator.
7056 "--method ldes names the discrete-event engine, and no engine was found beside "
7057 "this binary (common/ldes or common/ldes.jar, or $LINE_LDES_DIR); -s ssa is the "
7058 "simulator this port builds in process");
7059 return "ldes";
7060 }
7061 if (fam == "jmt") {
7062 // IT IS WRAPPED NOW. This refused the token outright until the JMT
7063 // client landed, and stayed behind: `-s jmt` drives jsim and jmva
7064 // through `solver_jmt_run_analyzer`, so refusing `--method jmt` denied
7065 // under `-s auto` what the very same binary answers under `-s jmt`.
7066 // Availability is left to the wrapper, which names what is missing (a
7067 // JVM, common/JMT.jar or a REST endpoint) rather than guessing here.
7068 return "jmt";
7069 }
7070 // On a flat Network the lqns family's methods are the qns ones, served by
7071 // `qnsolver` through `solve_model_lqns_network`.
7072 if (fam == "lqns") return "lqns";
7073 if (fam == "ln")
7075 "--method ln names the layered solver, which takes a LayeredNetwork: pass the model "
7076 "as -i lqnx -s ln rather than as a Network");
7077 throw line::InputError("SolverAUTO: no engine stands behind method family '" + fam + "'");
7078}
7079
7080/**
7081 * Is this model.json an Environment envelope rather than a Network?
7082 *
7083 * `-s auto` has to know before it parses: the two readers take different
7084 * documents, and the reference's chooser has an Environment arm that is
7085 * unreachable if every auto run is assumed to hold a Network. A malformed
7086 * document answers false, so the real reader reports the parse error.
7087 */
7088bool model_is_environment(const std::string& file) {
7089 try {
7090 line::io::detail::json root;
7091 if (file.empty()) {
7092 std::istringstream in(stdin_model_text());
7093 in >> root;
7094 } else {
7095 std::ifstream in(file.c_str());
7096 if (!in) return false;
7097 in >> root;
7098 }
7099 // The envelope may wrap the model, exactly as build_environment_from_json
7100 // unwraps it; `type` is what that reader keys on, so this reads the same
7101 // field rather than a second convention of its own.
7102 if (!root.is_object()) return false;
7103 const line::io::detail::json& model = root.contains("model") ? root.at("model") : root;
7104 return model.is_object() && model.value("type", std::string()) == "Environment";
7105 } catch (...) {
7106 return false;
7107 }
7108}
7109
7110/**
7111 * `-s auto`: which engine answers, by `chooseSolver.m` through solver_auto.h.
7112 *
7113 * THREE THINGS DECIDE, in the reference's own order. `--method` is resolved
7114 * first, because a method FAMILY ('nc', 'nc.comom') names the engine outright
7115 * and bypasses every ranking, while a selection INTENT ('exact', 'sim', 'fast',
7116 * 'accurate') picks which ranking runs. Then the model class: an Environment
7117 * envelope takes the Environment arm, a Network the Network one. Then the
7118 * GETTER the caller asked for, since the reference keys the ranking on the
7119 * metric family and not on the model alone.
7120 *
7121 * THE ORDER IS A RETRY LIST, not a single name. `delegate.m` tries the chosen
7122 * solver and then every feasible candidate, so a refusal moves to the next
7123 * engine instead of ending the run; the caller sees which one answered.
7124 *
7125 * The choice reads structure only -- traits, feature sets, product form,
7126 * populations -- so it is made in the arithmetic the run will use and costs one
7127 * extra parse of the model, nothing more.
7128 */
7129template <class T>
7130AutoPlan choose_auto_plan(const std::string& file, const std::string& analysis,
7131 const std::string& method_token) {
7133 try {
7134 tok = line::autosolver::auto_resolve_token(method_token);
7135 } catch (const line::InputError&) {
7136 // A bare algorithm name ('comom') resolves to the family declaring it on THIS model
7137 // (familyDeclaringMethod), which needs a Network; any other model class keeps the refusal.
7138 if (model_is_environment(file)) throw;
7139 tok = line::autosolver::auto_resolve_token(method_token, read_model<T>(file).get_struct());
7140 }
7141 AutoPlan plan;
7142 if (!tok.is_intent) {
7143 plan.order.push_back(auto_cli_token_of_family(tok.family));
7144 if (tok.submethod != "default") plan.method = tok.submethod;
7145 return plan;
7146 }
7147
7148 const std::string getter = auto_getter_of_analysis(analysis);
7149 if (model_is_environment(file)) {
7152 // One `-s env` attempt per candidate ensemble, each naming its stage
7153 // solver, as `delegate.m` walks SolverENV(model, @SolverX) in turn.
7154 for (std::size_t i = 0; i < ec.retry.size(); ++i) {
7155 plan.order.push_back("env");
7156 plan.stage.push_back(line::autosolver::auto_env_stage_solver(ec.retry[i]));
7157 }
7158 for (std::size_t i = 0; i < ec.skipped.size(); ++i)
7159 plan.note += std::string(i ? ", " : " (the ranking preferred ") +
7161 if (!ec.skipped.empty()) plan.note += ", which this port does not build)";
7162 return plan;
7163 }
7164
7165 line::qn::Network<T> net = read_model<T>(file);
7168 plan.method = c.method;
7169 const std::vector<line::autosolver::AutoSolver> proposed =
7171 for (std::size_t i = 0; i < proposed.size(); ++i)
7172 plan.order.push_back(line::autosolver::auto_solver_name(proposed[i]));
7173 for (std::size_t i = 0; i < c.skipped.size(); ++i)
7174 plan.note += std::string(i ? ", " : " (the ranking preferred ") +
7176 if (!c.skipped.empty()) plan.note += ", which this port does not build)";
7177 return plan;
7178}
7179
7180AutoPlan choose_auto_plan_dispatch(const std::string& arith, const std::string& file,
7181 const std::string& analysis, const std::string& method_token) {
7182 if (arith == "exact") return choose_auto_plan<line::Rational>(file, analysis, method_token);
7183 if (arith == "real:16") return choose_auto_plan<line::Real<16> >(file, analysis, method_token);
7184 if (arith == "real" || arith == "real:32")
7185 return choose_auto_plan<line::Real<32> >(file, analysis, method_token);
7186 if (arith == "real:64") return choose_auto_plan<line::Real<64> >(file, analysis, method_token);
7187 if (arith == "real:128")
7188 return choose_auto_plan<line::Real<128> >(file, analysis, method_token);
7189 if (arith == "real:256")
7190 return choose_auto_plan<line::Real<256> >(file, analysis, method_token);
7191 return choose_auto_plan<double>(file, analysis, method_token);
7192}
7193
7194/**
7195 * The numeric clean-up SolverLN.getAvgTable applies before printing.
7196 *
7197 * It is reproduced here because the reference's reported table IS the
7198 * sanitized one, so a row-by-row comparison against it has to compare like
7199 * with like. Two rules: snap a value to one decimal place when it is already
7200 * within CoarseTol of it relatively, and snap anything at or below FineTol to
7201 * zero. The second rule is what turns the residual queue length of a chain of
7202 * Immediate classes -- of order 1e-8 by construction, since Immediate has rate
7203 * 1e8 -- into the exact zero the reference prints.
7204 */
7205double ln_sanitize(double x) {
7206 const double r = std::round(x * 10.0);
7207 if (std::fabs(x * 10.0 - r) < line::lang::GlobalConstants::CoarseTol * x * 10.0) x = r / 10.0;
7208 if (x <= line::lang::GlobalConstants::FineTol) x = 0.0;
7209 return x;
7210}
7211
7212const char* ln_element_kind(const line::lqn::LqnStruct<double>& l, std::size_t i) {
7213 switch (l.type[i]) {
7214 case line::lang::LqnElement::HOST: return "Processor";
7215 case line::lang::LqnElement::TASK: return l.isref[i] ? "RefTask" : "Task";
7216 case line::lang::LqnElement::ENTRY: return "Entry";
7217 default: return "Activity";
7218 }
7219}
7220
7221/**
7222 * Print every layer's stations, classes and routing, in a form a MATLAB dump of
7223 * `solver.ensemble{k}` can be diffed against line by line.
7224 *
7225 * A layered result that is close but not equal across codebases is almost never
7226 * a difference in the MVA call; it is a layer that was BUILT differently -- a
7227 * class that is present in one and not the other, a population, a routing
7228 * probability. Comparing the final AvgTable cannot tell those apart, so the
7229 * structure has to be observable directly.
7230 */
7231template <class T>
7232void ln_dump_layers(const line::ln::SolverLN<T>& solver) {
7233 using namespace line;
7234 const std::vector<qn::Layer<T> >& ens = solver.layers();
7235 for (std::size_t k = 0; k < ens.size(); ++k) {
7236 const qn::Layer<T>& L = ens[k];
7237 std::printf("LAYER %zu %s nstations=%zu nclasses=%zu nchains=%zu\n", k + 1, L.name.c_str(),
7238 L.stations.size(), L.classes.size(), L.nchains);
7239 for (std::size_t i = 0; i < L.stations.size(); ++i)
7240 std::printf(" STATION %zu %s sched=%s nservers=%g\n", i + 1, L.stations[i].name.c_str(),
7241 lang::sched_to_text(L.stations[i].sched), L.stations[i].nservers);
7242 for (std::size_t r = 0; r < L.classes.size(); ++r)
7243 std::printf(" CLASS %zu %s pop=%.17g refstat=%zu completes=%d\n", r + 1,
7244 L.classes[r].name.c_str(), L.classes[r].population, L.classes[r].refstat,
7245 int(L.classes[r].completes));
7246 for (std::size_t i = 0; i < L.stations.size(); ++i)
7247 for (std::size_t r = 0; r < L.classes.size(); ++r) {
7248 if (L.disabled.empty() || L.disabled[i][r]) continue;
7249 std::printf(" RATE %s %s %.17g scv=%.17g\n", L.stations[i].name.c_str(),
7250 L.classes[r].name.c_str(), num_traits<T>::to_double(L.rates(i, r)),
7251 num_traits<T>::to_double(L.scv(i, r)));
7252 }
7253 for (const auto& kv : L.P) {
7254 const Matrix<T>& B = kv.second;
7255 for (std::size_t i = 0; i < B.rows(); ++i)
7256 for (std::size_t j = 0; j < B.cols(); ++j) {
7257 const double p = num_traits<T>::to_double(B(i, j));
7258 if (p == 0.0) continue;
7259 std::printf(" ROUTE %s->%s %s->%s %.17g\n",
7260 L.classes[kv.first.first - 1].name.c_str(),
7261 L.classes[kv.first.second - 1].name.c_str(),
7262 L.nodes[i].name.c_str(), L.nodes[j].name.c_str(), p);
7263 }
7264 }
7265 }
7266}
7267
7268/** The LnOptions a set of CLI knobs describes; arithmetic-independent. */
7269inline line::ln::LnOptions ln_options_from(const Knobs& k) {
7270 using namespace line;
7271 // The reference's own LnOptions defaults stand unless the caller overrode
7272 // them; the CLI does not restate them, so an untouched knob keeps whatever
7273 // SolverLN itself considers default.
7275 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
7276 if (k.iter_tol >= 0.0) opt.iter_tol = k.iter_tol;
7277 if (k.no_interlocking) opt.interlocking = false;
7278 if (!k.interlock_method.empty()) opt.interlock_method = k.interlock_method;
7279 if (k.interlock_maxpaths >= 0.0) opt.interlock_maxpaths = k.interlock_maxpaths;
7280 if (!k.interlock_refpath_scope.empty()) opt.interlock_refpath_scope = k.interlock_refpath_scope;
7281 if (!k.layer_solver.empty()) opt.layer_solver = k.layer_solver;
7282 if (!k.method.empty()) opt.method = k.method;
7283 // --samples and --seed reach whichever simulator runs the layers; for `ldes`
7284 // and `jmt` the seed is the BASE of SolverLN.pre's per-layer schedule.
7285 if (k.samples) {
7286 opt.layer_ssa.samples = k.samples;
7287 opt.layer_ldes.samples = static_cast<std::size_t>(k.samples);
7288 opt.layer_jmt.samples = static_cast<double>(k.samples);
7289 }
7290 if (k.seed) {
7291 opt.layer_ssa.seed = k.seed;
7292 opt.layer_ldes.seed = static_cast<long>(k.seed);
7293 opt.layer_jmt.seed = static_cast<long>(k.seed);
7294 }
7295 if (k.t1 >= 0.0) opt.timespan_end = k.t1;
7296 if (k.tran_points) opt.tran_points = k.tran_points;
7297 if (!k.ln_transient.empty()) opt.ln_transient = k.ln_transient;
7298 if (!k.ln_transient_channels.empty()) opt.ln_transient_channels = k.ln_transient_channels;
7299 for (const auto& kv : k.lld) opt.lld[kv.first] = kv.second;
7300 if (k.nlp_alpha >= 0.0) opt.nlp_alpha = k.nlp_alpha;
7301 if (k.nlp_warm >= 0) opt.nlp_warm = int(k.nlp_warm);
7302 if (k.nlp_maxiter >= 0) opt.nlp_maxiter = int(k.nlp_maxiter);
7303 if (!k.nlp_fork.empty()) opt.nlp_fork = k.nlp_fork;
7304 if (!k.warmstart.empty()) opt.warmstart = k.warmstart;
7305 if (k.mol_iter_max >= 0) opt.mol_iter_max = std::size_t(k.mol_iter_max);
7306 if (k.mol_iter_tol >= 0.0) opt.mol_iter_tol = k.mol_iter_tol;
7307 if (k.mol_relax_factor >= 0.0) opt.mol_relax_factor = k.mol_relax_factor;
7308 return opt;
7309}
7310
7311/** The engine name the banner reports, which is never a hardcoded MVA. */
7312inline const char* ln_layer_engine_name(const std::string& layer_solver) {
7313 if (layer_solver == "fluid") return "Fluid";
7314 if (layer_solver == "nc") return "NC";
7315 if (layer_solver == "ssa") return "SSA";
7316 if (layer_solver == "mam") return "MAM";
7317 if (layer_solver == "ctmc") return "CTMC";
7318 if (layer_solver == "ldes") return "LDES";
7319 if (layer_solver == "jmt") return "JMT";
7320 return "MVA";
7321}
7322
7323/**
7324 * `-a tran`: the layered transient, one block of time series per layer.
7325 *
7326 * The blocks are printed rather than the block-diagonal cell array the
7327 * reference assembles, because the off-diagonal blocks of that array are empty
7328 * by construction and each layer keeps its own grid.
7329 */
7330template <class T>
7331int run_ln_tran(const std::string& file, const std::string& output, const Knobs& k) {
7332 using namespace line;
7333 const lqn::LqnStruct<T> model = io::read_layered_model<T>(file);
7334 ln::LnOptions opt = ln_options_from(k);
7335 ln::SolverLN<T> solver(model, opt);
7336 const ln::LnTranSolution tr = solver.get_tran_avg();
7337 const std::vector<qn::Layer<T>>& layers = solver.layers();
7338
7339 if (output == "json") {
7340 reg::Json j = reg::Json::object();
7341 j["model"] = file;
7342 j["arith"] = num_traits<T>::name();
7343 j["mode"] = tr.mode;
7344 j["iterations"] = tr.iterations;
7345 j["gap"] = ln_sanitize(tr.gap);
7346 reg::Json ls = reg::Json::array();
7347 for (std::size_t e = 0; e < tr.layers.size(); ++e) {
7348 reg::Json le = reg::Json::object();
7349 le["layer"] = layers[e].name;
7350 reg::Json tt = reg::Json::array();
7351 for (double t : tr.layers[e].t) tt.push_back(ln_sanitize(t));
7352 le["t"] = tt;
7353 reg::Json series = reg::Json::array();
7354 for (std::size_t i = 0; i < tr.layers[e].QN.size(); ++i)
7355 for (std::size_t r = 0; r < tr.layers[e].QN[i].size(); ++r) {
7356 reg::Json s = reg::Json::object();
7357 s["station"] = layers[e].stations[i].name;
7358 s["class"] = layers[e].classes[r].name;
7359 auto arr = [&](const std::vector<double>& v) {
7360 reg::Json a = reg::Json::array();
7361 for (double x : v) a.push_back(ln_sanitize(x));
7362 return a;
7363 };
7364 s["QLen"] = arr(tr.layers[e].QN[i][r]);
7365 s["Util"] = arr(tr.layers[e].UN[i][r]);
7366 s["Tput"] = arr(tr.layers[e].TN[i][r]);
7367 series.push_back(s);
7368 }
7369 le["series"] = series;
7370 ls.push_back(le);
7371 }
7372 j["layers"] = ls;
7373 emit_document(dump_document(j, 1));
7374 return 0;
7375 }
7376
7377 std::printf("SolverLN(Solver%s) getTranAvg arith=%s mode=%s layers=%zu iterations=%ld gap=%.3e\n",
7378 ln_layer_engine_name(opt.layer_solver), num_traits<T>::name(), tr.mode.c_str(),
7379 tr.layers.size(), tr.iterations, tr.gap);
7380 for (std::size_t e = 0; e < tr.layers.size(); ++e) {
7381 const std::vector<double>& t = tr.layers[e].t;
7382 if (t.empty()) continue;
7383 std::printf("\nLayer %s (%zu points on [%.6g, %.6g])\n", layers[e].name.c_str(), t.size(),
7384 t.front(), t.back());
7385 std::printf("%-30s %-24s %12s %12s %12s %12s\n", "Station", "JobClass", "QLen(0)",
7386 "QLen(end)", "Util(end)", "Tput(end)");
7387 for (std::size_t i = 0; i < tr.layers[e].QN.size(); ++i)
7388 for (std::size_t r = 0; r < tr.layers[e].QN[i].size(); ++r) {
7389 const std::vector<double>& q = tr.layers[e].QN[i][r];
7390 if (q.empty()) continue;
7391 std::printf("%-30s %-24s %12.6g %12.6g %12.6g %12.6g\n",
7392 layers[e].stations[i].name.c_str(), layers[e].classes[r].name.c_str(),
7393 ln_sanitize(q.front()), ln_sanitize(q.back()),
7394 ln_sanitize(tr.layers[e].UN[i][r].back()),
7395 ln_sanitize(tr.layers[e].TN[i][r].back()));
7396 }
7397 }
7398 return 0;
7399}
7400
7401/** `-a sens`: the layer sensitivity tables under a leading Layer column. */
7402template <class T>
7403int run_ln_sens(const std::string& file, const std::string& output, const Knobs& k) {
7404 using namespace line;
7405 const lqn::LqnStruct<T> model = io::read_layered_model<T>(file);
7406 ln::LnOptions opt = ln_options_from(k);
7407 ln::SolverLN<T> solver(model, opt);
7409 if (!k.sens_method.empty()) so.method = k.sens_method;
7410 if (!k.sens_scheme.empty()) so.scheme = k.sens_scheme;
7411 if (k.sens_step > 0.0) so.step = k.sens_step;
7412 const ln::LnSensTable<T> tbl = solver.get_sensitivity_table(so);
7413
7414 if (output == "json") {
7415 reg::Json j = reg::Json::object();
7416 j["model"] = file;
7417 j["arith"] = num_traits<T>::name();
7418 j["method"] = tbl.method;
7419 reg::Json rows = reg::Json::array();
7420 for (const auto& r : tbl.rows) {
7421 reg::Json o = reg::Json::object();
7422 o["Layer"] = r.layer;
7423 o["Station"] = r.station;
7424 o["JobClass"] = r.jobclass;
7425 o["dTput_dRate"] = sens_sanitize_signed(num_traits<T>::to_double(r.dTput));
7426 o["dRespT_dRate"] = sens_sanitize_signed(num_traits<T>::to_double(r.dRespT));
7427 o["dQLen_dRate"] = sens_sanitize_signed(num_traits<T>::to_double(r.dQLen));
7428 o["dUtil_dRate"] = sens_sanitize_signed(num_traits<T>::to_double(r.dUtil));
7429 rows.push_back(o);
7430 }
7431 j["rows"] = rows;
7432 emit_document(dump_document(j, 1));
7433 return 0;
7434 }
7435
7436 std::printf("SolverLN(Solver%s) getSensitivityTable arith=%s method=%s rows=%zu\n",
7437 ln_layer_engine_name(opt.layer_solver), num_traits<T>::name(), tbl.method.c_str(),
7438 tbl.rows.size());
7439 std::printf("%-28s %-28s %-20s %14s %14s %14s %14s\n", "Layer", "Station", "JobClass",
7440 "dTput_dRate", "dRespT_dRate", "dQLen_dRate", "dUtil_dRate");
7441 for (const auto& r : tbl.rows)
7442 std::printf("%-28s %-28s %-20s %14.6g %14.6g %14.6g %14.6g\n", r.layer.c_str(),
7443 r.station.c_str(), r.jobclass.c_str(),
7444 sens_sanitize_signed(num_traits<T>::to_double(r.dTput)),
7445 sens_sanitize_signed(num_traits<T>::to_double(r.dRespT)),
7446 sens_sanitize_signed(num_traits<T>::to_double(r.dQLen)),
7447 sens_sanitize_signed(num_traits<T>::to_double(r.dUtil)));
7448 return 0;
7449}
7450
7451/** `-a cdf`: the per-entry response-time distribution of the moment3 method. */
7452template <class T>
7453int run_ln_cdf(const std::string& file, const std::string& output, const Knobs& k) {
7454 using namespace line;
7455 const lqn::LqnStruct<T> model = io::read_layered_model<T>(file);
7456 ln::LnOptions opt = ln_options_from(k);
7457 // getCdfRespT.m runs the ensemble under moment3 whatever the caller asked
7458 // for, and restores the method afterwards: the mean-based update forms no
7459 // distribution at all, so there is nothing else to report.
7460 opt.method = "moment3";
7461 ln::SolverLN<T> solver(model, opt);
7462 const std::vector<ln::LnCdf> cdf = solver.get_cdf_respt();
7464
7465 if (output == "json") {
7466 reg::Json j = reg::Json::object();
7467 j["model"] = file;
7468 j["arith"] = num_traits<T>::name();
7469 reg::Json rows = reg::Json::array();
7470 for (std::size_t e = 1; e <= model.nentries && e < cdf.size(); ++e) {
7471 reg::Json o = reg::Json::object();
7472 o["entry"] = names.names[model.eshift + e];
7473 reg::Json tt = reg::Json::array(), ff = reg::Json::array();
7474 for (std::size_t p = 0; p < cdf[e].t.size(); ++p) {
7475 tt.push_back(ln_sanitize(cdf[e].t[p]));
7476 ff.push_back(ln_sanitize(cdf[e].cdf[p]));
7477 }
7478 o["t"] = tt;
7479 o["F"] = ff;
7480 rows.push_back(o);
7481 }
7482 j["entries"] = rows;
7483 emit_document(dump_document(j, 1));
7484 return 0;
7485 }
7486
7487 std::printf("SolverLN(Solver%s) getCdfRespT arith=%s method=moment3 entries=%zu\n",
7488 ln_layer_engine_name(opt.layer_solver), num_traits<T>::name(), model.nentries);
7489 for (std::size_t e = 1; e <= model.nentries && e < cdf.size(); ++e) {
7490 if (cdf[e].t.empty()) {
7491 std::printf("%-40s (no distribution: the entry has no fitted term)\n",
7492 names.names[model.eshift + e].c_str());
7493 continue;
7494 }
7495 // Quartiles, which is what a CDF is read for; the full grid goes to JSON.
7496 auto quantile = [&](double p) {
7497 for (std::size_t i = 0; i < cdf[e].cdf.size(); ++i)
7498 if (cdf[e].cdf[i] >= p) return cdf[e].t[i];
7499 return cdf[e].t.back();
7500 };
7501 std::printf("%-40s p25=%12.6g p50=%12.6g p75=%12.6g p95=%12.6g points=%zu\n",
7502 names.names[model.eshift + e].c_str(), ln_sanitize(quantile(0.25)),
7503 ln_sanitize(quantile(0.50)), ln_sanitize(quantile(0.75)),
7504 ln_sanitize(quantile(0.95)), cdf[e].t.size());
7505 }
7506 return 0;
7507}
7508
7509/**
7510 * Solve a .lqnx layered queueing network with SolverLN and print its AvgTable.
7511 *
7512 * The output is one row per LQN element, with its queue length, utilization,
7513 * response time, residence time and throughput, in the same element order as
7514 * MATLAB's getAvgTable, so a row-by-row numeric comparison against the
7515 * reference is a plain diff.
7516 *
7517 * `--repeat` re-runs the whole solve K times and reports the best wall-clock
7518 * time, which is what the arithmetic-backend benchmark reads.
7519 */
7520template <class T>
7521int run_ln(const std::string& file, const std::string& output, const Knobs& k) {
7522 using namespace line;
7523 const lqn::LqnStruct<T> model = io::read_layered_model<T>(file);
7524
7525 ln::LnOptions opt = ln_options_from(k);
7526 const int repeat = k.repeat > 0 ? k.repeat : 1;
7527
7528 double best = 1e300;
7530 std::size_t nlayers = 0;
7531 for (int rep = 0; rep < repeat; ++rep) {
7532 const auto t0 = std::chrono::steady_clock::now();
7533 ln::SolverLN<T> solver(model, opt);
7534 sol = solver.get_ensemble_avg();
7535 nlayers = solver.nlayers();
7536 if (output == "layers") {
7537 ln_dump_layers(solver);
7538 return 0;
7539 }
7540 const auto t1 = std::chrono::steady_clock::now();
7541 best = std::min(best, std::chrono::duration<double>(t1 - t0).count());
7542 }
7543 if (!sol.warning.empty()) std::fprintf(stderr, "Warning: %s\n", sol.warning.c_str());
7544
7545 // element names and kinds are arithmetic-independent, so read them once
7547
7548 if (output == "json") {
7549 reg::Json j = reg::Json::object();
7550 j["model"] = file;
7551 j["arith"] = num_traits<T>::name();
7552 j["layers"] = nlayers;
7553 j["iterations"] = sol.iterations;
7554 j["converged"] = sol.converged;
7555 j["seconds"] = best;
7556 reg::Json rows = reg::Json::array();
7557 for (std::size_t i = 1; i <= model.nidx; ++i) {
7558 reg::Json r = reg::Json::object();
7559 r["node"] = names.names[i];
7560 r["type"] = ln_element_kind(names, i);
7561 auto put = [&](const char* key, const std::vector<T>& v, const std::vector<bool>& d) {
7562 if (d[i]) r[key] = ln_sanitize(num_traits<T>::to_double(v[i]));
7563 else if (sol.is_bound) r[key] = 0.0; // see the note in the table below
7564 else r[key] = nullptr;
7565 };
7566 put("QLen", sol.QN, sol.defined_Q);
7567 put("Util", sol.UN, sol.defined_U);
7568 put("RespT", sol.RN, sol.defined_R);
7569 put("ResidT", sol.WN, sol.defined_W);
7570 put("Tput", sol.TN, sol.defined_T);
7571 rows.push_back(r);
7572 }
7573 j["rows"] = rows;
7574 emit_document(dump_document(j, 1));
7575 return 0;
7576 }
7577
7578 // The banner names the LAYER solver actually used, not a hardcoded MVA: the
7579 // two converge to different fixed points, so a reader (or a parity row) that
7580 // cannot tell them apart is reading numbers it cannot attribute.
7581 std::printf(
7582 "SolverLN(Solver%s) arith=%s type=%s layers=%zu iterations=%d converged=%d time=%.4fs\n",
7583 ln_layer_engine_name(opt.layer_solver), num_traits<T>::name(),
7584 line::util::method_type("LN", opt.method).c_str(), nlayers, sol.iterations,
7585 int(sol.converged), best);
7586 std::printf("%-62s %-10s %12s %12s %12s %12s %12s\n", "Node", "NodeType", "QLen", "Util",
7587 "RespT", "ResidT", "Tput");
7588 for (std::size_t i = 1; i <= model.nidx; ++i) {
7589 // NaN IS THE UNDEFINED MARKER EVERYWHERE EXCEPT UNDER A BOUND. MATLAB's
7590 // getAvgTable prints NaN for a measure the element does not have (a
7591 // processor has no queue length), and this reproduces that. A BOUND is
7592 // the one case where the reference prints 0 instead: `mw.*` defines
7593 // throughput and processor utilization only, and both MATLAB and the JAR
7594 // report the rest as zero rather than as absent (the JAR maps the NaN
7595 // explicitly, SolverLN.java:3294-3299). The `defined_*` flags still say
7596 // undefined to any caller of the API; only the printed table follows the
7597 // reference, so that a numeric parity row compares like with like.
7598 //
7599 // This table is for a human; a cross-codebase comparison must read the
7600 // `-o json` above, which carries the raw double, and quantize it itself.
7601 auto fmt = [&](const std::vector<T>& v, const std::vector<bool>& d, char* buf) {
7602 if (!d[i] && sol.is_bound) std::snprintf(buf, 24, "%12.6g", 0.0);
7603 else if (!d[i]) std::snprintf(buf, 24, "%12s", "NaN");
7604 else std::snprintf(buf, 24, "%12.6g", ln_sanitize(num_traits<T>::to_double(v[i])));
7605 };
7606 char q[24], u[24], rr[24], w[24], t[24];
7607 fmt(sol.QN, sol.defined_Q, q);
7608 fmt(sol.UN, sol.defined_U, u);
7609 fmt(sol.RN, sol.defined_R, rr);
7610 fmt(sol.WN, sol.defined_W, w);
7611 fmt(sol.TN, sol.defined_T, t);
7612 std::printf("%-62s %-10s %s %s %s %s %s\n", names.names[i].c_str(),
7613 ln_element_kind(names, i), q, u, rr, w, t);
7614 }
7615 return 0;
7616}
7617
7618/**
7619 * `-i lqnx -s ldes -a cdf`: the SIMULATED response time distribution per entry.
7620 *
7621 * The measured counterpart of `run_ln_cdf`, which fits an APH to three moments of
7622 * a fluid passage time and convolves. Here the engine timed every invocation from
7623 * the instant the request reached the entry to its reply -- the interval `RLN`
7624 * averages -- so this law's mean reproduces that row and its tail is observed
7625 * rather than extrapolated.
7626 */
7627int run_ln_ldes_cdf(const std::string& file, const std::string& output, const Knobs& k) {
7628 using namespace line;
7631 if (k.samples) o.samples = k.samples;
7632 if (k.seed) o.seed = static_cast<long>(k.seed);
7633
7635
7636 // The per-entry ecdf, through the same API function the other codebases
7637 // call getCdfRespTLN.
7638 const std::vector<ldes::engine::LnEntryCdf> cdf =
7640 std::vector<std::vector<double> > tt(model.nentries), ff(model.nentries);
7641 for (std::size_t e = 0; e < model.nentries; ++e) {
7642 tt[e] = cdf[e].t;
7643 ff[e] = cdf[e].F;
7644 }
7645
7646 if (output == "json") {
7647 reg::Json j = reg::Json::object();
7648 j["model"] = file;
7649 j["engine"] = "native-ln";
7650 reg::Json rows = reg::Json::array();
7651 for (std::size_t e = 0; e < model.nentries; ++e) {
7652 reg::Json ob = reg::Json::object();
7653 ob["entry"] = model.names[model.eshift + e + 1];
7654 reg::Json at = reg::Json::array(), af = reg::Json::array();
7655 for (std::size_t i = 0; i < tt[e].size(); ++i) {
7656 at.push_back(tt[e][i]);
7657 af.push_back(ff[e][i]);
7658 }
7659 ob["t"] = at;
7660 ob["F"] = af;
7661 ob["observations"] = static_cast<double>(
7662 e < r.entry_resp_samples.size() ? r.entry_resp_samples[e].size() : 0);
7663 rows.push_back(ob);
7664 }
7665 j["entries"] = rows;
7666 emit_document(dump_document(j, 1));
7667 return 0;
7668 }
7669
7670 std::printf("SolverLDES(native LN engine) getCdfRespT entries=%zu\n", model.nentries);
7671 for (std::size_t e = 0; e < model.nentries; ++e) {
7672 if (tt[e].empty()) {
7673 std::printf("%-40s (no observation)\n", model.names[model.eshift + e + 1].c_str());
7674 continue;
7675 }
7676 // Quartiles plus p95, which is what a measured law is read for.
7677 struct Q {
7678 const std::vector<double>& t;
7679 const std::vector<double>& f;
7680 double operator()(double p) const {
7681 for (std::size_t i = 0; i < f.size(); ++i)
7682 if (f[i] >= p) return t[i];
7683 return t.back();
7684 }
7685 } q = {tt[e], ff[e]};
7686 std::printf("%-40s p25=%12.6g p50=%12.6g p75=%12.6g p95=%12.6g n=%zu\n",
7687 model.names[model.eshift + e + 1].c_str(), q(0.25), q(0.50), q(0.75),
7688 q(0.95), r.entry_resp_samples[e].size());
7689 }
7690 return 0;
7691}
7692
7693/**
7694 * `-s ldes`: the layered model simulated directly, by the IN-PROCESS engine.
7695 *
7696 * IT IS NOT THE SUBPROCESS `-s ldes` OF THE FLAT PATH. That arm hands a
7697 * `model.json` to `common/ldes`, and the engine behind that wire refuses a
7698 * layered document outright ("LDES currently supports Network models only"), so
7699 * there is nothing to forward. This arm calls `ldes_ln_engine_solve` in process
7700 * -- the C++ twin of `Solver_ssj_ln.java` -- which simulates entries,
7701 * activities, task threads and synchronous calls directly instead of
7702 * decomposing the model into layers. So it is not a noisier route to `-s ln`:
7703 * SolverLN's decomposition is an APPROXIMATION and this is a sample path of the
7704 * model itself, which is what makes it the reference the layered solvers are
7705 * checked against.
7706 *
7707 * THE NaN MASK OF THE LAYERED TABLE IS PART OF THE ANSWER, and it belongs to
7708 * the table rather than to whichever solver filled it: a processor has no queue
7709 * length, a task no response time, an entry no residence, and `-s ln` and
7710 * `-s lqns` both print NaN there. This engine MEASURES more than that -- a
7711 * processor's completion rate is sitting in `LnResult::TLN` -- and printing it
7712 * under a column the other two arms leave empty would make one column mean
7713 * different things depending on who filled it; the JAR's `getLNAvgTable` masks
7714 * the same way. Nothing is discarded: the
7715 * unmasked measurements stay on `LnResult` for a programmatic caller, and only
7716 * the shared table is masked, so that it can be diffed row by row.
7717 *
7718 * THE NUMBERS ARE NOT `ln_sanitize`d, for the reason `run_lqns` states below:
7719 * that helper snaps to a tenth and floors at FineTol, which is right for a
7720 * fixed point this port computed and wrong for a measurement it made. A
7721 * simulated utilization of 1e-9 is a rare event that was observed, not a
7722 * negligible residue of an iteration, and the JAR's own layered LDES table
7723 * reports the raw estimate too -- so snapping here would put the two out of
7724 * step on exactly the models a parity row is read on.
7725 */
7726int run_ln_ldes(const std::string& file, const std::string& output, const Knobs& k) {
7727 using namespace line;
7729
7730 // The engine reads THREE settings and no more (`o.samples`, `o.events`,
7731 // `o.seed`); the dispatcher refuses the rest of the --ldes-* family rather
7732 // than letting this function drop them silently.
7734 if (k.samples) o.samples = k.samples;
7735 if (k.seed) o.seed = static_cast<long>(k.seed);
7736
7737 // --repeat is a TIMING loop and stays honest here only because the stream is
7738 // seeded: every replication of one command walks the same sample path, so
7739 // the table is that run's table and `time=` is the only thing that varies.
7740 // This is why -s lqns refuses the flag and this arm does not -- lqsim seeds
7741 // itself, so re-running it would report different numbers under one banner.
7742 const int repeat = k.repeat > 0 ? k.repeat : 1;
7743 double best = 1e300;
7745 for (int rep = 0; rep < repeat; ++rep) {
7746 const auto t0 = std::chrono::steady_clock::now();
7747 r = ldes::ldes_ln_engine_solve(model, o);
7748 const auto t1 = std::chrono::steady_clock::now();
7749 best = std::min(best, std::chrono::duration<double>(t1 - t0).count());
7750 }
7751
7752 // The mask lives beside the data it masks (`ldes::engine::ln_defined`), so
7753 // that the doctest suite can pin it against `LnSolution::defined_*` without
7754 // reaching into this file. Spelling it here instead would put the rule that
7755 // decides what the table MEANS inside a printer.
7756 typedef ldes::engine::LnColumn Col;
7757 const auto def = [&](std::size_t i, Col c) {
7758 return ldes::engine::ln_defined(model, r, i, c);
7759 };
7760
7761 if (output == "json") {
7762 reg::Json j = reg::Json::object();
7763 j["model"] = file;
7764 j["arith"] = "double";
7765 j["solver"] = "ldes";
7766 // WHICH ENGINE ANSWERED, on the same grounds the flat arm's `engine=` is
7767 // not decoration: `-s ldes` names two different simulators depending on
7768 // whether the model is layered, and a number quoted from one must not be
7769 // read as the other's.
7770 j["engine"] = "native-ln";
7771 j["samples"] = o.samples;
7772 j["seed"] = o.seed;
7773 j["simulatedTime"] = r.simulated_time;
7774 j["completions"] = r.completions;
7775 j["seconds"] = best;
7776 reg::Json rows = reg::Json::array();
7777 for (std::size_t i = 1; i <= model.nidx; ++i) {
7778 reg::Json row = reg::Json::object();
7779 row["node"] = model.names[i];
7780 row["type"] = ln_element_kind(model, i);
7781 auto put = [&](const char* key, double v, bool defined) {
7782 if (defined) row[key] = v;
7783 else row[key] = nullptr;
7784 };
7785 put("QLen", r.QLN(i, 0), def(i, Col::QLen));
7786 put("Util", r.ULN(i, 0), def(i, Col::Util));
7787 put("RespT", r.RLN(i, 0), def(i, Col::RespT));
7788 put("ResidT", r.WLN(i, 0), def(i, Col::ResidT));
7789 put("Tput", r.TLN(i, 0), def(i, Col::Tput));
7790 rows.push_back(row);
7791 }
7792 j["rows"] = rows;
7793 emit_document(dump_document(j, 1));
7794 return 0;
7795 }
7796
7797 std::printf("SolverLDES(native LN engine) arith=double type=%s samples=%zu seed=%ld "
7798 "simtime=%.6g completions=%lld time=%.4fs\n",
7799 line::util::method_type("LDES", o.method).c_str(), o.samples, o.seed,
7800 r.simulated_time, r.completions, best);
7801 std::printf("%-62s %-10s %12s %12s %12s %12s %12s\n", "Node", "NodeType", "QLen", "Util",
7802 "RespT", "ResidT", "Tput");
7803 for (std::size_t i = 1; i <= model.nidx; ++i) {
7804 // Six digits, as on the two tables around it, so the three arms diff.
7805 auto fmt = [&](double v, bool defined, char* buf) {
7806 if (!defined) std::snprintf(buf, 24, "%12s", "NaN");
7807 else std::snprintf(buf, 24, "%12.6g", v);
7808 };
7809 char q[24], u[24], rr[24], w[24], t[24];
7810 fmt(r.QLN(i, 0), def(i, Col::QLen), q);
7811 fmt(r.ULN(i, 0), def(i, Col::Util), u);
7812 fmt(r.RLN(i, 0), def(i, Col::RespT), rr);
7813 fmt(r.WLN(i, 0), def(i, Col::ResidT), w);
7814 fmt(r.TLN(i, 0), def(i, Col::Tput), t);
7815 std::printf("%-62s %-10s %s %s %s %s %s\n", model.names[i].c_str(),
7816 ln_element_kind(model, i), q, u, rr, w, t);
7817 }
7818 return 0;
7819}
7820
7821/**
7822 * `-s lqns`: the same layered model, solved by the external binary.
7823 *
7824 * The table has the SAME columns as run_ln's so that the two can be diffed row
7825 * by row, but the numbers are not sanitized the same way: `ln_sanitize` also
7826 * snaps anything at or below FineTol to zero, which is right for a fixed point
7827 * this port computed and wrong for a measurement it did not -- lqns reports no
7828 * residence time and no arrival rate at all, and a zero there would read as a
7829 * computed zero. Those two columns print NaN, and only the snap-to-tenth of the
7830 * reference's getAvgTable is applied.
7831 */
7832template <class T>
7833int run_lqns(const std::string& file, const std::string& output, const Knobs& k) {
7834 using namespace line;
7835 const lqn::LqnModel<T> model =
7837
7839 if (!k.method.empty()) opt.method = k.method;
7840 if (!k.multiserver.empty()) opt.multiserver = k.multiserver;
7841 if (k.samples) opt.samples = static_cast<double>(k.samples);
7842 opt.verbose = k.verbose;
7843 opt.keep = k.keep;
7844 opt.remote = k.remote;
7845 if (!k.remote_url.empty()) opt.remote_url = k.remote_url;
7846
7847 lqns::SolverLQNS<T> solver(model, opt);
7848 const lqns::LqnsSolution<T> sol = solver.get_ensemble_avg();
7849 const lqn::LqnStruct<T>& sn = solver.get_struct();
7851
7852 if (output == "json") {
7853 reg::Json j = reg::Json::object();
7854 j["model"] = file;
7855 j["arith"] = num_traits<T>::name();
7856 j["solver"] = lqns::SolverLQNS<T>::is_stochastic_method(opt.method) ? "lqsim" : "lqns";
7857 j["method"] = opt.method;
7858 j["iterations"] = sol.iterations;
7859 j["seconds"] = solver.runtime();
7860 reg::Json rows = reg::Json::array();
7861 for (std::size_t i = 1; i <= sn.nidx; ++i) {
7862 reg::Json r = reg::Json::object();
7863 r["node"] = names.names[i];
7864 r["type"] = ln_element_kind(names, i);
7865 auto put = [&](const char* key, const std::vector<T>& v, const std::vector<bool>& d) {
7866 if (d[i]) r[key] = lqns::detail::snap_to_tenth(num_traits<T>::to_double(v[i]));
7867 else r[key] = nullptr;
7868 };
7869 put("QLen", sol.QN, sol.defined_Q);
7870 put("Util", sol.UN, sol.defined_U);
7871 put("RespT", sol.RN, sol.defined_R);
7872 put("ResidT", sol.WN, sol.defined_W);
7873 put("Tput", sol.TN, sol.defined_T);
7874 rows.push_back(r);
7875 }
7876 j["rows"] = rows;
7877 emit_document(dump_document(j, 1));
7878 return 0;
7879 }
7880
7881 std::printf("SolverLQNS(%s) arith=%s type=%s iterations=%d time=%.4fs\n",
7883 line::util::method_type("LQNS", opt.method).c_str(), sol.iterations,
7884 solver.runtime());
7885 std::printf("%-62s %-10s %12s %12s %12s %12s %12s\n", "Node", "NodeType", "QLen", "Util",
7886 "RespT", "ResidT", "Tput");
7887 for (std::size_t i = 1; i <= sn.nidx; ++i) {
7888 // Six digits, as on the SolverLN table above and for the same reason.
7889 auto fmt = [&](const std::vector<T>& v, const std::vector<bool>& d, char* buf) {
7890 if (!d[i]) std::snprintf(buf, 24, "%12s", "NaN");
7891 else
7892 std::snprintf(buf, 24, "%12.6g",
7893 lqns::detail::snap_to_tenth(num_traits<T>::to_double(v[i])));
7894 };
7895 char q[24], u[24], rr[24], w[24], t[24];
7896 fmt(sol.QN, sol.defined_Q, q);
7897 fmt(sol.UN, sol.defined_U, u);
7898 fmt(sol.RN, sol.defined_R, rr);
7899 fmt(sol.WN, sol.defined_W, w);
7900 fmt(sol.TN, sol.defined_T, t);
7901 std::printf("%-62s %-10s %s %s %s %s %s\n", names.names[i].c_str(),
7902 ln_element_kind(names, i), q, u, rr, w, t);
7903 }
7904 return 0;
7905}
7906
7907/** The solver method name as the console names it, e.g. "mva" -> "MVA". */
7908std::string upper_tag(const std::string& s) {
7909 std::string out = s;
7910 for (std::size_t i = 0; i < out.size(); ++i)
7911 out[i] = static_cast<char>(std::toupper(static_cast<unsigned char>(out[i])));
7912 return out;
7913}
7914
7915/**
7916 * `-i lqnx|xml|srvn`: the layered path, sibling to solve_model_dispatch.
7917 *
7918 * `-s auto` CONSULTS THE LAYERED ARM of the chooser, which is keyed on the
7919 * metric and on one trait of the model: a cache task promotes the NC layer
7920 * engine, because the cache layer is where NC beats MVA. LQNS leads two of
7921 * those rankings and IS wrapped, so `-s auto` selects it wherever the binary is
7922 * installed -- which makes the choice machine-dependent, exactly as
7923 * `chooseAvgSolverHeur.m` makes it, since LINE ships no LQNS binary. The banner
7924 * always names what answered.
7925 *
7926 * THE METHOD NAMES NAME THE LAYER ENGINE, as the Java CLI's do: `ln.mva` runs
7927 * the layers under SolverMVA and `ln.comom` under SolverNC. The bare `ln` keeps
7928 * MVA layers although the Java CLI reads it as NC, since changing it would
7929 * re-baseline every existing layered result -- so `ln.comom` is the way to ask
7930 * for NC layers. `lqns` is not one of them: it does not solve LAYERS at all, it
7931 * hands the whole model to another program, so it takes the wrapper's own knobs
7932 * and none of SolverLN's.
7933 */
7934int solve_lqn_dispatch(const std::string& arith, const std::string& solver,
7935 const std::string& analysis, const std::string& output,
7936 const std::string& file, const Knobs& k) {
7937 if (file.empty())
7938 throw line::InputError(
7939 "a layered model is read from a file: pass -f <model.lqnx> or -f <model.json> (neither "
7940 "layered reader has a stdin form)");
7941 if (analysis != "avg" && analysis != "tran" && analysis != "sens" && analysis != "cdf")
7942 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
7943 "the layered path ports -a avg (getAvgTable), -a tran (getTranAvg), -a sens "
7944 "(getSensitivityTable) and -a cdf (getCdfRespT); got '" + analysis + "'");
7945 const std::string s = solver.empty() ? "auto" : solver;
7946 if (s != "auto" && s != "ln" && s != "ln.mva" && s != "ln.comom" && s != "lqns" &&
7947 s != "ldes")
7949 "the layered path takes -s ln, ln.mva, ln.comom, ldes, lqns or auto (got '" + s +
7950 "'); a Network solver cannot be applied to a LayeredNetwork directly");
7951
7952 // Solver console: the layered path has its own dispatcher and never
7953 // reaches solve_model_dispatch, so it opens the narrated run here. The
7954 // guard's destructor closes it, on an exception too.
7955 line::util::LineConsole::Run consoleRun(upper_tag(s), "", true);
7956
7957 Knobs kk = k;
7958 // What will actually answer: the token, or what `-s auto` resolves to.
7959 std::string engine = s;
7960 // `-s auto` with no explicit layer engine consults chooseLayeredSolver. An
7961 // explicit --layer-solver is a choice the caller already made, so the
7962 // chooser does not overrule it.
7963 if (s == "auto" && kk.layer_solver.empty()) {
7964 std::string getter = "getAvgTable";
7965 if (analysis == "tran") getter = "getTranAvg";
7966 else if (analysis == "cdf") getter = "getCdfRespT";
7967 else if (analysis == "sens") getter = "getSensitivityTable";
7968 // `iscache` is the one trait the ranking reads, and it costs one parse
7969 // of the .lqnx: the same document the solve parses again below.
7971 bool has_cache_task = false;
7972 for (std::size_t i = 0; i < probe.iscache.size(); ++i)
7973 if (probe.iscache[i]) has_cache_task = true;
7975 line::autosolver::auto_choose_layered_solver(getter, has_cache_task);
7976 const std::string token = line::autosolver::auto_layered_name(lc.solver);
7977 if (token == "lqns") engine = "lqns";
7978 else if (token == "ln.comom") kk.layer_solver = "nc";
7979 else if (token == "ln.fld") kk.layer_solver = "fluid";
7980 else if (token == "ln.mam") kk.layer_solver = "mam";
7981 else kk.layer_solver = "mva";
7982 std::string note;
7983 for (std::size_t i = 0; i < lc.skipped.size(); ++i)
7984 note += std::string(i ? ", " : " (the ranking preferred ") +
7986 if (!lc.skipped.empty()) note += ", which is not available here)";
7987 std::printf("SolverAUTO selected %s%s\n", token.c_str(), note.c_str());
7988 }
7989
7990 // ---- the wrapper, BEFORE the SolverLN knob ladder ---------------------
7991 // It is a wrapper, not a layer engine: --samples is the lqsim run length
7992 // rather than a simulated LAYER's, and --keep and --remote describe a
7993 // child process no SolverLN run has. Asking the ladder below
7994 // about them would answer for the wrong solver.
7995 if (engine == "lqns") {
7996 if (analysis != "avg")
7997 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
7998 "SolverLQNS reports the mean table its binary computes; it has no transient, no "
7999 "sensitivity and no response-time distribution here, so it takes -a avg (got '" +
8000 analysis + "')");
8001 if (!kk.layer_solver.empty())
8002 throw line::InputError(
8003 "--layer-solver names the engine SolverLN runs on each layer; -s lqns solves no "
8004 "layers, it hands the whole model to the lqns binary");
8005 if (output == "layers")
8007 "-o layers dumps the stations and routing SolverLN BUILT from the model; lqns "
8008 "builds its own submodels inside another process and this port never sees them");
8009 if (kk.iter_tol >= 0.0 || kk.iter_max > 0)
8011 "--iter_tol and --iter_max are SolverLN's layer-iteration knobs; lqns runs its own "
8012 "iteration and takes neither (its --iteration-limit is unreliable as of 6.2.27, "
8013 "which is why the reference stopped passing it)");
8014 if (kk.seed)
8016 "--seed sets the stream of a simulator this port drives; lqsim seeds itself and "
8017 "the wrapper passes no seed, exactly as the reference does not");
8018 if (kk.repeat > 1)
8020 "--repeat times a solve by re-running it; re-running lqsim would report a "
8021 "different answer under the same banner");
8022 if (kk.no_interlocking || kk.interlock_knobs_given() || !kk.ln_transient.empty() || !kk.ln_transient_channels.empty() ||
8023 !kk.sens_method.empty() || !kk.sens_scheme.empty() || kk.sens_step > 0.0 || kk.nlp_knobs_given())
8025 "--no-interlocking, --interlock-*, --ln-transient*, --sens-*, --lld, --nlp-*, --warmstart and "
8026 "--mol-* are SolverLN options; -s lqns has none of them");
8027 if (arith != "double")
8028 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
8029 "SolverLQNS reads a result file another program wrote in decimal double "
8030 "precision; there is no higher precision to carry, so rerun with --arith double "
8031 "(got '" + arith + "')");
8032 // The Network-only knobs the SolverLN ladder below refuses are refused
8033 // HERE TOO. This branch returns before that ladder runs, so a knob left
8034 // out of it is silently DROPPED rather than refused -- and which branch
8035 // a bare `.lqnx` path takes depends on whether an lqns binary is
8036 // installed, so the same command line would be refused on one machine
8037 // and quietly ignored on another.
8038 if (kk.has_cutoff())
8040 "--cutoff bounds the open population of a CTMC state space and applies to -s "
8041 "ctmc; the layered path enumerates no states");
8042 if (kk.node)
8044 "--node selects the stateful node a CTMC query is labelled by; the layered path "
8045 "reports every LQN element");
8046 return run_lqns<double>(file, output, kk);
8047 }
8048 if (k.keep || k.verbose || k.remote || !k.remote_url.empty())
8050 "--keep, --verbose, --remote and --remote-url describe the child process "
8051 "of an external solver and apply to -s lqns only");
8052 // ---- the native LN simulator, BEFORE the SolverLN knob ladder ----------
8053 // It solves no LAYERS, so the ladder below asks its questions of a
8054 // decomposition this arm never builds: --iter_tol and --iter_max bound a
8055 // fixed point it does not iterate, --layer-solver names an engine it does
8056 // not run, and --samples and --seed -- which the ladder refuses outright
8057 // unless a layer is simulated -- are precisely this arm's two settings.
8058 if (engine == "ldes") {
8059 if (analysis != "avg" && analysis != "cdf")
8060 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
8061 "the native LN engine measures a sample path: it takes -a avg for the mean table "
8062 "and -a cdf for the per-entry response time distribution, and has no transient "
8063 "and no sensitivity here (got '" + analysis + "')");
8064 if (arith != "double")
8065 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
8066 "the native LN engine accumulates its estimators in double, so there is no higher "
8067 "precision to carry; rerun with --arith double (got '" + arith + "')");
8068 if (output == "layers")
8070 "-o layers dumps the stations and routing SolverLN BUILT from the model; -s ldes "
8071 "simulates the layered semantics directly and builds no submodels");
8072 if (!kk.layer_solver.empty())
8073 throw line::InputError(
8074 "--layer-solver names the engine SolverLN runs on each layer; -s ldes solves no "
8075 "layers, it simulates entries, activities and calls directly");
8076 if (kk.iter_tol >= 0.0 || kk.iter_max > 0 || kk.no_interlocking || kk.interlock_knobs_given())
8078 "--iter_tol, --iter_max, --no-interlocking and --interlock-* are SolverLN's layer-iteration "
8079 "knobs; a simulated sample path converges by run length, which is --samples");
8080 if (!kk.ln_transient.empty() || !kk.ln_transient_channels.empty() ||
8081 !kk.sens_method.empty() || !kk.sens_scheme.empty() || kk.sens_step > 0.0 || kk.nlp_knobs_given())
8083 "--ln-transient*, --sens-*, --lld, --nlp-*, --warmstart and --mol-* are SolverLN options; "
8084 "-s ldes has none of them");
8085 if (!kk.method.empty() && kk.method != "default")
8087 "--method on the layered path names the LN UPDATE (default, moment3, mw.*); "
8088 "-s ldes performs no update, it simulates the model (got '" + kk.method + "')");
8089 // The --ldes-* family is the SUBPROCESS engine's settings. The native LN
8090 // engine reads samples, events and seed and nothing else, so a warmup
8091 // filter or a CI estimator passed here would be DROPPED rather than
8092 // honoured -- and a dropped `--ldes-tranfilter none` reads as a run with
8093 // no warmup removal that in fact removed one.
8094 if (!kk.ldes_tranfilter.empty() || kk.ldes_warmupfrac >= 0.0 ||
8095 !kk.ldes_cimethod.empty() || kk.ldes_cnvgon || kk.ldes_cnvgtol > 0.0 ||
8096 kk.ldes_slotted || kk.ldes_slotlength > 0.0 || kk.ldes_replications > 0 ||
8097 kk.ldes_numthreads > 0 || kk.ldes_maxtime > 0.0 || !kk.ldes_initsol.empty() ||
8098 !kk.ldes_rest_url.empty())
8100 "the --ldes-* flags configure the SUBPROCESS engine that answers -s ldes on a "
8101 "Network (warmup filter, CI estimator, slot lattice, replications, warm-start "
8102 "placement); the native LN engine behind -i lqnx -s ldes reads --samples and "
8103 "--seed only");
8104 // The Network-only knobs the SolverLN ladder refuses below are refused
8105 // HERE TOO: this branch returns before that ladder runs, so a knob left
8106 // out of it would be silently dropped rather than refused.
8107 if (kk.has_cutoff())
8109 "--cutoff bounds the open population of a CTMC state space and applies to -s "
8110 "ctmc; the layered path enumerates no states");
8111 if (kk.node)
8113 "--node selects the stateful node a CTMC query is labelled by; the layered path "
8114 "reports every LQN element");
8115 if (kk.t1 >= 0.0)
8117 "--tspan sets the horizon of a transient analysis; the native LN engine runs to "
8118 "a completion budget, which is --samples");
8119 if (kk.tol >= 0.0)
8121 "--tol is not an LDES option; the run length is set with --samples");
8122 if (analysis == "cdf") return run_ln_ldes_cdf(file, output, kk);
8123 return run_ln_ldes(file, output, kk);
8124 }
8125 // The solver method name and --layer-solver name the same choice, so they may not
8126 // disagree: silently letting one win would report the other in the banner.
8127 if (s == "ln.comom") {
8128 if (!kk.layer_solver.empty() && kk.layer_solver != "nc")
8129 throw line::InputError("-s ln.comom already selects NC layers, but --layer-solver says '" +
8130 kk.layer_solver + "'");
8131 kk.layer_solver = "nc";
8132 } else if (s == "ln.mva") {
8133 if (!kk.layer_solver.empty() && kk.layer_solver != "mva")
8134 throw line::InputError("-s ln.mva already selects MVA layers, but --layer-solver says '" +
8135 kk.layer_solver + "'");
8136 kk.layer_solver = "mva";
8137 }
8138 // --layer-solver is this port's own flag, the C++ spelling of the
8139 // reference's solver FACTORY: `LN(model, @(m) MVA(m))` against
8140 // `LN(model, @(m) Fluid(m))`. They converge to DIFFERENT fixed points.
8141 if (!kk.layer_solver.empty() && kk.layer_solver != "mva" && kk.layer_solver != "nc" &&
8142 kk.layer_solver != "fluid" && kk.layer_solver != "ssa" && kk.layer_solver != "mam" &&
8143 kk.layer_solver != "ctmc" && kk.layer_solver != "ldes" && kk.layer_solver != "jmt")
8144 throw line::InputError("--layer-solver takes mva, nc, fluid, ssa, mam, ctmc, ldes or jmt (got '" +
8145 kk.layer_solver + "')");
8146 // ---- knobs the layered path does not have are refused, not dropped ----
8147 if ((k.samples || k.seed) && kk.layer_solver != "ssa" && kk.layer_solver != "ldes" &&
8148 kk.layer_solver != "jmt")
8150 "--samples and --seed set the run length and the stream of a SIMULATED layer; the "
8151 "layered path draws no random numbers unless --layer-solver ssa, ldes or jmt is in force");
8152 if (k.has_cutoff())
8154 "--cutoff bounds the open population of a CTMC state space and applies to -s ctmc; the "
8155 "layered path enumerates no states");
8156 if (k.t1 >= 0.0 && analysis != "tran")
8158 "--tspan sets the horizon of a transient analysis and applies to the layered path "
8159 "only with -a tran");
8160 if (analysis == "tran" && !(k.t1 >= 0.0))
8161 throw line::InputError(
8162 "-a tran integrates each layer's drift and needs a horizon: pass --tspan <t0>:<t1>");
8163 if (k.node)
8165 "--node selects the stateful node a CTMC query is labelled by; the layered path "
8166 "reports every LQN element");
8167 if (k.tol >= 0.0)
8169 "--tol is not a SolverLN option (LnOptions carries iter_tol and iter_max); "
8170 "use --iter_tol");
8171 // --method names the LN METHOD, which is a different question from the layer
8172 // engine: the srvn* / flat* names choose the LAYERING and the ENCODING
8173 // (SolverLN.listValidMethods, with the aliases ln_requested_method folds),
8174 // `moment3` reports a distribution the default never forms, the two bound
8175 // requests report a bound instead of a fixed point, and `nlp` builds no
8176 // layers at all, rooting the model as one program.
8177 {
8178 static const char* const ln_methods[] = {
8179 "default", "moment3", "mw.upper", "mw.lower", "srvn", "srvn.ph", "srvn.cs",
8180 "flat", "flat.cs", "flat.ph", "srvncs", "ph", "cs", "flatcs", "flatph",
8181 "squashed", "squashed.ph", "nlp", "qdamva", "qd-amva"};
8182 bool known = k.method.empty();
8183 for (const char* m : ln_methods)
8184 if (k.method == m) known = true;
8185 if (!known)
8187 "--method on the layered path takes default, srvn, srvn.ph, srvn.cs, flat, "
8188 "flat.cs, flat.ph, moment3, mw.upper, mw.lower or nlp (alias qdamva, qd-amva) (got '" +
8189 k.method + "'); the per-layer engine is chosen with --layer-solver");
8190 }
8191 if ((k.method == "nlp" || k.method == "qdamva" || k.method == "qd-amva") &&
8192 (analysis != "avg" || output == "layers"))
8194 "--method nlp states the model as one program and builds no layers, so it has no transient, "
8195 "no per-layer sensitivity, no response-time law and no layer to dump; use -a avg");
8196 if ((k.method == "mw.upper" || k.method == "mw.lower") && analysis != "avg")
8198 "--method mw.* reports a throughput and utilization BOUND and solves no layer, so "
8199 "it has no transient, no sensitivity and no response-time law; use -a avg");
8200 if (!k.sens_method.empty() && analysis != "sens")
8201 throw line::UnsupportedError(line::ErrorKind{"Option"}, "--sens-method applies to -a sens");
8202 if (!k.ln_transient.empty() && analysis != "tran")
8203 throw line::UnsupportedError(line::ErrorKind{"Option"}, "--ln-transient applies to -a tran");
8204
8205 if (analysis == "tran") {
8206 if (arith != "double")
8207 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
8208 "the layered transient integrates each layer's drift with LSODA, which is double "
8209 "precision by construction; rerun with --arith double (got '" + arith + "')");
8210 return run_ln_tran<double>(file, output, kk);
8211 }
8212 if (analysis == "cdf") {
8213 if (arith != "double")
8214 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
8215 "-a cdf fits an APH to a fluid passage time, integrated by LSODA in double "
8216 "precision; rerun with --arith double (got '" + arith + "')");
8217 return run_ln_cdf<double>(file, output, kk);
8218 }
8219 if (analysis == "sens") {
8220 if (arith == "double") return run_ln_sens<double>(file, output, kk);
8221 if (arith == "exact") return run_ln_sens<line::Rational>(file, output, kk);
8222 if (arith == "real:16") return run_ln_sens<line::Real<16> >(file, output, kk);
8223 if (arith == "real" || arith == "real:32")
8224 return run_ln_sens<line::Real<32> >(file, output, kk);
8225 if (arith == "real:64") return run_ln_sens<line::Real<64> >(file, output, kk);
8226 if (arith == "real:128") return run_ln_sens<line::Real<128> >(file, output, kk);
8227 if (arith == "real:256") return run_ln_sens<line::Real<256> >(file, output, kk);
8228 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
8229 }
8230
8231 if (arith == "double") return run_ln<double>(file, output, kk);
8232 if (arith == "exact") return run_ln<line::Rational>(file, output, kk);
8233 // precision-ladder rationale (real:16 rung): see _kb/14-cpp-multiprecision.md
8234 if (arith == "real:16") return run_ln<line::Real<16> >(file, output, kk);
8235 if (arith == "real" || arith == "real:32") return run_ln<line::Real<32> >(file, output, kk);
8236 if (arith == "real:64") return run_ln<line::Real<64> >(file, output, kk);
8237 if (arith == "real:128") return run_ln<line::Real<128> >(file, output, kk);
8238 if (arith == "real:256") return run_ln<line::Real<256> >(file, output, kk);
8239 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
8240}
8241
8242// Shared with the example corpus, which prints the same node tables.
8244
8245/**
8246 * The LDES result document mapped onto the station AvgResult, BY NAME.
8247 *
8248 * The engine reports its own station and class order, and pairing the two off
8249 * positionally would put one station's numbers on another's row; `-a avg`
8250 * already matches by name for exactly that reason and this is the same match.
8251 * `WN` is recomputed rather than taken, for the reason the `-a avg` arm states:
8252 * the engine counts one visit per station, so its residence time is the response
8253 * time whenever a visit ratio is not 1.
8254 *
8255 * REGION ROWS RIDE PAST THE STATIONS, in the (M+F) layout `jmt_map_measures`
8256 * already uses, so a caller reads both engines' finite-capacity rows the same
8257 * way.
8258 */
8259inline line::mva::AvgResult<double> avg_result_from_ldes(
8261 const std::size_t M = sn.nstations, K = sn.nclasses;
8262 const std::size_t F = a.QNfcr.empty() ? 0 : a.QNfcr.rows();
8264 line::Matrix<double>* dst[6] = {&r.QN, &r.UN, &r.RN, &r.TN, &r.AN, &r.WN};
8265 const line::Matrix<double>* src[6] = {&a.QN, &a.UN, &a.RN, &a.TN, &a.AN, &a.WN};
8266 const line::Matrix<double>* fcr[6] = {&a.QNfcr, &a.UNfcr, &a.RNfcr,
8267 &a.TNfcr, &a.ANfcr, &a.WNfcr};
8268 std::vector<std::size_t> st_of(a.station_names.size(), 0); // 1-based, 0 = unmatched
8269 for (std::size_t i = 0; i < a.station_names.size(); ++i)
8270 for (std::size_t j = 0; j < M; ++j)
8271 if (sn.stations[j].name == a.station_names[i]) { st_of[i] = j + 1; break; }
8272 std::vector<std::size_t> cl_of(a.class_names.size(), 0);
8273 for (std::size_t c = 0; c < a.class_names.size(); ++c)
8274 for (std::size_t j = 0; j < K; ++j)
8275 if (sn.classes[j].name == a.class_names[c]) { cl_of[c] = j + 1; break; }
8276 for (int m = 0; m < 6; ++m) {
8277 *dst[m] = line::Matrix<double>(M + F, K, 0.0);
8278 for (std::size_t i = 0; i < a.station_names.size(); ++i)
8279 for (std::size_t c = 0; c < a.class_names.size(); ++c)
8280 if (st_of[i] && cl_of[c])
8281 (*dst[m])(st_of[i] - 1, cl_of[c] - 1) = ldes_at(*src[m], i, c);
8282 for (std::size_t f = 0; f < F; ++f)
8283 for (std::size_t c = 0; c < a.class_names.size(); ++c)
8284 if (cl_of[c]) (*dst[m])(M + f, cl_of[c] - 1) = ldes_at(*fcr[m], f, c);
8285 }
8286 line::Matrix<double> RNs(M, K, 0.0);
8287 for (std::size_t i = 0; i < M; ++i)
8288 for (std::size_t c = 0; c < K; ++c) RNs(i, c) = r.RN(i, c);
8290 for (std::size_t i = 0; i < M; ++i)
8291 for (std::size_t c = 0; c < K; ++c) r.WN(i, c) = WNs(i, c);
8292 for (std::size_t c = 0; c < K; ++c) {
8293 r.CN.push_back(ldes_at(a.CN, 0, c));
8294 r.XN.push_back(ldes_at(a.XN, 0, c));
8295 }
8296 r.method = a.method;
8297 r.actualmethod = a.method;
8298 return r;
8299}
8300
8301/**
8302 * Solve for the station AvgResult with the named engine.
8303 *
8304 * SHARED BY EVERY @@NetworkSolver TABLE THAT IS NOT THE AvgTable -- `-a node`,
8305 * `-a sys`, `-a chain`, `-a nodechain` -- because each of them is a VIEW of the
8306 * same solved result and differs only in how it is indexed and aggregated.
8307 * Giving each arm its own engine ladder would let the five drift apart in which
8308 * knobs they honour, which is exactly the silent divergence the Knobs struct
8309 * exists to prevent one layer up.
8310 *
8311 * SSA and Fluid reach it through `avg_result_from_sim`, and only under
8312 * `--arith double`: both integrate transcendental quantities (exponential
8313 * clocks, an LSODA drift), so the dispatcher refuses the other backends by name
8314 * before the ladder is entered, exactly as their own `-a avg` arms do.
8315 *
8316 * THE TWO WRAPPERS ARE HERE FOR THE SAME REASON THE TWO SIMULATORS ARE.
8317 * `getAvgNodeTable` is @@NetworkSolver's and is a VIEW of whatever AvgResult a
8318 * solver returned; JMT and LDES both return one (`JmtResult::avg`, the LDES
8319 * result document), so refusing them the four views said "no C++ simulation
8320 * engine" about engines this port drives. `file` is what LDES needs and the
8321 * others ignore: it hands the model DOCUMENT to an external process rather
8322 * than reading the struct.
8323 */
8324template <class T>
8325line::mva::AvgResult<T> run_avg_engine(const line::qn::NetworkStruct<T>& sn, const Knobs& k,
8326 const std::string& s, std::string& banner,
8327 std::string* suffix = nullptr,
8328 const std::string* file = nullptr) {
8330 if (s == "jmt" || s == "ldes") {
8331 // COMPILE-TIME, as for the two simulators: both wrappers report in
8332 // double and the dispatcher has already refused every other arithmetic
8333 // by name, so the discarded branch is unreachable rather than narrowed.
8334 if constexpr (std::is_same_v<T, double>) {
8335 if (s == "jmt") {
8337 if (!k.method.empty() && k.method != "default") o.method = k.method;
8338 if (k.samples > 0) o.samples = static_cast<double>(k.samples);
8339 if (k.seed != 0) o.seed = static_cast<long>(k.seed);
8340 o.keep = k.keep;
8341 if (k.t1 >= 0.0) o.max_simulated_time = k.t1;
8342 o.verbose = k.verbose;
8344 r = a.avg;
8345 banner = "SolverJMT";
8346 // THE SEED IS PART OF THE ANSWER, as it is for SSA: two runs of
8347 // a simulation are the same measurement only if both state it.
8348 if (suffix) {
8349 char buf[128];
8350 std::snprintf(buf, sizeof(buf), " samples=%g seed=%ld", o.samples, o.seed);
8351 *suffix = buf;
8352 }
8353 } else {
8354 const line::ldes::LdesOptions o = ldes_options(k);
8355 const line::ldes::LdesResult a =
8356 ldes_run(file ? *file : std::string(), o, std::vector<std::string>());
8357 r = avg_result_from_ldes(sn, a);
8358 r.fj = line::ldes::ldes_fj_metrics(sn, a); // the engine's "forkJoin" block, for -a fj
8359 banner = "SolverLDES";
8360 if (suffix) {
8361 char buf[160];
8362 std::snprintf(buf, sizeof(buf), " engine=%s samples=%zu seed=%ld",
8363 a.engine.empty() ? "?" : a.engine.c_str(), o.samples, o.seed);
8364 *suffix = buf;
8365 }
8366 }
8367 } else {
8368 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"}, "-s " + s + " runs under --arith double only");
8369 }
8370 } else if (s == "ssa" || s == "fluid") {
8371 // COMPILE-TIME, not just run-time: both runners static_assert on
8372 // transcendental arithmetic inside (an exponential clock, a square root
8373 // in the Cox refit), so instantiating them at Rational is a hard error
8374 // and not a refusal. The dispatcher has already rejected every arith
8375 // but double by name, so the discarded branch is unreachable rather
8376 // than silently narrowed.
8377 if constexpr (std::is_same_v<T, double>) {
8378 if (s == "ssa") {
8380 if (!k.method.empty() && k.method != "default") opt.method = k.method;
8381 if (k.samples) opt.samples = k.samples;
8382 if (k.seed) opt.seed = k.seed;
8383 if (k.cutoff >= 0.0) opt.cutoff = k.cutoff;
8384 if (k.timestep > 0.0) opt.timestep = k.timestep; // the fixed step of -m tstep
8385 // The cache write-back rides beside the metric table, for the
8386 // reason `node_metrics` states: the realized hit and miss shares
8387 // are what the simulation MEASURED, and without them the node
8388 // table falls back to the split `link()` offered.
8389 std::vector<line::ssa::SsaCacheRatio> cache;
8391 // ResidT and ArvR are derived from the VISITS, and a cache's
8392 // split is routing, so both are taken on the struct carrying the
8393 // measured hit/miss shares rather than on `link()`'s even offer.
8394 r = avg_result_from_sim<T>(line::ssa::sn_with_ssa_cache_split<T>(sn, cache),
8395 a.QN, a.UN, a.RN, a.TN, a.CN, a.XN, a.method);
8397 // THE SEED AND THE SAMPLE COUNT ARE PART OF THE ANSWER, not of
8398 // the invocation, so they ride in the banner here as they do in
8399 // `-a avg`: two runs of a simulation are the same measurement
8400 // only if both are stated, and a parity row that quotes one of
8401 // these tables has to carry them with it.
8402 banner = "SolverSSA";
8403 // APPENDED, NOT PREFIXED. Every consumer recognises a banner by
8404 // `Solver<name> arith=`, so a fact wedged between the two makes
8405 // the table belong to no solver at all -- which is how the
8406 // parity harness lost the whole SSA section.
8407 if (suffix) {
8408 char buf[128];
8409 std::snprintf(buf, sizeof(buf), " samples=%zu seed=%lu time=%.6g", a.samples,
8410 static_cast<unsigned long>(opt.seed), a.simulated_time);
8411 *suffix = buf;
8412 }
8413 } else {
8414 const line::fluid::FluidOptions opt = fluid_options(k);
8415 // THE map_env FALLBACK IS ASKED FOR HERE RATHER THAN THROUGH
8416 // `run_avg`: the fluid runner returns a `FluidSolution` and not
8417 // an `AvgResult`, so this arm cannot pass itself as the `Run`
8418 // callable. It asks `needs_map_env` the same question with the
8419 // same config instead of carrying a second copy of the decision.
8420 const line::solvers::MapEnvConfig mecfg = map_env_config(k);
8422 mecfg)
8423 .needed) {
8424 r = line::solvers::map_env_approx<T>(sn, "SolverFluid", mecfg,
8426 opt.method);
8427 banner = "SolverFluid";
8428 if (suffix) *suffix = " map_env=" + r.actualmethod;
8429 return r;
8430 }
8431 // The cache decomposition renormalizes the self-switch at the
8432 // converged split; `-a node` needs that struct or it reports the
8433 // 1/2-1/2 `link()` left behind (see `node_metrics`).
8435 // The null must be typed: a bare `nullptr` is `std::nullptr_t`
8436 // and blocks deduction of T from the fourth argument.
8437 // THE SPLIT ITSELF IS TAKEN TOO, not only the struct it
8438 // renormalized: `node_metrics` prefers the stated split over the
8439 // visit ratios, and `-a cache` is built from nothing else.
8442 sn, opt, static_cast<line::qn::NetworkStruct<T>*>(nullptr), &refreshed, &cache);
8443 // Non-empty only where the cache branch ran, which is the same
8444 // test `node_metrics` makes on the pointer. IT IS ALSO THE
8445 // STRUCT THE ARRIVAL RATE IS READ FROM: that column is derived
8446 // from the class-expanded routing, and the base struct still
8447 // holds the 1/2-1/2 self-switch `link()` offered, so deriving it
8448 // there reports 0.5/0.5 where cache_replc_routing's Delay1 sees
8449 // 0.4/0.6. Every other column is indexed by station and is the
8450 // same in both structs.
8451 const bool has_ref = !refreshed.nodes.empty();
8452 r = avg_result_from_sim<T>(has_ref ? refreshed : sn, a.QN, a.UN, a.RN, a.TN, a.CN,
8453 a.XN, a.method);
8454 if (has_ref) r.refreshed_struct.reset(new line::qn::NetworkStruct<T>(refreshed));
8455 r.cache = cache;
8456 r.fj = a.fj; // the fork-join fixed point's section metrics, for -a fj
8457 r.iter = static_cast<int>(a.iters);
8458 banner = "SolverFluid";
8459 if (suffix) {
8460 char buf[64];
8461 std::snprintf(buf, sizeof(buf), " iters=%zu", a.iters);
8462 *suffix = buf;
8463 }
8464 }
8465 } else {
8466 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"}, "-s " + s + " runs under --arith double only");
8467 }
8468 } else if (s == "nc") {
8470 if (!k.method.empty() && k.method != "default") opt.method = k.method;
8471 if (k.tol >= 0.0) opt.tol = k.tol;
8472 if (k.iter_tol >= 0.0) opt.iter_tol = k.iter_tol;
8473 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
8474 if (!k.fork_join.empty()) opt.fork_join = k.fork_join;
8475 // The map_env fallback, wired here for the reason this engine exists at
8476 // all: these views ARE the `getAvg` funnel of this CLI, so a view that
8477 // refused a MAP model the `-a avg` arm accepts would answer a different
8478 // model for the same command line.
8479 // COMPILE-TIME because the driver is double-only: `map_env_approx`
8480 // refuses `T != double` at run time, but its body still has to compile,
8481 // and an `EnvStageAvgFn<double>` does not convert to an
8482 // `EnvStageAvgFn<Rational>`.
8483 if constexpr (std::is_same_v<T, double>) {
8485 sn, "SolverNC", line::qn::nc_feature_set(opt.method), map_env_config(k),
8488 },
8490 } else {
8492 }
8493 banner = "SolverNC";
8494 } else if (s == "mam") {
8495 // The same builder as every other `-s mam` entry point, so --timescale,
8496 // --slotlength and the fork-join knobs reach -a avg too.
8497 const line::mam::MamOptions opt = mam_options(k);
8499 banner = "SolverMAM";
8500 } else if (s == "ag") {
8502 apply_ag_knobs(k, opt);
8504 banner = "SolverAG";
8505 } else if (s == "ba") {
8507 if (!k.method.empty() && k.method != "default") opt.method = k.method;
8509 banner = "SolverBA";
8510 } else if (s == "ctmc") {
8512 if (!k.method.empty()) opt.method = k.method;
8513 if (k.cutoff >= 0.0) opt.cutoff = k.cutoff;
8514 opt.cutoff_mat = k.cutoff_mat;
8515 opt.force = k.force;
8516 if (!k.nonmkv.empty()) opt.nonmkv = k.nonmkv;
8519 banner = "SolverCTMC";
8520 } else {
8522 if (!k.method.empty() && k.method != "default") opt.method = k.method;
8523 if (k.tol >= 0.0) opt.tol = k.tol;
8524 if (k.iter_tol >= 0.0) opt.iter_tol = k.iter_tol;
8525 if (k.iter_max >= 0) opt.iter_max = k.iter_max;
8526 // `-a avg` has honoured --multiserver since the flag existed; these
8527 // views are the SAME solve indexed differently, so ignoring it here made
8528 // `-a chain` answer a different model than `-a avg` for the same command
8529 // line. Measured on cqn_repairmen_multi, where softmin and the default
8530 // rule differ by 39% on the Delay queue length.
8531 if (!k.multiserver.empty()) opt.multiserver = k.multiserver;
8532 if (!k.fork_join.empty()) opt.fork_join = k.fork_join;
8533 line::Matrix<T> init;
8534 // Same funnel, same compile-time guard as the nc arm above.
8535 if constexpr (std::is_same_v<T, double>) {
8537 sn, "SolverMVA",
8539 map_env_config(k),
8540 [&opt, &init](const line::qn::NetworkStruct<double>& m) {
8541 return line::mva::solver_mva_run_analyzer(m, opt, init);
8542 },
8544 } else {
8546 }
8547 banner = "SolverMVA";
8548 }
8549 return r;
8550}
8551
8552/* `NodeMetrics` / `node_metrics` MOVED to line/solvers/solver_node_tables.h;
8553 * see the note above `run_avg_engine`. Used unchanged by both arms below. */
8556
8557/**
8558 * `-a node`: `@@NetworkSolver/getAvgNodeTable`, the means per NODE.
8559 *
8560 * A DIFFERENT INDEX SPACE FROM `-a avg`, not a relabelling of it. The AvgTable
8561 * is indexed by STATION, so a ClassSwitch, a Router, a Fork, a Join and a Sink
8562 * are absent from it entirely -- they hold no jobs, so they have no row -- yet
8563 * jobs flow through them and the flow is what a caller sizing a link or an
8564 * interconnect needs. This table has one row per node and reports the arrival
8565 * rate and the throughput at every one of them, which is the only place those
8566 * two numbers exist for a non-station node.
8567 *
8568 * QLen, Util, RespT and ResidT ARE the station numbers, scattered to the node
8569 * indices and left at zero elsewhere; that is the reference's own construction
8570 * and not a gap, because a node that is not a station holds no jobs and serves
8571 * nothing. ArvR and Tput are the two the reference recomputes, through
8572 * `sn_get_node_arvr_from_tput` and `sn_get_node_tput_from_tput`.
8573 *
8574 * THE F REGION PSEUDO-NODE ROWS OF THE REFERENCE ARE NOT EMITTED. MATLAB
8575 * appends one row per finite-capacity region, filled from `result.Avg` rows
8576 * M+1..M+F; the C++ `AvgResult` carries no per-region queue length or
8577 * utilization, so those rows have no data source here and are omitted rather
8578 * than fabricated as zeros, which would read as an empty region.
8579 */
8580template <class T>
8581int solve_model_node(const std::string& file, const Knobs& k, const std::string& s) {
8582 line::qn::Network<T> net = read_model<T>(file);
8584 std::string banner, suffix;
8585 const line::mva::AvgResult<T> r = run_avg_engine<T>(sn, k, s, banner, &suffix, &file);
8586
8587 const std::size_t I = sn.nodes.size(), R = sn.nclasses;
8588 const NodeMetrics<T> nm = node_metrics<T>(sn, r);
8589 const line::Matrix<T>&QNn = nm.QN, &UNn = nm.UN, &RNn = nm.RN, &WNn = nm.WN, &ANn = nm.AN,
8590 &TNn = nm.TN;
8591
8592 const std::vector<bool> hidden = line::solvers::node_table_hidden_classes<T>(sn);
8593 auto d = [](const T& v) { return line::num_traits<T>::to_double(v); };
8594 // A FINITE CAPACITY REGION IS NOT A NODE, and the reference still prints it
8595 // in this table: `getAvgNodeTable` appends one row per region past the
8596 // nodes, because a WAITQ region holds jobs that are in no station's QLen and
8597 // the model's population only balances once they are read. The rows ride
8598 // past the stations in the returned AvgResult -- the (M+F) layout both
8599 // wrappers report -- and no analytical solver fills them, so this block is
8600 // empty for every engine that does not measure a region.
8601 //
8602 // Util AND ArvR ARE NaN, NOT ZERO. A region has no server to be busy and no
8603 // arrival process of its own; the reference reports both as missing, and a
8604 // zero there would be a number the run never measured.
8605 const std::size_t F =
8606 r.QN.rows() > sn.nstations ? r.QN.rows() - sn.nstations : static_cast<std::size_t>(0);
8607 const double region_nan = std::numeric_limits<double>::quiet_NaN();
8608 auto region_name = [&](std::size_t f) {
8609 return (f < sn.regions.size() && !sn.regions[f].name.empty())
8610 ? sn.regions[f].name
8611 : "FCR" + std::to_string(f + 1);
8612 };
8613 // The reference's own filter, the region twin of the all-zero row test: a
8614 // region no job ever entered is absent rather than a row of zeros.
8615 auto region_empty = [&](std::size_t f, std::size_t c) {
8616 return !(d(r.QN(sn.nstations + f, c)) > 0.0 || d(r.RN(sn.nstations + f, c)) > 0.0 ||
8617 d(r.TN(sn.nstations + f, c)) > 0.0);
8618 };
8619 if (g_json_output) {
8620 // The banner under `-o json` too, for print_chain_table's reason: the
8621 // envelope names the arithmetic and the method but never the SOLVER.
8622 std::printf("%s arith=%s method=%s nodes=%zu%s\n", banner.c_str(), line::num_traits<T>::name(),
8623 r.actualmethod.c_str(), I, suffix.c_str());
8624 line::reg::Json p = line::reg::Json::object();
8625 p["type"] = "AvgNodeTable";
8626 p["indexBase"] = 0;
8627 for (const char* key : {"Node", "JobClass", "QLen", "Util", "RespT", "ResidT", "ArvR",
8628 "Tput"})
8629 p[key] = line::reg::Json::array();
8630 for (std::size_t i = 0; i < I; ++i)
8631 for (std::size_t c = 0; c < R; ++c) {
8632 if (hidden[c]) continue; // auxiliary retrieval class, see node_table_hidden_classes
8633 // The reference's own row filter: a node a class never reaches
8634 // is absent, not a row of zeros, exactly as in the AvgTable.
8635 if (d(QNn(i, c)) == 0.0 && d(UNn(i, c)) == 0.0 && d(RNn(i, c)) == 0.0 &&
8636 d(WNn(i, c)) == 0.0 && d(ANn(i, c)) == 0.0 && d(TNn(i, c)) == 0.0)
8637 continue;
8638 p["Node"].push_back(sn.nodes[i].name);
8639 p["JobClass"].push_back(sn.classes[c].name);
8640 p["QLen"].push_back(d(QNn(i, c)));
8641 p["Util"].push_back(d(UNn(i, c)));
8642 p["RespT"].push_back(d(RNn(i, c)));
8643 p["ResidT"].push_back(d(WNn(i, c)));
8644 p["ArvR"].push_back(d(ANn(i, c)));
8645 p["Tput"].push_back(d(TNn(i, c)));
8646 }
8647 for (std::size_t f = 0; f < F; ++f)
8648 for (std::size_t c = 0; c < R; ++c) {
8649 if (region_empty(f, c)) continue;
8650 p["Node"].push_back(region_name(f));
8651 p["JobClass"].push_back(sn.classes[c].name);
8652 p["QLen"].push_back(d(r.QN(sn.nstations + f, c)));
8653 p["Util"].push_back(region_nan);
8654 p["RespT"].push_back(d(r.RN(sn.nstations + f, c)));
8655 p["ResidT"].push_back(d(r.WN(sn.nstations + f, c)));
8656 p["ArvR"].push_back(region_nan);
8657 p["Tput"].push_back(d(r.TN(sn.nstations + f, c)));
8658 }
8659 emit_analysis<T>("node", p, r.actualmethod);
8660 return 0;
8661 }
8662 std::printf("%s arith=%s method=%s nodes=%zu%s\n", banner.c_str(), line::num_traits<T>::name(),
8663 r.actualmethod.c_str(), I, suffix.c_str());
8664 std::printf("%-16s %-14s %12s %12s %12s %12s %12s %12s\n", "Node", "JobClass", "QLen", "Util",
8665 "RespT", "ResidT", "ArvR", "Tput");
8666 for (std::size_t i = 0; i < I; ++i)
8667 for (std::size_t c = 0; c < R; ++c) {
8668 if (hidden[c]) continue; // auxiliary retrieval class, see node_table_hidden_classes
8669 if (d(QNn(i, c)) == 0.0 && d(UNn(i, c)) == 0.0 && d(RNn(i, c)) == 0.0 &&
8670 d(WNn(i, c)) == 0.0 && d(ANn(i, c)) == 0.0 && d(TNn(i, c)) == 0.0)
8671 continue;
8672 std::printf("%-16s %-14s %12.6g %12.6g %12.6g %12.6g %12.6g %12.6g\n",
8673 sn.nodes[i].name.c_str(), sn.classes[c].name.c_str(), d(QNn(i, c)),
8674 d(UNn(i, c)), d(RNn(i, c)), d(WNn(i, c)), d(ANn(i, c)), d(TNn(i, c)));
8675 }
8676 for (std::size_t f = 0; f < F; ++f)
8677 for (std::size_t c = 0; c < R; ++c) {
8678 if (region_empty(f, c)) continue;
8679 std::printf("%-16s %-14s %12.6g %12.6g %12.6g %12.6g %12.6g %12.6g\n",
8680 region_name(f).c_str(), sn.classes[c].name.c_str(),
8681 d(r.QN(sn.nstations + f, c)), region_nan, d(r.RN(sn.nstations + f, c)),
8682 d(r.WN(sn.nstations + f, c)), region_nan, d(r.TN(sn.nstations + f, c)));
8683 }
8684 return 0;
8685}
8686
8687/**
8688 * `-a cache`: `@@NetworkSolver/getAvgCacheTable`, per Cache node and READ class.
8689 *
8690 * ONE TOTAL ROW PER (node, read class), plus one row per cache list where the
8691 * solver reported a per-list breakdown and the cache has more than one list.
8692 * The `List` column tells them apart: 0 is the total over every list, l is
8693 * list l. Only the total row carries the delayed-hit and miss columns, because
8694 * a miss is a property of the cache and not of any one list.
8695 *
8696 * THE ArvR COLUMN IS THE READ-CLASS ARRIVAL RATE `arvr` (= HitRate +
8697 * DHitRate + MissRate) on the total row as on a list row. That is the
8698 * reference's choice and it is Little-consistent with ResidT: the residence
8699 * time reported beside it is the expected latency averaged over ALL read
8700 * requests (paper eq. latency tot, a hit waiting zero), so ArvR * ResidT is the
8701 * mean number of requests in the retrieval system, sum_i (phi_i + d_i).
8702 *
8703 * A READ CLASS IS ONE WITH A HIT CLASS DEFINED. A class that never reads the
8704 * cache has no row at all rather than a row of zeros, which is the same rule
8705 * the AvgTable applies to a class that never visits a station.
8706 */
8707template <class T>
8708int solve_model_cache(const std::string& file, const Knobs& k, const std::string& s) {
8709 line::qn::Network<T> net = read_model<T>(file);
8711 std::string banner, suffix;
8712 const line::mva::AvgResult<T> r = run_avg_engine<T>(sn, k, s, banner, &suffix, &file);
8713 if (r.cache.empty())
8714 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
8715 "-a cache reports the per-Cache hit and miss table and this model has no Cache node, "
8716 "or the solver that ran analyzes none; SolverNC's cache branches are what fill it");
8717
8718 // The read-class arrival rate of an OPEN class is its SOURCE throughput: every read request enters the cache, so
8719 // this holds across solvers, including the simulators where a delayed hit is not folded into the hit throughput.
8720 // A CLOSED read class has no source row: its requests are the cache's departures in the hit and miss classes.
8721 const NodeMetrics<T> nm = node_metrics<T>(sn, r);
8722 std::size_t srcnode = 0;
8723 for (std::size_t i = 0; i < sn.nodes.size(); ++i)
8724 if (sn.nodes[i].nodetype == line::lang::NodeType::Source) { srcnode = i + 1; break; }
8725
8726 struct Row {
8727 std::string node, cls;
8728 double item, list, listcap, items, hitp, dhitp, missp, hitr, dhitr, missr, arvr, residt, cost;
8729 };
8730 std::vector<Row> rows;
8731 const double dnan = std::numeric_limits<double>::quiet_NaN();
8732
8733 for (std::size_t c = 0; c < r.cache.caches.size(); ++c) {
8734 const line::solvers::CacheNodeMetrics<T>& m = r.cache.caches[c];
8735 const typename std::map<std::size_t, line::qn::CacheParam<T> >::const_iterator it =
8736 sn.nodeparam.find(m.node);
8737 if (it == sn.nodeparam.end()) continue;
8738 const std::vector<std::size_t>& hitclass = it->second.hitclass;
8739 const std::size_t h = m.itemcap.size();
8740 double totcap = 0.0;
8741 for (std::size_t l = 0; l < h; ++l) totcap += m.itemcap[l];
8742 double totcost = dnan;
8743 if (!m.listcost.empty()) {
8744 totcost = 0.0;
8745 for (std::size_t l = 0; l < m.listcost.size(); ++l)
8747 }
8748
8749 for (std::size_t cl = 0; cl < sn.nclasses; ++cl) {
8750 if (cl >= hitclass.size() || hitclass[cl] == 0) continue; // not a read class
8751 double ph = cache_at(m.hitprob, cl), pm = cache_at(m.missprob, cl),
8752 pd = cache_at(m.delayedprob, cl);
8753 if (std::isnan(ph) && std::isnan(pm) && std::isnan(pd)) continue;
8754 if (std::isnan(ph)) ph = 0.0;
8755 if (std::isnan(pm)) pm = 0.0;
8756 if (std::isnan(pd)) pd = 0.0;
8757 double arvr = 0.0;
8758 if (!std::isfinite(sn.classes[cl].population)) {
8759 if (srcnode) arvr = line::num_traits<T>::to_double(nm.TN(srcnode - 1, cl));
8760 } else {
8761 arvr = line::num_traits<T>::to_double(nm.TN(m.node - 1, hitclass[cl] - 1));
8762 if (cl < it->second.missclass.size() && it->second.missclass[cl] > 0)
8763 arvr += line::num_traits<T>::to_double(nm.TN(m.node - 1, it->second.missclass[cl] - 1));
8764 }
8765 const double lat = cache_at(m.latency, cl);
8766
8767 Row t;
8768 t.node = sn.nodes[m.node - 1].name;
8769 t.cls = sn.classes[cl].name;
8770 // item a per-item read class requests (setItemReadClasses), 0 for an ordinary read class
8771 t.item = cl < it->second.classitem.size() ? static_cast<double>(it->second.classitem[cl]) : 0.0;
8772 t.list = 0;
8773 t.listcap = totcap;
8774 t.items = static_cast<double>(m.nitems);
8775 t.hitp = ph;
8776 t.dhitp = pd;
8777 t.missp = pm;
8778 t.hitr = arvr * ph;
8779 t.dhitr = arvr * pd;
8780 t.missr = arvr * pm;
8781 t.arvr = arvr;
8782 t.residt = lat;
8783 t.cost = totcost;
8784 rows.push_back(t);
8785
8786 // Per-list rows, only where a genuine multi-list breakdown exists.
8787 bool any = false;
8788 if (h > 1 && cl < m.hitproblist.rows())
8789 for (std::size_t l = 0; l < m.hitproblist.cols(); ++l)
8790 if (!std::isnan(line::num_traits<T>::to_double(m.hitproblist(cl, l))))
8791 any = true;
8792 if (!any) continue;
8793 for (std::size_t l = 0; l < h; ++l) {
8794 double phl = l < m.hitproblist.cols()
8796 : dnan;
8797 if (std::isnan(phl)) phl = 0.0;
8798 Row u;
8799 u.node = t.node;
8800 u.cls = t.cls;
8801 u.item = t.item;
8802 u.list = static_cast<double>(l + 1);
8803 u.listcap = m.itemcap[l];
8804 u.items = t.items;
8805 u.hitp = phl;
8806 u.dhitp = dnan;
8807 u.missp = dnan;
8808 u.hitr = arvr * phl;
8809 u.dhitr = dnan;
8810 u.missr = dnan;
8811 u.arvr = arvr;
8812 u.residt = dnan;
8813 u.cost = l < m.listcost.size()
8815 : dnan;
8816 rows.push_back(u);
8817 }
8818 }
8819 }
8820
8821 if (g_json_output) {
8822 line::reg::Json p = line::reg::Json::object();
8823 p["type"] = "AvgCacheTable";
8824 p["indexBase"] = 0;
8825 for (const char* key : {"Node", "JobClass", "Item", "List", "ListCap", "Items", "HitProb",
8826 "DelayedHitProb", "MissProb", "HitRate", "DelayedHitRate",
8827 "MissRate", "ArvR", "ResidT", "ListCost"})
8828 p[key] = line::reg::Json::array();
8829 for (std::size_t i = 0; i < rows.size(); ++i) {
8830 p["Node"].push_back(rows[i].node);
8831 p["JobClass"].push_back(rows[i].cls);
8832 p["Item"].push_back(rows[i].item);
8833 p["List"].push_back(rows[i].list);
8834 p["ListCap"].push_back(rows[i].listcap);
8835 p["Items"].push_back(rows[i].items);
8836 p["HitProb"].push_back(rows[i].hitp);
8837 p["DelayedHitProb"].push_back(rows[i].dhitp);
8838 p["MissProb"].push_back(rows[i].missp);
8839 p["HitRate"].push_back(rows[i].hitr);
8840 p["DelayedHitRate"].push_back(rows[i].dhitr);
8841 p["MissRate"].push_back(rows[i].missr);
8842 p["ArvR"].push_back(rows[i].arvr);
8843 p["ResidT"].push_back(rows[i].residt);
8844 p["ListCost"].push_back(rows[i].cost);
8845 }
8846 emit_analysis<T>("cache", p, r.actualmethod);
8847 return 0;
8848 }
8849 std::printf("%s arith=%s method=%s caches=%zu\n", banner.c_str(), line::num_traits<T>::name(),
8850 r.actualmethod.c_str(), r.cache.caches.size());
8851 std::printf("%-14s %-12s %5s %5s %8s %6s %10s %10s %10s %10s %10s %10s %10s %10s %10s\n", "Node",
8852 "JobClass", "Item", "List", "ListCap", "Items", "HitProb", "DHitProb", "MissProb",
8853 "HitRate", "DHitRate", "MissRate", "ArvR", "ResidT", "ListCost");
8854 for (std::size_t i = 0; i < rows.size(); ++i)
8855 std::printf(
8856 "%-14s %-12s %5g %5g %8g %6g %10.6g %10.6g %10.6g %10.6g %10.6g %10.6g %10.6g %10.6g "
8857 "%10.6g\n",
8858 rows[i].node.c_str(), rows[i].cls.c_str(), rows[i].item, rows[i].list, rows[i].listcap,
8859 rows[i].items, rows[i].hitp, rows[i].dhitp, rows[i].missp, rows[i].hitr,
8860 rows[i].dhitr, rows[i].missr, rows[i].arvr, rows[i].residt, rows[i].cost);
8861 return 0;
8862}
8863
8864/**
8865 * `-a item`: `@@NetworkSolver/getAvgItemTable`, one row per (Cache, item, list).
8866 *
8867 * THE PER-ITEM OCCUPANCY, which only a solver that computes a genuine per-item
8868 * distribution has: the exact NC cache recursions and the delayed-hit retrieval
8869 * algorithms. Every other branch measures the aggregate hit probability and
8870 * never forms the item law, and the arm refuses rather than filling the column
8871 * with the uniform guess that would reproduce the same aggregate.
8872 *
8873 * `Cost` is `Size * Prob`, so summing it over the items of a list reproduces
8874 * that list's ListCost in the cache table -- which is what makes the two tables
8875 * checkable against each other.
8876 */
8877template <class T>
8878int solve_model_item(const std::string& file, const Knobs& k, const std::string& s) {
8879 line::qn::Network<T> net = read_model<T>(file);
8881 std::string banner, suffix;
8882 const line::mva::AvgResult<T> r = run_avg_engine<T>(sn, k, s, banner, &suffix, &file);
8883 if (r.cache.empty())
8884 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
8885 "-a item reports the per-item cache occupancy and this model has no Cache node, or "
8886 "the solver that ran analyzes none");
8887
8888 const double dnan = std::numeric_limits<double>::quiet_NaN();
8889 struct Row {
8890 std::string node;
8891 double item, list, listcap, size, prob, cost, dhq, dhqf;
8892 };
8893 std::vector<Row> rows;
8894 for (std::size_t c = 0; c < r.cache.caches.size(); ++c) {
8895 const line::solvers::CacheNodeMetrics<T>& m = r.cache.caches[c];
8896 const std::size_t h = m.itemcap.size();
8897 // EITHER measurement earns the item its rows. A solver may form the
8898 // per-item occupancy (the NC and MVA cache recursions) or the per-item
8899 // delayed-hit queue length (the exact chain) and not the other, and
8900 // requiring both would drop the CTMC's whole table.
8901 if (h == 0 || (m.itemprob.rows() == 0 && m.delayedhitqlen.empty())) continue;
8902 const std::size_t nit =
8903 m.itemprob.rows() > 0 ? m.itemprob.rows() : m.delayedhitqlen.size();
8904 for (std::size_t i = 0; i < nit; ++i)
8905 for (std::size_t l = 0; l < h; ++l) {
8906 Row t;
8907 t.node = sn.nodes[m.node - 1].name;
8908 t.item = static_cast<double>(i + 1);
8909 t.list = static_cast<double>(l + 1);
8910 t.listcap = m.itemcap[l];
8911 t.size = i < m.itemsize.size() ? m.itemsize[i] : dnan;
8912 // Column 0 of `itemprob` is the MISS column, so list l is column
8913 // l+1; reading it as l would report every item one list too low.
8914 t.prob = (l + 1) < m.itemprob.cols()
8916 : dnan;
8917 t.cost = t.size * t.prob;
8918 t.dhq = i < m.delayedhitqlen.size()
8920 : dnan;
8921 t.dhqf = i < m.delayedhitqlenfull.size()
8923 : dnan;
8924 rows.push_back(t);
8925 }
8926 }
8927 if (rows.empty())
8928 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
8929 "-a item needs a per-item occupancy law and this solve produced none; the NC/MVA "
8930 "cache recursions (isolated and integrated alike) and the delayed-hit retrieval "
8931 "algorithms compute the embedded one, SolverCTMC the time-weighted one, and the "
8932 "simulators none");
8933
8934 if (g_json_output) {
8935 line::reg::Json p = line::reg::Json::object();
8936 p["type"] = "AvgItemTable";
8937 p["indexBase"] = 0;
8938 for (const char* key : {"Node", "Item", "List", "ListCap", "Size", "Prob", "Cost",
8939 "DelayedHitQLen", "DelayedHitQLenFull"})
8940 p[key] = line::reg::Json::array();
8941 for (std::size_t i = 0; i < rows.size(); ++i) {
8942 p["Node"].push_back(rows[i].node);
8943 p["Item"].push_back(rows[i].item);
8944 p["List"].push_back(rows[i].list);
8945 p["ListCap"].push_back(rows[i].listcap);
8946 p["Size"].push_back(rows[i].size);
8947 p["Prob"].push_back(rows[i].prob);
8948 p["Cost"].push_back(rows[i].cost);
8949 p["DelayedHitQLen"].push_back(rows[i].dhq);
8950 p["DelayedHitQLenFull"].push_back(rows[i].dhqf);
8951 }
8952 emit_analysis<T>("item", p, r.actualmethod);
8953 return 0;
8954 }
8955 std::printf("%s arith=%s method=%s rows=%zu\n", banner.c_str(), line::num_traits<T>::name(),
8956 r.actualmethod.c_str(), rows.size());
8957 std::printf("%-14s %6s %6s %8s %10s %12s %12s %14s %18s\n", "Node", "Item", "List", "ListCap",
8958 "Size", "Prob", "Cost", "DelayedHitQLen", "DelayedHitQLenFull");
8959 for (std::size_t i = 0; i < rows.size(); ++i)
8960 std::printf("%-14s %6g %6g %8g %10g %12.8g %12.8g %14.8g %18.8g\n", rows[i].node.c_str(),
8961 rows[i].item, rows[i].list, rows[i].listcap, rows[i].size, rows[i].prob,
8962 rows[i].cost, rows[i].dhq, rows[i].dhqf);
8963 return 0;
8964}
8965
8966/**
8967 * `-a sys`: `@@NetworkSolver/getAvgSysTable`, one row per CHAIN.
8968 *
8969 * SysRespT is the chain's CYCLE TIME and SysTput the flow that completes it,
8970 * both measured at the chain's reference station -- not a column of the
8971 * AvgTable summed up. On a closed chain the two are tied by Little's law and
8972 * the table is the standard capacity-planning view: N = X * R.
8973 */
8974template <class T>
8975int solve_model_sys(const std::string& file, const Knobs& k, const std::string& s) {
8976 line::qn::Network<T> net = read_model<T>(file);
8978 std::string banner, suffix;
8979 const line::mva::AvgResult<T> r = run_avg_engine<T>(sn, k, s, banner, &suffix, &file);
8981 const std::vector<std::string> cn = line::solvers::chain_names(sn.nchains);
8982 const std::vector<std::string> cc = line::solvers::chain_class_labels<T>(sn);
8983 auto d = [](const T& v) { return line::num_traits<T>::to_double(v); };
8984
8985 if (g_json_output) {
8986 // The banner under `-o json` too, for print_chain_table's reason: the
8987 // envelope names the arithmetic and the method but never the SOLVER.
8988 std::printf("%s arith=%s method=%s chains=%zu%s\n", banner.c_str(), line::num_traits<T>::name(),
8989 r.actualmethod.c_str(), cn.size(), suffix.c_str());
8990 line::reg::Json p = line::reg::Json::object();
8991 p["type"] = "AvgSysTable";
8992 p["indexBase"] = 0;
8993 for (const char* key : {"Chain", "JobClasses", "SysRespT", "SysTput"})
8994 p[key] = line::reg::Json::array();
8995 for (std::size_t c = 0; c < sn.nchains; ++c) {
8996 p["Chain"].push_back(cn[c]);
8997 p["JobClasses"].push_back(cc[c]);
8998 p["SysRespT"].push_back(d(sys.CN[c]));
8999 p["SysTput"].push_back(d(sys.XN[c]));
9000 }
9001 emit_analysis<T>("sys", p, r.actualmethod);
9002 return 0;
9003 }
9004 std::printf("%s arith=%s method=%s chains=%zu%s\n", banner.c_str(),
9005 line::num_traits<T>::name(), r.actualmethod.c_str(), sn.nchains, suffix.c_str());
9006 std::printf("%-10s %-24s %14s %14s\n", "Chain", "JobClasses", "SysRespT", "SysTput");
9007 for (std::size_t c = 0; c < sn.nchains; ++c)
9008 std::printf("%-10s %-24s %14.6g %14.6g\n", cn[c].c_str(), cc[c].c_str(), d(sys.CN[c]),
9009 d(sys.XN[c]));
9010 return 0;
9011}
9012
9013/** Render a station- or node-level chain table, as text or as the host's JSON. */
9014template <class T>
9015void print_chain_table(const char* key, const char* type, const char* rowlabel,
9016 const std::vector<std::string>& rows,
9017 const std::vector<std::string>& chains,
9018 const std::vector<std::string>& classes,
9019 const line::solvers::ChainResult<T>& t, const std::string& method,
9020 const char* banner, const char* arith, const char* suffix = "") {
9021 auto d = [](const T& v) { return line::num_traits<T>::to_double(v); };
9022 if (g_json_output) {
9023 // THE BANNER IS PRINTED UNDER `-o json` TOO, as the AvgTable path does:
9024 // the envelope names the arithmetic and the method but never the
9025 // SOLVER, so a host that pairs a table with another codebase's by the
9026 // solver in its banner cannot attribute a bannerless one at all. Its
9027 // absence here made `-o json` unusable for these four analyses.
9028 std::printf("%s arith=%s method=%s chains=%zu%s\n", banner, arith, method.c_str(),
9029 chains.size(), suffix);
9030 line::reg::Json p = line::reg::Json::object();
9031 p["type"] = type;
9032 p["indexBase"] = 0;
9033 for (const char* c : {rowlabel, "Chain", "JobClasses", "QLen", "Util", "RespT", "ResidT",
9034 "ArvR", "Tput"})
9035 p[c] = line::reg::Json::array();
9036 // ROW-MAJOR OVER (row, chain), the reference's `(ist-1)*C+c` ordering,
9037 // so a host reading the two codebases' tables side by side indexes them
9038 // the same way.
9039 for (std::size_t i = 0; i < rows.size(); ++i)
9040 for (std::size_t c = 0; c < chains.size(); ++c) {
9041 p[rowlabel].push_back(rows[i]);
9042 p["Chain"].push_back(chains[c]);
9043 p["JobClasses"].push_back(classes[c]);
9044 p["QLen"].push_back(d(t.QN(i, c)));
9045 p["Util"].push_back(d(t.UN(i, c)));
9046 p["RespT"].push_back(d(t.RN(i, c)));
9047 p["ResidT"].push_back(d(t.WN(i, c)));
9048 p["ArvR"].push_back(d(t.AN(i, c)));
9049 p["Tput"].push_back(d(t.TN(i, c)));
9050 }
9051 emit_analysis<T>(key, p, method);
9052 return;
9053 }
9054 std::printf("%s arith=%s method=%s chains=%zu%s\n", banner, arith, method.c_str(),
9055 chains.size(), suffix);
9056 std::printf("%-16s %-10s %-20s %12s %12s %12s %12s %12s %12s\n", rowlabel, "Chain",
9057 "JobClasses", "QLen", "Util", "RespT", "ResidT", "ArvR", "Tput");
9058 for (std::size_t i = 0; i < rows.size(); ++i)
9059 for (std::size_t c = 0; c < chains.size(); ++c)
9060 std::printf("%-16s %-10s %-20s %12.6g %12.6g %12.6g %12.6g %12.6g %12.6g\n",
9061 rows[i].c_str(), chains[c].c_str(), classes[c].c_str(), d(t.QN(i, c)),
9062 d(t.UN(i, c)), d(t.RN(i, c)), d(t.WN(i, c)), d(t.AN(i, c)),
9063 d(t.TN(i, c)));
9064}
9065
9066/**
9067 * `-a chain`: `@@NetworkSolver/getAvgChainTable`, the station table by CHAIN.
9068 *
9069 * EVERY ROW IS EMITTED, including the all-zero ones, unlike the AvgTable and the
9070 * AvgNodeTable. The reference builds this table with a full (M x C) grid and no
9071 * row filter, and a chain that is absent from a station is information -- it is
9072 * the shape of the routing -- where a class absent from a station in the
9073 * AvgTable is only the class's own scope.
9074 */
9075template <class T>
9076int solve_model_chain(const std::string& file, const Knobs& k, const std::string& s) {
9077 line::qn::Network<T> net = read_model<T>(file);
9079 std::string banner, suffix;
9080 const line::mva::AvgResult<T> r = run_avg_engine<T>(sn, k, s, banner, &suffix, &file);
9082 std::vector<std::string> rows;
9083 for (std::size_t i = 0; i < sn.nstations; ++i) rows.push_back(sn.stations[i].name);
9084 print_chain_table<T>("chain", "AvgChainTable", "Station", rows,
9087 banner.c_str(), line::num_traits<T>::name(), suffix.c_str());
9088 return 0;
9089}
9090
9091/** `-a nodechain`: `@@NetworkSolver/getAvgNodeChainTable`, the node table by CHAIN. */
9092template <class T>
9093int solve_model_nodechain(const std::string& file, const Knobs& k, const std::string& s) {
9094 line::qn::Network<T> net = read_model<T>(file);
9096 std::string banner, suffix;
9097 const line::mva::AvgResult<T> r = run_avg_engine<T>(sn, k, s, banner, &suffix, &file);
9098 const NodeMetrics<T> nm = node_metrics<T>(sn, r);
9100 line::solvers::solver_get_avg_node_chain<T>(sn, nm.QN, nm.UN, nm.RN, nm.WN, nm.AN, nm.TN);
9101 std::vector<std::string> rows;
9102 for (std::size_t i = 0; i < sn.nodes.size(); ++i) rows.push_back(sn.nodes[i].name);
9103 print_chain_table<T>("nodechain", "AvgNodeChainTable", "Node", rows,
9106 banner.c_str(), line::num_traits<T>::name(), suffix.c_str());
9107 return 0;
9108}
9109
9110/**
9111 * `-a fj`: `getAvgFJTable`, the fork-join section metrics of the same solve, one row per (Fork/Join
9112 * pair, class) with a value > 0, columns as the JAR CLI's `-a fj`. Empty for a solver that computes none.
9113 */
9114template <class T>
9115int solve_model_fj(const std::string& file, const Knobs& k, const std::string& s) {
9116 line::qn::Network<T> net = read_model<T>(file);
9118 std::string banner, suffix;
9119 const line::mva::AvgResult<T> r = run_avg_engine<T>(sn, k, s, banner, &suffix, &file);
9120 std::printf("%s arith=%s method=%s%s\n", banner.c_str(), line::num_traits<T>::name(),
9121 r.actualmethod.c_str(), suffix.c_str());
9122 line::reg::Json t = fj_extra_json(sn, r.fj);
9123 if (t.is_null()) {
9124 t = line::reg::Json::object();
9125 for (const char* key : {"Fork", "Join", "JobClass", "FJQLen", "FJRespT", "FJTput"})
9126 t[key] = line::reg::Json::array();
9127 t["type"] = "AvgFJTable";
9128 }
9129 if (g_json_output) {
9130 emit_analysis<T>("fj", t, r.actualmethod);
9131 return 0;
9132 }
9133 std::printf("%-16s %-16s %-14s %14s %14s %14s\n", "Fork", "Join", "JobClass", "FJQLen", "FJRespT",
9134 "FJTput");
9135 for (std::size_t i = 0; i < t["Fork"].size(); ++i)
9136 std::printf("%-16s %-16s %-14s %14.6g %14.6g %14.6g\n", t["Fork"][i].get<std::string>().c_str(),
9137 t["Join"][i].get<std::string>().c_str(), t["JobClass"][i].get<std::string>().c_str(),
9138 t["FJQLen"][i].get<double>(), t["FJRespT"][i].get<double>(), t["FJTput"][i].get<double>());
9139 return 0;
9140}
9141
9142/** The @@NetworkSolver tables that are VIEWS of one solved AvgResult (`fj` reads its fork-join block). */
9143inline bool is_avg_view(const std::string& analysis) {
9144 return analysis == "node" || analysis == "sys" || analysis == "chain" ||
9145 analysis == "nodechain" || analysis == "fj";
9146}
9147
9148/** The solvers whose analyzer runs `sn_nonmarkov_toph`, so `--nonmkv` reaches them. */
9149inline bool nonmkv_reader(const std::string& s) {
9150 return s == "ctmc" || s == "mam" || s == "fluid" || s == "fld" || s == "ag";
9151}
9152
9153/**
9154 * Dispatch one of those four views at a fixed arithmetic.
9155 *
9156 * The wrapper arms reach the views through this rather than through the shared
9157 * ladder further down: they return before it, having validated their own knobs
9158 * against an engine the ladder knows nothing about. The arithmetic is fixed
9159 * because both wrappers report in double and have already refused every other
9160 * backend by name.
9161 */
9162template <class T>
9163int solve_avg_view(const std::string& file, const Knobs& k, const std::string& s,
9164 const std::string& analysis) {
9165 if (analysis == "node") return solve_model_node<T>(file, k, s);
9166 if (analysis == "sys") return solve_model_sys<T>(file, k, s);
9167 if (analysis == "chain") return solve_model_chain<T>(file, k, s);
9168 if (analysis == "fj") return solve_model_fj<T>(file, k, s);
9169 return solve_model_nodechain<T>(file, k, s);
9170}
9171
9172int solve_model_dispatch(const std::string& arith, const std::string& solver,
9173 const std::string& analysis, const std::string& file, const Knobs& k) {
9174 std::string s = solver.empty() ? "auto" : solver;
9175 if (s != "mva" && s != "auto" && s != "fluid" && s != "fld" && s != "nc" && s != "mam" &&
9176 s != "ag" && s != "ba" && s != "ssa" && s != "ctmc" && s != "uq" && s != "env" &&
9177 s != "lqns" && s != "ldes" && s != "jmt")
9179 "the model-solving path ports -s mva, nc, ctmc, mam, ag, ba, ssa, fluid, ldes, jmt, "
9180 "uq, env and lqns (got '" + s + "'); other solvers remain API-only");
9181 // Every solver on this path but JMT and LQNS runs in-process, so the flags
9182 // that describe an external solver's child process have nothing to act on.
9183 // Those two do run one, and both write a scratch directory --keep names:
9184 // `solve_model_jmt` forwards it to JmtOptions.keep, which is what leaves
9185 // model.jsim behind, and refusing it here made the one document a parity
9186 // difference has to be read from unobtainable.
9187 if ((k.verbose && s != "ldes") || k.remote || !k.remote_url.empty() ||
9188 (k.keep && s != "lqns" && s != "jmt"))
9190 "--keep, --verbose, --remote and --remote-url describe the child process of an "
9191 "external solver; on this path -s jmt and -s lqns run one and take --keep, -s ldes "
9192 "runs one and takes --verbose (which echoes the resolved engine command line), and "
9193 "no path takes --remote or --remote-url");
9194 // --fork-join names an arm of the fork-join FIXED POINT, which only the
9195 // mean-value arms drive: a simulator walks the fork on its sample path and
9196 // a CTMC enumerates it, so neither has a transform to choose. Refused by
9197 // name rather than ignored, which would report the default arm's numbers
9198 // under the caller's choice.
9199 if (!k.fork_join.empty() && s != "mva" && s != "nc")
9201 "--fork-join selects the fork-join transform of the shared mean-value fixed point "
9202 "and is read by -s mva and -s nc; -s " + s +
9203 " either simulates or enumerates the fork and applies no transform");
9204 // REFUSED BY NAME RATHER THAN IGNORED, on the same grounds as --fork-join
9205 // above: a knob silently dropped reports the DEFAULT arm's numbers under
9206 // the caller's choice, which is the one outcome stating the flag exists to
9207 // rule out.
9208 if (k.warmupfrac >= 0.0 && s != "ssa")
9210 "--warmupfrac discards a leading fraction of a SIMULATED path before the means are "
9211 "taken and is read by -s ssa; -s " + s +
9212 " has no path to discard (the LDES engine takes --ldes-warmupfrac)");
9213 if (k.pstar > 0.0 && s != "fluid" && s != "fld")
9215 "--pstar is the exponent of the fluid p-norm smoothing of the drift and is read by "
9216 "-s fluid; -s " + s + " integrates no drift");
9217 if (!k.fluid_boundary.empty() && s != "fluid" && s != "fld")
9219 "--fluid-boundary picks how the fluid Petri 'dae' route reports a fluid place level held at a "
9220 "bound and is read by -s fluid; -s " + s + " has no such report");
9221 // auto passes: its branch below keeps --nonmkv only for a candidate that reads it.
9222 if (!k.nonmkv.empty() && s != "auto" && !nonmkv_reader(s))
9224 "--nonmkv selects the phase-type fit of a non-Markovian law and is read by -s ctmc, "
9225 "mam, fluid and ag; -s " + s + " runs no such fit");
9226 if ((!k.busy_orders.empty() || !k.busy_subnet.empty()) && analysis != "busyperiod")
9228 "--busyperiod and --busyperiod-subnet name the orders and the subnetwork of "
9229 "-a busyperiod; got -a " + analysis);
9230 // Solver console: this dispatcher is the single point every model-solving
9231 // arm passes through, so the narrated run is opened here and closed by the
9232 // guard's destructor -- on an exception too, so a failed analysis still
9233 // reports what it had reached. The model name is not known before the file
9234 // is read, so the header names the file's model once the struct compiles.
9235 line::util::LineConsole::Run consoleRun(upper_tag(s), "", true);
9236
9237 // ---- SolverUQ, BEFORE the per-solver knob ladder ----------------------
9238 // It is a wrapper, not an engine: `--method`, `--samples` and `--seed`
9239 // describe its DESIGN and the convergence knobs belong to whatever
9240 // `--uq-solver` names, so the ladder below -- which asks "does THIS solver
9241 // have a sample count" -- answers about the wrong solver here.
9242 if (s == "uq") {
9243 if (analysis != "avg" && analysis != "posterior" && analysis != "interval")
9244 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
9245 "SolverUQ ports -a avg (the prior-weighted expectation), -a posterior (the "
9246 "per-design-point table) and -a interval (the support-only range); got '" +
9247 analysis + "'");
9248 if (k.uq_solver.empty())
9249 throw line::InputError(
9250 "-s uq needs --uq-solver: UQ computes nothing itself, it expands the Prior and "
9251 "runs another solver at each design point (the C++ spelling of UQ(model, "
9252 "@SolverMVA)). Naming one here by default would attribute the numbers to an "
9253 "engine the caller never chose");
9254 if (k.t1 >= 0.0 || k.node || !k.notation.empty())
9256 "--tspan, --node and --notation name a transient horizon, a stateful node and an "
9257 "ODE document; SolverUQ reports steady-state means over a design of models and "
9258 "has none of the three");
9259 if (k.no_interlocking || k.interlock_knobs_given() || k.repeat > 0 || !k.layer_solver.empty() ||
9260 k.nlp_knobs_given())
9262 "--no-interlocking, --interlock-*, --repeat, --layer-solver, --lld, --nlp-*, --warmstart and "
9263 "--mol-* are options of the layered solver "
9264 "and apply to -i lqnx; a Network model has no layers to interlock");
9265 if (arith == "double") return solve_model_uq<double>(file, k, analysis);
9266 if (arith == "exact") return solve_model_uq<line::Rational>(file, k, analysis);
9267 if (arith == "real:16") return solve_model_uq<line::Real<16> >(file, k, analysis);
9268 if (arith == "real" || arith == "real:32")
9269 return solve_model_uq<line::Real<32> >(file, k, analysis);
9270 if (arith == "real:64") return solve_model_uq<line::Real<64> >(file, k, analysis);
9271 if (arith == "real:128") return solve_model_uq<line::Real<128> >(file, k, analysis);
9272 if (arith == "real:256") return solve_model_uq<line::Real<256> >(file, k, analysis);
9273 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
9274 }
9275 // ---- SolverENV, also BEFORE the per-solver knob ladder ----------------
9276 // It reads a DIFFERENT MODEL TYPE: an Environment envelope, whose stages
9277 // each hold a Network. The ladder below asks its questions of one Network
9278 // model -- `--cutoff` per open class, `--node` on a stateful node -- and
9279 // the model-level knobs it would validate belong to the STAGE solver here,
9280 // so ENV states its own refusals and routes around it.
9281 if (s == "env") {
9282 if (analysis != "avg")
9283 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
9284 "SolverENV reports -a avg, the environment-blended means; getEnsembleAvg is its "
9285 "only metric entry in the reference too (got '" + analysis + "')");
9286 if (k.samples || k.seed)
9288 "--samples and --seed describe a simulation; SolverENV iterates a fixed point over "
9289 "transient stage solves and draws nothing");
9290 // `--cutoff` IS ADMITTED WITH `--stage-solver ctmc`, and only then: every
9291 // stage is then enumerated, and an open stage's chain has to be
9292 // truncated somewhere. It stays refused for a fluid ensemble, which
9293 // enumerates nothing.
9294 if (k.has_cutoff() && k.stage_solver != "ctmc")
9296 "--cutoff bounds the open population of an enumerated state space and applies to "
9297 "-s env only beside --stage-solver ctmc; the " +
9298 (k.stage_solver.empty() ? std::string("fluid") : k.stage_solver) +
9299 " stages of this ensemble enumerate no states");
9300 if (k.node || !k.notation.empty())
9302 "--node and --notation name a stateful node and an ODE document of ONE network; "
9303 "an Environment holds a network per stage and "
9304 "SolverENV reports the blend over them");
9305 if (k.no_interlocking || k.interlock_knobs_given() || k.repeat > 0 || !k.layer_solver.empty() ||
9306 k.nlp_knobs_given())
9308 "--no-interlocking, --interlock-*, --repeat, --layer-solver, --lld, --nlp-*, --warmstart and "
9309 "--mol-* are options of the layered solver "
9310 "and apply to -i lqnx; an Environment has stages, not layers");
9311 if (k.t0 != 0.0)
9313 "--tspan on the ENV path states the transient HORIZON each stage solve integrates "
9314 "to, and every stage starts from its entry state at 0; a nonzero t0 would name a "
9315 "start the coupling has no state for");
9316 // The mean-field coupling integrates the stage drift with LSODA, which
9317 // is double; the state-vector one uniformizes a CTMC and carries the
9318 // whole ladder. Narrowing silently would report an `exact` banner over
9319 // a double solve, so the refusal names the coupling that decided it.
9320 // `blend` is a spelling of `default` since 2026-09-13 (it named the
9321 // state-vector coupling before that), so it normalizes to `meanfield`
9322 // here and every gate below reads it as such without repeating it.
9323 const std::string coupling =
9324 (k.method.empty() || k.method == "default" || k.method == "mean"
9325 || k.method == "blend" || k.method == "blending")
9326 ? "meanfield"
9327 : k.method;
9328 if (k.tran_points && coupling == "statevec")
9330 "--tran-points is the mean-field coupling's quadrature grid; the state-vector "
9331 "coupling carries the whole joint law across a switch and sums over no such grid, "
9332 "so the value would be accepted and never used");
9333 // `statedep` is a C++-API method and not a file one: it needs a rate
9334 // function PER ARC (`Environment::set_env_rate_reset`), which is a
9335 // function of the stage exit metrics and has no representation in
9336 // model.json -- the reference cannot serialize `resetEnvRatesFun`
9337 // either. Reaching it from a file would find no hook and refuse deeper
9338 // in, with a message about an environment the caller never wrote.
9339 if (coupling == "statedep")
9341 "--method statedep makes each environment transition depend on the state its "
9342 "stage is left in, through a rate function per arc that no model.json can carry "
9343 "(the reference cannot serialize resetEnvRatesFun either); it is reachable from "
9344 "the C++ API, through Environment::set_env_rate_reset");
9345 if (k.tran_points && coupling == "occupation")
9347 "--tran-points is the mean-field coupling's quadrature grid; --method occupation "
9348 "solves each stage in steady state and integrates the stage law in closed form, "
9349 "so the value would be accepted and never used");
9350 if (!k.env_init.empty() && coupling != "occupation")
9352 "--env-init is options.config.env_init, the initial stage law of --method "
9353 "occupation; the '" + coupling + "' coupling reads the stationary stage law and "
9354 "would accept the value and never use it");
9355 if ((k.tran_points || k.t1 >= 0.0) && (coupling == "avg" || coupling == "dec"))
9357 "--tran-points and --tspan state the grid and the horizon of a TRANSIENT stage "
9358 "solve; the closed-form limits --method avg and --method dec solve in steady "
9359 "state and carry nothing across a switch, so both would be accepted and never "
9360 "used");
9361 if (arith != "double" && coupling != "statevec")
9362 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
9363 "SolverENV solves a stage with the fluid analyzer on every method but the "
9364 "state-vector one -- the mean-field coupling transiently, the avg and dec limits "
9365 "in steady state -- and that analyzer is LSODA's and therefore double; --arith " +
9366 arith +
9367 " reaches ENV only through the state-vector coupling (--method statevec)");
9368 if (arith == "double") return solve_model_env<double>(file, k);
9369 if (arith == "exact") return solve_model_env<line::Rational>(file, k);
9370 if (arith == "real:16") return solve_model_env<line::Real<16> >(file, k);
9371 if (arith == "real" || arith == "real:32")
9372 return solve_model_env<line::Real<32> >(file, k);
9373 if (arith == "real:64") return solve_model_env<line::Real<64> >(file, k);
9374 if (arith == "real:128") return solve_model_env<line::Real<128> >(file, k);
9375 if (arith == "real:256") return solve_model_env<line::Real<256> >(file, k);
9376 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
9377 }
9378 if (!k.uq_solver.empty())
9380 "--uq-solver names the engine SolverUQ runs at each design point and applies to -s uq; "
9381 "'" + s + "' solves one model, not a design of them");
9382 if (k.tran_points)
9384 "--tran-points is the resolution of the transient grid SolverENV sums its stage exit "
9385 "metrics over and applies to -s env; '" + s + "' has no such quadrature");
9386 // ---- SolverLDES, BEFORE the per-solver knob ladder --------------------
9387 // It hands the model DOCUMENT to an external engine instead of reading it,
9388 // so the ladder below -- which validates knobs against a parsed struct --
9389 // asks its questions of a model this path never parses. LDES states its own
9390 // refusals here for the same reason UQ and ENV state theirs.
9391 const bool ldes_knob = !k.ldes_tranfilter.empty() || k.ldes_warmupfrac >= 0.0 ||
9392 !k.ldes_cimethod.empty() || k.ldes_cnvgon || k.ldes_slotted ||
9393 k.ldes_replications > 0 || k.ldes_numthreads > 0 ||
9394 k.ldes_maxtime > 0.0 || !k.ldes_initsol.empty() ||
9395 !k.ldes_rest_url.empty();
9396 if (ldes_knob && s != "ldes" && s != "auto")
9398 "the --ldes-* flags are the discrete-event engine's own settings (warmup filter, "
9399 "confidence-interval estimator, slot lattice, replications, warm-start placement) and "
9400 "apply to -s ldes; '" + s + "' has none of them");
9401 if (k.jmt_replications > 0 && s != "jmt")
9403 "--jmt-replications is SolverJMT's transient ensemble size (-s jmt -a tran / -a "
9404 "tranprob); '" + s + "' has none (-s ldes takes --ldes-replications)");
9405 if (s == "jmt") {
9406 if (arith != "double")
9407 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
9408 "SolverJMT is a client of the Java Modelling Tools engine, which simulates in "
9409 "double and reports in double; --arith " + arith +
9410 " would label a double answer with an arithmetic that never touched it");
9411 // THE LIST AND `auto_family_metrics("jmt")` ARE ONE ANSWER, and they
9412 // had drifted: the family table advertised tran, tranprob and sample
9413 // while this gate refused all three, so a caller following
9414 // `--find-solver` was refused by name. `jmt_logs.h` implements every
9415 // one of them (`jmt_transient_replications`, `jmt_get_tran_prob_aggr`,
9416 // `jmt_sample_aggr`, `jmt_sample_sys_aggr`); what was missing was the
9417 // way in.
9418 if (analysis != "avg" && analysis != "cdf" && analysis != "trancdf" &&
9419 analysis != "trancdfpasst" && analysis != "prob" && analysis != "tran" &&
9420 analysis != "tranprob" && analysis != "sample" && !is_avg_view(analysis))
9421 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
9422 "-s jmt reports -a avg (the JSIM or JMVA mean table), its four views -a node, "
9423 "-a sys, -a chain and -a nodechain, -a cdf (the empirical response-time law read "
9424 "back from the JMT logs, preloaded at the rounded steady-state queue lengths), "
9425 "-a tran-cdf-respt and -a tran-cdf-passt (the same logged run from the default "
9426 "initial state, so the samples cover the transient), -a prob (the time each "
9427 "declared state is held for along the logged trajectory), -a tran (the transient "
9428 "means over --jmt-replications independent replications), -a tranprob (the same "
9429 "replications' aggregate state law at one station) and -a sample (one logged "
9430 "trajectory); the DETAILED laws -a states and getTranProb have no counterpart, "
9431 "since a JMT log records per-class job counts and nothing about the buffer order "
9432 "or the service phase");
9433 {
9434 const std::string removed = line::jmt::jmt_removed_method_refusal(k.method);
9435 if (!removed.empty()) throw line::UnsupportedError(line::ErrorKind{"Method"}, removed);
9436 }
9437 const std::vector<std::string> valid = line::jmt::jmt_list_valid_methods();
9438 if (!k.method.empty() &&
9439 std::find(valid.begin(), valid.end(), k.method) == valid.end())
9441 "SolverJMT methods are default, jsim and the jmva family (jmva, jmva.amva, "
9442 "jmva.mva, jmva.recal, jmva.comom, jmva.chow, jmva.bs, jmva.aql, jmva.lin, "
9443 "jmva.dmlin); got '" + k.method + "'");
9444 // `--iter_max` MEANS NOTHING TO JMT. It used to be the replication count of `-a tran` and
9445 // `-a tranprob`; that count is now `options.config.replications`, spelt --jmt-replications.
9446 const bool jmt_replicated = analysis == "tran" || analysis == "tranprob";
9447 if (k.iter_max >= 0)
9449 "--iter_max is not a SolverJMT option: the number of independent replications -a "
9450 "tran and -a tranprob average over is --jmt-replications (options.config."
9451 "replications, default 10)");
9452 if (k.tol >= 0.0 || k.iter_tol >= 0.0 || !k.multiserver.empty())
9454 "--tol, --iter_tol and --multiserver configure a fixed-point iteration; JSIM "
9455 "simulates a sample path and JMVA takes its tolerance from the exported document. "
9456 "The simulation's stopping rule is --samples");
9457 if (k.jmt_replications > 0 && !jmt_replicated)
9459 "--jmt-replications sizes the transient ensemble of -a tran and -a tranprob; "
9460 "steady-state JSIM (-a " + analysis + ") is one run and reads no replication count");
9461 if (k.has_cutoff())
9463 "--cutoff truncates an enumerated state space; JMT enumerates none");
9464 // `--node` NAMES ONE STATION, on the three arms that answer about one.
9465 // On `-a prob` it says which station `--state` overrides, the second
9466 // argument of `getProbAggr(node, state_a)`; on `-a tranprob` it is the
9467 // station whose aggregate law is estimated; on `-a sample` it is the
9468 // node whose own trajectory is returned instead of the system's. Every
9469 // other JMT arm reports a table over all stations and classes.
9470 const bool jmt_node_arm =
9471 analysis == "prob" || analysis == "tranprob" || analysis == "sample";
9472 if ((k.node && !jmt_node_arm) || k.jobclass || !k.marg_states.empty())
9474 "--node, --class and --marg-states select the marginal law of one (node, class); "
9475 "the JMT arms report tables over every station and class, and --node applies to "
9476 "-a prob (which station --state overrides), -a tranprob (whose state law) and "
9477 "-a sample (whose trajectory)");
9478 if (!k.state.empty() && analysis != "prob")
9480 "--state names the state a probability is asked about and applies to -a prob");
9481 if (!k.state.empty() && !k.node)
9483 "--state is the per-class job count of ONE station and needs --node to say "
9484 "which; a bare count vector cannot be matched against a whole network");
9485 if (!k.notation.empty() || !k.symbolic.empty() || k.equilibria)
9487 "--notation, --symbolic and --equilibria describe an exported ODE document; JMT "
9488 "integrates no ODE");
9489 if (!k.cdf_algorithm.empty())
9491 "--cdf-algorithm selects between the two sojourn-time INVERSIONS of -s nc; the "
9492 "JMT response-time law is the ecdf of the passages its loggers recorded and is "
9493 "not computed from a transform");
9494 if (is_avg_view(analysis)) return solve_avg_view<double>(file, k, "jmt", analysis);
9495 return solve_model_jmt(file, k, analysis);
9496 }
9497 if (s == "ldes") {
9498 if (arith != "double")
9499 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
9500 "SolverLDES is a client of the SSJ engine, which simulates in double and reports "
9501 "in double; --arith " + arith +
9502 " would label a double answer with an arithmetic that never touched it");
9503 // 'parallel' asks the engine for INDEPENDENT REPLICATIONS and the mean
9504 // over them, which is what its parallel analyzer is; it is not a second
9505 // engine. It resolves to a replication count here, taking --ldes-
9506 // replications when given and 8 otherwise -- the same default the SSA
9507 // parallel analyzer uses. Mirrors SolverLDES.listValidMethods in every
9508 // codebase, which advertises exactly {default, para, parallel}, 'para'
9509 // being the short spelling of 'parallel' as in SolverSSA.
9510 if (!k.method.empty() && k.method != "default" && k.method != "para" && k.method != "parallel")
9512 "SolverLDES has the methods 'default' and 'parallel' (alias 'para'; listValidMethods returns "
9513 "exactly those in every codebase); got '" + k.method + "'");
9514
9515 if (k.tol >= 0.0 || k.iter_tol >= 0.0 || k.iter_max >= 0 || !k.multiserver.empty())
9517 "--tol, --iter_tol, --iter_max and --multiserver are the knobs of a fixed-point "
9518 "iteration; LDES simulates a sample path and iterates nothing. Its stopping rule "
9519 "is --samples, or --ldes-cnvgon with --ldes-cnvgtol");
9520 if (k.has_cutoff())
9522 "--cutoff truncates an enumerated state space; a simulator visits the states the "
9523 "sample path reaches and enumerates none");
9524 if (k.jobclass || !k.marg_states.empty() || (k.node && analysis != "prob"))
9526 "--class and --marg-states select a marginal law of one (node, class), and --node "
9527 "applies to -a prob beside --state; the other LDES arms report tables over every "
9528 "station and class");
9529 if (!k.state.empty() && (analysis != "prob" || !k.node))
9531 "--state is getProbAggr(node, state)'s per-class job count of ONE station: it "
9532 "applies to -s ldes -a prob and needs --node to say which");
9533 if (!k.notation.empty() || !k.symbolic.empty() || k.equilibria)
9535 "--notation, --symbolic and --equilibria describe an exported ODE document; LDES "
9536 "integrates no ODE");
9537 if (!k.percentiles.empty() && analysis != "perct")
9539 "--percentiles names the levels getPerctRespT is read at and applies to -s ldes -a "
9540 "perct-respt; '" + analysis + "' reads no percentile");
9541 if (!k.cdf_algorithm.empty())
9543 "--cdf-algorithm selects between the two sojourn-time INVERSIONS of -s nc; the "
9544 "LDES response-time law is the ecdf of the samples the engine recorded and is not "
9545 "computed from a transform");
9546 if (k.no_interlocking || k.interlock_knobs_given() || k.repeat > 0 || !k.layer_solver.empty() ||
9547 k.nlp_knobs_given())
9549 "--no-interlocking, --interlock-*, --repeat, --layer-solver, --lld, --nlp-*, --warmstart and "
9550 "--mol-* are options of the layered solver "
9551 "and apply to -i lqnx; the LDES layered path runs in the JAR's own ensemble "
9552 "backend and has no JSON interface to reach from here");
9553 if (!k.sens_method.empty() || !k.sens_scheme.empty() || k.sens_step >= 0.0)
9555 "--sens-method, --sens-scheme and --sens-step configure the layered sensitivity "
9556 "table; LDES reports no sensitivity");
9557 if (analysis == "tran" && !(k.t1 >= 0.0))
9558 throw line::InputError(
9559 "-s ldes -a tran needs --tspan <t1> or --tspan <t0>:<t1>: a trajectory over an unstated "
9560 "horizon is not a quantity, and the engine only records buckets once a timespan "
9561 "makes the run transient");
9562 if (k.t1 >= 0.0 && analysis != "tran")
9564 "--tspan names the horizon of -a tran; -a sample runs over [0, --samples], which "
9565 "is the horizon runTransientJson uses, and the other arms are steady state");
9566 // `-a tran-cdf-*` NAMES THE TRANSIENT LAW AND IS THE STEADY-STATE ONE
9567 // HERE, because a simulator has only the samples it observed: the
9568 // reference's `getTranCdfRespT` reads the same `respTimeSamples` its
9569 // `getCdfRespT` reads, and its `getTranCdfPassT` is a one-line delegation
9570 // to `getTranCdfRespT`. Warned rather than refused, so a script written
9571 // against the JAR runs and its author is told what the curve is.
9572 if ((analysis == "trancdf" || analysis == "trancdfpasst") &&
9573 k.verbosity != "silent")
9574 std::fprintf(stderr,
9575 "Warning: -a %s is the ecdf of the per-job response times the run "
9576 "observed, the same curve -a cdf reports; the reference's LDES "
9577 "getTranCdfRespT reads the same samples\n",
9578 analysis.c_str());
9579 // method='parallel' resolved to its replication count, after every
9580 // other knob has been validated against the caller's own Knobs.
9581 Knobs kldes = k;
9582 if ((kldes.method == "parallel" || kldes.method == "para") && kldes.ldes_replications <= 1)
9583 kldes.ldes_replications = 8;
9584 if (is_avg_view(analysis)) return solve_avg_view<double>(file, kldes, "ldes", analysis);
9585 return solve_model_ldes(file, kldes, analysis);
9586 }
9587 // SolverAUTO resolves to a real engine BEFORE the knob checks below, so a
9588 // model the chooser sends to SSA accepts --samples and one it sends to CTMC
9589 // accepts --cutoff: the checks must see the solver that will actually run.
9590 if (s == "auto") {
9591 // `chooseSolverHeur` picks an engine from a GETTER, and the age laws are
9592 // not one of its getters: a model whose table it would send to MVA does
9593 // not thereby have an AoI answer. Refusing by name here beats letting
9594 // the chosen engine refuse an analysis it was never asked about.
9595 if (analysis == "aoi")
9596 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
9597 "-a aoi is the AoI branch of the fluid 'mfq' method and no other engine reports "
9598 "it, so SolverAUTO does not choose for it: ask for it by name with -s fluid");
9599 const AutoPlan plan = choose_auto_plan_dispatch(arith, file, analysis, k.method);
9600 // `delegate.m` runs the chosen solver and, when it fails, every other
9601 // feasible candidate in slot order. Reproduced here by re-entering this
9602 // dispatch with a CONCRETE method name, so each attempt is validated against
9603 // the knobs of the solver that will actually run it. Only the first
9604 // attempt carries the method the ranking gated on ('exact'): a method
9605 // name is a solver's own vocabulary and does not travel to the next.
9606 if (plan.order.size() == 1) {
9607 // A forced method name (a method family, or the Environment envelope)
9608 // leaves ONE solver, and its own diagnostic is then the whole
9609 // story: the reference rethrows it rather than wrapping it.
9610 Knobs kk = k;
9611 kk.method = plan.method;
9612 if (!nonmkv_reader(plan.order[0])) kk.nonmkv.clear(); // as the reference's chosen solver ignores it
9613 if (!plan.stage.empty() && !plan.stage[0].empty() && kk.stage_solver.empty())
9614 kk.stage_solver = plan.stage[0];
9615 std::printf("SolverAUTO selected %s%s\n", plan.order[0].c_str(), plan.note.c_str());
9616 return solve_model_dispatch(arith, plan.order[0], analysis, file, kk);
9617 }
9618 std::string first_error, first_category, first_kind;
9619 for (std::size_t i = 0; i < plan.order.size(); ++i) {
9620 Knobs kk = k;
9621 kk.method = (i == 0) ? plan.method : std::string();
9622 if (!nonmkv_reader(plan.order[i])) kk.nonmkv.clear();
9623 // An Environment candidate names its ensemble, unless the caller already did.
9624 if (i < plan.stage.size() && !plan.stage[i].empty() && kk.stage_solver.empty())
9625 kk.stage_solver = plan.stage[i];
9626 if (i == 0)
9627 std::printf("SolverAUTO selected %s%s\n", plan.order[i].c_str(),
9628 plan.note.c_str());
9629 else
9630 std::printf("SolverAUTO retrying with %s\n", plan.order[i].c_str());
9631 try {
9632 return solve_model_dispatch(arith, plan.order[i], analysis, file, kk);
9633 } catch (const InterruptRequested&) {
9634 throw; // the host asked the run to stop, so no candidate may be tried after it
9635 } catch (const line::Error& e) {
9636 // The category decides, not the message (_kb/17-error-vocabulary.md, "SolverAUTO"):
9637 // input and internal failures propagate, since no other candidate can mend a
9638 // malformed model or a bug; unsupported, numerical and external ones move on. An
9639 // unclassified LINE:Error moves on too, but loudly: it may be a crash, not a refusal.
9640 const std::string cat = e.category();
9641 if (cat == "input" || cat == "internal") throw;
9642 if (cat.empty())
9643 std::fprintf(stderr,
9644 "line-cli: warning: SolverAUTO candidate %s failed with an "
9645 "unclassified error [%s] %s; trying the next candidate\n",
9646 plan.order[i].c_str(), e.id().c_str(), e.what());
9647 if (first_error.empty()) {
9648 first_error = plan.order[i] + ": " + e.what();
9649 first_category = cat;
9650 first_kind = e.kind();
9651 }
9652 std::printf("SolverAUTO: %s cannot serve this run ([%s] %s)\n",
9653 plan.order[i].c_str(), e.id().c_str(), e.what());
9654 } catch (const std::exception& e) {
9655 // A foreign exception is unclassified by definition: move on, with the warning.
9656 std::fprintf(stderr,
9657 "line-cli: warning: SolverAUTO candidate %s failed with a non-LINE "
9658 "exception (%s); trying the next candidate\n",
9659 plan.order[i].c_str(), e.what());
9660 if (first_error.empty()) first_error = plan.order[i] + ": " + e.what();
9661 std::printf("SolverAUTO: %s cannot serve this run (%s)\n", plan.order[i].c_str(),
9662 e.what());
9663 }
9664 }
9665 // Every candidate failed: report under the FIRST failure's id, the chosen engine's.
9666 const std::string all_failed =
9667 "SolverAUTO: every candidate refused this run. The chosen engine reported -- " +
9668 first_error;
9669 if (first_category == "numerical")
9670 throw line::NumericError(line::ErrorKind{first_kind}, all_failed);
9671 if (first_category == "external")
9672 throw line::ExternalError(line::ErrorKind{first_kind}, all_failed);
9673 if (first_category == "unsupported")
9674 throw line::UnsupportedError(line::ErrorKind{first_kind}, all_failed);
9675 throw line::Error(all_failed);
9676 }
9677 // ---- knobs the CHOSEN solver does not have are refused, not dropped ----
9678 // Accepting an option and discarding it is the one place the port would
9679 // answer a question it was not asked: the caller believes a value the
9680 // solver never saw. Every refusal below names the option and the solver.
9681 const bool is_sim = (s == "ssa");
9682 // `-s ctmc -a sample` walks the chain with an exponential clock, so it has a
9683 // run length and a stream in the same sense a simulation does; every other
9684 // CTMC analysis is a solve and still refuses both.
9685 // The NC cftp methods draw iid stationary states, so they too have a run
9686 // length and a stream, the NC `options.samples` / `options.seed`. They are
9687 // named here rather than through is_stochastic_method, which classifies
9688 // them as SolverCTMC did and is deliberately unchanged by their move.
9689 const bool is_cftp =
9690 (s == "nc" && (k.method == "cftp" || k.method == "cftp.approx"));
9691 // NC IS NOT ONE SOLVER HERE: its Monte Carlo integrators, logistic sampler,
9692 // importance-sampling estimators and Chen-O'Cinneide MCMC all read a run
9693 // length and a stream, which is why solve_model_nc wires k.samples and
9694 // k.seed into NcSolverOptions and says so in its own doc comment. This
9695 // guard contradicted that file for every NC method, so a caller naming one
9696 // of those methods was told 'nc' has no sample count -- the refusal that
9697 // made the statepr_sys_aggr_large [M2C] parity row skip, its MATLAB source
9698 // being NC(model,'seed',23000,'method','ls','samples',10000).
9699 // is_stochastic_method is the port of SolverNC.isStochasticMethod and
9700 // tokenizes on '.' and '/', so 'nc.ls' and 'default/imci' classify alike.
9701 // A method nobody named stays refused: 'default' RESOLVES to a stochastic
9702 // method only at runtime, and accepting a knob on the strength of what a
9703 // name might become is the same discard this block exists to prevent.
9704 const bool nc_draws = (s == "nc" && line::nc::is_stochastic_method(k.method));
9705 const bool draws_samples =
9706 is_sim || (s == "ctmc" && analysis == "sample") || is_cftp || nc_draws;
9707 if (k.samples && !draws_samples)
9708 throw line::UnsupportedError(line::ErrorKind{"Option"}, "--samples applies to the simulation solver (-s ssa), to "
9709 "-s ctmc -a sample and to the stochastic -s nc methods "
9710 "(mci, imci, ls, is, sampling, mcmc, cftp, cftp.approx); '" +
9711 s + "' has no sample count");
9712 if (k.seed && !draws_samples)
9713 throw line::UnsupportedError(line::ErrorKind{"Option"}, "--seed applies to the simulation solver (-s ssa), to "
9714 "-s ctmc -a sample and to the stochastic -s nc methods "
9715 "(mci, imci, ls, is, sampling, mcmc, cftp, cftp.approx); '" +
9716 s + "' draws no random numbers");
9717 // --mdd-tol / --mdd-maxiter drive the level iteration, which only the mdd
9718 // method runs. Accepting them elsewhere would let a caller believe a
9719 // tolerance was applied to a solve that has no iteration in it.
9720 if ((k.mdd_tol > 0.0 || k.mdd_maxiter > 0) && !(s == "ctmc" && k.method == "mdd"))
9722 "--mdd-tol and --mdd-maxiter set the coupled level iteration of -s ctmc --method mdd; "
9723 "'" + s + " / " + (k.method.empty() ? std::string("default") : k.method) +
9724 "' iterates no levels");
9725 // --tspan names a transient horizon, which only the CTMC transient analyses
9726 // have; accepting it elsewhere would let a caller believe a horizon was used.
9727 // The fluid solver integrates a forward equation too, and its horizon is what
9728 // `kp` reports its covariance AT, so --tspan reaches it as well; every other
9729 // fluid method restarts from its own end state until the moved mass stops
9730 // changing, and a horizon there caps that iteration rather than naming a time.
9731 if (k.t1 >= 0.0 &&
9732 !(s == "ctmc" &&
9733 (analysis == "tran" || analysis == "tranprob" || analysis == "tranreward")) &&
9734 !(s == "fluid" || s == "fld") && !(s == "mam" && analysis == "tran"))
9736 "--tspan sets the horizon of a transient analysis and applies to -s ctmc -a tran, "
9737 "-a tranprob and -a tranreward, to -s mam -a tran and to -s fluid; '" + s + " / " +
9738 analysis + "' integrates no forward equation");
9739 // --node narrows an answer to one node's block of the state, which only the
9740 // per-node CTMC queries and the per-node MAM queue-length law have; every
9741 // other analysis reports the whole network.
9742 // `-s ctmc -a prob` takes it TOGETHER WITH --state and only then: the arm
9743 // reports every station's marginal, so a bare --node would narrow nothing,
9744 // while --state names a row of ONE node's own space and needs --node to say
9745 // whose.
9746 if (k.node && !(s == "ctmc" && (analysis == "tranprob" || analysis == "sample")) &&
9747 !(s == "ctmc" && analysis == "prob" && !k.state.empty()) &&
9748 !(s == "nc" && analysis == "prob" && !k.state.empty()) &&
9749 !(s == "ssa" && analysis == "sample") && !(s == "mam" && analysis == "prob") &&
9750 !((s == "mva" || s == "nc") && analysis == "marg"))
9752 "--node selects the stateful node a state query is labelled by and applies to -s ctmc "
9753 "-a tranprob and -a sample, to -s ctmc|nc -a prob beside --state, to -s ssa -a sample, "
9754 "to -s mam -a prob and to -s mva|nc -a marg; '" + s + " / " + analysis +
9755 "' reports the whole network");
9756 // --class and --marg-states are the remaining two arguments of getProbMarg,
9757 // and nothing else in the surface takes either: every other analysis reports
9758 // all classes, and no other law is evaluated at a caller-chosen job count.
9759 if ((k.jobclass || !k.marg_states.empty()) && !(s == "mva" && analysis == "marg"))
9761 "--class and --marg-states are the job class and the state list of getProbMarg and "
9762 "apply to -s mva -a marg; '" + s + " / " + analysis +
9763 "' reports every class over its own range");
9764 // --notation selects which document the ODE export writes, and only the
9765 // export writes one; every other analysis reports numbers, which have no
9766 // notation to choose.
9767 if (!k.notation.empty() && !((s == "fluid" || s == "fld") && analysis == "odes"))
9769 "--notation selects the form of the exported ODE document and applies to -s fluid -a "
9770 "odes; '" + s + " / " + analysis + "' exports no equations");
9771 // --symbolic and --equilibria select the computer-algebra backend and ask it
9772 // to solve f(x) = 0; only the Jacobian consults one.
9773 if ((!k.symbolic.empty() || k.equilibria) &&
9774 !((s == "fluid" || s == "fld") && analysis == "jacobian"))
9776 "--symbolic selects the computer-algebra backend and --equilibria asks it for the "
9777 "solutions of f(x) = 0; both apply to -s fluid -a jacobian, and '" + s + " / " +
9778 analysis + "' consults no backend");
9779 // ---- the five JAR knobs, each refused where it would be accepted and never
9780 // read. Same discipline as every knob above: a caller who passed one to an
9781 // arm that does not consult it would believe a setting had been applied.
9782 // `-s jmt -a prob` reads it too, and reads it DIFFERENTLY: an exact chain is
9783 // indexed by the ENCODED row of a node's own state space, while a JMT log
9784 // records per-class job counts and nothing else, so there the vector is
9785 // `getProbAggr(node, state_a)`'s per-class count. Both are "the state this
9786 // probability is about"; which encoding it is in follows the solver.
9787 if (!k.state.empty() &&
9788 !(analysis == "prob" && (s == "ctmc" || s == "auto" || s == "jmt" || s == "nc")))
9790 "--state names the state `getProb(node, state)` asks about and applies to -a prob "
9791 "under -s ctmc, -s nc and -s jmt, the arms whose answer is indexed by a state; '" + s +
9792 " / " + analysis + "' reports a mean or a law over all of them");
9793 if (k.events && analysis != "sample")
9795 "--events is the length of ONE sampled trajectory and applies to -a sample; use "
9796 "--samples for a solver's run length ('" + s + " / " + analysis + "')");
9797 if (!k.percentiles.empty() && !(s == "mam" && (analysis == "cdf" || analysis == "cdfpasst" ||
9798 analysis == "perct")))
9800 "--percentiles names the levels getPerctRespT is read at and applies to -s mam -a "
9801 "perct-respt (and to the percentiles printed beside -a cdf); '" + s + " / " +
9802 analysis + "' inverts no response-time law");
9803 if (!k.reward_name.empty() && analysis != "rewardvalue")
9805 "--reward-name selects which declared reward -a reward-value returns the value "
9806 "function of; -a reward returns every reward's steady-state expectation and needs no "
9807 "name ('" + s + " / " + analysis + "')");
9808 if (k.timestep > 0.0 &&
9809 !(s == "ctmc" &&
9810 (analysis == "tran" || analysis == "tranprob" || analysis == "tranreward")) &&
9811 !(s == "ssa" && k.method == "tstep" && (analysis == "avg" || is_avg_view(analysis))))
9813 "--timestep is the fixed output grid of a transient CTMC solve, `options.timestep` of "
9814 "ctmc_transient.m, and applies to -s ctmc -a tran, -a tranprob and -a tranreward (and, as "
9815 "the fixed simulation step, to -s ssa -m tstep -a avg); the "
9816 "fluid "
9817 "and simulated transients report the points their own integrator or engine produced "
9818 "('" + s + " / " + analysis + "')");
9819 if ((!k.rate_sched.empty() || k.ctmc_tv_ngrid > 0) && !(s == "ctmc" && analysis == "tran"))
9821 "--rate-sched (and --ctmc-tv-ngrid) makes the CTMC generator time-inhomogeneous, "
9822 "`options.config.rate_sched` of solver_ctmc_transient_analyzer.m, and applies to "
9823 "-s ctmc -a tran only ('" + s + " / " + analysis + "')");
9824 if ((!k.transient_method.empty() || k.fau_epsilon > 0.0 || k.fau_delta >= 0.0) &&
9825 !(s == "ctmc" &&
9826 (analysis == "tran" || analysis == "tranprob" || analysis == "tranreward")))
9828 "--transient-method (and --fau-epsilon / --fau-delta) selects how the CTMC forward "
9829 "equation is advanced, `options.config.transient_method` of "
9830 "solver_ctmc_transient_analyzer.m, and applies to -s ctmc -a tran, -a tranprob and "
9831 "-a tranreward; every other analysis solves no forward equation ('" +
9832 s + " / " + analysis + "')");
9833 // --cdf-algorithm selects how the sojourn law is inverted, which only the NC
9834 // response-time distribution does; the CTMC one is read off tagged chains
9835 // and has no such choice.
9836 if (!k.cdf_algorithm.empty() && !(s == "nc" && analysis == "cdf"))
9838 "--cdf-algorithm selects the sojourn-time inversion of the NC response-time "
9839 "distribution and applies to -s nc -a cdf; '" + s + " / " + analysis +
9840 "' inverts no generating function");
9841 // The passage flags name the two state sets of getCdfFirstPassT and of
9842 // getFirstPassTMoments, which are the only two arms that time a state-set
9843 // passage. --passage-method selects the inversion and so belongs to the
9844 // curve alone; the moments involve no inversion at all.
9845 const bool passage_arm =
9846 (s == "ctmc" && (analysis == "firstpasst" || analysis == "firstpasstmom"));
9847 if ((!k.passage_from.empty() || !k.passage_into.empty() || k.passage_orders > 0 ||
9848 !k.passage_taboo.empty()) &&
9849 !passage_arm)
9851 "--passage-from, --passage-into, --passage-taboo and --passage-orders name the state "
9852 "sets and the moment order of -s ctmc -a firstpasst / firstpasstmom; '" + s + " / " +
9853 analysis + "' times no state-set passage");
9854 // --passage-tset is the grid of the CURVE; the moments arm has no time axis.
9855 if (!k.passage_tset.empty() && !(s == "ctmc" && analysis == "firstpasst"))
9857 "--passage-tset is the time grid of -s ctmc -a firstpasst; '" + s + " / " +
9858 analysis + "' evaluates no passage-time curve");
9859 if (!k.passage_method.empty() && !(s == "ctmc" && analysis == "firstpasst"))
9861 "--passage-method selects the transform inversion of -s ctmc -a firstpasst; '" + s +
9862 " / " + analysis + "' inverts none (the moments arm solves for them directly)");
9863 // --perm-engine selects the permanent estimator, which only the NC joint law
9864 // of the per-station totals uses; nothing else in the tree evaluates one.
9865 if (k.method_perm != "exact" && !(s == "nc" && analysis == "sysmarg"))
9867 "--perm-engine selects the permanent estimator of the NC joint total-queue-length "
9868 "law and applies to -s nc -a sysmarg; '" + s + " / " + analysis +
9869 "' evaluates no permanent");
9870 // The layered path's own knobs, refused here for the same reason every other
9871 // knob above is: a caller who passed one to a Network solve would believe a
9872 // setting was applied that no Network solver has. --sens-* is the exception:
9873 // getSensitivityTable is a @@NetworkSolver method, so it selects the branch
9874 // of `-s nc -a sens` as much as of the layered one.
9875 const bool nc_sens = s == "nc" && analysis == "sens";
9876 if (!nc_sens && (!k.sens_method.empty() || !k.sens_scheme.empty() || k.sens_step > 0.0))
9878 "--sens-method, --sens-scheme and --sens-step select the branch of a sensitivity "
9879 "table and apply to -i lqnx -a sens or to -s nc -a sens; '" + s + " / " + analysis +
9880 "' differentiates nothing");
9881 if (k.no_interlocking || k.interlock_knobs_given() || k.repeat > 0 || !k.layer_solver.empty() ||
9882 !k.ln_transient.empty() || !k.ln_transient_channels.empty() || k.nlp_knobs_given())
9884 "--no-interlocking, --interlock-*, --repeat, --layer-solver, --ln-transient*, --lld, --nlp-*, "
9885 "--warmstart and --mol-* are options of the layered solver and apply to -i lqnx; a Network "
9886 "model has no layers to interlock");
9887 if (s == "ba" && (k.tol >= 0.0 || k.iter_tol >= 0.0 || k.iter_max >= 0))
9889 "--tol, --iter_tol and --iter_max do not apply to -s ba: a bound is a closed form, "
9890 "with nothing to converge");
9891 // Silent acceptance is the defect these guard against: a caller who passed
9892 // a QRF table to another solver would believe a parameterisation was
9893 // applied that nothing read.
9894 if (s != "ba" && (!k.qrf_params.empty() || !k.qrf_alpha.empty()))
9896 "--qrf-params and --qrf-alpha parameterise the QRF reduction bounds and apply to "
9897 "-s ba; '" + s + "' solves no reduction program");
9898 if (s != "ba" && k.level > 0)
9900 "--level is the hierarchy level of the SolverBA bound families and applies to -s ba; "
9901 "'" + s + "' has no bound hierarchy");
9902 if (is_sim && (k.tol >= 0.0 || k.iter_tol >= 0.0 || k.iter_max >= 0))
9904 "--tol, --iter_tol and --iter_max do not apply to -s ssa: a sample path is not an "
9905 "iteration; use --samples to set its length");
9906 if (s == "mam" && k.iter_tol >= 0.0)
9908 "--iter_tol is not a SolverMAM option (MamOptions carries tol and iter_max); "
9909 "use --tol");
9910 if (s == "ag" && k.iter_tol >= 0.0)
9912 "--iter_tol is not a SolverAG option (AgOptions carries tol and iter_max, the "
9913 "tolerance and the sweep budget of the reversed-rate fixed point); use --tol");
9914 // --max-states BOUNDS AN OPEN AGENT'S QUEUE-LENGTH DIMENSION, and only the
9915 // RCAT agents have one: a closed class is bounded by its own population
9916 // instead, and 'inapinf' ignores the level entirely and solves the open
9917 // agents on the infinite state space. Accepting it elsewhere would be the
9918 // silent-acceptance defect these guards exist for -- a caller who passed it
9919 // to -s ctmc would believe a truncation applied that nothing truncated.
9920 if (k.max_states >= 0 && s != "ag")
9922 "--max-states truncates the queue-length dimension of a SolverAG agent and applies "
9923 "to -s ag; '" + s + "' truncates no agent (use --cutoff for a CTMC state space)");
9924 // The cutoff BOUNDS A STATE SPACE, and only SolverCTMC and the MAM
9925 // queue-length law have one -- the latter because an OPEN queue's level
9926 // process is unbounded and `getProb` has to stop somewhere. Accepting it
9927 // elsewhere would be the silent-acceptance defect: a caller who passed it to
9928 // -s mva would believe the answer was truncated when nothing truncated it.
9929 if (k.has_cutoff() && s != "ctmc" && !(s == "mam" && analysis == "prob") && s != "env")
9931 "--cutoff bounds the open population of a CTMC state space, and the level truncation "
9932 "of -s mam -a prob; '" + s + " / " + analysis + "' enumerates no states");
9933 // THE MATRIX SPELLING IS NARROWER THAN THE SCALAR ONE. Only the CTMC state
9934 // space is enumerated per station, so only it can honour a per-station
9935 // bound; the MAM level truncation and an environment's stage cutoff are one
9936 // number each. Refused rather than reduced to a maximum, because that
9937 // silently answers a LARGER chain than the caller asked for.
9938 if (!k.cutoff_mat.empty() && s != "ctmc")
9940 "--cutoff as a per-(station,class) matrix bounds an enumerated state space per "
9941 "station and applies to -s ctmc; '" + s + "' takes one number");
9942 // `--stage-solver` names the solver each STAGE of an environment is run
9943 // with, and nothing else has stages: a layer of an LQN takes
9944 // `--layer-solver`, which is a different set for a different reason (a
9945 // layer is solved in steady state, a stage transiently).
9946 if (!k.env_init.empty() && s != "env")
9948 "--env-init is the initial stage law of a random environment (SolverENV method "
9949 "'occupation') and applies to -s env; '" + s + "' has no stages");
9950 if (!k.stage_solver.empty() && s != "env")
9952 "--stage-solver names the solver each stage of a random environment is run with and "
9953 "applies to -s env; '" + s + "' has no stages");
9954 // `mva` and `nc` are admitted here and refused by the COUPLING when it needs
9955 // a transient they lack (SolverENV.methodRefusal): they serve 'avg'/'dec'.
9956 if (!k.stage_solver.empty() && k.stage_solver != "fluid" && k.stage_solver != "ctmc" &&
9957 k.stage_solver != "mam" && k.stage_solver != "mva" && k.stage_solver != "nc")
9959 "--stage-solver '" + k.stage_solver +
9960 "' is not available: the stage solvers of this port are fluid, ctmc, mam (statevec "
9961 "only), mva and nc (the 'avg'/'dec' limits only)");
9962 // The three `--map-env` knobs. Refused beside `-s ba`, whose bounds the
9963 // environment image does not bracket, and beside `-s env`, which IS the
9964 // environment solver and has a model with stages already.
9965 if (!k.map_env.empty() && k.map_env != "auto" && k.map_env != "default" && k.map_env != "off")
9966 throw line::InputError(line::ErrorKind{"Option"}, "--map-env '" + k.map_env +
9967 "' is not a value: use 'auto' (or 'default') or 'off'");
9968 if (!k.map_env_method.empty() && k.map_env_method != "auto" && k.map_env_method != "dec" &&
9969 k.map_env_method != "avg" && k.map_env_method != "meanfield")
9970 throw line::InputError(line::ErrorKind{"Option"},
9971 "--map-env-method '" + k.map_env_method +
9972 "' is not an environment recombination: use 'auto', 'meanfield', 'dec' or 'avg'");
9973 if ((!k.map_env.empty() || !k.map_env_method.empty() || k.map_env_maxstages) &&
9974 (s == "ba" || s == "env"))
9976 "--map-env* asks a solver to fall back on a random-environment image of a non-renewal "
9977 "process; '-s " + s +
9978 "' takes no such fallback (a bound must not be computed on an approximation, and the "
9979 "environment solver already takes a model with stages)");
9980 // `mam` IS THE STATE-VECTOR COUPLING'S BACKEND ONLY. The mean-field one
9981 // carries marginal means and reads them off a transient mean the LD-QBD
9982 // reduction does not produce; accepting it there would run the CTMC
9983 // ensemble under the MAM name.
9984 if (k.stage_solver == "mam" && k.method != "statevec")
9986 "--stage-solver mam applies to -s env --method statevec: the LD-QBD backend flattens "
9987 "its blocks into a generator the state-vector coupling propagates a distribution "
9988 "across, and the mean-field coupling carries marginal MEANS instead");
9989 // The two FJ_codes knobs configure ONE analyzer, solver_mam_fj, which the
9990 // MAM dispatch reaches on a homogeneous fork-join model. Accepting them
9991 // anywhere else would let a caller believe an accuracy setting had been
9992 // honoured by a solver that never read it.
9993 if ((k.fj_accuracy > 0 || !k.fj_tmode.empty()) && s != "mam")
9995 "--fj-accuracy and --fj-tmode configure the FJ_codes fork-join approximation of "
9996 "solver_mam_fj.m and apply to -s mam; '" + s + "' does not run it");
9997 // --sync-phases configures the synchronous approximation alone, i.e. -s mam
9998 // with method sync.faster or sync.slower.
9999 if (k.sync_phases >= 0 && (s != "mam" || (k.method != "sync.faster" && k.method != "sync.slower")))
10001 "--sync-phases sets the synchronous phase expansion of -s mam --method sync.faster or "
10002 "sync.slower; it is not read by '" + s + (k.method.empty() ? "" : "." + k.method) + "'");
10003 // --ispn-place and --ispn-maxlevel configure the iSPN analyzer, i.e. -s mam
10004 // with method ispn or default (which routes a Petri net there).
10005 if ((!k.ispn_place.empty() || k.ispn_maxlevel >= 0) &&
10006 (s != "mam" || (!k.method.empty() && k.method != "default" && k.method != "ispn")))
10008 "--ispn-place and --ispn-maxlevel configure the infinite-state SPN analyzer of -s mam "
10009 "--method ispn (or default on a Petri net); they are not read by '" + s +
10010 (k.method.empty() ? "" : "." + k.method) + "'");
10011 // --censor-level configures the successive censoring analyzer, -s mam
10012 // --method censor alone (no other method routes there).
10013 if ((!k.censor_level.empty() || k.censor_level_index.has_value()) &&
10014 (s != "mam" || k.method != "censor"))
10016 "--censor-level sets the level station of -s mam --method censor; it is not read by '" +
10017 s + (k.method.empty() ? "" : "." + k.method) + "'");
10018 // --mapmsg-quantization configures the MAP/M/s+G reneging analyzer of -s mam
10019 // alone ('default' or 'retrial' reach it on a reneging queue).
10020 if (k.mapmsg_quantization >= 0 && s != "mam")
10022 "--mapmsg-quantization sets the patience regime count of the -s mam reneging "
10023 "analyzer; '" + s + "' does not run it");
10024 // --timescale gates the slotted branch of the MAM dispatch alone. SolverNC
10025 // has its own discrete product form and takes --slotted for it, so a
10026 // caller that names a time scale for any other solver is told rather than
10027 // silently answered on the continuous one.
10028 if (!k.timescale.empty() && s != "mam")
10030 "--timescale selects the time scale of the MAM discrete-time path and applies to "
10031 "-s mam; '" + s + "' does not read it (SolverNC takes --slotted)");
10032 // ---- `-a node`, ahead of the per-solver whitelists ---------------------
10033 // getAvgNodeTable is @@NetworkSolver's, not any one solver's: it is the
10034 // station table scattered to the node index space plus the two flow columns
10035 // recomputed from it, so every solver that produces an AvgResult can answer
10036 // it and none of them needs its own arm.
10037 // `-a node`, `-a sys`, `-a chain` and `-a nodechain` are the four
10038 // @@NetworkSolver tables that are VIEWS of one solved AvgResult -- scattered
10039 // to nodes, aggregated to chains, or reduced to the reference station -- so
10040 // they share the engine whitelist and the arithmetic ladder. Adding a
10041 // per-arm copy of either would let the four drift on which solvers and
10042 // which arithmetics they accept, for tables built from the same numbers.
10043 // `-s ssa` and `-s fluid` return their own solution types rather than an
10044 // AvgResult; `run_avg_engine` bridges them (`avg_result_from_sim`), so the
10045 // reference's rule holds here too -- a solver that reports an AvgTable
10046 // reports its four views. The two external wrappers obey the same rule and
10047 // are dispatched in their own arms above, which run before this one: they
10048 // validate knobs the ladder here knows nothing about, and LDES is handed the
10049 // model DOCUMENT rather than a parsed struct.
10050 if (analysis == "node" || analysis == "sys" || analysis == "chain" ||
10051 analysis == "nodechain" || analysis == "cache" || analysis == "item" || analysis == "fj") {
10052 const bool is_sim_engine = (s == "ssa" || s == "fluid");
10053 // The two cache tables are read off the SAME solved result, so they
10054 // belong to the same group; SolverNC is the only engine here whose
10055 // branches fill `AvgResult::cache`, and the arms say so when it is
10056 // empty rather than being whitelisted to nc alone -- `-s auto` on a
10057 // cache model resolves to nc, and refusing the token would refuse the
10058 // model.
10059 //
10060 // BOTH SIMULATORS ARE ADMITTED TO `-a cache`, and only there.
10061 // `run_avg_engine` fills `r.cache` for `-s ssa` from
10062 // `cache_metrics_of_ssa` -- the realized hit, delayed-hit and miss
10063 // SHARES the sample path measured -- and for `-s fluid` from the
10064 // cacheqn decomposition's converged split, which is the same quantity
10065 // its refreshed struct is renormalized at. Both are how
10066 // `SSA(model).getAvgCacheTable()` and `Fluid(model).getAvgCacheTable()`
10067 // answer in the reference, which reads them off the node the analyzer
10068 // wrote. `-a item` stays refused for both: the per-item occupancy is a
10069 // recursion of the
10070 // NC/MVA cache branches and no simulator forms it, so admitting it
10071 // would report an empty table for a quantity that was never measured.
10072 const bool cache_table = (analysis == "cache" || analysis == "item");
10073 const bool sim_cache_ok = (analysis == "cache");
10074 // `-a cache` and `-a item` are the CACHE tables, which RCAT does not
10075 // form -- so `ag` joins the AvgResult views and not those two.
10076 const bool ag_view = (s == "ag" && !cache_table);
10077 if ((s != "mva" && s != "auto" && s != "nc" && s != "mam" && s != "ba" && s != "ctmc" &&
10078 !ag_view && !is_sim_engine) ||
10079 (cache_table && is_sim_engine && !sim_cache_ok))
10080 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
10081 // `-a node`'s own wording is kept verbatim: it is the message a
10082 // caller has been reading since the arm existed, and the group
10083 // it now shares does not change what it says.
10084 (analysis == "node"
10085 ? std::string("-a node reports the per-node table of -s mva, nc, mam, ag, ba, "
10086 "ctmc, ssa, fluid, jmt, ldes and auto; '")
10087 : "-a " + analysis +
10088 " is a view of the station AvgResult and is reported by -s mva, nc, "
10089 "mam, " + (analysis == "item" ? "" : "ag, ") + "ba, ctmc" +
10090 (analysis == "item" ? "" : ", ssa, fluid, jmt, ldes") + " and auto; '") +
10091 s + "' does not return the station AvgResult it is built from");
10092 // The same refusal their own `-a avg` arms raise, for the same reason:
10093 // an SSA sample path is generated from exponential clocks and a fluid
10094 // trajectory is integrated by LSODA, so neither is carried by an exact
10095 // or an extended-precision backend. Refused BY NAME here rather than
10096 // narrowed silently in the ladder below.
10097 if (is_sim_engine && arith != "double")
10098 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
10099 "-a " + analysis + " under -s " + s +
10100 " is read off a " + (s == "ssa" ? "sample path" : "fluid trajectory") +
10101 ", which is transcendental; rerun with --arith double (got '" + arith + "')");
10102 const std::string eng = (s == "auto") ? std::string("mva") : s;
10103#define LINE_CLI_TABLE_LADDER(FN) \
10104 do { \
10105 if (arith == "double") return FN<double>(file, k, eng); \
10106 if (arith == "exact") return FN<line::Rational>(file, k, eng); \
10107 if (arith == "real:16") return FN<line::Real<16> >(file, k, eng); \
10108 if (arith == "real" || arith == "real:32") return FN<line::Real<32> >(file, k, eng); \
10109 if (arith == "real:64") return FN<line::Real<64> >(file, k, eng); \
10110 if (arith == "real:128") return FN<line::Real<128> >(file, k, eng); \
10111 if (arith == "real:256") return FN<line::Real<256> >(file, k, eng); \
10112 } while (0)
10113 if (analysis == "node") LINE_CLI_TABLE_LADDER(solve_model_node);
10114 if (analysis == "sys") LINE_CLI_TABLE_LADDER(solve_model_sys);
10115 if (analysis == "chain") LINE_CLI_TABLE_LADDER(solve_model_chain);
10116 if (analysis == "nodechain") LINE_CLI_TABLE_LADDER(solve_model_nodechain);
10117 if (analysis == "fj") LINE_CLI_TABLE_LADDER(solve_model_fj);
10118 if (analysis == "cache") LINE_CLI_TABLE_LADDER(solve_model_cache);
10119 if (analysis == "item") LINE_CLI_TABLE_LADDER(solve_model_item);
10120#undef LINE_CLI_TABLE_LADDER
10121 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10122 }
10123 if (s == "ctmc") {
10124 // The CTMC surface the port reaches: the AvgTable, plus the @@SolverCTMC
10125 // methods that are not means -- the generator and the state space
10126 // (getInfGen, getStateSpace), the transient occupancy (getTranProbSysAggr),
10127 // a marked trajectory (sampleSys), the declared rewards (getAvgReward),
10128 // the response-time laws (getCdfRespT, getCdfSysRespT) and the parametric
10129 // sensitivity (getSensitivityRanking).
10130 if (analysis != "avg" && analysis != "prob" && analysis != "gen" && analysis != "states" &&
10131 analysis != "tran" && analysis != "tranprob" && analysis != "tranreward" &&
10132 analysis != "sample" && analysis != "reward" && analysis != "rewardvalue" &&
10133 analysis != "cdf" && analysis != "sens" && analysis != "firstpasst" &&
10134 analysis != "firstpasstmom")
10135 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
10136 "the CTMC solver ports -a avg, node, sys, chain, nodechain, prob, gen, states, "
10137 "tran, tranprob, tranreward, sample, reward, reward-value, cdf, first-passt, "
10138 "first-passt-moments and sens (got '" + analysis + "')");
10139 // The generator-free method answers MEANS and nothing else: mdd holds
10140 // the reachable set in a diagram, so there is no state space to list, no
10141 // filtration to split and no trajectory to walk. Refused by name rather
10142 // than served from the enumerated chain, which would report an answer
10143 // under a method that did not produce it.
10144 if (k.method == "mdd" && analysis != "avg")
10145 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
10146 "the '" + k.method +
10147 "' method never builds the explicit generator, so it serves -a avg only (got '" +
10148 analysis + "'); use --method default for the state-space analyses");
10149 if (k.tol >= 0.0 || k.iter_tol >= 0.0 || k.iter_max >= 0)
10151 "--tol, --iter_tol and --iter_max do not apply to -s ctmc: the stationary vector "
10152 "is obtained by a direct solve of pi Q = 0, with nothing to converge. The mdd "
10153 "method's level iteration has --mdd-tol and --mdd-maxiter of its own");
10154 // Every step from the generator to the means is a field operation, so
10155 // there is no arithmetic to refuse: exact returns the exact rational
10156 // stationary law. The transient analyses refuse inside, by name.
10157 if (arith == "double") return solve_model_ctmc<double>(file, k, analysis);
10158 if (arith == "exact") return solve_model_ctmc<line::Rational>(file, k, analysis);
10159 if (arith == "real:16") return solve_model_ctmc<line::Real<16> >(file, k, analysis);
10160 if (arith == "real" || arith == "real:32")
10161 return solve_model_ctmc<line::Real<32> >(file, k, analysis);
10162 if (arith == "real:64") return solve_model_ctmc<line::Real<64> >(file, k, analysis);
10163 if (arith == "real:128") return solve_model_ctmc<line::Real<128> >(file, k, analysis);
10164 if (arith == "real:256") return solve_model_ctmc<line::Real<256> >(file, k, analysis);
10165 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10166 }
10167
10168 // ---- the solvers that carry their own arithmetic restriction -----------
10169 // Each refuses BY NAME rather than being narrowed silently, and the reason
10170 // is the solver's own, not a limitation of the CLI.
10171 if (s == "mam") {
10172 // The @@SolverMAM surface the port reaches: the AvgTable, the
10173 // queue-length law (getProb / getProbMarg), the response-time law
10174 // (getCdfRespT and its getSjrnT / sjrnT aliases, plus getPerctRespT),
10175 // the transient means (getTranAvg) and the M/G/1-type internals of the
10176 // queue (getMAMResult).
10177 if (analysis != "avg" && analysis != "prob" && analysis != "cdf" &&
10178 analysis != "cdfpasst" && analysis != "perct" && analysis != "tran" &&
10179 analysis != "internals")
10180 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
10181 "the MAM solver ports -a avg, node, prob, cdf, cdf-passt, perct-respt, tran and "
10182 "internals (got '" + analysis + "')");
10183 if (arith != "double")
10184 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
10185 "the MAM solver fits phase-type representations, whose fitter requires "
10186 "transcendental arithmetic; rerun with --arith double (got '" + arith + "')");
10187 if (analysis == "tran" && k.t1 < 0.0)
10189 "-s mam -a tran integrates the transient queue length over a horizon and there is "
10190 "no default for it; pass --tspan t0 t1");
10191 if (analysis == "prob") return solve_model_mam_prob<double>(file, k);
10192 if (analysis == "cdf") return solve_model_mam_cdf<double>(file, k, "cdf", "CdfRespT");
10193 // `getCdfPassT` IS `getCdfRespT` here, and that is the reference's
10194 // construction rather than an alias invented in the CLI: SolverMAM.java
10195 // computes both from the SAME `solver_mam_passage_time(sn, sn.proc,
10196 // options)` call. It is emitted under its own key so a caller that
10197 // asked the passage-time question is answered it, and the payload's
10198 // `type` records which of the two names produced the curve.
10199 if (analysis == "cdfpasst")
10200 return solve_model_mam_cdf<double>(file, k, "cdfpasst", "CdfPassT");
10201 if (analysis == "perct") return solve_model_mam_perct<double>(file, k);
10202 if (analysis == "tran") return solve_model_mam_tran<double>(file, k);
10203 if (analysis == "internals") return solve_model_mam_internals<double>(file, k);
10204 return solve_model_mam<double>(file, k);
10205 }
10206 if (s == "ssa") {
10207 // `-a cdf` is refused BY NAME rather than falling into the generic
10208 // message, because the refusal is the reference's own answer and not a
10209 // port gap: `@@SolverSSA/getCdfRespT.m` raises the same error, since SSA
10210 // samples state trajectories and not per-job sojourn times.
10211 if (analysis == "cdf") line::ssa::ssa_cdf_respt_refuse();
10212 if (analysis != "avg" && analysis != "prob" && analysis != "sample")
10213 throw line::UnsupportedError(line::ErrorKind{"Analysis"}, "the SSA solver ports -a avg, -a prob and -a sample (got '" +
10214 analysis + "')");
10215 // `tstep` advances aggregate counts on a fixed grid and draws no event path (@SolverSSA/sample*.m).
10216 if (k.method == "tstep" && analysis != "avg")
10218 "SSA 'tstep' returns steady-state averages only; it records no sample path (use another SSA "
10219 "method for -a " + analysis + ")");
10220 if (arith != "double")
10221 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
10222 "an SSA sample path is generated from exponential clocks, which are "
10223 "transcendental; rerun with --arith double (got '" + arith + "')");
10224 if (analysis == "prob") return solve_model_ssa_prob<double>(file, k);
10225 if (analysis == "sample") return solve_model_ssa_sample<double>(file, k);
10226 return solve_model_ssa<double>(file, k);
10227 }
10228 if (s == "nc") {
10229 if (analysis != "avg" && analysis != "prob" && analysis != "marg" &&
10230 analysis != "sysmarg" && analysis != "cdf" && analysis != "sens" &&
10231 analysis != "normconst" && analysis != "busyperiod")
10232 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
10233 "the NC solver ports -a avg, -a node, -a prob, -a marg, -a sysmarg, -a cdf, "
10234 "-a sens, -a normconst and -a busyperiod (got '" + analysis + "')");
10235 // The perfect sampler answers MEANS from iid stationary draws and yields
10236 // no normalizing constant, so none of the other NC analyses has anything
10237 // to be computed from. Refused by name rather than served by a different
10238 // NC route under the caller's method.
10239 if ((k.method == "cftp" || k.method == "cftp.approx") && analysis != "avg")
10240 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
10241 "the '" + k.method +
10242 "' method draws stationary states and yields no normalizing constant, so it "
10243 "serves -a avg only (got '" + analysis + "'); use another --method for the "
10244 "other NC analyses");
10245 if (analysis == "busyperiod") {
10246 if (arith == "double") return solve_model_nc_busyp<double>(file, k);
10247 if (arith == "exact") return solve_model_nc_busyp<line::Rational>(file, k);
10248 if (arith == "real:16") return solve_model_nc_busyp<line::Real<16> >(file, k);
10249 if (arith == "real" || arith == "real:32")
10250 return solve_model_nc_busyp<line::Real<32> >(file, k);
10251 if (arith == "real:64") return solve_model_nc_busyp<line::Real<64> >(file, k);
10252 if (arith == "real:128") return solve_model_nc_busyp<line::Real<128> >(file, k);
10253 if (arith == "real:256") return solve_model_nc_busyp<line::Real<256> >(file, k);
10254 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10255 }
10256 if (analysis == "sysmarg") {
10257 if (arith == "double") return solve_model_nc_sysmarg<double>(file, k);
10258 if (arith == "exact") return solve_model_nc_sysmarg<line::Rational>(file, k);
10259 if (arith == "real:16") return solve_model_nc_sysmarg<line::Real<16> >(file, k);
10260 if (arith == "real" || arith == "real:32")
10261 return solve_model_nc_sysmarg<line::Real<32> >(file, k);
10262 if (arith == "real:64") return solve_model_nc_sysmarg<line::Real<64> >(file, k);
10263 if (arith == "real:128") return solve_model_nc_sysmarg<line::Real<128> >(file, k);
10264 if (arith == "real:256") return solve_model_nc_sysmarg<line::Real<256> >(file, k);
10265 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10266 }
10267 if (analysis == "marg") {
10268 if (arith == "double") return solve_model_nc_marg<double>(file, k);
10269 if (arith == "exact") return solve_model_nc_marg<line::Rational>(file, k);
10270 if (arith == "real:16") return solve_model_nc_marg<line::Real<16> >(file, k);
10271 if (arith == "real" || arith == "real:32")
10272 return solve_model_nc_marg<line::Real<32> >(file, k);
10273 if (arith == "real:64") return solve_model_nc_marg<line::Real<64> >(file, k);
10274 if (arith == "real:128") return solve_model_nc_marg<line::Real<128> >(file, k);
10275 if (arith == "real:256") return solve_model_nc_marg<line::Real<256> >(file, k);
10276 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10277 }
10278 // Served under NC too so `-s auto -a normconst`, which chooseSolverHeur
10279 // sends to NC on a product-form model, lands on an arm that answers.
10280 if (analysis == "normconst") {
10281 if (arith == "double") return solve_model_normconst<double>(file, k, s);
10282 if (arith == "exact") return solve_model_normconst<line::Rational>(file, k, s);
10283 if (arith == "real:16") return solve_model_normconst<line::Real<16> >(file, k, s);
10284 if (arith == "real" || arith == "real:32")
10285 return solve_model_normconst<line::Real<32> >(file, k, s);
10286 if (arith == "real:64") return solve_model_normconst<line::Real<64> >(file, k, s);
10287 if (arith == "real:128") return solve_model_normconst<line::Real<128> >(file, k, s);
10288 if (arith == "real:256") return solve_model_normconst<line::Real<256> >(file, k, s);
10289 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10290 }
10291 if (analysis == "sens") {
10292 if (arith == "double") return solve_model_nc_sens<double>(file, k);
10293 if (arith == "exact") return solve_model_nc_sens<line::Rational>(file, k);
10294 if (arith == "real:16") return solve_model_nc_sens<line::Real<16> >(file, k);
10295 if (arith == "real" || arith == "real:32")
10296 return solve_model_nc_sens<line::Real<32> >(file, k);
10297 if (arith == "real:64") return solve_model_nc_sens<line::Real<64> >(file, k);
10298 if (arith == "real:128") return solve_model_nc_sens<line::Real<128> >(file, k);
10299 if (arith == "real:256") return solve_model_nc_sens<line::Real<256> >(file, k);
10300 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10301 }
10302 if (analysis == "cdf") {
10303 if (arith == "double") return solve_model_nc_cdf<double>(file, k);
10304 if (arith == "exact") return solve_model_nc_cdf<line::Rational>(file, k);
10305 if (arith == "real:16") return solve_model_nc_cdf<line::Real<16> >(file, k);
10306 if (arith == "real" || arith == "real:32")
10307 return solve_model_nc_cdf<line::Real<32> >(file, k);
10308 if (arith == "real:64") return solve_model_nc_cdf<line::Real<64> >(file, k);
10309 if (arith == "real:128") return solve_model_nc_cdf<line::Real<128> >(file, k);
10310 if (arith == "real:256") return solve_model_nc_cdf<line::Real<256> >(file, k);
10311 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10312 }
10313 if (analysis == "prob") {
10314 if (arith == "double") return solve_model_nc_prob<double>(file, k);
10315 if (arith == "exact") return solve_model_nc_prob<line::Rational>(file, k);
10316 if (arith == "real:16") return solve_model_nc_prob<line::Real<16> >(file, k);
10317 if (arith == "real" || arith == "real:32")
10318 return solve_model_nc_prob<line::Real<32> >(file, k);
10319 if (arith == "real:64") return solve_model_nc_prob<line::Real<64> >(file, k);
10320 if (arith == "real:128") return solve_model_nc_prob<line::Real<128> >(file, k);
10321 if (arith == "real:256") return solve_model_nc_prob<line::Real<256> >(file, k);
10322 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10323 }
10324 if (arith == "double") return solve_model_nc<double>(file, k);
10325 if (arith == "exact") return solve_model_nc<line::Rational>(file, k);
10326 if (arith == "real:16") return solve_model_nc<line::Real<16> >(file, k);
10327 if (arith == "real" || arith == "real:32") return solve_model_nc<line::Real<32> >(file, k);
10328 if (arith == "real:64") return solve_model_nc<line::Real<64> >(file, k);
10329 if (arith == "real:128") return solve_model_nc<line::Real<128> >(file, k);
10330 if (arith == "real:256") return solve_model_nc<line::Real<256> >(file, k);
10331 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10332 }
10333 if (s == "ag") {
10334 // The @@SolverAG surface the port reaches: the AvgTable and its four
10335 // views, plus -a cdf as the inherited base-class exponential fallback.
10336 // RCAT converges a fixed point over the synchronization rates and
10337 // reports mean measures; it forms no state probability and no
10338 // transient, so there is nothing else to expose.
10339 if (analysis != "avg" && analysis != "cdf")
10340 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
10341 "the AG solver ports -a avg (with its views -a node, -a sys, -a chain and "
10342 "-a nodechain) and -a cdf, the inherited exponential fallback: RCAT converges a "
10343 "fixed point over the synchronization rates and reports mean measures, forming no "
10344 "state probability or transient (got '" + analysis + "')");
10345 if (analysis == "cdf") {
10346 if (arith == "double") return solve_model_ag_cdf<double>(file, k);
10347 if (arith == "exact") return solve_model_ag_cdf<line::Rational>(file, k);
10348 if (arith == "real:16") return solve_model_ag_cdf<line::Real<16> >(file, k);
10349 if (arith == "real" || arith == "real:32")
10350 return solve_model_ag_cdf<line::Real<32> >(file, k);
10351 if (arith == "real:64") return solve_model_ag_cdf<line::Real<64> >(file, k);
10352 if (arith == "real:128") return solve_model_ag_cdf<line::Real<128> >(file, k);
10353 if (arith == "real:256") return solve_model_ag_cdf<line::Real<256> >(file, k);
10354 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10355 }
10356 if (arith == "double") return solve_model_ag<double>(file, k);
10357 if (arith == "exact") return solve_model_ag<line::Rational>(file, k);
10358 if (arith == "real:16") return solve_model_ag<line::Real<16> >(file, k);
10359 if (arith == "real" || arith == "real:32") return solve_model_ag<line::Real<32> >(file, k);
10360 if (arith == "real:64") return solve_model_ag<line::Real<64> >(file, k);
10361 if (arith == "real:128") return solve_model_ag<line::Real<128> >(file, k);
10362 if (arith == "real:256") return solve_model_ag<line::Real<256> >(file, k);
10363 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10364 }
10365 if (s == "ba") {
10366 if (analysis != "avg" && analysis != "bounds" && analysis != "cdf")
10367 throw line::UnsupportedError(line::ErrorKind{"Analysis"}, "the BA solver ports -a avg, -a node, -a bounds and "
10368 "-a cdf, the inherited exponential fallback (got '" +
10369 analysis + "')");
10370 if (analysis == "cdf") {
10371 if (arith == "double") return solve_model_ba_cdf<double>(file, k);
10372 if (arith == "exact") return solve_model_ba_cdf<line::Rational>(file, k);
10373 if (arith == "real:16") return solve_model_ba_cdf<line::Real<16> >(file, k);
10374 if (arith == "real" || arith == "real:32")
10375 return solve_model_ba_cdf<line::Real<32> >(file, k);
10376 if (arith == "real:64") return solve_model_ba_cdf<line::Real<64> >(file, k);
10377 if (arith == "real:128") return solve_model_ba_cdf<line::Real<128> >(file, k);
10378 if (arith == "real:256") return solve_model_ba_cdf<line::Real<256> >(file, k);
10379 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10380 }
10381 if (analysis == "bounds") {
10382 if (arith == "double") return solve_model_ba_bounds<double>(file, k);
10383 if (arith == "exact") return solve_model_ba_bounds<line::Rational>(file, k);
10384 if (arith == "real:16") return solve_model_ba_bounds<line::Real<16> >(file, k);
10385 if (arith == "real" || arith == "real:32")
10386 return solve_model_ba_bounds<line::Real<32> >(file, k);
10387 if (arith == "real:64") return solve_model_ba_bounds<line::Real<64> >(file, k);
10388 if (arith == "real:128") return solve_model_ba_bounds<line::Real<128> >(file, k);
10389 if (arith == "real:256") return solve_model_ba_bounds<line::Real<256> >(file, k);
10390 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10391 }
10392 if (arith == "double") return solve_model_ba<double>(file, k);
10393 if (arith == "exact") return solve_model_ba<line::Rational>(file, k);
10394 if (arith == "real:16") return solve_model_ba<line::Real<16> >(file, k);
10395 if (arith == "real" || arith == "real:32") return solve_model_ba<line::Real<32> >(file, k);
10396 if (arith == "real:64") return solve_model_ba<line::Real<64> >(file, k);
10397 if (arith == "real:128") return solve_model_ba<line::Real<128> >(file, k);
10398 if (arith == "real:256") return solve_model_ba<line::Real<256> >(file, k);
10399 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10400 }
10401 if (s == "lqns") {
10402 if (analysis != "avg" && analysis != "cdf")
10403 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
10404 "SolverLQNS on a Network reports -a avg and -a cdf, the inherited exponential "
10405 "fallback: "
10406 "qnsolver returns one chain-level table of means and computes no state "
10407 "probability and no transient (got '" + analysis + "')");
10408 // The numbers arrive as the decimal text qnsolver printed, so every
10409 // digit past double is one this port invented; the ladder is refused
10410 // rather than run at a width the answer does not have.
10411 if (arith != "double")
10412 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
10413 "SolverLQNS reads its results back as the decimal text an external binary printed, "
10414 "which is double at best; --arith " + arith +
10415 " would report a precision the tool never produced");
10416 if (analysis == "cdf") return solve_model_lqns_network_cdf(file, k);
10417 return solve_model_lqns_network<double>(file, k);
10418 }
10419 if (s == "fluid" || s == "fld") {
10420 if (analysis != "avg" && analysis != "odes" && analysis != "var" &&
10421 analysis != "tranvar" && analysis != "jacobian" && analysis != "tran" &&
10422 analysis != "prob" && analysis != "cdf" && analysis != "aoi" &&
10423 analysis != "statevec")
10424 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
10425 "the fluid solver ports -a avg, -a tran, -a tranvar, -a prob, -a cdf, -a aoi, "
10426 "-a odes, -a statevec, -a var and -a jacobian (got '" + analysis + "')");
10427 // The drift is integrated by LSODA, whose coefficients assume double;
10428 // a higher-precision request is refused rather than quietly narrowed.
10429 if (arith != "double")
10430 throw line::UnsupportedError(line::ErrorKind{"Arithmetic"},
10431 "the fluid solver integrates its drift with LSODA, which is double precision by "
10432 "construction; rerun with --arith double (got '" + arith + "')");
10433 if (analysis == "odes") return solve_model_fluid_odes<double>(file, k);
10434 if (analysis == "statevec") return solve_model_fluid_statevec<double>(file, k);
10435 if (analysis == "jacobian") return solve_model_fluid_jacobian<double>(file, k);
10436 if (analysis == "var") return solve_model_fluid_var<double>(file, k);
10437 if (analysis == "tranvar") return solve_model_fluid_tranvar<double>(file, k);
10438 if (analysis == "tran") return solve_model_fluid_tran<double>(file, k);
10439 if (analysis == "prob") return solve_model_fluid_prob<double>(file, k);
10440 if (analysis == "cdf") return solve_model_fluid_cdf<double>(file, k);
10441 if (analysis == "aoi") return solve_model_fluid_aoi<double>(file, k);
10442 return solve_model_fluid<double>(file, k);
10443 }
10444 if (analysis == "prob") {
10445 if (arith == "double") return solve_model_prob<double>(file, k);
10446 if (arith == "exact") return solve_model_prob<line::Rational>(file, k);
10447 if (arith == "real:16") return solve_model_prob<line::Real<16> >(file, k);
10448 if (arith == "real" || arith == "real:32") return solve_model_prob<line::Real<32> >(file, k);
10449 if (arith == "real:64") return solve_model_prob<line::Real<64> >(file, k);
10450 if (arith == "real:128") return solve_model_prob<line::Real<128> >(file, k);
10451 if (arith == "real:256") return solve_model_prob<line::Real<256> >(file, k);
10452 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10453 }
10454 if (analysis == "marg") {
10455 if (arith == "double") return solve_model_marg<double>(file, k);
10456 if (arith == "exact") return solve_model_marg<line::Rational>(file, k);
10457 if (arith == "real:16") return solve_model_marg<line::Real<16> >(file, k);
10458 if (arith == "real" || arith == "real:32") return solve_model_marg<line::Real<32> >(file, k);
10459 if (arith == "real:64") return solve_model_marg<line::Real<64> >(file, k);
10460 if (arith == "real:128") return solve_model_marg<line::Real<128> >(file, k);
10461 if (arith == "real:256") return solve_model_marg<line::Real<256> >(file, k);
10462 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10463 }
10464 if (analysis == "normconst") {
10465 if (arith == "double") return solve_model_normconst<double>(file, k, s);
10466 if (arith == "exact") return solve_model_normconst<line::Rational>(file, k, s);
10467 if (arith == "real:16") return solve_model_normconst<line::Real<16> >(file, k, s);
10468 if (arith == "real" || arith == "real:32")
10469 return solve_model_normconst<line::Real<32> >(file, k, s);
10470 if (arith == "real:64") return solve_model_normconst<line::Real<64> >(file, k, s);
10471 if (arith == "real:128") return solve_model_normconst<line::Real<128> >(file, k, s);
10472 if (arith == "real:256") return solve_model_normconst<line::Real<256> >(file, k, s);
10473 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10474 }
10475 if (analysis == "cdf") {
10476 // The inherited base-class exponential fallback over the MVA means,
10477 // as @@NetworkSolver/getCdfRespT.m serves it for SolverMVA
10478 if (arith == "double") return solve_model_mva_cdf<double>(file, k);
10479 if (arith == "exact") return solve_model_mva_cdf<line::Rational>(file, k);
10480 if (arith == "real:16") return solve_model_mva_cdf<line::Real<16> >(file, k);
10481 if (arith == "real" || arith == "real:32")
10482 return solve_model_mva_cdf<line::Real<32> >(file, k);
10483 if (arith == "real:64") return solve_model_mva_cdf<line::Real<64> >(file, k);
10484 if (arith == "real:128") return solve_model_mva_cdf<line::Real<128> >(file, k);
10485 if (arith == "real:256") return solve_model_mva_cdf<line::Real<256> >(file, k);
10486 throw line::InputError("--arith '" + arith + "' is not a model-solve backend");
10487 }
10488 if (analysis != "avg")
10489 throw line::UnsupportedError(line::ErrorKind{"Analysis"},
10490 "the model-solving path ports -a avg, -a node, -a prob, -a marg, -a normconst and "
10491 "-a cdf (got '" +
10492 analysis + "')");
10493 // The mvaDispatch ladder's transcendental-only analyzers (open-queue closed
10494 // forms, DPS-exact, Marie, size-based) refuse by name under exact/real via
10495 // their if-constexpr guards, so the field-arithmetic branches (product-form
10496 // MVA, LD scaling) stay exact while a transcendental model is refused rather
10497 // than silently degraded.
10498 if (arith == "double") return solve_model_mva<double>(file, k);
10499 if (arith == "exact") return solve_model_mva<line::Rational>(file, k);
10500 if (arith == "real:16") return solve_model_mva<line::Real<16> >(file, k);
10501 if (arith == "real" || arith == "real:32") return solve_model_mva<line::Real<32> >(file, k);
10502 if (arith == "real:64") return solve_model_mva<line::Real<64> >(file, k);
10503 if (arith == "real:128") return solve_model_mva<line::Real<128> >(file, k);
10504 if (arith == "real:256") return solve_model_mva<line::Real<256> >(file, k);
10505 throw line::InputError(
10506 "--arith '" + arith +
10507 "' is not a model-solve backend; use double, exact or real:<16|32|64|128|256>");
10508}
10509
10510/**
10511 * The no-argument and `-h` message: the flags a first run actually needs.
10512 *
10513 * The full reference below is ~460 lines, which is not a thing a human reads at
10514 * a prompt; it stays one flag away under `--help-all` rather than being the
10515 * first thing the binary says.
10516 */
10517void print_brief_help() {
10518 std::printf(
10519 "LINE solver (C++), version %s\n"
10520 "\n"
10521 "Usage: line-cli -f <model> [-s <solver>] [-a <analysis>] [-o <format>]\n"
10522 " cat model.json | line-cli\n"
10523 "\n"
10524 "Common options:\n"
10525 " -f, --file <path> model file: .json (network), .lqnx or .in (layered),\n"
10526 " .jsimg (JMT), .pnml (Petri net); stdin if omitted\n"
10527 " -s, --solver <name> auto (default), mva, nc, ctmc, mam, fluid, ssa,\n"
10528 " ldes, jmt, ag, ba, uq; ln for layered models, env\n"
10529 " for random environments\n"
10530 " -a, --analysis <type> avg (default), node, sys, chain, tran, prob, cdf,\n"
10531 " states, sample, normconst, bounds, ... (comma list)\n"
10532 " -o, --output <fmt> readable (default) | json | jsimg (export the\n"
10533 " model as a JMT simulation document)\n"
10534 " --method <name> algorithm within the chosen solver\n"
10535 " --samples <n> simulation run length (ssa, ldes); default 10000\n"
10536 " --seed <n> random seed; default 23000\n"
10537 " --timeout <s> wall-clock budget of the whole solve, any solver\n"
10538 " (seconds, fractional allowed; inf = none, the\n"
10539 " default). A solve it cuts short returns its\n"
10540 " interim metrics, warns, and -o json adds\n"
10541 " \"timedOut\": true at the top level; one with no\n"
10542 " valid partial result fails LINE:numerical:Timeout\n"
10543 " -v, --verbosity <lvl> silent | standard | debug; debug turns on\n"
10544 " the solver console, a running progress log\n"
10545 " --find-solver [m] which solvers and methods can analyze this model,\n"
10546 " optionally only those answering measure <m>\n"
10547 " (avg, tran, cdf, prob, sample, ...); reports and exits\n"
10548 " --find-solver-all [m] the same, keeping the refused pairs and the\n"
10549 " reason each was refused\n"
10550 " -h, --help this message\n"
10551 " --help-all every option, solver by solver\n"
10552 " -V, --version version string\n"
10553 " --install environment check: which optional backends\n"
10554 " (Java/JMT, LQNS, qnsolver, SageMath) are reachable\n"
10555 "\n"
10556 "Examples:\n"
10557 " line-cli -f model.json solve, letting auto pick the solver\n"
10558 " line-cli -f model.json -s mva -a avg mean queue lengths, MVA\n"
10559 " line-cli -f model.lqnx -s ln solve a layered model\n"
10560 " line-cli -f model.json -s ssa --samples 1e6 -o json\n"
10561 " line-cli -f model.json --find-solver what can solve this model\n"
10562 " line-cli -f model.json --find-solver cdf ... and return a passage-time law\n"
10563 "\n"
10564 "Each solver has flags of its own (tolerances, horizons, engine choices):\n"
10565 "run `line-cli --help-all` for the full reference.\n",
10566 kVersion);
10567}
10568
10569void print_help() {
10570 std::printf(
10571 "LINE multiprecision solver (C++), version %s\n"
10572 "\n"
10573 "Usage: line-cli [OPTIONS]\n"
10574 " cat model.json | line-cli -i json [OPTIONS]\n"
10575 " line-cli model.lqnx [OPTIONS]\n"
10576 "\n"
10577 "Options (flag-compatible with jline.cli.LineCLI):\n"
10578 " -f, --file <path> model file; stdin when omitted (json only)\n"
10579 " -i, --input <fmt> input format: json | jsim | jsimg | jsimw |\n"
10580 " lqnx | xml | srvn | pnml. Without it a .lqnx or\n"
10581 " .xml path is read as a layered model, a .in\n"
10582 " path (or a .lqn one not opening with '<') as\n"
10583 " a layered model in the LQNS SRVN text, a\n"
10584 " .jsim/.jsimg/.jsimw path as a JMT simulation\n"
10585 " document, a .pnml path as a place/transition\n"
10586 " net (ISO/IEC 15909-2), and anything else as a\n"
10587 " Network model.json. The three jsim spellings\n"
10588 " name ONE format, as they do in JMT\n"
10589 " -o, --output <fmt> output format: readable | json | jsimg\n"
10590 " (| layers, lqnx for layered models).\n"
10591 " jsimg exports the model as a JMT simulation\n"
10592 " document and solves nothing -- the write half\n"
10593 " of -i jsim|jsimg|jsimw, and the same three\n"
10594 " spellings are accepted. --seed, --samples and\n"
10595 " --tspan set the controls its header carries\n"
10596 " json is honoured by EVERY analysis, not only\n"
10597 " -a avg: each answers under a key named after\n"
10598 " its -a, with the arithmetic and the resolved\n"
10599 " method beside it, and every index inside a\n"
10600 " payload is 0-based against the tables' 1-based\n"
10601 " columns (each payload states its indexBase)\n"
10602 " -s, --solver <name> Network: auto, mva, nc, ctmc, mam, ba, ssa, fluid, uq,\n"
10603 " ldes (the SSJ discrete-event engine, run as a\n"
10604 " subprocess on common/ldes or common/ldes.jar),\n"
10605 " jmt (the Java Modelling Tools engine),\n"
10606 " lqns (its qns methods, the external qnsolver\n"
10607 " binary)\n"
10608 " layered: auto, ln, ln.mva, ln.comom, lqns,\n"
10609 " ldes (the native in-process LN simulator, a\n"
10610 " sample path of the layered model itself and\n"
10611 " not a decomposition into layers; it takes\n"
10612 " --samples and --seed, and NOT the --ldes-*\n"
10613 " family, which configures the subprocess\n"
10614 " engine that answers -s ldes on a Network)\n"
10615 " environment: env (an Environment model.json)\n"
10616 " -a, --analysis <type> analysis: avg, node, sys, chain, nodechain,\n"
10617 " stage, cache, item, fj, prob, marg, cdf, cdf-passt,\n"
10618 " perct-respt, tran, tran-cdf-respt,\n"
10619 " tran-cdf-passt, tranprob, tranreward,\n"
10620 " reward-value, normconst, gen, states, sample,\n"
10621 " reward, sens, first-passt, odes, statevec,\n"
10622 " var, tranvar, busyperiod,\n"
10623 " jacobian, aoi, internals, bounds, posterior,\n"
10624 " interval. A COMMA LIST runs several in order\n"
10625 " (`-a avg,sys`), emitting one -o json envelope\n"
10626 " per analysis rather than one merged object.\n"
10627 " The JAR CLI's own spellings are accepted as\n"
10628 " aliases -- cdf-respt, prob-sys-aggr, tran-avg,\n"
10629 " generator, reward-steady, all -- and collapse\n"
10630 " onto the arm that already answers them whole:\n"
10631 " -a prob reports getProbSys, getProbSysAggr and\n"
10632 " the per-station pair together, -a sample walks\n"
10633 " all four samplers at once, and -a stage IS\n"
10634 " -a avg on a Network (one implicit stage).\n"
10635 " Which names a\n"
10636 " solver serves is stated by its own refusal;\n"
10637 " ssa serves avg, prob and sample (prob and\n"
10638 " sample run the SERIAL engine whatever -m\n"
10639 " said, since the NRM simulates counts rather\n"
10640 " than the state encoding)\n"
10641 " -v, --verbosity <lvl> silent | standard | debug; debug turns on\n"
10642 " the solver console, a running progress log\n"
10643 " of every solver run\n"
10644 " -d, --seed <n> random seed (SSA, nc --method cftp); default\n"
10645 " 23000. -d is the JAR CLI's spelling\n"
10646 " --warmupfrac <f> SSA: leading fraction of the path discarded\n"
10647 " before the means are taken, in [0,1); unset,\n"
10648 " 0.2 on a model with an open class, else 0\n"
10649 " --pstar <p> fluid: exponent of the p-norm smoothing of the\n"
10650 " drift; without it the hard min() is integrated\n"
10651 " --fluid-boundary <m> fluid (Petri dae): reflect (default) reports a\n"
10652 " fluid place level held at a bound as the bound;\n"
10653 " diffusion as a reflected Brownian motion's mean\n"
10654 " --nonmkv <method> ctmc, mam, fluid, ag: bernstein (default) fits a\n"
10655 " phase-type to a non-Markovian law; none skips it\n"
10656 " --busyperiod <n,..> -a busyperiod: the orders wanted; default 1\n"
10657 " --busyperiod-subnet <i,..>\n"
10658 " -a busyperiod: the 1-based stations forming the\n"
10659 " subnetwork. Required -- a busy period is defined\n"
10660 " for a NAMED set and no default can choose one\n"
10661 " --method <name> algorithm within the solver\n"
10662 " --samples <n> simulation run length (SSA); default 10000.\n"
10663 " Accepts 1e6 as well as 1000000. A simulation\n"
10664 " figure is only a measurement WITH this number,\n"
10665 " which is why the SSA banner reports it back.\n"
10666 " Also the draw count of nc --method cftp,\n"
10667 " default 1e5, where the draw is the answer.\n"
10668 " --mdd-tol <x> level-iteration tolerance of ctmc --method mdd;\n"
10669 " default 1e-12. NOT --tol: that iteration is an\n"
10670 " inner solve whose fixed point is checked\n"
10671 " against the population invariant at 1e-6, so a\n"
10672 " solver-sized tolerance stops short of it\n"
10673 " --mdd-maxiter <n> coupled sweeps before ctmc --method mdd is\n"
10674 " declared non-convergent; default 500\n"
10675 " --level <n> hierarchy level of the ba pbh/bjbh/cbh/sib\n"
10676 " families; default 2\n"
10677 " --qrf-params <j> JSON (inline or a path) with the QRF blocking\n"
10678 " tables of -s ba --method qrf.bas|qrf.rsrd:\n"
10679 " f, MR, BB, MM, MM1, ZZ and optionally F, the\n"
10680 " fields sn_to_qrf_params assembles. ZM is\n"
10681 " derived from ZZ. There is no default: assuming\n"
10682 " no blocking puts the bound ~31x farther from\n"
10683 " exact, so its absence is refused\n"
10684 " --qrf-alpha <j> JSON (nstations x N) load-dependent scaling of\n"
10685 " the ba qrf.mmi.ld, qrf.mmi.linear and qrf.rsrd\n"
10686 " arms; default all ones\n"
10687 " --tol <x> convergence tolerance (mva, nc, mam, ag, fluid)\n"
10688 " --iter_tol <x> outer-loop tolerance (mva, nc, fluid)\n"
10689 " --iter_max <n> iteration cap (mva, nc, mam, ag, fluid)\n"
10690 " --stiff <true|false> options.stiff of a ctmc transient and of the\n"
10691 " ctmc stages of env: false is ode23 at RelTol\n"
10692 " 1e-3, true (default) the stiff integrator\n"
10693 " --max-states <n> truncation level of an OPEN agent's queue-length\n"
10694 " dimension (ag), options.config.maxStates;\n"
10695 " default 100. A closed class is bounded by its\n"
10696 " own population instead, and --method inapinf\n"
10697 " ignores the level and solves the open agents on\n"
10698 " the infinite state space\n"
10699 " --fork-join <arm> which fork-join transform the mean-value fixed\n"
10700 " point takes (mva, nc): default|mmt|fjt is the\n"
10701 " MMT transform, ht|heidelberger-trivedi the\n"
10702 " Heidelberger-Trivedi one, which is CLOSED\n"
10703 " models only and a different answer to the same\n"
10704 " model rather than a faster route to one\n"
10705 " --cutoff <n|matrix> open jobs per class in the CTMC state space;\n"
10706 " a matrix is per (station,class), '1,1,0;3,3,0;0,0,3'\n"
10707 " (ctmc); without it the reference's\n"
10708 " ceil(6000^(1/(M*K))) is used and reported.\n"
10709 " Also the level truncation of mam -a prob,\n"
10710 " whose open queue has no bound of its own\n"
10711 " --fj-accuracy <n> FJ_codes truncation C of the queue-length\n"
10712 " difference between the two fork-join\n"
10713 " branches (mam, homogeneous fork-join);\n"
10714 " default 100, larger is more accurate\n"
10715 " --fj-tmode <mode> how that approximation solves for its T\n"
10716 " matrix: NARE (default) or Sylvester\n"
10717 " --sync-phases <n> synchronous phase expansion of mam\n"
10718 " --method sync.faster|sync.slower; 0 (default)\n"
10719 " solves without expansion, n >= 1 needs a\n"
10720 " deterministic service and tightens both bounds\n"
10721 " --ispn-place <p> unbounded place of mam --method ispn (a place\n"
10722 " name, or place.class); default: the one level\n"
10723 " no S-invariant covers\n"
10724 " --ispn-maxlevel <n> largest level window mam --method ispn explores\n"
10725 " before refusing the net (default 200)\n"
10726 " --censor-level <s> level station of mam --method censor, a station\n"
10727 " name or a 1-based station index; default: each\n"
10728 " station by decreasing job-count range\n"
10729 " --mapmsg-quantization <n>\n"
10730 " patience regimes of the mam MAP/M/s+G reneging\n"
10731 " analyzer; default 81, at least 2\n"
10732 " --timescale <mode> auto (default), discrete or continuous: how\n"
10733 " -s mam reads the time scale. auto lets the\n"
10734 " distributions decide; discrete raises rather\n"
10735 " than solve a model that mixes lattice and\n"
10736 " non-lattice laws. The slot is --slotlength\n"
10737 " --tspan <t0>:<t1> transient horizon (ctmc -a tranprob,\n"
10738 " mam -a tran, fluid); a bare <t1> starts at 0.\n"
10739 " For the CTMC and MAM there is no default:\n"
10740 " pi(t) on an unstated horizon is not a\n"
10741 " quantity. For the fluid solver it bounds the\n"
10742 " integration, and is what -s fluid --method kp\n"
10743 " reports its covariance AT\n"
10744 " -n, --node <n> 1-based stateful node a state query is\n"
10745 " labelled by (ctmc -a tranprob, -a sample and\n"
10746 " ssa -a sample), the\n"
10747 " queue mam -a prob reports, or the station\n"
10748 " mva -a marg reports; without it the\n"
10749 " whole network is reported (the MAM queries\n"
10750 " take the model's only Queue)\n"
10751 " -c, --class <r> 1-based job class of mva -a marg; without it\n"
10752 " every class is reported\n"
10753 " NOTE ON THE INDEX BASE: -n and -c are 1-BASED\n"
10754 " here, as every station index this CLI takes\n"
10755 " is, and 0-BASED in jline.cli.LineCLI, which\n"
10756 " indexes as Java does. The short spellings are\n"
10757 " accepted so one command line parses in both,\n"
10758 " but the SAME number names a different node --\n"
10759 " the two bridges (cpp_dispatch, jar_dispatch)\n"
10760 " each convert for their own CLI\n"
10761 " --marg-states <ns> comma-separated job counts the mva -a marg\n"
10762 " curve is evaluated at, the reference's\n"
10763 " state_m; without it each law takes its own\n"
10764 " default range (0..N_r closed, mean + 5 sigma\n"
10765 " Poisson, the 1e-10 tail geometric)\n"
10766 " --notation <form> scalar (default) | matrix, the form the ODE\n"
10767 " export writes (fluid -a odes only)\n"
10768 " --symbolic <b> computer-algebra backend of fluid -a\n"
10769 " jacobian: auto (default, searches for a\n"
10770 " line-sage-rest service), a URL, an image\n"
10771 " name, or none to differentiate locally\n"
10772 " --equilibria also ask the backend for the solutions of\n"
10773 " f(x) = 0 (fluid -a jacobian). Needs a\n"
10774 " backend: solving is not differentiating\n"
10775 " --cdf-algorithm <a> exact (default, pfqn_stdf) | rd\n"
10776 " (pfqn_stdf_heur), how the sojourn law is\n"
10777 " inverted (nc -a cdf only)\n"
10778 " --perm-engine <e> exact (default, Ryser) | spm | bethe | heur |\n"
10779 " huberlaw | adapart, the permanent estimator\n"
10780 " of nc -a sysmarg. The five approximations\n"
10781 " refuse a demand matrix with a zero entry;\n"
10782 " spm is the saddle point, whose cost does not\n"
10783 " grow with the population\n"
10784 " --env-init <p,...> initial probability of each environment stage,\n"
10785 " options.config.env_init of -s env --method\n"
10786 " occupation; default the first stage. --tspan\n"
10787 " <t1> sets its horizon, unbounded without it\n"
10788 " --tran-points <n> points on the uniform transient grid the ENV\n"
10789 " mean-field coupling sums its stage exit\n"
10790 " metrics over (env only); default 1001\n"
10791 " --state <n,...> the ENCODED state row of the node named by\n"
10792 " --node that -a prob asks about, i.e.\n"
10793 " getProb(node, state)'s second argument; without\n"
10794 " it the query is about the model's default\n"
10795 " initial state\n"
10796 " --events <n> length of ONE sampled trajectory (-a sample);\n"
10797 " default 1000. NOT --samples, which is a\n"
10798 " solver's run length\n"
10799 " --timestep <dt> fixed output step of a transient CTMC solve\n"
10800 " (-a tranprob, -a tranreward), options.timestep\n"
10801 " of ctmc_transient.m; without it the grid is the\n"
10802 " integrator's own adaptive one. It changes WHERE\n"
10803 " the solution is reported, not how it is\n"
10804 " computed: the grid points are read off the same\n"
10805 " interpolant\n"
10806 " --transient-method <m> ode (default) or fau, how the CTMC forward\n"
10807 " equation is advanced over the output grid\n"
10808 " --fau-epsilon <e> fau: probability mass the grid may discard\n"
10809 " --fau-delta <d> fau: occupancy below which a state is dropped\n"
10810 " --rate-sched <j> -s ctmc -a tran: time-varying rates, a JSON array\n"
10811 " (inline or a file) of {station, class, tgrid,\n"
10812 " rates[, nominal]}; station and class by name or\n"
10813 " 1-based index. The rate of that pair follows the\n"
10814 " piecewise-linear schedule, held at its end values\n"
10815 " outside tgrid (options.config.rate_sched)\n"
10816 " --ctmc-tv-ngrid <n> grid size of the --rate-sched propagator (100)\n"
10817 " --percentiles <p,..> levels getPerctRespT is read at (-s mam, ldes),\n"
10818 " as fractions (0.9) or percents (90); default\n"
10819 " 0.50,0.90,0.95,0.99, the reference's pers_stored\n"
10820 " (-s ldes: 10,25,50,75,90,95,99 percent)\n"
10821 " --reward-name <nm> which declared reward -a reward-value returns\n"
10822 " the value function of. REQUIRED there and never\n"
10823 " defaulted: two rewards have different value\n"
10824 " functions, and picking one would mislabel it\n"
10825 " --map-env <mode> auto (the default) | off, whether a model whose ONLY\n"
10826 " unsupported features are MAP/MMPP2/MMAP/MPH is\n"
10827 " solved through a random-environment image of the\n"
10828 " modulating chain instead of being refused. Not a\n"
10829 " -s env knob: it applies to mva, nc and fluid,\n"
10830 " which is where the refusal it replaces comes\n"
10831 " from. off restores that plain refusal\n"
10832 " --map-env-method <m> auto (default) | dec | avg | meanfield, the\n"
10833 " recombination the image is solved with. auto\n"
10834 " picks from the environment timescale; meanfield\n"
10835 " needs a stage backend and is refused by name\n"
10836 " where there is none\n"
10837 " --map-env-maxstages <n> cap on the stages map2renv draws from the\n"
10838 " modulating chain; 0, the default, takes every\n"
10839 " phase. Beyond the JAR, which has no such cap\n"
10840 " -p, --port <n> run as a solve SERVER on this port, speaking\n"
10841 " LineWebSocketServer's protocol: one WebSocket\n"
10842 " text message per connection, its first line the\n"
10843 " comma-separated argument list and its remainder\n"
10844 " the model document; the CLI's output comes back\n"
10845 " as one text message. Plaintext, one connection\n"
10846 " at a time, and -f is refused beside it\n"
10847 " -m, --maxreq <n> quit after serving n requests; without it the\n"
10848 " server runs until interrupted\n"
10849 " -h, --help the short message: the flags a first run needs\n"
10850 " --help-all this message, every option solver by solver\n"
10851 " -V, --version version string\n"
10852 " --install environment check: report which optional backends\n"
10853 " (Java/JMT, LQNS, qnsolver, SageMath) are reachable\n"
10854 "\n"
10855 "Layered models (-i lqnx|xml) additionally take:\n"
10856 " --layer-solver <s> solver run in each layer: mva (default)|nc|\n"
10857 " fluid|ssa|mam|ctmc|ldes|jmt, the C++ spelling of the\n"
10858 " reference's\n"
10859 " factory argument: LN(model, @(m) MVA(m))\n"
10860 " against LN(model, @(m) Fluid(m)). They converge\n"
10861 " to DIFFERENT fixed points, not to the same one\n"
10862 " by different routes, because each layer's\n"
10863 " results feed the next outer iteration's demands.\n"
10864 " fluid is double only and refuses a layer with a\n"
10865 " fork; ssa, ldes and jmt are NOISY, so the outer\n"
10866 " loop switches to the Robbins-Monro / Polyak-Ruppert\n"
10867 " controller, and --samples/--seed set their run\n"
10868 " length and BASE seed (layer e of iteration it runs\n"
10869 " at seed+(it-1)*nlayers+e). ldes is the native\n"
10870 " engine in process; jmt runs JSIM per layer\n"
10871 " --method <name> the LN method: default | srvn | srvn.ph |\n"
10872 " srvn.cs | flat | flat.cs | flat.ph | moment3 |\n"
10873 " mw.upper | mw.lower. srvn*/flat* choose the\n"
10874 " layering (one submodel per server, or one for\n"
10875 " all) and the encoding (.cs routing, .ph composed\n"
10876 " phase-type law); default is srvn. moment3 fits an APH to each layer's\n"
10877 " response-time CDF and convolves along the entry,\n"
10878 " which is what makes -a cdf possible; mw.*\n"
10879 " reports Majumdar-Woodside box BOUNDS on\n"
10880 " throughput and processor utilization and solves\n"
10881 " no layer at all (every other metric is NaN)\n"
10882 " --ln-transient <m> coupled (default) | decoupled, how -a tran\n"
10883 " couples the layers. decoupled freezes the\n"
10884 " inter-layer demands at the fixed point; coupled\n"
10885 " relaxes time-varying demands through the fluid\n"
10886 " rate schedule until the trajectories settle\n"
10887 " --ln-transient-channels <c> both (default) | thinkt | callservt,\n"
10888 " which inter-layer coupling the relaxation\n"
10889 " injects, for isolating one channel's share\n"
10890 " --sens-method <m> auto (default) | exact | fd, the branch each\n"
10891 " LAYER's sensitivity table takes (-a sens);\n"
10892 " the same three under -s nc -a sens\n"
10893 " --sens-scheme <s> forward (default) | central, the difference\n"
10894 " quotient of the fd branch\n"
10895 " --sens-step <h> relative rate perturbation of the fd branch,\n"
10896 " in (0,1); default 1e-4, or 1e-2 for ssa layers\n"
10897 " --no-interlocking disable the interlocking correction\n"
10898 " --interlock-method <m> ilrate (default) | refpath | none, how\n"
10899 " the interlock is tracked; refpath merges the\n"
10900 " callers that are one reference task's\n"
10901 " customers into one chain (srvn.cs only, it\n"
10902 " falls back to ilrate elsewhere, with a warning)\n"
10903 " --interlock-maxpaths <n> refpath refuses a layer carrying more\n"
10904 " reference routes into it; default 32\n"
10905 " --interlock-refpath-scope <s> merging (default) | all, whether\n"
10906 " refpath also rewrites a lone-caller layer\n"
10907 " --method nlp (alias qdamva, qd-amva) build NO layers: root\n"
10908 " the QD-AMVA laws of the whole model as one\n"
10909 " nonlinear program (-a avg only)\n"
10910 " --lld <STATION=EXPR> a smooth rate multiplier in n for a\n"
10911 " processor or task, read by nlp; repeatable\n"
10912 " --nlp-alpha <a> softmin sharpness for min(n, m); default 20\n"
10913 " --nlp-warm <k> warm sweeps the Newton ladder starts from; 0\n"
10914 " --nlp-maxiter <k> budget of the fallback descent; default 3000\n"
10915 " --nlp-fork <f> refuse (default) | exp, how nlp prices an\n"
10916 " AND-fork: E[max] of exponential branches\n"
10917 " --warmstart <w> nlp | mol, seed a LAYERED method's fixed\n"
10918 " point from the program or the Method of\n"
10919 " Layers; not with srvn.ph/flat.ph or nlp\n"
10920 " --mol-iter-max <k>, --mol-iter-tol <t>, --mol-relax-factor <w>\n"
10921 " lqn_mol's settings for --warmstart mol;\n"
10922 " defaults 200, 1e-6, 0.5\n"
10923 " --repeat <k> re-solve k times, report the best wall clock\n"
10924 " -o layers dump every layer's stations, classes, rates\n"
10925 " and routing instead of the AvgTable\n"
10926 " -a takes avg (getAvgTable), tran (getTranAvg, needs --tspan and fluid\n"
10927 " layers), sens (getSensitivityTable) and cdf (getCdfRespT, moment3).\n"
10928 " --iter_max and --iter_tol set the outer LN loop; --tol does not apply,\n"
10929 " and neither does any Network solver token.\n"
10930 "\n"
10931 "The external LQNS binary (-s lqns) additionally takes:\n"
10932 " --method <name> default | lqns | srvn | exactmva |\n"
10933 " srvn.exactmva | sim | lqsim | lqns.default.\n"
10934 " sim and lqsim run lqsim, the SIMULATOR;\n"
10935 " lqns.default is lqns with no pragma at all,\n"
10936 " which is a different fixed point and not a\n"
10937 " synonym for default\n"
10938 " --multiserver <p> conway|rolia|zhou|suri|reiser|schmidt|default\n"
10939 " (= rolia), the -Pmultiserver= pragma. Not\n"
10940 " passed to lqsim, which has no MVA to configure\n"
10941 " --samples <n> lqsim run length (-A); default 10000\n"
10942 " --timeout <s> the wall-clock budget (see the general options);\n"
10943 " the child is killed 30 s after it runs out\n"
10944 " --keep keep the working directory with model.lqnx and\n"
10945 " model.lqxo instead of removing it\n"
10946 " --verbose echo the command line and the binary's output\n"
10947 " --remote[-url <u>] solve on a host running lqns-rest instead of\n"
10948 " locally; -url implies --remote. LINE ships no\n"
10949 " LQNS binary, so this is the other way to reach\n"
10950 " one\n"
10951 " -a takes avg only: lqns computes no transient, no sensitivity and no\n"
10952 " response-time distribution. QLen is the element utilization, Util its\n"
10953 " processor utilization per server, RespT its phase-1 service time;\n"
10954 " ResidT and ArvR print NaN because lqns reports neither.\n"
10955 "\n"
10956 "The external qnsolver binary (-s lqns on a Network) additionally takes:\n"
10957 " --method <name> default | qns (both = rolia) | qns.conway |\n"
10958 " qns.rolia | qns.zhou | qns.reiser | qns.suri |\n"
10959 " qns.schmidt. The multiserver approximation,\n"
10960 " passed as qnsolver -m and only\n"
10961 " when the model HAS a multiserver station. suri\n"
10962 " and schmidt are lqns approximations: they reach\n"
10963 " the tool only on the non-product-form closed\n"
10964 " branch below, and a multiserver model on the\n"
10965 " qnsolver branch refuses them by name\n"
10966 " --multiserver <p> the same choice under its config spelling;\n"
10967 " --method wins when it names one\n"
10968 " --timeout <s> the wall-clock budget (see the general options);\n"
10969 " the child is killed 30 s after it runs out\n"
10970 " --keep keep the working directory with model.jmva and\n"
10971 " result.jmva instead of removing it\n"
10972 " -a takes avg only. The model is marshalled to the JMVA interchange\n"
10973 " format at CHAIN level and the chain results are de-aggregated back to\n"
10974 " classes, so only Queue, Delay and Source stations are expressible; any\n"
10975 " other station is refused rather than dropped. A closed model that is\n"
10976 " NOT product-form is converted with QN2LQN and delegated to lqns, as the\n"
10977 " reference does, so it also needs the lqns binary; class priorities are\n"
10978 " outside that conversion and are refused. --arith is double only, since\n"
10979 " the results arrive as the text an external binary printed.\n"
10980 "\n"
10981 "The Java Modelling Tools wrapper (-s jmt) additionally takes:\n"
10982 " --jmt-replications <n> independent JSIM runs the transient ensemble\n"
10983 " of -a tran and -a tranprob averages over\n"
10984 " (options.config.replications, default 10),\n"
10985 " replication k seeded seed+k-1. A single path\n"
10986 " is NOT E[N](t); --method jsim is one run\n"
10987 "\n"
10988 "Discrete-event simulation (-s ldes) additionally takes:\n"
10989 " --ldes-tranfilter <f> warmup filter: mser5 (default), fixed, none\n"
10990 " --ldes-warmupfrac <x> fraction the fixed filter discards (0.2)\n"
10991 " --ldes-cimethod <m> CI estimator: obm (default), bm, spectral,\n"
10992 " none\n"
10993 " --ldes-cnvgon stop on relative precision instead of on\n"
10994 " the --samples budget\n"
10995 " --ldes-cnvgtol <x> that precision target (0.05); implies\n"
10996 " --ldes-cnvgon\n"
10997 " --slotted run the analytical solver on a discrete\n"
10998 " (slotted) time scale; SolverNC routes to the\n"
10999 " discrete-time product form and refuses a model\n"
11000 " outside it\n"
11001 " --slotlength <x> the slot in model time units; implies --slotted\n"
11002 " --ldes-slotted run on a discrete (slotted) time scale; a\n"
11003 " sample off the lattice is an error, never\n"
11004 " rounded\n"
11005 " --ldes-slotlength <x> the slot (1.0); implies --ldes-slotted\n"
11006 " --ldes-replications <n> independent runs, averaged. A single path\n"
11007 " is NOT E[N](t): -a tran over an ensemble\n"
11008 " mean needs this\n"
11009 " --ldes-numthreads <n> workers for those replications\n"
11010 " --ldes-maxtime <s> wall-clock budget; the engine stops early\n"
11011 " and reports stopping=max_time\n"
11012 " --ldes-initsol <v,..> warm-start placement, station-major\n"
11013 " [st0_cl0, st0_cl1, ...]. Add --ldes-tranfilter\n"
11014 " fixed --ldes-warmupfrac 0 to reproduce\n"
11015 " initFromSolver, which assumes the placement\n"
11016 " is already a steady state\n"
11017 " --ldes-rest-url <u> solve on an LDES REST server instead of a\n"
11018 " local binary; same wire format, same numbers\n"
11019 " The model.json is forwarded to the engine BYTE FOR BYTE, so a model\n"
11020 " this port cannot itself parse (a cache with retrieval, an SPN, a\n"
11021 " polling server) is simulated exactly as the MATLAB and Python clients\n"
11022 " simulate it. -a avg, tran, cdf (the empirical response-time law),\n"
11023 " sample, reward and prob (the histogram's residence time at the declared\n"
11024 " per-class counts; --node with --state overrides one station) are\n"
11025 " served. --arith is double only.\n"
11026 "\n"
11027 "Uncertainty quantification (-s uq) additionally takes:\n"
11028 " --uq-solver <s> the engine run at each design point: mva, nc,\n"
11029 " mam, ba, ctmc, fluid or ssa. REQUIRED: UQ\n"
11030 " computes nothing itself, and defaulting it\n"
11031 " would attribute the numbers to an engine the\n"
11032 " caller never chose\n"
11033 " A model whose service or arrival process is a Prior is a FAMILY of\n"
11034 " models. UQ discretizes each Prior, solves the tensor product of the\n"
11035 " alternatives, and reports the prior-weighted expectation. Under -s uq\n"
11036 " three flags describe the DESIGN and not the engine: --method is\n"
11037 " quadrature (default, and the alias of discrete) or montecarlo,\n"
11038 " --samples the nodes per continuous Prior (11), --seed the Monte Carlo\n"
11039 " stream. The stage solver therefore keeps its own sample count and its\n"
11040 " own seed; --tol, --iter_tol, --iter_max and --cutoff pass through to\n"
11041 " it, since UQ has no convergence of its own. -a posterior prints every\n"
11042 " design point, its weight and the means it substituted, which is what\n"
11043 " says whether the expectation averaged two nearby models or two very\n"
11044 " different ones. Every other solver REFUSES a model carrying a Prior\n"
11045 " rather than lowering it to its mixture moments.\n"
11046 " -a interval answers the OTHER epistemic question, in which a\n"
11047 " parameter is bounded but not distributed: it drops the weights and\n"
11048 " keeps the endpoints. On a single-class closed model of LI\n"
11049 " single-server queues and delays it is the EXACT hull of MVA over the\n"
11050 " demand box (2*(m+2) MVA calls, no design solved at all); otherwise it\n"
11051 " falls back to the range over the solved design points, which for a\n"
11052 " continuous Prior lies strictly inside the true range. The table says\n"
11053 " which, and the fallback warns on stderr: a range that is not an\n"
11054 " enclosure must not read like one.\n"
11055 "\n"
11056 "Random environments (-s env) read an Environment model.json, whose\n"
11057 " stages each hold a Network and whose transitions carry the stage\n"
11058 " holding times. The stages are solved TRANSIENTLY and coupled: each\n"
11059 " stage starts from the queue lengths the previous one left, and the\n"
11060 " reported means are the per-stage sojourn averages blended by the\n"
11061 " environment probabilities. --method selects the coupling: meanfield\n"
11062 " (default, the reference's, carries the marginal means across a\n"
11063 " switch) or statevec|blend (carries the whole joint distribution).\n"
11064 " meanfield solves each stage with the fluid transient and is double\n"
11065 " only; statevec uniformizes a CTMC and takes the whole --arith ladder.\n"
11066 " --method avg|dec asks instead for a closed-form limit, which carries\n"
11067 " nothing across a switch and iterates nothing: avg solves ONE model\n"
11068 " whose modulated rates are their probEnv-weighted averages (exact as\n"
11069 " the environment gets fast), dec solves each stage in steady state and\n"
11070 " blends by probEnv (exact as it gets slow). A model with an\n"
11071 " environment-declared node breakdown is read from the nodeFailures\n"
11072 " block, in the expanded or the one-stage macro form.\n"
11073 " --tspan bounds the stage horizon and --tran-points its grid; --iter_tol\n"
11074 " and --iter_max drive the fixed point. RespT and ArvR print as nan\n"
11075 " because ENV computes neither -- the reference returns them as NaN too,\n"
11076 " and ResidT carries QLen/Tput.\n"
11077 "\n"
11078 "Additions specific to this port:\n"
11079 " --arith <mode> double (default) | exact | real:<digits>\n"
11080 " --list-api list the API functions ported so far, each\n"
11081 " with its access: api (callable by --api),\n"
11082 " library (no named-JSON form; reason given\n"
11083 " with -o json) or model (sn/lqn, reached via\n"
11084 " -f and -a). -o json emits one document\n"
11085 " --generate <spec> draw a random model and print it, solving\n"
11086 " nothing. <spec> is a JSON object inline, a\n"
11087 " path to one, or `-` for standard input.\n"
11088 " {\"kind\":\"network\"} draws a flat model and\n"
11089 " prints the line-model JSON document; its keys\n"
11090 " are seed, name, queues, delays, openClasses,\n"
11091 " closedClasses, schedStrat, routingStrat,\n"
11092 " distribution, cclassJobLoad,\n"
11093 " varyingServiceRates, multiServerQueues,\n"
11094 " randomCSNodes, multiChainCS and topology\n"
11095 " (rand|cyclic). A `delays` of -1, the default,\n"
11096 " lets the generator split the stations itself.\n"
11097 " {\"kind\":\"layered\"} draws an LQN and prints\n"
11098 " the .lqnx document; its keys are seed, name,\n"
11099 " clients, levels, tasks, processors,\n"
11100 " populationRange, thinkTimeRange,\n"
11101 " taskMultiRange, procMultiRange,\n"
11102 " hostDemandRange, synchCallRange (each a\n"
11103 " [lo,hi] pair), taskInfProbability and\n"
11104 " procInfProbability. Both draw from\n"
11105 " java.util.Random at `seed`, so a seeded spec\n"
11106 " reproduces; --arith is not read, since a draw\n"
11107 " is a double whatever the model is solved at.\n"
11108 " --api <name> invoke one API function directly\n"
11109 " --args <path> JSON arguments for --api; stdin when omitted\n"
11110 "\n"
11111 "Solvers and what they honour. Every model-solving solver reads -a avg,\n"
11112 "-f/-i and --method; nothing else is wired, so tolerances, iteration\n"
11113 "caps, seeds and sample counts keep their SolverOptions defaults rather\n"
11114 "than being invented here. mva and nc additionally read -a prob -- mva\n"
11115 "fits a binomial to its own means, nc returns the exact product-form\n"
11116 "probability, so the two disagree by construction. mva also reads -a\n"
11117 "marg, @SolverMVA's getProbMarg: P(n jobs of class r at station i) for\n"
11118 "every (station, class) pair, narrowed by --node / --class and evaluated\n"
11119 "at --marg-states. A closed class takes the Schmidt binomial fitted to\n"
11120 "Q(i,r); an open one takes the station's exact BCMP marginal (Poisson at\n"
11121 "an infinite server, multinomial-geometric at a queue). Both solvers read\n"
11122 "-a normconst, getProbNormConstAggr: nc reports the constant its solve\n"
11123 "already formed, mva RE-ENTERS its analyzer at method='exact', since only\n"
11124 "the exact recursion carries a G -- a model whose branch forms none, an\n"
11125 "open or mixed one above all, reports nan, as the reference does. nc also\n"
11126 "reads -a cdf,\n"
11127 "@SolverNC's getCdfRespT: the whole response-time law per (station,\n"
11128 "class) on one logarithmic grid, FCFS stations only, with\n"
11129 "--cdf-algorithm exact (pfqn_stdf, the default) or rd (pfqn_stdf_heur).\n"
11130 "nc reads -a sens as well, @NetworkSolver's getSensitivityTable: the\n"
11131 "derivative of each row's means with respect to its own service rate,\n"
11132 "selected with --sens-method / --sens-scheme / --sens-step. NC is one of\n"
11133 "the two engines whose exact branch differentiates the product-form\n"
11134 "recursion analytically, so auto takes it wherever the model is in its\n"
11135 "scope (single-server queues plus delays, not mixed) and falls back to\n"
11136 "finite differences elsewhere. NOT the -s ctmc -a sens analysis, which\n"
11137 "is getSensitivityRanking, a ranking of rate perturbations and not a\n"
11138 "table of derivatives.\n"
11139 "-a node is @NetworkSolver's getAvgNodeTable and is served by mva, nc,\n"
11140 "mam, ba and ctmc, the model solvers whose runner returns the station\n"
11141 "AvgResult it is built from. It is a DIFFERENT INDEX SPACE from -a avg,\n"
11142 "not a relabelling: the AvgTable has one row per STATION, so a\n"
11143 "ClassSwitch, Router, Fork, Join or Sink never appears in it, yet jobs\n"
11144 "flow through all of them. QLen, Util, RespT and ResidT are the station\n"
11145 "numbers scattered to their node indices and zero elsewhere -- a node\n"
11146 "that is not a station holds no jobs -- while ArvR and Tput are\n"
11147 "recomputed for every node by sn_get_node_arvr_from_tput and\n"
11148 "sn_get_node_tput_from_tput. The reference's finite-capacity-region\n"
11149 "pseudo-node rows are NOT emitted: this port's AvgResult carries no\n"
11150 "per-region queue length or utilization to fill them with.\n"
11151 "\n"
11152 "auto picks the engine\n"
11153 "with chooseSolverHeur and prints the name it picked; a branch selecting\n"
11154 "JMT or LDES refuses by name rather than substituting another. ctmc reads\n"
11155 "--cutoff and ports -a avg, prob, gen, states, tranprob, sample, reward,\n"
11156 "cdf, first-passt and sens, which are @SolverCTMC's\n"
11157 "getProbSys/getProbSysAggr and the per-station getProb/getProbAggr,\n"
11158 "getInfGen, getStateSpace, getTranProbSysAggr, sampleSys, getAvgReward,\n"
11159 "getCdfRespT, getCdfFirstPassT (state sets via --passage-from and\n"
11160 "--passage-into, as 1-based space rows '3,5' or state rows '0,2;1,1'),\n"
11161 "first-passt-moments (-a firstpasstmom, the same two sets plus\n"
11162 "--passage-orders: exact moments by one linear solve per order, so a\n"
11163 "variance or a skewness costs no truncated curve; both take --passage-taboo,\n"
11164 "a TABOO set C in the same syntax: entering it first loses the passage, the\n"
11165 "curve becomes defective and the moments conditional on B before C, and\n"
11166 "firstpasst also takes --passage-tset 't1,t2,...,inf' for its grid)\n"
11167 "and getSensitivityRanking. Its --method also takes mdd, which holds the\n"
11168 "reachable set in a decision diagram and solves K coupled level-CTMCs\n"
11169 "instead of the |S|-state generator; it serves -a avg only, having no\n"
11170 "explicit chain to answer the rest from. nc's --method also takes cftp /\n"
11171 "cftp.approx, which draw iid states from the exact stationary law of a\n"
11172 "closed single-class product-form network by coupling from the past;\n"
11173 "they serve -a avg only and their rows carry Monte Carlo error.\n"
11174 "mam ports -a avg,\n"
11175 "prob, cdf, tran and internals, which are @SolverMAM's getProb and\n"
11176 "getProbMarg (the joint (level, phase) law of the queue and its\n"
11177 "per-class marginals, truncated at --cutoff when the model is open),\n"
11178 "getCdfRespT with getPerctRespT beside it, getTranAvg over --tspan (the\n"
11179 "reference forces method ldqbd there, so --method does not select it),\n"
11180 "and getMAMResult, the M/G/1-type internals of a single queue. fluid\n"
11181 "additionally reads -a tran, -a prob, -a cdf, -a var and -a aoi, which\n"
11182 "are @SolverFLD's getTranAvg (the metrics along the trajectory, over\n"
11183 "--tspan or, without one, the horizon the reference's own adaptive loop\n"
11184 "converges at), getProbAggr (a law FITTED to the fluid means, so it does\n"
11185 "not agree with the mva or nc answer by construction), getCdfRespT (the\n"
11186 "response-time law per station and class, read off a marked-fluid\n"
11187 "integration started from the steady state), getMoments/getTranAvgVar\n"
11188 "and getAvgAoI with getCdfAoI beside it -- the last needing method mfq\n"
11189 "and the Source/Queue/Sink topology the age laws are defined for. It\n"
11190 "further reads -a odes, which is\n"
11191 "@SolverFLD/exportODEs, and --notation for the form it writes, and -a\n"
11192 "jacobian, which is @SolverFLD/getJacobian: d f_i / d x_j of the drift,\n"
11193 "differentiated locally over the structure of the system, with the\n"
11194 "equilibria beside it under --equilibria, which needs the\n"
11195 "line-sage-rest backend --symbolic names. Only the smooth methods have\n"
11196 "a Jacobian: min(n,S) has none where the regime switches, so the\n"
11197 "min-scaled drifts are refused by the factor that carries the kink.\n"
11198 "nc, ba and ctmc run\n"
11199 "under every --arith backend, nc's cftp method excepted: its sampler\n"
11200 "works in the log domain, so it refuses 'exact' by name rather than\n"
11201 "answering in a field it does not live in. mdd does run under 'exact'\n"
11202 "(its level solve drops Householder for a rational least squares there),\n"
11203 "but the LEVEL AGGREGATION is still an approximation away from product\n"
11204 "form: exact arithmetic pins the fixed point, not the model. mam is\n"
11205 "double only (its phase-type fitter\n"
11206 "needs transcendental arithmetic) and so is ssa (its sample path is\n"
11207 "generated from exponential clocks) and fluid (LSODA). ba reports a\n"
11208 "BOUND, not an estimate, and ssa a simulation carrying Monte Carlo\n"
11209 "error; neither is comparable with an exact solver except as such.\n"
11210 "\n"
11211 "Arithmetic: 'exact' computes in arbitrary-precision rationals and\n"
11212 "reports numerator and denominator alongside the double value; 'real'\n"
11213 "computes in fixed high-precision binary floating point, at 50, 100 or\n"
11214 "200 digits (a request in between is rounded up to the next tier).\n"
11215 "\n"
11216 "--api arguments are a JSON object keyed by the MATLAB parameter names,\n"
11217 "e.g. {\"L\": [[0.6,0.4]], \"N\": [2,1], \"Z\": [1,0.5]}: a 2-D array is a\n"
11218 "matrix (row-major), a 1-D array a row vector, a bare number a scalar.\n"
11219 "A JSON number is read as its shortest round-tripping decimal, so 0.6 is\n"
11220 "3/5 in exact arithmetic; pass a string such as \"1/3\" for anything else.\n",
11221 kVersion);
11222}
11223
11224/**
11225 * `--install`: the environment check, the C++ twin of MATLAB's `lineInstall`,
11226 * the JAR's `jline.cli.LineInstall` and Python's `line-install`.
11227 *
11228 * NOTHING IT LOOKS FOR IS REQUIRED. The C++ edition is header-only and its
11229 * native solvers stand alone, so every dependency probed here backs one
11230 * optional wrapper or backend. A miss is therefore a warning on stderr that
11231 * names the solvers it disables and how to install it, never an error: the
11232 * point of the command is to tell a fresh checkout which solvers it can
11233 * actually reach, not to refuse to run.
11234 *
11235 * @return true when nothing warned
11236 */
11237bool install_check() {
11238 bool has_warnings = false;
11239 // stdout is block-buffered when the check is piped or redirected while
11240 // stderr is not, so an unflushed progress line would surface AFTER the
11241 // warning it belongs to. Flush before every warning so the transcript reads
11242 // in the order the checks ran.
11243 const auto warn = [&](const std::string& text) {
11244 std::fflush(stdout);
11245 std::fprintf(stderr, "%s\n", text.c_str());
11246 std::fflush(stderr);
11247 has_warnings = true;
11248 };
11249
11250 std::printf("Checking LINE (C++)...\n");
11251 std::printf(" line-cli %s\n", kVersion);
11252
11253 std::printf("Checking Java runtime (JMT wrapper)...\n");
11254 const std::string java = line::jmt::detail::find_java();
11255 if (java.empty()) {
11256 warn("WARNING: no Java runtime was found in LINE_JAVA, JAVA_HOME or on PATH, so the "
11257 "JMT wrapper (-s jmt) cannot run. Install a JRE 8 or later.");
11258 } else {
11259 std::printf(" %s\n", java.c_str());
11260 }
11261
11262 std::printf("Checking JMT...\n");
11263 const std::string jmt_dir = line::jmt::detail::jmt_jar_path();
11264 if (jmt_dir.empty()) {
11265 // REPORTS, DOES NOT ACQUIRE: `jmt_jar_path` never downloads, and this
11266 // command must not either. An environment check that fetched 31 MiB as
11267 // a side effect of being asked would be changing the environment it is
11268 // reporting on, so the download is named here and performed by the
11269 // solver call that needs it.
11270 warn("WARNING: JMT.jar was not found, this is required by the JMT wrapper. Download it "
11271 "from https://line-solver.sourceforge.net/latest/JMT.jar into common/, or point "
11272 "LINE_JMT_DIR at the folder holding it, or set LINE_JMT_DOWNLOAD=1 to let the first "
11273 "JMT solve fetch and verify it.");
11274 } else {
11275 std::printf(" %s/JMT.jar\n", jmt_dir.c_str());
11276 }
11277
11278 std::printf("Checking LQNS...\n");
11280 const std::string banner = line::lqns::lqns_version();
11281 if (banner.empty())
11282 warn("WARNING: lqns is not installed, this is required by the LQNS wrapper (-s lqns) "
11283 "for layered models. Download it at: https://github.com/layeredqueuing/dist");
11284 else
11285 warn("WARNING: the installed lqns is too old for LINE, which needs release 6 or "
11286 "later; it reports '" + banner + "'. Upgrade it from: "
11287 "https://github.com/layeredqueuing/dist");
11288 } else {
11289 std::printf(" %s\n", line::lqns::lqns_version().c_str());
11290 }
11291
11292 std::printf("Checking qnsolver...\n");
11294 warn("WARNING: qnsolver is not installed, this is required by the qns methods of the "
11295 "LQNS wrapper (-s lqns on a Network). "
11296 "It ships with LQNS: https://github.com/layeredqueuing/dist");
11297 else
11298 std::printf(" qnsolver found\n"); // every other check reports its finding, so this one does too
11299
11300 std::printf("Checking symbolic backend (line-sage-rest)...\n");
11302 warn(std::string("WARNING: Docker is not available, so the SageMath symbolic backend "
11303 "cannot start. It is the only computer algebra system this edition "
11304 "reaches and is required by the symbolic methods of "
11305 "SolverCTMC/SolverFluid. Install Docker, then run: "
11306 "docker run -d -p 29204:8080 ") + line::sym::SYM_DOCKER_IMAGE);
11307 else {
11308 const std::string image = line::sym::sym_find_image();
11309 if (image.empty())
11310 warn(std::string("WARNING: the line-sage-rest image is not present locally, this may be "
11311 "required by some LINE methods. Pull it with: "
11312 "docker run -d -p 29204:8080 ") + line::sym::SYM_DOCKER_IMAGE);
11313 else
11314 std::printf(" %s (present locally)\n", image.c_str()); // as the JAR's check reports it
11315 }
11316
11317 if (has_warnings)
11318 std::printf("Completed. LINE has warnings.\n");
11319 else
11320 std::printf("Success. LINE is ready to use.\n");
11321 return !has_warnings;
11322}
11323
11324/**
11325 * The registry, with how each function is reached from outside the library.
11326 *
11327 * THE ACCESS COLUMN IS THE POINT. A ported function is "api" when --api (and
11328 * every host binding over it, R's api_invoke among them) can call it with named
11329 * JSON arguments, "library" when it can never be carried that way (a callable
11330 * argument, a generator passed by reference), with the reason beside it, and
11331 * "model" when it belongs to the sn/lqn domains, which operate on a model and
11332 * are reached through -f and -a rather than through --api; anything else is
11333 * "unwired", a gap the tests keep empty. Without the column a
11334 * host could list a function, call it, and only then learn it was never
11335 * callable.
11336 */
11337void list_api(const std::string& output) {
11338 if (output != "readable" && output != "json")
11339 throw line::InputError("unknown -o '" + output + "'; --list-api reports as: readable, json");
11340 const auto& reg = line::api_registry();
11341 const std::map<std::string, std::string> libonly = line::reg::api_library_only_functions();
11342 auto access_of = [&](const line::ApiEntry& e) -> std::string {
11343 if (line::reg::api_is_exposed(e.name)) return "api";
11344 if (libonly.count(e.name)) return "library";
11345 if (e.domain == "sn" || e.domain == "lqn") return "model";
11346 // Named rather than folded into "model": a registered function outside
11347 // every partition is a wiring gap, and test_cli_api holds it at zero.
11348 return "unwired";
11349 };
11350 if (output == "json") {
11351 line::reg::Json rows = line::reg::Json::array();
11352 for (const auto& e : reg) {
11354 r["function"] = e.name;
11355 r["domain"] = e.domain;
11356 line::reg::Json modes = line::reg::Json::array();
11357 for (std::size_t k = 0; k < e.arith.size(); ++k) modes.push_back(line::arith_name(e.arith[k]));
11358 r["arithmetic"] = modes;
11359 r["access"] = access_of(e);
11360 const auto it = libonly.find(e.name);
11361 r["reason"] = it == libonly.end() ? line::reg::Json(nullptr) : line::reg::Json(it->second);
11362 r["reference"] = e.reference;
11363 rows.push_back(r);
11364 }
11365 line::reg::Json doc;
11366 doc["listApi"] = rows;
11367 emit_document(doc.dump());
11368 return;
11369 }
11370 std::printf("%-24s %-8s %-24s %-8s %s\n", "function", "domain", "arithmetic", "access",
11371 "ported from");
11372 for (const auto& e : reg) {
11373 std::string modes;
11374 for (std::size_t k = 0; k < e.arith.size(); ++k) {
11375 if (k) modes += ",";
11376 modes += line::arith_name(e.arith[k]);
11377 }
11378 std::printf("%-24s %-8s %-24s %-8s %s\n", e.name.c_str(), e.domain.c_str(), modes.c_str(),
11379 access_of(e).c_str(), e.reference.c_str());
11380 }
11381 std::printf("\n%zu of ~480 API functions ported.\n", reg.size());
11382}
11383
11384/**
11385 * Read the --api argument object: from the file named by --args, or from stdin
11386 * when --args is absent. A parse failure names the source and the position, so
11387 * a malformed file is a legible error rather than an empty argument set.
11388 */
11389line::reg::Json read_api_args(const std::string& path) {
11390 std::string text;
11391 std::string source;
11392 if (path.empty()) {
11393 source = "standard input";
11394 text.assign(std::istreambuf_iterator<char>(std::cin), std::istreambuf_iterator<char>());
11395 } else {
11396 source = "'" + path + "'";
11397 std::ifstream in(path.c_str());
11398 if (!in) throw line::InputError("cannot open the --args file " + source);
11399 text.assign(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
11400 }
11401 // No --args and nothing on stdin means the caller forgot the arguments.
11402 if (text.find_first_not_of(" \t\r\n") == std::string::npos)
11403 throw line::InputError("no --api arguments given: pass --args <path> or a JSON object on "
11404 "standard input (read from " +
11405 source + ")");
11406 try {
11407 return line::reg::Json::parse(text);
11408 } catch (const line::reg::Json::parse_error& e) {
11409 throw line::InputError("malformed --api arguments in " + source + ": " + e.what());
11410 }
11411}
11412
11413/**
11414 * Read the --generate specification: inline when it starts with `{`, from
11415 * standard input when it is `-` or absent, and from a file otherwise.
11416 *
11417 * INLINE IS THE POINT. A host that already holds the spec as a string (the R
11418 * binding does, and so does an MCP tool) would otherwise have to write a
11419 * temporary file for a dozen numbers, and a `line_capi_run` caller has no
11420 * standard input to pipe it through either.
11421 */
11422line::reg::Json read_generate_spec(const std::string& arg) {
11423 std::string text;
11424 std::string source;
11425 const std::string::size_type first = arg.find_first_not_of(" \t\r\n");
11426 if (first != std::string::npos && arg[first] == '{') {
11427 source = "the --generate argument";
11428 text = arg;
11429 } else if (arg.empty() || arg == "-") {
11430 source = "standard input";
11431 text.assign(std::istreambuf_iterator<char>(std::cin), std::istreambuf_iterator<char>());
11432 } else {
11433 source = "'" + arg + "'";
11434 std::ifstream in(arg.c_str());
11435 if (!in) throw line::InputError("cannot open the --generate spec file " + source);
11436 text.assign(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
11437 }
11438 if (text.find_first_not_of(" \t\r\n") == std::string::npos)
11439 throw line::InputError("no --generate specification given: pass a JSON object inline, a "
11440 "path to one, or `-` for standard input (read from " +
11441 source + ")");
11442 try {
11443 return line::reg::Json::parse(text);
11444 } catch (const line::reg::Json::parse_error& e) {
11445 throw line::InputError("malformed --generate specification in " + source + ": " + e.what());
11446 }
11447}
11448
11449/** Read one integer spec key, refusing a value that is not a whole number. */
11450long gen_int(const line::reg::Json& j, const char* key, long dflt) {
11451 if (!j.contains(key) || j.at(key).is_null()) return dflt;
11452 const line::reg::Json& v = j.at(key);
11453 if (!v.is_number())
11454 throw line::InputError(std::string("--generate: '") + key + "' must be a number");
11455 const double d = v.get<double>();
11456 if (d != std::floor(d))
11457 throw line::InputError(std::string("--generate: '") + key + "' must be a whole number");
11458 return static_cast<long>(d);
11459}
11460
11461/** Read one real spec key. */
11462double gen_real(const line::reg::Json& j, const char* key, double dflt) {
11463 if (!j.contains(key) || j.at(key).is_null()) return dflt;
11464 const line::reg::Json& v = j.at(key);
11465 if (!v.is_number())
11466 throw line::InputError(std::string("--generate: '") + key + "' must be a number");
11467 return v.get<double>();
11468}
11469
11470/** Read one boolean spec key. */
11471bool gen_bool(const line::reg::Json& j, const char* key, bool dflt) {
11472 if (!j.contains(key) || j.at(key).is_null()) return dflt;
11473 const line::reg::Json& v = j.at(key);
11474 if (!v.is_boolean())
11475 throw line::InputError(std::string("--generate: '") + key + "' must be true or false");
11476 return v.get<bool>();
11477}
11478
11479/** Read one string spec key. */
11480std::string gen_str(const line::reg::Json& j, const char* key, const std::string& dflt) {
11481 if (!j.contains(key) || j.at(key).is_null()) return dflt;
11482 const line::reg::Json& v = j.at(key);
11483 if (!v.is_string())
11484 throw line::InputError(std::string("--generate: '") + key + "' must be a string");
11485 return v.get<std::string>();
11486}
11487
11488/** Read a two-element `[lo, hi]` range key. */
11489line::gen::Range gen_range(const line::reg::Json& j, const char* key, const line::gen::Range& dflt) {
11490 if (!j.contains(key) || j.at(key).is_null()) return dflt;
11491 const line::reg::Json& v = j.at(key);
11492 if (!v.is_array() || v.size() != 2 || !v[0].is_number() || !v[1].is_number())
11493 throw line::InputError(std::string("--generate: '") + key +
11494 "' must be a two-element array of numbers");
11495 return line::gen::Range(v[0].get<double>(), v[1].get<double>());
11496}
11497
11498/**
11499 * Refuse a spec key that is not one this kind reads.
11500 *
11501 * A TYPO IS A SILENT WRONG ANSWER OTHERWISE: `"openClases": 2` would generate a
11502 * closed model and the caller would have no way to tell it was not asked for.
11503 */
11504void gen_check_keys(const line::reg::Json& j, const char* const* allowed, std::size_t n) {
11505 for (line::reg::Json::const_iterator it = j.begin(); it != j.end(); ++it) {
11506 bool ok = false;
11507 for (std::size_t k = 0; k < n && !ok; ++k) ok = it.key() == allowed[k];
11508 if (!ok) {
11509 std::string names;
11510 for (std::size_t k = 0; k < n; ++k) {
11511 if (k) names += ", ";
11512 names += allowed[k];
11513 }
11514 throw line::InputError("--generate: unknown key '" + it.key() +
11515 "'; this kind reads: " + names);
11516 }
11517 }
11518}
11519
11520/**
11521 * The JAR CLI's `-a` spelling, mapped onto this port's token.
11522 *
11523 * `jline.cli.LineCLI` names its analyses with hyphenated, getter-shaped tokens
11524 * (`cdf-respt`, `prob-sys-aggr`, `tran-avg`) and this port names them by the
11525 * question (`cdf`, `prob`, `tran`), because one arm here answers what the JAR
11526 * splits across several: `-a prob` reports `getProbSys`, `getProbSysAggr` and
11527 * the per-station `getProb`/`getProbAggr` in ONE table, and `-a sample` walks
11528 * `sampleSys`, `sampleSysAggr` and the per-node pair in one trajectory. Both
11529 * spellings are therefore accepted and the JAR's collapse onto the arm that
11530 * already contains the answer -- a script written against the JAR CLI keeps
11531 * working, and nothing here is renamed to make that true.
11532 *
11533 * AN UNKNOWN METHOD NAME IS RETURNED UNCHANGED, not rejected here: the per-solver
11534 * whitelists downstream refuse by name and say which analyses that solver
11535 * serves, which is a better message than a table of every token in the CLI.
11536 */
11537std::string normalize_analysis(const std::string& a) {
11538 // Same question, different spelling.
11539 if (a == "cdf-respt" || a == "cdfrespt") return "cdf";
11540 if (a == "cdf-passt" || a == "cdfpasst") return "cdfpasst";
11541 if (a == "first-passt" || a == "cdf-firstpasst" || a == "cdffirstpasst") return "firstpasst";
11542 if (a == "first-passt-moments" || a == "firstpasst-moments" || a == "firstpasstmoments")
11543 return "firstpasstmom";
11544 if (a == "perct-respt" || a == "perctrespt") return "perct";
11545 if (a == "tran-avg" || a == "tranavg") return "tran";
11546 if (a == "tran-cdf-respt" || a == "trancdfrespt") return "trancdf";
11547 if (a == "tran-cdf-passt" || a == "trancdfpasst") return "trancdfpasst";
11548 if (a == "tran-prob" || a == "tranprob-sys-aggr") return "tranprob";
11549 if (a == "generator") return "gen";
11550 if (a == "state-space" || a == "statespace") return "states";
11551 if (a == "reward-steady" || a == "rewardsteady") return "reward";
11552 if (a == "reward-value" || a == "rewardvalue") return "rewardvalue";
11553 if (a == "node-chain" || a == "node-chain-table") return "nodechain";
11554 if (a == "fj-table" || a == "avg-fj" || a == "fjavgt") return "fj";
11555 // The JAR's four probability getters and its four samplers, each answered
11556 // whole by one arm here. Collapsing them is not a loss: the arm emits every
11557 // one of the four, so a caller asking for the aggregate receives it beside
11558 // the joint rather than instead of it.
11559 if (a == "prob-aggr" || a == "prob-sys" || a == "prob-sys-aggr") return "prob";
11560 if (a == "prob-marg" || a == "probmarg") return "marg";
11561 if (a == "prob-sys-marg" || a == "probsysmarg" || a == "sys-marg") return "sysmarg";
11562 if (a == "sample-aggr" || a == "sample-sys" || a == "sample-sys-aggr") return "sample";
11563 // `getStageTable` IS `getAvgTable` on a Network model, in the reference and
11564 // in the JAR both: a network has one implicit stage, and only an
11565 // Environment has several. Mapped here rather than given an arm of its own,
11566 // because an arm would be a second name for one table and free to drift
11567 // from it.
11568 if (a == "stage") return "avg";
11569 return a;
11570}
11571
11572/** `-a` split on commas, each token normalized; never empty. */
11573std::vector<std::string> analysis_list(const std::string& spec) {
11574 std::vector<std::string> out;
11575 std::size_t at = 0;
11576 while (at <= spec.size()) {
11577 const std::size_t comma = spec.find(',', at);
11578 std::string tok =
11579 spec.substr(at, comma == std::string::npos ? std::string::npos : comma - at);
11580 // A stray space around a comma is a typo, not a different analysis.
11581 while (!tok.empty() && std::isspace(static_cast<unsigned char>(tok.front())))
11582 tok.erase(tok.begin());
11583 while (!tok.empty() && std::isspace(static_cast<unsigned char>(tok.back())))
11584 tok.pop_back();
11585 if (tok.empty())
11586 throw line::InputError("-a takes a comma-separated list of analyses and one entry of '" +
11587 spec + "' is empty");
11588 // `all` is the JAR's composite of the station table and the system one,
11589 // expanded HERE rather than inside a solver arm so every downstream
11590 // whitelist sees the two analyses it already knows.
11591 if (normalize_analysis(tok) == "all") {
11592 out.push_back("avg");
11593 out.push_back("sys");
11594 } else {
11595 out.push_back(normalize_analysis(tok));
11596 }
11597 if (comma == std::string::npos) break;
11598 at = comma + 1;
11599 }
11600 if (out.empty()) throw line::InputError("-a takes at least one analysis");
11601 return out;
11602}
11603
11604struct Options {
11605 std::string file, input = "json", output = "readable", solver = "auto", analysis = "avg";
11606 std::string arith = "double", api, args;
11607 bool help = false, help_all = false, version = false, list = false;
11608 /**
11609 * `--find-solver [metric]`: report which solvers and methods can analyze the
11610 * model named by -f, and exit without solving it.
11611 *
11612 * `find_solver_all` is `--find-solver-all`, which keeps the refused pairs
11613 * and the reason each was refused. The report is arithmetic-independent --
11614 * it asks feature sets and shapes, not numbers -- so it always reads the
11615 * model at double and ignores --arith.
11616 */
11617 bool find_solver = false, find_solver_all = false;
11618 std::string find_solver_metric;
11619 /** `--install`: run the environment check and exit, solving nothing. */
11620 bool install = false;
11621 /**
11622 * `--generate <spec>`: draw a random model from a JSON specification and
11623 * print it, solving nothing.
11624 *
11625 * The spec is taken INLINE when it starts with `{`, from standard input
11626 * when it is `-` or empty, and from a file otherwise, so a host that has
11627 * the spec in a string never has to stage a file for it. `generate_given`
11628 * rather than a non-empty test, because `--generate ""` means "read stdin"
11629 * and is not the same as not passing the flag.
11630 */
11631 std::string generate;
11632 bool generate_given = false;
11633 /**
11634 * Whether -i was actually passed.
11635 *
11636 * Without it a `.lqnx` path could not be recognised: `input` defaults to
11637 * json, and a defaulted json is indistinguishable from an explicit one, so
11638 * the extension sniff below would either never fire or would override a
11639 * caller who said `-i json` deliberately.
11640 */
11641 bool input_given = false;
11642 /**
11643 * `-p/--port` and `-m/--maxreq`: server mode.
11644 *
11645 * `port == 0` is "not given" and not "port 0": binding port 0 asks the
11646 * kernel for an ephemeral one, which a caller who typed no port did not
11647 * ask for. `maxreq == 0` is unbounded, matching the JAR's documented
11648 * "quit after this many requests" with no cap by default.
11649 */
11650 int port = 0;
11651 int maxreq = 0;
11652 Knobs knobs;
11653};
11654
11655/** Whether `file` ends in one of JMT's three simulation-document extensions. */
11656bool has_jsim_extension(const std::string& file) {
11657 const std::string::size_type dot = file.find_last_of('.');
11658 if (dot == std::string::npos) return false;
11659 std::string ext = file.substr(dot + 1);
11660 for (std::size_t i = 0; i < ext.size(); ++i)
11661 ext[i] = static_cast<char>(std::tolower(static_cast<unsigned char>(ext[i])));
11662 return ext == "jsim" || ext == "jsimg" || ext == "jsimw";
11663}
11664
11665/** Whether `file` ends in the PNML extension. */
11666bool has_pnml_extension(const std::string& file) {
11667 const std::string::size_type dot = file.find_last_of('.');
11668 if (dot == std::string::npos) return false;
11669 std::string ext = file.substr(dot + 1);
11670 for (std::size_t i = 0; i < ext.size(); ++i)
11671 ext[i] = static_cast<char>(std::tolower(static_cast<unsigned char>(ext[i])));
11672 return ext == "pnml";
11673}
11674
11675/** Whether `file` ends in one of the layered model's XML extensions (`.lqn` also holds SRVN text, see is_srvn_path). */
11676bool has_lqn_extension(const std::string& file) {
11677 const std::string::size_type dot = file.find_last_of('.');
11678 if (dot == std::string::npos) return false;
11679 std::string ext = file.substr(dot + 1);
11680 for (std::size_t i = 0; i < ext.size(); ++i)
11681 ext[i] = static_cast<char>(std::tolower(static_cast<unsigned char>(ext[i])));
11682 return ext == "lqnx" || ext == "xml" || ext == "lqn";
11683}
11684
11685Options parse_args(int argc, char** argv) {
11686 Options o;
11687 for (int i = 1; i < argc; ++i) {
11688 std::string a = argv[i];
11689 auto next = [&](const char* what) -> std::string {
11690 if (i + 1 >= argc) throw line::InputError(std::string("missing value after ") + what);
11691 const char* v = argv[++i];
11692 // a flag carrying a config key with listed values takes only those (doc/line-config.schema.json)
11694 if (k && !line::solvers::config_value_ok(*k, v))
11695 throw line::InputError(line::ErrorKind{"ConfigInvalid"}, std::string(what) + " (options.config." + k->name + ") expects one of " +
11696 k->values + "; got '" + v + "'");
11697 return v;
11698 };
11699 if (a == "-h" || a == "--help") o.help = true;
11700 else if (a == "--help-all" || a == "--help-full") o.help_all = true;
11701 else if (a == "-V" || a == "--version") o.version = true;
11702 else if (a == "--install") o.install = true;
11703 else if (a == "--list-api") o.list = true;
11704 else if (a == "--generate") {
11705 // The value is OPTIONAL: a bare --generate reads the spec from
11706 // standard input, as --api does with its --args.
11707 o.generate_given = true;
11708 // A lone `-` IS the value (it names standard input); anything
11709 // else beginning with `-` is the next flag.
11710 if (i + 1 < argc && (argv[i + 1][0] != '-' || argv[i + 1][1] == '\0'))
11711 o.generate = argv[++i];
11712 }
11713 else if (a == "--find-solver" || a == "--find-method" || a == "--help-model") {
11714 o.find_solver = true;
11715 // The metric is OPTIONAL, so it is taken only when the next token is
11716 // not itself a flag: `--find-solver -f m.json` must not swallow -f.
11717 if (i + 1 < argc && argv[i + 1][0] != '-') o.find_solver_metric = argv[++i];
11718 } else if (a == "--find-solver-all" || a == "--find-method-all") {
11719 o.find_solver = true;
11720 o.find_solver_all = true;
11721 if (i + 1 < argc && argv[i + 1][0] != '-') o.find_solver_metric = argv[++i];
11722 }
11723 else if (a == "-f" || a == "--file") o.file = next("-f");
11724 else if (a == "-i" || a == "--input") { o.input = next("-i"); o.input_given = true; }
11725 else if (a == "-o" || a == "--output") o.output = next("-o");
11726 else if (a == "-s" || a == "--solver") o.solver = next("-s");
11727 else if (a == "-a" || a == "--analysis") o.analysis = next("-a");
11728 else if (a == "--arith") o.arith = next("--arith");
11729 else if (a == "-p" || a == "--port") {
11730 const std::string v = next("-p");
11731 const long n = std::atol(v.c_str());
11732 if (n < 1 || n > 65535)
11733 throw line::InputError("-p takes a TCP port in 1..65535 (got '" + v + "')");
11734 o.port = static_cast<int>(n);
11735 } else if (a == "-m" || a == "--maxreq") {
11736 const std::string v = next("-m");
11737 const long n = std::atol(v.c_str());
11738 if (n < 1)
11739 throw line::InputError(
11740 "-m is the number of requests the server serves before quitting and must be "
11741 "positive; omit it to serve indefinitely (got '" + v + "')");
11742 o.maxreq = static_cast<int>(n);
11743 }
11744 else if (a == "--api") o.api = next("--api");
11745 else if (a == "--args") o.args = next("--args");
11746 else if (a == "--method") o.knobs.method = next("--method");
11747 else if (a == "--qrf-params") o.knobs.qrf_params = next("--qrf-params");
11748 else if (a == "--qrf-alpha") o.knobs.qrf_alpha = next("--qrf-alpha");
11749 else if (a == "--level") {
11750 const std::string v = next("--level");
11751 const int lv = std::atoi(v.c_str());
11752 if (lv < 1) throw line::InputError("--level must be a positive integer (got '" + v + "')");
11753 o.knobs.level = lv;
11754 }
11755 else if (a == "--samples") {
11756 const std::string v = next("--samples");
11757 const double d = std::atof(v.c_str()); // accepts 1e6 as well as 1000000
11758 if (!(d >= 1.0))
11759 throw line::InputError("--samples must be a positive count (got '" + v + "')");
11760 o.knobs.samples = static_cast<std::size_t>(d);
11761 } else if (a == "-d" || a == "--seed") {
11762 const std::string v = next("--seed");
11763 o.knobs.seed = std::strtoul(v.c_str(), nullptr, 10);
11764 if (o.knobs.seed == 0)
11765 throw line::InputError("--seed must be a positive integer (got '" + v + "')");
11766 } else if (a == "--warmupfrac") {
11767 const std::string v = next("--warmupfrac");
11768 const double f = std::atof(v.c_str());
11769 if (!(f >= 0.0 && f < 1.0))
11770 throw line::InputError(
11771 "--warmupfrac is the fraction of the path discarded before the means are "
11772 "taken and must lie in [0,1) (got '" + v + "')");
11773 o.knobs.warmupfrac = f;
11774 } else if (a == "--pstar") {
11775 const std::string v = next("--pstar");
11776 const double ps = std::atof(v.c_str());
11777 if (!(ps > 0.0))
11778 throw line::InputError(
11779 "--pstar is the exponent of the fluid p-norm smoothing and must be positive "
11780 "(got '" + v + "')");
11781 o.knobs.pstar = ps;
11782 } else if (a == "--fluid-boundary") {
11783 const std::string v = next("--fluid-boundary");
11784 if (v != "reflect" && v != "diffusion")
11785 throw line::InputError(line::ErrorKind{"ConfigInvalid"},
11786 "--fluid-boundary (options.config.fluid_boundary) is 'reflect' (a fluid level held at a "
11787 "bound is the bound) or 'diffusion' (the mean of a reflected Brownian motion); got '" + v +
11788 "'");
11789 o.knobs.fluid_boundary = v;
11790 } else if (a == "--nonmkv") {
11791 const std::string v = next("--nonmkv");
11792 line::api::nonmkv_enabled(v); // refuses a name other than bernstein or none
11793 o.knobs.nonmkv = v;
11794 } else if (a == "--busyperiod" || a == "--busyperiod-subnet") {
11795 // Same all-or-nothing parse as --marg-states: an entry dropped from
11796 // the list is a DIFFERENT report, not a shorter one.
11797 const bool orders = (a == "--busyperiod");
11798 const std::string v = next(orders ? "--busyperiod" : "--busyperiod-subnet");
11799 std::vector<std::size_t>& into = orders ? o.knobs.busy_orders : o.knobs.busy_subnet;
11800 std::size_t at = 0;
11801 while (at <= v.size()) {
11802 const std::size_t comma = v.find(',', at);
11803 const std::string tok =
11804 v.substr(at, comma == std::string::npos ? std::string::npos : comma - at);
11805 if (tok.empty() || tok.find_first_not_of("0123456789") != std::string::npos ||
11806 std::atol(tok.c_str()) < 1)
11807 throw line::InputError(
11808 std::string(orders ? "--busyperiod takes a comma-separated list of "
11809 "positive orders"
11810 : "--busyperiod-subnet takes a comma-separated list of "
11811 "1-based station indexes") +
11812 " (got '" + v + "')");
11813 into.push_back(static_cast<std::size_t>(std::atol(tok.c_str())));
11814 if (comma == std::string::npos) break;
11815 at = comma + 1;
11816 }
11817 } else if (a == "--tol") o.knobs.tol = std::atof(next("--tol").c_str());
11818 else if (a == "--iter_tol") o.knobs.iter_tol = std::atof(next("--iter_tol").c_str());
11819 else if (a == "--iter_max") o.knobs.iter_max = std::atoi(next("--iter_max").c_str());
11820 else if (a == "--stiff") {
11821 const std::string v = next("--stiff");
11822 if (v == "true") o.knobs.stiff = 1;
11823 else if (v == "false") o.knobs.stiff = 0;
11824 else throw line::InputError("--stiff takes true or false (got '" + v + "')");
11825 }
11826 else if (a == "--max-states") {
11827 const std::string v = next("--max-states");
11828 const long long n = std::atoll(v.c_str());
11829 if (n <= 0)
11830 throw line::InputError(
11831 "--max-states truncates an open agent's queue-length dimension and takes a "
11832 "positive state count (got '" + v + "')");
11833 o.knobs.max_states = n;
11834 }
11835 else if (a == "--multiserver") o.knobs.multiserver = next("--multiserver");
11836 else if (a == "--fork-join" || a == "--fork_join")
11837 o.knobs.fork_join = next("--fork-join");
11838 else if (a == "--tran-points" || a == "--tran_points") {
11839 const std::string v = next("--tran-points");
11840 const long n = std::atol(v.c_str());
11841 if (n < 2)
11842 throw line::InputError(
11843 "--tran-points is the number of points on the transient grid and needs at "
11844 "least two, a start and an end (got '" + v + "')");
11845 o.knobs.tran_points = static_cast<std::size_t>(n);
11846 }
11847 else if (a == "--mdd-tol" || a == "--mdd_tol") {
11848 const std::string v = next("--mdd-tol");
11849 const double d = std::atof(v.c_str());
11850 if (!(d > 0.0))
11851 throw line::InputError("--mdd-tol must be a positive tolerance (got '" + v + "')");
11852 o.knobs.mdd_tol = d;
11853 } else if (a == "--mdd-maxiter" || a == "--mdd_maxiter") {
11854 const std::string v = next("--mdd-maxiter");
11855 const long n = std::atol(v.c_str());
11856 if (n < 1)
11857 throw line::InputError(
11858 "--mdd-maxiter must be a positive sweep count (got '" + v + "')");
11859 o.knobs.mdd_maxiter = static_cast<int>(n);
11860 }
11861 else if (a == "--fj-accuracy") {
11862 const std::string v = next("--fj-accuracy");
11863 const long n = std::atol(v.c_str());
11864 if (n < 1)
11865 throw line::InputError(
11866 "--fj-accuracy is the FJ_codes truncation C of the queue-length difference "
11867 "between the two fork-join branches and must be at least 1 (got '" + v + "')");
11868 o.knobs.fj_accuracy = static_cast<int>(n);
11869 } else if (a == "--fj-tmode") {
11870 const std::string v = next("--fj-tmode");
11871 if (v != "NARE" && v != "Sylvester")
11872 throw line::InputError(
11873 "--fj-tmode selects how computeT.m solves for the T matrix and is 'NARE' (the "
11874 "Riccati route, the default) or 'Sylvester' (the fixed-point iteration); got '" +
11875 v + "'");
11876 o.knobs.fj_tmode = v;
11877 } else if (a == "--sync-phases") {
11878 const std::string v = next("--sync-phases");
11879 char* end = nullptr;
11880 const long n = std::strtol(v.c_str(), &end, 10);
11881 if (v.empty() || end == nullptr || *end != '\0' || n < 0)
11882 throw line::InputError(
11883 "--sync-phases is the number of phases of the synchronous phase expansion and "
11884 "must be a non-negative integer (got '" + v + "')");
11885 o.knobs.sync_phases = static_cast<int>(n);
11886 } else if (a == "--ispn-place") {
11887 o.knobs.ispn_place = next("--ispn-place");
11888 if (o.knobs.ispn_place.empty())
11889 throw line::InputError("--ispn-place needs a place name");
11890 } else if (a == "--ispn-maxlevel") {
11891 const std::string v = next("--ispn-maxlevel");
11892 char* end = nullptr;
11893 const long n = std::strtol(v.c_str(), &end, 10);
11894 if (v.empty() || end == nullptr || *end != '\0' || n < 1)
11895 throw line::InputError(
11896 "--ispn-maxlevel is the largest explored level window of the ispn method and "
11897 "must be a positive integer (got '" + v + "')");
11898 o.knobs.ispn_maxlevel = static_cast<int>(n);
11899 } else if (a == "--censor-level") {
11900 const std::string v = next("--censor-level");
11901 if (v.empty())
11902 throw line::InputError(line::ErrorKind{"Argument"},
11903 "--censor-level needs a station name or a 1-based station index");
11904 char* end = nullptr;
11905 const double x = std::strtod(v.c_str(), &end);
11906 if (end != nullptr && *end == '\0') {
11907 o.knobs.censor_level_index = x;
11908 o.knobs.censor_level.clear();
11909 } else {
11910 o.knobs.censor_level = v;
11911 o.knobs.censor_level_index.reset();
11912 }
11913 } else if (a == "--mapmsg-quantization") {
11914 const std::string v = next("--mapmsg-quantization");
11915 char* end = nullptr;
11916 const long n = std::strtol(v.c_str(), &end, 10);
11917 if (v.empty() || end == nullptr || *end != '\0' || n < 2)
11918 throw line::InputError(
11919 "--mapmsg-quantization is the number of patience regimes of the MAP/M/s+G "
11920 "reneging analyzer and must be an integer of at least 2 (got '" + v + "')");
11921 o.knobs.mapmsg_quantization = static_cast<int>(n);
11922 } else if (a == "--timescale") {
11923 const std::string v = next("--timescale");
11924 if (v != "auto" && v != "discrete" && v != "continuous")
11925 throw line::InputError(
11926 "--timescale decides whether the model is read on a slot lattice and is "
11927 "'auto' (the default), 'discrete' or 'continuous'; got '" + v + "'");
11928 o.knobs.timescale = v;
11929 }
11930 else if (a == "--force") {
11931 o.knobs.force = true;
11932 }
11933 else if (a == "--cutoff") {
11934 const std::string v = next("--cutoff");
11935 if (v.find(',') != std::string::npos || v.find(';') != std::string::npos) {
11936 o.knobs.cutoff_mat = parse_cutoff_matrix(v);
11937 if (o.knobs.cutoff_mat.empty())
11938 throw line::InputError(
11939 "--cutoff takes a number or a per-(station,class) matrix written "
11940 "'r1c1,r1c2;r2c1,r2c2' (got '" + v + "')");
11941 } else {
11942 const double d = std::atof(v.c_str());
11943 if (!(d >= 1.0))
11944 throw line::InputError(
11945 "--cutoff must be a positive job count per open class (got '" + v + "')");
11946 o.knobs.cutoff = d;
11947 }
11948 } else if (a == "--tspan" || a == "--timespan") {
11949 const std::string v = next("--tspan");
11950 // BOTH SEPARATORS. This port has always written the horizon
11951 // `t0:t1`, and `jline.cli.LineCLI --timespan` has always written it
11952 // `t0,t1`; accepting only one made a command line that names a
11953 // horizon unportable between the two CLIs even after the flag names
11954 // were reconciled.
11955 std::string::size_type sep = v.find(':');
11956 if (sep == std::string::npos) sep = v.find(',');
11957 // A bare value is the END of the horizon and starts at 0, which is
11958 // what a transient from the initial state means; `t0:t1` states both.
11959 const double lo = sep == std::string::npos ? 0.0 : std::atof(v.substr(0, sep).c_str());
11960 const double hi = std::atof(
11961 (sep == std::string::npos ? v : v.substr(sep + 1)).c_str());
11962 // An INFINITE horizon is refused here rather than integrated to:
11963 // pi(t) on [0, Inf) is the stationary vector, which -a avg reports.
11964 if (!(hi > lo) || !(lo >= 0.0) || !std::isfinite(hi))
11965 throw line::InputError(
11966 "--tspan must be a finite horizon 0 <= t0 < t1, given as <t1>, <t0>:<t1> or "
11967 "<t0>,<t1> (got '" + v + "')");
11968 o.knobs.t0 = lo;
11969 o.knobs.t1 = hi;
11970 } else if (a == "-n" || a == "--node") {
11971 const std::string v = next("--node");
11972 const long n = std::atol(v.c_str());
11973 if (n < 1)
11974 throw line::InputError("--node must be a positive 1-based node index (got '" + v +
11975 "')");
11976 o.knobs.node = static_cast<std::size_t>(n);
11977 } else if (a == "-c" || a == "--class") {
11978 const std::string v = next("--class");
11979 const long c = std::atol(v.c_str());
11980 if (c < 1)
11981 throw line::InputError("--class must be a positive 1-based class index (got '" + v +
11982 "')");
11983 o.knobs.jobclass = static_cast<std::size_t>(c);
11984 } else if (a == "--marg-states" || a == "--marg_states") {
11985 // Every entry must parse: a dropped one shortens the curve silently.
11986 const std::string v = next("--marg-states");
11987 std::size_t at = 0;
11988 while (at <= v.size()) {
11989 const std::size_t comma = v.find(',', at);
11990 const std::string tok =
11991 v.substr(at, comma == std::string::npos ? std::string::npos : comma - at);
11992 if (tok.empty() || tok.find_first_not_of("0123456789") != std::string::npos)
11993 throw line::InputError(
11994 "--marg-states takes a comma-separated list of non-negative job counts "
11995 "(got '" + v + "')");
11996 o.knobs.marg_states.push_back(std::atol(tok.c_str()));
11997 if (comma == std::string::npos) break;
11998 at = comma + 1;
11999 }
12000 } else if (a == "--state") {
12001 // Same all-or-nothing discipline as --marg-states: a state vector
12002 // with one entry dropped is a DIFFERENT state, not a shorter one,
12003 // and the length is checked against the node's own space later.
12004 const std::string v = next("--state");
12005 std::size_t at = 0;
12006 while (at <= v.size()) {
12007 const std::size_t comma = v.find(',', at);
12008 const std::string tok =
12009 v.substr(at, comma == std::string::npos ? std::string::npos : comma - at);
12010 if (tok.empty() || tok.find_first_not_of("0123456789") != std::string::npos)
12011 throw line::InputError(
12012 "--state is the state vector -a prob asks about and takes a "
12013 "comma-separated list of non-negative counts (got '" + v + "')");
12014 o.knobs.state.push_back(std::atol(tok.c_str()));
12015 if (comma == std::string::npos) break;
12016 at = comma + 1;
12017 }
12018 } else if (a == "--events") {
12019 const std::string v = next("--events");
12020 const double d = std::atof(v.c_str()); // accepts 5e3 as well as 5000
12021 if (!(d >= 1.0))
12022 throw line::InputError(
12023 "--events is the length of a sampled trajectory and must be a positive event "
12024 "count (got '" + v + "')");
12025 o.knobs.events = static_cast<std::size_t>(d);
12026 } else if (a == "--timestep") {
12027 const std::string v = next("--timestep");
12028 const double d = std::atof(v.c_str());
12029 if (!(d > 0.0) || !std::isfinite(d))
12030 throw line::InputError(
12031 "--timestep is the fixed output step of a transient analysis and must be a "
12032 "positive finite time (got '" + v + "')");
12033 o.knobs.timestep = d;
12034 } else if (a == "--percentiles") {
12035 const std::string v = next("--percentiles");
12036 std::size_t at = 0;
12037 while (at <= v.size()) {
12038 const std::size_t comma = v.find(',', at);
12039 const std::string tok =
12040 v.substr(at, comma == std::string::npos ? std::string::npos : comma - at);
12041 if (tok.empty())
12042 throw line::InputError(
12043 "--percentiles takes a comma-separated list of levels (got '" + v + "')");
12044 double p = std::atof(tok.c_str());
12045 // A LEVEL ABOVE 1 IS A PERCENT, below it a probability. The JAR
12046 // documents `--percentiles 50,90,95,99` and MATLAB stores
12047 // `pers_stored` as fractions, so both spellings reach this port
12048 // and the magnitude is what tells them apart. 1 itself is read
12049 // as the fraction: P(T <= t) = 1 is a level, 1% is not one
12050 // anybody asks for beside 50, 90 and 99.
12051 if (p > 1.0) p /= 100.0;
12052 if (!(p > 0.0) || !(p < 1.0))
12053 throw line::InputError(
12054 "--percentiles levels lie strictly inside (0,1) as fractions or (0,100) "
12055 "as percents; the 100th percentile of an unbounded law is not finite "
12056 "(got '" + tok + "')");
12057 o.knobs.percentiles.push_back(p);
12058 if (comma == std::string::npos) break;
12059 at = comma + 1;
12060 }
12061 } else if (a == "--reward-name" || a == "--reward_name") {
12062 o.knobs.reward_name = next("--reward-name");
12063 } else if (a == "--notation") {
12064 const std::string v = next("--notation");
12065 // The exporter validates the name; it is not defaulted here, so an
12066 // unrecognised notation is refused rather than answered with scalar.
12067 o.knobs.notation = v;
12068 } else if (a == "--symbolic") {
12069 // `sym_resolve` validates the name: auto, none, a URL or an image.
12070 // It is not defaulted here, so `--symbolic none` stays local rather
12071 // than being read as "not given" and searching anyway.
12072 o.knobs.symbolic = next("--symbolic");
12073 } else if (a == "--equilibria") o.knobs.equilibria = true;
12074 else if (a == "--perm-engine") {
12075 // The analyzer validates the name; an unrecognised engine is
12076 // refused rather than answered with exact.
12077 o.knobs.method_perm = next("--perm-engine");
12078 } else if (a == "--transient-method") {
12079 // The analyzer validates the name, so an unrecognised one is
12080 // refused rather than answered with the default.
12081 o.knobs.transient_method = next("--transient-method");
12082 } else if (a == "--rate-sched") {
12083 o.knobs.rate_sched = next("--rate-sched");
12084 } else if (a == "--ctmc-tv-ngrid") {
12085 const std::string v = next("--ctmc-tv-ngrid");
12086 const long n = std::atol(v.c_str());
12087 if (n < 2)
12088 throw line::InputError("--ctmc-tv-ngrid is the grid size of the rate_sched "
12089 "propagator and must be an integer >= 2 (got '" + v + "')");
12090 o.knobs.ctmc_tv_ngrid = static_cast<std::size_t>(n);
12091 } else if (a == "--fau-epsilon") {
12092 const std::string v = next("--fau-epsilon");
12093 const double d = std::atof(v.c_str());
12094 if (!(d > 0.0) || !std::isfinite(d))
12095 throw line::InputError(
12096 "--fau-epsilon is the probability mass the transient grid may discard and "
12097 "must be a positive finite number (got '" + v + "')");
12098 o.knobs.fau_epsilon = d;
12099 } else if (a == "--fau-delta") {
12100 const std::string v = next("--fau-delta");
12101 const double d = std::atof(v.c_str());
12102 if (!(d >= 0.0) || !std::isfinite(d))
12103 throw line::InputError(
12104 "--fau-delta is the occupancy below which a state is dropped and must be a "
12105 "nonnegative finite number (got '" + v + "')");
12106 o.knobs.fau_delta = d;
12107 } else if (a == "--cdf-algorithm") {
12108 // The analyzer validates the name; it is not defaulted here, so an
12109 // unrecognised algorithm is refused rather than answered with exact.
12110 o.knobs.cdf_algorithm = next("--cdf-algorithm");
12111 } else if (a == "--passage-from") o.knobs.passage_from = next("--passage-from");
12112 else if (a == "--passage-into") o.knobs.passage_into = next("--passage-into");
12113 else if (a == "--passage-method") o.knobs.passage_method = next("--passage-method");
12114 else if (a == "--passage-taboo") o.knobs.passage_taboo = next("--passage-taboo");
12115 else if (a == "--passage-tset") {
12116 o.knobs.passage_tset = next("--passage-tset");
12117 if (o.knobs.passage_tset.empty())
12118 throw line::InputError("--passage-tset needs at least one time ('t1,t2,...')");
12119 }
12120 else if (a == "--passage-orders")
12121 o.knobs.passage_orders = static_cast<std::size_t>(std::stoul(next("--passage-orders")));
12122 else if (a == "--no-interlocking") o.knobs.no_interlocking = true;
12123 else if (a == "--interlock-method") o.knobs.interlock_method = next("--interlock-method");
12124 else if (a == "--interlock-maxpaths")
12125 o.knobs.interlock_maxpaths = std::stod(next("--interlock-maxpaths"));
12126 else if (a == "--interlock-refpath-scope")
12127 o.knobs.interlock_refpath_scope = next("--interlock-refpath-scope");
12128 else if (a == "--lld") {
12129 // STATION=EXPR, repeatable; the expression is checked when the program is built
12130 const std::string v = next("--lld");
12131 const std::size_t eq = v.find('=');
12132 if (eq == std::string::npos || eq == 0 || eq + 1 == v.size())
12133 throw line::InputError("--lld takes STATION=EXPR, a processor or task name and an "
12134 "expression in n (got '" + v + "')");
12135 const std::string st = v.substr(0, eq);
12136 if (o.knobs.lld.count(st))
12137 throw line::InputError("--lld names station '" + st + "' twice");
12138 o.knobs.lld[st] = v.substr(eq + 1);
12139 } else if (a == "--nlp-alpha") {
12140 const std::string v = next("--nlp-alpha");
12141 const double x = std::atof(v.c_str());
12142 if (!(x > 0.0) || !std::isfinite(x))
12143 throw line::InputError("--nlp-alpha is the softmin sharpness and must be a positive finite "
12144 "number (got '" + v + "')");
12145 o.knobs.nlp_alpha = x;
12146 } else if (a == "--nlp-warm") {
12147 const long w = std::stol(next("--nlp-warm"));
12148 if (w < 0) throw line::InputError("--nlp-warm counts warm-start sweeps and must be >= 0");
12149 o.knobs.nlp_warm = w;
12150 } else if (a == "--nlp-maxiter") {
12151 const long m = std::stol(next("--nlp-maxiter"));
12152 if (m < 0) throw line::InputError("--nlp-maxiter is an iteration budget and must be >= 0");
12153 o.knobs.nlp_maxiter = m;
12154 } else if (a == "--nlp-fork") o.knobs.nlp_fork = next("--nlp-fork");
12155 else if (a == "--warmstart") o.knobs.warmstart = next("--warmstart");
12156 else if (a == "--mol-iter-max") {
12157 const long m = std::stol(next("--mol-iter-max"));
12158 if (m < 0) throw line::InputError("--mol-iter-max is an iteration budget and must be >= 0");
12159 o.knobs.mol_iter_max = m;
12160 } else if (a == "--mol-iter-tol") {
12161 const std::string v = next("--mol-iter-tol");
12162 const double x = std::atof(v.c_str());
12163 if (!(x > 0.0) || !std::isfinite(x))
12164 throw line::InputError("--mol-iter-tol must be a positive finite number (got '" + v + "')");
12165 o.knobs.mol_iter_tol = x;
12166 } else if (a == "--mol-relax-factor") {
12167 const std::string v = next("--mol-relax-factor");
12168 const double x = std::atof(v.c_str());
12169 if (!(x > 0.0) || !(x <= 1.0))
12170 throw line::InputError("--mol-relax-factor must lie in (0, 1] (got '" + v + "')");
12171 o.knobs.mol_relax_factor = x;
12172 } else if (a == "--layer-solver") o.knobs.layer_solver = next("--layer-solver");
12173 else if (a == "--stage-solver") o.knobs.stage_solver = next("--stage-solver");
12174 else if (a == "--env-init") o.knobs.env_init = next("--env-init");
12175 else if (a == "--map-env") o.knobs.map_env = next("--map-env");
12176 else if (a == "--map-env-method") o.knobs.map_env_method = next("--map-env-method");
12177 else if (a == "--map-env-maxstages")
12178 o.knobs.map_env_maxstages = static_cast<std::size_t>(std::stoul(next("--map-env-maxstages")));
12179 else if (a == "--ln-transient") o.knobs.ln_transient = next("--ln-transient");
12180 else if (a == "--ln-transient-channels")
12181 o.knobs.ln_transient_channels = next("--ln-transient-channels");
12182 else if (a == "--sens-method") o.knobs.sens_method = next("--sens-method");
12183 else if (a == "--sens-scheme") o.knobs.sens_scheme = next("--sens-scheme");
12184 else if (a == "--sens-step") {
12185 const std::string v = next("--sens-step");
12186 const double h = std::atof(v.c_str());
12187 if (!(h > 0.0) || !(h < 1.0))
12188 throw line::InputError(
12189 "--sens-step is the RELATIVE rate perturbation and must lie in (0,1) (got '" +
12190 v + "')");
12191 o.knobs.sens_step = h;
12192 }
12193 else if (a == "--uq-solver") o.knobs.uq_solver = next("--uq-solver");
12194 else if (a == "--keep") o.knobs.keep = true;
12195 else if (a == "--verbose") o.knobs.verbose = true;
12196 else if (a == "--remote") o.knobs.remote = true;
12197 else if (a == "--remote-url") {
12198 // Implies --remote: a URL given and then ignored because the flag
12199 // was forgotten would solve LOCALLY and report nothing about it.
12200 o.knobs.remote_url = next("--remote-url");
12201 o.knobs.remote = true;
12202 }
12203 else if (a == "--timeout") {
12204 // options.timeout, any solver: seconds, fractional allowed, and
12205 // `inf` is an explicit "no budget" (what the bridges send for Inf).
12206 const std::string v = next("--timeout");
12207 char* end = nullptr;
12208 const double s = std::strtod(v.c_str(), &end);
12209 if (end == v.c_str() || *end != '\0' || !(s > 0.0))
12210 throw line::InputError("--timeout is a wall-clock budget in seconds and must be "
12211 "positive, or inf for none (got '" + v + "')");
12212 o.knobs.timeout_seconds = s;
12213 }
12214 else if (a == "--repeat") {
12215 const std::string v = next("--repeat");
12216 const long n = std::atol(v.c_str());
12217 if (n < 1)
12218 throw line::InputError("--repeat must be a positive run count (got '" + v + "')");
12219 o.knobs.repeat = static_cast<int>(n);
12220 }
12221 // ---- the simulator's own knobs ------------------------------------
12222 else if (a == "--ldes-tranfilter") {
12223 const std::string v = next("--ldes-tranfilter");
12224 if (v != "mser5" && v != "fixed" && v != "none")
12225 throw line::InputError(
12226 "--ldes-tranfilter selects the warmup filter and is mser5, fixed or none (got '" +
12227 v + "')");
12228 o.knobs.ldes_tranfilter = v;
12229 }
12230 else if (a == "--ldes-warmupfrac") {
12231 const std::string v = next("--ldes-warmupfrac");
12232 const double d = std::atof(v.c_str());
12233 if (!(d >= 0.0 && d < 1.0))
12234 throw line::InputError(
12235 "--ldes-warmupfrac is the fraction of the run the fixed filter discards and "
12236 "lies in [0,1) (got '" + v + "')");
12237 o.knobs.ldes_warmupfrac = d;
12238 }
12239 else if (a == "--ldes-cimethod") {
12240 const std::string v = next("--ldes-cimethod");
12241 if (v != "obm" && v != "bm" && v != "spectral" && v != "none")
12242 throw line::InputError(
12243 "--ldes-cimethod selects the confidence-interval estimator and is obm, bm, "
12244 "spectral or none (got '" + v + "')");
12245 o.knobs.ldes_cimethod = v;
12246 }
12247 else if (a == "--ldes-cnvgon") o.knobs.ldes_cnvgon = true;
12248 else if (a == "--ldes-cnvgtol") {
12249 // Implies --ldes-cnvgon: a tolerance given and then ignored because
12250 // the switch was forgotten would run the full budget and say nothing.
12251 const std::string v = next("--ldes-cnvgtol");
12252 const double d = std::atof(v.c_str());
12253 if (!(d > 0.0 && d < 1.0))
12254 throw line::InputError(
12255 "--ldes-cnvgtol is a RELATIVE precision target and lies in (0,1) (got '" + v +
12256 "')");
12257 o.knobs.ldes_cnvgtol = d;
12258 o.knobs.ldes_cnvgon = true;
12259 }
12260 else if (a == "--ldes-slotted") o.knobs.ldes_slotted = true;
12261 else if (a == "--slotted") o.knobs.slotted = true;
12262 else if (a == "--slotlength") {
12263 // Implies --slotted, as --ldes-slotlength does for the simulator.
12264 const std::string v = next("--slotlength");
12265 const double d = std::atof(v.c_str());
12266 if (!(d > 0.0))
12267 throw line::InputError(
12268 "--slotlength is the slot of the discrete time scale and must be positive "
12269 "(got '" + v + "')");
12270 o.knobs.slotlength = d;
12271 o.knobs.slotted = true;
12272 }
12273 else if (a == "--ldes-slotlength") {
12274 // Implies --ldes-slotted, as --slotlength does on the engine's CLI.
12275 const std::string v = next("--ldes-slotlength");
12276 const double d = std::atof(v.c_str());
12277 if (!(d > 0.0))
12278 throw line::InputError(
12279 "--ldes-slotlength is the slot of the discrete time scale and must be positive "
12280 "(got '" + v + "')");
12281 o.knobs.ldes_slotlength = d;
12282 o.knobs.ldes_slotted = true;
12283 }
12284 else if (a == "--jmt-replications") {
12285 const std::string v = next("--jmt-replications");
12286 const long n = std::atol(v.c_str());
12287 if (n < 1)
12288 throw line::InputError(
12289 "--jmt-replications is a positive count of independent runs (got '" + v + "')");
12290 o.knobs.jmt_replications = static_cast<int>(n);
12291 }
12292 else if (a == "--ldes-replications") {
12293 const std::string v = next("--ldes-replications");
12294 const long n = std::atol(v.c_str());
12295 if (n < 1)
12296 throw line::InputError(
12297 "--ldes-replications is a positive count of independent runs (got '" + v + "')");
12298 o.knobs.ldes_replications = static_cast<int>(n);
12299 }
12300 else if (a == "--ldes-numthreads") {
12301 const std::string v = next("--ldes-numthreads");
12302 const long n = std::atol(v.c_str());
12303 if (n < 1)
12304 throw line::InputError(
12305 "--ldes-numthreads is a positive worker count (got '" + v + "')");
12306 o.knobs.ldes_numthreads = static_cast<int>(n);
12307 }
12308 else if (a == "--ldes-maxtime") {
12309 const std::string v = next("--ldes-maxtime");
12310 const double d = std::atof(v.c_str());
12311 if (!(d > 0.0))
12312 throw line::InputError(
12313 "--ldes-maxtime is a wall-clock budget in seconds and must be positive (got '" +
12314 v + "')");
12315 o.knobs.ldes_maxtime = d;
12316 }
12317 else if (a == "--ldes-initsol") {
12318 // A STATION-MAJOR placement, [st0_cl0, st0_cl1, ...]; the engine
12319 // reads it as the initial state and skips its default placement.
12320 const std::string v = next("--ldes-initsol");
12321 std::size_t b = 0;
12322 while (b <= v.size()) {
12323 const std::size_t e = v.find(',', b);
12324 const std::string tok =
12325 v.substr(b, e == std::string::npos ? std::string::npos : e - b);
12326 if (tok.empty())
12327 throw line::InputError(
12328 "--ldes-initsol is a comma-separated placement with no empty entry (got '" +
12329 v + "')");
12330 o.knobs.ldes_initsol.push_back(std::atof(tok.c_str()));
12331 if (e == std::string::npos) break;
12332 b = e + 1;
12333 }
12334 }
12335 else if (a == "--ldes-rest-url") o.knobs.ldes_rest_url = next("--ldes-rest-url");
12336 else if (a == "-v" || a == "--verbosity") {
12337 const std::string v = next(a.c_str());
12338 // The JAR names two levels and this port's help documents three;
12339 // all five spellings are accepted, and an unknown one is refused
12340 // rather than read as `standard`, which would silence nothing while
12341 // reporting that it had.
12342 if (v != "silent" && v != "standard" && v != "normal" && v != "debug" &&
12343 v != "verbose")
12344 throw line::InputError(
12345 "-v takes silent, standard (the JAR spells it normal) or debug; got '" + v +
12346 "'");
12347 o.knobs.verbosity = (v == "normal") ? "standard" : v;
12348 }
12349 else if (!a.empty() && a[0] == '-')
12350 throw line::InputError("unknown option: " + a);
12351 else
12352 o.file = a;
12353 }
12354 return o;
12355}
12356
12357} // namespace
12358
12359/**
12360 * `--find-solver`: which solvers and methods can analyze the model named by -f.
12361 *
12362 * It reports rather than solves, so it stops before the solver ladder in
12363 * `solve_model_dispatch` and before every knob that describes a run. The answer
12364 * is arithmetic-independent -- `auto_find_solver` asks feature sets, shapes and
12365 * gates, never numbers -- so the model is read at double whatever --arith says,
12366 * and a caller who passed one is told rather than silently obeyed.
12367 *
12368 * The layered path is not covered: `auto_find_solver` narrows the flat Network
12369 * families, and a LayeredNetwork's are `ln` and `lqns`, which this port reaches
12370 * through `solve_lqn_dispatch` and not through an AUTO of its own.
12371 */
12372int find_solver_report(const Options& o) {
12373 // A MODEL ON STDIN IS A MODEL. This used to refuse anything but `-f`, which
12374 // made the report the one part of the vocabulary a piped model could not
12375 // reach -- and `read_model` has read stdin on the empty path all along.
12376 if (o.file.empty() && !g_stdin_loaded)
12377 throw line::InputError("--find-solver reports on a model; name one with -f");
12378 const bool layered = o.file.empty()
12379 ? line::io::is_layered_json_text(stdin_model_text())
12380 : (has_lqn_extension(o.file) || line::lqn::is_srvn_path(o.file) ||
12382 if (!o.input_given && layered)
12384 "--find-solver reports on a flat Network model; a layered one is solved by -s ln "
12385 "and -s lqns, which this port reaches through the -i lqnx path");
12386 if (o.output != "readable" && o.output != "json")
12387 throw line::InputError("unknown -o '" + o.output +
12388 "'; --find-solver reports as: readable, json");
12389 line::qn::Network<double> net = read_model<double>(o.file);
12390 const std::vector<line::autosolver::SolverCandidate> rows = line::autosolver::auto_find_solver(
12391 net.get_struct(), o.find_solver_metric, o.find_solver_all);
12392 if (o.output != "json") {
12393 std::printf("%s", line::autosolver::auto_find_solver_table(rows).c_str());
12394 return 0;
12395 }
12396 // THE STRUCTURED ROWS EXIST ALREADY AND HAD NO WAY OUT. auto_find_solver
12397 // returns solver, method, runnable, the method class, the metrics and the
12398 // reason for a refusal, and the fixed-width table was the only rendering,
12399 // so every caller that wanted the reason had to parse columns. All five
12400 // front ends and the MCP `find_solver` tool benefit from this arm.
12401 line::reg::Json j = line::reg::Json::object();
12402 line::reg::Json cands = line::reg::Json::array();
12403 for (std::size_t i = 0; i < rows.size(); ++i) {
12404 line::reg::Json c = line::reg::Json::object();
12405 c["solver"] = rows[i].solver;
12406 c["method"] = rows[i].method;
12407 c["runnable"] = rows[i].runnable;
12408 c["methodClass"] = rows[i].method_class;
12409 c["reason"] = rows[i].reason;
12410 // metrics is already the comma-joined string the table prints; iterating
12411 // it pushed one character code per element.
12412 c["metrics"] = rows[i].metrics;
12413 cands.push_back(c);
12414 }
12415 line::reg::Json body = line::reg::Json::object();
12416 body["type"] = "FindSolver";
12417 body["candidates"] = cands;
12418 j["findSolver"] = body;
12419 emit_document(dump_document(j));
12420 return 0;
12421}
12422
12423/**
12424 * Everything one invocation does once the arguments are in hand.
12425 *
12426 * SPLIT OUT OF `main` FOR SERVER MODE, which runs it once per request with a
12427 * different `-f` and a captured stdout. Keeping one body means a request served
12428 * over the socket takes exactly the path the same command line takes at the
12429 * shell -- the failure this avoids is a server that answers slightly differently
12430 * from the CLI it is supposed to BE.
12431 */
12432/**
12433 * `--timeout`: the warning a solve cut short by the budget prints once, on
12434 * stderr, after its output. Not on an error: a run that raised Timeout said so
12435 * in its error line.
12436 */
12438 std::string solver;
12439 double budget;
12441 CliTimeoutReport(const std::string& s, double b)
12442 : solver(s), budget(b), uncaught(std::uncaught_exceptions()) {}
12444 if (std::uncaught_exceptions() == uncaught && line::util::timeout_tripped()) {
12445 std::string name = solver;
12446 std::transform(name.begin(), name.end(), name.begin(), ::toupper);
12447 line::util::timeout_warn("Solver" + name, budget);
12448 }
12449 }
12450};
12451
12452int run_invocation(Options o) {
12453 // --timeout, options.timeout: ONE budget for everything this invocation
12454 // solves, whichever solver; every checkpoint, wrapper and child process
12455 // below reads it off this thread's deadline stack. Declared in this
12456 // order so the report reads the latch before the frame pops.
12457 line::util::TimeoutScope cli_budget = line::util::timeout_arm(o.knobs.timeout_seconds);
12458 const CliTimeoutReport cli_timeout_report(o.solver, o.knobs.timeout_seconds);
12459 // Validated on every path, not only --api: an unrecognised --arith is a
12460 // caller error whatever else the invocation asks for.
12461 line::reg::parse_arith(o.arith);
12462 if (!o.api.empty()) {
12463 if (o.output != "readable" && o.output != "json")
12464 throw line::InputError("unknown -o '" + o.output +
12465 "'; accepted forms are: readable, json");
12466 const line::reg::Json result =
12467 line::reg::api_invoke(o.api, o.arith, read_api_args(o.args));
12468 if (o.output == "json")
12469 emit_document(dump_document(result, 2));
12470 else
12471 std::printf("%s", line::reg::api_render_readable(result).c_str());
12472 return 0;
12473 }
12474 // A .lqnx/.xml path with no -i is taken as a layered model, so naming
12475 // the file is enough to solve it. An explicit -i always wins, so a
12476 // caller who says -i json about an oddly-named file still gets json.
12477 if (!o.input_given && has_lqn_extension(o.file)) o.input = "lqnx";
12478 // The LQNS SRVN text: `.in` always, `.lqn` unless the file opens with '<' (then it is lqnx).
12479 if (!o.input_given && !o.file.empty() && line::lqn::is_srvn_path(o.file)) o.input = "srvn";
12480 // The same courtesy for a JMT document: naming the file is enough.
12481 if (!o.input_given && has_jsim_extension(o.file)) o.input = "jsimg";
12482 // And for a PNML document.
12483 if (!o.input_given && has_pnml_extension(o.file)) o.input = "pnml";
12484 // A model.json can carry EITHER model kind, and `linemodel_save` writes
12485 // `.json` for both, so the extension cannot decide it. The content can:
12486 // a `LayeredNetwork` type takes the layered path whatever `-i` says,
12487 // because handing it to the Network reader only produces "model type
12488 // 'LayeredNetwork' is not a Network" one frame further down.
12489 // THE SNIFF NOW COVERS A PIPED DOCUMENT. It took a PATH and was
12490 // therefore skipped entirely on stdin, so a LayeredNetwork arriving on
12491 // the standard input was handed to the Network reader and refused with
12492 // "the model-solving path ports -s mva, nc, ..." -- a message about the
12493 // solver, for a model the CLI could read perfectly well from a file.
12494 // Staging the text to a temporary file would have worked and would cost
12495 // a file per solve, which a host calling this in a sweep notices.
12496 const bool sniffable = o.input != "lqnx" && o.input != "xml" && o.input != "srvn" && o.input != "pnml" &&
12497 o.input.compare(0, 4, "jsim") != 0;
12498 if (sniffable && !o.file.empty() && !has_pnml_extension(o.file) &&
12499 !has_jsim_extension(o.file) && line::io::is_layered_json(o.file))
12500 o.input = "lqnx";
12501 else if (sniffable && o.file.empty() && g_stdin_loaded &&
12502 line::io::is_layered_json_text(stdin_model_text()))
12503 o.input = "lqnx";
12504 if (o.input == "lqnx" || o.input == "xml" || o.input == "srvn") {
12505 // `-i srvn` is read by TRANSLATION to .lqnx (lqn::srvn2lqnx), and every layered reader
12506 // recognises a `.in` / non-XML `.lqn` path itself. Only an SRVN file under another
12507 // extension is staged, as its translation, to a temporary document the arms can read.
12508 std::string lqn_file = o.file;
12509 std::string staged;
12510 if (o.input == "srvn" && !o.file.empty() && !line::lqn::is_srvn_path(o.file)) {
12511 const std::string doc = line::lqn::srvn_file_to_lqnx(o.file);
12512 const char* tmpdir = std::getenv("TMPDIR");
12513 std::string path = std::string(tmpdir && *tmpdir ? tmpdir : "/tmp") + "/line-cli-srvn-XXXXXX";
12514 std::vector<char> buf(path.begin(), path.end());
12515 buf.push_back('\0');
12516 const int fd = ::mkstemp(&buf[0]);
12517 if (fd < 0) throw line::InputError(line::ErrorKind{"File"}, "cannot stage the SRVN translation of " + o.file);
12518 ::close(fd);
12519 staged.assign(&buf[0]);
12520 std::ofstream(staged.c_str(), std::ios::binary) << doc;
12521 lqn_file = staged;
12522 }
12523 struct Unstage {
12524 const std::string& p;
12525 ~Unstage() { if (!p.empty()) std::remove(p.c_str()); }
12526 } unstage{staged};
12527 if (o.output != "readable" && o.output != "json" && o.output != "layers")
12528 throw line::InputError("unknown -o '" + o.output +
12529 "'; accepted forms on the layered path are: readable, "
12530 "json, layers");
12531 // ONE ENVELOPE PER ANALYSIS, in the order asked for. `-a avg,sens`
12532 // is the JAR's comma list, and the JAR merges the results into one
12533 // JSON object; here each arm prints as it computes, so the multi
12534 // form emits a sequence of the SAME envelopes a single `-a` emits
12535 // (JSON Lines). That keeps one parser for both spellings, where a
12536 // merged object would need a second one for the multi case alone.
12537 const std::vector<std::string> as = analysis_list(o.analysis);
12538 for (std::size_t i = 0; i + 1 < as.size(); ++i) {
12539 const int rc = solve_lqn_dispatch(o.arith, o.solver, as[i], o.output, lqn_file,
12540 o.knobs);
12541 if (rc != 0) return rc;
12542 poll_interrupt();
12543 }
12544 return solve_lqn_dispatch(o.arith, o.solver, as.back(), o.output, lqn_file, o.knobs);
12545 }
12546 // `-i jsim | jsimg | jsimw`: a JMT simulation document, read by
12547 // `read_jsim`. The three extensions name ONE format -- JMT writes the
12548 // same `<sim>` document under all three -- and are accepted separately
12549 // because the JAR CLI accepts them separately and a script naming the
12550 // wrong one is not describing a different model.
12551 if (o.input == "jsim" || o.input == "jsimg" || o.input == "jsimw")
12552 g_jsim_input = true;
12553 else if (o.input == "pnml")
12554 g_pnml_input = true;
12555 else if (o.input != "json")
12557 "the model-solving path reads -i json for a Network model, -i jsim|jsimg|jsimw "
12558 "for a JMT simulation document, -i pnml for a place/transition net and "
12559 "-i lqnx|xml|srvn for a layered one (got '" + o.input + "')");
12560 // `-o json` IS WIRED FOR EVERY ANALYSIS: every arm emits a payload
12561 // (`emit_analysis`) under a key named after its own `-a`, so a caller can
12562 // tell which question was answered. An arm added without a payload must
12563 // refuse `-o json`, not ignore it. On `-a avg` the solver BANNER still
12564 // precedes the object on stdout, as the JAR's does; it contains no brace,
12565 // so the wrapper's first-`{` scan is unaffected. The other arms print no
12566 // banner: what it carried -- the arithmetic, the resolved method, the
12567 // state count and the cutoff -- is inside the payload, where a host reads
12568 // it as data instead of scraping it from a line above.
12569 // `-o jsimg`: EXPORT the model as a JMT simulation document instead of
12570 // solving it. It is the missing half of a pair -- `-i jsimg` has read one
12571 // back all along -- and the C++ twin of MATLAB's `JMTIO`, the JAR's
12572 // `QN2JSIMG` and Python's `qn2jsimg`. The three spellings name ONE
12573 // format, as they do on `-i` and in JMT.
12574 if (o.output == "jsim" || o.output == "jsimg" || o.output == "jsimw") {
12575 line::qn::Network<double> net = read_model<double>(o.file);
12578 wopt.file_name = "model";
12579 wopt.log_path = sn.log_path;
12580 // The simulation controls the header carries are the ones a solve
12581 // would have written into it, so an exported document run through
12582 // JMT by hand reproduces `-s jmt` rather than the writer defaults.
12583 if (o.knobs.seed) wopt.seed = static_cast<long>(o.knobs.seed);
12584 if (o.knobs.samples) wopt.max_samples = static_cast<double>(o.knobs.samples);
12585 if (o.knobs.t1 >= 0.0) wopt.max_simulated_time = o.knobs.t1;
12586 emit_document(line::io::jmt_write_jsim<double>(sn, wopt));
12587 return 0;
12588 }
12589 if (o.output != "readable" && o.output != "json")
12590 throw line::InputError("unknown -o '" + o.output +
12591 "'; accepted forms are: readable, json, jsimg");
12592 g_json_output = (o.output == "json");
12593 // See the layered path above for why a comma list emits one envelope
12594 // per analysis rather than one merged object.
12595 const std::vector<std::string> as = analysis_list(o.analysis);
12596 for (std::size_t i = 0; i + 1 < as.size(); ++i) {
12597 const int rc = solve_model_dispatch(o.arith, o.solver, as[i], o.file, o.knobs);
12598 if (rc != 0) return rc;
12599 poll_interrupt();
12600 }
12601 return solve_model_dispatch(o.arith, o.solver, as.back(), o.file, o.knobs);
12602}
12603
12604/**
12605 * Redirect a file descriptor into a temporary file for a scope, and give back
12606 * what was written to it.
12607 *
12608 * A TEMPORARY FILE AND NOT A PIPE, which was already the choice here and is
12609 * worth keeping deliberately: a pipe holds 64 KB and nobody is draining it, so
12610 * a solve that prints more than that would deadlock against its own output.
12611 *
12612 * IT IS AN OBJECT so that the restore happens on the way out of the scope
12613 * whatever happens inside it. The server's version below did the same dance
12614 * inline and could not have survived a throw between the dup2 and the restore,
12615 * which is survivable in a one-shot process and is a leaked file descriptor
12616 * per call in a host that calls this in a loop.
12617 */
12619 public:
12620 explicit FdCapture(int fd) : fd_(fd), saved_(-1), tfd_(-1) {
12621 if (fd_ < 0) return; // "do not capture", so the object is inert
12622 const char* tmpdir = std::getenv("TMPDIR");
12623 std::string path =
12624 std::string(tmpdir && *tmpdir ? tmpdir : "/tmp") + "/line-cli-cap-XXXXXX";
12625 std::vector<char> buf(path.begin(), path.end());
12626 buf.push_back('\0');
12627 tfd_ = ::mkstemp(&buf[0]);
12628 if (tfd_ < 0) return;
12629 path_.assign(&buf[0]);
12630 std::fflush(fd_ == 1 ? stdout : stderr);
12631 saved_ = ::dup(fd_);
12632 ::dup2(tfd_, fd_);
12633 }
12634
12635 // restore() closes the descriptor; only take() removes the backing file, so a
12636 // capture abandoned by a throw would leave one behind. The server calls
12637 // run_invocation_captured once per request, so that is a leak per FAILED
12638 // request, which is the same defect the JAR CLI had in its model staging.
12639 // take() clears path_ after removing, so this is a no-op on the normal path.
12641 restore();
12642 if (!path_.empty()) {
12643 std::remove(path_.c_str());
12644 path_.clear();
12645 }
12646 }
12647
12648 /** Restore the descriptor and read back what was written. Idempotent. */
12649 std::string take() {
12650 restore();
12651 if (path_.empty()) return std::string();
12652 std::ifstream in(path_.c_str());
12653 std::string out((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
12654 in.close();
12655 std::remove(path_.c_str());
12656 path_.clear();
12657 return out;
12658 }
12659
12660 bool active() const { return saved_ >= 0; }
12661
12662 private:
12663 void restore() {
12664 if (saved_ < 0) return;
12665 std::fflush(fd_ == 1 ? stdout : stderr);
12666 ::dup2(saved_, fd_);
12667 ::close(saved_);
12668 saved_ = -1;
12669 if (tfd_ >= 0) {
12670 ::close(tfd_);
12671 tfd_ = -1;
12672 }
12673 }
12674 FdCapture(const FdCapture&);
12675 FdCapture& operator=(const FdCapture&);
12676
12677 int fd_;
12678 int saved_;
12679 int tfd_;
12680 std::string path_;
12681};
12682
12683/**
12684 * Run one invocation with stdout captured, and return what it printed.
12685 *
12686 * SERVER MODE'S ONE PIECE OF MACHINERY. Every arm of this CLI writes its answer
12687 * with `printf`, which is the right thing for a command-line tool and leaves a
12688 * server nothing to send. Redirecting fd 1 around the call means the arms need
12689 * no server-aware variant and cannot drift from the command-line behaviour;
12690 * stderr is deliberately NOT captured, so a warning still reaches the operator's
12691 * console rather than being folded into the client's answer.
12692 */
12693std::string run_invocation_captured(Options o, int& rc) {
12694 // EVERY REQUEST STARTS FROM A CLEAN SLATE. Without this a request carrying
12695 // `-i jsimg` left g_jsim_input true and poisoned every later request on the
12696 // same server, which is a live bug in shipped code rather than a
12697 // hypothetical one.
12698 reset_invocation_state(false);
12699 FdCapture cap(1);
12700 if (!cap.active()) {
12701 rc = 3;
12702 return "line-cli: cannot create a capture file for the response\n";
12703 }
12704 std::string err;
12705 try {
12706 rc = run_invocation(o);
12707 } catch (const line::Error& e) {
12708 rc = 2;
12709 err = std::string("line-cli: [") + e.id() + "] " + e.what() + "\n";
12710 } catch (const std::exception& e) {
12711 rc = 3;
12712 err = std::string("line-cli: unexpected failure: ") + e.what() + "\n";
12713 }
12714 std::string out = cap.take();
12715 // THE ERROR IS THE ANSWER when the solve failed: a client that receives an
12716 // empty message cannot tell a refusal from a model with no rows.
12717 return err.empty() ? out : out + err;
12718}
12719
12720/**
12721 * `-p/--port`: serve solve requests over a WebSocket, as `LineWebSocketServer`
12722 * does.
12723 *
12724 * THE PROTOCOL IS THE JAR's, unchanged: one text message per connection, whose
12725 * FIRST LINE is the comma-separated argument list and whose remainder is the
12726 * model document. The JAR overwrites the first two arguments with `--file` and
12727 * the path it staged the document at, so the client's own first two tokens are
12728 * placeholders; the same substitution happens here, which is what lets an
12729 * existing client talk to this server without knowing which binary answered.
12730 */
12731int run_server(const Options& base) {
12732 line::ws::Server server(base.port);
12733 std::printf("--------------------------------------------------------------------\n");
12734 std::printf("LINE Solver - Command Line Interface (C++)\n");
12735 std::printf("Copyright (c) 2012-2026, QORE Lab, Imperial College London\n");
12736 std::printf("Version %s. All rights reserved.\n", kVersion);
12737 std::printf("--------------------------------------------------------------------\n");
12738 std::printf("Running in server mode on port %d.\n", base.port);
12739 if (base.maxreq)
12740 std::printf("Quitting after %d request(s).\n", base.maxreq);
12741 std::fflush(stdout);
12742
12743 int served = 0;
12744 while (base.maxreq == 0 || served < base.maxreq) {
12745 const bool ok = server.serve_one([&](const std::string& msg) -> std::string {
12746 const std::string::size_type nl = msg.find('\n');
12747 if (nl == std::string::npos)
12748 return "line-cli: the request's first line is the argument list and its "
12749 "remainder is the model document; this message has no newline\n";
12750 const std::string argline = msg.substr(0, nl);
12751 const std::string model = msg.substr(nl + 1);
12752
12753 const char* tmpdir = std::getenv("TMPDIR");
12754 std::string path =
12755 std::string(tmpdir && *tmpdir ? tmpdir : "/tmp") + "/line-cli-req-XXXXXX";
12756 std::vector<char> nb(path.begin(), path.end());
12757 nb.push_back('\0');
12758 const int mfd = ::mkstemp(&nb[0]);
12759 if (mfd < 0) return "line-cli: cannot stage the client model\n";
12760 ::close(mfd);
12761 path.assign(&nb[0]);
12762 {
12763 std::ofstream mf(path.c_str());
12764 mf << model;
12765 }
12766
12767 // The argument list, with the first two tokens replaced by the
12768 // staged path exactly as `LineWebSocketServer.onMessage` replaces
12769 // them. A list SHORTER than two is the client's error and is
12770 // reported rather than padded, since padding would solve the
12771 // default model instead of the one it sent.
12772 std::vector<std::string> toks;
12773 std::string::size_type at = 0;
12774 while (at <= argline.size()) {
12775 const std::string::size_type comma = argline.find(',', at);
12776 toks.push_back(argline.substr(
12777 at, comma == std::string::npos ? std::string::npos : comma - at));
12778 if (comma == std::string::npos) break;
12779 at = comma + 1;
12780 }
12781 std::string result;
12782 if (toks.size() < 2) {
12783 result = "line-cli: the argument list needs at least two tokens; the first two "
12784 "are replaced by --file and the staged model path\n";
12785 } else {
12786 toks[0] = "--file";
12787 toks[1] = path;
12788 std::vector<char*> argv;
12789 std::vector<std::string> store;
12790 store.push_back("line-cli");
12791 for (std::size_t i = 0; i < toks.size(); ++i) store.push_back(toks[i]);
12792 for (std::size_t i = 0; i < store.size(); ++i)
12793 argv.push_back(const_cast<char*>(store[i].c_str()));
12794 int rc = 0;
12795 try {
12796 Options ro = parse_args(static_cast<int>(argv.size()), &argv[0]);
12797 // The server's own flags never travel into a request: a
12798 // client that sent `-p` would otherwise make the server
12799 // recurse into a second listener on the same process.
12800 ro.port = 0;
12801 ro.maxreq = 0;
12802 result = run_invocation_captured(ro, rc);
12803 } catch (const line::Error& e) {
12804 result = std::string("line-cli: [") + e.id() + "] " + e.what() + "\n";
12805 }
12806 }
12807 std::remove(path.c_str());
12808 return result;
12809 });
12810 // A dropped client is not a reason to stop serving, and it does not
12811 // count against --maxreq either: the JAR counts REQUESTS, and a peer
12812 // that vanished before sending one made none.
12813 if (ok) ++served;
12814 }
12815 return 0;
12816}
12817
12818/**
12819 * `--generate`: draw a random model and print it, solving nothing.
12820 *
12821 * `{"kind":"network", ...}` emits the `line-model` JSON document that every
12822 * reader in the project already takes, so the generated model round-trips
12823 * through `-f` and through `load_model` in R and Python without a second
12824 * format. `{"kind":"layered", ...}` emits the `.lqnx` document instead,
12825 * because that is the only interchange the layered readers all share; it is
12826 * plain text on standard output rather than a collected JSON document, since
12827 * an XML string is not one.
12828 *
12829 * THE ARITHMETIC IS ALWAYS double. Both generators draw from
12830 * `java.util.Random`, whose output is a double by definition, so generating at
12831 * `--arith exact` would fabricate an exactness the draw never had. A caller who
12832 * wants the model solved in another arithmetic reads it back with that --arith.
12833 */
12834int run_generate(const Options& o) {
12835 const line::reg::Json spec = read_generate_spec(o.generate);
12836 if (!spec.is_object())
12837 throw line::InputError("--generate takes a JSON object, e.g. "
12838 "{\"kind\":\"network\",\"queues\":3,\"closedClasses\":1}");
12839 const std::string kind = gen_str(spec, "kind", "network");
12840 if (kind == "network") {
12841 static const char* const keys[] = {
12842 "kind", "seed", "name", "queues", "delays", "openClasses", "closedClasses",
12843 "schedStrat", "routingStrat", "distribution", "cclassJobLoad", "varyingServiceRates",
12844 "multiServerQueues", "randomCSNodes", "multiChainCS", "topology"};
12845 gen_check_keys(spec, keys, sizeof(keys) / sizeof(keys[0]));
12847 if (spec.contains("seed")) g.set_seed(gen_int(spec, "seed", 0));
12848 g.set_model_name(gen_str(spec, "name", "nw"));
12849 g.set_sched_strat(gen_str(spec, "schedStrat", "randomize"));
12850 g.set_routing_strat(gen_str(spec, "routingStrat", "randomize"));
12851 g.set_distribution(gen_str(spec, "distribution", "randomize"));
12852 g.set_cclass_job_load(gen_str(spec, "cclassJobLoad", "randomize"));
12853 g.set_varying_service_rates(gen_bool(spec, "varyingServiceRates", false));
12854 g.set_multi_server_queues(gen_bool(spec, "multiServerQueues", false));
12855 g.set_random_cs_nodes(gen_bool(spec, "randomCSNodes", false));
12856 g.set_multi_chain_cs(gen_bool(spec, "multiChainCS", false));
12857 const std::string topo = gen_str(spec, "topology", "rand");
12858 if (topo == "rand")
12860 else if (topo == "cyclic")
12862 else
12863 throw line::InputError("--generate: unknown topology '" + topo +
12864 "'; accepted forms are: rand, cyclic");
12865 // `delays` defaults to -1, which is the generator's "decide for me":
12866 // it then draws the split between queues and delays itself.
12867 const long nq = gen_int(spec, "queues", 1);
12868 const long nd = gen_int(spec, "delays", -1);
12869 const long no = gen_int(spec, "openClasses", 0);
12870 const long nc = gen_int(spec, "closedClasses", 1);
12871 line::qn::Network<double> m = g.generate(static_cast<int>(nq), static_cast<int>(nd),
12872 static_cast<int>(no), static_cast<int>(nc));
12873 emit_document(line::io::network_json_envelope(m.get_struct()).dump(2));
12874 return 0;
12875 }
12876 if (kind == "layered") {
12877 static const char* const keys[] = {
12878 "kind", "seed", "name", "clients", "levels", "tasks", "processors", "populationRange",
12879 "thinkTimeRange", "taskMultiRange", "procMultiRange", "hostDemandRange",
12880 "synchCallRange", "taskInfProbability", "procInfProbability"};
12881 gen_check_keys(spec, keys, sizeof(keys) / sizeof(keys[0]));
12883 if (spec.contains("seed")) g.set_seed(gen_int(spec, "seed", 0));
12884 g.set_model_name(gen_str(spec, "name", "lnw"));
12885 g.set_population_range(gen_range(spec, "populationRange", line::gen::Range(1, 1)));
12886 g.set_think_time_range(gen_range(spec, "thinkTimeRange", line::gen::Range(1, 1)));
12887 g.set_task_multi_range(gen_range(spec, "taskMultiRange", line::gen::Range(1, 1)));
12888 g.set_proc_multi_range(gen_range(spec, "procMultiRange", line::gen::Range(1, 1)));
12889 g.set_host_demand_range(gen_range(spec, "hostDemandRange", line::gen::Range(1, 1)));
12890 g.set_synch_call_range(gen_range(spec, "synchCallRange", line::gen::Range(1, 1)));
12891 g.set_task_inf_probability(gen_real(spec, "taskInfProbability", 0.0));
12892 g.set_proc_inf_probability(gen_real(spec, "procInfProbability", 0.0));
12893 const long ncl = gen_int(spec, "clients", 1);
12894 const long nlv = gen_int(spec, "levels", 1);
12895 const long ntk = gen_int(spec, "tasks", 1);
12896 const long npr = gen_int(spec, "processors", 1);
12898 g.generate(static_cast<int>(ncl), static_cast<int>(nlv), static_cast<int>(ntk),
12899 static_cast<int>(npr));
12900 // BUILT BEFORE IT IS PRINTED, so a model the finalizer refuses is a
12901 // failure here rather than a document that only fails when read back.
12902 b.build();
12903 std::printf("%s\n", line::lqn::lqnx_to_string(b.model(), g.model_name()).c_str());
12904 return 0;
12905 }
12906 throw line::InputError("--generate: unknown kind '" + kind +
12907 "'; accepted forms are: network, layered");
12908}
12909
12910/**
12911 * Everything `main` did, with the arguments already in hand.
12912 *
12913 * SPLIT OUT SO A HOST CAN CALL IT. The binary's `main` is now ten lines in its
12914 * own translation unit, and this is the body both it and the C ABI run, so a
12915 * command line and an in-process call take the same path by construction
12916 * rather than by review.
12917 *
12918 * `no_args` replaces the `argc == 1` that decided the brief help, because an
12919 * in-process caller has no argv[0] to count and would otherwise never see it.
12920 */
12921int dispatch(const Options& in, bool allow_server, bool no_args) {
12922 {
12923 Options o = in;
12924 // Before any arm runs: `read_model` raises the priority warning and has
12925 // no knobs of its own to read the level from.
12926 if (!o.knobs.verbosity.empty()) g_verbosity = o.knobs.verbosity;
12927 // Solver console: set for the whole process, so that the model compile
12928 // narrates too -- LineConsole::writes() falls back to the session level
12929 // when no run is open, and reading the model happens before any solver
12930 // exists. `-v debug` (and its `verbose` spelling) is the ONLY way in.
12932 g_verbosity == "silent" ? line::util::VerboseLevel::SILENT
12933 : (g_verbosity == "debug" || g_verbosity == "verbose")
12936 if (o.help_all) {
12937 print_help();
12938 return 0;
12939 }
12940 if (o.help || no_args) {
12941 print_brief_help();
12942 return 0;
12943 }
12944 if (o.version) {
12945 std::printf("line-cli %s\n", kVersion);
12946 return 0;
12947 }
12948 // A warning is not a failure: every dependency the check probes is
12949 // optional, so the command exits 0 whenever the check itself ran.
12950 if (o.install) {
12951 install_check();
12952 return 0;
12953 }
12954 if (o.list) {
12955 list_api(o.output);
12956 return 0;
12957 }
12958 // BEFORE the model-reading path, and not inside it: --generate PRODUCES
12959 // a model rather than consuming one, so -f is neither required nor read.
12960 if (o.generate_given) return run_generate(o);
12961 if (o.find_solver) return find_solver_report(o);
12962 if (o.port) {
12963 // A HOST DOES NOT GET A SERVER BY ACCIDENT. `-p` blocks the calling
12964 // thread and opens a listening socket, so a host forwarding a
12965 // user's argument string would otherwise be handing that user both.
12966 if (!allow_server)
12967 throw line::InputError(
12968 "-p runs the solver as a server, which this caller did not permit");
12969 // `-f` and `-p` together would be two model sources for one run;
12970 // the request carries the model in server mode, so a file named on
12971 // the command line could only be ignored.
12972 if (!o.file.empty())
12973 throw line::InputError(
12974 "-p runs the solver as a server, where each request carries its own model; "
12975 "-f names a model on the command line and the two cannot both be the source");
12976 return run_server(o);
12977 }
12978 return run_invocation(o);
12979 }
12980}
12981
12982namespace line {
12983namespace cli {
12984
12985Response run(const Request& req) {
12986 Response res;
12987 reset_invocation_state(false);
12988 g_interrupt_cb = req.interrupt;
12989 g_interrupt_user = req.interrupt_user;
12990 if (req.has_stdin) set_stdin_override(req.stdin_text);
12991
12992 std::vector<std::string> docs;
12993 if (req.collect_json) g_json_sink = &docs;
12994
12995 // argv[0] IS SYNTHESISED HERE. parse_args skips it, as every argv parser
12996 // does, and a host that passed its own would have its first real argument
12997 // eaten. Requiring the host to prepend one would be requiring it to know
12998 // that, which is exactly the kind of knowledge a boundary should absorb.
12999 std::vector<std::string> store;
13000 store.push_back("line-cli");
13001 for (std::size_t i = 0; i < req.argv.size(); ++i) store.push_back(req.argv[i]);
13002 std::vector<char*> argv;
13003 for (std::size_t i = 0; i < store.size(); ++i) argv.push_back(&store[i][0]);
13004
13005 {
13006 // THE CAPTURES ENCLOSE THE try/catch, NOT JUST THE CALL. A failure
13007 // message the arms would have written to fd 2 is therefore captured
13008 // too, rather than escaping to the host's console -- which for R means
13009 // escaping to a terminal the user may not even be looking at. They are
13010 // plain scoped objects taking a sentinel fd for "do not capture",
13011 // because a std::optional here is the same thing with a longer name.
13012 FdCapture out(req.capture_stdout ? 1 : -1);
13013 FdCapture err(req.capture_stderr ? 2 : -1);
13014 try {
13015 res.exit_code = dispatch(parse_args(static_cast<int>(argv.size()), &argv[0]),
13016 req.allow_server, req.argv.empty());
13017 } catch (const InterruptRequested& e) {
13018 res.exit_code = 2;
13019 res.error = e.what();
13020 res.error_id = "line:interrupt";
13021 res.line_error_id = e.id();
13022 } catch (const line::Error& e) {
13023 res.exit_code = 2;
13024 res.error = e.what();
13026 res.line_error_id = e.id();
13027 } catch (const std::exception& e) {
13028 res.exit_code = 3;
13029 res.error = std::string("unexpected failure: ") + e.what();
13030 res.error_id = "line:internal";
13031 }
13032 if (req.capture_stdout) res.text = out.take();
13033 if (req.capture_stderr) res.diagnostics = err.take();
13034 }
13035
13036 g_json_sink = nullptr;
13037 g_interrupt_cb = nullptr;
13038 g_interrupt_user = nullptr;
13039 res.documents = docs;
13040 reset_invocation_state(false);
13041 return res;
13042}
13043
13044int main_body(int argc, char** argv) {
13045 try {
13046 return dispatch(parse_args(argc, argv), true, argc == 1);
13047 } catch (const line::Error& e) {
13048 std::fprintf(stderr, "line-cli: [%s] %s\n", e.id().c_str(), e.what());
13049 return 2;
13050 } catch (const std::exception& e) {
13051 std::fprintf(stderr, "line-cli: unexpected failure: %s\n", e.what());
13052 return 3;
13053 }
13054}
13055
13056} // namespace cli
13057} // namespace line
The -s ag entry point: gates, fixed point, mean measures.
Direct invocation of a single API function from named JSON arguments.
SolverAUTO.listValidMethods: the method names THIS MODEL can actually run.
Redirect a file descriptor into a temporary file for a scope, and give back what was written to it.
FdCapture(int fd)
bool active() const
std::string take()
Restore the descriptor and read back what was written.
Base error for the multiprecision C++ port.
Definition error.h:73
const std::string & id() const noexcept
The full identifier, e.g.
Definition error.h:78
std::string category() const
unsupported, numerical, input, external, internal, or empty for LINE:Error.
Definition error.h:81
std::string kind() const
The <kind> part, or empty for LINE:Error.
Definition error.h:88
A tool, binary, service or bridge LINE depends on is missing or failed: LINE:external:<kind>.
Definition error.h:124
Malformed or inconsistent input (dimensions, negative populations, ...): LINE:input:<kind>.
Definition error.h:103
std::size_t cols() const
Definition matrix.h:90
std::size_t rows() const
Definition matrix.h:89
bool empty() const
Definition matrix.h:92
The algorithm cannot produce a trustworthy answer on this instance: LINE:numerical:<kind>.
Definition error.h:110
A refusal: the feature, method or analysis is not covered: LINE:unsupported:<kind>.
Definition error.h:117
const EnvStage< T > & stage(std::size_t e) const
std::size_t nstages() const
A random lqn::LqnBuilder<T> source, configured once and then drawn from.
void set_host_demand_range(const Range &r)
Activity host demands.
lqn::LqnBuilder< T > generate(int num_clients, int num_levels, int num_tasks, int num_processors)
void set_proc_inf_probability(double p)
Probability that a processor is infinite-server rather than PS.
void set_synch_call_range(const Range &r)
Mean number of synchronous calls on a call arc.
void set_model_name(const std::string &nm)
The name of the generated model.
void set_population_range(const Range &r)
Reference-task populations.
void set_think_time_range(const Range &r)
Client think times.
void set_proc_multi_range(const Range &r)
Processor multiplicities, for the processors that are not infinite-server.
void set_task_multi_range(const Range &r)
Task multiplicities, for the tasks that are not infinite-server.
void set_task_inf_probability(double p)
Probability that a server task is infinite-server rather than FCFS.
void set_seed(long long seed)
Reseed the single stream every draw comes from.
A random qn::Network<T> source, configured once and then drawn from.
void set_cclass_job_load(const std::string &load)
high, medium, low, or randomize: the population band of a closed class.
void set_model_name(const std::string &nm)
The name given to the generated model.
void set_seed(long long seed)
Reseed the single stream every draw comes from, as MATLAB rng(seed).
void set_topology(TopologyKind kind)
Pick one of the two shipped topology generators; validated like set_topology_fcn.
void set_distribution(const std::string &d)
Exp, Erlang, HyperExp, or randomize.
void set_multi_chain_cs(bool v)
Classes are partitioned into random chains and switching is confined to a chain, instead of the defau...
void set_sched_strat(const std::string &strat)
fcfs, ps, inf, lcfs, lcfspr, siro, sjf, ljf, sept, lept, or randomize.
void set_random_cs_nodes(bool v)
Each link gets a ClassSwitch node inserted on a coin flip.
qn::Network< T > generate(int num_queues, int num_delays, int num_oclass, int num_cclass)
The full form.
void set_routing_strat(const std::string &strat)
Probabilities, Random, or randomize.
void set_varying_service_rates(bool v)
Service means spread over 2^-6 .
void set_multi_server_queues(bool v)
Queues get 1..40 servers instead of exactly one.
LnSensTable< T > get_sensitivity_table(const sens::SensOptions &sopt)
Port of @SolverLN/getSensitivityTable: solve the ensemble, then concatenate each layer solver's own t...
Definition solver_ln.h:735
LnTranSolution get_tran_avg()
Port of @SolverLN/getTranAvg: the block-diagonal aggregate transient.
Definition solver_ln.h:712
std::size_t nlayers() const
Definition solver_ln.h:823
std::vector< LnCdf > get_cdf_respt()
Port of @SolverLN/getCdfRespT: the per-entry response-time distribution.
Definition solver_ln.h:669
LnSolution< T > get_ensemble_avg()
Port of getEnsembleAvg: run the iteration and aggregate onto LQN elements.
Definition solver_ln.h:600
const std::vector< qn::Layer< T > > & layers() const
Definition solver_ln.h:824
LqnStruct< T > build() const
Flatten into the struct SolverLN consumes.
const LqnModel< T > & model() const
The layered model solved by lqns or lqsim.
static bool is_stochastic_method(const std::string &method)
Only the lqsim methods draw random numbers.
static std::string version()
The version banner of the local binary, empty when there is none.
A layer network: everything a NetworkStruct holds, plus the LQN back-mapping.
Definition qn_layer.h:52
A network plus its refreshed NetworkStruct.
std::size_t nvars_of(std::size_t ind) const
Total local-variable width of node ind (1-based).
std::size_t stateful_index(std::size_t ind) const
1-based stateful index of node ind, 0 when the node is not stateful.
std::size_t nof_nodes() const
std::map< std::pair< std::size_t, std::size_t >, Matrix< T > > P
P[(r,s)] is an (nnodes x nnodes) block; absent means all zero.
std::size_t phases_of(std::size_t ist, std::size_t r) const
sn.phases(i,r): the order of the process representation.
std::vector< Reward > reward
std::vector< std::size_t > stateful_nodes
1-based node indices, ascending
std::vector< std::vector< Distrib< T > > > service
service[i][r], 0-based station and class; a disabled entry marks a pair never visited.
std::vector< std::vector< bool > > disabled
std::map< std::size_t, CacheParam< T > > nodeparam
Cache parameters by 1-based NODE index; only Cache nodes have an entry.
std::vector< JobClass > classes
std::vector< Station< T > > stations
stations[k-1] is the k-th station
Matrix< T > rates
(nstations x nclasses) service rates and SCVs, with a PARALLEL disabled flag instead of MATLAB's NaN ...
std::vector< NodeDef > nodes
every node, in creation order
std::vector< std::size_t > station_to_node
(nstations) 1-based node index
std::vector< Region > regions
A queueing network under construction.
const NetworkStruct< T > & get_struct()
The refreshed struct, MATLAB's model.getStruct().
NetworkStruct< T > & raw_struct()
The struct WITHOUT refreshing it, for a caller that is still building.
RAII guard: opens a run on construction, closes it on scope exit.
static void reset()
Forget any open run (used after an interrupted solve).
static void set_verbose(VerboseLevel level)
Set the session verbosity.
The RAII frame timeout_arm returns.
A listening socket; one connection is served at a time.
Definition websocket.h:189
bool serve_one(Fn serve)
Accept one connection, complete the handshake, read ONE text message and hand it to serve; send what ...
Definition websocket.h:225
The CLI's argument vector, reachable in-process.
The keys a LINE solver accepts under options.config, in all four codebases.
Docker primitives for the backends that legitimately ship an image.
The SolverENV entry surface: a port of the analyzer selection that @@SolverENV/SolverENV....
Reader for the LINE model.json interchange of an ENVIRONMENT model into an env::Environment<T>.
The exception types the port throws.
Port of @@SolverFLD/getJacobian, all four of its outputs.
The fluid solver's outermost entry point: @@SolverFLD/runAnalyzer.m's method resolution over solver_f...
The log-driven half of SolverJMT: linkAndLog, parseLogs, parseTranState, parseTranRespT,...
Port of @@JMTIO: a refreshed NetworkStruct written out as a JMT .jsimg simulation model.
Read a JMT .jsim / .jsimg / .jsimw model into a qn::Network.
Random layered-queueing-network generation: the C++ twin of MATLAB @LayeredNetworkGenerator,...
The NATIVE LDES engine for LAYERED (LQN) models, the C++ twin of jline/solvers/ldes/handlers/Solver_s...
int dispatch(const Options &in, bool allow_server, bool no_args)
Everything main did, with the arguments already in hand.
int run_invocation(Options o)
#define LINE_CLI_TABLE_LADDER(FN)
int find_solver_report(const Options &o)
--find-solver: which solvers and methods can analyze the model named by -f.
int run_generate(const Options &o)
--generate: draw a random model and print it, solving nothing.
std::string run_invocation_captured(Options o, int &rc)
Run one invocation with stdout captured, and return what it printed.
int run_server(const Options &base)
-p/--port: serve solve requests over a WebSocket, as LineWebSocketServer does.
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.
model.json with type: "LayeredNetwork" -> LqnStruct, via LqnBuilder.
.lqnx -> LqnStruct, a port of matlab/src/lang/layered/@LayeredNetwork/parseXML.m followed by ....
LqnModel -> .lqnx, a port of matlab/src/lang/layered/@LayeredNetwork/writeXML.m.
The flat-Network path of @@SolverLQNS: its qns methods, served by qnsolver of the RADS/LQNS distribut...
Port of @NetworkSolver/mapEnvApprox.m: the solver-agnostic random-environment approximation of a netw...
The stage solvers map_env_approx injects, one per runner that can be a caller.
Boundary marshalling for host bindings (MATLAB MEX, pybind11, the JSON CLI).
Classification of a solution method, as printed in the solver banner: "<accuracy>,...
mva::AvgResult< T > solver_ag_run_analyzer(const qn::NetworkStruct< T > &L, const AgOptions &opt)
SolverAG.runAnalyzer: the converged agents as mean measures.
Definition ag_dispatch.h:34
Matrix< T > sn_declared_marginal(const qn::NetworkStruct< T > &sn)
The (nstations x nclasses) per-class job counts of the model's OWN state.
Definition sn_state.h:85
bool nonmkv_enabled(const std::string &method)
Resolve options.config.nonmkv to NonmarkovOptions::enabled.
AutoEnvChoice auto_choose_env_solver(const std::string &method, AutoMode mode=AutoMode::HEUR)
The Environment arm of chooseSolverHeur / chooseSolverExact / chooseSolverSim.
std::string auto_find_solver_table(const std::vector< SolverCandidate > &rows)
The rows as an aligned text table, the form the CLI and a console caller want.
AutoLayeredChoice auto_choose_layered_solver(const std::string &method, bool has_cache_task, AutoMode mode=AutoMode::HEUR)
chooseLayeredSolver plus the LayeredNetwork arm of chooseAvgSolverHeur.
const char * auto_env_stage_solver(AutoEnv s)
The EnvOptions::stage_solver (and --stage-solver) name of a candidate ensemble.
const char * auto_solver_name(AutoSolver s)
AutoToken auto_resolve_token(const std::string &raw, const qn::NetworkStruct< T > &sn)
resolveMethodToken with its third arm: an intent, a family[.submethod], or else a BARE method name,...
std::vector< AutoSolver > auto_proposed_solvers(const qn::NetworkStruct< T > &sn, const std::string &method, AutoMode mode)
delegate's proposed order: the chosen solver, then every feasible candidate in slot order.
AutoChoice auto_choose_solver_mode(const qn::NetworkStruct< T > &sn, const std::string &method, AutoMode mode)
chooseSolver: the selection mode picks the ranking, and every mode but the two learned ones keeps the...
std::vector< SolverCandidate > auto_find_solver(const qn::NetworkStruct< T > &sn, const std::string &metric=std::string(), bool show_all=false)
SolverAUTO.findSolver: which solvers and solver methods can analyze this model, and for the ones that...
const char * auto_env_name(AutoEnv s)
const char * auto_layered_name(AutoLayered s)
The layered names are the CLI's own tokens, because that is what the choice is spent on: ln....
BaBounds< T > ba_bounds(const qn::NetworkStruct< T > &L, const BaOptions &opt)
Port of SolverBA.getBounds.
mva::AvgResult< T > solver_ba_run_analyzer(const qn::NetworkStruct< T > &L, const BaOptions &opt_in)
Port of @@SolverBA/runAnalyzer.m for the lang='matlab' path.
std::string resolve_method(const std::string &method)
Port of runAnalyzer's method aliases: default is the geometric upper bound, bare auto is the AUTO com...
int main_body(int argc, char **argv)
The binary's main, so line_cli_main.cpp stays ten lines.
Response run(const Request &req)
Run one invocation and return what it produced.
Matrix< T > solver_ctmc_sample(const NetworkStruct< T > &sn, const CtmcSamplePath< T > &path, std::size_t ind)
Port of @@SolverCTMC/sample: the walk restricted to ONE stateful node's local block.
CtmcSolution< T > solver_ctmc_analyzer(const NetworkStruct< T > &sn_in, const CtmcOptions &opt, const CtmcStationaryHook< T > &stationary=CtmcStationaryHook< T >())
Port of solver_ctmc_analyzer.m plus the fork-join wrapper of @@SolverCTMC/runAnalyzer....
Matrix< T > solver_ctmc_sample_aggr(const NetworkStruct< T > &sn, const CtmcSamplePath< T > &path, std::size_t ind)
Port of @@SolverCTMC/sampleAggr: one node's per-class counts over time.
std::vector< CdfCurve< T > > solver_ctmc_cdf_sys_respt(const NetworkStruct< T > &sn, const CtmcOptions &opt)
Port of @@SolverCTMC/getCdfSysRespT.m: the per-chain SYSTEM response-time CDF, indexed by chain.
T solver_ctmc_jointaggr(const NetworkStruct< T > &sn, const CtmcSolution< T > &d, const NetState< T > &state)
Port of solver_ctmc_jointaggr: P(the network holds exactly these per-class counts),...
CtmcTranProb< T > ctmc_get_tran_prob_sys(const NetworkStruct< T > &sn, const CtmcTransient< T > &tr)
Port of @@SolverCTMC/getTranProbSys.m: pi(t), labelled by the whole network state with its phases.
CtmcSamplePath< T > solver_ctmc_sample_sys(const NetworkStruct< T > &sn, const CtmcOptions &opt_in, std::size_t nevents, unsigned long seed=23000)
Port of @@SolverCTMC/sampleSys: a marked walk on the whole network state.
CtmcTranProb< T > ctmc_get_tran_prob_sys_aggr(const NetworkStruct< T > &sn, const CtmcTransient< T > &tr)
Port of @@SolverCTMC/getTranProbSysAggr.m: pi(t), labelled by the network's per-(station,...
mva::AvgResult< T > solver_ctmc_avg_table(const NetworkStruct< T > &sn, const CtmcSolution< T > &d, const std::string &method)
Port of @@SolverCTMC/runAnalyzer.m's result assembly: solve, then apply the metric filter @@NetworkSo...
CtmcMddSolution< T > solver_ctmc_mdd_analyzer(const NetworkStruct< T > &sn, const CtmcOptions &opt, const mdd::MddMcdOptions &mcdopt=mdd::MddMcdOptions())
Solve with the mdd method.
CtmcGenerator< T > ctmc_get_infgen(const NetworkStruct< T > &sn, const CtmcSolution< T > &d)
@@SolverCTMC/getInfGen.m, a pure alias of getGenerator in the reference.
std::vector< T > solver_ctmc_margaggr(const NetworkStruct< T > &sn, const CtmcSolution< T > &d, const NetState< T > &state)
Port of solver_ctmc_margaggr: per STATION, P(that station holds exactly these per-class counts).
std::vector< CtmcSensRank< T > > solver_ctmc_sensitivity_ranking(const NetworkStruct< T > &sn, const CtmcOptions &opt, const std::vector< CtmcSensParam< T > > &params, const std::vector< T > &reward)
Port of @@SolverCTMC/getSensitivityRanking: rank parameters by influence.
std::vector< std::vector< CdfCurve< T > > > solver_ctmc_cdf_respt(const NetworkStruct< T > &sn, const CtmcOptions &opt)
Port of @@SolverCTMC/getCdfRespT.m: the per-(station, class) response-time CDF, indexed [ist-1][r-1].
std::vector< T > solver_ctmc_marg(const NetworkStruct< T > &sn, const CtmcSolution< T > &d, const NetState< T > &state)
Port of solver_ctmc_marg: per STATION, P(that station is in exactly its local slice of state),...
std::vector< T > solver_ctmc_avg_reward(const NetworkStruct< T > &sn, const CtmcOptions &opt, std::vector< std::string > *names=nullptr)
Port of @@SolverCTMC/getAvgReward: the steady-state expected rewards.
CtmcStateSpace< T > ctmc_get_state_space(const NetworkStruct< T > &, const CtmcSolution< T > &d)
Port of @@SolverCTMC/getStateSpace.m.
CtmcTransient< T > solver_ctmc_transient_analyzer(const NetworkStruct< T > &sn_arg, const CtmcOptions &opt, const T &t0, const T &t1, const std::vector< T > &grid=std::vector< T >())
Port of solver_ctmc_transient_analyzer.m.
CtmcFirstPassageMoments< T > ctmc_firstpasst_moments(const NetworkStruct< T > &, const CtmcSolution< T > &d, const Matrix< double > &A, const Matrix< double > &B, std::size_t nmax, const Matrix< double > &C)
Port of @@SolverCTMC/getFirstPassTMoments.m: moments of order 1..nmax of the first passage time from ...
T solver_ctmc_joint(const NetworkStruct< T > &sn, const CtmcSolution< T > &d, const NetState< T > &state)
Port of solver_ctmc_joint: P(the network is in exactly state).
Matrix< T > ctmc_get_state_space_aggr(const NetworkStruct< T > &sn, const CtmcOptions &opt)
Port of @@SolverCTMC/getStateSpaceAggr.m: the per-(station, class) job counts of every state,...
CtmcFirstPassage ctmc_cdf_firstpasst(const NetworkStruct< T > &, const CtmcSolution< T > &d, const Matrix< double > &A, const Matrix< double > &B, const Matrix< double > &C, std::vector< double > tset, const std::string &method="expm")
Port of @@SolverCTMC/getCdfFirstPassT.m: the distribution of the FIRST PASSAGE TIME from state set A ...
CtmcAnySolution< T > solver_ctmc_analyzer_any(const NetworkStruct< T > &sn, const CtmcOptions &opt)
The entry point a caller who does not know which path a model needs should use: pick the WAITQ walk w...
CtmcTranProb< T > ctmc_get_tran_prob(const NetworkStruct< T > &sn, const CtmcTransient< T > &tr, std::size_t ind)
Port of @@SolverCTMC/getTranProb.m: pi(t) over the whole chain, labelled by one node's local state.
Matrix< T > ctmc_state_space_aggr(const NetworkStruct< T > &sn, const std::vector< NetState< T > > &space)
Port of StateSpaceAggr: the per-(station, class) job counts of every state, as an (nstates x nstation...
CtmcTranProb< T > ctmc_get_tran_prob_aggr(const NetworkStruct< T > &sn, const CtmcTransient< T > &tr, std::size_t ind)
Port of @@SolverCTMC/getTranProbAggr.m: pi(t), labelled by one node's per-class job counts.
std::vector< std::vector< T > > solver_ctmc_tran_reward(const NetworkStruct< T > &sn, const CtmcOptions &opt, const T &t0, const T &t1, std::vector< T > *tout=nullptr, std::vector< std::string > *names=nullptr)
Port of @@SolverCTMC/getTranReward: E[r(X(t))] = sum_s pi_t(s) r(s).
CtmcReward< T > solver_ctmc_reward(const NetworkStruct< T > &sn, const CtmcOptions &opt, std::size_t tmax=1000)
Port of solver_ctmc_reward.m.
Matrix< T > solver_ctmc_sample_sys_aggr(const NetworkStruct< T > &sn, const CtmcSamplePath< T > &path)
Port of @@SolverCTMC/sampleSysAggr: the same walk, reported as per-(station, class) job counts rather...
EnvStatevecSolution< T > solver_env_statevec(Environment< T > &e, const EnvStatevecOptions< T > &o)
Solve in one call, for a caller with no use for the solver object.
EnvAnalyzerSolution< T > solver_env(Environment< T > &e, const EnvOptions &o)
SolverENV.init's analyzer selection: solve the environment with the coupling o.method names.
FluidKpTransient solver_fluid_tran_avg_var(const qn::NetworkStruct< T > &sn, const FluidOptions &opt)
Port of @@SolverFLD/getTranAvgVar: the queue-length VARIANCE along the trajectory,...
Definition fluid_kp.h:1070
double aoi_cdf(const AoiMe &me, double t)
getCdfAoI: F(t) = 1 - S(t) with S the survival function of the age law.
Definition fluid_aoi.h:681
double fluid_prob_aggr(const qn::NetworkStruct< T > &sn, const FluidSolution &sol, std::size_t ist, double *logp_out=nullptr)
Port of @@SolverFLD/getProbAggr: the probability that station ist holds the marginal population of th...
AoiTopology aoi_is_aoi(const qn::NetworkStruct< T > &sn)
Port of aoi_is_aoi.m.
Definition fluid_aoi.h:106
std::string solver_fluid_export_odes(const qn::NetworkStruct< T > &sn, const FluidOptions &opt, const std::string &notation="scalar", const std::string &model_name="model")
Port of @@SolverFLD/exportODEs.m, which hands options.method to solver_fluid_symodes UNRESOLVED: defa...
FluidSolution solver_fluid_run_analyzer(const qn::NetworkStruct< T > &sn, const FluidOptions &opt, qn::NetworkStruct< T > *sn_out=nullptr, qn::NetworkStruct< T > *refreshed_out=nullptr, solvers::CacheMetrics< T > *cache_out=nullptr, const qn::NetworkStruct< T > *gate_sn=nullptr)
Port of @@SolverFLD/runAnalyzer.m: resolve the method, route to the function the reference routes to,...
FluidJacobian fluid_jacobian(const FluidSymSystem &sys, const FluidSymbolicOptions &opt=FluidSymbolicOptions())
Jacobian, drift and equilibria of the mean-field vector field.
std::vector< std::vector< FluidPassage > > solver_fluid_cdf_respt(const qn::NetworkStruct< T > &sn, const FluidOptions &opt, std::size_t points=201)
Port of @@SolverFLD/getCdfRespT: the response-time law of every (station, class) pair,...
FluidSymSystem fluid_symodes(const qn::NetworkStruct< T > &sn, const std::string &method_in, double pstar, const std::vector< double > &init_sol)
Build the symbolic system of sn under opt.method.
std::vector< FluidTranPoint > solver_fluid_run_transient(const qn::NetworkStruct< T > &sn, const FluidOptions &opt, std::size_t points=101)
-a tran / @@SolverFLD/getTranAvg with the method HONOURED, which is the one place the reference does ...
bool is_layered_json(const std::string &path)
True when a file is a LayeredNetwork model.json rather than an .lqnx.
std::string jsim_stage_stdin(const std::string &text)
Write a piped XML model document to a temporary file and return its path.
qn::Network< T > read_network_json(const std::string &path)
Parse a model.json file into a qn::Network<T>.
qn::Network< T > read_jsim(const std::string &path, const std::string &name=std::string())
Read a JSIM document into a Network.
lqn::LqnModel< T > read_lqnx_model(const std::string &path)
Read a .lqnx file into the model-level LqnModel, which write_lqnx accepts back.
Definition lqnx_io.h:39
lqn::LqnStruct< T > read_layered_model(const std::string &path)
Read a layered model from any of its interchanges: the LINE model.json, the LQNS ....
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.
env::Environment< T > build_environment_from_json(const detail::json &root)
Build an env::Environment<T> from a parsed model.json envelope.
env::Environment< T > read_environment_json(const std::string &path)
Parse a model.json file into an env::Environment<T>.
qn::Network< T > build_network_from_json(const detail::json &root)
Build a qn::Network<T> from a parsed model.json envelope.
bool docker_daemon_available()
True if the Docker daemon is reachable.
detail::json network_json_envelope(const qn::NetworkStruct< T > &sn)
The complete model.json envelope: {format, version, model}.
const char * error_id(const Error &e)
Stable identifier for an error, for mexErrMsgIdAndTxt and for mapping to a host exception class.
Definition marshal.h:146
bool is_layered_json_text(const std::string &text)
True when a DOCUMENT ALREADY IN MEMORY is a LayeredNetwork model.json.
qn::Network< T > pnml_load(const std::string &path, const std::string &net_id=std::string())
Read one net of a PNML place/transition document into a Network.
Definition pnml.h:492
JmtReplication< T > jmt_transient_replications(const qn::NetworkStruct< T > &sn, const JmtOptions &opt)
Port of the transient ensemble of @@SolverJMT/runAnalyzer.m (default over a finite timespan).
Definition jmt_logs.h:912
JmtSysTrace< T > jmt_sample_sys_aggr(const qn::NetworkStruct< T > &sn, std::size_t num_events, const JmtOptions &opt)
Port of sampleSysAggr: every station's trajectory on one time grid.
Definition jmt_logs.h:501
JmtNodeTrace< T > jmt_sample_aggr(const qn::NetworkStruct< T > &sn, std::size_t node, std::size_t num_events, const JmtOptions &opt)
Port of sampleAggr: the queue-length trajectory of one node.
Definition jmt_logs.h:450
std::vector< std::string > jmt_list_valid_methods()
Port of SolverJMT.listValidMethods.
std::size_t jmt_transient_replication_count(const JmtOptions &opt, const std::string &what)
How many JSIM runs a transient estimate is over: the gate the two transient arms share.
Definition jmt_logs.h:677
JmtResult< T > solver_jmt_run_analyzer(const qn::NetworkStruct< T > &sn, const JmtOptions &opt_in)
Port of @@SolverJMT/runAnalyzer.m, the jsim and jmva arms.
std::map< std::pair< std::size_t, std::size_t >, std::vector< std::pair< double, double > > > jmt_get_cdf_resp_t(const qn::NetworkStruct< T > &sn, const JmtOptions &opt, bool seed_from_steady=true)
Port of getCdfRespT: the empirical response-time distribution per (station, class),...
Definition jmt_logs.h:573
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.
std::pair< std::vector< double >, std::vector< std::vector< double > > > jmt_get_tran_prob_aggr(const qn::NetworkStruct< T > &sn, std::size_t station, const JmtOptions &opt, std::vector< std::vector< double > > &states_out)
Port of getTranProbAggr: the transient distribution of one station's aggregate state,...
Definition jmt_logs.h:706
JmtProbAggr jmt_prob_aggr(const qn::NetworkStruct< T > &sn, const JmtOptions &opt, std::size_t target_station=0, const std::vector< double > &target=std::vector< double >())
Port of getProbAggr and getProbSysAggr, both off ONE instrumented run.
Definition jmt_logs.h:816
const char * sched_to_text(SchedStrategy s)
Definition lang_types.h:248
const char * event_to_text(EventType e)
Definition lang_types.h:148
LnColumn
A column of the shared layered average table, as line-cli prints it.
bool ln_defined(const lqn::LqnStruct< T > &lsn, const LnResult &r, std::size_t i, LnColumn c)
Does the element at i HAVE the quantity in column c?
std::vector< LnEntryCdf > ldes_ln_cdf_respt(const LnResult &r, std::size_t nentries)
The empirical response time CDF of every ENTRY, the getCdfRespTLN of the other codebases: one [F(t),...
std::vector< LdesPercentileResult > ldes_perct_respt(const LdesResult &r, const std::vector< double > &percentiles, int replications, const std::string &method=std::string(), double level=0.95, long job_class=-1)
Port of @SolverLDES/getPerctRespT: steady-state response-time p-quantiles with confidence intervals,...
solvers::FjMetrics< double > ldes_fj_metrics(const qn::NetworkStruct< T > &sn, const LdesResult &r)
ldesParseForkJoin: the engine's "forkJoin" rows mapped onto the Fork/Join pairs of sn by (fork name,...
engine::LnResult ldes_ln_engine_solve(const lqn::LqnStruct< T > &lsn, const LdesOptions &o)
Simulate a layered model in process.
LdesResult solver_ldes_text(const std::string &doc, const LdesOptions &o, const std::vector< std::string > &extra_flags=std::vector< std::string >())
Runs one LDES simulation on a model.json DOCUMENT and parses its result.
bool ldes_is_available()
True when this machine can run the engine at all, by either image.
Definition ldes_probe.h:253
double ldes_perct_level(const LdesOptions &o)
The confidence level getPerctRespT uses: confint when intervals are on (a level in (0,...
int ldes_replications(const LdesOptions &o)
The replication count a run asks the engine for: replications when it is above one,...
std::string ldes_perct_method(int replications, const std::string &method)
The quantile procedure a replication count calls for: 'fquest' on one path (R <= 1),...
std::string fmt(const char *f, double v)
bool in(const std::string &s, std::initializer_list< const char * > set)
const std::string * get(const Element *el, const std::string &key)
el.get(key), with Python's None as a null pointer.
Definition srvn_writer.h:62
std::string name(const Element *el, const std::string &key="name")
std::string srvn_file_to_lqnx(const std::string &path)
Translate the SRVN file path to .lqnx text, model name = its basename without extension.
LqnModel< T > read_srvn_model(const std::string &path)
Read an SRVN file (.in, or a .lqn that is not XML) into the intermediate LqnModel,...
std::string lqnx_to_string(const LqnModel< T > &m, const std::string &model_name=std::string("LQN"), bool use_abstract_names=false)
The .lqnx document as a STRING, for a caller with no file to write to – the CLI's model-generation mo...
Definition lqn_writer.h:666
bool is_srvn_path(const std::string &path)
Whether path should be read as SRVN: a .in file, or a .lqn file that is not XML.
mva::AvgResult< T > solve_network_run_analyzer(const qn::NetworkStruct< T > &L, const QnsOptions &opt)
Port of @@SolverLQNS/runAnalyzerNetwork.m and solver_qns.m: SolverLQNS on a flat Network.
const std::string & lqns_version()
The version banner of the local lqns, empty when there is none.
Definition lqns_probe.h:49
bool lqns_is_available()
True when lqns is installed AND is a release this port speaks.
Definition lqns_probe.h:69
bool qnsolver_is_available()
Port of SolverLQNS.hasQnsolver: a native qnsolver binary on the PATH.
std::vector< T > mam_percentiles_from_cdf(const RespTCdf< T > &cdf, const std::vector< double > &pcts)
Port of the CDF path of @@SolverMAM/getPerctRespT.m: linear interpolation of the response-time CDF at...
TranResult< T > solver_mam_get_tran_avg(const qn::NetworkStruct< T > &L, const MamOptions &opt_in)
Port of @@SolverMAM/getTranAvg.m: transient queue length, utilization and throughput.
std::vector< RespTCdf< T > > solver_mam_get_cdf_respt(const qn::NetworkStruct< T > &L, const MamOptions &opt)
@@SolverMAM/getCdfRespT.m: the response-time CDF per class.
mva::AvgResult< T > solver_mam_run_analyzer(const qn::NetworkStruct< T > &L, const MamOptions &opt)
Port of @@SolverMAM/runAnalyzer.m for the lang='matlab' path: solve, then apply the metric filter @@N...
ProbTable< T > solver_mam_get_prob(const qn::NetworkStruct< T > &L, const MamOptions &opt, std::size_t node, const mva::AvgResult< T > &avg)
@@SolverMAM/getProb.m: the joint (level, phase) table at a node.
std::vector< std::vector< T > > solver_mam_get_perct_respt(const qn::NetworkStruct< T > &L, const MamOptions &opt, const std::vector< double > &percentiles)
@@SolverMAM/getPerctRespT.m: response-time percentiles per class.
bool mam_has_fj_percentiles(const qn::NetworkStruct< T > &L, const MamOptions &opt)
Whether getPerctRespT reads the FJ_codes table rather than inverting a CDF.
std::vector< T > solver_mam_get_prob_marg(const qn::NetworkStruct< T > &L, const MamOptions &opt, std::size_t ist, std::size_t jobclass, const mva::AvgResult< T > &avg)
@@SolverMAM/getProbMarg.m: P(n jobs of one class) at a station.
qsys::BmapM1Result< T > solver_mam_get_mam_result(const qn::NetworkStruct< T > &L)
@@SolverMAM/getMAMResult.m: the M/G/1-type internals of a single queue.
double var(const std::vector< double > &x)
Sample variance with the n - 1 denominator.
Matrix< double > to_matrix(const std::vector< std::vector< double > > &Q)
const std::map< std::string, std::vector< std::string > > & table()
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.
AggrResult< T > solver_mva_get_prob_aggr(const qn::NetworkStruct< T > &L, const AvgResult< T > &avg, std::size_t ist, const std::string &method="default")
T solver_mva_get_prob_norm_const_aggr(const qn::NetworkStruct< T > &L, const MvaOptions &opt)
Port of @@SolverMVA/getProbNormConstAggr.m: log G.
std::string resolve_method(const qn::NetworkStruct< T > &L, const std::string &method)
Port of SolverMVA.resolveMethod: the feature-driven default -> rqna upgrade for a bursty single-class...
MargResult< T > solver_mva_get_prob_marg(const qn::NetworkStruct< T > &L, const AvgResult< T > &avg, std::size_t ist, std::size_t r, const std::vector< long > &states, const std::string &method="default")
Port of @@SolverMVA/getProbMarg.m: P(n jobs of class r at station i) for the states in states (or the...
AggrResult< T > solver_mva_get_prob_sys_aggr(const qn::NetworkStruct< T > &L, const AvgResult< T > &avg, const std::string &method="default")
Port of @@SolverMVA/getProbSysAggr.m: the joint probability of the model's whole state across all sta...
Matrix< T > sn_get_arvr_from_tput(const qn::NetworkStruct< T > &L, const Matrix< T > &TN)
Port of sn_get_arvr_from_tput: the arrival rate each station sees, from the throughputs and the class...
AvgResult< T > solver_mva_run_analyzer(const qn::NetworkStruct< T > &L, const MvaOptions &opt_in, const Matrix< T > &init_sol)
Port of @@SolverMVA/runAnalyzer.m for the lang='matlab' path: gate, solve, convert,...
NcCftpSolution< T > solver_nc_cftp(const qn::NetworkStruct< T > &sn, const NcSolverOptions &opt, const NcCftpOptions &cftpopt)
Solve with the cftp / cftp.approx method.
mva::AvgResult< T > solver_nc_run_analyzer(const qn::NetworkStruct< T > &L_in, const NcSolverOptions &opt_in)
T solver_nc_getprob_sys_marg(const qn::NetworkStruct< T > &sn, const NcSolverOptions &opt, const std::vector< int > &nvec, const std::string &engine="exact")
Port of @@SolverNC/getProbSysMarg.m.
T solver_nc_getprob_sys_aggr(const qn::NetworkStruct< T > &sn, const NcSolverOptions &opt, const MarginalState &nir)
Port of @@SolverNC/getProbSysAggr.m.
NcSolution< T > solver_nc_cftp_solution(const NcCftpSolution< T > &s)
A cftp solve in the shape every other SolverNC analyzer returns, so the runner's metric filter applie...
T solver_nc_joint(const qn::NetworkStruct< T > &sn, const NcSolverOptions &opt, const MarginalState &nir, double *lG_out)
Port of solver_nc_joint.m: the probability of the WHOLE system state.
std::vector< double > solver_nc_busyp(const qn::NetworkStruct< T > &sn, const std::vector< std::size_t > &subnet, const std::vector< std::size_t > &orders)
Mean busy period of order n for a set of stations.
NcQueueLengthDist< T > solver_nc_getprob_marg(const qn::NetworkStruct< T > &sn, const NcSolverOptions &opt, std::size_t ist)
Port of @@SolverNC/getProbMarg.m: the TOTAL queue-length distribution.
NcMargResult< T > solver_nc_margaggr(const qn::NetworkStruct< T > &sn, const NcSolverOptions &opt, const MarginalState &nir, double lG)
Port of solver_nc_margaggr.m.
bool is_stochastic_method(const std::string &method)
Port of SolverNC.isStochasticMethod.
NcSolution< T > solver_nc_solve(const qn::NetworkStruct< T > &L_in, const NcSolverOptions &opt_in)
The gates, the multiserver conversion and the dispatch of @@SolverNC/runAnalyzer.m,...
CdfRespTResult< T > solver_nc_cdf_respt(const qn::NetworkStruct< T > &sn, const NcSolverOptions &opt)
Port of @@SolverNC/getCdfRespT.m.
NcMargResult< T > solver_nc_marg(const qn::NetworkStruct< T > &sn, const NcSolverOptions &opt, const MarginalState &nir, double lG)
Port of solver_nc_marg.m: the DETAILED marginal, which weighs the station's internal arrangement and ...
std::vector< std::vector< int > > MarginalState
A state, as this port expresses it: nir[i][r] jobs of class r at station i.
mva::AvgResult< T > solver_nc_avg_table(const qn::NetworkStruct< T > &L_in, const NcSolution< T > &d, const std::string &origmethod)
Port of @@SolverNC/runAnalyzer.m for the lang='matlab' path: solve, then apply the metric filter @@Ne...
std::string solver_nc_cftp_supports(const qn::NetworkStruct< T > &sn)
The cftp model-class gate as a public predicate.
NcldMethod
The load-dependent methods this port dispatches.
Definition pfqn_ncld.h:87
std::vector< std::vector< int > > multichoose_rows(int n, int k)
All n-vectors of nonnegative integers summing to k, in MATLAB multichoose(n,k) order.
bool ncld_method_try(const std::string &s, NcldMethod &out)
Map a method name to its enum; false when the name is not one of them.
Definition pfqn_ncld.h:109
FeatureSet fluid_feature_set(const std::string &method)
Marginal< T > to_marginal(const NetworkStruct< T > &sn, std::size_t ist, const std::vector< T > &state_i, const std::vector< std::size_t > &phasesz, const std::vector< std::size_t > &phaseshift, std::size_t nvar=0)
Port of State.toMarginal for a STATION, one state row at a time.
Definition state.h:139
FeatureSet nc_feature_set(const std::string &method)
SolverNC.getFeatureSet, 48 names, transcribed unchanged.
FeatureSet mva_feature_set(const std::string &raw_method)
SolverMVA.getFeatureSet, plus getMethodFeatureSet's per-method deltas.
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.
nlohmann::json Json
Definition api_json.h:63
std::string api_render_readable(const Json &result)
Human-readable rendering of the object api_invoke returns, for -o readable.
ArithSpec parse_arith(const std::string &text)
Parse –arith.
std::map< std::string, std::string > api_library_only_functions()
Registered functions that can NEVER be carried by named JSON arguments, each with the reason (a calla...
bool api_is_exposed(const std::string &name)
True when the named function has a dispatch entry.
Json api_invoke(const std::string &name, const std::string &arith, const Json &args)
Invoke one API function.
SensTable< T > solver_sensitivity_table(qn::NetworkStruct< T > &sn, const SensOptions &opt, bool exact_available, const std::function< mva::MvaSolution< T >()> &solve)
Build the sensitivity table of sn under solve.
std::pair< double, double > quantile(const std::vector< double > &R, const std::vector< double > &L, std::size_t from, std::size_t to, double p, int m1, int m2, double sumAlpha)
Eq.
void put(Matrix< double > &A, std::size_t r0, std::size_t c0, const Matrix< double > &S)
A(r0:, c0:) = S.
Definition mg1.h:927
MapEnvDecision needs_map_env(const qn::FeatureSet &declared, const qn::NetworkStruct< T > &sn, const MapEnvConfig &cfg=MapEnvConfig())
needsMapEnv: does this model need the environment image, and would the image make it solvable?
std::vector< std::string > chain_class_labels(const qn::NetworkStruct< T > &sn)
(ClassA ClassB), the JobClasses column: which classes a chain holds.
std::vector< bool > node_table_hidden_classes(const line::qn::NetworkStruct< T > &sn)
The classes getAvgNodeTable omits: the auxiliary retrieval classes that Cache.setRetrievalSystem mint...
env::EnvStageAvgFn< double > nc_stage_fn(const nc::NcSolverOptions &opt)
NC stages, bound to the caller's own NcSolverOptions.
SysResult< T > solver_get_avg_sys(const qn::NetworkStruct< T > &sn, const mva::AvgResult< T > &r)
Port of @@NetworkSolver/getAvgSys.m.
FjMetrics< double > fj_metrics_to_double(const FjMetrics< T > &in)
The same metrics in double precision, for the facade and the CLI.
Definition fj_metrics.h:90
line::mva::AvgResult< T > avg_result_from_sim(const line::qn::NetworkStruct< T > &sn, const line::Matrix< double > &QN, const line::Matrix< double > &UN, const line::Matrix< double > &RN, const line::Matrix< double > &TN, const std::vector< double > &CN, const std::vector< double > &XN, const std::string &method)
The station AvgResult of a solver whose runner returns its own solution type, i.e.
NodeMetrics< T > node_metrics(const line::qn::NetworkStruct< T > &sn, const line::mva::AvgResult< T > &r)
bool config_value_ok(const ConfigKey &k, const char *value)
Whether value is admissible for k: always true when the key lists no values.
mva::AvgResult< T > run_avg(const qn::NetworkStruct< T > &sn, const std::string &solver, const qn::FeatureSet &declared, const MapEnvConfig &cfg, Run run, StageFn stage_fn, const std::string &requested_method="default")
The getAvg funnel: run the model, or its environment image when the ONLY thing in the way is a non-re...
Definition map_env.h:332
ChainResult< T > solver_get_avg_node_chain(const qn::NetworkStruct< T > &sn, const Matrix< T > &QNn, const Matrix< T > &UNn, const Matrix< T > &RNn, const Matrix< T > &WNn, const Matrix< T > &ANn, const Matrix< T > &TNn)
Port of @@NetworkSolver/getAvgNodeChain.m: the NODE table aggregated by chain.
ChainResult< T > solver_get_avg_chain(const qn::NetworkStruct< T > &sn, const mva::AvgResult< T > &r)
Port of @@NetworkSolver/getAvgChain.m: the station table aggregated by chain.
mva::AvgResult< T > map_env_approx(const qn::NetworkStruct< T > &sn, const std::string &solver, const MapEnvConfig &cfg, StageFn stage_fn, const std::string &requested_method="default")
mapEnvApprox: solve the model through the random-environment image of its non-renewal processes.
Definition map_env.h:186
const ConfigKey * config_key_for_flag(const char *flag)
The config key a line-cli flag carries; nullptr when the flag carries none.
std::vector< std::vector< DefaultCdfCurve > > solver_default_cdf_respt(const qn::NetworkStruct< T > &sn, const Matrix< T > &RN)
The NetworkSolver base-class response-time CDF: an exponential law with the right mean per (station,...
std::vector< std::string > chain_names(std::size_t nchains)
Chain1, Chain2, ... – the reference's own chain labels.
env::EnvStageAvgFn< double > fluid_stage_fn(const fluid::FluidOptions &opt)
Fluid stages, bound to the caller's own FluidOptions.
env::EnvStageAvgFn< double > mva_stage_fn(const mva::MvaOptions &opt)
MVA stages, bound to the caller's own MvaOptions.
double dot(const Vec &a, const Vec &b)
Definition spn_ispn.h:201
SsaSerialSolution< T > solver_ssa_serial_analyzer(const qn::NetworkStruct< T > &sn_in, const SsaSerialOptions &opt)
Port of solver_ssa_analyzer_serial.m plus the fork-join wrapper @@SolverSSA/runAnalyzer....
SsaSamplePath< T > ssa_sample_node(const qn::NetworkStruct< T > &sn, const SsaSerialRun< T > &r, std::size_t ind)
sample(node) and sampleAggr(node): the same trajectory, one node's block.
SsaProbReport solver_ssa_prob(const qn::NetworkStruct< T > &sn_arg, const SsaSerialOptions &opt_in)
The whole -a prob report over the model's DEFAULT INITIAL STATE, which is the state SolverCTMC's own ...
SsaSamplePath< T > ssa_sample_sys(const qn::NetworkStruct< T > &sn, const SsaSerialRun< T > &r)
sampleSys and sampleSysAggr: the trajectory itself.
SsaSolution solver_ssa(const qn::NetworkStruct< T > &sn, const SsaOptions &opt, std::vector< SsaCacheRatio > *cache=nullptr)
qn::NetworkStruct< T > sn_with_ssa_cache_split(const qn::NetworkStruct< T > &base, const std::vector< SsaCacheRatio > &cache)
@@SolverSSA/runAnalyzer itself: the engine the method selects, then the result assembly the reference...
void ssa_cdf_respt_refuse()
getCdfRespT: refused, and the refusal is the ANSWER rather than a gap.
solvers::CacheMetrics< T > cache_metrics_of_ssa(const qn::NetworkStruct< T > &sn, const std::vector< SsaCacheRatio > &cache)
CacheMetrics from the serial engine's cache write-back.
std::string sym_find_image()
const char *const SYM_DOCKER_IMAGE
Image serving the symbolic REST API.
Definition sym_engines.h:74
UqSolution< T > solver_uq_run_analyzer(qn::Network< T > &net, const UqStageSolver< T > &stage, const UqOptions &opt=UqOptions())
UQ.runAnalyzer as a free call: expand, solve every design point, aggregate.
Definition solver_uq.h:576
UqInterval< T > uq_interval_run(qn::Network< T > &net, const UqStageSolver< T > &stage, const UqOptions &opt=UqOptions())
getInterval from the model, running the ensemble ONLY when it is needed.
Definition solver_uq.h:976
std::vector< PriorSite< T > > uq_detect_priors(const qn::NetworkStruct< T > &sn)
UQ.detectPriors: find every Prior, in node order and then class order.
Definition solver_uq.h:198
UqStageSolver< T > uq_stage_solver(const UqStageOptions &o)
The stage solver named by o.solver.
TimeoutScope timeout_arm(double budget)
Arm budget seconds for the scope's lifetime, capped by the outer frame's remaining time.
std::string method_type(const std::string &solvername, const std::string &method)
Banner classification of a solution method.
bool timeout_tripped()
Whether the innermost budget was tripped by a checkpoint or by timeout_trip.
void timeout_warn(const std::string &solver, double budget)
The one warning a solve that stopped on its budget prints, MATLAB's flagTimeout text,...
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
const char * arith_name(Arith a)
Definition registry.h:28
const std::vector< ApiEntry > & api_registry()
The registry is a function-local static, not a global object, so there is no static-initialization or...
Definition registry.h:49
Random queueing-network generation: the C++ twin of MATLAB @NetworkGenerator, the JAR jline....
Reader for the LINE model.json interchange (a Network model) into a qn::Network<T> built through the ...
Number-type abstraction for the templated API port.
PNML (ISO/IEC 15909-2) place/transition nets, read and written.
Coverage registry of the C++ port.
Ports of matlab/src/api/sn/sn_get_node_arvr_from_tput.m and sn_get_node_tput_from_tput....
Ports of matlab/src/api/sn/sn_get_state_aggr.m and sn_is_state_valid.m.
The SolverAUTO chooser: which solver a model is handed to.
The SolverBA class surface: @@SolverBA/runAnalyzer.m, listValidMethods, getBounds and getBoundsTable.
The CHAIN-level and SYSTEM-level views of a solved model.
Port of solver_ctmc_analyzer.m and the parts of @@SolverCTMC/runAnalyzer.m that surround one solve: t...
Port of @@SolverCTMC/getCdfRespT.m and @@SolverCTMC/getCdfSysRespT.m: the exact distribution of the r...
The remaining @@SolverCTMC accessors: getGenerator / getInfGen, getStateSpace / getStateSpaceAggr and...
The mdd method of SolverCTMC: stationary analysis of a closed single-class network whose state space ...
The SolverCTMC probability family: solver_ctmc_joint, _jointaggr, _marg, _margaggr,...
Port of solver_ctmc_reward.m and the @@SolverCTMC reward surface (runRewardAnalyzer,...
Port of the @@SolverCTMC sampling surface: sample, sampleAggr, sampleSys, sampleSysAggr.
Port of @@SolverCTMC/getSensitivity and getSensitivityRanking: the parametric sensitivity of a steady...
Port of solver_ctmc_fcr_waitq.m: the reachability-built generator of a model whose finite capacity re...
The base-class fallback for a response-time CDF.
SolverFluid: the closing method, a port of solver_fluid.m, solver_fluid_iteration....
Port of SolverJMT, the Java Modelling Tools client.
Port of SolverLDES, the discrete-event simulator, as its C++ client.
SolverLN: layered decomposition of a layered queueing network.
SolverLQNS: the layered model solved by the external lqns / lqsim binaries.
The SolverMAM class surface: @@SolverMAM/runAnalyzer.m and the gates around it.
The state-probability half of the SolverMVA class surface.
The SolverMVA class surface: @@SolverMVA/runAnalyzer.m and the gates around it.
Port of @SolverNC/getAvgBusyPeriod.m and of the Python-native SolverNC.getAvgBusyPeriod: the mean bus...
Port of @@SolverNC/getCdfRespT.m, and of its two aliases getSjrnT and sjrnT.
The cftp and cftp.approx methods of SolverNC: stationary analysis of a closed single-class product-fo...
The state-probability half of the SolverNC class surface: ports of solver_nc_marg....
The SolverNC class surface: @@SolverNC/runAnalyzer.m and the gates around it.
The NODE-indexed view of a station result, behind getAvgNodeTable.
Performance sensitivities with respect to service rates.
The SolverSSA queries that are not the average table: getProb, getProbAggr, getProbSys,...
SRVN input format (the LQNS .in / .lqn text grammar) for layered models, the C++ twin of python/line_...
The SolverSSA entry surface: a port of @@SolverSSA/runAnalyzer.m's method whitelist,...
Everything one invocation does once the arguments are in hand.
CliTimeoutReport(const std::string &s, double b)
std::string solver
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
std::string method
'default', 'inap', 'inaprc', 'inapinf' or the vestigial 'exact'.
Definition ag_types.h:51
int iter_max
SolverOptions('AG') lowers this from the global 1000 to 100.
Definition ag_types.h:57
double tol
Convergence tolerance of the reversed-rate fixed point.
Definition ag_types.h:54
std::size_t max_states
Truncation level of an OPEN agent's queue-length dimension.
Definition ag_types.h:65
std::string nonmkv
options.config.nonmkv: 'bernstein' (default) runs sn_nonmarkov_toph, 'none' skips it; any other name ...
Definition ag_types.h:76
What a ranking resolved to, and what it had to skip to get there.
std::string method
The method the choice was gated on: "" for the default, "exact".
std::vector< AutoSolver > skipped
Slots that outranked solver and have no engine in this port.
std::vector< AutoEnv > retry
delegate.m's proposed list: the chosen ensemble, then every candidate in slot order (MVA,...
std::vector< AutoEnv > skipped
std::vector< AutoLayered > skipped
resolveMethodToken, minus the unqualified-algorithm-name arm.
std::string submethod
the method handed to the family, "default" when bare
std::string family
empty when is_intent
Port of SolverBA.getBounds: the {lower,upper} bracket of a family.
std::vector< std::vector< bool > > keep
getBoundsTable's row filter, (M x K): whether the (station, class) pair earns a row.
Matrix< T > Qupper
(M x K), all-NaN on a side the family lacks
options.config.qrf_params, the blocking tables the BAS and RS-RD arms need.
std::vector< std::vector< int > > MM1
(MR x M) extended order
std::vector< std::vector< int > > MM
(MR x 2) blocking order
std::vector< std::vector< int > > BB
(MR x M) blocking state
int MR
number of blocking configurations
int f
finite-capacity queue, 1-based as in the reference
std::vector< int > ZZ
(MR) blocked count per config
std::vector< int > F
(M) capacity; empty takes sn.cap
The options SolverBA reads.
int level
options.level: the hierarchy level of pbh/bjbh/cbh/sib.
std::string method
Bound method; default resolves to gb.upper in the runner.
Matrix< double > qrf_alpha
options.config.qrf_alpha, the (nstations x N) load-dependent scaling of the two load-dependent QRF ar...
One invocation: the argument vector, plus what a pipe would have carried.
Definition cli_run.h:49
bool collect_json
Collect the JSON documents as they are emitted.
Definition cli_run.h:68
void * interrupt_user
Definition cli_run.h:100
int(*) interrupt(void *user)
Polled between analyses and at each document emission; non-zero aborts.
Definition cli_run.h:99
std::vector< std::string > argv
The argument vector WITHOUT argv[0], e.g.
Definition cli_run.h:55
std::string stdin_text
The model document, as if piped to the binary's stdin.
Definition cli_run.h:64
bool capture_stderr
Redirect fd 2 for the duration of the call into Response::diagnostics.
Definition cli_run.h:72
bool capture_stdout
Redirect fd 1 for the duration of the call into Response::text.
Definition cli_run.h:70
bool allow_server
Permit -p, which serves until its request budget is exhausted.
Definition cli_run.h:81
What one invocation produced.
Definition cli_run.h:104
std::string line_error_id
The cross-codebase identifier of error, LINE:<category>:<kind> or the unclassified LINE:Error (_kb/17...
Definition cli_run.h:147
int exit_code
The CLI's own exit status: 0 ok, 2 line::Error, 3 other.
Definition cli_run.h:106
std::string error_id
line::io::error_id's stable identifier for error.
Definition cli_run.h:140
std::vector< std::string > documents
Each JSON document the run emitted, in emission order, AS EMITTED.
Definition cli_run.h:124
std::string error
Empty on success; the what() of the exception otherwise.
Definition cli_run.h:132
std::string text
Everything written to fd 1, with the collected documents still in it.
Definition cli_run.h:127
std::string diagnostics
Everything written to fd 2: warnings, and the failure message.
Definition cli_run.h:129
A CTMC solve routed to whichever path the model's region rules require.
std::vector< T > parked
mean parked jobs per class; empty off the WAITQ path
The answer of @@SolverCTMC/getFirstPassTMoments.m.
std::vector< T > p
(nstates) probability of entering B (before C), one row per state
Matrix< T > mall
(nstates x nmax), one row per starting state
std::vector< std::size_t > source
resolved 0-based rows; empty = conditional stationary
std::vector< std::size_t > target
resolved 0-based rows
std::vector< std::size_t > taboo
resolved 0-based rows of C minus B; empty = none
std::vector< T > m
(nmax) moments for a passage started uniformly in A
The answer of @@SolverCTMC/getCdfFirstPassT.m: the [F(t), t] curve with its grid, density and resolve...
[infGen, eventFilt, ev] of @@SolverCTMC/getGenerator.m.
std::vector< std::vector< Matrix< T > > > preempt_filt
std::vector< Matrix< T > > filt
eventFilt: filt[a] holds only what synchronization sync[a] contributed, so sum_a filt[a] is the off-d...
std::vector< Sync< T > > sync
ev, the reference's sn.sync
std::vector< std::vector< Matrix< T > > > start_filt
The DERIVED START/PREEMPT filtrations, indexed [station-1][class-1].
Matrix< T > Q
the infinitesimal generator
What one mdd solve produces beside the means, i.e.
long long num_states
|S|, counted in the diagram without ever listing a state.
int iters
Coupled fixed-point sweeps performed.
bool no_aggregation
True certifies the answer is exact structurally; see the file header.
std::string encoding
Which local encoding was picked, "np" or "ps".
std::vector< std::size_t > level_sizes
|M_k| per paper level; their sum is what the diagram actually holds.
The SolverCTMC knobs this port honours.
bool force
options.force: downgrade the memory pre-gate's refusal to a warning.
bool stiff
options.stiff, which SolverOptions defaults to TRUE and the transient passes to ctmc_transient as use...
std::vector< std::vector< std::size_t > > cutoff_mat
options.cutoff AS A (station x class) MATRIX, or empty.
double fau_delta
options.config.fau_delta: occupancy below which a state is dropped.
double cutoff
< 0 = not given
double timestep
options.timestep: the FIXED OUTPUT STEP of a transient analysis.
std::string nonmkv
options.config.nonmkv: 'bernstein' (default) runs sn_nonmarkov_toph, 'none' skips it; any other name ...
std::string transient_method
options.config.transient_method: "ode" (the default) integrates the forward equation,...
std::vector< CtmcRateSched > rate_sched
options.config.rate_sched: the TIME-INHOMOGENEOUS transient.
std::size_t ctmc_tv_ngrid
options.config.ctmc_tv_ngrid: uniform grid size of the rate_sched propagator.
double fau_epsilon
options.config.fau_epsilon: total probability mass the whole grid may discard under "fau".
bool keep_filtration
Keep the per-synchronization EVENT FILTRATION alongside Q.
One entry of options.config.rate_sched: the rate of (station, class) follows the piecewise-linear sch...
std::vector< double > rates
std::vector< double > tgrid
What the reward analyzer produces, per declared reward.
std::vector< Matrix< T > > V
V[r] is (Tmax+1 x nstates).
std::vector< T > t
iteration index / q
Matrix< T > state_space_aggr
the rows the reward saw
std::vector< std::string > names
One sampled trajectory of the chain.
std::vector< std::size_t > event
synchronization that fired to LEAVE it
std::vector< std::size_t > state
0-based index into chain.space
std::vector< T > t
time at which each state was ENTERED
The scalar parameter a sensitivity is taken with respect to.
std::function< void(NetworkStruct< T > &, double)> set
Apply theta to a COPY of the struct; the original is never mutated.
Everything one CTMC solve produces.
std::string warning
Set when the chain is a reducible mixture solved from an invented seed.
std::vector< std::size_t > cutoff
the per-class cutoff actually used
std::vector< T > pi
stationary distribution over chain.space
[stateSpace, localStateSpace] of @@SolverCTMC/getStateSpace.m.
std::vector< std::size_t > node_width
column width of each stateful node's block
std::vector< Matrix< T > > local
localStateSpace{f}: one matrix per stateful node, its DISTINCT local rows in first-appearance order.
Matrix< T > flat
the blocks concatenated, as MATLAB returns them
The time-dependent answer of one getTranProb* query.
Matrix< T > pit
(ntimes x nstates) occupancy over the solved chain
std::vector< T > t
The reference returns Pi_t = [t, pi_t], one matrix with time glued on as column 1.
Matrix< T > labels
(nstates x width) the state descriptor the query asked for
What one transient CTMC solve produces.
What the ENV entry reports: the environment-blended metrics, and the whole result of whichever coupli...
std::string method
What ran: meanfield, statevec, or the limit avg / dec.
EnvLimitSolution limit
Populated on the closed-form limit path (avg, dec, occupation); limit.occupation / limit....
EnvStatevecSolution< T > statevec
Populated on the state-vector path.
bool converged
True on the limit path: a closed form has converged by construction.
solvers::CacheMetrics< T > cache
The environment-blended cache surface, whichever coupling produced it.
int iterations
ZERO ON THE LIMIT PATH, and that is the answer rather than a gap: a limit reads the environment once ...
std::vector< double > occupation
occupation only (getStageOccupation): the expected time spent in each stage over the horizon,...
std::vector< double > occupation_weight
Options of SolverENV.
Definition solver_env.h:122
std::string method
The inter-stage coupling: meanfield is the reference's default.
Definition solver_env.h:145
std::vector< double > env_init
Method occupation: options.config.env_init, the initial probability of each stage.
Definition solver_env.h:175
std::string stage_solver
Which solver runs each FLAT stage: fluid (the fluid transient), ctmc (the enumerated chain),...
Definition solver_env.h:139
bool stage_stiff
options.stiff of a CTMC stage, read only when stage_solver is ctmc.
Definition solver_env.h:160
fluid::FluidOptions stage
Options handed to each stage solver.
Definition solver_env.h:149
double stage_cutoff
options.cutoff of a CTMC stage, read only when stage_solver is ctmc.
Definition solver_env.h:154
double timespan_end
options.timespan(2) of the inner solver: the transient horizon.
Definition solver_env.h:162
double env_timespan_start
Method occupation: SolverENV's OWN options.timespan, [t0, t1].
Definition solver_env.h:169
std::size_t tran_points
Points on a UNIFORM transient grid, used only where stage_grid declines to build one (a stage whose h...
Definition solver_env.h:188
std::vector< double > g
Definition fluid_aoi.h:259
std::vector< double > h
Definition fluid_aoi.h:261
Matrix< double > A
Definition fluid_aoi.h:260
std::string system_type
"bufferless" or "singlebuffer"
Definition fluid_aoi.h:269
What the AoI gate found, when it matches.
Definition fluid_aoi.h:88
The four outputs of @@SolverFLD/getJacobian.
std::string engine
sage or local, whichever produced J
std::vector< std::string > rhs
the drift, one expression per variable
std::vector< std::vector< std::string > > J
J[i][j] = d f_i / d x_j.
bool has_equilibria
the backend answered the equilibria request
std::vector< std::map< std::string, std::string > > equilibria
Nonnegative solutions of f(x) = 0 together with the conserved invariants (fluid_conservation_constrai...
std::vector< std::string > vars
state variable names
The transient the covariance equation produces, i.e.
Definition fluid_kp.h:120
Matrix< double > Sigma
state-level covariance, on range(D)
Matrix< double > QStd
per station and class queue-length variance
Controls, defaulting to SolverOptions('Fluid') in the reference.
double pstar
exponent of the 'pnorm' smoothing
double iter_tol
>0 stops early when the moved-mass ratio falls below it; 0 runs to iter_max, as the reference does
double tol
absolute and relative tolerance handed to the integrator
std::string fluid_boundary
options.config.fluid_boundary: how the Petri dae route reports a fluid place level held at a bound,...
std::string nonmkv
options.config.nonmkv: 'bernstein' (default) runs sn_nonmarkov_toph, 'none' skips it; any other name ...
std::size_t iter_max
cap on outer integrations
bool pstar_set
Opt in to the p-norm under matrix/default too, which is what options.config.pstar does in MATLAB,...
What the analyzer returns, in the same shape as the MVA solver's result.
bool has_moments
result.solverSpecific.moments: set only by minnormal and mnrefined.
std::vector< double > XN
bool has_aoi
result.solverSpecific.aoiResults: set only by the AoI branch of mfq, where the age laws,...
FluidMomentReport moments
std::string warning
The reference's line_warning text, verbatim, empty when it did not warn.
std::vector< double > xvec
the converged fluid state
solvers::FjMetrics< double > fj
self.result.FJ, set by the fork-join arm (fluid_fork_join_run); empty otherwise.
std::vector< double > CN
The symbolic system, in whichever of the two forms the method implies.
Backend selection, mirroring options.config.symbolic and its timeout.
bool equilibria
The reference's nargout >= 4: ask the backend to solve f(x) = 0.
std::string backend
auto to search, a URL, an image name, or none to stay local.
A closed interval the generator samples from.
The simulation controls the JSIM header carries, MATLAB's JMTIO properties.
Definition jmt_writer.h:69
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
The per-class queue-length trajectory of one node, plus its event stream.
Definition jmt_logs.h:227
The options of one JMT solve, SolverOptions('JMT') restricted to what is read.
Definition solver_jmt.h:123
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
bool keep
keep the scratch directory after the solve
Definition solver_jmt.h:127
double samples
samples per measure; raised to 5000 below
Definition solver_jmt.h:125
What jmt_prob_aggr reports: the system probability and the per-station ones.
Definition jmt_logs.h:779
std::vector< bool > station_seen
the same, per station
Definition jmt_logs.h:783
bool sys_seen
whether the joint state occurred at all
Definition jmt_logs.h:782
double sys
P(the whole network is in the declared state).
Definition jmt_logs.h:780
std::vector< double > station
P(station i holds its declared per-class counts).
Definition jmt_logs.h:781
Transient averages over independent replications, on one time grid.
Definition jmt_logs.h:880
std::vector< double > t
Definition jmt_logs.h:881
std::vector< std::vector< std::vector< double > > > UNt
Definition jmt_logs.h:884
std::size_t valid
Replications that produced a usable trajectory.
Definition jmt_logs.h:887
std::vector< std::vector< std::vector< double > > > TNt
Definition jmt_logs.h:885
std::vector< std::vector< std::vector< double > > > QNt
QNt[ist-1][r] over t.
Definition jmt_logs.h:883
The result of a JMT solve: the shared AvgResult plus what only JMT reports.
Definition solver_jmt.h:828
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
mva::AvgResult< T > avg
Definition solver_jmt.h:829
Matrix< T > ACI
confidence half-widths, empty when disabled
Definition solver_jmt.h:830
Matrix< T > DropRateNfcr
(nregions x nclasses) carried and lost rate
Definition solver_jmt.h:832
The system trajectory: one per-class block per station, on a common grid.
Definition jmt_logs.h:483
static Distrib exp_rate(const T &r)
static constexpr double FineTol
Definition lang_types.h:823
static constexpr double CoarseTol
Definition lang_types.h:824
The knobs of one LDES run.
double warmupfrac
–warmupfrac, only for tranfilter=fixed
bool verbose
echo the resolved command line before running it
double cnvgtol
–cnvgtol
std::string rest_url
Base URL of an LDES REST server (the imperialqore/ldes container).
long seed
–seed; -1 requests a random stream
bool slotted
–slotted, run on the slot lattice
bool cnvgon
–cnvgon
std::string cimethod
–cimethod: obm | bm | spectral | none
double slot_length
–slotlength
int replications
–replications; 0 = not given (one path)
std::size_t events
0 = not given; overrides samples when set
std::string tranfilter
–tranfilter: mser5 | fixed | none
std::vector< double > init_sol
–initsol, the warm-start placement as a STATION-MAJOR vector [st0_cl0, st0_cl1, .....
int numthreads
–numthreads; 0 = not given
std::size_t samples
-s, service-completion budget
double timeout
–maxtime, a COOPERATIVE wall-clock budget the event loop polls; the wrapper caps it by any options....
bool has_timespan
true when [t0,t1] was set: a TRANSIENT run
One (station, class) row of getPerctRespT on SolverLDES: the steady-state response-time p-quantiles w...
std::vector< bool > heuristic
true where the fallback interval was used
std::string station
node name of the station
double level
confidence level
std::vector< double > halfwidth
halfwidths
std::vector< double > lower
lower confidence limits
std::size_t station_index
0-based station index in the result
std::vector< double > upper
upper confidence limits
std::vector< double > percentiles
fractions in (0,1)
std::size_t class_index
0-based class index in the result
std::string job_class
class name (class in MATLAB / Python)
std::size_t samples
observations used (per replication after trimming, times R)
std::vector< double > values
point estimates (QuestResult::estimate)
std::string method
"fquest" or "firquest"
One ldes-result document, parsed.
std::vector< std::string > fj_forks
Fork and Join node NAMES of each pair, ordered by fork node then join node; empty without a pair.
std::map< std::string, LdesCacheMetrics > cache_metrics
Per-cache metrics, keyed by the Cache NODE name.
Matrix< double > FJTput
getAvgFJ, FJQLen = FJTput * FJRespT
Matrix< double > TNCI
Matrix< double > WNfcr
std::vector< std::vector< Matrix< double > > > QNt
[STATION][class] -> (npoints x 2), columns [value, time].
Matrix< double > XN
(1 x nclasses), per-class visits and system tput
std::vector< std::vector< std::vector< double > > > respTimeSamples
[station][class] -> the per-job response times the engine recorded, in departure order.
Matrix< double > FJQLen
Matrix< double > UNfcr
Matrix< double > FJRespT
Matrix< double > WeightNfcr
Matrix< double > QNfcr
Matrix< double > UN
Matrix< double > DropRateNfcr
Matrix< double > histogram_space
The exact joint-state residence-time histogram (–export-histogram).
std::string stopping_reason
convergence | max_events | max_sim_events | max_time.
std::vector< std::vector< Matrix< double > > > UNt
std::vector< std::string > class_names
Matrix< double > TN
Matrix< double > UNCI
Matrix< double > RN
std::string engine
"native" or "jar": which runner produced these numbers.
Matrix< double > QNCI
Matrix< double > CN
Matrix< double > RNfcr
Matrix< double > WN
Matrix< double > AN
long long total_simulated_events
Matrix< double > MemOccNfcr
Matrix< double > TNfcr
std::vector< std::string > station_names
Matrix< double > DropRateJoin
quorum-Join sibling drops, Join rows only
std::vector< std::string > fj_joins
Matrix< double > histogram_time
Matrix< double > RNCI
std::vector< double > t
the time vector, empty on a steady-state run
Matrix< double > WNCI
Matrix< double > QN
std::vector< std::vector< Matrix< double > > > TNt
Matrix< double > ANfcr
Matrix< double > ANCI
The layered result: per element, the mean measures.
Matrix< double > WLN
Residence time per element, the ResidT column: the time an activity holds ITS HOST PROCESSOR per visi...
std::vector< std::vector< double > > entry_resp_samples
Every per-request ENTRY response time observed, one vector per entry in LOCAL index space (0....
double simulated_time
Length of the MEASURED span, from the end of warmup to the end of the run.
long long completions
Reference-task cycles completed in the measured span.
Options of SolverLN.
Definition solver_ln.h:275
getSensitivityTable of the ensemble: the layer tables under a Layer column.
Definition solver_ln.h:485
std::vector< Row > rows
Definition solver_ln.h:490
std::string method
The summary label: the common branch, or "mixed" when they differ.
Definition solver_ln.h:494
The LQN-level answer, indexed by element 1..nidx.
Definition solver_ln.h:420
std::vector< T > WN
Definition solver_ln.h:421
std::vector< bool > defined_W
Definition solver_ln.h:422
std::vector< bool > defined_U
Definition solver_ln.h:422
std::string warning
A warning the analysis raised, verbatim, empty when it raised none (method='nlp' off a root).
Definition solver_ln.h:433
std::vector< T > QN
Definition solver_ln.h:421
std::vector< bool > defined_R
Definition solver_ln.h:422
std::vector< T > RN
Definition solver_ln.h:421
std::vector< bool > defined_Q
Definition solver_ln.h:422
bool is_bound
True when the numbers are a BOUND (method = mw.upper / mw.lower) rather than the fixed point.
Definition solver_ln.h:431
std::vector< T > UN
Definition solver_ln.h:421
std::vector< bool > defined_T
Definition solver_ln.h:422
std::vector< T > TN
Definition solver_ln.h:421
The layered transient: one block per layer, plus how it was produced.
Definition solver_ln.h:476
The intermediate model, and the second stage that flattens it.
Definition lqn_reader.h:411
std::vector< LqnElement > type
(nidx+1)
Definition lqn_struct.h:213
std::vector< bool > iscache
(tshift+ntasks+1)
Definition lqn_struct.h:266
std::size_t nentries
Definition lqn_struct.h:208
std::vector< std::string > names
(nidx+1) declared name
Definition lqn_struct.h:211
std::vector< bool > isref
(tshift+ntasks+1)
Definition lqn_struct.h:265
Knobs of the wrapper, the subset of SolverOptions that reaches lqns.
Definition solver_lqns.h:84
The six measures, on the element index space, with a defined mask each.
std::vector< bool > defined_U
std::vector< T > UN
std::vector< bool > defined_W
std::vector< bool > defined_Q
std::vector< T > RN
std::vector< bool > defined_R
std::vector< T > TN
std::vector< T > QN
std::vector< bool > defined_T
std::vector< T > WN
SolverLQNS.defaultOptions on a flat Network plus the knobs the JMVA document carries.
bool keep
options.keep: leave the scratch directory behind, to inspect what was sent.
std::string multiserver
options.config.multiserver.
std::string method
default, qns or qns.NAME; see qns_methods().
The options SolverMAM reads.
Definition mam_types.h:30
std::size_t mapmsg_quantization
options.config.mapmsg_quantization: the number of regimes the MAP/M/s+G reneging analyzer quantizes t...
Definition mam_types.h:128
int iter_max
SolverOptions('MAM') lowers this from the global 1000 to 100.
Definition mam_types.h:34
std::string ispn_place
options.config.ispn_place: the unbounded level of the 'ispn' method, a place name or 'place....
Definition mam_types.h:134
double timespan_start
options.timespan: the transient horizon.
Definition mam_types.h:184
std::optional< double > censor_level_index
options.config.censor_level given as a 1-based STATION INDEX.
Definition mam_types.h:152
std::string timescale
options.config.timescale: "auto", "discrete" or "continuous".
Definition mam_types.h:167
std::string nonmkv
options.config.nonmkv: 'bernstein' (default) runs sn_nonmarkov_toph, 'none' skips it; any other name ...
Definition mam_types.h:61
std::size_t fj_accuracy
options.config.fj_accuracy: the FJ_codes truncation C of the queue-length DIFFERENCE between the two ...
Definition mam_types.h:109
std::string method
Definition mam_types.h:31
std::size_t cutoff
options.cutoff: the level truncation getProb / getProbMarg use for an OPEN model, where the queue len...
Definition mam_types.h:81
std::string censor_level
options.config.censor_level given as a STATION NAME: the level station of the 'censor' method (solver...
Definition mam_types.h:144
std::string fj_tmode
options.config.fj_tmode: which route computeT.m takes to the T matrix, 'NARE' (Riccati,...
Definition mam_types.h:115
std::size_t sync_phases
options.config.sync_phases: the synchronous phase expansion of the 'sync.faster' / 'sync....
Definition mam_types.h:122
double slotlength
options.config.slotlength: the slot in model time units, the lattice unit d.
Definition mam_types.h:178
std::size_t ispn_maxlevel
options.config.ispn_maxlevel: the largest level window the 'ispn' method explores before refusing the...
Definition mam_types.h:139
The joint (level, phase) table getProb returns: rows levels, cols phases.
What getTranAvg returns: queue length, utilization and throughput curves.
Knobs of the level iteration in mdd_mcd.
Definition mdd_types.h:212
double tol
Convergence tolerance on the level marginals.
Definition mdd_types.h:214
int maxiter
Maximum coupled sweeps before the iteration is declared non-convergent.
Definition mdd_types.h:216
Port of @@SolverMVA/getProbAggr.m: P(n1 jobs of class 1, n2 of class 2, ...) at station ist for the m...
The metrics getAvg returns, after filtering.
std::shared_ptr< qn::NetworkStruct< T > > refreshed_struct
The struct whose cache self-switch carries the CONVERGED hit/miss split, filled by the cacheqn branch...
Matrix< T > TN
throughput
Matrix< T > RN
response time, per visit
std::string warning
The reference's own warning text, verbatim, empty when it did not warn.
Matrix< T > UN
utilization
solvers::FjMetrics< T > fj
self.result.FJ: the fork-join section metrics FJQLen, FJRespT and FJTput, filled by the solvers the f...
std::vector< T > listcost
(h) mean storage cost held by each cache list, K_j = sum_i sigma_i pi_ij, filled only by the NC cache...
std::optional< double > lognormconst
@@SolverNC/getProbNormConstAggr, i.e.
std::optional< bool > converged
Whether the fixed point met its tolerance, empty when the handler reports none.
Matrix< T > WN
residence time, per job
std::string method
the method asked for
std::string actualmethod
the algorithm that ran
Matrix< T > QN
queue length
std::vector< T > CN
system response time per class
std::vector< T > XN
system throughput per class
solvers::CacheMetrics< T > cache
What the cache branches observed, EMPTY on a model with no Cache node and on every solver that does n...
Matrix< T > AN
arrival rate
A marginal distribution and its logarithm, over the states asked for.
std::vector< T > logP
The options SolverMVA reads.
Definition mva_types.h:32
std::string multiserver
Definition mva_types.h:37
std::string method
Definition mva_types.h:33
std::string fork_join
options.config.fork_join: which fork-join arm the fixed point takes.
Definition mva_types.h:52
Class-level results, the [Q,U,R,T,C,X] of the MATLAB analyzers.
Definition mva_types.h:97
std::vector< T > X
Definition mva_types.h:99
std::vector< T > C
Definition mva_types.h:99
The response-time distributions, station by class.
std::vector< std::vector< Matrix< T > > > RD
std::string warning
Non-empty when the reference WARNS AND RETURNS EMPTY rather than computing: today only "applies only ...
std::vector< T > tset
the shared evaluation grid
The knobs of one perfect-sampling run.
std::size_t samples
Number of iid stationary draws, SolverOptions('NC').samples by default.
unsigned long seed
Stream seed, so a row is reproducible within this port.
What one cftp solve produces beside the means.
std::vector< long > horizon
(samples) per-draw coalescence horizon, or the mixing steps of M_A.
std::vector< std::vector< int > > distinct_states
The distinct sampled states, aligned with paggr.
What the marginal analyzers return: one probability per station.
std::vector< T > P
(M) probability that station i holds its given vector
The [Q,U,R,T,C,X,lG] of the reference, plus the algorithm that ran.
Definition nc_types.h:134
std::string actualmethod
Definition nc_types.h:136
Controls, defaulting to SolverOptions('NC') in the reference.
Definition nc_types.h:35
double slotlength
options.config.slotlength, the slot length in model time units: the lattice unit, never a rescale.
Definition nc_types.h:119
std::string multiserver
options.config.multiserver: how a finite multiserver station is represented.
Definition nc_types.h:65
std::string fork_join
options.config.fork_join: which fork-join arm the shared fixed point takes on a model with a Fork.
Definition nc_types.h:53
double tol
options.tol
Definition nc_types.h:37
std::size_t samples
options.samples, read by the estimators
Definition nc_types.h:66
unsigned long seed
options.seed, read by the estimators
Definition nc_types.h:67
bool slotted
options.config.slotted.
Definition nc_types.h:108
std::string cdf_algorithm
options.config.algorithm for getCdfRespT: 'exact' selects pfqn_stdf, 'rd' the heuristic pfqn_stdf_heu...
Definition nc_types.h:92
double iter_tol
options.iter_tol, the eta stopping test
Definition nc_types.h:38
What State.toMarginal returns for one station and one state row.
Definition state.h:56
std::vector< T > nir
jobs per class
Definition state.h:58
One network state: the per-stateful-node local rows it is composed of.
Definition state.h:3022
std::vector< std::vector< T > > local
local[isf] is that node's state row
Definition state.h:3023
Everything qsys_bmapm1 returns, mirroring the MATLAB result struct.
Definition qsys_bmapm1.h:62
T q
uniformization constant actually used
Definition qsys_bmapm1.h:66
T drift
stable iff strictly negative
Definition qsys_bmapm1.h:72
T pi0
probability the system is empty
Definition qsys_bmapm1.h:75
Matrix< T > levelProb
level probabilities, row n = pi_n
Definition qsys_bmapm1.h:74
T lambda
mean arrival rate, theta (sum_k k D_k) e
Definition qsys_bmapm1.h:64
std::vector< T > theta
stationary vector of the BMAP phase process
Definition qsys_bmapm1.h:63
T rho
offered load lambda/mu
Definition qsys_bmapm1.h:65
double decayRate
measured pi_(n+1)/pi_n; NaN when unmeasurable
Definition qsys_bmapm1.h:73
std::vector< T > alpha
stationary vector of A
Definition qsys_bmapm1.h:70
The name-value contract of getSensitivityTable.
bool simulation
True when the callback is a simulator, which widens the default step.
double step
Relative step of the rate perturbation; negative selects the default.
std::string scheme
forward | central
std::string method
auto | exact | fd
One (station, class) row of the table.
What the table carries, plus the branch that produced it.
std::vector< SensRow< T > > rows
std::string method
"exact" or "fd", the branch actually taken
Every Cache node of the model, in node order; empty on a model with none.
std::vector< CacheNodeMetrics< T > > caches
One Cache node's measured behaviour.
std::vector< T > delayedhitqlen
(n) mean secondary requests waiting on the in-flight fetch of each item, and the same including the r...
std::vector< double > itemcap
(h) capacity of each list
std::vector< double > itemsize
(n) storage cost per item, EMPTY without setItemSizes
std::vector< T > hitprob
(K) TRUE hit fraction, EMPTY = not computed
std::vector< T > delayedprob
(K) delayed-hit fraction, EMPTY off a retrieval system
Matrix< T > hitproblist
(K x h) per-list hit fraction, EMPTY = not computed
std::size_t node
1-based node index of the Cache
std::vector< T > latency
(K) expected latency per read request (hits wait 0), EMPTY = not computed
std::vector< T > listcost
(h) mean storage cost held by each list
Matrix< T > itemprob
(n x h+1), column 0 = miss; EMPTY = not computed
std::vector< T > delayedhitqlenfull
std::string name
The Cache node's NAME, which is what a cross-language payload must key on.
The station- or node-level table aggregated by chain.
Matrix< T > TN
(rows x nchains), rows = stations or nodes
One options.config key; an empty placement means "not implemented there".
const char * values
comma-separated admissible values; empty when any string is taken
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
bool empty() const
No pair to report: a model without Fork/Join, or a solver that does not compute them.
Definition fj_metrics.h:52
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
The caller-facing map_env knobs, options.config.map_env and friends.
std::size_t max_stages
0 = the transform's own default cap
The station table scattered to the NODE index space, plus the two flow columns the reference recomput...
@@NetworkSolver/getAvgSys: one response time and one throughput per chain.
std::vector< T > XN
(nchains) system throughput at the reference station
std::vector< T > CN
(nchains) system response time, i.e. the cycle time
Controls, defaulting to SolverOptions('SSA') in the reference.
Definition ssa_types.h:71
std::size_t samples
Reaction firings to simulate; options.samples in the reference.
Definition ssa_types.h:75
double warmupfrac
options.config.warmupfrac: the leading fraction of the path discarded before the means are taken.
Definition ssa_types.h:96
std::string method
default and nrm both select the Next Reaction Method here.
Definition ssa_types.h:73
double timestep
options.timestep: the fixed step h of method tstep (ssa_tstep.h).
Definition ssa_types.h:121
unsigned long seed
options.seed; LINE's own default is 23000.
Definition ssa_types.h:77
double cutoff
options.cutoff: the bound on an open class's jobs at a station, which the serial and replicated engin...
Definition ssa_types.h:114
The four probabilities -a prob reports, over one requested state.
SsaProbResult sys_aggr
getProbSys, getProbSysAggr
std::vector< SsaProbResult > aggr
getProb, getProbAggr, per station
std::vector< SsaProbResult > marg
One trajectory, in the shape the reference's sampleSys returns it.
std::vector< double > t
the event times, increasing
Matrix< T > aggr
the same, as per-(stateful, class) counts
std::vector< std::size_t > event
which synchronization fired
Matrix< T > state
per event: the state OCCUPIED until then
The serial engine's knobs: SsaOptions plus the three the serial path reads and the NRM has no use for...
The serial analyzer's return: the metric table, the path, and the stream.
std::shared_ptr< const qn::NetworkStruct< T > > solved_sn
The struct the path was simulated on when it differs from the caller's (ctmc_mapc widens a multiserve...
What the analyzer returns, in the same shape as the MVA and fluid results.
Definition ssa_types.h:154
std::vector< double > XN
Definition ssa_types.h:156
std::vector< double > CN
Definition ssa_types.h:156
Matrix< double > UN
Definition ssa_types.h:155
Matrix< double > RN
Definition ssa_types.h:155
double simulated_time
Simulated time the metrics are averaged over; the reference's totalTime.
Definition ssa_types.h:168
Matrix< double > TN
Definition ssa_types.h:155
std::size_t samples
Reaction firings actually performed.
Definition ssa_types.h:170
Matrix< double > QN
Definition ssa_types.h:155
std::string method
The concrete algorithm, as the reference's method.
Definition ssa_types.h:166
UQ.getInterval: the RANGE of every metric over the support of the Priors.
Definition solver_uq.h:728
std::string method
mvainterval or sampled.
Definition solver_uq.h:738
bool exact
True when the interval is the attained hull rather than a sampled range.
Definition solver_uq.h:736
Matrix< T > Qlo
(nstations x nclasses) lower and upper endpoints of each metric.
Definition solver_uq.h:730
std::string why
On the sampled path, the condition that disqualified the exact one.
Definition solver_uq.h:740
T Xlo
System throughput and total response time; the EXACT path only.
Definition solver_uq.h:732
UQ.defaultOptions plus the stream the Monte Carlo design draws from.
Definition solver_uq.h:86
std::string method
default | dd | quad | mc, MATLAB UQ.listValidMethods.
Definition solver_uq.h:93
std::size_t samples
Nodes per continuous Prior, or design points under mc; the reference's options.samples,...
Definition solver_uq.h:100
unsigned long seed
The Monte Carlo stream; unread by a quadrature design, which draws nothing.
Definition solver_uq.h:102
What solver_uq_run_analyzer returns.
Definition solver_uq.h:126
std::vector< T > weights
The design weights, summing to 1.
Definition solver_uq.h:132
std::string method
The RESOLVED discretization method: quad or mc.
Definition solver_uq.h:138
std::vector< mva::AvgResult< T > > points
The result at each design point, in design order.
Definition solver_uq.h:130
std::vector< PriorSite< T > > sites
Where the Priors were found.
Definition solver_uq.h:136
std::vector< UqDesignPoint< T > > design
The alternatives each point substituted, one per site.
Definition solver_uq.h:134
mva::AvgResult< T > avg
The prior-weighted expectation of every metric, (nstations x nclasses).
Definition solver_uq.h:128
The inner solver's knobs, carried through untranslated.
Definition uq_dispatch.h:65
double tol
< 0 = not given
Definition uq_dispatch.h:70
double cutoff
ctmc open-population cutoff; < 0 = not given
Definition uq_dispatch.h:75
std::string solver
mva | nc | mam | ba | ctmc | fluid | ssa.
Definition uq_dispatch.h:67
Resolves the symbolic backend to use, and owns the container that serves it.
The stage solver of SolverUQ, named rather than passed.
Minimal RFC 6455 WebSocket server, enough to serve LineWebSocketServer's protocol.