LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
jmt_writer.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 */
5#ifndef LINE_IO_JMT_WRITER_H
6#define LINE_IO_JMT_WRITER_H
7
8/**
9 * @file
10 * @ingroup line_io
11 * Port of `@@JMTIO`: a refreshed `NetworkStruct` written out as a JMT `.jsimg`
12 * simulation model.
13 *
14 * THE REFERENCE WALKS NODE OBJECTS; THIS PORT WALKS THE STRUCT. MATLAB's
15 * `writeJSIM` iterates `model.nodes{i}` and asks each for its three SECTIONS
16 * (input, server, output), which are objects the node's constructor installed.
17 * This port has no node objects -- `network_builder` produces a `NetworkStruct`
18 * directly -- so `jmt_sections` re-derives the same triple from the node type
19 * and the scheduling strategy, transcribing the constructors of `Queue.m`,
20 * `Source.m`, `Sink.m`, `Router.m`, `ClassSwitch.m`, `Cache.m`, `Logger.m`,
21 * `Fork.m`, `Join.m`, `Place.m` and `Transition.m`. That table is the one place
22 * where this port can drift from the reference without a compiler error, so it
23 * names its source file for each row.
24 *
25 * WHAT IS DELIBERATELY REPRODUCED RATHER THAN CORRECTED. Two places in the
26 * reference emit less than they appear to, and all four codebases agree on the
27 * result, so this port agrees with them and says so at the site:
28 * - `saveForkStrategy` emits ONE OutPath entry (the last connected node),
29 * not one per branch -- harmless only because `isSimplifiedFork` is true.
30 * - the analytic `MMPP2Par` branch of `saveServiceStrategy` is unreachable,
31 * because the MAP branch catches MMPP2 first.
32 * Changing either here would make the C++ row the odd one out, which is the
33 * opposite of what a port is for.
34 */
35
36#include <algorithm>
37#include <cmath>
38#include <cstdio>
39#include <iostream>
40#include <limits>
41#include <map>
42#include <memory>
43#include <set>
44#include <string>
45#include <vector>
46
47#include "line/io/jmt_dist.h"
49#include "line/util/error.h"
50#include "line/util/xml.h"
51
52namespace line {
53namespace io {
54
56using lang::NodeType;
61
62/**
63 * The simulation controls the JSIM header carries, MATLAB's `JMTIO` properties.
64 *
65 * `max_events = -1` and `sim_conf_int = 0.99` / `sim_max_rel_err = 0.03` are the
66 * reference's constructor defaults; `max_samples` is `options.samples`, which
67 * `runAnalyzer` raises to 5000 before it reaches here.
68 */
70 std::string file_name = "model"; ///< base name; the header echoes it plus `.jsimg`
71 std::string log_path; ///< `model.getLogPath`, the `logPath` attribute
72 long seed = 23000;
73 double max_samples = 10000.0;
74 double max_events = -1.0;
75 double max_simulated_time = std::numeric_limits<double>::infinity();
76 double sim_conf_int = 0.99;
77 double sim_max_rel_err = 0.03;
78 /// JMT 1.5.0 or later runs the document: its Server takes a switchover
79 /// argument ahead of delayOff/setUp, so the delay-off form gains it.
80 bool jmt150 = false;
81};
82
83/**
84 * `sn.connmatrix`: which ordered pairs of nodes the model LINKED.
85 *
86 * The reference carries the matrix on the struct, recorded by `Network.addLink`.
87 * This port records the links only through the routing blocks `P`, so the
88 * connection set is their union support. That is the same set for every model
89 * built the way `link(P)` builds one -- `addLink` is called from `link` for each
90 * nonzero entry -- and it is what the JSIM `<connection>` list, the ClassSwitch
91 * row sum, the WRROBIN and PROB destination lists and the SPN input/output
92 * vectors all read.
93 *
94 * `Peff` IS NOT USED HERE, deliberately: it has the RAND/RROBIN expansion and
95 * the class-switch folding applied, so a Router's declared links would come
96 * back as the links of the stations it routes to, and the exported topology
97 * would not be the user's.
98 */
99template <class T>
100std::vector<std::vector<bool>> jmt_conn_matrix(const qn::NetworkStruct<T>& sn) {
101 const std::size_t I = sn.nodes.size();
102 std::vector<std::vector<bool>> C(I, std::vector<bool>(I, false));
103 const T zero = num_traits<T>::from_int(0);
104 for (const auto& kv : sn.P) {
105 const Matrix<T>& B = kv.second;
106 for (std::size_t a = 0; a < B.rows() && a < I; ++a)
107 for (std::size_t b = 0; b < B.cols() && b < I; ++b)
108 if (!(B(a, b) == zero)) C[a][b] = true;
109 }
110 return C;
111}
112
113/**
114 * Port of `getExportableClasses`.
115 *
116 * A closed class with no customers is dropped from the exported model UNLESS
117 * jobs can still reach it: as a cache hit/miss class, or through a class switch
118 * from a populated class of the same chain. Exporting it anyway would give JMT
119 * a class it can never see and, for a closed class, a reference station with
120 * zero population -- which JMT reports as an unreachable measure rather than as
121 * an empty one.
122 */
123template <class T>
125 const std::size_t K = sn.nclasses;
126 std::set<std::size_t> cache_classes; // 1-based
127 for (const auto& kv : sn.nodeparam) {
128 const qn::CacheParam<T>& cp = kv.second;
129 for (std::size_t r = 0; r < cp.hitclass.size(); ++r)
130 if (cp.hitclass[r] > 0) cache_classes.insert(cp.hitclass[r]);
131 for (std::size_t r = 0; r < cp.missclass.size(); ++r)
132 if (cp.missclass[r] > 0) cache_classes.insert(cp.missclass[r]);
133 }
134 std::set<std::size_t> switch_classes;
135 for (std::size_t c = 0; c < sn.chains.size(); ++c) {
136 std::vector<std::size_t> in;
137 for (std::size_t r = 0; r < K; ++r)
138 if (sn.chains[c][r]) in.push_back(r + 1);
139 if (in.size() <= 1) continue;
140 bool has_jobs = false;
141 for (std::size_t r : in)
142 if (sn.classes[r - 1].population > 0.0) has_jobs = true;
143 if (has_jobs)
144 for (std::size_t r : in) switch_classes.insert(r);
145 }
146 std::vector<bool> keep(K, true);
147 for (std::size_t r = 1; r <= K; ++r) {
148 const double n = sn.classes[r - 1].population;
149 if (std::isfinite(n) && n == 0.0 && !cache_classes.count(r) && !switch_classes.count(r))
150 keep[r - 1] = false;
151 }
152 return keep;
153}
154
155/**
156 * The three JMT section class names of a node: input, server, output.
157 *
158 * An empty entry is a section the node does not have -- only a Sink, whose
159 * `getSections` returns `{'', JobSink, ''}`. The names are LINE's section class
160 * names; `jmt_write_jsim` overwrites the ones JMT spells differently, exactly
161 * where the reference does.
162 */
163template <class T>
165 std::string input, server, output;
166};
167
168template <class T>
171 const qn::NodeDef& nd = sn.nodes[ind - 1];
172 const std::size_t ist = nd.station;
173 switch (nd.nodetype) {
174 case NodeType::Source: // Source.m:66-68
175 s.input = "RandomSource";
176 s.server = "ServiceTunnel";
177 s.output = "Dispatcher";
178 break;
179 case NodeType::Sink: // Sink.m:28, getSections
180 s.server = "JobSink";
181 break;
182 case NodeType::Router: // Router.m:62-66
183 s.input = "Buffer";
184 s.server = "ServiceTunnel";
185 s.output = "Dispatcher";
186 break;
187 case NodeType::ClassSwitch: // ClassSwitch.m:32-38
188 s.input = "Buffer";
189 s.server = "StatelessClassSwitcher";
190 s.output = "Dispatcher";
191 break;
192 case NodeType::Cache: // Cache.m:57-58; the server section is a
193 s.input = "Buffer"; // CacheClassSwitcher whose className is 'Cache'
194 s.server = "Cache";
195 s.output = "Dispatcher";
196 break;
197 case NodeType::Logger: // Logger.m:40-47
198 s.input = "Buffer";
199 s.server = "LogTunnel";
200 s.output = "Dispatcher";
201 break;
202 case NodeType::Fork: // Fork.m:106-109
203 s.input = "Buffer";
204 s.server = "ServiceTunnel";
205 s.output = "Forker";
206 break;
207 case NodeType::Join: // Join.m:34-36
208 s.input = "Joiner";
209 s.server = "ServiceTunnel";
210 s.output = "Dispatcher";
211 break;
212 case NodeType::Transition: // Transition.m:29-36
213 s.input = "Enabling";
214 s.server = "Timing";
215 s.output = "Firing";
216 break;
217 case NodeType::Place: // Place.m:27-31 and installQueueServer
218 s.input = "Storage";
219 s.output = "Linkage";
220 s.server = "ServiceTunnel";
221 if (ist != 0) {
222 bool queueing = false;
223 for (std::size_t r = 0; r < sn.nclasses; ++r)
224 if (!sn.service[ist - 1][r].disabled) queueing = true;
225 if (queueing) {
226 const SchedStrategy sch = sn.stations[ist - 1].sched;
227 if (sch == SchedStrategy::INF)
228 s.server = "InfiniteServer";
229 else if (sch == SchedStrategy::PS || sch == SchedStrategy::DPS ||
230 sch == SchedStrategy::GPS || sch == SchedStrategy::LPS)
231 s.server = "SharedServer";
232 else
233 s.server = "Server";
234 }
235 }
236 break;
237 case NodeType::Queue:
238 case NodeType::Delay:
239 default: { // Queue.m:48-53 and the schedStrategy switch at :79-110
240 s.input = "Buffer";
241 s.output = "Dispatcher";
242 const SchedStrategy sch =
243 ist != 0 ? sn.stations[ist - 1].sched : SchedStrategy::FCFS;
244 switch (sch) {
245 case SchedStrategy::PS:
246 case SchedStrategy::DPS:
247 case SchedStrategy::GPS:
248 case SchedStrategy::PSPRIO:
249 case SchedStrategy::DPSPRIO:
250 case SchedStrategy::GPSPRIO:
251 case SchedStrategy::LPS:
252 s.server = "SharedServer";
253 break;
254 // SRPTStrategy, like every put strategy below, implements
255 // QueuePutStrategies.PreemptiveStrategy, so JMT's Queue.process
256 // casts the server section to PreemptiveServer and a plain
257 // Server aborts the run with a ClassCastException.
258 case SchedStrategy::SRPT:
259 case SchedStrategy::SRPTPRIO:
260 case SchedStrategy::LCFSPR:
261 case SchedStrategy::LCFSPRPRIO:
262 case SchedStrategy::FCFSPR:
263 case SchedStrategy::FCFSPRPRIO:
264 case SchedStrategy::LCFSPI:
265 case SchedStrategy::LCFSPIPRIO:
266 case SchedStrategy::FCFSPI:
267 case SchedStrategy::FCFSPIPRIO:
268 case SchedStrategy::EDF:
269 s.server = "PreemptiveServer";
270 break;
271 case SchedStrategy::INF:
272 s.server = "InfiniteServer";
273 break;
274 case SchedStrategy::POLLING:
275 s.server = "PollingServer";
276 break;
277 case SchedStrategy::RR:
278 // JSIM has no time-slice (quantum) server section; writing the
279 // station as FCFS would drop the preemptions silently.
280 throw UnsupportedError(ErrorKind{"SchedStrategy_RR"},
281 "SolverJMT: station uses round-robin (RR) scheduling with a quantum, "
282 "which JSIM does not simulate; use SolverLDES or SolverCTMC");
283 default:
284 s.server = "Server";
285 break;
286 }
287 break;
288 }
289 }
290 return s;
291}
292
293// ---------------------------------------------------------------------------
294// The metric handles, MATLAB `@@MNetwork/getAvgHandles.m`
295// ---------------------------------------------------------------------------
296
297/** The measure kinds `saveMetrics` requests, in the order it requests them. */
298enum class JmtMetricKind { QLen, Util, RespT, Tput, ArvR, Tard, SysTard };
299
300/** The JMT `type` attribute, MATLAB `MetricType.toText`. */
301inline const char* jmt_metric_text(JmtMetricKind k) {
302 switch (k) {
303 case JmtMetricKind::QLen: return "Number of Customers";
304 case JmtMetricKind::Util: return "Utilization";
305 case JmtMetricKind::RespT: return "Response Time";
306 case JmtMetricKind::Tput: return "Throughput";
307 case JmtMetricKind::ArvR: return "Arrival Rate";
308 case JmtMetricKind::Tard: return "Tardiness";
309 case JmtMetricKind::SysTard: return "System Tardiness";
310 }
311 return "Unknown Metric";
312}
313
314/**
315 * Port of the `disabled` rules in `getAvgHandles`, per (station, class).
316 *
317 * The rules are per kind: a Source or a Sink reports no queue length, response
318 * time, utilization or tardiness but DOES report throughput and arrival rate;
319 * a Fork or a Join reports no utilization; a station whose class has no service
320 * process reports nothing, EXCEPT that a cache hit/miss class keeps its
321 * throughput and arrival rate -- a job only ever passes through such a class,
322 * it is never served in it, and disabling the measure would leave the cache's
323 * hit rate unobservable.
324 *
325 * `has_service_tunnel` reproduces the reference's test on the SECTION object:
326 * a Source, a Join and an ordinary Place have a ServiceTunnel and are therefore
327 * exempt from the service-defined test entirely.
328 */
329template <class T>
330bool jmt_metric_enabled(const qn::NetworkStruct<T>& sn, JmtMetricKind kind, std::size_t ist,
331 std::size_t r, const std::vector<bool>& is_cache_class) {
332 const std::size_t ind = sn.station_to_node[ist - 1];
333 const NodeType ty = sn.nodes[ind - 1].nodetype;
334 const bool is_source = ty == NodeType::Source;
335 const bool is_sink = ty == NodeType::Sink;
336 const JmtSections<T> sec = jmt_sections(sn, ind);
337 const bool tunnel = sec.server == "ServiceTunnel" || sec.server == "JobSink";
338 const bool service_defined = !sn.disabled[ist - 1][r - 1];
339
340 switch (kind) {
344 if (is_source || is_sink) return false;
345 return tunnel || service_defined;
347 if (is_source || is_sink) return false;
348 if (ty == NodeType::Join || ty == NodeType::Fork) return false;
349 return tunnel || service_defined;
352 if (tunnel) return true;
353 return service_defined || is_cache_class[r - 1];
355 return true;
356 }
357 return false;
358}
359
360/**
361 * Port of `jmtDeadlineRefusal.m`: the due date an EDD or EDF station needs and the
362 * model does not carry, as a sentence; empty when every such station can be exported.
363 *
364 * JMT 1.2.x orders an EDD/EDF buffer by softDeadlines(classId) + arrival time, read
365 * from the node's `<classSoftDeadlines>`, and EDDStrategy.put THROWS on a job without
366 * one ("Attempting to schedule job with no soft deadline") instead of serving FCFS.
367 * The `<userClass softDeadline>` attribute feeds the system tardiness only. A class
368 * not served at the station (`sn.disabled`, MATLAB's NaN rate) never enters the
369 * buffer and needs none.
370 *
371 * ONE PREDICATE, TWO CALLERS: `JmtWriter::save_class_soft_deadlines` raises it, and
372 * `jmt::jmt_method_refusal` returns it for the jsim engine.
373 */
374template <class T>
376 for (std::size_t ist = 0; ist < sn.nstations; ++ist) {
377 const SchedStrategy sc = sn.stations[ist].sched;
378 if (sc != SchedStrategy::EDD && sc != SchedStrategy::EDF) continue;
379 for (std::size_t r = 0; r < sn.nclasses; ++r) {
380 if (sn.disabled[ist][r]) continue; // not served here, never enters this buffer
381 if (std::isfinite(sn.classes[r].deadline)) continue;
382 const std::string& cl = sn.classes[r].name;
383 return "Station " + sn.nodes[sn.station_to_node[ist] - 1].name + " is scheduled " +
384 (sc == SchedStrategy::EDD ? "EDD" : "EDF") + " but class " + cl +
385 " carries no deadline. JMT orders an EDD or EDF buffer by a per-station due "
386 "date it reads from the <classSoftDeadlines> element, and a job that reaches "
387 "such a buffer without one aborts the run with \"Attempting to schedule job "
388 "with no soft deadline\" rather than being served FCFS. Give the class a "
389 "finite deadline, e.g. OpenClass(model, '" + cl + "', prio, 5.0), or use "
390 "SolverLDES, which sorts a class of infinite deadline last instead of refusing "
391 "it.";
392 }
393 }
394 return std::string();
395}
396
397/**
398 * MATLAB `num2str` of a real scalar: an integer-valued double has no decimal point ("5", not
399 * "5.0"), anything else is `%.Ng` with N = max(floor(log10|v|)+5, 5) significant digits, capped
400 * at 16 (0.123456 is "0.12346").
401 */
402inline std::string jmt_num2str(double v) {
403 if (std::isnan(v)) return "NaN";
404 if (std::isinf(v)) return v > 0 ? "Inf" : "-Inf";
405 char buf[64];
406 if (v == std::rint(v) && std::fabs(v) < 1e15) {
407 std::snprintf(buf, sizeof(buf), "%lld", static_cast<long long>(v));
408 return buf;
409 }
410 const int e10 = static_cast<int>(std::floor(std::log10(std::fabs(v))));
411 const int digits = std::min(std::max(e10 + 5, 5), 16);
412 std::snprintf(buf, sizeof(buf), "%.*g", digits, v);
413 return buf;
414}
415
416/** saveClasses.m: `num2str` of a finite deadline, `0.0` otherwise: the `<userClass softDeadline>` text. */
417inline std::string jmt_soft_deadline_text(double d) {
418 if (!std::isfinite(d)) return "0.0";
419 return jmt_num2str(d);
420}
421
422/** The classes a Cache switches jobs into; they keep their Tput/ArvR measures. */
423template <class T>
424std::vector<bool> jmt_cache_classes(const qn::NetworkStruct<T>& sn) {
425 std::vector<bool> f(sn.nclasses, false);
426 for (const auto& kv : sn.nodeparam) {
427 const qn::CacheParam<T>& cp = kv.second;
428 for (std::size_t r = 0; r < cp.hitclass.size(); ++r)
429 if (cp.hitclass[r] > 0 && cp.hitclass[r] <= sn.nclasses) f[cp.hitclass[r] - 1] = true;
430 for (std::size_t r = 0; r < cp.missclass.size(); ++r)
431 if (cp.missclass[r] > 0 && cp.missclass[r] <= sn.nclasses) f[cp.missclass[r] - 1] = true;
432 }
433 return f;
434}
435
436// ---------------------------------------------------------------------------
437// Small shared emitters
438// ---------------------------------------------------------------------------
439
440/** `<parameter array="true" classPath="CP" name="NAME">` */
441inline xml::Element& jmt_param(xml::Element& section, const char* class_path, const char* name,
442 bool array) {
443 xml::Element& p = section.add_child("parameter");
444 if (array) p.set_attr("array", "true");
445 p.set_attr("classPath", class_path);
446 p.set_attr("name", name);
447 return p;
448}
449
450/** `<parameter classPath="CP" name="NAME"><value>V</value></parameter>` */
451inline void jmt_param_value(xml::Element& section, const char* class_path, const char* name,
452 const std::string& value) {
453 xml::Element& p = jmt_param(section, class_path, name, false);
454 p.add_text_child("value", value);
455}
456
457/** `<refClass>NAME</refClass>`, the per-class marker of an array parameter. */
458inline void jmt_ref_class(xml::Element& parent, const std::string& class_name) {
459 parent.add_text_child("refClass", class_name);
460}
461
462/** MATLAB `DropStrategy.toText`, the strings JMT's dropRule field expects. */
463inline const char* jmt_drop_text(DropStrategy d) {
464 switch (d) {
465 case DropStrategy::WAITQ: return "waiting queue";
466 case DropStrategy::DROP: return "drop";
467 case DropStrategy::BAS: return "BAS blocking";
468 case DropStrategy::BBS: return "BBS blocking";
469 case DropStrategy::RSRD: return "RSRD blocking";
470 case DropStrategy::RETRIAL: return "retrial";
471 case DropStrategy::RETRIAL_WITH_LIMIT: return "retrial with limit";
472 }
473 throw InputError("SolverJMT: unrecognized drop strategy");
474}
475
476/**
477 * Whether JMT's queue section can read this drop strategy at all.
478 *
479 * It recognizes exactly four `dropStrategies` strings -- 'drop', 'BAS blocking',
480 * 'waiting queue', 'retrial' (a lookupswitch on String.hashCode in
481 * `jmt/engine/NodeSections/Queue.class`; the Storage section of a Place is even
482 * narrower and drops 'retrial'). An unrecognized value falls through the default arm
483 * with NO flag set, so BBS, RSRD and retrial-with-limit are not approximated, they are
484 * IGNORED.
485 */
486inline bool jmt_reads_drop(DropStrategy d) {
487 return d == DropStrategy::DROP || d == DropStrategy::BAS || d == DropStrategy::WAITQ ||
488 d == DropStrategy::RETRIAL;
489}
490
491/** MATLAB `HeteroSchedPolicy.toJMTText`: JMT's long descriptive identifiers. */
493 switch (p) {
494 case lang::HeteroSchedPolicy::ORDER: return "Order (Assign according to order below)";
495 case lang::HeteroSchedPolicy::ALIS: return "ALIS (Assign Longest Idle Server)";
496 case lang::HeteroSchedPolicy::ALFS: return "ALFS (Assign Least Flexible Server)";
497 case lang::HeteroSchedPolicy::FAIRNESS: return "Fairness (Move back server type when used)";
498 case lang::HeteroSchedPolicy::FSF: return "FSF (Fastest Servers First)";
499 case lang::HeteroSchedPolicy::RAIS: return "RAIS (Random Assignment to Idle Servers)";
500 }
501 return "Order (Assign according to order below)";
502}
503
504/**
505 * The writer itself. One instance per exported model; it holds the derived
506 * tables (connections, exportable classes, cache classes) that nearly every
507 * handler reads, so they are computed once rather than per section as the
508 * reference recomputes them.
509 */
510template <class T>
512public:
514 : sn_(sn),
515 opt_(opt),
516 conn_(jmt_conn_matrix(sn)),
518 cacheclass_(jmt_cache_classes(sn)) {}
519
520 /** Port of `@@JMTIO/writeJSIM.m`; returns the serialized document. */
521 std::string write_jsim() {
522 std::unique_ptr<xml::Element> sim = xml::element("sim");
523 save_xml_header(*sim);
524 save_classes(*sim);
525 for (std::size_t ind = 1; ind <= sn_.nodes.size(); ++ind) save_node(*sim, ind);
526 save_metrics(*sim);
527 save_links(*sim);
528 save_regions(*sim);
529 save_preload(*sim);
530 return xml::serialize(*sim);
531 }
532
533 /**
534 * The buffer-capacity refusals of `save_buffer_capacity`, as a SENTENCE
535 * rather than an exception; empty when every buffer is exportable.
536 *
537 * ONE PREDICATE, TWO CALLERS. `save_buffer_capacity` raises it while writing
538 * the JSIM document, and `jmt::jmt_method_refusal` returns it so that
539 * `findSolver` never offers a jmt row on a model the writer will refuse. It
540 * was reachable only from inside the writer, which is why the gate could not
541 * see it and offered `jmt.jsim` on a binding buffer.
542 *
543 * WHAT MAKES A BUFFER BIND is not that `sn.cap` is finite: `refresh_capacity`
544 * DERIVES a finite cap for every station nobody capped. It is that the cap is
545 * strictly below the population that can REACH the station, and an
546 * infinite-server station has no buffer at all -- the same two tests
547 * `save_buffer_capacity` applies before it exports anything.
548 *
549 * `jmva_engine` selects the verdict, because the two engines fail a binding
550 * buffer for OPPOSITE reasons. JSIM exports it whenever JMT can read the drop
551 * rule, so only `assert_station_cap_exportable`'s cases go. JMVA has no
552 * capacity element in its document at all -- `write_jmva` emits a station
553 * type, a per-chain demand and a per-chain visit count and nothing else -- so
554 * ANY binding buffer would be solved as if it were unbounded: measured on a
555 * closed Delay+FCFS model, N=4, cap 2, every jmva method reported 2.19 jobs
556 * at a station that can hold 2, against the exact 1.33.
557 */
558 std::string buffer_capacity_refusal(bool jmva_engine) const {
559 for (std::size_t ist = 1; ist <= sn_.nstations; ++ist) {
560 // A SOURCE AND A SINK HAVE NO BUFFER THAT CAN BIND. The Source IS the
561 // external world and the Sink absorbs, so neither ever holds a job a
562 // capacity could refuse, yet `refresh_capacity` writes them a row like
563 // any other station. Excluded on NODE TYPE, as
564 // `qn::binding_capacity_reason` excludes them, and not by name.
565 const qn::NodeType ty = sn_.nodes[sn_.station_to_node[ist - 1] - 1].nodetype;
566 if (ty == qn::NodeType::Source || ty == qn::NodeType::Sink) continue;
567 // UNBOUNDED IS inf HERE, `Station<T>::cap` defaulting to infinity.
568 // The JAR cannot: its Station.cap is an int whose "no bound" value is
569 // Integer.MAX_VALUE, and refreshCapacity SUMS that sentinel across
570 // the classes served, so a mixed station comes out as
571 // 2147483647 + N there and needs SaveHandlers.jmtCapIsUnbounded.
572 if (!std::isfinite(sn_.cap[ist - 1])) continue;
573 if (sn_.cap[ist - 1] >= reachable_population(ist)) continue;
574 if (!std::isfinite(sn_.stations[ist - 1].nservers)) continue;
575 if (jmva_engine)
576 return "SolverJMT: station '" + nname(sn_.station_to_node[ist - 1]) +
577 "' carries a finite capacity " + jmt_int(sn_.cap[ist - 1]) +
578 " that binds. The JMVA document has no capacity element at all, so the "
579 "analytical engine would solve the model as if the buffer were unbounded "
580 "and report that as the answer. Use the 'jsim' method, which exports the "
581 "buffer with its drop rule when JMT can express it, or SolverCTMC, "
582 "SolverSSA or SolverLDES";
583 try {
584 assert_station_cap_exportable(ist);
585 } catch (const UnsupportedError& e) {
586 return std::string(e.what());
587 }
588 }
589 return std::string();
590 }
591
592private:
593 const qn::NetworkStruct<T>& sn_;
594 JmtWriteOptions opt_;
595 std::vector<std::vector<bool>> conn_;
596 std::vector<bool> keep_, cacheclass_;
597
598 double d(const T& x) const { return num_traits<T>::to_double(x); }
599 const std::string& cname(std::size_t r) const { return sn_.classes[r - 1].name; }
600 const std::string& nname(std::size_t i) const { return sn_.nodes[i - 1].name; }
601
602 /** The 1-based node indices `ind` is linked TO. */
603 std::vector<std::size_t> outputs_of(std::size_t ind) const {
604 std::vector<std::size_t> v;
605 for (std::size_t j = 1; j <= sn_.nodes.size(); ++j)
606 if (conn_[ind - 1][j - 1]) v.push_back(j);
607 return v;
608 }
609
610 /** The 1-based node indices linked TO `ind`. */
611 std::vector<std::size_t> inputs_of(std::size_t ind) const {
612 std::vector<std::size_t> v;
613 for (std::size_t j = 1; j <= sn_.nodes.size(); ++j)
614 if (conn_[j - 1][ind - 1]) v.push_back(j);
615 return v;
616 }
617
618 /**
619 * 1-based (place, transition) pairs with a finite inhibitor threshold but no link. An inhibitor arc is itself a
620 * place -> transition connection in JMT; without it JMT threw a NullPointerException in
621 * TransitionMatrix.getTotal (jmtInhibitorOnlyArcs.m).
622 */
623 std::vector<std::pair<std::size_t, std::size_t>> inhibitor_only_arcs() const {
624 std::vector<std::pair<std::size_t, std::size_t>> arcs;
625 for (const auto& kv : sn_.transparam) {
626 const std::size_t t = kv.first;
627 for (std::size_t p = 1; p <= sn_.nodes.size(); ++p) {
628 if (sn_.nodes[p - 1].nodetype != lang::NodeType::Place || conn_[p - 1][t - 1]) continue;
629 bool finite = false;
630 for (const Matrix<T>& M : kv.second.inhibiting) {
631 if (p > M.rows()) continue;
632 for (std::size_t r = 0; r < M.cols() && !finite; ++r)
633 finite = std::isfinite(num_traits<T>::to_double(M(p - 1, r)));
634 if (finite) break;
635 }
636 if (finite) arcs.emplace_back(p, t);
637 }
638 }
639 return arcs;
640 }
641
642 // -- header and classes ------------------------------------------------
643
644 /** Port of `saveXMLHeader`. */
645 void save_xml_header(xml::Element& sim) {
646 sim.set_attr("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
647 sim.set_attr("name", opt_.file_name + ".jsimg");
648 sim.set_attr("xsi:noNamespaceSchemaLocation", "SIMmodeldefinition.xsd");
649 sim.set_attr("disableStatisticStop", "true");
650 sim.set_attr("logDecimalSeparator", ".");
651 sim.set_attr("logDelimiter", ";");
652 sim.set_attr("logPath", opt_.log_path);
653 sim.set_attr("logReplaceMode", "0");
654 sim.set_attr("maxSamples",
655 std::isnan(opt_.max_samples) ? "10000" : jmt_int(opt_.max_samples));
656 sim.set_attr("maxEvents", jmt_int(opt_.max_events));
657 if (std::isfinite(opt_.max_simulated_time)) {
658 char buf[64];
659 std::snprintf(buf, sizeof(buf), "%.3f", opt_.max_simulated_time);
660 sim.set_attr("maxSimulated", buf);
661 }
662 sim.set_attr("polling", "1.0");
663 sim.set_attr("seed", jmt_int(static_cast<double>(opt_.seed)));
664 }
665
666 /**
667 * Port of `saveClasses`.
668 *
669 * THE PRIORITY IS INVERTED. LINE orders priorities with the SMALLEST value
670 * most urgent and JMT with the largest, so the exported value is
671 * `max(prio) - prio(r)`. Exporting the raw number reverses the service
672 * order of every priority model without any diagnostic.
673 */
674 void save_classes(xml::Element& sim) {
675 int maxprio = 0;
676 for (std::size_t r = 0; r < sn_.nclasses; ++r)
677 maxprio = std::max(maxprio, sn_.classes[r].prio);
678 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
679 if (!keep_[r - 1]) continue;
680 const qn::JobClass& cl = sn_.classes[r - 1];
681 xml::Element& uc = sim.add_child("userClass");
682 uc.set_attr("name", cl.name);
683 const bool open = !std::isfinite(cl.population);
684 uc.set_attr("type", open ? "open" : "closed");
685 // saveClasses.m: the class deadline, "0.0" when it has none. This
686 // attribute feeds JMT's SYSTEM tardiness only; an EDD/EDF buffer is
687 // ordered by the per-node <classSoftDeadlines> (save_class_soft_deadlines).
688 uc.set_attr("softDeadline", jmt_soft_deadline_text(cl.deadline));
689 uc.set_attr("priority", jmt_int(static_cast<double>(maxprio - cl.prio)));
690 const std::size_t refst = cl.refstat;
691 const std::string refname = nname(sn_.station_to_node[refst - 1]);
692 if (!open) {
693 uc.set_attr("customers", jmt_int(cl.population));
694 uc.set_attr("referenceSource", refname);
695 } else if (sn_.disabled[refst - 1][r - 1]) {
696 // An open class with no arrival process at its reference
697 // station enters the model by class switching only; JMT names
698 // that source 'ClassSwitch'.
699 uc.set_attr("referenceSource", "ClassSwitch");
700 } else {
701 uc.set_attr("referenceSource", refname);
702 }
703 }
704 }
705
706 // -- the node/section walk ---------------------------------------------
707
708 /** Port of the section loop of `writeJSIM`. */
709 void save_node(xml::Element& sim, std::size_t ind) {
710 const JmtSections<T> sec = jmt_sections(sn_, ind);
711 xml::Element& node = sim.add_child("node");
712 node.set_attr("name", nname(ind));
713 // Ahead of the sections, as SIMmodeldefinition.xsd sequences <node>.
714 save_class_soft_deadlines(node, ind);
715 const std::string parts[3] = {sec.input, sec.server, sec.output};
716 for (int k = 0; k < 3; ++k) {
717 if (parts[k].empty()) continue;
718 std::string cls = parts[k];
719 // `writeJSIM` promotes a Server to a PreemptiveServer for the
720 // preemptive disciplines. `jmt_sections` already does that from the
721 // scheduling strategy, so the promotion is not repeated here; the
722 // remaining rewrites are the LINE-name to JMT-name ones.
723 xml::Element& xs = node.add_child("section");
724 xs.set_attr("className", cls);
725 if (cls == "Buffer") {
726 xs.set_attr("className", "Queue");
727 save_buffer_capacity(xs, ind);
728 save_drop_strategy(xs, ind);
729 if (has_retrial(ind)) {
730 // With retrial JMT selects a different Queue constructor,
731 // which takes the retrial distributions BEFORE the get and
732 // put strategies and takes no impatience at all.
733 save_retrial_distributions(xs, ind);
734 save_get_strategy(xs, ind);
735 save_put_strategy(xs, ind);
736 } else {
737 save_get_strategy(xs, ind);
738 save_put_strategy(xs, ind);
739 save_impatience(xs, ind);
740 }
741 } else if (cls == "Server") {
742 save_number_of_servers(xs, ind);
743 save_server_visits(xs);
744 save_service_strategy(xs, ind);
745 save_delay_off_strategy(xs, ind);
746 // Job parallelism and heterogeneous pools. SimLoader picks the Server
747 // constructor by the positional types of the parameters, so these five
748 // must follow the service strategies as one block.
749 save_class_parallelism(xs, ind);
750 save_server_type_names(xs, ind);
751 save_servers_per_type(xs, ind);
752 save_server_compatibilities(xs, ind);
753 save_hetero_sched_policy(xs, ind);
754 warn_hetero_rates(ind);
755 warn_switchover_on_non_polling(ind);
756 } else if (cls == "PreemptiveServer") {
757 save_number_of_servers(xs, ind);
758 save_server_visits(xs);
759 save_service_strategy(xs, ind);
760 save_delay_off_strategy(xs, ind);
761 } else if (cls == "SharedServer") {
762 xs.set_attr("className", "PSServer");
763 save_number_of_servers(xs, ind);
764 save_server_visits(xs);
765 save_service_strategy(xs, ind);
766 save_delay_off_strategy(xs, ind);
767 save_preemptive_strategy(xs, ind);
768 save_preemptive_weights(xs, ind);
769 } else if (cls == "InfiniteServer") {
770 xs.set_attr("className", "Delay");
771 save_service_strategy(xs, ind);
772 } else if (cls == "PollingServer") {
773 xs.set_attr("className", polling_server_class(ind));
774 save_number_of_servers(xs, ind);
775 save_server_visits(xs);
776 save_service_strategy(xs, ind);
777 save_switchover_strategy(xs, ind);
778 } else if (cls == "RandomSource") {
779 save_arrival_strategy(xs, ind);
780 } else if (cls == "Dispatcher") {
781 xs.set_attr("className", "Router");
782 save_routing_strategy(xs, ind);
783 } else if (cls == "StatelessClassSwitcher") {
784 xs.set_attr("className", "ClassSwitch");
785 save_class_switch_strategy(xs, ind);
786 } else if (cls == "Cache") {
787 save_cache_strategy(xs, ind);
788 } else if (cls == "LogTunnel") {
789 save_log_tunnel(xs, ind);
790 } else if (cls == "Joiner") {
791 xs.set_attr("className", "Join");
792 save_join_strategy(xs, ind);
793 } else if (cls == "Forker") {
794 xs.set_attr("className", "Fork");
795 save_fork_strategy(xs, ind);
796 } else if (cls == "Storage") {
797 save_total_capacity(xs, ind);
798 save_place_capacities(xs, ind);
799 save_drop_rule(xs, ind);
800 save_get_strategy(xs, ind);
801 save_put_strategies(xs, ind);
802 } else if (cls == "Enabling") {
803 save_enabling_conditions(xs, ind);
804 save_inhibiting_conditions(xs, ind);
805 } else if (cls == "Firing") {
806 save_firing_outcomes(xs, ind);
807 } else if (cls == "Timing") {
808 save_mode_names(xs, ind);
809 save_numbers_of_servers(xs, ind);
810 save_timing_strategies(xs, ind);
811 save_firing_priorities(xs, ind);
812 save_firing_weights(xs, ind);
813 }
814 // ServiceTunnel, JobSink and Linkage carry no parameters.
815 }
816 }
817
818 /** JMT's polling server class, by discipline; DECREMENTING and GLIMITED have none. */
819 const char* polling_server_class(std::size_t ind) const {
820 const std::size_t ist = sn_.nodes[ind - 1].station;
821 const typename qn::NetworkStruct<T>::PollingParam pp = sn_.effective_polling(ist);
822 switch (pp.ptype) {
823 case PollingType::GATED: return "GatedPollingServer";
824 case PollingType::EXHAUSTIVE: return "ExhaustivePollingServer";
825 case PollingType::KLIMITED: return "LimitedPollingServer";
826 case PollingType::DECREMENTING:
827 throw UnsupportedError(ErrorKind{"SchedStrategy_POLLING"},
828 "SolverJMT: JMT does not support the decrementing (semiexhaustive) polling "
829 "discipline; use the LDES solver");
830 case PollingType::GLIMITED:
831 throw UnsupportedError(ErrorKind{"SchedStrategy_POLLING"},
832 "SolverJMT: JMT does not support the G-limited polling discipline; use the "
833 "LDES solver");
834 }
835 throw UnsupportedError(ErrorKind{"SchedStrategy_POLLING"}, "SolverJMT: unknown polling discipline");
836 }
837
838 /** True when any class of the station declares a retrial orbit. */
839 bool has_retrial(std::size_t ind) const {
840 const std::size_t ist = sn_.nodes[ind - 1].station;
841 if (ist == 0) return false;
842 const auto it = sn_.retrialparam.find(ist);
843 if (it == sn_.retrialparam.end()) return false;
844 for (const lang::Distrib<T>& p : it->second.retrial_proc)
845 if (!p.disabled) return true;
846 return false;
847 }
848
849 /**
850 * Port of the `writeJSIM` guard on a switchover declared away from a
851 * polling server: JMT's ordinary Server has no SwitchoverStrategy, so the
852 * times are WARNED ABOUT AND DROPPED, exactly as the reference does. This
853 * threw instead until it was found to be the harsher rule of the two -- the
854 * reference solves switchover_basic and reports a table, so a refusal here
855 * left the C++ row with nothing to compare rather than with a documented
856 * difference.
857 */
858 void warn_switchover_on_non_polling(std::size_t ind) const {
859 const std::size_t ist = sn_.nodes[ind - 1].station;
860 if (ist == 0) return;
861 for (const lang::Distrib<T>& s : sn_.stations[ist - 1].switchover)
862 if (!s.disabled) {
863 std::cerr << "[LINE] Warning: JMT does not support switchover times for "
864 << "non-polling queues. Switchover times will be ignored for node '"
865 << nname(ind) << "'." << std::endl;
866 return;
867 }
868 // The (from, to) form is the one an ordinary Server can actually carry,
869 // and it is exactly the one JMT drops: `Server` has no switchover
870 // parameter, so the reference warns here too rather than writing a
871 // SwitchoverStrategy the loader would not read.
872 if (!sn_.stations[ist - 1].switchover_pair.empty())
873 std::cerr << "[LINE] Warning: JMT does not support switchover times for "
874 << "non-polling queues. Switchover times will be ignored for node '"
875 << nname(ind) << "'." << std::endl;
876 }
877
878 // -- Buffer section -----------------------------------------------------
879
880 /**
881 * Port of `saveBufferCapacity`.
882 *
883 * LINE's `cap` is Kendall's K, the WHOLE system capacity, and so is JMT's
884 * `size`, so the number crosses unchanged. -1 is JMT's "unbounded", and it
885 * is also what a capacity the population cannot REACH means: such a bound
886 * can never bind, and exporting it would make JMT reject arrivals that LINE
887 * admits at the instant the last job arrives.
888 *
889 * The test is `>=` and not `!=`: `refresh_capacity` DERIVES `sn.cap` for a
890 * station the user never capped, as the sum over the classes served there
891 * of the chain population, so a multi-class station gets (#classes) x N --
892 * 8 on a two-class model of 4 jobs. Under `!=` only the single-class case
893 * matched, and every multi-class one fell through to
894 * `assert_station_cap_exportable` and was refused as a "binding" buffer
895 * nobody declared. An open class carries an infinite population and so
896 * makes `total` infinite, which is what keeps a DECLARED cap in a mixed
897 * model refused: the open stream can fill the buffer under a closed job.
898 */
899 void save_buffer_capacity(xml::Element& section, std::size_t ind) {
900 const std::size_t ist = sn_.nodes[ind - 1].station;
901 std::string v = "-1";
902 if (ist != 0 && std::isfinite(sn_.cap[ist - 1])) {
903 const double total = reachable_population(ist);
904 const double ns = sn_.stations[ist - 1].nservers;
905 if (sn_.cap[ist - 1] < total && std::isfinite(ns)) {
906 assert_station_cap_exportable(ist);
907 v = jmt_int(sn_.cap[ist - 1]);
908 }
909 }
910 jmt_param_value(section, "java.lang.Integer", "size", v);
911 }
912
913 /**
914 * The most jobs that can be present at station `ist` (1-based).
915 *
916 * Read the way `refresh_capacity` derives the capacity itself: per CHAIN,
917 * because a chain's whole population can reach a station that serves any one
918 * of its classes (class switching moves jobs between them), and a chain none
919 * of whose classes is served there cannot put a single job on it.
920 *
921 * Deliberately NOT read off the clamped per-class capacities: comparing a
922 * capacity against a quantity derived from it would make every
923 * user-declared buffer look non-binding. Infinite when an open chain is
924 * served here, which is what the model total gave before and which sends
925 * the station to `assert_station_cap_exportable`, where the open classes
926 * are skipped by name.
927 *
928 * A class that never visits this station cannot fill it, so summing every
929 * class's population made a capacity that is exactly the reachable
930 * population look like a buffer -- which is what a SELF-LOOPING CLASS does.
931 * See the MATLAB twin in JMTIO/saveBufferCapacity.m.
932 */
933 double reachable_population(std::size_t ist) const {
934 double n = 0.0;
935 for (std::size_t c = 0; c < sn_.nchains; ++c) {
936 bool served = false;
937 double chain_jobs = 0.0;
938 for (std::size_t r : sn_.inchain[c]) {
939 if (!sn_.disabled[ist - 1][r - 1]) served = true;
940 chain_jobs += sn_.classes[r - 1].population;
941 }
942 if (served) n += chain_jobs;
943 }
944 return n;
945 }
946
947 /**
948 * True when station `ist` is the RECEIVING side of a true-BAS relation for
949 * class `r`, i.e. an arrival of `r` that finds `ist` full must block an
950 * upstream station rather than be lost.
951 *
952 * LINE accepts the BAS declaration in two places -- on the blocking
953 * (upstream) station, as `cqn_bas_blocking` does, or on the full
954 * destination, as a model read back from JMT does -- and
955 * `NetworkStruct::refresh_local_vars` resolves both into
956 * `sn.isbasdestination` (BUG-83). Reading `sn.droprule` at the capped
957 * station sees only the second form, which is what made SolverJMT refuse
958 * the first one.
959 */
960 bool is_bas_destination(std::size_t ist, std::size_t r) const {
961 if (ist == 0 || sn_.isbasdestination.size() < ist) return false;
962 if (sn_.isbasdestination[ist - 1].size() < r) return false;
963 return sn_.isbasdestination[ist - 1][r - 1];
964 }
965
966 /**
967 * The JMT dropStrategy/dropRule string for station `ist`, class `r`.
968 *
969 * Beyond `jmt_drop_text` this resolves the two ways LINE can declare BAS
970 * blocking onto the one way JMT can read it. JMT's queue section says what
971 * happens to an arrival that finds THIS buffer full, so it only understands
972 * the rule on the destination; a WAITQ slot that `is_bas_destination` marks
973 * is therefore written out as 'BAS blocking'. A node with no buffer of its
974 * own gets JMT's 'drop', as the reference does for a NaN station index.
975 *
976 * It also keeps the written file VALID: a strategy `jmt_reads_drop` rejects
977 * is spelled 'waiting queue', JMT's own no-limit default. That substitution
978 * is only ever reached where the rule cannot be consulted (infinite size, or
979 * a closed capacity equal to the population): a buffer that can actually
980 * fill under one of those is refused outright by
981 * `assert_station_cap_exportable`.
982 */
983 const char* drop_strategy_text(std::size_t ist, std::size_t r) const {
984 if (ist == 0) return "drop";
985 const DropStrategy d = sn_.droprule[ist - 1][r - 1];
986 if (d == DropStrategy::WAITQ && is_bas_destination(ist, r))
987 return jmt_drop_text(DropStrategy::BAS);
988 if (!jmt_reads_drop(d)) return jmt_drop_text(DropStrategy::WAITQ);
989 return jmt_drop_text(d);
990 }
991
992 /**
993 * Refuses a binding station capacity JMT cannot express, on two counts.
994 *
995 * (1) THE RULE IS ONE JMT CANNOT READ -- BBS, RSRD or retrial-with-limit;
996 * see `jmt_reads_drop`. Such a value is not approximated, it is IGNORED, so
997 * the capacity stops being enforced and JMT returns the unconstrained
998 * answer.
999 *
1000 * (2) THE RULE IS WAITQ AND A CLOSED CLASS CAN REACH THE LIMIT, the same
1001 * reason `assert_class_cap_exportable` below refuses the per-class one: JMT
1002 * cannot hold a blocked closed job at its upstream station. Note this is the
1003 * case where NO blocking rule is declared. A model that does declare BAS is
1004 * exported as JMT "BAS blocking", which is the same queueing model, under
1005 * either declaration form -- see `is_bas_destination`.
1006 *
1007 * That refusal advised expressing the limit as the STATION capacity instead,
1008 * and measured on 2026-08-19 the advice was wrong, and neither of the two
1009 * strategies a WAITQ station maps onto reproduces the UNDECLARED case:
1010 *
1011 * waiting queue does not enforce `size` at all. On a closed 3-queue
1012 * tandem, N=6, Exp(1) FCFS, cap 2 at Q2, JMT returned the
1013 * UNCONSTRAINED [2.03 1.99 1.98], X = 0.750, against the
1014 * exact [3.6090 0.9711 1.4199], X = 0.6522.
1015 * BAS blocking enforces it, but completes the service BEFORE blocking,
1016 * so the blocked job moves the instant room frees -- a
1017 * different queueing model, not a rounding: same fixture,
1018 * [2.871 1.373 1.756], X = 0.7126.
1019 *
1020 * With no rule declared LINE instead disables the upstream departure while
1021 * the destination is full, which for exponential service is repetitive
1022 * service (RS) and is what SolverCTMC, SolverSSA and SolverLDES all agree
1023 * on. So THAT model is refused rather than exported as either of the two
1024 * things JMT can say. See BUG-81. A declared-BAS model is a different model
1025 * and is exported, not refused: blocking after service is precisely what
1026 * JMT's "BAS blocking" does.
1027 *
1028 * That the limit CAN be reached is the caller's to establish and is not
1029 * retested here: `save_buffer_capacity` reaches this method only for a
1030 * capacity strictly below the total population, which is the one thing that
1031 * makes a buffer a buffer.
1032 */
1033 void assert_station_cap_exportable(std::size_t ist) const {
1034 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
1035 if (sn_.disabled[ist - 1][r - 1]) continue; // not served here
1036 const DropStrategy dr = sn_.droprule[ist - 1][r - 1];
1037 // Unmappable for EITHER class type, so this test precedes the open-class skip
1038 if (!jmt_reads_drop(dr))
1039 throw UnsupportedError(ErrorKind{"FiniteCapacity"},
1040 "SolverJMT: station '" + nname(sn_.station_to_node[ist - 1]) +
1041 "' applies drop strategy '" + jmt_drop_text(dr) + "' to class '" + cname(r) +
1042 "' and carries a finite capacity " + jmt_int(sn_.cap[ist - 1]) +
1043 " it can reach. JMT's queue section reads only 'drop', 'waiting queue', "
1044 "'BAS blocking' and 'retrial'; it does not approximate anything else, it "
1045 "ignores it, so the capacity would stop being enforced and the run would "
1046 "return the unconstrained answer. Use SolverCTMC, SolverSSA or SolverLDES");
1047 if (!std::isfinite(sn_.classes[r - 1].population)) continue; // open: JMT loses it too
1048 if (dr != DropStrategy::WAITQ)
1049 continue; // a mappable declared blocking rule is exported as itself
1050 if (is_bas_destination(ist, r))
1051 continue; // BAS declared on the UPSTREAM station: drop_strategy_text
1052 // moves it onto this one, which is where JMT reads it
1053 throw UnsupportedError(ErrorKind{"FiniteCapacity"},
1054 "SolverJMT: station '" + nname(sn_.station_to_node[ist - 1]) +
1055 "' carries a finite capacity " + jmt_int(sn_.cap[ist - 1]) +
1056 " that binds for the closed class '" + cname(r) +
1057 "'. LINE blocks a closed job that finds no room -- the upstream departure is "
1058 "disabled and the job stays where it is -- and no JMT drop strategy reproduces "
1059 "that: 'waiting queue' does not enforce the size at all, and 'BAS blocking' "
1060 "completes the service before blocking, which is a different queueing model. "
1061 "Use SolverCTMC, SolverSSA or SolverLDES, or declare DropStrategy.BAS if "
1062 "blocking after service is the model you want, which SolverJMT does export");
1063 }
1064 }
1065
1066 /** Port of `saveDropStrategy`: the per-class rule of a full buffer. */
1067 void save_drop_strategy(xml::Element& section, std::size_t ind) {
1068 const std::size_t ist = sn_.nodes[ind - 1].station;
1069 xml::Element& p = jmt_param(section, "java.lang.String", "dropStrategies", true);
1070 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
1071 if (!keep_[r - 1]) continue;
1072 jmt_ref_class(p, cname(r));
1073 const char* txt = drop_strategy_text(ist, r);
1074 xml::Element& sp = p.add_child("subParameter");
1075 sp.set_attr("classPath", "java.lang.String");
1076 sp.set_attr("name", "dropStrategy");
1077 sp.add_text_child("value", txt);
1078 }
1079 }
1080
1081 /**
1082 * Port of `saveGetStrategy`: FCFS everywhere except a polling queue, whose
1083 * discipline decides which of JMT's three polling get strategies serves it.
1084 */
1085 void save_get_strategy(xml::Element& section, std::size_t ind) {
1086 const std::size_t ist = sn_.nodes[ind - 1].station;
1087 const bool polling = sn_.nodes[ind - 1].nodetype == NodeType::Queue && ist != 0 &&
1088 sn_.stations[ist - 1].sched == SchedStrategy::POLLING;
1089 if (!polling) {
1090 xml::Element& p = section.add_child("parameter");
1091 p.set_attr("classPath", "jmt.engine.NetStrategies.QueueGetStrategies.FCFSstrategy");
1092 p.set_attr("name", "FCFSstrategy");
1093 return;
1094 }
1095 const typename qn::NetworkStruct<T>::PollingParam pp = sn_.effective_polling(ist);
1096 xml::Element& p = section.add_child("parameter");
1097 switch (pp.ptype) {
1098 case PollingType::GATED:
1099 p.set_attr("classPath",
1100 "jmt.engine.NetStrategies.QueueGetStrategies.GatedPollingGetStrategy");
1101 break;
1102 case PollingType::EXHAUSTIVE:
1103 p.set_attr(
1104 "classPath",
1105 "jmt.engine.NetStrategies.QueueGetStrategies.ExhaustivePollingGetStrategy");
1106 break;
1107 case PollingType::KLIMITED: {
1108 p.set_attr("classPath",
1109 "jmt.engine.NetStrategies.QueueGetStrategies.LimitedPollingGetStrategy");
1110 xml::Element& k = p.add_child("subParameter");
1111 k.set_attr("classPath", "java.lang.Integer");
1112 k.set_attr("name", "pollingKValue");
1113 k.add_text_child("value", jmt_int(static_cast<double>(pp.pk)));
1114 break;
1115 }
1116 case PollingType::DECREMENTING:
1117 throw UnsupportedError(ErrorKind{"SchedStrategy_POLLING"},
1118 "SolverJMT: JMT does not support the decrementing (semiexhaustive) polling "
1119 "discipline; use the LDES solver");
1120 case PollingType::GLIMITED:
1121 throw UnsupportedError(ErrorKind{"SchedStrategy_POLLING"},
1122 "SolverJMT: JMT does not support the G-limited polling discipline; use the "
1123 "LDES solver");
1124 }
1125 p.set_attr("name", "FCFSstrategy");
1126 }
1127
1128 /**
1129 * Port of `savePutStrategy`: the discipline expressed as WHERE an arrival
1130 * is inserted in the buffer.
1131 *
1132 * JMT has no scheduling-strategy field: FCFS is a tail insertion, LCFS a
1133 * head insertion, SJF/SRPT an ordered one, and a preemptive discipline its
1134 * own put strategy. Everything unlisted -- PS above all, whose sharing is
1135 * expressed by the PSServer section instead -- is a tail insertion.
1136 */
1137 void save_put_strategy(xml::Element& section, std::size_t ind) {
1138 const std::size_t ist = sn_.nodes[ind - 1].station;
1139 xml::Element& p =
1140 jmt_param(section, "jmt.engine.NetStrategies.QueuePutStrategy", "QueuePutStrategy", true);
1141 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
1142 if (!keep_[r - 1]) continue;
1143 jmt_ref_class(p, cname(r));
1144 const char* nm = "TailStrategy";
1145 if (ist != 0) {
1146 switch (sn_.stations[ist - 1].sched) {
1147 case SchedStrategy::SIRO: nm = "RandStrategy"; break;
1148 case SchedStrategy::LJF: nm = "LJFStrategy"; break;
1149 case SchedStrategy::SJF: nm = "SJFStrategy"; break;
1150 case SchedStrategy::LEPT: nm = "LEPTStrategy"; break;
1151 case SchedStrategy::SEPT: nm = "SEPTStrategy"; break;
1152 case SchedStrategy::LCFS: nm = "HeadStrategy"; break;
1153 case SchedStrategy::LCFSPRIO: nm = "HeadStrategyPriority"; break;
1154 case SchedStrategy::LCFSPR: nm = "LCFSPRStrategy"; break;
1155 case SchedStrategy::LCFSPI: nm = "LCFSPIStrategy"; break;
1156 case SchedStrategy::LCFSPRPRIO: nm = "LCFSPRStrategyPriority"; break;
1157 case SchedStrategy::LCFSPIPRIO: nm = "LCFSPIStrategyPriority"; break;
1158 case SchedStrategy::FCFSPR: nm = "FCFSPRStrategy"; break;
1159 case SchedStrategy::FCFSPI: nm = "FCFSPIStrategy"; break;
1160 case SchedStrategy::FCFSPRPRIO: nm = "FCFSPRStrategyPriority"; break;
1161 case SchedStrategy::FCFSPIPRIO: nm = "FCFSPIStrategyPriority"; break;
1162 case SchedStrategy::HOL: nm = "TailStrategyPriority"; break;
1163 case SchedStrategy::EDD: nm = "EDDStrategy"; break;
1164 case SchedStrategy::EDF: nm = "EDFStrategy"; break;
1165 case SchedStrategy::SRPT: nm = "SRPTStrategy"; break;
1166 case SchedStrategy::SRPTPRIO: nm = "SRPTStrategyPriority"; break;
1167 default: nm = "TailStrategy"; break;
1168 }
1169 }
1170 xml::Element& sp = p.add_child("subParameter");
1171 sp.set_attr("classPath",
1172 std::string("jmt.engine.NetStrategies.QueuePutStrategies.") + nm);
1173 sp.set_attr("name", nm);
1174 }
1175 }
1176
1177 // -- Server section -----------------------------------------------------
1178
1179 /**
1180 * Port of `saveNumberOfServers`.
1181 *
1182 * LPS EXPORTS AS ONE SERVER. Its admission limit is not a server count but
1183 * a cap on the number in service, which `save_regions` expresses as an
1184 * implicit finite capacity region; exporting the limit as the server count
1185 * would give a c-server FCFS queue instead of limited processor sharing.
1186 * A load-dependent station exports `max(nservers, max lldscaling)`, since
1187 * `min(1:N, c)` scaling IS a c-server queue.
1188 */
1189 void save_number_of_servers(xml::Element& section, std::size_t ind) {
1190 const std::size_t ist = sn_.nodes[ind - 1].station;
1191 double maxjobs = 1.0;
1192 if (ist != 0) {
1193 if (sn_.stations[ist - 1].sched == SchedStrategy::LPS) {
1194 maxjobs = 1.0;
1195 } else {
1196 maxjobs = sn_.stations[ist - 1].nservers;
1197 for (const T& s : sn_.stations[ist - 1].lldscaling)
1198 maxjobs = std::max(maxjobs, d(s));
1199 }
1200 }
1201 jmt_param_value(section, "java.lang.Integer", "maxJobs", jmt_int(maxjobs));
1202 }
1203
1204 /** Port of `saveServerVisits`: one visit per class, always. */
1205 void save_server_visits(xml::Element& section) {
1206 xml::Element& p = jmt_param(section, "java.lang.Integer", "numberOfVisits", true);
1207 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
1208 if (!keep_[r - 1]) continue;
1209 jmt_ref_class(p, cname(r));
1210 xml::Element& sp = p.add_child("subParameter");
1211 sp.set_attr("classPath", "java.lang.Integer");
1212 sp.set_attr("name", "numberOfVisits");
1213 sp.add_text_child("value", "1");
1214 }
1215 }
1216
1217 /**
1218 * Server pools and job parallelism of a node, as the JMT Server section needs them.
1219 *
1220 * JMT's Server section takes classParallelism, serverNames, serversPerServerType,
1221 * serverCompatibilities and schedulingPolicy as one positional block of its
1222 * constructor (`jmt.engine.NodeSections.Server`), so the five are emitted
1223 * together or not at all, and always after the service strategies. A station
1224 * declaring parallelism alone is therefore given one synthetic pool holding all
1225 * of its servers, since the pool counts, not numberOfServers, size the server
1226 * pool once any pool is declared.
1227 */
1228 struct ServerPools {
1229 bool present = false;
1230 std::vector<std::string> names;
1231 std::vector<double> counts;
1232 std::vector<std::vector<bool>> compat; ///< [type][class]
1234 std::vector<std::size_t> parallelism; ///< per class, one-based class order
1235 };
1236
1237 ServerPools server_pools(std::size_t ind) const {
1238 ServerPools pools;
1239 const std::size_t ist = sn_.nodes[ind - 1].station;
1240 if (ist == 0) return pools;
1241 const auto& st = sn_.stations[ist - 1];
1242 const bool has_types = !st.server_types.empty();
1243 bool has_parallelism = false;
1244 for (std::size_t n : st.server_parallelism) {
1245 if (n > 1) { has_parallelism = true; break; }
1246 }
1247 if (!has_types && !has_parallelism) return pools;
1248
1249 pools.present = true;
1250 pools.parallelism.assign(sn_.nclasses, 1);
1251 for (std::size_t r = 0; r < sn_.nclasses && r < st.server_parallelism.size(); ++r) {
1252 pools.parallelism[r] = st.server_parallelism[r] < 1 ? 1 : st.server_parallelism[r];
1253 }
1254 if (has_types) {
1255 pools.policy = st.hetero_policy;
1256 for (const auto& pool : st.server_types) {
1257 pools.names.push_back(pool.name);
1258 pools.counts.push_back(pool.count);
1259 std::vector<bool> row(sn_.nclasses, true);
1260 for (std::size_t r = 0; r < sn_.nclasses; ++r) {
1261 // An EMPTY compatibility row means "every class", the constructor
1262 // default; JMT has no such shorthand, so it is expanded here.
1263 row[r] = pool.compatible.empty()
1264 ? true
1265 : (r < pool.compatible.size() ? pool.compatible[r] : false);
1266 }
1267 pools.compat.push_back(row);
1268 }
1269 } else {
1270 pools.names.push_back(sn_.nodes[ind - 1].name + " - Server Type 1");
1271 pools.counts.push_back(st.nservers);
1272 pools.compat.push_back(std::vector<bool>(sn_.nclasses, true));
1273 }
1274 return pools;
1275 }
1276
1277 /** Port of `saveClassParallelism`: `Server.serverNumRequired`, per class. */
1278 void save_class_parallelism(xml::Element& section, std::size_t ind) {
1279 const ServerPools pools = server_pools(ind);
1280 if (!pools.present) return;
1281 xml::Element& p = jmt_param(section, "java.lang.Integer", "classParallelism", true);
1282 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
1283 if (!keep_[r - 1]) continue;
1284 jmt_ref_class(p, cname(r));
1285 xml::Element& sp = p.add_child("subParameter");
1286 sp.set_attr("classPath", "java.lang.Integer");
1287 sp.set_attr("name", "serverParallelism");
1288 sp.add_text_child("value", jmt_int(static_cast<double>(pools.parallelism[r - 1])));
1289 }
1290 }
1291
1292 /** Port of `saveServerTypeNames`. */
1293 void save_server_type_names(xml::Element& section, std::size_t ind) {
1294 const ServerPools pools = server_pools(ind);
1295 if (!pools.present) return;
1296 xml::Element& p = jmt_param(section, "java.lang.String", "serverNames", true);
1297 for (const std::string& name : pools.names) {
1298 xml::Element& sp = p.add_child("subParameter");
1299 sp.set_attr("classPath", "java.lang.String");
1300 sp.set_attr("name", "serverTypesNames");
1301 sp.add_text_child("value", name);
1302 }
1303 }
1304
1305 /** Port of `saveServersPerType`. */
1306 void save_servers_per_type(xml::Element& section, std::size_t ind) {
1307 const ServerPools pools = server_pools(ind);
1308 if (!pools.present) return;
1309 xml::Element& p = jmt_param(section, "java.lang.Integer", "serversPerServerType", true);
1310 for (double count : pools.counts) {
1311 xml::Element& sp = p.add_child("subParameter");
1312 sp.set_attr("classPath", "java.lang.Integer");
1313 sp.set_attr("name", "serverTypesNumOfServers");
1314 sp.add_text_child("value", jmt_int(count));
1315 }
1316 }
1317
1318 /** Port of `saveServerCompatibilities`. */
1319 void save_server_compatibilities(xml::Element& section, std::size_t ind) {
1320 const ServerPools pools = server_pools(ind);
1321 if (!pools.present) return;
1322 xml::Element& p = jmt_param(section, "java.lang.Object", "serverCompatibilities", true);
1323 for (const std::vector<bool>& row : pools.compat) {
1324 xml::Element& tn = p.add_child("subParameter");
1325 tn.set_attr("array", "true");
1326 tn.set_attr("classPath", "java.lang.Boolean");
1327 tn.set_attr("name", "serverTypesCompatibilities");
1328 for (std::size_t r = 0; r < sn_.nclasses; ++r) {
1329 xml::Element& cn = tn.add_child("subParameter");
1330 cn.set_attr("classPath", "java.lang.Boolean");
1331 cn.set_attr("name", "compatibilities");
1332 cn.add_text_child("value", row[r] ? "true" : "false");
1333 }
1334 }
1335 }
1336
1337 /** Port of `saveHeteroSchedPolicy`, via `HeteroSchedPolicy.toJMTText`. */
1338 void save_hetero_sched_policy(xml::Element& section, std::size_t ind) {
1339 const ServerPools pools = server_pools(ind);
1340 if (!pools.present) return;
1341 jmt_param_value(section, "java.lang.String", "schedulingPolicy",
1342 jmt_hetero_text(pools.policy));
1343 }
1344
1345 /**
1346 * Warns that per-server-type service rates cannot reach the JMT engine.
1347 *
1348 * JMT keys the ServiceStrategy array of a station by refClass, so its loader
1349 * (`jmt.engine.simEngine.SimLoader`) keeps one strategy per class however many
1350 * (type, class) entries are written, and every pool of a station ends up
1351 * serving at the class rate. Pool sizes, class compatibilities and the
1352 * assignment policy do cross; per-pool service laws do not.
1353 */
1354 void warn_hetero_rates(std::size_t ind) const {
1355 const std::size_t ist = sn_.nodes[ind - 1].station;
1356 if (ist == 0) return;
1357 const auto& pools = sn_.stations[ist - 1].server_types;
1358 if (pools.size() < 2) return;
1359 bool first_set = false, distinct = false;
1360 double first = 0.0;
1361 for (const auto& pool : pools) {
1362 for (const lang::Distrib<T>& sd : pool.service) {
1363 if (sd.disabled) continue;
1364 const double mean = num_traits<T>::to_double(sd.mean);
1365 if (!(mean > 0)) continue;
1366 if (!first_set) { first = mean; first_set = true; }
1367 else if (std::abs(mean - first) > 1e-12) { distinct = true; }
1368 }
1369 }
1370 if (!distinct) return;
1371 std::cerr << "[LINE] Warning: JMT keys service strategies by job class, so the "
1372 << "per-server-type service rates of station '" << sn_.nodes[ind - 1].name
1373 << "' cannot be exported; every pool will serve at the class service rate. "
1374 << "Use the LDES or CTMC solver for per-type rates." << std::endl;
1375 }
1376
1377 /**
1378 * Port of `saveServiceStrategy`.
1379 *
1380 * A pair the class never visits becomes a DisabledServiceTimeStrategy and
1381 * an Immediate becomes a ZeroServiceTimeStrategy; neither carries a
1382 * distribution. Everything else goes through the shared emitter.
1383 */
1384 void save_service_strategy(xml::Element& section, std::size_t ind) {
1385 const std::size_t ist = sn_.nodes[ind - 1].station;
1386 xml::Element& p = jmt_param(section, "jmt.engine.NetStrategies.ServiceStrategy",
1387 "ServiceStrategy", true);
1388 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
1389 if (!keep_[r - 1]) continue;
1390 jmt_ref_class(p, cname(r));
1391 xml::Element& sts = p.add_child("subParameter");
1392 const JmtDistView<T> v =
1393 ist == 0 ? JmtDistView<T>() : jmt_dist_view(sn_.service[ist - 1][r - 1]);
1394 if (v.type == lang::ProcessType::DISABLED) {
1395 sts.set_attr("classPath",
1396 "jmt.engine.NetStrategies.ServiceStrategies."
1397 "DisabledServiceTimeStrategy");
1398 sts.set_attr("name", "DisabledServiceTimeStrategy");
1399 continue;
1400 }
1401 if (v.type == lang::ProcessType::IMMEDIATE) {
1402 sts.set_attr("classPath",
1403 "jmt.engine.NetStrategies.ServiceStrategies.ZeroServiceTimeStrategy");
1404 sts.set_attr("name", "ZeroServiceTimeStrategy");
1405 continue;
1406 }
1407 sts.set_attr("classPath",
1408 "jmt.engine.NetStrategies.ServiceStrategies.ServiceTimeStrategy");
1409 sts.set_attr("name", "ServiceTimeStrategy");
1410 jmt_append_distribution(sts, v, "SolverJMT (service)");
1411 }
1412 }
1413
1414 /**
1415 * Port of `saveArrivalStrategy`.
1416 *
1417 * A CLOSED class has no arrival process at the Source and is exported as a
1418 * ServiceTimeStrategy with a literal `null` body, which is how JMT spells
1419 * "this class does not arrive here". So is an open class the Source
1420 * disables -- one that enters by class switching only.
1421 */
1422 void save_arrival_strategy(xml::Element& section, std::size_t ind) {
1423 const std::size_t ist = sn_.nodes[ind - 1].station;
1424 xml::Element& p = jmt_param(section, "jmt.engine.NetStrategies.ServiceStrategy",
1425 "ServiceStrategy", true);
1426 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
1427 if (!keep_[r - 1]) continue;
1428 jmt_ref_class(p, cname(r));
1429 xml::Element& sts = p.add_child("subParameter");
1430 sts.set_attr("classPath",
1431 "jmt.engine.NetStrategies.ServiceStrategies.ServiceTimeStrategy");
1432 sts.set_attr("name", "ServiceTimeStrategy");
1433 const bool closed = std::isfinite(sn_.classes[r - 1].population);
1434 const JmtDistView<T> v =
1435 ist == 0 ? JmtDistView<T>() : jmt_dist_view(sn_.service[ist - 1][r - 1]);
1436 if (closed || v.type == lang::ProcessType::DISABLED) {
1437 sts.add_text_child("value", "null");
1438 continue;
1439 }
1440 if (v.type == lang::ProcessType::IMMEDIATE) {
1441 sts.set_attr("classPath",
1442 "jmt.engine.NetStrategies.ServiceStrategies.ZeroServiceTimeStrategy");
1443 sts.set_attr("name", "ZeroServiceTimeStrategy");
1444 continue;
1445 }
1446 jmt_append_distribution(sts, v, "SolverJMT (arrival)");
1447 }
1448 }
1449
1450 /** Port of `savePreemptiveStrategy`: which PS variant a PSServer runs. */
1451 void save_preemptive_strategy(xml::Element& section, std::size_t ind) {
1452 const std::size_t ist = sn_.nodes[ind - 1].station;
1453 xml::Element& p = jmt_param(section, "jmt.engine.NetStrategies.PSStrategy", "PSStrategy",
1454 true);
1455 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
1456 if (!keep_[r - 1]) continue;
1457 jmt_ref_class(p, cname(r));
1458 const char* nm = nullptr;
1459 if (ist != 0) switch (sn_.stations[ist - 1].sched) {
1460 // LPS shares the server evenly among those admitted, so its
1461 // in-service discipline IS EPS; the limit is the region.
1462 case SchedStrategy::PS:
1463 case SchedStrategy::LPS: nm = "EPSStrategy"; break;
1464 case SchedStrategy::DPS: nm = "DPSStrategy"; break;
1465 case SchedStrategy::GPS: nm = "GPSStrategy"; break;
1466 case SchedStrategy::PSPRIO: nm = "EPSStrategyPriority"; break;
1467 case SchedStrategy::DPSPRIO: nm = "DPSStrategyPriority"; break;
1468 case SchedStrategy::GPSPRIO: nm = "GPSStrategyPriority"; break;
1469 default: nm = nullptr; break;
1470 }
1471 xml::Element& sp = p.add_child("subParameter");
1472 if (nm != nullptr) {
1473 sp.set_attr("classPath", std::string("jmt.engine.NetStrategies.PSStrategies.") + nm);
1474 sp.set_attr("name", nm);
1475 }
1476 }
1477 }
1478
1479 /** Port of `savePreemptiveWeights`: the DPS/GPS share of each class. */
1480 void save_preemptive_weights(xml::Element& section, std::size_t ind) {
1481 const std::size_t ist = sn_.nodes[ind - 1].station;
1482 xml::Element& p = jmt_param(section, "java.lang.Double", "serviceWeights", true);
1483 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
1484 if (!keep_[r - 1]) continue;
1485 jmt_ref_class(p, cname(r));
1486 double w = 0.0;
1487 if (ist != 0 && sn_.stations[ist - 1].schedparam.size() >= r)
1488 w = d(sn_.stations[ist - 1].schedparam[r - 1]);
1489 xml::Element& sp = p.add_child("subParameter");
1490 sp.set_attr("classPath", "java.lang.Double");
1491 sp.set_attr("name", "serviceWeight");
1492 sp.add_text_child("value", jmt_num(w));
1493 }
1494 }
1495
1496 /**
1497 * Port of `saveDelayOffStrategy`: the setup and delay-off times of a server
1498 * that powers down when idle.
1499 *
1500 * JMT casts each per-class entry to `ServiceStrategy[]` and reads element
1501 * [0], so the strategy sits inside a single-element array rather than
1502 * directly under the class. A class with no time declared gets a
1503 * deterministic zero, not an omission: an absent entry would leave JMT's
1504 * array short and shift every later class's setup time onto the wrong one.
1505 */
1506 void save_delay_off_strategy(xml::Element& section, std::size_t ind) {
1507 const std::size_t ist = sn_.nodes[ind - 1].station;
1508 if (ist == 0) return;
1509 const auto it = sn_.setupparam.find(ist);
1510 if (it == sn_.setupparam.end()) return;
1511 const qn::SetupDelayOffParam<T>& sp = it->second;
1512 bool any = false;
1513 for (const lang::Distrib<T>& s : sp.setup)
1514 if (!s.disabled) any = true;
1515 if (!any) return;
1516
1517 // JMT >= 1.5.0 binds the 6-argument Server constructor positionally:
1518 // (..., switchoverStrategies, delayOffTime, setUpTime). Earlier releases
1519 // take the 5-argument form, so the null switchover is written only there.
1520 if (opt_.jmt150) {
1521 xml::Element& sw = jmt_param(section, "java.lang.Object", "switchoverStrategies", true);
1522 sw.add_text_child("value", "null");
1523 }
1524 const char* names[2] = {"delayOffTime", "setUpTime"};
1525 for (int which = 0; which < 2; ++which) {
1526 const std::vector<lang::Distrib<T>>& tab = which == 0 ? sp.delayoff : sp.setup;
1527 xml::Element& p = jmt_param(section, "java.lang.Object", names[which], true);
1528 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
1529 jmt_ref_class(p, cname(r));
1530 xml::Element& row = p.add_child("subParameter");
1531 row.set_attr("array", "true");
1532 row.set_attr("classPath", "jmt.engine.NetStrategies.ServiceStrategy");
1533 row.set_attr("name", names[which]);
1534 xml::Element& sts = row.add_child("subParameter");
1535 sts.set_attr("classPath",
1536 "jmt.engine.NetStrategies.ServiceStrategies.ServiceTimeStrategy");
1537 sts.set_attr("name", "ServiceTimeStrategy");
1538 if (r <= tab.size() && !tab[r - 1].disabled)
1539 append_simple_distribution(sts, tab[r - 1]);
1540 else
1541 append_zero_time(sts);
1542 }
1543 }
1544 }
1545
1546 /** `appendZeroTimeXml`: a deterministic zero. */
1547 void append_zero_time(xml::Element& parent) {
1548 xml::Element& dn = parent.add_child("subParameter");
1549 dn.set_attr("classPath", "jmt.engine.random.DeterministicDistr");
1550 dn.set_attr("name", "Deterministic");
1551 xml::Element& par = parent.add_child("subParameter");
1552 par.set_attr("classPath", "jmt.engine.random.DeterministicDistrPar");
1553 par.set_attr("name", "distrPar");
1554 jmt_scalar(par, "java.lang.Double", "t", "0.0");
1555 }
1556
1557 /**
1558 * `appendDistributionXml`: the REDUCED emitter the setup/delay-off pair
1559 * uses -- Exp, Erlang, Det, Immediate, and everything else as a
1560 * deterministic time equal to its mean.
1561 *
1562 * The fallback is the reference's and is kept: a setup time is a small
1563 * fixed overhead in every model that has one, so replacing an exotic law by
1564 * its mean there is a documented simplification rather than a silent one,
1565 * and refusing would reject models JMT can otherwise run.
1566 */
1567 void append_simple_distribution(xml::Element& parent, const lang::Distrib<T>& dist) {
1568 if (dist.type == lang::ProcessType::IMMEDIATE) {
1569 append_zero_time(parent);
1570 return;
1571 }
1572 const double mean = d(dist.mean);
1573 if (dist.type == lang::ProcessType::EXP) {
1574 xml::Element& dn = parent.add_child("subParameter");
1575 dn.set_attr("classPath", "jmt.engine.random.Exponential");
1576 dn.set_attr("name", "Exponential");
1577 xml::Element& par = parent.add_child("subParameter");
1578 par.set_attr("classPath", "jmt.engine.random.ExponentialPar");
1579 par.set_attr("name", "distrPar");
1580 jmt_double(par, "lambda", mean > 0.0 ? 1.0 / mean : 0.0);
1581 return;
1582 }
1583 if (dist.type == lang::ProcessType::ERLANG) {
1584 const std::size_t ph = dist.phases();
1585 xml::Element& dn = parent.add_child("subParameter");
1586 dn.set_attr("classPath", "jmt.engine.random.Erlang");
1587 dn.set_attr("name", "Erlang");
1588 xml::Element& par = parent.add_child("subParameter");
1589 par.set_attr("classPath", "jmt.engine.random.ErlangPar");
1590 par.set_attr("name", "distrPar");
1591 jmt_double(par, "alpha", mean > 0.0 ? static_cast<double>(ph) / mean : 0.0);
1592 jmt_scalar(par, "java.lang.Long", "r", jmt_int(static_cast<double>(ph)));
1593 return;
1594 }
1595 xml::Element& dn = parent.add_child("subParameter");
1596 dn.set_attr("classPath", "jmt.engine.random.DeterministicDistr");
1597 dn.set_attr("name", "Deterministic");
1598 xml::Element& par = parent.add_child("subParameter");
1599 par.set_attr("classPath", "jmt.engine.random.DeterministicDistrPar");
1600 par.set_attr("name", "distrPar");
1601 jmt_double(par, "t", mean);
1602 }
1603
1604 // -- Dispatcher / ClassSwitch / Fork / Join ------------------------------
1605
1606 /**
1607 * Port of `saveRoutingStrategy`.
1608 *
1609 * A CLASS SWITCH NODE IS EXPORTED AS RANDOM ROUTING. It has exactly one
1610 * outgoing link, so uniform routing over it is the same routing, and it
1611 * avoids reading `rt` at a node whose class-switch mass the refresh has
1612 * already folded into the edges around it.
1613 */
1614 void save_routing_strategy(xml::Element& section, std::size_t ind) {
1615 const std::size_t K = sn_.nclasses;
1616 const bool is_cs = sn_.nodes[ind - 1].nodetype == NodeType::ClassSwitch;
1617 xml::Element& p =
1618 jmt_param(section, "jmt.engine.NetStrategies.RoutingStrategy", "RoutingStrategy", true);
1619 for (std::size_t r = 1; r <= K; ++r) {
1620 if (!keep_[r - 1]) continue;
1621 jmt_ref_class(p, cname(r));
1622 const RoutingStrategy rs =
1623 is_cs ? RoutingStrategy::RAND
1624 : (sn_.nodes[ind - 1].routing.size() >= r ? sn_.nodes[ind - 1].routing[r - 1]
1625 : RoutingStrategy::PROB);
1626 xml::Element& sp = p.add_child("subParameter");
1627 switch (rs) {
1628 case RoutingStrategy::RAND:
1629 sp.set_attr("classPath",
1630 "jmt.engine.NetStrategies.RoutingStrategies.RandomStrategy");
1631 sp.set_attr("name", "Random");
1632 break;
1633 case RoutingStrategy::RROBIN:
1634 sp.set_attr("classPath",
1635 "jmt.engine.NetStrategies.RoutingStrategies.RoundRobinStrategy");
1636 sp.set_attr("name", "Round Robin");
1637 break;
1638 case RoutingStrategy::JSQ:
1639 sp.set_attr("classPath",
1640 "jmt.engine.NetStrategies.RoutingStrategies."
1641 "ShortestQueueLengthRoutingStrategy");
1642 sp.set_attr("name", "Join the Shortest Queue (JSQ)");
1643 break;
1644 case RoutingStrategy::SQ: {
1645 sp.set_attr("classPath",
1646 "jmt.engine.NetStrategies.RoutingStrategies.PowerOfKRoutingStrategy");
1647 sp.set_attr("name", "Power of k");
1648 const int dpar = sn_.nodes[ind - 1].routing_param.size() >= r
1649 ? sn_.nodes[ind - 1].routing_param[r - 1]
1650 : 0;
1651 jmt_scalar(sp, "java.lang.Integer", "k", jmt_int(static_cast<double>(dpar)));
1652 // Always false: LINE implements SQ(d) only. JMT's
1653 // withMemory selects Anselmi & Dufour SQ(d,N), a different
1654 // policy.
1655 jmt_scalar(sp, "java.lang.Boolean", "withMemory", "false");
1656 break;
1657 }
1658 case RoutingStrategy::WRROBIN: {
1659 sp.set_attr("classPath",
1660 "jmt.engine.NetStrategies.RoutingStrategies."
1661 "WeightedRoundRobinStrategy");
1662 sp.set_attr("name", "Weighted Round Robin");
1663 xml::Element& arr =
1664 jmt_param_sub(sp, "jmt.engine.NetStrategies.RoutingStrategies.WeightEntry",
1665 "WeightEntryArray");
1666 const std::map<std::size_t, double>& w =
1667 sn_.nodes[ind - 1].routing_weights.size() >= r
1668 ? sn_.nodes[ind - 1].routing_weights[r - 1]
1669 : empty_weights_;
1670 for (std::size_t j : outputs_of(ind)) {
1671 const auto wi = w.find(j);
1672 xml::Element& e = arr.add_child("subParameter");
1673 e.set_attr("classPath",
1674 "jmt.engine.NetStrategies.RoutingStrategies.WeightEntry");
1675 e.set_attr("name", "WeightEntry");
1676 jmt_scalar(e, "java.lang.String", "stationName", nname(j));
1677 jmt_scalar(e, "java.lang.Integer", "weight",
1678 jmt_int(wi == w.end() ? 0.0 : wi->second));
1679 }
1680 break;
1681 }
1682 case RoutingStrategy::PROB: {
1683 sp.set_attr("classPath",
1684 "jmt.engine.NetStrategies.RoutingStrategies.EmpiricalStrategy");
1685 sp.set_attr("name", "Probabilities");
1686 xml::Element& arr = jmt_param_sub(sp, "jmt.engine.random.EmpiricalEntry",
1687 "EmpiricalEntryArray");
1688 for (std::size_t j : outputs_of(ind)) {
1689 const double pr = route_node(ind, r, j, r);
1690 if (!(pr > 0.0)) continue;
1691 xml::Element& e = arr.add_child("subParameter");
1692 e.set_attr("classPath", "jmt.engine.random.EmpiricalEntry");
1693 e.set_attr("name", "EmpiricalEntry");
1694 jmt_scalar(e, "java.lang.String", "stationName", nname(j));
1695 jmt_scalar(e, "java.lang.Double", "probability", jmt_fmt(pr));
1696 }
1697 break;
1698 }
1699 default:
1700 sp.set_attr(
1701 "classPath",
1702 "jmt.engine.NetStrategies.RoutingStrategies.DisabledRoutingStrategy");
1703 sp.set_attr("name", "Random");
1704 break;
1705 }
1706 }
1707 }
1708
1709 /** `<subParameter array="true" classPath=CP name=NAME>` */
1710 static xml::Element& jmt_param_sub(xml::Element& parent, const char* cp, const char* name) {
1711 xml::Element& e = parent.add_child("subParameter");
1712 e.set_attr("array", "true");
1713 e.set_attr("classPath", cp);
1714 e.set_attr("name", name);
1715 return e;
1716 }
1717
1718 /** `sn.rtnodes((i-1)K+r, (j-1)K+s)`, guarded against an unbuilt matrix. */
1719 double route_node(std::size_t i, std::size_t r, std::size_t j, std::size_t s) const {
1720 const std::size_t K = sn_.nclasses;
1721 const std::size_t a = (i - 1) * K + (r - 1), b = (j - 1) * K + (s - 1);
1722 if (sn_.rtnodes.rows() <= a || sn_.rtnodes.cols() <= b) return 0.0;
1723 return d(sn_.rtnodes(a, b));
1724 }
1725
1726 /**
1727 * Port of `saveClassSwitchStrategy`: the (K x K) switching matrix as JMT
1728 * reads it, each cell the mass class r leaves this node with as class s.
1729 *
1730 * The cell is the SUM over the node's outgoing links of `rtnodes`, not the
1731 * declared `csmatrix`: the refresh has already multiplied the switch by the
1732 * routing, and the sum recovers the switching probability independently of
1733 * how the mass was split over the links.
1734 */
1735 void save_class_switch_strategy(xml::Element& section, std::size_t ind) {
1736 const std::size_t K = sn_.nclasses;
1737 const std::vector<std::size_t> jset = outputs_of(ind);
1738 xml::Element& p = jmt_param(section, "java.lang.Object", "matrix", true);
1739 for (std::size_t r = 1; r <= K; ++r) {
1740 if (!keep_[r - 1]) continue;
1741 jmt_ref_class(p, cname(r));
1742 xml::Element& row = p.add_child("subParameter");
1743 row.set_attr("array", "true");
1744 row.set_attr("classPath", "java.lang.Float");
1745 row.set_attr("name", "row");
1746 for (std::size_t s = 1; s <= K; ++s) {
1747 if (!keep_[s - 1]) continue;
1748 jmt_ref_class(row, cname(s));
1749 double acc = 0.0;
1750 for (std::size_t j : jset) acc += route_node(ind, r, j, s);
1751 xml::Element& cell = row.add_child("subParameter");
1752 cell.set_attr("classPath", "java.lang.Float");
1753 cell.set_attr("name", "cell");
1754 cell.add_text_child("value", jmt_fmt(acc));
1755 }
1756 }
1757 }
1758
1759 /**
1760 * Port of `saveForkStrategy`.
1761 *
1762 * ONE OutPath ENTRY PER BRANCH. The reference used to build the entry
1763 * inside a loop over the connected nodes but append it outside, so only the
1764 * LAST link survived, and the JAR and this port transcribed the same shape.
1765 * It was harmless only because `isSimplifiedFork` is true, which makes JMT
1766 * send one job down every outgoing link and ignore the branch list -- and it
1767 * stops being harmless the moment a branch carries its own probability or
1768 * its own jobs-per-link. All four codebases now emit the full list.
1769 */
1770 void save_fork_strategy(xml::Element& section, std::size_t ind) {
1771 const qn::ForkParam<T>* fk = sn_.fork_param_of(ind);
1772 const double fan_out = sn_.nodes[ind - 1].tasks_per_link;
1773 jmt_param_value(section, "java.lang.Integer", "jobsPerLink", jmt_int(fan_out));
1774 jmt_param_value(section, "java.lang.Integer", "block", "-1");
1775
1776 // isSimplifiedFork lets JMT ignore the branch list and send one job down
1777 // every link. That is only the same model when every branch is certain
1778 // and carries the same number of tasks, so a variable forking level
1779 // switches it off and makes JMT read the per-branch entries below.
1780 bool simplified = true;
1781 if (fk != 0) {
1782 for (std::size_t k = 0; k < fk->fan_out_link.rows() && simplified; ++k)
1783 for (std::size_t r = 0; r < fk->fan_out_link.cols() && simplified; ++r) {
1784 const double p = num_traits<T>::to_double(fk->fan_out_prob(k, r));
1785 if (p == 0.0) continue; // link not taken
1786 if (p != 1.0) simplified = false;
1787 if (num_traits<T>::to_double(fk->fan_out_link(k, r)) != fan_out)
1788 simplified = false;
1789 if (!fk->fan_out_dist[k][r].disabled) simplified = false;
1790 }
1791 }
1792 jmt_param_value(section, "java.lang.Boolean", "isSimplifiedFork",
1793 simplified ? "true" : "false");
1794
1795 xml::Element& p =
1796 jmt_param(section, "jmt.engine.NetStrategies.ForkStrategy", "ForkStrategy", true);
1797 const std::vector<std::size_t> outs = outputs_of(ind);
1798 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
1799 if (!keep_[r - 1]) continue;
1800 jmt_ref_class(p, cname(r));
1801 xml::Element& cs = p.add_child("subParameter");
1802 cs.set_attr("classPath", "jmt.engine.NetStrategies.ForkStrategies.ProbabilitiesFork");
1803 cs.set_attr("name", "Branch Probabilities");
1804 xml::Element& arr = jmt_param_sub(
1805 cs, "jmt.engine.NetStrategies.ForkStrategies.OutPath", "EmpiricalEntryArray");
1806 const RoutingStrategy rs = sn_.nodes[ind - 1].routing.size() >= r
1807 ? sn_.nodes[ind - 1].routing[r - 1]
1808 : RoutingStrategy::PROB;
1809 if (rs != RoutingStrategy::PROB || outs.empty()) continue;
1810 for (std::size_t oi = 0; oi < outs.size(); ++oi) {
1811 xml::Element& entry = arr.add_child("subParameter");
1812 entry.set_attr("classPath", "jmt.engine.NetStrategies.ForkStrategies.OutPath");
1813 entry.set_attr("name", "OutPathEntry");
1814 xml::Element& unit = entry.add_child("subParameter");
1815 unit.set_attr("classPath", "jmt.engine.random.EmpiricalEntry");
1816 unit.set_attr("name", "outUnitProbability");
1817 jmt_scalar(unit, "java.lang.String", "stationName", nname(outs[oi]));
1818
1819 // branch activation probability: JMT's outUnitProbability
1820 const std::size_t k0 = outs[oi] - 1, r0 = r - 1;
1821 const bool has_fan = fk != 0;
1822 const double branch_p =
1823 has_fan ? num_traits<T>::to_double(fk->fan_out_prob(k0, r0)) : 1.0;
1824 jmt_scalar(unit, "java.lang.Double", "probability", jmt_fmt(branch_p));
1825
1826 // JobsPerLinkDis is an EmpiricalEntry ARRAY: one entry per point
1827 // of the jobs-per-link distribution. A deterministic fork emits
1828 // the single degenerate entry it always did.
1829 std::vector<double> pts, prs;
1830 if (has_fan && !fk->fan_out_dist[k0][r0].disabled) {
1831 const lang::Distrib<T>& d = fk->fan_out_dist[k0][r0];
1832 double tot = 0.0;
1833 for (std::size_t e = 0; e < d.params.size(); ++e)
1834 tot += num_traits<T>::to_double(d.params[e]);
1835 for (std::size_t e = 0; e < d.params.size(); ++e) {
1836 pts.push_back(d.trace.empty()
1837 ? static_cast<double>(e + 1)
1838 : num_traits<T>::to_double(d.trace[e]));
1839 prs.push_back(num_traits<T>::to_double(d.params[e]) / tot);
1840 }
1841 } else if (has_fan) {
1842 pts.push_back(num_traits<T>::to_double(fk->fan_out_link(k0, r0)));
1843 prs.push_back(1.0);
1844 } else {
1845 pts.push_back(fan_out);
1846 prs.push_back(1.0);
1847 }
1848
1849 xml::Element& jpl =
1850 jmt_param_sub(entry, "jmt.engine.random.EmpiricalEntry", "JobsPerLinkDis");
1851 for (std::size_t e = 0; e < pts.size(); ++e) {
1852 xml::Element& jple = jpl.add_child("subParameter");
1853 jple.set_attr("classPath", "jmt.engine.random.EmpiricalEntry");
1854 jple.set_attr("name", "EmpiricalEntry");
1855 jmt_scalar(jple, "java.lang.String", "numbers", jmt_int(pts[e]));
1856 jmt_scalar(jple, "java.lang.Double", "probability", jmt_fmt(prs[e]));
1857 }
1858 }
1859 }
1860 }
1861
1862 /**
1863 * Port of `saveJoinStrategy`.
1864 *
1865 * `numRequired` is -1 for a standard join -- JMT's "every sibling" -- and
1866 * the quorum for a partial one. The reference reads two separate fields
1867 * (`fanIn` and `joinRequired`); this port's `JoinDecl` carries the quorum
1868 * once, with 0 meaning "every sibling", which is the same information.
1869 */
1870 void save_join_strategy(xml::Element& section, std::size_t ind) {
1871 const auto it = sn_.joindecl.find(ind);
1872 const bool partial =
1873 it != sn_.joindecl.end() && it->second.strategy == JoinStrategy::PARTIAL;
1874 const double quorum = it != sn_.joindecl.end() ? it->second.quorum : 0.0;
1875 xml::Element& p =
1876 jmt_param(section, "jmt.engine.NetStrategies.JoinStrategy", "JoinStrategy", true);
1877 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
1878 jmt_ref_class(p, cname(r));
1879 xml::Element& sp = p.add_child("subParameter");
1880 if (partial) {
1881 sp.set_attr("classPath", "jmt.engine.NetStrategies.JoinStrategies.PartialJoin");
1882 sp.set_attr("name", "Quorum");
1883 } else {
1884 sp.set_attr("classPath", "jmt.engine.NetStrategies.JoinStrategies.NormalJoin");
1885 sp.set_attr("name", "Standard Join");
1886 }
1887 const double req = partial ? quorum : (quorum > 0.0 ? quorum : -1.0);
1888 jmt_scalar(sp, "java.lang.Integer", "numRequired", jmt_int(req));
1889 }
1890 }
1891
1892 /** Port of `saveLogTunnel`: the ten fields JMT's LogTunnel section takes. */
1893 void save_log_tunnel(xml::Element& section, std::size_t ind) {
1894 const qn::NodeDef::LoggerParam& lg = sn_.nodes[ind - 1].logger;
1895 std::string path = lg.file_path.empty() ? sn_.log_path : lg.file_path;
1896 if (!path.empty() && path[path.size() - 1] != '/') path += '/';
1897 const char* bools[7] = {"logExecTimestamp", "logLoggerName", "logTimeStamp",
1898 "logJobID", "logJobClass", "logTimeSameClass",
1899 "logTimeAnyClass"};
1900 const bool vals[7] = {lg.start_time, lg.logger_name, lg.timestamp, lg.job_id,
1901 lg.job_class, lg.time_same_class, lg.time_any_class};
1902 jmt_param_value(section, "java.lang.String", "logfileName", lg.file_name);
1903 jmt_param_value(section, "java.lang.String", "logfilePath", path);
1904 for (int j = 0; j < 7; ++j)
1905 jmt_param_value(section, "java.lang.Boolean", bools[j], vals[j] ? "true" : "false");
1906 jmt_param_value(section, "java.lang.Integer", "numClasses",
1907 jmt_int(static_cast<double>(sn_.nclasses)));
1908 }
1909
1910 // -- model-level blocks -------------------------------------------------
1911
1912 /**
1913 * Port of `saveMetrics`: one `<measure>` per enabled (station, class, kind),
1914 * plus the FCR and cache-hit-rate measures.
1915 *
1916 * `Residence Time` is NOT requested, as in the reference: JMT's definition
1917 * of it disagrees with LINE's on class-switching models, and the residence
1918 * time is recomputed from the response time and the visits instead.
1919 */
1920 void save_metrics(xml::Element& sim) {
1924 for (int k = 0; k < 5; ++k) save_metric(sim, kinds[k]);
1925 // saveMetrics.m: the per-station Tardiness handles, then the per-class
1926 // System Tardiness ones, which saveMetric.m writes with an empty
1927 // nodeType/referenceNode and the handle row index (1) in the name.
1928 save_metric(sim, JmtMetricKind::Tard);
1929 save_sys_tard_metrics(sim);
1930 save_fcr_metrics(sim);
1931 save_fj_metrics(sim);
1932 save_cache_hit_rate_metrics(sim);
1933 }
1934
1935 /**
1936 * Port of `saveFJMetrics`: 'Fork Join Response Time' and 'Fork Join Number of Customers' at the Fork of
1937 * every Fork/Join pair, for each class visiting it. JMT keeps the section list in the Fork's input
1938 * section and closes a job's entry when its Join fires, so both measure the whole fork-join section.
1939 */
1940 void save_fj_metrics(xml::Element& sim) {
1941 std::vector<std::size_t> forks;
1942 for (const auto& e : sn_.fj)
1943 if (e.first != 0 && e.second != 0) forks.push_back(e.first);
1944 std::sort(forks.begin(), forks.end());
1945 forks.erase(std::unique(forks.begin(), forks.end()), forks.end());
1946 static const char* types[2] = {"Fork Join Response Time", "Fork Join Number of Customers"};
1947 static const char* tags[2] = {"FJRespT", "FJQLen"};
1948 for (std::size_t f : forks)
1949 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
1950 if (!keep_[r - 1]) continue;
1951 bool visits = false;
1952 for (std::size_t c = 0; c < sn_.inchain.size() && c < sn_.nodevisits.size(); ++c) {
1953 const std::vector<std::size_t>& ic = sn_.inchain[c];
1954 if (std::find(ic.begin(), ic.end(), r) == ic.end()) continue;
1955 visits = num_traits<T>::to_double(sn_.nodevisits[c](f - 1, r - 1)) > 0.0;
1956 break;
1957 }
1958 if (!visits) continue;
1959 for (int k = 0; k < 2; ++k) {
1960 xml::Element& m = sim.add_child("measure");
1961 m.set_attr("alpha", jmt_sig2(1.0 - opt_.sim_conf_int));
1962 m.set_attr("name", std::string(tags[k]) + "_" + nname(f) + "_" + cname(r));
1963 m.set_attr("nodeType", "station");
1964 m.set_attr("precision", jmt_sig2(opt_.sim_max_rel_err));
1965 m.set_attr("referenceNode", nname(f));
1966 m.set_attr("referenceUserClass", cname(r));
1967 m.set_attr("type", types[k]);
1968 m.set_attr("verbose", "false");
1969 }
1970 }
1971 }
1972
1973 void save_metric(xml::Element& sim, JmtMetricKind kind) {
1974 for (std::size_t ist = 1; ist <= sn_.nstations; ++ist)
1975 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
1976 if (!keep_[r - 1]) continue;
1977 if (!jmt_metric_enabled(sn_, kind, ist, r, cacheclass_)) continue;
1978 xml::Element& m = sim.add_child("measure");
1979 m.set_attr("alpha", jmt_sig2(1.0 - opt_.sim_conf_int));
1980 m.set_attr("name", std::string("Performance_") +
1981 jmt_int(static_cast<double>(ist)));
1982 m.set_attr("nodeType", "station");
1983 m.set_attr("precision", jmt_sig2(opt_.sim_max_rel_err));
1984 m.set_attr("referenceNode", nname(sn_.station_to_node[ist - 1]));
1985 m.set_attr("referenceUserClass", cname(r));
1986 m.set_attr("type", jmt_metric_text(kind));
1987 m.set_attr("verbose", "false");
1988 }
1989 }
1990
1991 /** The `System Tardiness` measures of `saveMetrics.m`, one per exported class. */
1992 void save_sys_tard_metrics(xml::Element& sim) {
1993 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
1994 if (!keep_[r - 1]) continue;
1995 xml::Element& m = sim.add_child("measure");
1996 m.set_attr("alpha", jmt_sig2(1.0 - opt_.sim_conf_int));
1997 m.set_attr("name", "Performance_1");
1998 m.set_attr("nodeType", "");
1999 m.set_attr("precision", jmt_sig2(opt_.sim_max_rel_err));
2000 m.set_attr("referenceNode", "");
2001 m.set_attr("referenceUserClass", cname(r));
2002 m.set_attr("type", jmt_metric_text(JmtMetricKind::SysTard));
2003 m.set_attr("verbose", "false");
2004 }
2005 }
2006
2007 /**
2008 * Port of `saveClassSoftDeadlines.m`: the `<classSoftDeadlines>` child of an
2009 * EDD or EDF station's `<node>`, one `<softDeadline>` per exported class in
2010 * `<userClass>` order (SimLoader parses them positionally into
2011 * Queue.setSoftDeadlines). The deadline is RELATIVE to the arrival at the
2012 * station, as SolverLDES reads it. A no-op at every other node, since no
2013 * other put strategy reads the array.
2014 */
2015 void save_class_soft_deadlines(xml::Element& node, std::size_t ind) {
2016 const std::size_t ist = sn_.nodes[ind - 1].station;
2017 if (ist == 0) return;
2018 const SchedStrategy sc = sn_.stations[ist - 1].sched;
2019 if (sc != SchedStrategy::EDD && sc != SchedStrategy::EDF) return;
2020 const std::string reason = jmt_deadline_refusal(sn_);
2021 if (!reason.empty()) throw UnsupportedError(ErrorKind{"Structure"}, reason);
2022 xml::Element& dl = node.add_child("classSoftDeadlines");
2023 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2024 if (!keep_[r - 1]) continue;
2025 // a class without a deadline here is not served at this station (refused
2026 // above otherwise), so the engine never reads its slot
2027 const double d = sn_.classes[r - 1].deadline;
2028 char buf[64];
2029 std::snprintf(buf, sizeof(buf), "%.12f", std::isfinite(d) ? d : 0.0);
2030 dl.add_text_child("softDeadline", buf);
2031 }
2032 }
2033
2034 /** Port of `saveCacheHitRateMetrics`. */
2035 void save_cache_hit_rate_metrics(xml::Element& sim) {
2036 for (const auto& kv : sn_.nodeparam) {
2037 const std::size_t ind = kv.first;
2038 if (sn_.nodes[ind - 1].nodetype != NodeType::Cache) continue;
2039 const qn::CacheParam<T>& cp = kv.second;
2040 for (std::size_t r = 0; r < cp.hitclass.size(); ++r) {
2041 if (cp.hitclass[r] == 0) continue;
2042 xml::Element& m = sim.add_child("measure");
2043 m.set_attr("alpha", jmt_sig2(1.0 - opt_.sim_conf_int));
2044 m.set_attr("name", "CacheHitRate_" + nname(ind) + "_" + cname(cp.hitclass[r]));
2045 m.set_attr("nodeType", "station");
2046 m.set_attr("precision", jmt_sig2(opt_.sim_max_rel_err));
2047 m.set_attr("referenceNode", nname(ind));
2048 m.set_attr("referenceUserClass", cname(cp.hitclass[r]));
2049 m.set_attr("type", "Cache Hit Rate");
2050 m.set_attr("verbose", "false");
2051 }
2052 }
2053 }
2054
2055 /** Port of `saveFCRMetrics`: six aggregate measures per region. */
2056 void save_fcr_metrics(xml::Element& sim) {
2057 static const char* kinds[6] = {"Number of Customers", "Response Time", "Residence Time",
2058 "Throughput", "FCR Capacity", "FCR Memory"};
2059 int counter = 0;
2060 for (std::size_t f = 1; f <= sn_.regions.size(); ++f) {
2061 const std::string fcr = "FCRegion" + jmt_int(static_cast<double>(f));
2062 for (int k = 0; k < 6; ++k) {
2063 std::string flat(kinds[k]);
2064 flat.erase(std::remove(flat.begin(), flat.end(), ' '), flat.end());
2065 xml::Element& m = sim.add_child("measure");
2066 m.set_attr("alpha", jmt_sig2(1.0 - opt_.sim_conf_int));
2067 m.set_attr("name", "FCR_" + fcr + "_" + flat + "_" +
2068 jmt_int(static_cast<double>(counter)));
2069 m.set_attr("nodeType", "region");
2070 m.set_attr("precision", jmt_sig2(opt_.sim_max_rel_err));
2071 m.set_attr("referenceNode", fcr);
2072 m.set_attr("referenceUserClass", "");
2073 m.set_attr("type", kinds[k]);
2074 m.set_attr("verbose", "false");
2075 ++counter;
2076 }
2077 }
2078 }
2079
2080 /** Port of `saveLinks`: one `<connection>` per linked ordered pair. */
2081 void save_links(xml::Element& sim) {
2082 // Column-major, as MATLAB's `find` on the connection matrix returns.
2083 for (std::size_t j = 1; j <= sn_.nodes.size(); ++j)
2084 for (std::size_t i = 1; i <= sn_.nodes.size(); ++i) {
2085 if (!conn_[i - 1][j - 1]) continue;
2086 xml::Element& c = sim.add_child("connection");
2087 c.set_attr("source", nname(i));
2088 c.set_attr("target", nname(j));
2089 }
2090 for (const auto& pt : inhibitor_only_arcs()) { // inhibitor arcs with no token flow
2091 xml::Element& c = sim.add_child("connection");
2092 c.set_attr("source", nname(pt.first));
2093 c.set_attr("target", nname(pt.second));
2094 }
2095 }
2096
2097 /**
2098 * Port of the `preload` block of `writeJSIM`: where the jobs start.
2099 *
2100 * A Source has an infinite reservoir and a Join holds no jobs, so neither
2101 * takes a preload. Every other station reports its per-class count, and a
2102 * closed class with no customers anywhere is omitted -- JMT reads an
2103 * omitted class as zero, and writing the zero would also declare the class
2104 * present at a station it never visits.
2105 */
2106 void save_preload(xml::Element& sim) {
2107 // Collected before anything is emitted: the block is omitted entirely
2108 // when no station takes a preload, and an element already appended to
2109 // the document cannot be withdrawn.
2110 struct Row {
2111 std::size_t node;
2112 std::vector<std::pair<std::size_t, double>> pops; // (class, count)
2113 };
2114 std::vector<Row> rows;
2115 for (std::size_t ist = 1; ist <= sn_.nstations; ++ist) {
2116 const std::size_t ind = sn_.station_to_node[ist - 1];
2117 const NodeType ty = sn_.nodes[ind - 1].nodetype;
2118 if (ty == NodeType::Source || ty == NodeType::Join) continue;
2119 const std::vector<double> nir = initial_marginal(ist);
2120 Row row;
2121 row.node = ind;
2122 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2123 const double n = sn_.classes[r - 1].population;
2124 if (std::isfinite(n) && n == 0.0 && nir[r - 1] == 0.0) continue;
2125 row.pops.emplace_back(r, nir[r - 1]);
2126 }
2127 if (!row.pops.empty()) rows.push_back(row);
2128 }
2129 if (rows.empty()) return;
2130 xml::Element& preload = sim.add_child("preload");
2131 for (const Row& row : rows) {
2132 xml::Element& st = preload.add_child("stationPopulations");
2133 st.set_attr("stationName", nname(row.node));
2134 for (const auto& pc : row.pops) {
2135 xml::Element& cp = st.add_child("classPopulation");
2136 cp.set_attr("population", jmt_int(pc.second));
2137 cp.set_attr("refClass", cname(pc.first));
2138 }
2139 }
2140 }
2141
2142 /**
2143 * The per-class job count a station starts with.
2144 *
2145 * A Place's declared initial marking is its token count; every other
2146 * station takes `model.initDefault`, which puts each closed class's whole
2147 * population at its reference station and nothing anywhere else. Open
2148 * classes start empty.
2149 */
2150 std::vector<double> initial_marginal(std::size_t ist) const {
2151 std::vector<double> nir(sn_.nclasses, 0.0);
2152 const std::size_t ind = sn_.station_to_node[ist - 1];
2153 const auto im = sn_.initmarking.find(ind);
2154 if (im != sn_.initmarking.end()) {
2155 for (std::size_t r = 0; r < sn_.nclasses && r < im->second.size(); ++r)
2156 nir[r] = d(im->second[r]);
2157 return nir;
2158 }
2159 for (std::size_t r = 0; r < sn_.nclasses; ++r) {
2160 const double n = sn_.classes[r].population;
2161 if (std::isfinite(n) && sn_.classes[r].refstat == ist) nir[r] = n;
2162 }
2163 return nir;
2164 }
2165
2166 // -- Place (Storage / Linkage) ------------------------------------------
2167
2168 /** Port of `saveTotalCapacity`: the token bound of a place, -1 unbounded. */
2169 void save_total_capacity(xml::Element& section, std::size_t ind) {
2170 const std::size_t ist = sn_.nodes[ind - 1].station;
2171 const std::string v =
2172 (ist == 0 || !std::isfinite(sn_.cap[ist - 1])) ? "-1" : jmt_int(sn_.cap[ist - 1]);
2173 jmt_param_value(section, "java.lang.Integer", "totalCapacity", v);
2174 }
2175
2176 /** Port of `savePlaceCapacities`: the per-colour token bound. */
2177 void save_place_capacities(xml::Element& section, std::size_t ind) {
2178 const std::size_t ist = sn_.nodes[ind - 1].station;
2179 xml::Element& p = jmt_param(section, "java.lang.Integer", "capacities", true);
2180 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2181 if (!keep_[r - 1]) continue;
2182 jmt_ref_class(p, cname(r));
2183 const double c = ist == 0 ? std::numeric_limits<double>::infinity()
2184 : sn_.classcap[ist - 1][r - 1];
2185 xml::Element& sp = p.add_child("subParameter");
2186 sp.set_attr("classPath", "java.lang.Integer");
2187 sp.set_attr("name", "capacity");
2188 sp.add_text_child("value", std::isfinite(c) ? jmt_int(c) : "-1");
2189 }
2190 }
2191
2192 /**
2193 * Port of `saveDropRule`. It differs from `saveDropStrategy` only in the
2194 * parameter names JMT's Storage section expects (`dropRules`/`dropRule`).
2195 */
2196 void save_drop_rule(xml::Element& section, std::size_t ind) {
2197 const std::size_t ist = sn_.nodes[ind - 1].station;
2198 xml::Element& p = jmt_param(section, "java.lang.String", "dropRules", true);
2199 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2200 if (!keep_[r - 1]) continue;
2201 jmt_ref_class(p, cname(r));
2202 xml::Element& sp = p.add_child("subParameter");
2203 sp.set_attr("classPath", "java.lang.String");
2204 sp.set_attr("name", "dropRule");
2205 sp.add_text_child("value", drop_strategy_text(ist, r));
2206 }
2207 }
2208
2209 /**
2210 * Port of `savePutStrategies` (plural), the Storage section's insertion
2211 * rule. It offers only the three orders a place can hold tokens in, which
2212 * is why it is a separate handler from `savePutStrategy`.
2213 */
2214 void save_put_strategies(xml::Element& section, std::size_t ind) {
2215 const std::size_t ist = sn_.nodes[ind - 1].station;
2216 xml::Element& p = jmt_param(section, "jmt.engine.NetStrategies.QueuePutStrategy",
2217 "QueuePutStrategy", true);
2218 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2219 if (!keep_[r - 1]) continue;
2220 jmt_ref_class(p, cname(r));
2221 const char* nm = "TailStrategy";
2222 if (ist != 0) {
2223 if (sn_.stations[ist - 1].sched == SchedStrategy::SIRO) nm = "RandStrategy";
2224 else if (sn_.stations[ist - 1].sched == SchedStrategy::LCFS) nm = "HeadStrategy";
2225 }
2226 xml::Element& sp = p.add_child("subParameter");
2227 sp.set_attr("classPath",
2228 std::string("jmt.engine.NetStrategies.QueuePutStrategies.") + nm);
2229 sp.set_attr("name", nm);
2230 }
2231 }
2232
2233 // -- Transition (Enabling / Timing / Firing) ----------------------------
2234
2235 /** The transition parameters of node `ind`; refuses a node that has none. */
2236 const qn::TransitionParam<T>& transparam(std::size_t ind) const {
2237 const auto it = sn_.transparam.find(ind);
2238 if (it == sn_.transparam.end())
2239 throw InputError("SolverJMT: transition '" + nname(ind) + "' carries no mode table");
2240 return it->second;
2241 }
2242
2243 /**
2244 * Port of `saveEnablingConditions`.
2245 *
2246 * A place appears in the vector only when it carries a POSITIVE enabling or
2247 * inhibiting entry for the mode IN SOME CLASS. An enabling entry of infinity
2248 * is JMT's -1, "any number of tokens".
2249 *
2250 * THE ENTRIES ARE PER CLASS, which is what JSIM's own vector format is: one
2251 * `enablingEntry` per class, in class order. Writing the same number under
2252 * every class -- what this writer did while the struct had no class
2253 * dimension -- exported a net that demands every colour on every arc, and
2254 * that is why a multiclass net had to be refused here.
2255 */
2256 void save_enabling_conditions(xml::Element& section, std::size_t ind) {
2257 const qn::TransitionParam<T>& tp = transparam(ind);
2258 xml::Element& p =
2259 jmt_param(section, "jmt.engine.NetStrategies.TransitionUtilities.TransitionMatrix",
2260 "enablingConditions", true);
2261 for (std::size_t m = 0; m < tp.nmodes; ++m) {
2262 xml::Element& cond = p.add_child("subParameter");
2263 cond.set_attr("classPath",
2264 "jmt.engine.NetStrategies.TransitionUtilities.TransitionMatrix");
2265 cond.set_attr("name", "enablingCondition");
2266 xml::Element& vecs = jmt_param_sub(
2267 cond, "jmt.engine.NetStrategies.TransitionUtilities.TransitionVector",
2268 "enablingVectors");
2269 for (std::size_t k = 1; k <= sn_.nodes.size(); ++k) {
2270 bool relevant = false;
2271 for (std::size_t r = 1; r <= sn_.nclasses && !relevant; ++r) {
2272 const double en = arc(tp.enabling, m, k, r);
2273 const double in = arc(tp.inhibiting, m, k, r);
2274 relevant = (std::isfinite(en) && en > 0.0) ||
2275 (std::isfinite(in) && in > 0.0);
2276 }
2277 if (!relevant) continue;
2278 xml::Element& vec = vecs.add_child("subParameter");
2279 vec.set_attr("classPath",
2280 "jmt.engine.NetStrategies.TransitionUtilities.TransitionVector");
2281 vec.set_attr("name", "enablingVector");
2282 jmt_scalar(vec, "java.lang.String", "stationName", nname(k));
2283 xml::Element& entries = jmt_param_sub(vec, "java.lang.Integer", "enablingEntries");
2284 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2285 const double en = arc(tp.enabling, m, k, r);
2286 jmt_ref_class(entries, cname(r));
2287 xml::Element& e = entries.add_child("subParameter");
2288 e.set_attr("classPath", "java.lang.Integer");
2289 e.set_attr("name", "enablingEntry");
2290 e.add_text_child("value", std::isfinite(en) ? jmt_int(en) : "-1");
2291 }
2292 }
2293 }
2294 }
2295
2296 /**
2297 * Port of `saveInhibitingConditions`.
2298 *
2299 * The vectors cover the transition's INPUT places only, and an infinite
2300 * entry -- "no inhibitor arc" -- is written as 0, which is what JMT reads as
2301 * "never inhibits". Note that the reference's sentinel is inverted between
2302 * the two handlers: infinity is -1 in the enabling block and 0 here.
2303 */
2304 void save_inhibiting_conditions(xml::Element& section, std::size_t ind) {
2305 const qn::TransitionParam<T>& tp = transparam(ind);
2306 std::vector<std::size_t> inputs = inputs_of(ind);
2307 for (const auto& pt : inhibitor_only_arcs()) // places that only inhibit this transition
2308 if (pt.second == ind && std::find(inputs.begin(), inputs.end(), pt.first) == inputs.end())
2309 inputs.push_back(pt.first);
2310 xml::Element& p =
2311 jmt_param(section, "jmt.engine.NetStrategies.TransitionUtilities.TransitionMatrix",
2312 "inhibitingConditions", true);
2313 for (std::size_t m = 0; m < tp.nmodes; ++m) {
2314 xml::Element& cond = p.add_child("subParameter");
2315 cond.set_attr("classPath",
2316 "jmt.engine.NetStrategies.TransitionUtilities.TransitionMatrix");
2317 cond.set_attr("name", "inhibitingCondition");
2318 xml::Element& vecs = jmt_param_sub(
2319 cond, "jmt.engine.NetStrategies.TransitionUtilities.TransitionVector",
2320 "inhibitingVectors");
2321 for (std::size_t k : inputs) {
2322 xml::Element& vec = vecs.add_child("subParameter");
2323 vec.set_attr("classPath",
2324 "jmt.engine.NetStrategies.TransitionUtilities.TransitionVector");
2325 vec.set_attr("name", "inhibitingVector");
2326 jmt_scalar(vec, "java.lang.String", "stationName", nname(k));
2327 xml::Element& entries = jmt_param_sub(vec, "java.lang.Integer", "inhibitingEntries");
2328 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2329 const double in = arc(tp.inhibiting, m, k, r);
2330 jmt_ref_class(entries, cname(r));
2331 xml::Element& e = entries.add_child("subParameter");
2332 e.set_attr("classPath", "java.lang.Integer");
2333 e.set_attr("name", "inhibitingEntry");
2334 e.add_text_child("value", std::isfinite(in) ? jmt_int(in) : "0");
2335 }
2336 }
2337 }
2338 }
2339
2340 /** Port of `saveFiringOutcomes`: the tokens a firing puts in each output. */
2341 void save_firing_outcomes(xml::Element& section, std::size_t ind) {
2342 const qn::TransitionParam<T>& tp = transparam(ind);
2343 const std::vector<std::size_t> outs = outputs_of(ind);
2344 xml::Element& p =
2345 jmt_param(section, "jmt.engine.NetStrategies.TransitionUtilities.TransitionMatrix",
2346 "firingOutcomes", true);
2347 for (std::size_t m = 0; m < tp.nmodes; ++m) {
2348 xml::Element& out = p.add_child("subParameter");
2349 out.set_attr("classPath",
2350 "jmt.engine.NetStrategies.TransitionUtilities.TransitionMatrix");
2351 out.set_attr("name", "firingOutcome");
2352 xml::Element& vecs = jmt_param_sub(
2353 out, "jmt.engine.NetStrategies.TransitionUtilities.TransitionVector",
2354 "firingVectors");
2355 for (std::size_t k : outs) {
2356 xml::Element& vec = vecs.add_child("subParameter");
2357 vec.set_attr("classPath",
2358 "jmt.engine.NetStrategies.TransitionUtilities.TransitionVector");
2359 vec.set_attr("name", "firingVector");
2360 jmt_scalar(vec, "java.lang.String", "stationName", nname(k));
2361 xml::Element& entries = jmt_param_sub(vec, "java.lang.Integer", "firingEntries");
2362 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2363 const double f = arc(tp.firing, m, k, r);
2364 jmt_ref_class(entries, cname(r));
2365 xml::Element& e = entries.add_child("subParameter");
2366 e.set_attr("classPath", "java.lang.Integer");
2367 e.set_attr("name", "firingEntry");
2368 e.add_text_child("value", jmt_int(f));
2369 }
2370 }
2371 }
2372 }
2373
2374 /** `enabling`/`inhibiting`/`firing` of mode m at 1-based node k, class r. */
2375 double arc(const std::vector<Matrix<T>>& tab, std::size_t m, std::size_t k,
2376 std::size_t r) const {
2377 if (m >= tab.size() || k == 0 || k > tab[m].rows() || r == 0 || r > tab[m].cols())
2378 return 0.0;
2379 return d(tab[m](k - 1, r - 1));
2380 }
2381
2382 /** Port of `saveModeNames`. */
2383 void save_mode_names(xml::Element& section, std::size_t ind) {
2384 const qn::TransitionParam<T>& tp = transparam(ind);
2385 xml::Element& p = jmt_param(section, "java.lang.String", "modeNames", true);
2386 for (std::size_t m = 0; m < tp.nmodes; ++m) {
2387 xml::Element& sp = p.add_child("subParameter");
2388 sp.set_attr("classPath", "java.lang.String");
2389 sp.set_attr("name", "modeName");
2390 sp.add_text_child("value", m < tp.modenames.size() ? tp.modenames[m] : std::string());
2391 }
2392 }
2393
2394 /** Port of `saveNumbersOfServers`: the firing concurrency of each mode. */
2395 void save_numbers_of_servers(xml::Element& section, std::size_t ind) {
2396 const qn::TransitionParam<T>& tp = transparam(ind);
2397 xml::Element& p = jmt_param(section, "java.lang.Integer", "numbersOfServers", true);
2398 for (std::size_t m = 0; m < tp.nmodes; ++m) {
2399 const double ns = m < tp.nmodeservers.size() ? tp.nmodeservers[m] : 1.0;
2400 xml::Element& sp = p.add_child("subParameter");
2401 sp.set_attr("classPath", "java.lang.Integer");
2402 sp.set_attr("name", "numberOfServers");
2403 sp.add_text_child("value", std::isfinite(ns) ? jmt_int(ns) : "-1");
2404 }
2405 }
2406
2407 /**
2408 * Port of `saveTimingStrategies`.
2409 *
2410 * An immediate mode is a ZeroServiceTimeStrategy and carries no
2411 * distribution; a timed one carries its firing process through the shared
2412 * emitter, under JMT's `timingStrategy` name rather than the
2413 * `ServiceTimeStrategy` name a queue's service uses.
2414 */
2415 void save_timing_strategies(xml::Element& section, std::size_t ind) {
2416 const qn::TransitionParam<T>& tp = transparam(ind);
2417 xml::Element& p = jmt_param(section, "jmt.engine.NetStrategies.ServiceStrategy",
2418 "timingStrategies", true);
2419 for (std::size_t m = 0; m < tp.nmodes; ++m) {
2420 xml::Element& sp = p.add_child("subParameter");
2421 const bool immediate = m < tp.timing.size() &&
2422 tp.timing[m] == lang::TimingStrategy::IMMEDIATE;
2423 if (immediate) {
2424 sp.set_attr("classPath",
2425 "jmt.engine.NetStrategies.ServiceStrategies.ZeroServiceTimeStrategy");
2426 sp.set_attr("name", "ZeroServiceTimeStrategy");
2427 continue;
2428 }
2429 sp.set_attr("classPath",
2430 "jmt.engine.NetStrategies.ServiceStrategies.ServiceTimeStrategy");
2431 sp.set_attr("name", "timingStrategy");
2432 if (m >= tp.firingproc.size())
2433 throw InputError("SolverJMT: timed mode '" +
2434 (m < tp.modenames.size() ? tp.modenames[m] : std::string()) +
2435 "' of transition '" + nname(ind) + "' has no firing process");
2436 jmt_append_distribution(sp, jmt_dist_view(tp.firingproc[m]),
2437 "SolverJMT (transition firing)");
2438 }
2439 }
2440
2441 /** Port of `saveFiringPriorities`. */
2442 void save_firing_priorities(xml::Element& section, std::size_t ind) {
2443 const qn::TransitionParam<T>& tp = transparam(ind);
2444 xml::Element& p = jmt_param(section, "java.lang.Integer", "firingPriorities", true);
2445 for (std::size_t m = 0; m < tp.nmodes; ++m) {
2446 const double v = m < tp.firingprio.size() ? tp.firingprio[m] : 1.0;
2447 xml::Element& sp = p.add_child("subParameter");
2448 sp.set_attr("classPath", "java.lang.Integer");
2449 sp.set_attr("name", "firingPriority");
2450 sp.add_text_child("value", std::isfinite(v) ? jmt_int(v) : "-1");
2451 }
2452 }
2453
2454 /**
2455 * Port of `saveFiringWeights`.
2456 *
2457 * THE REFERENCE PRINTS THE WEIGHT AS AN INTEGER (`int2str`) although the
2458 * parameter is a `java.lang.Double`, so a weight of 0.3 exports as 0 and
2459 * the mode never wins a race it should sometimes win. That is a defect and
2460 * not a convention -- no other weight in the file is rounded -- so this
2461 * port writes the weight itself.
2462 */
2463 void save_firing_weights(xml::Element& section, std::size_t ind) {
2464 const qn::TransitionParam<T>& tp = transparam(ind);
2465 xml::Element& p = jmt_param(section, "java.lang.Double", "firingWeights", true);
2466 for (std::size_t m = 0; m < tp.nmodes; ++m) {
2467 const double v = m < tp.fireweight.size() ? d(tp.fireweight[m]) : 1.0;
2468 xml::Element& sp = p.add_child("subParameter");
2469 sp.set_attr("classPath", "java.lang.Double");
2470 sp.set_attr("name", "firingWeight");
2471 sp.add_text_child("value", std::isfinite(v) ? jmt_fmt(v) : "-1");
2472 }
2473 }
2474
2475 // -- blocking regions ---------------------------------------------------
2476
2477 /**
2478 * Port of `jmtClassCapCon`: the per-(station, class) capacities that are a
2479 * REAL constraint and must therefore reach JMT as a blocking region.
2480 *
2481 * A capacity is real only when it binds: not at a Source or a Place, not on
2482 * a pair the class never visits, and not when it already exceeds the
2483 * station's own capacity or the population of the class's chain -- such a
2484 * bound can never be reached, and exporting it as a region would add a
2485 * region JMT then reports measures for.
2486 */
2487 std::vector<std::vector<double>> class_cap_constraints() const {
2488 const double inf = std::numeric_limits<double>::infinity();
2489 std::vector<std::vector<double>> con(sn_.nstations, std::vector<double>(sn_.nclasses, inf));
2490 if (sn_.classcap.empty()) return con;
2491 std::vector<double> chainpop(sn_.nclasses, inf);
2492 for (std::size_t c = 0; c < sn_.inchain.size(); ++c) {
2493 double tot = 0.0;
2494 bool open = false;
2495 for (std::size_t r : sn_.inchain[c]) {
2496 const double n = sn_.classes[r - 1].population;
2497 if (std::isfinite(n)) tot += n; else open = true;
2498 }
2499 for (std::size_t r : sn_.inchain[c]) chainpop[r - 1] = open ? inf : tot;
2500 }
2501 for (std::size_t ist = 1; ist <= sn_.nstations; ++ist) {
2502 const NodeType ty = sn_.nodes[sn_.station_to_node[ist - 1] - 1].nodetype;
2503 if (ty == NodeType::Source || ty == NodeType::Place) continue;
2504 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2505 if (sn_.disabled[ist - 1][r - 1]) continue;
2506 const double cc = sn_.classcap[ist - 1][r - 1];
2507 if (std::isfinite(cc) && cc < 2147483647.0 &&
2508 cc < std::min(sn_.cap[ist - 1], chainpop[r - 1]))
2509 con[ist - 1][r - 1] = cc;
2510 }
2511 }
2512 return con;
2513 }
2514
2515 /**
2516 * Port of `jmtClassCapAssert`: the two per-class capacities JMT cannot
2517 * reproduce, refused by name rather than exported as something else.
2518 *
2519 * A CLOSED class is the first. LINE holds a blocked closed job at its
2520 * upstream station; JMT's blocking region parks it in the region's input
2521 * station instead, which frees the upstream server and loses the job from
2522 * the population count -- a different model, not a different rounding.
2523 * A non-loss drop strategy is the second: a region can only drop or defer.
2524 */
2525 void assert_class_cap_exportable(std::size_t ist, std::size_t r) const {
2526 const std::string sname = nname(sn_.station_to_node[ist - 1]);
2527 if (std::isfinite(sn_.classes[r - 1].population))
2528 throw UnsupportedError(ErrorKind{"FiniteCapacity"},
2529 "SolverJMT: station '" + sname + "' carries a finite capacity " +
2530 jmt_int(sn_.classcap[ist - 1][r - 1]) + " for the closed class '" + cname(r) +
2531 "'. LINE holds a blocked closed job at its upstream station, whereas JMT can "
2532 "only express a per-class capacity as a blocking region, which parks the job in "
2533 "the region input station instead, freeing the upstream server and losing it "
2534 "from the population count. Use SolverCTMC, SolverSSA or SolverLDES, or express "
2535 "the limit as the station capacity");
2536 const DropStrategy dr = sn_.droprule[ist - 1][r - 1];
2537 if (dr == DropStrategy::BAS || dr == DropStrategy::BBS || dr == DropStrategy::RSRD ||
2538 dr == DropStrategy::RETRIAL || dr == DropStrategy::RETRIAL_WITH_LIMIT)
2539 throw UnsupportedError(ErrorKind{"FiniteCapacity"},
2540 "SolverJMT: station '" + sname + "' applies drop strategy '" + jmt_drop_text(dr) +
2541 "' to class '" + cname(r) +
2542 "' and also carries a finite capacity for it. JMT exports a per-class capacity "
2543 "as a blocking region, which can only drop or defer an arrival. Remove the "
2544 "per-class capacity, or use the station capacity, which is exported with its "
2545 "drop strategy");
2546 }
2547
2548 /**
2549 * Port of `saveRegions`: three kinds of `<blockingRegion>`, in this order.
2550 *
2551 * 1. ONE PER LPS STATION. Limited processor sharing is a cap on the number
2552 * IN SERVICE, which JMT has no station-level field for; the single-node
2553 * region is how the limit is expressed, and it is why
2554 * `save_number_of_servers` exports an LPS station as a single server.
2555 * 2. The model's declared finite capacity regions.
2556 * 3. ONE PER STATION whose per-class capacity is a real constraint and that
2557 * no region above already covers, since JMT allows a node to belong to
2558 * at most one region.
2559 */
2560 void save_regions(xml::Element& sim) {
2561 const std::vector<std::vector<double>> con = class_cap_constraints();
2562 std::vector<bool> covered(sn_.nstations, false);
2563 std::size_t lps_idx = sn_.regions.size();
2564
2565 for (std::size_t ist = 1; ist <= sn_.nstations; ++ist) {
2566 if (sn_.stations[ist - 1].sched != SchedStrategy::LPS) continue;
2567 ++lps_idx;
2568 const std::size_t ind = sn_.station_to_node[ist - 1];
2569 const double limit = sn_.stations[ist - 1].schedparam.empty()
2570 ? 1.0
2571 : d(sn_.stations[ist - 1].schedparam[0]);
2572 xml::Element& br = sim.add_child("blockingRegion");
2573 br.set_attr("name", "LPSRegion" + jmt_int(static_cast<double>(lps_idx)));
2574 br.set_attr("type", "default");
2575 br.add_child("regionNode").set_attr("nodeName", nname(ind));
2576 br.add_child("globalConstraint").set_attr("maxJobs", jmt_num(limit));
2577 br.add_child("globalMemoryConstraint").set_attr("maxMemory", "-1");
2578 covered[ist - 1] = true;
2579 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2580 if (!std::isfinite(con[ist - 1][r - 1])) continue;
2581 assert_class_cap_exportable(ist, r); // rejects the non-loss cases first
2582 throw UnsupportedError(ErrorKind{"FiniteCapacity"},
2583 "SolverJMT: station '" + nname(ind) +
2584 "' has both LPS scheduling and a finite capacity for the open class '" +
2585 cname(r) +
2586 "'. JMT expresses both through a single blocking region, which admits only "
2587 "one drop rule per class, but LPS requires blocking while the open-class "
2588 "capacity requires dropping. Remove the per-class capacity or use a non-LPS "
2589 "scheduling strategy");
2590 }
2591 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2592 xml::Element& dr = br.add_child("dropRules");
2593 dr.set_attr("jobClass", cname(r));
2594 dr.set_attr("dropThisClass", "false");
2595 }
2596 }
2597
2598 for (std::size_t f = 1; f <= sn_.regions.size(); ++f) {
2599 const typename qn::NetworkStruct<T>::Region& rg = sn_.regions[f - 1];
2600 std::vector<std::size_t> members;
2601 for (std::size_t ist = 1; ist <= sn_.nstations; ++ist)
2602 if (ist <= rg.members.size() && rg.members[ist - 1]) {
2603 members.push_back(ist);
2604 covered[ist - 1] = true;
2605 }
2606 std::vector<double> region_class_cap(sn_.nclasses,
2607 std::numeric_limits<double>::infinity());
2608 for (std::size_t ist : members)
2609 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2610 if (!std::isfinite(con[ist - 1][r - 1])) continue;
2611 if (members.size() > 1)
2612 throw UnsupportedError(ErrorKind{"Region"},
2613 "SolverJMT: station '" + nname(sn_.station_to_node[ist - 1]) +
2614 "' carries a finite capacity for class '" + cname(r) +
2615 "' and also belongs to the multi-station region FCRegion" +
2616 jmt_int(static_cast<double>(f)) +
2617 ". JMT constrains a blocking region as a whole and allows a node to "
2618 "belong to only one region, so a per-station class capacity cannot "
2619 "be expressed alongside it");
2620 assert_class_cap_exportable(ist, r);
2621 if (!(r <= rg.rule.size() && rg.rule[r - 1] == DropStrategy::DROP))
2622 throw UnsupportedError(ErrorKind{"Region"},
2623 "SolverJMT: station '" + nname(sn_.station_to_node[ist - 1]) +
2624 "' carries a finite capacity for class '" + cname(r) +
2625 "' and also belongs to region FCRegion" +
2626 jmt_int(static_cast<double>(f)) +
2627 ", whose drop rule for that class is not DROP. A JMT blocking "
2628 "region admits a single drop rule per class, shared by all of its "
2629 "constraints, and the per-class capacity of an open class is a loss "
2630 "constraint");
2631 region_class_cap[r - 1] = con[ist - 1][r - 1];
2632 }
2633
2634 xml::Element& br = sim.add_child("blockingRegion");
2635 br.set_attr("name", "FCRegion" + jmt_int(static_cast<double>(f)));
2636 br.set_attr("type", "default");
2637 for (std::size_t ist : members)
2638 br.add_child("regionNode")
2639 .set_attr("nodeName", nname(sn_.station_to_node[ist - 1]));
2640 // The global caps are stored per MEMBER station and are the same at
2641 // each; the first member therefore carries the region's own values.
2642 const double gmax =
2643 members.empty() ? -1.0 : rg.cap[members[0] - 1][sn_.nclasses];
2644 const double gmem = members.empty() ? -1.0 : rg.maxmem[members[0] - 1];
2645 br.add_child("globalConstraint").set_attr("maxJobs", jmt_num(gmax));
2646 br.add_child("globalMemoryConstraint").set_attr("maxMemory", jmt_num(gmem));
2647 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2648 double cmax = members.empty() ? -1.0 : rg.cap[members[0] - 1][r - 1];
2649 // -1 is the struct's "unbounded"; the per-station capacity then
2650 // stands alone, and otherwise the tighter of the two binds.
2651 if (cmax == -1.0)
2652 cmax = std::isfinite(region_class_cap[r - 1]) ? region_class_cap[r - 1] : -1.0;
2653 else if (std::isfinite(region_class_cap[r - 1]))
2654 cmax = std::min(cmax, region_class_cap[r - 1]);
2655 if (cmax == -1.0 || !std::isfinite(cmax)) continue;
2656 xml::Element& cc = br.add_child("classConstraint");
2657 cc.set_attr("jobClass", cname(r));
2658 cc.set_attr("maxJobsPerClass", jmt_num(cmax));
2659 }
2660 // NO `classMemoryConstraint` IS EMITTED. `add_region` already folds
2661 // the per-class memory budget into the per-class job cap by
2662 // dividing it by the class size, so the constraint above carries it;
2663 // emitting it again would apply the same budget twice.
2664 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2665 xml::Element& dr = br.add_child("dropRules");
2666 dr.set_attr("jobClass", cname(r));
2667 dr.set_attr("dropThisClass",
2668 (r <= rg.rule.size() && rg.rule[r - 1] == DropStrategy::DROP)
2669 ? "true"
2670 : "false");
2671 }
2672 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2673 if (r > rg.weight.size()) continue;
2674 const double w = d(rg.weight[r - 1]);
2675 if (w == 1.0) continue;
2676 xml::Element& cw = br.add_child("classWeight");
2677 cw.set_attr("jobClass", cname(r));
2678 cw.set_attr("weight", jmt_num(w));
2679 }
2680 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2681 if (r > rg.size.size()) continue;
2682 const double s = d(rg.size[r - 1]);
2683 if (s == 1.0) continue;
2684 xml::Element& cs = br.add_child("classSize");
2685 cs.set_attr("jobClass", cname(r));
2686 cs.set_attr("size", jmt_num(s));
2687 }
2688 }
2689
2690 std::size_t cap_idx = 0;
2691 for (std::size_t ist = 1; ist <= sn_.nstations; ++ist) {
2692 if (covered[ist - 1]) continue;
2693 bool any = false;
2694 for (std::size_t r = 1; r <= sn_.nclasses; ++r)
2695 if (std::isfinite(con[ist - 1][r - 1])) any = true;
2696 if (!any) continue;
2697 ++cap_idx;
2698 for (std::size_t r = 1; r <= sn_.nclasses; ++r)
2699 if (std::isfinite(con[ist - 1][r - 1])) assert_class_cap_exportable(ist, r);
2700 xml::Element& br = sim.add_child("blockingRegion");
2701 br.set_attr("name", "ClassCapRegion" + jmt_int(static_cast<double>(cap_idx)));
2702 br.set_attr("type", "default");
2703 br.add_child("regionNode")
2704 .set_attr("nodeName", nname(sn_.station_to_node[ist - 1]));
2705 br.add_child("globalConstraint").set_attr("maxJobs", "-1");
2706 br.add_child("globalMemoryConstraint").set_attr("maxMemory", "-1");
2707 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2708 if (!std::isfinite(con[ist - 1][r - 1])) continue;
2709 xml::Element& cc = br.add_child("classConstraint");
2710 cc.set_attr("jobClass", cname(r));
2711 cc.set_attr("maxJobsPerClass", jmt_num(con[ist - 1][r - 1]));
2712 }
2713 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
2714 if (!std::isfinite(con[ist - 1][r - 1])) continue;
2715 xml::Element& dr = br.add_child("dropRules");
2716 dr.set_attr("jobClass", cname(r));
2717 dr.set_attr("dropThisClass", "true");
2718 }
2719 }
2720 }
2721
2722 // -- Cache --------------------------------------------------------------
2723
2724 /**
2725 * Port of `saveCacheStrategy`.
2726 *
2727 * THE LIST-TO-LIST MATRIX IS READ FROM THE ACCESS GRAPH (`accost`) FOR EVERY
2728 * POLICY (`cache_jmt_promotion`), as the reference does since 2026-10-16. The
2729 * old identity for every non-LRU policy pinned an RR or FIFO hit to its list,
2730 * so RR(1,2) never promoted anything (JMT hit ratio 0.20 against CTMC 0.60).
2731 * Each row is written as its CUMULATIVE distribution: JMT draws u ~ U(0,1)
2732 * and takes the first list l2 with u < cell(l1,l2).
2733 *
2734 * FIFO AND SFIFO ARE EXACT IN JMT ONLY WHEN EVERY LIST AN ITEM CAN STAY IN HAS
2735 * CAPACITY 1: JMT re-appends a hit item at the tail of the list it stays in
2736 * (removeItemMode 0), which is LRU order, so FIFO on one list of capacity 2
2737 * reads LRU's hit ratio exactly. Anything else is refused by name.
2738 *
2739 * SFIFO is exported as JMT's FIFO cache and every policy JMT has no object
2740 * for -- HLRU, CLIMB, QLRU -- is refused by name rather than falling back
2741 * to LRU as the reference's `otherwise` does: a q-LRU cache silently
2742 * simulated as LRU returns a hit rate that is wrong by the admission
2743 * probability, with nothing in the output to show for it.
2744 */
2745 void save_cache_strategy(xml::Element& section, std::size_t ind) {
2746 const auto it = sn_.nodeparam.find(ind);
2747 if (it == sn_.nodeparam.end())
2748 throw InputError("SolverJMT: cache node '" + nname(ind) + "' carries no parameters");
2749 const qn::CacheParam<T>& cp = it->second;
2750 const std::size_t K = sn_.nclasses;
2751 {
2752 const std::string why = cache_refusal(ind);
2753 if (!why.empty()) throw UnsupportedError(ErrorKind{"Cache"}, why);
2754 }
2755
2756 jmt_param_value(section, "java.lang.Integer", "maxItems",
2757 jmt_int(static_cast<double>(cp.nitems)));
2758 xml::Element& cap = jmt_param(section, "java.lang.Integer", "cacheCapacity", true);
2759 for (std::size_t l = 0; l < cp.itemcap.size(); ++l) {
2760 xml::Element& sp = cap.add_child("subParameter");
2761 sp.set_attr("classPath", "java.lang.Integer");
2762 sp.set_attr("name", "capacity");
2763 sp.add_text_child("value", jmt_int(static_cast<double>(cp.itemcap[l])));
2764 }
2765
2766 const std::size_t nlev = cp.itemcap.size();
2767 std::vector<std::size_t> readers; // 0-based classes that read this cache
2768 for (std::size_t r = 0; r < K; ++r)
2769 if ((r < cp.hitclass.size() && cp.hitclass[r] > 0) ||
2770 (r < cp.missclass.size() && cp.missclass[r] > 0))
2771 readers.push_back(r);
2772 const std::vector<std::vector<double>> promo = cache_jmt_promotion(cp, nlev, readers, ind);
2773 xml::Element& mat = jmt_param(section, "java.lang.Object", "matrix", true);
2774 for (std::size_t a = 0; a < nlev; ++a) {
2775 xml::Element& row = mat.add_child("subParameter");
2776 row.set_attr("array", "true");
2777 row.set_attr("classPath", "java.lang.Float");
2778 row.set_attr("name", "row");
2779 double cum = 0.0;
2780 for (std::size_t b = 0; b < nlev; ++b) {
2781 cum = std::min(cum + promo[a][b], 1.0);
2782 xml::Element& cell = row.add_child("subParameter");
2783 cell.set_attr("classPath", "java.lang.Float");
2784 cell.set_attr("name", "cell");
2785 char buf[32];
2786 std::snprintf(buf, sizeof(buf), "%.12g", cum);
2787 cell.add_text_child("value", buf);
2788 }
2789 }
2790
2791 xml::Element& jc = jmt_param(section, "jmt.engine.QueueNet.JobClass", "jobClasses", true);
2792 for (std::size_t r = 1; r <= K; ++r) {
2793 const bool used = (r <= cp.hitclass.size() && cp.hitclass[r - 1] > 0) ||
2794 (r <= cp.missclass.size() && cp.missclass[r - 1] > 0);
2795 if (!used) continue;
2796 xml::Element& sp = jc.add_child("subParameter");
2797 sp.set_attr("classPath", "jmt.engine.QueueNet.JobClass");
2798 sp.set_attr("name", "jobClass");
2799 sp.add_text_child("value", cname(r));
2800 }
2801 const char* switch_names[2] = {"hitClasses", "missClasses"};
2802 const char* entry_names[2] = {"hitClass", "missClass"};
2803 for (int w = 0; w < 2; ++w) {
2804 const std::vector<std::size_t>& tab = w == 0 ? cp.hitclass : cp.missclass;
2805 xml::Element& p =
2806 jmt_param(section, "jmt.engine.QueueNet.JobClass", switch_names[w], true);
2807 for (std::size_t r = 1; r <= K && r <= tab.size(); ++r) {
2808 if (tab[r - 1] == 0) continue;
2809 xml::Element& sp = p.add_child("subParameter");
2810 sp.set_attr("classPath", "jmt.engine.QueueNet.JobClass");
2811 sp.set_attr("name", entry_names[w]);
2812 sp.add_text_child("value", cname(tab[r - 1]));
2813 }
2814 }
2815
2816 const char* policy = nullptr;
2817 switch (cp.replacestrat) {
2819 policy = "jmt.engine.NetStrategies.CacheStrategies.LRUCache";
2820 break;
2823 policy = "jmt.engine.NetStrategies.CacheStrategies.FIFOCache";
2824 break;
2826 policy = "jmt.engine.NetStrategies.CacheStrategies.RandomCache";
2827 break;
2828 default: // HLRU, CLIMB, QLRU: cache_refusal raised it above
2829 throw UnsupportedError(ErrorKind{"Cache"}, cache_refusal(ind));
2830 }
2831 xml::Element& rp = section.add_child("parameter");
2832 rp.set_attr("classPath", policy);
2833 rp.set_attr("name", "replacePolicy");
2834
2835 /*
2836 * The popularity is PARAMETRIC in JMT: a Zipf exponent or a uniform
2837 * range, never a pmf. `CacheParam::preadkind` is what the reader kept
2838 * for exactly this, and a class whose pmf was supplied directly exports
2839 * as `null` -- the reference's own behaviour for anything that is not a
2840 * Zipf or a DiscreteSampler.
2841 */
2842 xml::Element& pop = jmt_param(
2843 section, "jmt.engine.random.discrete.DiscreteDistribution", "popularity", true);
2844 for (std::size_t r = 1; r <= K; ++r) {
2845 jmt_ref_class(pop, cname(r));
2846 const bool reads = r <= cp.pread.size() && !cp.pread[r - 1].empty();
2847 const typename qn::CacheParam<T>::Popularity kind =
2848 r <= cp.preadkind.size() ? cp.preadkind[r - 1]
2849 : typename qn::CacheParam<T>::Popularity();
2850 xml::Element& sp = pop.add_child("subParameter");
2851 if (reads && kind.type == lang::ProcessType::ZIPF) {
2852 sp.set_attr("classPath", "jmt.engine.random.discrete.Zipf");
2853 sp.set_attr("name", "popularity");
2854 jmt_scalar(sp, "java.lang.Double", "alpha", jmt_fmt(kind.s));
2855 jmt_scalar(sp, "java.lang.Integer", "numberOfElements",
2856 jmt_int(static_cast<double>(kind.n)));
2857 } else if (reads && kind.type == lang::ProcessType::DISCRETESAMPLER) {
2858 // Uniform is the one DiscreteSampler JMT reproduces exactly; cache_refusal refused any other pmf.
2859 sp.set_attr("classPath", "jmt.engine.random.discrete.Uniform");
2860 sp.set_attr("name", "popularity");
2861 jmt_scalar(sp, "java.lang.Integer", "min", "1");
2862 jmt_scalar(sp, "java.lang.Integer", "max",
2863 jmt_int(static_cast<double>(kind.n == 0 ? cp.nitems : kind.n)));
2864 } else if (reads) { // neither Zipf nor uniform: cache_refusal raised it above
2865 throw UnsupportedError(ErrorKind{"Cache"}, cache_refusal(ind));
2866 } else {
2867 sp.set_attr("classPath", "jmt.engine.random.discrete.DiscreteDistribution");
2868 sp.set_attr("name", "null");
2869 sp.add_text_child("value", "null");
2870 }
2871 }
2872 }
2873
2874 /**
2875 * Port of `cacheJmtPromotionMatrix`: the list-to-list promotion pmf on a hit.
2876 *
2877 * `accost[v][k]` is (h+1)x(h+1), row 0 the miss insertion and row l the move of a
2878 * hit in list l. JMT has ONE matrix for all classes and items, always inserts a miss
2879 * into list 1 and cannot demote an item out of the cache, so a graph is exported only
2880 * when it agrees across the reading classes and items and respects both. An absent
2881 * graph is the linear chain l -> l+1, the last list keeping its item, for every policy
2882 * (RR and FIFO swap the promoted item with a victim of the list above, JMT's
2883 * removeItemMode 0). A zero row keeps the item where it is.
2884 */
2885 std::vector<std::vector<double>> cache_jmt_promotion(const qn::CacheParam<T>& cp,
2886 std::size_t h,
2887 const std::vector<std::size_t>& readers,
2888 std::size_t ind) const {
2889 std::vector<std::vector<double>> P;
2890 const std::string why = cache_jmt_promotion_reason(cp, h, readers, ind, P);
2891 if (!why.empty()) throw UnsupportedError(ErrorKind{"Cache"}, why);
2892 return P;
2893 }
2894
2895 public:
2896 /**
2897 * Everything `save_cache_strategy` refuses for cache node `ind`, as a SENTENCE; empty when JMT
2898 * reproduces the cache (MATLAB `jmtCachePromotion`, shared by `saveCacheStrategy` and
2899 * `jmtMethodRefusal`).
2900 *
2901 * ONE PREDICATE, TWO CALLERS: the writer raises it, and `jmt::jmt_method_refusal` returns it through
2902 * `jmt_cache_refusal`, so the supports check and findSolver refuse a FIFO list of capacity 2 that the
2903 * writer would refuse at run time instead of offering `jmt.jsim` on it. Unlike MATLAB, this port
2904 * keeps the popularity KIND on the struct (`CacheParam::preadkind`), so the popularity rules are
2905 * visible to the gate as well.
2906 */
2907 std::string cache_refusal(std::size_t ind) const {
2908 const auto it = sn_.nodeparam.find(ind);
2909 if (it == sn_.nodeparam.end()) return "SolverJMT: cache node '" + nname(ind) + "' carries no parameters";
2910 const qn::CacheParam<T>& cp = it->second;
2911 const std::size_t K = sn_.nclasses;
2914 return "SolverJMT: cache '" + nname(ind) +
2915 "' uses a replacement policy JMT has no cache object for (HLRU, CLIMB and "
2916 "QLRU); use SolverLDES, which simulates them directly";
2917 const std::size_t nlev = cp.itemcap.size();
2918 std::vector<std::size_t> readers; // 0-based classes that read this cache
2919 for (std::size_t r = 0; r < K; ++r)
2920 if ((r < cp.hitclass.size() && cp.hitclass[r] > 0) ||
2921 (r < cp.missclass.size() && cp.missclass[r] > 0))
2922 readers.push_back(r);
2923 std::vector<std::vector<double>> promo;
2924 {
2925 const std::string why = cache_jmt_promotion_reason(cp, nlev, readers, ind, promo);
2926 if (!why.empty()) return why;
2927 }
2930 for (std::size_t l = 0; l < nlev; ++l) {
2931 if (promo[l][l] > 0.0 && cp.itemcap[l] > 1)
2932 return "SolverJMT: cache '" + nname(ind) + "' uses " +
2933 std::string(cp.replacestrat == lang::ReplacementStrategy::SFIFO ? "SFIFO" : "FIFO") +
2934 " replacement, but JMT moves an item hit in list " + std::to_string(l + 1) +
2935 " (capacity " + std::to_string(cp.itemcap[l]) +
2936 ") to the tail of that list, which is LRU order: the simulation would solve a "
2937 "different policy. JMT is exact for FIFO only when every list an item can stay "
2938 "in has capacity 1. Use SSA, LDES or CTMC.";
2939 }
2940 }
2941 // The popularity is PARAMETRIC in JMT, a Zipf exponent or a uniform range, never a pmf.
2942 for (std::size_t r = 1; r <= K; ++r) {
2943 const bool reads = r <= cp.pread.size() && !cp.pread[r - 1].empty();
2944 if (!reads) continue;
2945 const typename qn::CacheParam<T>::Popularity kind =
2946 r <= cp.preadkind.size() ? cp.preadkind[r - 1] : typename qn::CacheParam<T>::Popularity();
2947 if (kind.type == lang::ProcessType::ZIPF) continue;
2949 const auto& pm = cp.pread[r - 1];
2950 double psum = 0.0;
2951 for (const auto& v : pm) psum += static_cast<double>(v);
2952 for (const auto& v : pm)
2953 if (std::abs(static_cast<double>(v) / psum - 1.0 / static_cast<double>(pm.size())) > 1e-3)
2954 return "SolverJMT: cache '" + nname(ind) + "' gives class '" + cname(r) +
2955 "' a non-uniform DiscreteSampler popularity, which JMT cannot express: its Cache "
2956 "section takes a parametric popularity (Zipf or uniform) and has no empirical "
2957 "discrete form, so this would be exported as a uniform draw over all " +
2958 std::to_string(cp.nitems) + " items and solved as a different model. Use Zipf, "
2959 "a uniform popularity, or a solver other than JMT (SSA, LDES, CTMC, MVA, NC all take it).";
2960 continue;
2961 }
2962 // A null popularity on a class that READS makes JMT abort mid-run ("Cannot find the
2963 // corresponding DiscreteDistribution popularity"), and JMT has no generic empirical law.
2964 return "SolverJMT: cache '" + nname(ind) + "' gives class '" + cname(r) +
2965 "' a popularity that is neither Zipf nor uniform; the JMT Cache section takes Zipf "
2966 "or a uniform popularity only. Use SSA, LDES, CTMC, MVA or NC.";
2967 }
2968 return std::string();
2969 }
2970
2971 private:
2972 /** `cache_jmt_promotion` returning its refusal as a sentence (empty when exportable), the matrix in `P`. */
2973 std::string cache_jmt_promotion_reason(const qn::CacheParam<T>& cp, std::size_t h,
2974 const std::vector<std::size_t>& readers, std::size_t ind,
2975 std::vector<std::vector<double>>& P) const {
2976 const double tol = 1e-8; // GlobalConstants.FineTol
2977 std::vector<std::vector<double>> ref;
2978 for (const std::size_t r : readers) {
2979 if (r >= cp.accost.size()) continue;
2980 for (std::size_t k = 0; k < cp.nitems && k < cp.accost[r].size(); ++k) {
2981 const Matrix<T>& M = cp.accost[r][k];
2982 if (M.empty()) continue;
2983 std::vector<std::vector<double>> dm(M.rows(), std::vector<double>(M.cols(), 0.0));
2984 for (std::size_t a = 0; a < M.rows(); ++a)
2985 for (std::size_t b = 0; b < M.cols(); ++b) dm[a][b] = static_cast<double>(M(a, b));
2986 if (ref.empty()) {
2987 ref = dm;
2988 continue;
2989 }
2990 bool same = dm.size() == ref.size() && dm[0].size() == ref[0].size();
2991 for (std::size_t a = 0; same && a < dm.size(); ++a)
2992 for (std::size_t b = 0; same && b < dm[a].size(); ++b)
2993 if (std::abs(dm[a][b] - ref[a][b]) > tol) same = false;
2994 if (!same)
2995 return "SolverJMT: cache '" + nname(ind) + "' has an access graph that differs across "
2996 "classes or items; the JMT Cache section takes one list-promotion matrix for all "
2997 "of them. Use SSA, LDES or CTMC.";
2998 }
2999 }
3000 P.assign(h, std::vector<double>(h, 0.0));
3001 if (ref.empty()) {
3002 for (std::size_t l = 0; l < h; ++l) P[l][std::min(l + 1, h - 1)] = 1.0;
3003 return std::string();
3004 }
3005 if (ref.size() != h + 1 || ref[0].size() != h + 1)
3006 return "SolverJMT: cache '" + nname(ind) + "' has a " + std::to_string(ref.size()) + "x" +
3007 std::to_string(ref[0].size()) + " access graph for " + std::to_string(h) +
3008 " lists; expected " + std::to_string(h + 1) + "x" + std::to_string(h + 1) + ".";
3009 double ins_sum = 0.0;
3010 for (std::size_t b = 1; b <= h; ++b) ins_sum += ref[0][b];
3011 if (ref[0][0] > 0.0 || std::abs(ins_sum - 1.0) > tol || std::abs(ref[0][1] - 1.0) > tol)
3012 return "SolverJMT: cache '" + nname(ind) + "' inserts a missed item somewhere other than "
3013 "list 1; JMT always inserts a miss into the first list. Use SSA, LDES or CTMC.";
3014 for (std::size_t l = 1; l <= h; ++l) {
3015 if (ref[l][0] > 0.0)
3016 return "SolverJMT: cache '" + nname(ind) + "' demotes a hit in list " + std::to_string(l) +
3017 " out of the cache; the JMT Cache section has no such move. Use SSA, LDES or CTMC.";
3018 double tot = 0.0;
3019 for (std::size_t b = 1; b <= h; ++b) tot += ref[l][b];
3020 if (tot <= 0.0) {
3021 P[l - 1][l - 1] = 1.0;
3022 } else {
3023 for (std::size_t b = 1; b <= h; ++b) P[l - 1][b - 1] = ref[l][b] / tot;
3024 }
3025 }
3026 return std::string();
3027 }
3028
3029 // -- impatience, retrials and switchover --------------------------------
3030
3031 /**
3032 * Port of `saveImpatience`: the per-class Balking or Reneging strategy.
3033 *
3034 * BALKING AND RENEGING ARE MUTUALLY EXCLUSIVE per class here, as in the
3035 * reference: JMT's Impatience array holds one strategy per class, and
3036 * balking is checked first. A class with neither gets a Reneging strategy
3037 * whose body is the literal `null`.
3038 */
3039 void save_impatience(xml::Element& section, std::size_t ind) {
3040 const std::size_t ist = sn_.nodes[ind - 1].station;
3041 xml::Element& p = jmt_param(
3042 section, "jmt.engine.NetStrategies.ImpatienceStrategies.Impatience", "Impatience", true);
3043 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
3044 if (!keep_[r - 1]) continue;
3045 jmt_ref_class(p, cname(r));
3046 xml::Element& sp = p.add_child("subParameter");
3047 const qn::Station<T>* st = ist == 0 ? nullptr : &sn_.stations[ist - 1];
3048 const bool balks = st != nullptr && r <= st->balking.size() &&
3049 st->balking[r - 1].strategy ==
3051 if (balks) {
3052 sp.set_attr("classPath", "jmt.engine.NetStrategies.ImpatienceStrategies.Balking");
3053 sp.set_attr("name", "Balking");
3054 save_balking_strategy(sp, st->balking[r - 1].thresholds, st->nservers);
3055 continue;
3056 }
3057 sp.set_attr("classPath", "jmt.engine.NetStrategies.ImpatienceStrategies.Reneging");
3058 sp.set_attr("name", "Reneging");
3059 const bool renegs = st != nullptr && r <= st->impatience.size() &&
3060 st->impatience[r - 1] == lang::ImpatienceType::RENEGING &&
3061 r <= st->patience.size() && !st->patience[r - 1].disabled;
3062 if (!renegs) {
3063 sp.add_text_child("value", "null");
3064 continue;
3065 }
3066 const JmtDistView<T> v = jmt_dist_view(st->patience[r - 1]);
3067 if (v.type == lang::ProcessType::UNIFORM) {
3068 // The reference exports a patience Uniform as [0, 2*mean],
3069 // matching the MEAN only, where the service-time emitter
3070 // matches the mean and the SCV. Kept: a patience law is
3071 // declared by its mean in every model that has one.
3072 xml::Element& dn = sp.add_child("subParameter");
3073 dn.set_attr("classPath", "jmt.engine.random.Uniform");
3074 dn.set_attr("name", "Uniform");
3075 xml::Element& par = sp.add_child("subParameter");
3076 par.set_attr("classPath", "jmt.engine.random.UniformPar");
3077 par.set_attr("name", "distrPar");
3078 jmt_scalar(par, "java.lang.Double", "min", "0.0");
3079 jmt_double(par, "max", v.rate > 0.0 ? 2.0 / v.rate : 0.0);
3080 continue;
3081 }
3082 jmt_append_distribution(sp, v, "SolverJMT (patience)");
3083 }
3084 }
3085
3086 /**
3087 * Port of `saveBalkingStrategy`.
3088 *
3089 * THE THRESHOLDS ARE SHIFTED DOWN BY THE SERVER COUNT. LINE evaluates
3090 * balking against the TOTAL station population, JMT's Balking against the
3091 * number WAITING; in the regime where balking matters the servers are busy,
3092 * so the two differ by exactly S and JMT waiting w is LINE total w + S.
3093 * A gap between two intervals gets an explicit zero-probability breakpoint,
3094 * since JMT selects the LAST range with `from <= queueLength` and would
3095 * otherwise let a queue length outside every interval inherit its
3096 * neighbour's balking probability.
3097 */
3098 void save_balking_strategy(xml::Element& balking,
3099 const std::vector<typename qn::Station<T>::BalkingThreshold>& th,
3100 double nservers) {
3101 struct Bp {
3102 double from, prob;
3103 };
3104 std::vector<typename qn::Station<T>::BalkingThreshold> sorted = th;
3105 std::sort(sorted.begin(), sorted.end(),
3106 [](const typename qn::Station<T>::BalkingThreshold& a,
3107 const typename qn::Station<T>::BalkingThreshold& b) {
3108 return a.min_jobs < b.min_jobs;
3109 });
3110 const double S =
3111 (!std::isfinite(nservers) || nservers < 1.0) ? 1.0 : nservers;
3112 std::vector<Bp> bps;
3113 for (std::size_t i = 0; i < sorted.size(); ++i) {
3114 const double lo = sorted[i].min_jobs;
3115 // -1 is the wire's unbounded upper end; every other value is a
3116 // closed interval, which is why the gap test below is `hi + 1`.
3117 const double hi = sorted[i].max_jobs < 0.0
3118 ? std::numeric_limits<double>::infinity()
3119 : sorted[i].max_jobs;
3120 const double pr = d(sorted[i].probability);
3121 bps.push_back(Bp{std::max(0.0, lo - S), pr});
3122 if (!std::isfinite(hi)) continue;
3123 const double next_lo = i + 1 < sorted.size()
3124 ? sorted[i + 1].min_jobs
3125 : std::numeric_limits<double>::infinity();
3126 if (hi + 1.0 < next_lo) bps.push_back(Bp{std::max(0.0, hi + 1.0 - S), 0.0});
3127 }
3128 xml::Element& ld = balking.add_child("subParameter");
3129 ld.set_attr("classPath", "jmt.engine.NetStrategies.ServiceStrategies.LoadDependentStrategy");
3130 ld.set_attr("name", "LoadDependentStrategy");
3131 xml::Element& arr = jmt_param_sub(
3132 ld, "jmt.engine.NetStrategies.ServiceStrategies.LDParameter", "LDParameter");
3133 for (const Bp& b : bps) {
3134 xml::Element& rn = arr.add_child("subParameter");
3135 rn.set_attr("classPath", "jmt.engine.NetStrategies.ServiceStrategies.LDParameter");
3136 rn.set_attr("name", "LDParameter");
3137 jmt_scalar(rn, "java.lang.Integer", "from", jmt_int(b.from));
3138 // A DUMMY distribution: only the `function` string below is read
3139 // for balking, but the LDParameter shape requires the pair.
3140 xml::Element& dn = rn.add_child("subParameter");
3141 dn.set_attr("classPath", "jmt.engine.random.Exponential");
3142 dn.set_attr("name", "Exponential");
3143 xml::Element& par = rn.add_child("subParameter");
3144 par.set_attr("classPath", "jmt.engine.random.ExponentialPar");
3145 par.set_attr("name", "distrPar");
3146 jmt_scalar(par, "java.lang.Double", "lambda", "1.0");
3147 jmt_scalar(rn, "java.lang.String", "function", jmt_fmt(b.prob));
3148 }
3149 jmt_scalar(balking, "java.lang.Boolean", "priorityActivated", "false");
3150 }
3151
3152 /**
3153 * Port of `saveRetrialDistributions`: the orbit delay of each class.
3154 *
3155 * A class with no orbit still gets an entry -- an Exp(1) placeholder -- so
3156 * that JMT's per-class array stays aligned; omitting it would shift every
3157 * later class's retrial delay onto the wrong class.
3158 */
3159 void save_retrial_distributions(xml::Element& section, std::size_t ind) {
3160 const std::size_t ist = sn_.nodes[ind - 1].station;
3161 const auto it = ist == 0 ? sn_.retrialparam.end() : sn_.retrialparam.find(ist);
3162 xml::Element& p = jmt_param(section, "jmt.engine.NetStrategies.ServiceStrategy",
3163 "retrialDistributions", true);
3164 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
3165 if (!keep_[r - 1]) continue;
3166 jmt_ref_class(p, cname(r));
3167 xml::Element& sts = p.add_child("subParameter");
3168 sts.set_attr("classPath",
3169 "jmt.engine.NetStrategies.ServiceStrategies.ServiceTimeStrategy");
3170 sts.set_attr("name", "ServiceTimeStrategy");
3171 const bool has = it != sn_.retrialparam.end() &&
3172 r <= it->second.retrial_proc.size() &&
3173 !it->second.retrial_proc[r - 1].disabled;
3174 if (!has) {
3175 xml::Element& dn = sts.add_child("subParameter");
3176 dn.set_attr("classPath", "jmt.engine.random.Exponential");
3177 dn.set_attr("name", "Exponential");
3178 xml::Element& par = sts.add_child("subParameter");
3179 par.set_attr("classPath", "jmt.engine.random.ExponentialPar");
3180 par.set_attr("name", "distrPar");
3181 jmt_scalar(par, "java.lang.Double", "lambda", "1.000000000000");
3182 continue;
3183 }
3184 jmt_append_distribution(sts, jmt_dist_view(it->second.retrial_proc[r - 1]),
3185 "SolverJMT (retrial delay)");
3186 }
3187 }
3188
3189 /**
3190 * Port of the polling branch of `saveSwitchoverStrategy`.
3191 *
3192 * ONLY the polling branch is ported: `writeJSIM` reaches this handler from
3193 * the PollingServer section alone, and the reference's second branch --
3194 * a (K x K) per-class-pair switchover for an ordinary Server -- is
3195 * unreachable there. A switchover declared on a non-polling queue is
3196 * refused in `warn_switchover_on_non_polling`, which is where the reference
3197 * warns and drops it.
3198 */
3199 void save_switchover_strategy(xml::Element& section, std::size_t ind) {
3200 const std::size_t ist = sn_.nodes[ind - 1].station;
3201 const typename qn::NetworkStruct<T>::PollingParam pp = sn_.effective_polling(ist);
3202 xml::Element& p = jmt_param(section, "jmt.engine.NetStrategies.ServiceStrategy",
3203 "SwitchoverStrategy", true);
3204 for (std::size_t r = 1; r <= sn_.nclasses; ++r) {
3205 jmt_ref_class(p, cname(r));
3206 xml::Element& sts = p.add_child("subParameter");
3207 sts.set_attr("classPath",
3208 "jmt.engine.NetStrategies.ServiceStrategies.ServiceTimeStrategy");
3209 sts.set_attr("name", "ServiceTimeStrategy");
3210 // JMT charges the switchover of the class ENTERED (PollingServer.waitSwitchover), LINE the class LEFT,
3211 // so JMT entry r carries LINE switchover of r's predecessor in the cyclic class order.
3212 const std::size_t rp = (r + sn_.nclasses - 2) % sn_.nclasses + 1;
3213 const lang::Distrib<T>& so =
3214 rp <= pp.switchover.size() ? pp.switchover[rp - 1] : empty_dist_;
3215 const JmtDistView<T> v = jmt_dist_view(so);
3216 if (so.disabled || v.type == lang::ProcessType::IMMEDIATE) {
3217 // No switchover declared for this buffer is a zero switchover,
3218 // not an omission: JMT reads the array positionally. An
3219 // Immediate switchover is the same zero, declared: the
3220 // reference maps both to ZeroServiceTimeStrategy, which carries
3221 // no distribution, and there is no JMT distribution to fall
3222 // back on -- an unhandled Immediate aborted the whole solve.
3223 sts.set_attr("classPath",
3224 "jmt.engine.NetStrategies.ServiceStrategies.ZeroServiceTimeStrategy");
3225 sts.set_attr("name", "ZeroServiceTimeStrategy");
3226 continue;
3227 }
3228 jmt_append_distribution(sts, v, "SolverJMT (switchover)");
3229 }
3230 }
3231
3232 std::map<std::size_t, double> empty_weights_;
3233 lang::Distrib<T> empty_dist_;
3234};
3235
3236/** Port of `@@JMTIO/writeJSIM.m`: serialize `sn` as a JMT `.jsimg` document. */
3237template <class T>
3239 JmtWriter<T> w(sn, opt);
3240 return w.write_jsim();
3241}
3242
3243/**
3244 * `JmtWriter::buffer_capacity_refusal` without a document: the writer's own
3245 * binding-buffer verdict, for the gate in `jmt::jmt_method_refusal`.
3246 */
3247template <class T>
3248std::string jmt_buffer_capacity_refusal(const qn::NetworkStruct<T>& sn, bool jmva_engine) {
3250 return w.buffer_capacity_refusal(jmva_engine);
3251}
3252
3253/**
3254 * `JmtWriter::cache_refusal` over every Cache node, without a document: the writer's own cache verdict, for the
3255 * gate in `jmt::jmt_method_refusal`; empty when every cache is exportable.
3256 */
3257template <class T>
3259 bool any = false;
3260 for (const auto& nd : sn.nodes)
3261 if (nd.nodetype == qn::NodeType::Cache) any = true;
3262 if (!any) return std::string();
3264 for (std::size_t ind = 1; ind <= sn.nodes.size(); ++ind) {
3265 if (sn.nodes[ind - 1].nodetype != qn::NodeType::Cache) continue;
3266 const std::string why = w.cache_refusal(ind);
3267 if (!why.empty()) return why;
3268 }
3269 return std::string();
3270}
3271
3272} // namespace io
3273} // namespace line
3274
3275#endif // LINE_IO_JMT_WRITER_H
InputError(const std::string &what)
Definition error.h:105
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
A refusal: the feature, method or analysis is not covered: LINE:unsupported:<kind>.
Definition error.h:117
UnsupportedError(const std::string &what)
Definition error.h:119
The writer itself.
Definition jmt_writer.h:511
std::string write_jsim()
Port of @@JMTIO/writeJSIM.m; returns the serialized document.
Definition jmt_writer.h:521
std::string buffer_capacity_refusal(bool jmva_engine) const
The buffer-capacity refusals of save_buffer_capacity, as a SENTENCE rather than an exception; empty w...
Definition jmt_writer.h:558
JmtWriter(const qn::NetworkStruct< T > &sn, const JmtWriteOptions &opt)
Definition jmt_writer.h:513
std::string cache_refusal(std::size_t ind) const
Everything save_cache_strategy refuses for cache node ind, as a SENTENCE; empty when JMT reproduces t...
A network plus its refreshed NetworkStruct.
std::vector< JobClass > classes
std::vector< NodeDef > nodes
every node, in creation order
The exception types the port throws.
The distribution subtree of a JMT .jsimg file, and the scalar formatting every JMT writer shares.
std::string jmt_soft_deadline_text(double d)
saveClasses.m: num2str of a finite deadline, 0.0 otherwise: the <userClass softDeadline> text.
Definition jmt_writer.h:417
std::string jmt_num2str(double v)
MATLAB num2str of a real scalar: an integer-valued double has no decimal point ("5",...
Definition jmt_writer.h:402
void jmt_append_distribution(xml::Element &wrapper, const JmtDistView< T > &v, const char *who)
Append the distribution and distrPar pair for one process.
Definition jmt_dist.h:226
const char * jmt_drop_text(DropStrategy d)
MATLAB DropStrategy.toText, the strings JMT's dropRule field expects.
Definition jmt_writer.h:463
JmtMetricKind
The measure kinds saveMetrics requests, in the order it requests them.
Definition jmt_writer.h:298
bool jmt_metric_enabled(const qn::NetworkStruct< T > &sn, JmtMetricKind kind, std::size_t ist, std::size_t r, const std::vector< bool > &is_cache_class)
Port of the disabled rules in getAvgHandles, per (station, class).
Definition jmt_writer.h:330
std::string jmt_fmt(double x)
sprintf('%.12f', x), the numeric format of every JMT <value> body.
Definition jmt_dist.h:53
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.
JmtSections< T > jmt_sections(const qn::NetworkStruct< T > &sn, std::size_t ind)
Definition jmt_writer.h:169
void jmt_param_value(xml::Element &section, const char *class_path, const char *name, const std::string &value)
<parameter classPath="CP" name="NAME"><value>V</value></parameter>
Definition jmt_writer.h:451
std::string jmt_buffer_capacity_refusal(const qn::NetworkStruct< T > &sn, bool jmva_engine)
JmtWriter::buffer_capacity_refusal without a document: the writer's own binding-buffer verdict,...
std::vector< bool > jmt_cache_classes(const qn::NetworkStruct< T > &sn)
The classes a Cache switches jobs into; they keep their Tput/ArvR measures.
Definition jmt_writer.h:424
xml::Element & jmt_scalar(xml::Element &parent, const char *class_path, const char *name, const std::string &value)
<subParameter classPath="java.lang.Double" name="NAME"><value>V</value>
Definition jmt_dist.h:81
bool jmt_reads_drop(DropStrategy d)
Whether JMT's queue section can read this drop strategy at all.
Definition jmt_writer.h:486
std::vector< std::vector< bool > > jmt_conn_matrix(const qn::NetworkStruct< T > &sn)
sn.connmatrix: which ordered pairs of nodes the model LINKED.
Definition jmt_writer.h:100
xml::Element & jmt_double(xml::Element &parent, const char *name, double v)
A java.lang.Double scalar subparameter.
Definition jmt_dist.h:91
std::vector< bool > jmt_exportable_classes(const qn::NetworkStruct< T > &sn)
Port of getExportableClasses.
Definition jmt_writer.h:124
const char * jmt_hetero_text(lang::HeteroSchedPolicy p)
MATLAB HeteroSchedPolicy.toJMTText: JMT's long descriptive identifiers.
Definition jmt_writer.h:492
std::string jmt_cache_refusal(const qn::NetworkStruct< T > &sn)
JmtWriter::cache_refusal over every Cache node, without a document: the writer's own cache verdict,...
std::string jmt_deadline_refusal(const qn::NetworkStruct< T > &sn)
Port of jmtDeadlineRefusal.m: the due date an EDD or EDF station needs and the model does not carry,...
Definition jmt_writer.h:375
const char * jmt_metric_text(JmtMetricKind k)
The JMT type attribute, MATLAB MetricType.toText.
Definition jmt_writer.h:301
xml::Element & jmt_param(xml::Element &section, const char *class_path, const char *name, bool array)
<parameter array="true" classPath="CP" name="NAME">
Definition jmt_writer.h:441
void jmt_ref_class(xml::Element &parent, const std::string &class_name)
<refClass>NAME</refClass>, the per-class marker of an array parameter.
Definition jmt_writer.h:458
JmtDistView< T > jmt_dist_view(const Distrib< T > &d)
Lower a Distrib to the view above.
Definition jmt_dist.h:122
std::string jmt_int(double x)
int2str(x): round to nearest, print as a decimal integer.
Definition jmt_dist.h:60
std::string jmt_num(double x)
num2str(x): MATLAB's default five-significant-digit form.
Definition jmt_dist.h:67
std::string jmt_sig2(double x)
num2str(x, 2): the two-significant-digit form used for alpha/precision.
Definition jmt_dist.h:74
SchedStrategy
Scheduling disciplines, with the values of MATLAB SchedStrategy.
Definition lang_types.h:194
DropStrategy
Blocking and loss rules, with the values of MATLAB DropStrategy.
Definition lang_types.h:465
@ IMMEDIATE
fires with zero delay, resolved by weight and priority
Definition lang_types.h:384
JoinStrategy
Join rules, with the values of MATLAB JoinStrategy.
Definition lang_types.h:502
RoutingStrategy
Routing strategies, with the values of MATLAB RoutingStrategy.
Definition lang_types.h:430
HeteroSchedPolicy
How a heterogeneous station picks among its server types, MATLAB HeteroSchedPolicy.
Definition lang_types.h:492
PollingType
Polling service disciplines, with the values of MATLAB PollingType.
Definition lang_types.h:391
NodeType
Node kinds, with the values of MATLAB NodeType.
Definition lang_types.h:345
@ LRU
least recently used
Definition lang_types.h:423
@ FIFO
first in, first out
Definition lang_types.h:421
double tot(const std::vector< double > &pops)
bool in(const std::string &s, std::initializer_list< const char * > set)
std::unique_ptr< Element > element(const std::string &tag)
A fresh detached element, the createElement of the write side.
Definition xml.h:299
std::string serialize(const Element &root)
Serialize a document: the XML declaration MATLAB's xmlwrite emits, then the root subtree.
Definition xml.h:369
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
The three JMT section class names of a node: input, server, output.
Definition jmt_writer.h:164
The simulation controls the JSIM header carries, MATLAB's JMTIO properties.
Definition jmt_writer.h:69
bool jmt150
JMT 1.5.0 or later runs the document: its Server takes a switchover argument ahead of delayOff/setUp,...
Definition jmt_writer.h:80
std::string log_path
model.getLogPath, the logPath attribute
Definition jmt_writer.h:71
std::string file_name
base name; the header echoes it plus .jsimg
Definition jmt_writer.h:70
The popularity LAW each class declared, beside the pmf it expands to.
The parameters of a Cache node, MATLAB's sn.nodeparam{ind} for a Cache.
std::vector< Popularity > preadkind
per class, parallel to pread
std::vector< std::vector< Matrix< T > > > accost
(u) x (n) of (h+1)x(h+1), or empty
std::vector< int > itemcap
std::vector< std::size_t > missclass
std::vector< std::size_t > hitclass
lang::ReplacementStrategy replacestrat
std::vector< std::vector< T > > pread
(u) x (n), empty row = NaN
A node of the network.
Element & add_child(const std::string &tag)
createElement + appendChild in one step; the child is owned here.
Definition xml.h:107
Element & set_attr(const std::string &key, const std::string &value)
setAttribute: replace the value in place when the key already exists, otherwise append.
Definition xml.h:96
Element & add_text_child(const std::string &tag, const std::string &value)
The common shape <tag>value</tag>.
Definition xml.h:122
A minimal XML DOM: read for the .lqnx interchange format, write for the JMT .jsimg and ....