LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
ldes_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
6/**
7 * @file
8 * `ldes`: the native LDES engine behind the interface of `jline.cli.LdesCLI`.
9 *
10 * WHAT THIS BINARY IS FOR. `common/ldes` has been a GraalVM image of the JAVA
11 * engine; this program is its replacement, built from
12 * `cpp/include/line/solvers/ldes/`. Every client of that binary -- MATLAB's
13 * `@SolverLDES/solveCli.m`, native Python's `wrappers/solver_ldes`, and the C++
14 * client `wrappers/ldes/solver_ldes.h` -- speaks to it through exactly two
15 * artefacts: the ARGUMENT VECTOR and the `ldes-result` DOCUMENT. Neither may
16 * drift. A client is not recompiled when the engine changes hands, so an
17 * argument this program rejects and the Java one accepted, or a key it spells
18 * differently, is a silent breakage in three codebases at once.
19 *
20 * THE INTERFACE IS THEREFORE COPIED, not designed:
21 *
22 * ldes solve <model.json> -o <result.json> [flags]
23 *
24 * with the flag set of `LdesCLI.handleSolveCommand` and the document shape of
25 * `LDESResultIO.write`. Flags this engine cannot honour are REFUSED BY NAME
26 * rather than ignored, which is the one deliberate difference from the AOT
27 * image it replaces: that image ignored flags it predated, and an ignored
28 * `--slotlength` silently ran a continuous-time simulation under a slotted
29 * model's name. A refusal is visible; a silent default is not.
30 *
31 * A LAYEREDNETWORK document (`modelType: LayeredNetwork`) is dispatched to the
32 * native LN engine, `ldes_ln_engine_solve`, and answered with the layered
33 * document of `LDESResultIO.saveLN` (see `ln_result_json`). Flags that engine
34 * has no counterpart for (transient, histograms, busy periods, warm starts,
35 * slotted time, replications) are refused by name.
36 *
37 * WHAT IS NOT HERE. `--rest`/server mode belongs to `line_cli` and is refused
38 * with the reason rather than accepted and dropped.
39 */
40
41#include <algorithm>
42#include <cctype>
43#include <cerrno>
44#include <chrono>
45#include <cmath>
46#include <cstdio>
47#include <ctime>
48#include <cstdlib>
49#include <fstream>
50#include <iostream>
51#include <limits>
52#include <sstream>
53#include <string>
54#include <vector>
55
62#include "line/util/error.h"
63
64namespace {
65
68
69void print_help() {
70 std::cout
71 << "LDES: discrete-event simulation engine for LINE models.\n\n"
72 << "Usage: ldes solve <model.json> [-o <result.json>] [options]\n\n"
73 << "Options:\n"
74 << " -s, --samples N service completions to simulate (default 200000)\n"
75 << " -e, --maxevents N event budget; overrides --samples\n"
76 << " --maxtime SECONDS wall-clock budget\n"
77 << " --seed N run seed (default 23000; -1 draws one)\n"
78 << " --method NAME engine method (default 'default')\n"
79 << " --cnvgon stop on the convergence check\n"
80 << " --cnvgtol X relative tolerance of that check\n"
81 << " --cnvgbatch N batches before the first check\n"
82 << " --cnvgchk N events between checks\n"
83 << " --tranfilter NAME mser5 | fixed | none\n"
84 << " --mserbatch N MSER batch size\n"
85 << " --warmupfrac X warmup fraction, for --tranfilter fixed\n"
86 << " --tranobs N transient observation points over --timespan\n"
87 << " --cimethod NAME obm | bm | spectral | none\n"
88 << " --obmoverlap X overlap of the batch means\n"
89 << " --ciminbatch N batches below which no CI is reported\n"
90 << " --ciminobs N observations below which no CI is reported\n"
91 << " --spectrallowfreqfrac X low-frequency fraction of the spectral CI\n"
92 << " --slotted run on the slot lattice\n"
93 << " --slotlength X slot length (implies --slotted)\n"
94 << " --replications N independent replications\n"
95 << " --numthreads N threads across replications\n"
96 << " --timespan T0,T1 transient run over [T0,T1]\n"
97 << " --busyperiod K busy-period orders 1..K\n"
98 << " --busyperiod-subnet i,j,... an extra busy-period target\n"
99 << " --initsol V initial state, station-major, comma separated\n"
100 << " --initjobs J job-level initial state, one row per job, rows ';'\n"
101 << " separated: station,class,remaining,elapsed,qage,sage,order[,id]\n"
102 << " --trackjobs export the final job-level state and tagged departures\n"
103 << " --export-histogram fill the state histogram block\n"
104 << " --trajectory fill the state trajectory block\n"
105 << " --respt-samples record every per-visit response time\n"
106 << " --sample-path <N> Export the exact sample path: N rows of events and LINE State\n"
107 << " (one replication, no warmup removal)\n"
108 << " -h, --help this text\n";
109}
110
111[[noreturn]] void fail(const std::string& msg) {
112 std::cerr << "Error: " << msg << "\n";
113 std::exit(1);
114}
115
116/** A flag the reference accepts and this engine cannot honour: say so. */
117[[noreturn]] void refuse(const std::string& flag, const std::string& why) {
118 std::cerr << "Error: " << flag << " is accepted by the Java engine but not by this one: "
119 << why << ".\nRun the model through common/ldes.jar for it, rather than "
120 "taking a silently different simulation.\n";
121 std::exit(1);
122}
123
124std::string need_value(int argc, char** argv, int& i, const std::string& flag) {
125 if (i + 1 >= argc) fail(flag + " requires a value.");
126 return std::string(argv[++i]);
127}
128
129std::vector<double> parse_doubles(const std::string& csv) {
130 std::vector<double> out;
131 std::stringstream ss(csv);
132 std::string tok;
133 while (std::getline(ss, tok, ',')) {
134 if (!tok.empty()) out.push_back(std::atof(tok.c_str()));
135 }
136 return out;
137}
138
139std::vector<std::size_t> parse_indices(const std::string& csv) {
140 std::vector<std::size_t> out;
141 std::stringstream ss(csv);
142 std::string tok;
143 while (std::getline(ss, tok, ',')) {
144 if (!tok.empty()) out.push_back(static_cast<std::size_t>(std::atol(tok.c_str())));
145 }
146 return out;
147}
148
149/** A JSON number the way the reference writes it: full round-trip precision. */
150std::string num(double v) {
151 if (std::isnan(v)) return "null";
152 if (std::isinf(v)) return v > 0 ? "1e999" : "-1e999";
153 char buf[40];
154 std::snprintf(buf, sizeof(buf), "%.17g", v);
155 return std::string(buf);
156}
157
158/** A (rows x cols) matrix as the nested array `LDESResultIO` emits. */
159std::string mat_json(const line::Matrix<double>& m, std::size_t rows, std::size_t cols) {
160 std::string s = "[";
161 for (std::size_t i = 0; i < rows; ++i) {
162 if (i) s += ", ";
163 s += "[";
164 for (std::size_t j = 0; j < cols; ++j) {
165 if (j) s += ", ";
166 const bool inside = (i < m.rows() && j < m.cols());
167 s += num(inside ? m(i, j) : 0.0);
168 }
169 s += "]";
170 }
171 s += "]";
172 return s;
173}
174
175/** One `[station][class][sample]` block of per-visit response times. */
176std::string respt_block_json(const std::vector<std::vector<std::vector<double>>>& b) {
177 std::string s = "[";
178 for (std::size_t i = 0; i < b.size(); ++i) {
179 if (i) s += ", ";
180 s += "[";
181 for (std::size_t k = 0; k < b[i].size(); ++k) {
182 if (k) s += ", ";
183 s += "[";
184 for (std::size_t j = 0; j < b[i][k].size(); ++j) {
185 if (j) s += ", ";
186 s += num(b[i][k][j]);
187 }
188 s += "]";
189 }
190 s += "]";
191 }
192 s += "]";
193 return s;
194}
195
196/** The per-visit response times as the nested `[station][class][sample]` array. */
197std::string respt_samples_json(const LdesResult& r) {
198 if (r.respTimeSamples.empty()) return std::string();
199 return respt_block_json(r.respTimeSamples);
200}
201
202/**
203 * The per-replication response times as the nested `[rep][station][class][sample]`
204 * array, or empty when the run kept none (one path, or a transient run): the
205 * engine fills `respTimeSamplesRep` only for replications >= 2.
206 */
207std::string respt_samples_rep_json(const LdesResult& r) {
208 if (r.respTimeSamplesRep.size() < 2) return std::string();
209 std::string s = "[";
210 for (std::size_t q = 0; q < r.respTimeSamplesRep.size(); ++q) {
211 if (q) s += ", ";
212 s += respt_block_json(r.respTimeSamplesRep[q]);
213 }
214 s += "]";
215 return s;
216}
217
218std::string str_json(const std::string& s) {
219 std::string out = "\"";
220 for (char c : s) {
221 if (c == '"' || c == '\\') {
222 out += '\\';
223 out += c;
224 } else if (c == '\n') {
225 out += "\\n";
226 } else {
227 out += c;
228 }
229 }
230 out += "\"";
231 return out;
232}
233
234/**
235 * The `ldes-result` document, key for key with `LDESResultIO.write`.
236 *
237 * The order of the keys is the reference's, and the blocks a run did not fill
238 * are still emitted with their zero matrices: every client indexes this
239 * document by key and by station row, and a missing block reads as a parse
240 * failure rather than as an absent measurement.
241 */
242
243std::string sp_mat(const line::Matrix<double>& m) {
244 std::string s = "[";
245 for (std::size_t i = 0; i < m.rows(); ++i) {
246 if (i) s += ", ";
247 s += "[";
248 for (std::size_t j = 0; j < m.cols(); ++j) {
249 if (j) s += ", ";
250 s += num(m(i, j));
251 }
252 s += "]";
253 }
254 return s + "]";
255}
256
257/** The `samplePath` block: t, events, statefulNodes, state, aggr, refusals, phases, unboundScripts, simTime. */
258std::string sample_path_json(const line::ldes::LdesSamplePath& sp) {
259 std::string s = "{\"t\": [";
260 for (std::size_t k = 0; k < sp.t.size(); ++k) s += (k ? ", " : "") + num(sp.t[k]);
261 s += "], \"events\": [";
262 for (std::size_t k = 0; k < sp.events.size(); ++k) {
263 s += k ? ", [" : "[";
264 for (std::size_t c = 0; c < sp.events[k].size(); ++c) s += (c ? ", " : "") + num(sp.events[k][c]);
265 s += "]";
266 }
267 s += "], \"statefulNodes\": [";
268 for (std::size_t k = 0; k < sp.stateful_nodes.size(); ++k)
269 s += (k ? ", " : "") + std::to_string(sp.stateful_nodes[k]);
270 s += "], \"state\": [";
271 for (std::size_t k = 0; k < sp.state.size(); ++k)
272 s += (k ? ", " : "") + (sp.refusals[k].empty() ? sp_mat(sp.state[k]) : std::string("null"));
273 s += "], \"aggr\": [";
274 for (std::size_t k = 0; k < sp.aggr.size(); ++k) s += (k ? ", " : "") + sp_mat(sp.aggr[k]);
275 s += "], \"refusals\": [";
276 for (std::size_t k = 0; k < sp.refusals.size(); ++k)
277 s += (k ? ", " : "") + (sp.refusals[k].empty() ? std::string("null") : str_json(sp.refusals[k]));
278 s += "], \"phases\": [";
279 for (std::size_t i = 0; i < sp.phases.size(); ++i) {
280 s += i ? ", [" : "[";
281 for (std::size_t k = 0; k < sp.phases[i].size(); ++k)
282 s += (k ? ", " : "") + num(static_cast<double>(sp.phases[i][k]));
283 s += "]";
284 }
285 s += "], \"unboundScripts\": " + std::to_string(sp.unbound_scripts);
286 s += ", \"simTime\": " + num(sp.sim_time) + "}";
287 return s;
288}
289
290std::string result_json(const LdesResult& r, const LdesOptions& o, double runtime,
291 std::size_t events) {
292 const std::size_t S = r.nstations, C = r.nclasses;
293 std::string s;
294 s += "{\n";
295 s += " \"format\": \"ldes-result\",\n";
296 s += " \"version\": \"1.0\",\n";
297 s += " \"solver\": \"SolverLDES\",\n";
298 s += " \"method\": " + str_json(o.method) + ",\n";
299 s += " \"runtime\": " + num(runtime) + ",\n";
300 // The engine's own verdict: these were written as constants, so a run that
301 // stopped on `--cnvgon` reported `max_events` and 0 batches (closed 2026-11-14).
302 s += std::string(" \"converged\": ") + (r.converged ? "true" : "false") + ",\n";
303 s += std::string(" \"stoppingReason\": \"") +
304 (r.stopping_reason == "sample_path" || r.stopping_reason == "max_time" ||
305 r.stopping_reason == "convergence"
306 ? r.stopping_reason
307 : std::string("max_events")) +
308 "\",\n";
309 s += " \"convergenceBatches\": " + std::to_string(r.convergence_batches) + ",\n";
310 s += " \"totalSimulatedEvents\": " + std::to_string(events) + ",\n";
311
312 s += " \"dimensions\": {\"nstations\": " + std::to_string(S) +
313 ", \"nclasses\": " + std::to_string(C) + ", \"nchains\": " + std::to_string(r.nchains) +
314 ", \"stationNames\": [";
315 for (std::size_t i = 0; i < r.station_names.size(); ++i) {
316 if (i) s += ", ";
317 s += str_json(r.station_names[i]);
318 }
319 s += "], \"classNames\": [";
320 for (std::size_t i = 0; i < r.class_names.size(); ++i) {
321 if (i) s += ", ";
322 s += str_json(r.class_names[i]);
323 }
324 s += "]},\n";
325
326 s += " \"metrics\": {";
327 s += "\"QN\": " + mat_json(r.QN, S, C);
328 s += ", \"UN\": " + mat_json(r.UN, S, C);
329 s += ", \"RN\": " + mat_json(r.RN, S, C);
330 s += ", \"TN\": " + mat_json(r.TN, S, C);
331 s += ", \"AN\": " + mat_json(r.AN, S, C);
332 s += ", \"WN\": " + mat_json(r.WN, S, C);
333 s += ", \"CN\": " + mat_json(r.CN, 1, C);
334 s += ", \"XN\": " + mat_json(r.XN, 1, C);
335 // The sibling-drop rate at a Join, where LossRate = ArvR - Tput does NOT
336 // hold: ArvR counts the SIBLINGS offered and Tput the PARENT jobs released.
337 // `LDESResultIO.write` puts it inside `metrics`, so it goes here and not in
338 // an optional block of its own.
339 if (!r.DropRateJoin.empty()) s += ", \"DropRateJoin\": " + mat_json(r.DropRateJoin, S, C);
340 s += "},\n";
341
342 // THE OPTIONAL BLOCKS, each written ONLY when the run measured it, exactly
343 // as `LDESResultIO.write` gates them. A block emitted empty is not the same
344 // as an absent one: `ldes_prob_from_histogram` and `getAvgBusyPeriod` both
345 // treat presence as the claim that the measurement was taken.
346 // GATED ON THE FLAG, not on the measurement. A transient run computes the
347 // histogram whether or not anyone asked for it, and `LDESResultIO` writes
348 // the block only when the flag was given; emitting it anyway would make
349 // this engine's document differ from the reference's on every transient run.
350 if (o.export_histogram && r.histogram_space.rows() > 0 && r.histogram_time.rows() > 0) {
351 s += " \"stateHistogram\": {";
352 s += "\"space\": " + mat_json(r.histogram_space, r.histogram_space.rows(),
353 r.histogram_space.cols());
354 s += ", \"time\": " + mat_json(r.histogram_time, r.histogram_time.rows(), 1);
355 if (r.traj_space.rows() > 0 && r.traj_time.rows() > 0) {
356 s += ", \"trajSpace\": " +
357 mat_json(r.traj_space, r.traj_space.rows(), r.traj_space.cols());
358 s += ", \"trajTime\": " + mat_json(r.traj_time, r.traj_time.rows(), 1);
359 }
360 s += "},\n";
361 }
362
363 if (!r.busy_periods.empty()) {
364 s += " \"busyPeriods\": {\"orders\": " +
365 std::to_string(r.busy_periods[0].mean.size()) + ", \"targets\": [";
366 for (std::size_t ti = 0; ti < r.busy_periods.size(); ++ti) {
367 const LdesResult::BusyPeriodTarget& t = r.busy_periods[ti];
368 if (ti) s += ", ";
369 s += "{\"name\": " + str_json(t.name) + ", \"stations\": [";
370 for (std::size_t k = 0; k < t.stations.size(); ++k) {
371 if (k) s += ", ";
372 s += std::to_string(t.stations[k]);
373 }
374 s += "], \"class\": " + std::to_string(t.job_class) + ", \"mean\": [";
375 for (std::size_t k = 0; k < t.mean.size(); ++k) {
376 if (k) s += ", ";
377 s += num(t.mean[k]);
378 }
379 s += "], \"count\": [";
380 for (std::size_t k = 0; k < t.count.size(); ++k) {
381 if (k) s += ", ";
382 s += num(t.count[k]);
383 }
384 s += "]}";
385 }
386 s += "]},\n";
387 }
388
389 // The job-level end state, in the --initjobs layout, so a run can be continued from it.
390 if (o.track_jobs || o.init_jobs.rows() > 0) {
391 s += " \"jobState\": {\"finalJobs\": " +
392 mat_json(r.finalJobs, r.finalJobs.rows(), r.finalJobs.cols());
393 s += ", \"jobDepartures\": " +
394 mat_json(r.jobDepartures, r.jobDepartures.rows(), r.jobDepartures.cols()) + "},\n";
395 }
396
397 // --sample-path: the recorded path, in the layout LDESResultIO writes.
398 if (r.has_sample_path) s += " \"samplePath\": " + sample_path_json(r.sample_path) + ",\n";
399
400 if (!r.cache_metrics.empty()) {
401 s += " \"cacheMetrics\": {";
402 bool first = true;
403 for (std::map<std::string, line::ldes::LdesCacheMetrics>::const_iterator it =
404 r.cache_metrics.begin();
405 it != r.cache_metrics.end(); ++it) {
406 if (!first) s += ", ";
407 first = false;
408 const line::ldes::LdesCacheMetrics& cm = it->second;
409 s += str_json(it->first) + ": {";
410 s += "\"hit\": " + mat_json(cm.hit, cm.hit.rows(), cm.hit.cols());
411 s += ", \"delayed\": " + mat_json(cm.delayed, cm.delayed.rows(), cm.delayed.cols());
412 s += ", \"miss\": " + mat_json(cm.miss, cm.miss.rows(), cm.miss.cols());
413 s += ", \"latency\": " + mat_json(cm.latency, cm.latency.rows(), cm.latency.cols());
414 s += ", \"hitList\": " + mat_json(cm.hitList, cm.hitList.rows(), cm.hitList.cols());
415 s += ", \"itemProb\": " + mat_json(cm.itemProb, cm.itemProb.rows(), cm.itemProb.cols());
416 s += ", \"listCost\": " + mat_json(cm.listCost, cm.listCost.rows(), cm.listCost.cols());
417 s += "}";
418 }
419 s += "},\n";
420 }
421
422 if (r.QNfcr.rows() > 0) {
423 const std::size_t G = r.QNfcr.rows();
424 s += " \"fcr\": {\"nregions\": " + std::to_string(G);
425 s += ", \"QNfcr\": " + mat_json(r.QNfcr, G, C);
426 s += ", \"UNfcr\": " + mat_json(r.UNfcr, G, C);
427 s += ", \"RNfcr\": " + mat_json(r.RNfcr, G, C);
428 s += ", \"TNfcr\": " + mat_json(r.TNfcr, G, C);
429 s += ", \"ANfcr\": " + mat_json(r.ANfcr, G, C);
430 s += ", \"WNfcr\": " + mat_json(r.WNfcr, G, C);
431 s += ", \"WeightNfcr\": " + mat_json(r.WeightNfcr, G, C);
432 s += ", \"MemOccNfcr\": " + mat_json(r.MemOccNfcr, G, C);
433 s += ", \"DropRateNfcr\": " + mat_json(r.DropRateNfcr, G, C);
434 s += "},\n";
435 }
436
437 // Fork-join section metrics (getAvgFJ), TOP-LEVEL as the Java engine writes them: one row per Fork/Join pair,
438 // named by "forks"/"joins", in fork-then-join node order. Steady state only, and only on a model with a pair.
439 if (r.t.empty() && !r.fj_forks.empty() && r.FJTput.rows() == r.fj_forks.size()) {
440 const std::size_t P = r.fj_forks.size();
441 s += " \"forkJoin\": {\"forks\": [";
442 for (std::size_t p = 0; p < P; ++p) s += (p ? ", " : "") + str_json(r.fj_forks[p]);
443 s += "], \"joins\": [";
444 for (std::size_t p = 0; p < P; ++p) s += (p ? ", " : "") + str_json(r.fj_joins[p]);
445 s += "]";
446 s += ", \"FJQLen\": " + mat_json(r.FJQLen, P, C);
447 s += ", \"FJRespT\": " + mat_json(r.FJRespT, P, C);
448 s += ", \"FJTput\": " + mat_json(r.FJTput, P, C);
449 s += "},\n";
450 }
451
452 // The reference gates the whole transient block on `--trajectory`, not on
453 // the run being transient.
454 // The samples appear at TOP LEVEL under --respt-samples and INSIDE the
455 // transient block under --trajectory. Both spellings are the reference's,
456 // and both are read: the C++ client takes whichever is present, MATLAB's
457 // `sample()` and `sampleSys()` read the nested one and returned nothing
458 // while only the top-level spelling existed.
459 const std::string respt_json = respt_samples_json(r);
460 if (o.export_trajectory && !r.t.empty()) {
461 s += " \"transient\": {\"t\": [";
462 for (std::size_t k = 0; k < r.t.size(); ++k) {
463 if (k) s += ", ";
464 s += num(r.t[k]);
465 }
466 s += "]";
467 const char* keys[3] = {"QNt", "UNt", "TNt"};
468 const std::vector<std::vector<line::Matrix<double>>>* src[3] = {&r.QNt, &r.UNt, &r.TNt};
469 for (int q = 0; q < 3; ++q) {
470 s += std::string(", \"") + keys[q] + "\": [";
471 for (std::size_t i = 0; i < src[q]->size(); ++i) {
472 if (i) s += ", ";
473 s += "[";
474 for (std::size_t k = 0; k < (*src[q])[i].size(); ++k) {
475 if (k) s += ", ";
476 const line::Matrix<double>& mm = (*src[q])[i][k];
477 s += mat_json(mm, mm.rows(), mm.cols());
478 }
479 s += "]";
480 }
481 s += "]";
482 }
483 if (!respt_json.empty()) s += ", \"respTimeSamples\": " + respt_json;
484 s += "},\n";
485 }
486
487 if (o.export_respt && !respt_json.empty())
488 s += " \"respTimeSamples\": " + respt_json + ",\n";
489 // [rep][station][class][sample], right after the pooled block and only under --respt-samples with R >= 2.
490 if (o.export_respt && o.replications >= 2) {
491 const std::string rep_json = respt_samples_rep_json(r);
492 if (!rep_json.empty()) s += " \"respTimeSamplesRep\": " + rep_json + ",\n";
493 }
494 s += " \"sampleCounts\": {";
495 s += "\"QNSamples\": " + mat_json(r.QNSamples, S, C);
496 s += ", \"UNSamples\": " + mat_json(r.UNSamples, S, C);
497 s += ", \"RNSamples\": " + mat_json(r.RNSamples, S, C);
498 s += ", \"TNSamples\": " + mat_json(r.TNSamples, S, C);
499 s += "},\n";
500
501 s += " \"confidenceIntervals\": {";
502 s += "\"QNCI\": " + mat_json(r.QNCI, S, C);
503 s += ", \"UNCI\": " + mat_json(r.UNCI, S, C);
504 s += ", \"RNCI\": " + mat_json(r.RNCI, S, C);
505 s += ", \"TNCI\": " + mat_json(r.TNCI, S, C);
506 s += ", \"ANCI\": " + mat_json(r.ANCI, S, C);
507 s += ", \"WNCI\": " + mat_json(r.WNCI, S, C);
508 s += "},\n";
509
510 s += " \"relativePrecision\": {";
511 s += "\"QNRelPrec\": " + mat_json(r.QNRelPrec, S, C);
512 s += ", \"UNRelPrec\": " + mat_json(r.UNRelPrec, S, C);
513 s += ", \"RNRelPrec\": " + mat_json(r.RNRelPrec, S, C);
514 s += ", \"TNRelPrec\": " + mat_json(r.TNRelPrec, S, C);
515 s += "},\n";
516
517 s += " \"impatience\": {";
518 s += "\"renegedCustomers\": " + mat_json(r.renegedCustomers, S, C);
519 s += ", \"avgRenegingWaitTime\": " + mat_json(r.avgRenegingWaitTime, S, C);
520 s += ", \"renegingRate\": " + mat_json(r.renegingRate, S, C);
521 s += ", \"balkedCustomers\": " + mat_json(r.balkedCustomers, S, C);
522 s += ", \"balkingProbability\": " + mat_json(r.balkingProbability, S, C);
523 s += ", \"retriedCustomers\": " + mat_json(r.retriedCustomers, S, C);
524 s += ", \"retrialDropped\": " + mat_json(r.retrialDropped, S, C);
525 s += ", \"avgOrbitSize\": " + mat_json(r.avgOrbitSize, S, C);
526 s += "}\n";
527 s += "}\n";
528 return s;
529}
530
531/** A 1-based (nidx+1) x 1 element column as the 1 x nidx row `LDESResultIO.saveLN` emits. */
532/**
533 * The instability cap the reference document carries: `LdesCLI` writes after `solver.getAvg()`, and
534 * `NetworkSolver.getAvg` caps every finite-server open station whose offered load
535 * rho = sum_r TN(i,r) / (c * lldpeak * rate(i,r)) reaches 1. Its UN becomes rho_r / rho_tot (station total 1)
536 * and QN, RN of its open classes become Inf; WN, TN and AN are left alone, since WN was derived before the cap.
537 * Exempt, as there: delays and the Source, a binding buffer (cap, classcap or a region), reneging, and a bulk
538 * (batch-service) station, whose `rates` is per firing rather than per job. It restates the Java rule rather than
539 * calling `mva::cap_unstable_open_stations`, which differs in the bulk exemption and would pull the MVA runner
540 * into this CLI. Before 2026-11-14 the engine reported the raw simulated backlog of a saturated station (he_arr:
541 * QN 222.9 against the reference's Inf).
542 */
543void ldes_cap_unstable_open_stations(const line::qn::NetworkStruct<double>& L, LdesResult& r) {
544 const std::size_t M = L.nstations, K = L.nclasses;
545 if (r.UN.rows() != M || r.TN.rows() != M || r.UN.cols() != K || r.TN.cols() != K) return;
546 bool any_open = false;
547 for (std::size_t k = 0; k < K; ++k)
548 if (std::isinf(L.classes[k].population)) any_open = true;
549 if (!any_open) return;
550 const double dinf = std::numeric_limits<double>::infinity();
551 for (std::size_t i = 0; i < M; ++i) {
552 const double c = L.stations[i].nservers;
553 if (std::isinf(c) || c <= 0.0) continue;
554 if (L.stations[i].nodetype == line::qn::NodeType::Source) continue;
555 bool exempt = (i < L.cap.size() && std::isfinite(L.cap[i]) && L.cap[i] >= 0.0);
556 if (!exempt && i < L.classcap.size())
557 for (double cc : L.classcap[i])
558 if (std::isfinite(cc) && cc >= 0.0) { exempt = true; break; }
559 if (!exempt)
560 for (const auto& rg : L.regions)
561 if (i < rg.members.size() && rg.members[i]) { exempt = true; break; }
562 if (!exempt)
563 for (line::lang::ImpatienceType it : L.stations[i].impatience)
564 if (it == line::lang::ImpatienceType::RENEGING) { exempt = true; break; }
565 if (!exempt)
566 for (std::size_t k = 0; k < K; ++k)
567 if (line::lang::process_is_batch(L.procid(i + 1, k + 1))) { exempt = true; break; }
568 if (exempt) continue;
569 double lldpeak = 1.0;
570 for (double v : L.stations[i].lldscaling)
571 if (!std::isnan(v) && !std::isinf(v) && v > lldpeak) lldpeak = v;
572 std::vector<double> rho(K, 0.0);
573 double rho_open = 0.0, rho_tot = 0.0;
574 bool has_open = false;
575 for (std::size_t k = 0; k < K; ++k) {
576 const double rate = L.rates(i, k), t = r.TN(i, k);
577 if (rate > 0.0 && t > 0.0) {
578 rho[k] = t / (c * lldpeak * rate);
579 rho_tot += rho[k];
580 if (std::isinf(L.classes[k].population)) {
581 rho_open += rho[k];
582 has_open = true;
583 }
584 }
585 }
586 if (!(has_open && rho_open >= 1.0 && rho_tot > 0.0)) continue;
587 for (std::size_t k = 0; k < K; ++k) {
588 r.UN(i, k) = rho[k] / rho_tot;
589 if (std::isinf(L.classes[k].population)) {
590 if (r.RN.rows() == M && r.RN.cols() == K) r.RN(i, k) = dinf;
591 if (r.QN.rows() == M && r.QN.cols() == K) r.QN(i, k) = dinf;
592 }
593 }
594 }
595}
596
597/**
598 * The per-JOB residence time the reference document carries as WN: `snGetResidTFromRespT`, which `LdesCLI` applies
599 * through `solver.getAvg()` before writing. RN is per visit, so it is scaled by this station's visits over the
600 * reference station's visits of the chain's reference class (or of every class in the chain when the chain names
601 * none); an Immediate class (RN below FineTol) passes through and values below 10*FineTol read as zero. It restates
602 * `mva::sn_get_residt_from_respt` rule for rule, because that header pulls the whole MVA runner into a CLI that
603 * otherwise compiles the engine alone (the build went past ten minutes with it), and must change with it.
604 */
605line::Matrix<double> ldes_residt_from_respt(const line::qn::NetworkStruct<double>& L, const line::Matrix<double>& RN) {
606 const std::size_t M = L.nstations, K = L.nclasses;
607 line::Matrix<double> V(M, K, 0.0);
608 for (std::size_t c = 0; c < L.nchains; ++c)
609 for (std::size_t i = 0; i < M; ++i) {
610 const std::size_t sf = L.stateful_of_station(i + 1);
611 for (std::size_t k = 0; k < K; ++k) V(i, k) += L.visits[c](sf - 1, k);
612 }
613 const double fine = line::lang::GlobalConstants::FineTol;
614 line::Matrix<double> WN(M, K, 0.0);
615 for (std::size_t i = 0; i < M; ++i)
616 for (std::size_t k = 0; k < K; ++k) {
617 const bool is_place = L.stations[i].nodetype == line::qn::NodeType::Place;
618 if ((L.disabled[i][k] && !is_place) || !(RN(i, k) > 0.0)) continue;
619 if (RN(i, k) < fine) {
620 WN(i, k) = RN(i, k);
621 continue;
622 }
623 std::size_t c = L.nchains;
624 for (std::size_t cc = 0; cc < L.nchains; ++cc)
625 if (L.chains[cc][k]) c = cc;
626 if (c == L.nchains) continue;
627 const std::size_t rs = L.classes[k].refstat;
628 double den = 0.0;
629 if (L.refclass[c] > 0) {
630 den = V(rs - 1, L.refclass[c] - 1);
631 } else {
632 for (std::size_t r : L.inchain[c]) den += V(rs - 1, r - 1);
633 }
634 if (den > 0.0) WN(i, k) = RN(i, k) * V(i, k) / den;
635 }
636 for (std::size_t i = 0; i < M; ++i)
637 for (std::size_t k = 0; k < K; ++k)
638 if (WN(i, k) < 10.0 * fine) WN(i, k) = 0.0;
639 return WN;
640}
641
642std::string ln_row_json(const line::Matrix<double>& m, std::size_t nidx) {
643 std::string s = "[[";
644 for (std::size_t k = 1; k <= nidx; ++k) {
645 if (k > 1) s += ", ";
646 s += num(k < m.rows() ? m(k, 0) : 0.0);
647 }
648 return s + "]]";
649}
650
651/** A 1 x n row of a per-call or per-entry-stream measure, as `addMatrix` writes it. */
652std::string ln_vec_json(const std::vector<double>& v) {
653 std::string s = "[[";
654 for (std::size_t k = 0; k < v.size(); ++k) {
655 if (k) s += ", ";
656 s += num(v[k]);
657 }
658 return s + "]]";
659}
660
661/**
662 * The LAYERED `ldes-result` document, key for key with `LDESResultIO.saveLN`, in the JAR's
663 * 0-based element index space (C++ element k is entry k-1 of every row and of `cacheMetrics`).
664 *
665 * UCallLN and TCallLN are per CALL (0-based call index, 1 x max(1, ncalls)) and UEntryClassLN per
666 * entry stream (local entry index, 1 x max(1, nentries)), as Solver_ssj_ln sizes them. The CI
667 * block is all null, as the JAR's layered engine leaves it.
668 */
669std::string ln_result_json(const line::lqn::LqnStruct<double>& lsn,
670 const line::ldes::engine::LnResult& r, const LdesOptions& o,
671 double runtime, bool respt) {
672 const std::size_t n = lsn.nidx;
673 // THE DOCUMENT CARRIES THE JAR ENGINE'S RAW CONVENTIONS, which differ from the LnResult table:
674 // ULN is MEAN BUSY SERVERS, undivided, because every client divides it by hostReachMult itself
675 // (Python getLNAvgTable); emitting the per-server figure would divide twice. QLN at a processor
676 // and RLN at a task are 0, as Solver_ssj_ln writes them; the native engine measures both, and
677 // LnResult keeps them for an in-process caller.
678 line::Matrix<double> QLN = r.QLN, ULN = r.ULN, RLN = r.RLN;
679 for (std::size_t k = 1; k <= n; ++k) {
680 ULN(k, 0) *= lsn.host_reach_mult(k);
681 if (k > lsn.hshift && k <= lsn.hshift + lsn.nhosts) QLN(k, 0) = 0.0;
682 if (k > lsn.tshift && k <= lsn.tshift + lsn.ntasks) RLN(k, 0) = 0.0;
683 }
684 std::string s = "{\"format\": \"ldes-result\", \"version\": \"1.0\", "
685 "\"modelType\": \"LayeredNetwork\", \"solver\": \"LDES\", ";
686 s += "\"method\": " + str_json(o.method) + ", \"runtime\": " + num(runtime) + ", ";
687 // Why the run stopped, LDESResultIO.saveLN's key: a client flags timedOut on "max_time".
688 s += std::string("\"stoppingReason\": \"") + (r.timed_out ? "max_time" : "max_events") + "\", ";
689 s += "\"dimensions\": {\"nidx\": " + std::to_string(n) +
690 ", \"nhosts\": " + std::to_string(lsn.nhosts) +
691 ", \"ntasks\": " + std::to_string(lsn.ntasks) +
692 ", \"nentries\": " + std::to_string(lsn.nentries) +
693 ", \"nacts\": " + std::to_string(lsn.nacts) +
694 ", \"ncalls\": " + std::to_string(lsn.ncalls) +
695 ", \"tshift\": " + std::to_string(lsn.tshift) +
696 ", \"eshift\": " + std::to_string(lsn.eshift) +
697 ", \"ashift\": " + std::to_string(lsn.ashift) + ", \"names\": [";
698 for (std::size_t k = 1; k <= n; ++k) {
699 if (k > 1) s += ", ";
700 s += str_json(k < lsn.names.size() ? lsn.names[k] : "Element" + std::to_string(k - 1));
701 }
702 s += "]}, \"metrics\": {";
703 s += "\"QLN\": " + ln_row_json(QLN, n) + ", \"ULN\": " + ln_row_json(ULN, n);
704 s += ", \"RLN\": " + ln_row_json(RLN, n) + ", \"WLN\": " + ln_row_json(r.WLN, n);
705 s += ", \"TLN\": " + ln_row_json(r.TLN, n) + ", \"ALN\": " + ln_row_json(r.ALN, n);
706 s += ", \"ZLN\": " + ln_row_json(r.ZLN, n);
707 s += ", \"UCallLN\": " + ln_vec_json(r.UCallLN) + ", \"TCallLN\": " + ln_vec_json(r.TCallLN);
708 s += ", \"UEntryClassLN\": " + ln_vec_json(r.UEntryClassLN) + "}, ";
709 s += "\"confidenceIntervals\": {\"QLNCI\": null, \"ULNCI\": null, \"RLNCI\": null, "
710 "\"TLNCI\": null}";
711 if (!r.cache_task.empty()) {
712 s += ", \"cacheMetrics\": [";
713 for (std::size_t i = 0; i < r.cache_task.size(); ++i) {
714 if (i) s += ", ";
715 s += "{\"cacheTaskIdx\": " + std::to_string(r.cache_task[i] - 1) +
716 ", \"itemEntryIdx\": " + std::to_string(r.cache_entry[i] - 1) +
717 ", \"hitProb\": " + num(r.cache_hit[i]) + ", \"missProb\": " +
718 num(r.cache_miss[i]) + ", \"delayedProb\": " + num(r.cache_delayed[i]) +
719 ", \"readRate\": " + num(r.cache_read_rate[i]) + "}";
720 }
721 s += "]";
722 }
723 if (respt) {
724 s += ", \"entryRespTimeSamples\": [";
725 for (std::size_t e = 0; e < r.entry_resp_samples.size(); ++e) {
726 if (e) s += ", ";
727 s += "[";
728 for (std::size_t j = 0; j < r.entry_resp_samples[e].size(); ++j) {
729 if (j) s += ", ";
730 s += num(r.entry_resp_samples[e][j]);
731 }
732 s += "]";
733 }
734 s += "]";
735 }
736 return s + "}\n";
737}
738
739} // namespace
740
741int main(int argc, char** argv) {
742 if (argc < 2) {
743 print_help();
744 return 1;
745 }
746 const std::string cmd = argv[1];
747 if (cmd == "-h" || cmd == "--help") {
748 print_help();
749 return 0;
750 }
751 if (cmd != "solve") {
752 std::cerr << "Error: unknown command '" << cmd << "'. The only command is 'solve'.\n";
753 return 1;
754 }
755 if (argc < 3) fail("solve requires a model file.");
756
757 const std::string model_path = argv[2];
758 std::string output_path;
759 LdesOptions o;
760 bool have_samples = false, have_events = false;
761 std::vector<std::string> given; // every flag passed, for the layered path's refusals
762
763 for (int i = 3; i < argc; ++i) {
764 const std::string a = argv[i];
765 given.push_back(a);
766 if (a == "-o") {
767 output_path = need_value(argc, argv, i, a);
768 } else if (a == "-s" || a == "--samples") {
769 o.samples = static_cast<std::size_t>(std::atol(need_value(argc, argv, i, a).c_str()));
770 have_samples = true;
771 } else if (a == "-e" || a == "--maxevents") {
772 o.events = static_cast<std::size_t>(std::atol(need_value(argc, argv, i, a).c_str()));
773 have_events = true;
774 } else if (a == "--maxtime") {
775 o.timeout = std::atof(need_value(argc, argv, i, a).c_str());
776 } else if (a == "--seed") {
777 o.seed = std::atol(need_value(argc, argv, i, a).c_str());
778 } else if (a == "--method") {
779 o.method = need_value(argc, argv, i, a);
780 } else if (a == "--cnvgon") {
781 o.cnvgon = true;
782 } else if (a == "--cnvgtol") {
783 o.cnvgtol = std::atof(need_value(argc, argv, i, a).c_str());
784 } else if (a == "--cnvgbatch") {
785 o.cnvgbatch = std::atoi(need_value(argc, argv, i, a).c_str());
786 } else if (a == "--cnvgchk") {
787 o.cnvgchk = std::atoi(need_value(argc, argv, i, a).c_str());
788 } else if (a == "--tranfilter") {
789 o.tranfilter = need_value(argc, argv, i, a);
790 } else if (a == "--mserbatch") {
791 o.mserbatch = std::atoi(need_value(argc, argv, i, a).c_str());
792 } else if (a == "--tranobs") {
793 o.tranobs = std::atoi(need_value(argc, argv, i, a).c_str());
794 if (o.tranobs <= 0) fail("--tranobs must be positive.");
795 } else if (a == "--warmupfrac") {
796 o.warmupfrac = std::atof(need_value(argc, argv, i, a).c_str());
797 } else if (a == "--cimethod") {
798 o.cimethod = need_value(argc, argv, i, a);
799 } else if (a == "--obmoverlap") {
800 o.obmoverlap = std::atof(need_value(argc, argv, i, a).c_str());
801 } else if (a == "--ciminbatch") {
802 o.ciminbatch = std::atoi(need_value(argc, argv, i, a).c_str());
803 } else if (a == "--ciminobs") {
804 o.ciminobs = std::atoi(need_value(argc, argv, i, a).c_str());
805 } else if (a == "--spectrallowfreqfrac") {
806 o.spectral_low_freq_frac = std::atof(need_value(argc, argv, i, a).c_str());
807 } else if (a == "--slotted") {
808 o.slotted = true;
809 } else if (a == "--slotlength") {
810 o.slot_length = std::atof(need_value(argc, argv, i, a).c_str());
811 o.slotted = true; // the reference lets --slotlength imply --slotted
812 } else if (a == "--replications") {
813 o.replications = std::atoi(need_value(argc, argv, i, a).c_str());
814 } else if (a == "--numthreads") {
815 o.numthreads = std::atoi(need_value(argc, argv, i, a).c_str());
816 } else if (a == "--timespan") {
817 const std::vector<double> t = parse_doubles(need_value(argc, argv, i, a));
818 if (t.size() != 2) fail("--timespan takes T0,T1.");
819 o.has_timespan = true;
820 o.t0 = t[0];
821 o.t1 = t[1];
822 } else if (a == "--busyperiod") {
823 o.busy_period_orders = std::atoi(need_value(argc, argv, i, a).c_str());
824 } else if (a == "--busyperiod-subnet") {
825 o.busy_period_subnets.push_back(parse_indices(need_value(argc, argv, i, a)));
826 } else if (a == "--initsol") {
827 o.init_sol = parse_doubles(need_value(argc, argv, i, a));
828 } else if (a == "--initjobs") {
829 const std::string v = need_value(argc, argv, i, a);
830 std::vector<std::vector<double>> rows;
831 std::size_t at = 0;
832 while (at <= v.size()) {
833 const std::size_t semi = std::min(v.find(';', at), v.size());
834 if (semi > at) rows.push_back(parse_doubles(v.substr(at, semi - at)));
835 at = semi + 1;
836 }
837 const std::size_t ncols = rows.empty() ? 0 : rows[0].size();
838 for (std::size_t r = 0; r < rows.size(); ++r)
839 if (rows[r].size() != ncols) fail("--initjobs rows must have the same length.");
840 o.init_jobs = line::Matrix<double>(rows.size(), ncols, 0.0);
841 for (std::size_t r = 0; r < rows.size(); ++r)
842 for (std::size_t c = 0; c < ncols; ++c) o.init_jobs(r, c) = rows[r][c];
843 } else if (a == "--trackjobs") {
844 o.track_jobs = true;
845 } else if (a == "--export-histogram") {
846 o.export_histogram = true;
847 } else if (a == "--trajectory") {
848 o.export_trajectory = true;
849 } else if (a == "--respt-samples") {
850 o.export_respt = true;
851 } else if (a == "--sample-path") {
852 // The reference's messages, verbatim (LdesCLI): Integer.parseInt is strict.
853 if (i + 1 >= argc) fail("--sample-path requires the number of rows.");
854 const std::string v(argv[++i]);
855 char* end = nullptr;
856 errno = 0;
857 const long n = std::strtol(v.c_str(), &end, 10);
858 if (v.empty() || *end != '\0' || errno == ERANGE || n > 2147483647L || n < -2147483648L ||
859 std::isspace(static_cast<unsigned char>(v[0])))
860 fail("Invalid sample-path value.");
861 if (n <= 0) fail("--sample-path requires a positive number of rows.");
862 o.sample_path_events = static_cast<int>(n);
863 } else if (a == "--rest") {
864 refuse(a, "server mode belongs to line-cli, not to this binary");
865 } else if (a == "-h" || a == "--help") {
866 print_help();
867 return 0;
868 } else {
869 fail("unknown option '" + a + "'.");
870 }
871 }
872 if (have_events && !have_samples) o.samples = o.events;
873
874 try {
875 // A LayeredNetwork takes the native LN engine (the twin of Solver_ssj_ln) and the layered
876 // document, as LdesCLI routes it to its own. That engine reads --samples/--maxevents,
877 // --seed and the wall-clock --maxtime (Solver_ssj_ln's options.timeout); the flags that
878 // change WHAT is simulated or reported are refused by name, where the JAR refuses
879 // --timespan/--trajectory/--sample-path and silently ignores the rest, and the estimation
880 // knobs (--cimethod, --warmup*, ...) are ignored exactly as the JAR's layered engine ignores
881 // them. Method 'ssj' is the JAR layered analyzer's alias of 'default'.
882 if (line::io::is_layered_json(model_path)) {
883 if (o.sample_path_events > 0)
884 fail("--sample-path is a Network-path option; the layered engine has no LINE State "
885 "layout to record.");
886 static const char* const network_only[] = {
887 "--timespan", "--tranobs", "--trajectory", "--export-histogram", "--busyperiod",
888 "--busyperiod-subnet", "--initsol", "--initjobs", "--trackjobs", "--slotted",
889 "--slotlength", "--replications"};
890 for (const std::string& g : given)
891 for (const char* f : network_only)
892 if (g == f)
893 fail(g + " is a Network-path option; the layered engine reports the steady "
894 "state of one replication only.");
895 if (o.method != "default" && o.method != "ssj")
896 fail("method '" + o.method + "' is not a layered LDES method; use 'default' or 'ssj'.");
899 const std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now();
901 const double runtime =
902 std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
903 const std::string doc = ln_result_json(lsn, r, o, runtime, o.export_respt);
904 if (output_path.empty()) {
905 std::cout << doc;
906 } else {
907 std::ofstream out(output_path.c_str());
908 if (!out) fail("cannot write '" + output_path + "'.");
909 out << doc;
910 }
911 std::cerr << "LDES analysis [method: default; type: approximate, randomized; lang: cpp; "
912 "native LN engine] completed in " << runtime << "s. Iterations: "
913 << r.events << ".\n";
914 return 0;
915 }
916 // A sample path is one realisation: never an average of replications.
917 if (o.sample_path_events > 0) o.replications = 1;
920
921 // WALL time, not std::clock(): the replications run on a thread pool, and CPU time summed over the
922 // threads would report the serial cost of a run that took a fraction of it.
923 const std::chrono::steady_clock::time_point t_start = std::chrono::steady_clock::now();
924 LdesResult r = line::ldes::ldes_engine_solve(sn, o);
925 const double runtime =
926 std::chrono::duration<double>(std::chrono::steady_clock::now() - t_start).count();
927 // WN IS THE PER-JOB RESIDENCE TIME, not the per-visit response time: the reference's `LdesCLI` writes the
928 // document after `solver.getAvg()`, whose `snGetResidTFromRespT` scales RN by V(i,r)/V(ref) and whose
929 // `SnArvRStateDependentBalance` then re-derives AN and WN at the stations a JSQ/SQ dispatcher feeds. The
930 // engine's single-visit WN = RN reported half the reference on a Bernoulli feedback loop with V = 2
931 // (imf_off: 4.90676 against 9.81351 at seed 23000; closed 2026-11-14).
932 if (r.RN.rows() == sn.nstations && r.RN.cols() == sn.nclasses) {
933 r.WN = ldes_residt_from_respt(sn, r.RN);
934 if (r.AN.rows() == sn.nstations && r.TN.rows() == sn.nstations)
935 line::sn::sn_arvr_state_dependent_balance(sn, r.AN, r.TN, &r.WN);
936 }
937 // WNCI: WN is RN times the visit ratio, so its half-width scales by the same
938 // WN/RN. It used to be left at 0; the JAR copies RNCI, which is the same
939 // number at a single-visit station and too narrow under feedback (closed 2026-11-14).
940 if (r.RNCI.rows() == r.RN.rows() && r.RNCI.cols() == r.RN.cols() &&
941 r.WN.rows() == r.RN.rows() && r.WN.cols() == r.RN.cols()) {
942 r.WNCI = r.RNCI;
943 for (std::size_t i = 0; i < r.RN.rows(); ++i)
944 for (std::size_t k = 0; k < r.RN.cols(); ++k) {
945 const double rn = r.RN(i, k), wn = r.WN(i, k);
946 if (rn > 0.0 && std::isfinite(rn) && std::isfinite(wn)) r.WNCI(i, k) = r.RNCI(i, k) * (wn / rn);
947 }
948 }
949 ldes_cap_unstable_open_stations(sn, r);
950
951 // The events the run SIMULATED, as the reference's `totalEventCount` counts them, not the budget: a run
952 // that converges, times out or ends its sample path early spent fewer, and a client planning a run
953 // length from the budget overstates N (closed 2026-11-14).
954 const std::string doc = result_json(r, o, runtime,
955 static_cast<std::size_t>(std::max<long long>(0, r.total_simulated_events)));
956 if (output_path.empty()) {
957 std::cout << doc;
958 } else {
959 std::ofstream out(output_path.c_str());
960 if (!out) fail("cannot write '" + output_path + "'.");
961 out << doc;
962 }
963 std::cerr << "LDES analysis [method: " << o.method
964 << "; type: approximate, randomized; lang: cpp] completed in " << runtime
965 << "s. Iterations: " << o.samples << ".\n";
966 return 0;
967 } catch (const line::UnsupportedError& e) {
968 std::cerr << "Error: [" << e.id() << "] " << e.what() << "\n";
969 return 2;
970 } catch (const line::Error& e) {
971 // Same exit status as before; only the vocabulary id is added to the line.
972 std::cerr << "Error: [" << e.id() << "] " << e.what() << "\n";
973 return 1;
974 } catch (const std::exception& e) {
975 std::cerr << "Error: " << e.what() << "\n";
976 return 1;
977 }
978}
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::size_t cols() const
Definition matrix.h:90
std::size_t rows() const
Definition matrix.h:89
A refusal: the feature, method or analysis is not covered: LINE:unsupported:<kind>.
Definition error.h:117
A network plus its refreshed NetworkStruct.
std::size_t stateful_of_station(std::size_t st) const
std::vector< std::vector< bool > > chains
(nchains x nclasses)
std::vector< std::size_t > refclass
(nchains) 1-based class, 0 = none
std::vector< std::vector< bool > > disabled
Matrix< double > procid() const
sn.procid (M x K): the ProcessType id of each (station, class) pair, as refreshProcessTypes....
std::vector< double > cap
sn.cap and sn.classcap: the total and per-class buffers.
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< std::vector< std::size_t > > inchain
1-based class indices per chain
std::vector< std::vector< double > > classcap
std::vector< Matrix< T > > visits
(nchains) each (nstateful x nclasses)
std::vector< Region > regions
A queueing network under construction.
const NetworkStruct< T > & get_struct()
The refreshed struct, MATLAB's model.getStruct().
The exception types the port throws.
int main(int argc, char **argv)
Definition ldes_cli.cpp:741
The NATIVE LDES discrete-event engine.
The NATIVE LDES engine for LAYERED (LQN) models, the C++ twin of jline/solvers/ldes/handlers/Solver_s...
The option and result records of SolverLDES, the discrete-event simulator.
model.json with type: "LayeredNetwork" -> LqnStruct, via LqnBuilder.
bool is_layered_json(const std::string &path)
True when a file is a LayeredNetwork model.json rather than an .lqnx.
qn::Network< T > read_network_json(const std::string &path)
Parse a model.json file into a qn::Network<T>.
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 ....
bool process_is_batch(ProcessType p)
True when an EVENT of this process releases (or, as a service process, completes) a BATCH of jobs who...
Definition lang_types.h:771
ImpatienceType
Impatience kinds, with the values of MATLAB ImpatienceType.
Definition lang_types.h:483
LdesResult ldes_engine_solve(const qn::NetworkStruct< T > &sn, const LdesOptions &o)
Simulate sn, over independent REPLICATIONS when options.replications > 1.
engine::LnResult ldes_ln_engine_solve(const lqn::LqnStruct< T > &lsn, const LdesOptions &o)
Simulate a layered model in process.
void fail(const std::string &msg)
Definition lqn_focus.h:153
void sn_arvr_state_dependent_balance(const qn::NetworkStruct< T > &L, Matrix< T > &AN, const Matrix< T > &TN, Matrix< T > *WN)
void refuse(const std::string &m)
Definition spn_ispn.h:110
Reader for the LINE model.json interchange (a Network model) into a qn::Network<T> built through the ...
Arrival rates at stations fed by a JSQ or SQ(d) dispatcher, from flow balance.
static constexpr double FineTol
Definition lang_types.h:823
Per-cache hit/miss/latency, as the cacheMetrics block carries them.
Matrix< double > listCost
(1 x nlists) mean storage cost held per list
Matrix< double > latency
(1 x nclasses) expected retrieval latency
Matrix< double > hitList
(nclasses x nlists) hit probability by list
Matrix< double > itemProb
(nitems x nlists+1) item position law
Matrix< double > delayed
(1 x nclasses) delayed-hit probability
Matrix< double > miss
(1 x nclasses) miss probability
Matrix< double > hit
(1 x nclasses) hit probability
The knobs of one LDES run.
One ldes-result document, parsed.
The samplePath block (--sample-path N): one simulated path in SolverSSA's row convention.
std::vector< Matrix< double > > aggr
[stateful] per-class counts per row (Inf at a source).
std::vector< std::vector< double > > events
Rows {step, time, type, node, class, jobId, phase}.
std::vector< int > stateful_nodes
0-based node index of each stateful node, in stateful order.
std::vector< std::vector< int > > phases
[stateful][class] phase count used for the state layout.
std::vector< Matrix< double > > state
[stateful] detailed rows (empty when refused), left-padded to equal width.
std::vector< std::string > refusals
[stateful] why the detailed state is not recorded, empty when it is.
std::vector< double > t
long long unbound_scripts
Drawn intervals no phase script could be bound to (recorded as one phase).
The layered result: per element, the mean measures.
std::vector< double > cache_read_rate
Matrix< double > ZLN
Think time per element, Solver_ssj_ln's ZLN: Little's law on a task's thread pool read backwards,...
bool timed_out
The run stopped on its wall-clock budget (LdesOptions::timeout) before max_events.
std::vector< double > cache_miss
Matrix< double > ALN
Arrival rate per element, Solver_ssj_ln's ALN: an entry's request rate (its throughput,...
std::vector< double > UEntryClassLN
Matrix< double > WLN
Residence time per element, the ResidT column: the time an activity holds ITS HOST PROCESSOR per visi...
std::vector< std::size_t > cache_entry
std::vector< double > cache_hit
std::vector< std::vector< double > > entry_resp_samples
Every per-request ENTRY response time observed, one vector per entry in LOCAL index space (0....
std::vector< std::size_t > cache_task
Cache measures, one row per ItemEntry that was read, pooled over the replicas of its cache task as So...
long long events
Activity completions over the whole run, warmup included: what the budget counts.
std::vector< double > TCallLN
Dispatches of each call per unit time, counted where the CALLER issues it (TCallLN[c-1]),...
std::vector< double > cache_delayed
std::vector< double > UCallLN
Per-CLASS occupancy of the task thread pools, Solver_ssj_ln's UCallLN and UEntryClassLN: the mean num...
std::size_t nentries
Definition lqn_struct.h:208
std::vector< std::string > names
(nidx+1) declared name
Definition lqn_struct.h:211
double host_reach_mult(std::size_t idx) const
Servers of the host of element idx that its work can reach: the divisor of every LQN Util column (Sol...
Definition lqn_struct.h:382