LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
network_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_NETWORK_WRITER_H
6#define LINE_IO_NETWORK_WRITER_H
7
8/**
9 * @file
10 * @ingroup line_io
11 * `qn::NetworkStruct` -> model.json, the inverse of network_reader.h.
12 *
13 * The wire format is the one `linemodel_save.m`, the Python `save_model` and
14 * the JAR `LineModelIO` write, so a model saved here loads in any of the four
15 * codebases and a model saved by any of them and read back here is unchanged.
16 *
17 * WHAT IS AND IS NOT ROUND-TRIPPABLE. Two things on a model are FUNCTIONS, and
18 * a function cannot cross JSON:
19 *
20 * the rate-scaling handles beta_r(n), eta_i(n) and the OI mu(c)
21 * a reward built from a lambda
22 *
23 * The reference solves the first by MATERIALIZING the handle over the per-class
24 * box lattice, and this writer does the same, with the same cutoffs (a closed
25 * class's population, or 10 for an open one) and the same comma-joined key, so
26 * the table is byte-comparable with MATLAB's. The second it solves by writing
27 * only the DECLARATIVE rewards and warning about the rest; here a reward with
28 * no `kind` is omitted for the same reason -- emitting a guess would produce a
29 * model.json that reloads into a different reward.
30 *
31 * EVERY OTHER KEY IS EXACT. The writer emits exactly the keys the reader
32 * consumes, which is what makes the round trip a test rather than a hope: a
33 * field added to one side without the other shows up as a read-back mismatch
34 * in `test_network_roundtrip.cpp`.
35 */
36
37#include <cctype>
38#include <algorithm>
39#include <cmath>
40#include <fstream>
41#include <functional>
42#include <limits>
43#include <map>
44#include <string>
45#include <vector>
46
51#include "line/num/number.h"
52#include "line/util/error.h"
53
54namespace line {
55namespace io {
56
57namespace detail {
58
59/** The model.json `type` of a node kind. */
60inline const char* node_type_to_json(lang::NodeType t) {
61 switch (t) {
62 case lang::NodeType::Queue: return "Queue";
63 case lang::NodeType::Source: return "Source";
64 case lang::NodeType::Delay: return "Delay";
65 case lang::NodeType::ClassSwitch: return "ClassSwitch";
66 case lang::NodeType::Logger: return "Logger";
67 case lang::NodeType::Cache: return "Cache";
68 case lang::NodeType::Router: return "Router";
69 case lang::NodeType::Fork: return "Fork";
70 case lang::NodeType::Place: return "Place";
71 case lang::NodeType::Transition: return "Transition";
72 case lang::NodeType::Region: return "Region";
73 case lang::NodeType::Join: return "Join";
74 case lang::NodeType::Sink: return "Sink";
75 }
76 throw UnsupportedError(ErrorKind{"Export"}, "network_writer: unnamed node type");
77}
78
79inline const char* drop_to_json(lang::DropStrategy d) {
80 switch (d) {
81 case lang::DropStrategy::WAITQ: return "waitingQueue";
82 case lang::DropStrategy::DROP: return "drop";
83 case lang::DropStrategy::BAS: return "blockingAfterService";
84 case lang::DropStrategy::BBS: return "blockingBeforeService";
85 case lang::DropStrategy::RSRD: return "resamplingRepetitiveService";
86 case lang::DropStrategy::RETRIAL: return "retrial";
87 case lang::DropStrategy::RETRIAL_WITH_LIMIT: return "retrialWithLimit";
88 }
89 throw UnsupportedError(ErrorKind{"Export"}, "network_writer: unnamed drop strategy");
90}
91
92inline const char* replacement_to_json(lang::ReplacementStrategy r) {
93 switch (r) {
94 case lang::ReplacementStrategy::RR: return "RR";
95 case lang::ReplacementStrategy::FIFO: return "FIFO";
96 case lang::ReplacementStrategy::SFIFO: return "SFIFO";
97 case lang::ReplacementStrategy::LRU: return "LRU";
98 case lang::ReplacementStrategy::HLRU: return "HLRU";
99 case lang::ReplacementStrategy::CLIMB: return "CLIMB";
100 case lang::ReplacementStrategy::QLRU: return "QLRU";
101 }
102 throw UnsupportedError(ErrorKind{"Export"}, "network_writer: unnamed replacement strategy");
103}
104
105inline const char* polling_to_json(lang::PollingType p) {
106 switch (p) {
107 case lang::PollingType::EXHAUSTIVE: return "EXHAUSTIVE";
108 case lang::PollingType::GATED: return "GATED";
109 case lang::PollingType::KLIMITED: return "KLIMITED";
110 case lang::PollingType::DECREMENTING: return "DECREMENTING";
111 case lang::PollingType::GLIMITED: return "GLIMITED";
112 }
113 throw UnsupportedError(ErrorKind{"Export"}, "network_writer: unnamed polling type");
114}
115
116inline const char* polling_order_to_json(lang::PollingOrder o) {
117 switch (o) {
118 case lang::PollingOrder::CYCLIC: return "CYCLIC";
119 case lang::PollingOrder::SKIPEMPTY: return "SKIPEMPTY";
120 case lang::PollingOrder::LQF: return "LQF";
121 case lang::PollingOrder::THRESHOLD: return "THRESHOLD";
122 }
123 throw UnsupportedError(ErrorKind{"Export"}, "network_writer: unnamed polling order");
124}
125
126inline const char* impatience_to_json(lang::ImpatienceType i) {
127 switch (i) {
128 case lang::ImpatienceType::RENEGING: return "RENEGING";
129 case lang::ImpatienceType::BALKING: return "BALKING";
130 case lang::ImpatienceType::RETRIAL: return "RETRIAL";
131 case lang::ImpatienceType::NONE: break;
132 }
133 throw UnsupportedError(ErrorKind{"Export"}, "network_writer: a patience block with no impatience type");
134}
135
136inline const char* balking_to_json(lang::BalkingStrategy b) {
137 switch (b) {
138 case lang::BalkingStrategy::QUEUE_LENGTH: return "QUEUE_LENGTH";
139 case lang::BalkingStrategy::EXPECTED_WAIT: return "EXPECTED_WAIT";
140 case lang::BalkingStrategy::COMBINED: return "COMBINED";
141 case lang::BalkingStrategy::NONE: break;
142 }
143 throw UnsupportedError(ErrorKind{"Export"}, "network_writer: a balking block with no strategy");
144}
145
146/**
147 * The `routingStrategies` name of a dispatcher.
148 *
149 * NOT `lang::routing_to_text`, which is the lower-case name `sn.routing` prints
150 * in a struct dump. The wire carries the enum CONSTANT, upper case, matching
151 * the JAR's `RoutingStrategy` names one for one -- and the readers compare it
152 * exactly, so `rrobin` reloads as an unknown strategy rather than as RROBIN.
153 */
154inline const char* routing_to_json(lang::RoutingStrategy r) {
155 switch (r) {
156 case lang::RoutingStrategy::RAND: return "RAND";
157 case lang::RoutingStrategy::PROB: return "PROB";
158 case lang::RoutingStrategy::RROBIN: return "RROBIN";
159 case lang::RoutingStrategy::WRROBIN: return "WRROBIN";
160 case lang::RoutingStrategy::JSQ: return "JSQ";
161 case lang::RoutingStrategy::FIRING: return "FIRING";
162 case lang::RoutingStrategy::SQ: return "SQ";
163 case lang::RoutingStrategy::SDR: return "SDR";
164 case lang::RoutingStrategy::DISABLED: return "DISABLED";
165 }
166 throw UnsupportedError(ErrorKind{"Export"}, "network_writer: unnamed routing strategy");
167}
168
169inline const char* hetero_to_json(lang::HeteroSchedPolicy h) {
170 switch (h) {
171 case lang::HeteroSchedPolicy::ORDER: return "ORDER";
172 case lang::HeteroSchedPolicy::ALIS: return "ALIS";
173 case lang::HeteroSchedPolicy::ALFS: return "ALFS";
174 case lang::HeteroSchedPolicy::FAIRNESS: return "FAIRNESS";
175 case lang::HeteroSchedPolicy::FSF: return "FSF";
176 case lang::HeteroSchedPolicy::RAIS: return "RAIS";
177 }
178 throw UnsupportedError(ErrorKind{"Export"}, "network_writer: unnamed heterogeneous scheduling policy");
179}
180
181/**
182 * The `scheduling` name of a discipline.
183 *
184 * UPPER CASE, which is not what `lang::sched_to_text` returns: that is the
185 * lower-case spelling `sn.sched` prints in a struct dump, while the wire
186 * carries the enum constant (`upper(SchedStrategy.toText(...))` in
187 * `linemodel_save.m`, matching `jline.lang.constant.SchedStrategy`). A
188 * lower-case `fcfs` reloads as an unknown discipline.
189 */
190inline std::string sched_to_json(lang::SchedStrategy s) {
191 std::string out = lang::sched_to_text(s);
192 for (std::size_t i = 0; i < out.size(); ++i)
193 out[i] = static_cast<char>(std::toupper(static_cast<unsigned char>(out[i])));
194 return out;
195}
196
197/** A dense matrix as the array of row arrays the readers expect. */
198template <class T>
199json mat_to_json(const Matrix<T>& M) {
200 json rows = json::array();
201 for (std::size_t i = 0; i < M.rows(); ++i) {
202 json row = json::array();
203 for (std::size_t j = 0; j < M.cols(); ++j)
204 row.push_back(num_traits<T>::to_double(M(i, j)));
205 rows.push_back(row);
206 }
207 return rows;
208}
209
210template <class T>
211json vec_to_json(const std::vector<T>& v) {
212 json a = json::array();
213 for (const T& x : v) a.push_back(num_traits<T>::to_double(x));
214 return a;
215}
216
217/**
218 * Rewrite every non-finite number into the wire's own INFINITY SPELLING.
219 *
220 * JSON has no infinity literal, so `linemodel_save` -- the reference -- writes
221 * an infinite scalar as the STRING "Infinity" / "-Infinity" and a NaN as
222 * `null`, a rule it applies to EVERY numeric field rather than a named few;
223 * `num_from_json` on the reading side decodes exactly that pair. nlohmann
224 * silently dumps an infinity as `null` instead, which the reader then takes for
225 * a NaN, so a state row that carries the sentinel -- an open class holds an
226 * infinite population, so a Source's `initialState` does the moment the model
227 * is initialized -- crossed as a hole rather than as a value. Applied once over
228 * the finished document, as the JAR and Python writers apply theirs, so no
229 * individual field has to remember the rule.
230 */
231inline void wire_nonfinite(json& j) {
232 if (j.is_object() || j.is_array()) {
233 for (json::iterator it = j.begin(); it != j.end(); ++it) wire_nonfinite(*it);
234 return;
235 }
236 if (!j.is_number_float()) return;
237 const double v = j.get<double>();
238 if (std::isnan(v))
239 j = json();
240 else if (std::isinf(v))
241 j = json(v > 0.0 ? "Infinity" : "-Infinity");
242}
243
244/**
245 * `x` of a `DiscreteSampler` whose support is the item index, i.e. 1..n.
246 *
247 * MATLAB `DiscreteSampler(p)` defaults `x = 1:n` and every writer records it;
248 * the JAR and Python readers require the key and fail on a file that omits it,
249 * so a pmf-only document is unreadable outside this port even though the value
250 * is implied.
251 */
252inline json discrete_support(std::size_t n) {
253 json a = json::array();
254 for (std::size_t i = 1; i <= n; ++i) a.push_back(static_cast<double>(i));
255 return a;
256}
257
258/**
259 * A distribution as its model.json record, the inverse of `dist_from_json`.
260 *
261 * The parameter-carrying families are written from `Distrib::params`, which
262 * holds the constructor arguments in MATLAB's getParam order -- that is what
263 * makes the record reload into the SAME object rather than into a phase-type
264 * that shares two moments with it.
265 */
266template <class T>
267json dist_to_json(const lang::Distrib<T>& d) {
268 using lang::ProcessType;
269 json j;
270 j["type"] = lang::process_to_text(d.type);
271 const std::vector<T>& p = d.params;
272 auto need = [&](std::size_t n, const char* who) {
273 if (p.size() < n)
274 throw InputError(std::string("network_writer: a ") + who + " carries " +
275 std::to_string(p.size()) + " parameters, and " + std::to_string(n) +
276 " are needed to write it back");
277 };
278 switch (d.type) {
279 case ProcessType::DISABLED:
280 case ProcessType::IMMEDIATE:
281 return j; // both are bare tags
282 case ProcessType::EXP:
283 need(1, "Exp");
284 j["params"]["lambda"] = num_traits<T>::to_double(p[0]);
285 return j;
286 case ProcessType::DET:
287 j["params"]["value"] = num_traits<T>::to_double(d.mean);
288 return j;
289 case ProcessType::ERLANG:
290 need(2, "Erlang");
291 j["params"]["lambda"] = num_traits<T>::to_double(p[0]);
292 j["params"]["k"] = static_cast<long>(std::lround(num_traits<T>::to_double(p[1])));
293 return j;
294 case ProcessType::HYPEREXP: {
295 // The two-branch form stores (p, lambda1, lambda2) and the general
296 // one (p_1..p_n, lambda_1..lambda_n); both write the same two
297 // vectors, which is the only form on the wire.
298 json pv = json::array(), lv = json::array();
299 if (p.size() == 3) {
300 pv.push_back(num_traits<T>::to_double(p[0]));
301 pv.push_back(1.0 - num_traits<T>::to_double(p[0]));
302 lv.push_back(num_traits<T>::to_double(p[1]));
303 lv.push_back(num_traits<T>::to_double(p[2]));
304 } else {
305 const std::size_t n = p.size() / 2;
306 for (std::size_t i = 0; i < n; ++i) pv.push_back(num_traits<T>::to_double(p[i]));
307 for (std::size_t i = 0; i < n; ++i) lv.push_back(num_traits<T>::to_double(p[n + i]));
308 }
309 j["params"]["p"] = pv;
310 j["params"]["lambda"] = lv;
311 return j;
312 }
313 case ProcessType::COXIAN:
314 case ProcessType::COX2: {
315 const std::size_t n = p.size() / 2;
316 json mu = json::array(), phi = json::array();
317 for (std::size_t i = 0; i < n; ++i) mu.push_back(num_traits<T>::to_double(p[i]));
318 for (std::size_t i = 0; i < n; ++i) phi.push_back(num_traits<T>::to_double(p[n + i]));
319 // Coxian is the only name the readers reconstruct from (mu, phi);
320 // Cox2 is the two-phase constructor and shares the representation.
321 j["type"] = "Coxian";
322 j["params"]["mu"] = mu;
323 j["params"]["phi"] = phi;
324 return j;
325 }
326 case ProcessType::PH:
327 case ProcessType::APH:
328 case ProcessType::ME: {
329 json alpha = json::array();
330 for (const T& v : p) alpha.push_back(num_traits<T>::to_double(v));
331 if (d.type == ProcessType::ME) {
332 j["params"]["alpha"] = alpha;
333 j["params"]["A"] = mat_to_json(d.D0);
334 } else {
335 j["ph"]["alpha"] = alpha;
336 j["ph"]["T"] = mat_to_json(d.D0);
337 }
338 return j;
339 }
340 case ProcessType::MAP:
341 j["map"]["D0"] = mat_to_json(d.D0);
342 j["map"]["D1"] = mat_to_json(d.D1);
343 return j;
344 case ProcessType::RAP:
345 j["params"]["H0"] = mat_to_json(d.D0);
346 j["params"]["H1"] = mat_to_json(d.D1);
347 return j;
348 case ProcessType::DMAP:
349 j["params"]["D0"] = mat_to_json(d.D0);
350 j["params"]["D1"] = mat_to_json(d.D1);
351 return j;
352 case ProcessType::MMPP2: {
353 // Recovered from the pair rather than from `params`, which
354 // `map_dist` does not fill: lambda_i is the arrival rate in phase i
355 // and sigma_i the modulating rate out of it.
356 if (d.D0.rows() != 2)
357 throw InputError("network_writer: an MMPP2 must be of order two");
358 j["params"]["lambda0"] = num_traits<T>::to_double(d.D1(0, 0));
359 j["params"]["lambda1"] = num_traits<T>::to_double(d.D1(1, 1));
360 j["params"]["sigma0"] = num_traits<T>::to_double(d.D0(0, 1));
361 j["params"]["sigma1"] = num_traits<T>::to_double(d.D0(1, 0));
362 return j;
363 }
364 case ProcessType::MPH: {
365 // Stored as the MMAP cell it lowers to, but the (alpha, S, {s_c}) split IS
366 // recoverable from it and is what the other codebases expect back: every row
367 // of D1_agg is (-S e)_i alpha, so alpha is any nonzero row normalised, and
368 // s_c(i) is the row sum of that mark's block. Writing the lowered cell instead
369 // would come back as a plain MMAP and lose the process type.
370 const std::size_t H = d.D0.rows();
371 std::vector<double> alpha(H, 0.0);
372 for (std::size_t i = 0; i < H; ++i) {
373 double row = 0.0;
374 for (std::size_t q = 0; q < H; ++q) row += num_traits<T>::to_double(d.D1(i, q));
375 if (row > 0.0) {
376 for (std::size_t q = 0; q < H; ++q)
377 alpha[q] = num_traits<T>::to_double(d.D1(i, q)) / row;
378 break;
379 }
380 }
381 j["mph"]["alpha"] = alpha;
382 j["mph"]["S"] = mat_to_json(d.D0);
383 json exits = json::array();
384 for (const Matrix<T>& Dk : d.Dmark) {
385 std::vector<double> sk(H, 0.0);
386 for (std::size_t i = 0; i < H; ++i)
387 for (std::size_t q = 0; q < H; ++q)
388 sk[i] += num_traits<T>::to_double(Dk(i, q));
389 exits.push_back(sk);
390 }
391 j["mph"]["exit"] = exits;
392 return j;
393 }
394 case ProcessType::MMAP: {
395 j["mmap"]["D0"] = mat_to_json(d.D0);
396 json blocks = json::array();
397 for (const Matrix<T>& Dk : d.Dmark) blocks.push_back(mat_to_json(Dk));
398 j["mmap"]["D1k"] = blocks;
399 return j;
400 }
401 case ProcessType::BMAP: {
402 json blocks = json::array();
403 blocks.push_back(mat_to_json(d.D0));
404 for (const Matrix<T>& Dk : d.Dmark) blocks.push_back(mat_to_json(Dk));
405 j["params"]["D"] = blocks;
406 return j;
407 }
408 case ProcessType::UNIFORM:
409 need(2, "Uniform");
410 j["params"]["a"] = num_traits<T>::to_double(p[0]);
411 j["params"]["b"] = num_traits<T>::to_double(p[1]);
412 return j;
413 case ProcessType::PARETO:
414 need(2, "Pareto");
415 j["params"]["alpha"] = num_traits<T>::to_double(p[0]);
416 j["params"]["scale"] = num_traits<T>::to_double(p[1]);
417 return j;
418 case ProcessType::GAMMA:
419 need(2, "Gamma");
420 j["params"]["alpha"] = num_traits<T>::to_double(p[0]);
421 j["params"]["beta"] = num_traits<T>::to_double(p[1]);
422 return j;
423 case ProcessType::WEIBULL:
424 // `alpha` is the SCALE here and the SHAPE in Pareto above; that is
425 // the reference's own key naming and the one trap in this table.
426 need(2, "Weibull");
427 j["params"]["alpha"] = num_traits<T>::to_double(p[0]);
428 j["params"]["beta"] = num_traits<T>::to_double(p[1]);
429 return j;
430 case ProcessType::LOGLOGISTIC:
431 // Weibull's pairing: `alpha` the SCALE, `beta` the SHAPE.
432 need(2, "LogLogistic");
433 j["params"]["alpha"] = num_traits<T>::to_double(p[0]);
434 j["params"]["beta"] = num_traits<T>::to_double(p[1]);
435 return j;
436 case ProcessType::MASSATORIGIN:
437 case ProcessType::DEFECTIVE:
438 need(1, lang::process_to_text(d.type));
439 if (!d.inner)
440 throw InputError(ErrorKind{"Format"}, "network_writer: a wrapper law without its inner law");
441 j["params"][d.type == ProcessType::MASSATORIGIN ? "p0" : "pInf"] =
442 num_traits<T>::to_double(p[0]);
443 j["dist"] = dist_to_json(*d.inner);
444 return j;
445 case ProcessType::LOGNORMAL:
446 need(2, "Lognormal");
447 j["params"]["mu"] = num_traits<T>::to_double(p[0]);
448 j["params"]["sigma"] = num_traits<T>::to_double(p[1]);
449 return j;
450 case ProcessType::DUNIFORM:
451 need(2, "DiscreteUniform");
452 j["params"]["min"] = num_traits<T>::to_double(p[0]);
453 j["params"]["max"] = num_traits<T>::to_double(p[1]);
454 return j;
455 case ProcessType::BERNOULLI:
456 need(1, "Bernoulli");
457 j["params"]["p"] = num_traits<T>::to_double(p[0]);
458 return j;
459 case ProcessType::BINOMIAL:
460 need(2, "Binomial");
461 j["params"]["n"] = static_cast<long>(std::lround(num_traits<T>::to_double(p[0])));
462 j["params"]["p"] = num_traits<T>::to_double(p[1]);
463 return j;
464 case ProcessType::POISSON:
465 need(1, "Poisson");
466 j["params"]["lambda"] = num_traits<T>::to_double(p[0]);
467 return j;
468 case ProcessType::GEOMETRIC:
469 need(1, "Geometric");
470 j["params"]["p"] = num_traits<T>::to_double(p[0]);
471 return j;
472 case ProcessType::ZIPF:
473 need(2, "Zipf");
474 j["params"]["s"] = num_traits<T>::to_double(p[0]);
475 j["params"]["n"] = static_cast<long>(std::lround(num_traits<T>::to_double(p[1])));
476 return j;
477 case ProcessType::DISCRETESAMPLER:
478 j["params"]["p"] = vec_to_json(p);
479 if (!d.trace.empty()) j["params"]["x"] = vec_to_json(d.trace);
480 return j;
481 case ProcessType::EMPIRICALCDF:
482 j["params"]["x"] = vec_to_json(d.trace);
483 j["params"]["F"] = vec_to_json(p);
484 return j;
485 case ProcessType::REPLAYER:
486 // The trace itself has no wire form: every writer emits the file
487 // PATH, plus the mean beside it as the documented fallback for a
488 // reader on another machine where the path does not resolve. A
489 // Replayer built from in-memory samples has no path, and then only
490 // the moments can be written -- which reloads as a distribution
491 // matching them, not as the trace, exactly as the reference warns.
492 if (!d.trace_file.empty()) j["params"]["fileName"] = d.trace_file;
493 j["params"]["mean"] = num_traits<T>::to_double(d.mean);
494 if (d.trace_file.empty())
495 j["params"]["scv"] = num_traits<T>::to_double(d.scv);
496 return j;
497 case ProcessType::MMAPT:
498 case ProcessType::MPHT: {
499 j["params"]["breakpoints"] = vec_to_json(d.sched_bp);
500 j["params"]["cyclic"] = d.sched_cyclic;
501 json A = json::array();
502 for (const Matrix<T>& M : d.sched_D0) A.push_back(mat_to_json(M));
503 json blocks = json::array();
504 for (const std::vector<Matrix<T> >& per_mark : d.sched_Dmark) {
505 json segs = json::array();
506 for (const Matrix<T>& M : per_mark) segs.push_back(mat_to_json(M));
507 blocks.push_back(segs);
508 }
509 // An MPHt is STORED lowered to MMAPt form -- see the Distrib header -- so the
510 // (alpha, S, exits) split is not recoverable here and it is written in the
511 // MMAPt spelling it reloads identically from. Exactly what a PHt does below,
512 // and for the same reason: this port keeps one representation per family.
513 j["type"] = "MMAPt";
514 j["params"]["D0"] = A;
515 j["params"]["D1k"] = blocks;
516 return j;
517 }
518 case ProcessType::BMMAPT: {
519 // Only the BLOCKS travel, nested mark, then batch size, then segment. The
520 // reader derives the batch-aggregated D1k and the aggregate D1 from them,
521 // so the wire cannot carry a level that disagrees with the blocks summing
522 // to it.
523 j["params"]["breakpoints"] = vec_to_json(d.sched_bp);
524 j["params"]["cyclic"] = d.sched_cyclic;
525 json A = json::array();
526 for (const Matrix<T>& M : d.sched_D0) A.push_back(mat_to_json(M));
527 json blocks = json::array();
528 for (const std::vector<std::vector<Matrix<T> > >& per_mark : d.sched_Dbatch) {
529 json per_batch = json::array();
530 for (const std::vector<Matrix<T> >& batch : per_mark) {
531 json segs = json::array();
532 for (const Matrix<T>& M : batch) segs.push_back(mat_to_json(M));
533 per_batch.push_back(segs);
534 }
535 blocks.push_back(per_batch);
536 }
537 j["params"]["D0"] = A;
538 j["params"]["D1kb"] = blocks;
539 return j;
540 }
541 // NHPP belongs with MAPt: it is a one-phase MAPt and is written back as its
542 // `rates` vector by the branch below. It briefly sat with the MARKED families
543 // above, where it was emitted as an `MMAPt` carrying an EMPTY `D1k` -- a
544 // document no reader accepts, since the MMAPt factory refuses a schedule with
545 // no mark block.
546 case ProcessType::NHPP:
547 case ProcessType::MAPT:
548 case ProcessType::PHT: {
549 j["params"]["breakpoints"] = vec_to_json(d.sched_bp);
550 j["params"]["cyclic"] = d.sched_cyclic;
551 if (d.type == ProcessType::NHPP) {
552 // A one-phase schedule: the rate of segment k is D1[k](0,0).
553 json rates = json::array();
554 for (const Matrix<T>& D1 : d.sched_D1)
555 rates.push_back(num_traits<T>::to_double(D1(0, 0)));
556 j["params"]["rates"] = rates;
557 return j;
558 }
559 json A = json::array(), B = json::array();
560 for (const Matrix<T>& M : d.sched_D0) A.push_back(mat_to_json(M));
561 for (const Matrix<T>& M : d.sched_D1) B.push_back(mat_to_json(M));
562 // A PHt is STORED converted to (D0, D1) -- see the Distrib header --
563 // so it is written in the MAPt spelling it reloads identically from.
564 j["type"] = "MAPt";
565 j["params"]["D0"] = A;
566 j["params"]["D1"] = B;
567 return j;
568 }
569 case ProcessType::NNPP: {
570 // The shared NNPP wire form (see network_reader.h). The horizon is
571 // written for a pwlinear rate too, and the reader checks it.
572 if (!d.nnpp)
573 throw InputError("network_writer: an NNPP carries no rate function to write back");
574 const lang::Nnpp& n = *d.nnpp;
575 auto arr = [](const std::vector<double>& v) {
576 json a = json::array();
577 for (double x : v) a.push_back(x);
578 return a;
579 };
580 json rate;
581 rate["kind"] = n.kind_name();
582 if (n.kind() == lang::Nnpp::EPTMP) {
583 rate["alpha"] = arr(n.alpha());
584 rate["gamma"] = arr(n.gamma());
585 rate["omega"] = arr(n.omega());
586 rate["phi"] = arr(n.phi());
587 } else {
588 rate["times"] = arr(n.times());
589 rate["rates"] = arr(n.rates());
590 }
591 j["params"]["rate"] = rate;
592 j["params"]["horizon"] = n.horizon();
593 j["params"]["dispersion"] = n.dispersion();
594 j["params"]["cyclic"] = n.is_cyclic();
595 j["params"]["Q"] = n.q();
596 return j;
597 }
598 case ProcessType::PRIOR:
599 throw UnsupportedError(ErrorKind{"Export"},
600 "network_writer: a Prior is a set of alternative MODELS rather than one law; save "
601 "the design point SolverUQ built, not the design");
602 default:
603 break;
604 }
605 throw UnsupportedError(ErrorKind{"Export"}, std::string("network_writer: distribution family '") +
606 lang::process_to_text(d.type) + "' has no model.json record");
607}
608
609/**
610 * The per-class cutoffs a materialized rate table is swept over: a closed
611 * class's population, and 10 for an open one.
612 *
613 * The same rule as `linemodel_save.m:157-163`, and it has to be, or the tables
614 * this writer emits would be keyed over a different lattice than the reference's
615 * for the same model and the two files would not compare.
616 */
617template <class T>
618std::vector<int> lattice_cutoffs(const qn::NetworkStruct<T>& sn) {
619 std::vector<int> cut(sn.classes.size(), 10);
620 for (std::size_t r = 0; r < sn.classes.size(); ++r)
621 if (sn.classes[r].type == lang::JobClassType::CLOSED &&
622 std::isfinite(sn.classes[r].population))
623 cut[r] = static_cast<int>(std::lround(sn.classes[r].population));
624 return cut;
625}
626
627/**
628 * Enumerate the box lattice 0 <= n(r) <= cut(r), calling `visit(counts, key)`.
629 * The empty state is skipped unless `with_empty`: an OI/PAS table omits it, a
630 * class/joint-dependence table lists it, as MATLAB, the JAR and Python do.
631 */
632template <class F>
633void for_each_lattice_point(const std::vector<int>& cut, const F& visit, bool with_empty = false) {
634 std::size_t total = 1;
635 for (int c : cut) total *= static_cast<std::size_t>(c + 1);
636 const std::size_t K = cut.size();
637 for (std::size_t i = 0; i < total; ++i) {
638 std::vector<int> cnt(K, 0);
639 std::size_t li = i;
640 for (std::size_t d = 0; d < K; ++d) {
641 cnt[d] = static_cast<int>(li % static_cast<std::size_t>(cut[d] + 1));
642 li /= static_cast<std::size_t>(cut[d] + 1);
643 }
644 std::string key;
645 int tot = 0;
646 for (std::size_t d = 0; d < K; ++d) {
647 if (d) key += ',';
648 key += std::to_string(cnt[d]);
649 tot += cnt[d];
650 }
651 if (tot == 0 && !with_empty) continue; // an OI/PAS table omits the empty state
652 visit(cnt, key);
653 }
654}
655
656/**
657 * Enumerate the simplex 1 <= sum(n) <= cmax over K classes, calling
658 * `visit(counts, key)`. The extent Python `save_model` gives a non-saturating
659 * OI/PAS rate at a finite buffer, written with no `oiCutoffs`.
660 */
661template <class F>
662void for_each_simplex_point(std::size_t K, int cmax, const F& visit) {
663 for (int tot = 1; tot <= cmax; ++tot) {
664 std::vector<int> cnt(K, 0);
665 cnt[0] = tot;
666 while (true) {
667 std::string key;
668 for (std::size_t d = 0; d < K; ++d) {
669 if (d) key += ',';
670 key += std::to_string(cnt[d]);
671 }
672 visit(cnt, key);
673 // next composition: move one unit from the first nonzero part j < K-1
674 // to part j+1 and gather the remainder in part 0
675 std::size_t j = K;
676 for (std::size_t d = 0; d + 1 < K; ++d)
677 if (cnt[d] > 0) {
678 j = d;
679 break;
680 }
681 if (j == K) break;
682 const int v = cnt[j];
683 cnt[j] = 0;
684 ++cnt[j + 1];
685 cnt[0] = v - 1;
686 }
687 }
688}
689
690} // namespace detail
691
692/** The per-class saturation cutoffs of a count-indexed rate table. */
694 std::vector<int> tau; ///< tau(r): beyond it the function no longer changes with class-r jobs
695 bool bounded = true; ///< false when some tau(r) passed the search limit or reached cmax
696};
697
698/**
699 * Per-class saturation cutoffs of a count-indexed function f(n), the search
700 * behind the OI/PAS and class/joint-dependence table extents. Twin of Python
701 * `_saturation_cutoffs` (linemodel_io.py), MATLAB `saturation_cutoffs.m` and the
702 * JAR `LineModelIO.saturationCutoffs`.
703 *
704 * `f_at(n)` returns the values the writer would tabulate at the count vector n,
705 * ALREADY SANITIZED (non-finite -> 0), so the search compares what the table
706 * holds. Starting from tau = 1, a class whose extra job still changes f anywhere
707 * on the current box has its cutoff raised, until no class moves. Only pairs
708 * (m, m + e_r) with sum(m) + 1 <= cmax are compared: a state above the buffer is
709 * never visited, so whatever a reloaded table answers there cannot move the
710 * search, which is what makes save -> load -> save a fixed point. Passing
711 * `max_cutoff`, or a cutoff reaching cmax (where the box would be no smaller
712 * than the buffer), reports the function unbounded.
713 */
715 const std::function<std::vector<double>(const std::vector<int>&)>& f_at, std::size_t K,
716 double cmax = std::numeric_limits<double>::infinity(), int max_cutoff = 256,
717 double tol = 1e-9) {
718 PasSaturation out;
719 out.tau.assign(K, 1);
720 bool changed = true;
721 while (changed) {
722 changed = false;
723 for (std::size_t r = 0; r < K; ++r) {
724 // Every count vector with n(r) = tau(r) and n(j) <= tau(j) elsewhere.
725 std::size_t total = 1;
726 for (std::size_t j = 0; j < K; ++j)
727 if (j != r) total *= static_cast<std::size_t>(out.tau[j] + 1);
728 bool sat = true;
729 for (std::size_t li = 0; li < total && sat; ++li) {
730 std::vector<int> m(K, 0);
731 std::size_t rem = li;
732 int sum = 0;
733 for (std::size_t j = 0; j < K; ++j) {
734 if (j == r) {
735 m[j] = out.tau[r];
736 } else {
737 m[j] = static_cast<int>(rem % static_cast<std::size_t>(out.tau[j] + 1));
738 rem /= static_cast<std::size_t>(out.tau[j] + 1);
739 }
740 sum += m[j];
741 }
742 if (static_cast<double>(sum) + 1.0 > cmax) continue;
743 std::vector<int> mp(m);
744 ++mp[r];
745 const std::vector<double> a = f_at(mp), b = f_at(m);
746 double d = 0.0;
747 for (std::size_t k = 0; k < a.size() && k < b.size(); ++k)
748 d = std::max(d, std::fabs(a[k] - b[k]));
749 if (d > tol) sat = false;
750 }
751 if (!sat) {
752 ++out.tau[r];
753 changed = true;
754 if (out.tau[r] > max_cutoff) {
755 out.bounded = false;
756 return out;
757 }
758 }
759 }
760 }
761 for (std::size_t r = 0; r < K; ++r)
762 if (!(static_cast<double>(out.tau[r]) < cmax)) out.bounded = false;
763 return out;
764}
765
766/**
767 * The saturation cutoffs of an order-independent rate mu(c), searched over the
768 * states a buffer of `cmax` jobs can hold (see saturation_cutoffs). Port of the
769 * search in Python `save_model`. mu receives 1-BASED class tags, the convention
770 * of `sn.pasparam`, so the canonical list holds n(r) copies of r+1; a
771 * non-finite rate compares as 0, the value the table holds.
772 */
773template <class T>
775 const std::function<T(const std::vector<std::size_t>&)>& mu, std::size_t K,
776 double cmax = std::numeric_limits<double>::infinity()) {
777 return saturation_cutoffs(
778 [&mu, K](const std::vector<int>& n) {
779 std::vector<std::size_t> order;
780 for (std::size_t r = 0; r < K; ++r)
781 for (int c = 0; c < n[r]; ++c) order.push_back(r + 1);
782 const double v = num_traits<T>::to_double(mu(order));
783 return std::vector<double>(1, std::isfinite(v) ? v : 0.0);
784 },
785 K, cmax);
786}
787
788namespace detail {
789
790/** beta(n) as the writer tabulates it: a short row padded from its first entry, non-finite -> 0. */
791template <class T>
792std::vector<double> cd_scaling_at(const lang::CdScaling<T>& fun, const std::vector<int>& cnt,
793 std::size_t K) {
794 std::vector<T> n(K, num_traits<T>::from_int(0));
795 for (std::size_t r = 0; r < K; ++r) n[r] = num_traits<T>::from_int(static_cast<long>(cnt[r]));
796 const std::vector<T> v = fun(n);
797 std::vector<double> out(K, 0.0);
798 for (std::size_t r = 0; r < K; ++r) {
799 double x = 0.0;
800 if (v.size() == 1) x = num_traits<T>::to_double(v[0]);
801 else if (r < v.size()) x = num_traits<T>::to_double(v[r]);
802 out[r] = std::isfinite(x) ? x : 0.0;
803 }
804 return out;
805}
806
807/**
808 * Materialize a class/joint-dependence handle over the extent that reproduces
809 * it on every state the station can reach. Twin of Python `_cd_scaling_extent`.
810 *
811 * bb(r) = sn.classcap(ist, r) and C = sn.cap(ist), the per-class and total
812 * counts the station can hold (chain populations, declared buffers, class caps):
813 * - every bb finite, sum(bb) <= C: the box 0..bb with `cutoffs` = bb;
814 * - every bb finite, sum(bb) > C: the box truncated at sum(n) <= C and NO
815 * `cutoffs`, so the readers look the raw counts up;
816 * - some bb infinite (an open class at a station with no buffer): the
817 * saturation box 0..tau with `cutoffs` = tau when beta saturates, else the
818 * box with 10 for each unbounded class, with cutoffs (lossy above 10).
819 */
820template <class T>
821void cd_scaling_extent(const lang::CdScaling<T>& fun, std::size_t K, const std::vector<double>& bb,
822 double C, json& blk) {
823 const auto put = [&](json& tbl, const std::vector<int>& cnt, const std::string& key) {
824 tbl[key] = cd_scaling_at<T>(fun, cnt, K);
825 };
826 bool finite = true;
827 for (std::size_t r = 0; r < K; ++r) finite = finite && r < bb.size() && std::isfinite(bb[r]);
828 json tbl = json::object();
829 if (finite) {
830 std::vector<int> maxc(K, 0);
831 long tot = 0;
832 for (std::size_t r = 0; r < K; ++r) {
833 maxc[r] = static_cast<int>(std::floor(bb[r]));
834 tot += maxc[r];
835 }
836 const double cs = std::isfinite(C) ? std::floor(C) : C;
837 if (static_cast<double>(tot) <= cs) {
838 for_each_lattice_point(maxc, [&](const std::vector<int>& cnt, const std::string& key) {
839 put(tbl, cnt, key);
840 }, true);
841 blk["cutoffs"] = maxc;
842 } else {
843 for_each_lattice_point(maxc, [&](const std::vector<int>& cnt, const std::string& key) {
844 long s = 0;
845 for (int c : cnt) s += c;
846 if (static_cast<double>(s) <= cs) put(tbl, cnt, key);
847 }, true);
848 }
849 blk["scaling"] = tbl;
850 return;
851 }
852 const PasSaturation sat = saturation_cutoffs(
853 [&fun, K](const std::vector<int>& n) { return cd_scaling_at<T>(fun, n, K); }, K);
854 std::vector<int> maxc;
855 if (sat.bounded) {
856 maxc = sat.tau;
857 } else {
858 maxc.assign(K, 10);
859 for (std::size_t r = 0; r < K; ++r)
860 if (r < bb.size() && std::isfinite(bb[r])) maxc[r] = static_cast<int>(std::floor(bb[r]));
861 }
862 for_each_lattice_point(maxc, [&](const std::vector<int>& cnt, const std::string& key) {
863 put(tbl, cnt, key);
864 }, true);
865 blk["cutoffs"] = maxc;
866 blk["scaling"] = tbl;
867}
868
869} // namespace detail
870
871/**
872 * `qn::NetworkStruct` -> the model.json `model` object.
873 *
874 * Takes the struct rather than the `qn::Network` builder because that is what a
875 * solver holds, and because `get_struct()` is what the builder hands out.
876 */
877template <class T>
879 using detail::json;
880 typedef qn::NetworkStruct<T> SN;
881 const std::size_t K = sn.classes.size();
882 const std::vector<int> cut = detail::lattice_cutoffs(sn);
883
884 json model;
885 model["type"] = "Network";
886 model["name"] = sn.name;
887 // The directory every Logger writes into; model-level because that is where
888 // the reference keeps it and because a Logger's constructor refuses without it.
889 if (!sn.log_path.empty()) model["logPath"] = sn.log_path;
890
891 // -- classes --------------------------------------------------------------
892 json classes = json::array();
893 for (std::size_t r = 0; r < K; ++r) {
894 const qn::JobClass& c = sn.classes[r];
895 json cj;
896 cj["name"] = c.name;
897 // A G-network SIGNAL is written as its own wire type with the kind it
898 // removes under: written back as an ordinary class it becomes inert,
899 // and the reloaded model is a queueing network with no removals at all.
900 const bool sig = r < sn.issignal.size() && sn.issignal[r];
901 if (sig) {
902 cj["type"] = "Signal";
903 cj["openOrClosed"] = c.type == lang::JobClassType::CLOSED ? "Closed" : "Open";
904 const lang::SignalType st = sn.signaltype[r];
905 cj["signalType"] = st == lang::SignalType::REPLY
906 ? "reply"
907 : (st == lang::SignalType::CATASTROPHE ? "catastrophe"
908 : "negative");
909 if (sn.signaltarget[r] >= 1 && sn.signaltarget[r] <= K)
910 cj["targetClass"] = sn.classes[sn.signaltarget[r] - 1].name;
911 const lang::RemovalPolicy rp = sn.signalrempolicy[r];
913 cj["removalPolicy"] = rp == lang::RemovalPolicy::FCFS ? "FCFS" : "LCFS";
914 if (!sn.signalremdist[r].empty()) {
915 json pv = json::array();
916 for (const T& v : sn.signalremdist[r]) pv.push_back(num_traits<T>::to_double(v));
917 json xv = json::array();
918 // THE SUPPORT STARTS AT ZERO, unlike every other pmf written
919 // here: `signalremdist` is indexed BY BATCH SIZE, and a batch of
920 // zero is a real outcome. `discrete_support` numbers items from
921 // 1, so using it shifted every batch by one job on the way back
922 // through any reader that honours `x` -- MATLAB's included.
923 for (std::size_t b = 0; b < pv.size(); ++b) xv.push_back(static_cast<double>(b));
924 json rd;
925 rd["type"] = "DiscreteSampler";
926 rd["params"]["p"] = pv;
927 rd["params"]["x"] = xv;
928 cj["removalDistribution"] = rd;
929 }
930 } else {
931 cj["type"] = c.type == lang::JobClassType::CLOSED
932 ? (c.self_looping ? "SelfLooping" : "Closed")
933 : "Open";
934 }
936 // An integer, as linemodel_save.m and Python's save_model write it; a non-integral value is kept as written.
937 const double pop = c.population;
938 if (std::isfinite(pop) && pop == std::floor(pop) && std::fabs(pop) < 9.0e15)
939 cj["population"] = static_cast<long long>(pop);
940 else
941 cj["population"] = pop;
942 if (c.refstat == 0 || c.refstat > sn.station_to_node.size())
943 throw InputError("network_writer: class '" + c.name +
944 "' names no reference station, which a closed class must have");
945 cj["refNode"] = sn.nodes[sn.station_to_node[c.refstat - 1] - 1].name;
946 }
947 if (c.prio != 0) cj["priority"] = c.prio;
948 if (c.immfeed) cj["immediateFeedback"] = true;
949 if (c.is_ref_class) cj["isReferenceClass"] = true;
950 if (std::isfinite(c.deadline)) cj["deadline"] = c.deadline;
951 if (c.spawn >= 1 && c.spawn <= K) cj["spawnClass"] = sn.classes[c.spawn - 1].name;
952 if (r < sn.syncreply.size() && sn.syncreply[r] >= 1 && sn.syncreply[r] <= K)
953 cj["replySignalClass"] = sn.classes[sn.syncreply[r] - 1].name;
954 classes.push_back(cj);
955 }
956 model["classes"] = classes;
957
958 // -- nodes ----------------------------------------------------------------
959 json nodes = json::array();
960 for (std::size_t i = 0; i < sn.nodes.size(); ++i) {
961 const qn::NodeDef& nd = sn.nodes[i];
962 const std::size_t ind = i + 1, ist = nd.station;
963 json nj;
964 nj["name"] = nd.name;
965 // a Queue declared INF keeps its class on the wire, as linemodel_save writes isa(node,'Queue') nodes
966 nj["type"] = nd.queue_object ? "Queue" : detail::node_type_to_json(nd.nodetype);
967
968 if (nd.nodetype == lang::NodeType::Fork && nd.tasks_per_link > 1.0)
969 nj["tasksPerLink"] = nd.tasks_per_link;
970 // VARIABLE FORKING LEVELS, in the record shape `linemodel_save.m:509-553`
971 // writes: one {dest, class, value} per link rather than a matrix, since
972 // that is what the reader replays through the setters.
973 //
974 // Every link a class takes is listed, not only the ones the model
975 // overrode. The reader seeds an untouched link from `tasksPerLink`,
976 // which is the MEAN once an override exists, so a partial list would
977 // reload a fork that emits a count it was never given.
978 if (nd.nodetype == lang::NodeType::Fork) {
979 const qn::ForkParam<T>* fp = sn.fork_param_of(ind);
980 if (fp != 0) {
981 json by_dest = json::array(), by_prob = json::array(), by_dist = json::array();
982 for (std::size_t k = 0; k < fp->fan_out_link.rows(); ++k)
983 for (std::size_t r = 0; r < fp->fan_out_link.cols() && r < K; ++r) {
984 const double p = num_traits<T>::to_double(fp->fan_out_prob(k, r));
985 if (p == 0.0) continue; // link this class does not take
986 json rec;
987 rec["dest"] = sn.nodes[k].name;
988 rec["class"] = r + 1;
989 rec["value"] = num_traits<T>::to_double(fp->fan_out_link(k, r));
990 by_dest.push_back(rec);
991 if (p != 1.0) {
992 json pr;
993 pr["dest"] = sn.nodes[k].name;
994 pr["class"] = r + 1;
995 pr["value"] = p;
996 by_prob.push_back(pr);
997 }
998 const lang::Distrib<T>& d = fp->fan_out_dist[k][r];
999 if (!d.disabled) {
1000 json dr;
1001 dr["dest"] = sn.nodes[k].name;
1002 dr["class"] = r + 1;
1003 json pv = json::array(), xv = json::array();
1004 for (std::size_t e = 0; e < d.params.size(); ++e) {
1005 pv.push_back(num_traits<T>::to_double(d.params[e]));
1006 xv.push_back(d.trace.empty()
1007 ? static_cast<double>(e + 1)
1009 }
1010 dr["p"] = pv;
1011 dr["x"] = xv;
1012 by_dist.push_back(dr);
1013 }
1014 }
1015 if (!by_dest.empty()) nj["fanOutByDest"] = by_dest;
1016 if (!by_prob.empty()) nj["fanOutProb"] = by_prob;
1017 if (!by_dist.empty()) nj["fanOutDist"] = by_dist;
1018 }
1019 }
1020 // A Logger with no file name exports as a tunnel that logs nowhere, so
1021 // the name is what makes the node mean anything on reload.
1022 if (nd.nodetype == lang::NodeType::Logger && !nd.logger.file_name.empty())
1023 nj["fileName"] = nd.logger.file_name;
1024 // The trace columns and a per-node directory, written only where they leave the
1025 // defaults so the documents of existing models are unchanged; `network_reader` reads all.
1026 if (nd.nodetype == lang::NodeType::Logger) {
1027 const qn::NodeDef::LoggerParam& lg = nd.logger;
1028 const qn::NodeDef::LoggerParam def;
1029 if (!lg.file_path.empty()) nj["filePath"] = lg.file_path;
1030 if (lg.start_time != def.start_time) nj["startTime"] = lg.start_time;
1031 if (lg.logger_name != def.logger_name) nj["loggerName"] = lg.logger_name;
1032 if (lg.timestamp != def.timestamp) nj["timestamp"] = lg.timestamp;
1033 if (lg.job_id != def.job_id) nj["jobID"] = lg.job_id;
1034 if (lg.job_class != def.job_class) nj["jobClass"] = lg.job_class;
1035 if (lg.time_same_class != def.time_same_class) nj["timeSameClass"] = lg.time_same_class;
1036 if (lg.time_any_class != def.time_any_class) nj["timeAnyClass"] = lg.time_any_class;
1037 }
1038 if (nd.nodetype == lang::NodeType::Join) {
1039 typename std::map<std::size_t, std::pair<std::size_t, std::size_t> >::const_iterator fj;
1040 for (std::size_t f = 0; f < sn.fj.size(); ++f)
1041 if (sn.fj[f].second == ind)
1042 nj["forkNode"] = sn.nodes[sn.fj[f].first - 1].name;
1043 typename std::map<std::size_t, typename SN::JoinDecl>::const_iterator jd =
1044 sn.joindecl.find(ind);
1045 if (jd != sn.joindecl.end()) {
1046 if (jd->second.strategy == lang::JoinStrategy::PARTIAL)
1047 nj["joinStrategy"] = "PARTIAL";
1048 if (jd->second.quorum > 0) nj["joinQuorum"] = jd->second.quorum;
1049 }
1050 }
1051 {
1052 typename std::map<std::size_t, Matrix<T> >::const_iterator cs = sn.csmatrix.find(ind);
1053 if (cs != sn.csmatrix.end()) {
1054 json csm;
1055 for (std::size_t r = 0; r < K; ++r) {
1056 json row;
1057 for (std::size_t s = 0; s < K; ++s) {
1058 const double v = num_traits<T>::to_double(cs->second(r, s));
1059 if (v != 0.0) row[sn.classes[s].name] = v;
1060 }
1061 if (!row.empty()) csm[sn.classes[r].name] = row;
1062 }
1063 nj["classSwitchMatrix"] = csm;
1064 }
1065 }
1066 {
1067 typename std::map<std::size_t, qn::CacheParam<T> >::const_iterator cp =
1068 sn.nodeparam.find(ind);
1069 if (cp != sn.nodeparam.end()) {
1070 const qn::CacheParam<T>& c = cp->second;
1071 nj["numItems"] = c.nitems;
1072 nj["itemLevelCap"] = c.itemcap;
1073 nj["replacementStrategy"] = detail::replacement_to_json(c.replacestrat);
1074 if (num_traits<T>::to_double(c.qlru) != 1.0)
1075 nj["admissionProb"] = num_traits<T>::to_double(c.qlru);
1076 if (!c.itemsize.empty()) nj["itemSizes"] = c.itemsize;
1077 if (!c.costcap.empty()) {
1078 if (c.costcapglobal) nj["costCaps"] = c.costcap.empty() ? 0 : c.costcap[0];
1079 else nj["costCaps"] = c.costcap;
1080 }
1081 json pop, hit, miss, itemcls;
1082 for (std::size_t r = 0; r < K && r < c.pread.size(); ++r) {
1083 if (c.pread[r].empty()) continue;
1084 json pj;
1085 pj["type"] = "DiscreteSampler";
1086 pj["params"]["p"] = detail::vec_to_json(c.pread[r]);
1087 pj["params"]["x"] = detail::discrete_support(c.pread[r].size());
1088 pop[sn.classes[r].name] = pj;
1089 }
1090 for (std::size_t r = 0; r < K && r < c.hitclass.size(); ++r)
1091 if (c.hitclass[r] != 0)
1092 hit[sn.classes[r].name] = sn.classes[c.hitclass[r] - 1].name;
1093 for (std::size_t r = 0; r < K && r < c.missclass.size(); ++r)
1094 if (c.missclass[r] != 0)
1095 miss[sn.classes[r].name] = sn.classes[c.missclass[r] - 1].name;
1096 for (std::size_t r = 0; r < K && r < c.classitem.size(); ++r)
1097 if (c.classitem[r] != 0)
1098 itemcls[sn.classes[r].name] = static_cast<double>(c.classitem[r]);
1099 if (!pop.empty()) nj["popularity"] = pop;
1100 if (!hit.empty()) nj["hitClass"] = hit;
1101 if (!miss.empty()) nj["missClass"] = miss;
1102 if (!itemcls.empty()) nj["itemClass"] = itemcls;
1103 if (!c.accost.empty()) {
1104 json ap = json::array();
1105 for (const std::vector<Matrix<T> >& per_class : c.accost) {
1106 json row = json::array();
1107 for (const Matrix<T>& g : per_class)
1108 row.push_back(g.rows() == 0 ? json::array() : detail::mat_to_json(g));
1109 ap.push_back(row);
1110 }
1111 nj["accessProb"] = ap;
1112 }
1113 if (!c.initstate.empty()) nj["initialState"] = detail::vec_to_json(c.initstate);
1114 if (c.retrieval_capacity > 0 || !c.retrieval_queues.empty()) {
1115 json rs;
1116 rs["capacity"] = c.retrieval_capacity;
1117 json by;
1118 for (const auto& kv : c.retrieval_queues) {
1119 json entry;
1120 json qs = json::array();
1121 for (std::size_t q : kv.second) qs.push_back(sn.nodes[q - 1].name);
1122 entry["queues"] = qs;
1123 json items;
1124 for (std::size_t it = 0; it < c.retrieval_classes.size(); ++it)
1125 if (kv.first < c.retrieval_classes[it].size() &&
1126 c.retrieval_classes[it][kv.first] != 0)
1127 items[std::to_string(it)] =
1128 sn.classes[c.retrieval_classes[it][kv.first] - 1].name;
1129 entry["items"] = items;
1130 by[sn.classes[kv.first].name] = entry;
1131 }
1132 rs["byClass"] = by;
1133 nj["retrievalSystem"] = rs;
1134 }
1135 }
1136 }
1137 {
1138 typename std::map<std::size_t, std::vector<T> >::const_iterator im =
1139 sn.initmarking.find(ind);
1140 if (im != sn.initmarking.end()) nj["initialState"] = detail::vec_to_json(im->second);
1141 typename std::map<std::size_t, std::vector<T> >::const_iterator sp =
1142 sn.stateprior.find(ind);
1143 typename std::map<std::size_t, Matrix<T> >::const_iterator ss = sn.statespace.find(ind);
1144 if (sp != sn.stateprior.end() && ss != sn.statespace.end()) {
1145 nj["stateSpace"] = detail::mat_to_json(ss->second);
1146 nj["statePrior"] = detail::vec_to_json(sp->second);
1147 }
1148 }
1149
1150 if (ist != 0) {
1151 const qn::Station<T>& st = sn.stations[ist - 1];
1154 nj["scheduling"] = detail::sched_to_json(st.sched);
1155 // The server count of a multiserver Queue, and of a QUEUEING PLACE
1156 // whose embedded queue has more than one: the Place branch of the
1157 // reader defaults it to one, so a c > 1 that is not written here is
1158 // a c that does not survive the round trip.
1160 std::isfinite(st.nservers) && st.nservers > 1.0)
1161 nj["servers"] = st.nservers;
1162 if (std::isfinite(st.cap) && st.cap > 0) nj["buffer"] = st.cap;
1163 // A fluid place (FSPN) holds one level instead of tokens; PlaceCodec.m writes the bound and the
1164 // initial level only when they differ from the defaults (Inf, 0).
1165 if (nd.nodetype == lang::NodeType::Place && st.fluid) {
1166 nj["fluid"] = true;
1167 if (std::isfinite(st.fluidcap)) nj["fluidCapacity"] = st.fluidcap;
1168 if (st.fluidinit > 0.0) nj["fluidLevel"] = st.fluidinit;
1169 }
1170
1171 json svc, cc, dr, sp, imf;
1172 for (std::size_t r = 0; r < K; ++r) {
1173 if (ist - 1 < sn.service.size() && r < sn.service[ist - 1].size() &&
1174 !sn.service[ist - 1][r].disabled)
1175 svc[sn.classes[r].name] = detail::dist_to_json(sn.service[ist - 1][r]);
1176 if (r < st.classcap.size() && std::isfinite(st.classcap[r]))
1177 cc[sn.classes[r].name] = st.classcap[r];
1178 // 0 is the "the model declared none" sentinel of the station's
1179 // own vector, not a DropStrategy; `refresh_capacity` reads it
1180 // as `user_rule` for exactly that reason. Naming it would have
1181 // to invent a rule, so the entry is simply not written.
1182 if (r < st.droprule.size() && st.droprule[r] != 0)
1183 dr[sn.classes[r].name] =
1184 detail::drop_to_json(static_cast<lang::DropStrategy>(st.droprule[r]));
1185 if (r < st.immfeed.size() && st.immfeed[r]) imf[sn.classes[r].name] = true;
1186 }
1189 for (std::size_t r = 0; r < K && r < st.schedparam.size(); ++r)
1190 sp[sn.classes[r].name] = num_traits<T>::to_double(st.schedparam[r]);
1191 if (!svc.empty()) nj["service"] = svc;
1192 if (!cc.empty()) nj["classCap"] = cc;
1193 if (!dr.empty()) nj["dropRule"] = dr;
1194 if (!sp.empty()) nj["schedParams"] = sp;
1195 if (!imf.empty()) nj["immediateFeedback"] = imf;
1196
1197 if (!st.lldscaling.empty()) {
1198 json ld;
1199 ld["type"] = "loadDependent";
1200 ld["scaling"] = detail::vec_to_json(st.lldscaling);
1201 nj["loadDependence"] = ld;
1202 }
1203 // The two rate-scaling handles, materialized over the extent that
1204 // reproduces them on every reachable state (detail::cd_scaling_extent):
1205 // the only way a function reaches the wire.
1206 for (int kind = 0; kind < 2; ++kind) {
1207 const lang::CdScaling<T>& fun = kind == 0 ? st.cdscaling : st.jdscaling;
1208 if (!static_cast<bool>(fun)) continue;
1209 json blk;
1210 blk["type"] = kind == 0 ? "classDependent" : "jointDependent";
1211 std::vector<double> bb(K, std::numeric_limits<double>::infinity());
1212 if (ist - 1 < sn.classcap.size())
1213 for (std::size_t r = 0; r < K && r < sn.classcap[ist - 1].size(); ++r)
1214 bb[r] = sn.classcap[ist - 1][r];
1215 const double C = ist - 1 < sn.cap.size() ? sn.cap[ist - 1]
1216 : std::numeric_limits<double>::infinity();
1217 detail::cd_scaling_extent<T>(fun, K, bb, C, blk);
1218 blk["peak"] = detail::vec_to_json(kind == 0 ? st.cdscalingpeak : st.jdscalingpeak);
1219 nj[kind == 0 ? "classDependence" : "jointDependence"] = blk;
1220 }
1221 {
1222 typename std::map<std::size_t, typename SN::PasParam>::const_iterator pas =
1223 sn.pasparam.find(ist);
1224 if (pas != sn.pasparam.end() && static_cast<bool>(pas->second.svc_rate_fun)) {
1225 // The extent of Python `save_model`: the saturation box with
1226 // `oiCutoffs` when mu saturates, else the simplex up to the
1227 // declared buffer with no cutoffs. Unbounded and uncapped saves
1228 // over the population box, exact only when every class is closed
1229 // with a finite population; an open class would be clamped at 10
1230 // and read back wrong, so it is refused with Python's message.
1231 json tbl;
1232 const auto put = [&](const std::vector<int>& cnt, const std::string& key) {
1233 std::vector<std::size_t> micro;
1234 for (std::size_t r = 0; r < K; ++r)
1235 for (int c = 0; c < cnt[r]; ++c) micro.push_back(r + 1);
1236 const double v = num_traits<T>::to_double(pas->second.svc_rate_fun(micro));
1237 tbl[key] = std::isfinite(v) ? v : 0.0; // the writers' encoding of an undefined rate
1238 };
1239 // The search reads only the states the declared buffer can hold,
1240 // so a reloaded table, whatever it answers above the buffer,
1241 // yields the same document (save -> load -> save fixed point).
1242 const double cmax = std::isfinite(st.cap)
1243 ? std::max(std::floor(st.cap), 1.0)
1244 : std::numeric_limits<double>::infinity();
1245 const PasSaturation sat =
1246 pas_saturation_cutoffs<T>(pas->second.svc_rate_fun, K, cmax);
1247 if (sat.bounded) {
1248 detail::for_each_lattice_point(sat.tau, put);
1249 nj["oiServiceRate"] = tbl;
1250 nj["oiCutoffs"] = sat.tau;
1251 } else if (std::isfinite(st.cap)) {
1252 detail::for_each_simplex_point(
1253 K, std::max(static_cast<int>(std::floor(st.cap)), 1), put);
1254 nj["oiServiceRate"] = tbl;
1255 } else {
1256 for (std::size_t r = 0; r < K; ++r)
1257 if (sn.classes[r].type != lang::JobClassType::CLOSED ||
1258 !std::isfinite(sn.classes[r].population))
1259 throw InputError("PAS station '" + st.name +
1260 "' has an unbounded order-independent service rate (mu does not "
1261 "saturate) and no finite buffer; call setCap(N) on the station.");
1262 detail::for_each_lattice_point(cut, put);
1263 nj["oiServiceRate"] = tbl;
1264 nj["oiCutoffs"] = cut;
1265 }
1266 bool any_swap = false;
1267 for (const std::vector<bool>& row : pas->second.swap_graph)
1268 for (bool v : row) any_swap = any_swap || v;
1269 if (any_swap) {
1270 json sg = json::array();
1271 for (const std::vector<bool>& row : pas->second.swap_graph) {
1272 json rj = json::array();
1273 for (bool v : row) rj.push_back(v ? 1 : 0);
1274 sg.push_back(rj);
1275 }
1276 nj["swapGraph"] = sg;
1277 }
1278 }
1279 }
1280 // TWO APIS DECLARE A POLLING CONTROLLER: `set_polling` fills
1281 // `sn.pollingparam`, setPollingType / setSwitchover fill the Station
1282 // fields (see `NetworkStruct::effective_polling`, which prefers the
1283 // former). Writing only the Station fields saved a `set_polling`
1284 // model as no controller at all, so it reloaded as EXHAUSTIVE with
1285 // immediate switchovers. The wire has one spelling for both: the
1286 // type by NAME, `pollingPar` only under KLIMITED/GLIMITED, and one
1287 // `switchoverTimes` entry per buffer the server LEAVES.
1288 const bool via_param = st.sched == lang::SchedStrategy::POLLING &&
1289 sn.pollingparam.find(ist) != sn.pollingparam.end();
1290 const std::vector<lang::Distrib<T> >& so_buf =
1291 via_param ? sn.pollingparam.find(ist)->second.switchover : st.switchover;
1292 if (via_param) {
1293 const typename qn::NetworkStruct<T>::PollingParam& pp =
1294 sn.pollingparam.find(ist)->second;
1295 nj["pollingType"] = detail::polling_to_json(pp.ptype);
1297 nj["pollingPar"] = pp.pk;
1298 } else if (!st.polling_type.empty()) {
1299 nj["pollingType"] = detail::polling_to_json(st.polling_type[0]);
1300 if (st.polling_par != 0) nj["pollingPar"] = st.polling_par;
1301 }
1302 {
1303 // One key, two shapes, as `linemodel_save` writes them: under
1304 // POLLING an entry names the buffer the server LEAVES and
1305 // carries no `to`; otherwise it names the ordered class PAIR.
1306 json so = json::array();
1307 for (std::size_t r = 0; r < K && r < so_buf.size(); ++r) {
1308 if (so_buf[r].disabled) continue;
1309 json e;
1310 e["from"] = sn.classes[r].name;
1311 e["distribution"] = detail::dist_to_json(so_buf[r]);
1312 so.push_back(e);
1313 }
1314 for (std::size_t r = 0; r < K && r < st.switchover_pair.size(); ++r)
1315 for (std::size_t c = 0; c < K && c < st.switchover_pair[r].size(); ++c) {
1316 if (st.switchover_pair[r][c].disabled) continue;
1317 json e;
1318 e["from"] = sn.classes[r].name;
1319 e["to"] = sn.classes[c].name;
1320 e["distribution"] = detail::dist_to_json(st.switchover_pair[r][c]);
1321 so.push_back(e);
1322 }
1323 if (!so.empty()) nj["switchoverTimes"] = so;
1324 }
1325 if (st.sched == lang::SchedStrategy::RR) {
1326 // Round robin: the per-class time slice, {className: distribution},
1327 // as `linemodel_save` writes it.
1328 json qm = json::object();
1329 for (std::size_t r = 0; r < K && r < st.quantum.size(); ++r) {
1330 if (st.quantum[r].disabled) continue;
1331 qm[sn.classes[r].name] = detail::dist_to_json(st.quantum[r]);
1332 }
1333 if (!qm.empty()) nj["quantum"] = qm;
1334 }
1336 // Polling table, load-dependent order and visit timers, classes
1337 // by name, as linemodel_save writes them.
1338 if (!st.polling_table.empty()) {
1339 json tab = json::array();
1340 for (std::size_t t = 0; t < st.polling_table.size(); ++t) {
1341 json te;
1342 te["class"] = sn.classes[st.polling_table[t] - 1].name;
1343 if (t < st.polling_table_sw.size() && !st.polling_table_sw[t].disabled)
1344 te["switchover"] = detail::dist_to_json(st.polling_table_sw[t]);
1345 tab.push_back(te);
1346 }
1347 nj["pollingTable"] = tab;
1348 }
1350 nj["pollingOrder"] = detail::polling_order_to_json(st.polling_order);
1352 nj["pollingOrderClass"] = sn.classes[st.polling_order_class - 1].name;
1353 nj["pollingOrderThreshold"] = st.polling_order_threshold;
1354 }
1355 }
1357 json tm;
1358 tm["scope"] = st.polling_timer_scope == lang::PollingTimer::GLOBAL ? "GLOBAL" : "LOCAL";
1359 tm["preemptive"] = st.polling_timer_preempt;
1360 json td = json::array();
1361 for (std::size_t r = 0; r < K && r < st.polling_timer.size(); ++r) {
1362 if (st.polling_timer[r].disabled) continue;
1363 json e;
1364 e["class"] = sn.classes[r].name;
1365 e["distribution"] = detail::dist_to_json(st.polling_timer[r]);
1366 td.push_back(e);
1367 }
1368 tm["distributions"] = td;
1369 nj["pollingTimer"] = tm;
1370 }
1371 }
1372 {
1373 typename std::map<std::size_t, qn::SetupDelayOffParam<T> >::const_iterator sd =
1374 sn.setupparam.find(ist);
1375 if (sd != sn.setupparam.end()) {
1376 json su, doff;
1377 for (std::size_t r = 0; r < K && r < sd->second.setup.size(); ++r) {
1378 if (sd->second.setup[r].disabled) continue;
1379 su[sn.classes[r].name] = detail::dist_to_json(sd->second.setup[r]);
1380 doff[sn.classes[r].name] = detail::dist_to_json(sd->second.delayoff[r]);
1381 }
1382 if (!su.empty()) {
1383 nj["setupTime"] = su;
1384 nj["delayOffTime"] = doff;
1385 }
1386 }
1387 }
1388 {
1389 // Server breakdown, in `linemodel_save`'s shape: the two clocks
1390 // always, and `downService` keyed by class name only where a
1391 // degraded rate was declared. A zero rate is an ABSENT entry and
1392 // not a zero-mean distribution, which has no reading.
1393 typename std::map<std::size_t, qn::BreakdownParam<T> >::const_iterator bd =
1394 sn.breakdownparam.find(ist);
1395 if (bd != sn.breakdownparam.end()) {
1396 json bj;
1397 bj["failure"] = detail::dist_to_json(bd->second.failure);
1398 bj["repair"] = detail::dist_to_json(bd->second.repair);
1399 json ds;
1400 for (std::size_t r = 0; r < K && r < bd->second.down_service_rates.size(); ++r) {
1401 const double rate =
1402 num_traits<T>::to_double(bd->second.down_service_rates[r]);
1403 if (!(rate > 0.0)) continue;
1404 ds[sn.classes[r].name] = detail::dist_to_json(
1406 }
1407 if (!ds.empty()) bj["downService"] = ds;
1408 nj["breakdown"] = bj;
1409 }
1410 }
1411 {
1412 typename std::map<std::size_t, qn::RetrialParam<T> >::const_iterator rt =
1413 sn.retrialparam.find(ist);
1414 if (rt != sn.retrialparam.end()) {
1415 json rj;
1416 for (std::size_t r = 0; r < K && r < rt->second.retrial_proc.size(); ++r) {
1417 if (rt->second.retrial_proc[r].disabled) continue;
1418 json e;
1419 e["delay"] = detail::dist_to_json(rt->second.retrial_proc[r]);
1420 e["maxAttempts"] = rt->second.max_attempts[r];
1421 if (r < rt->second.policy.size() && rt->second.policy[r] == 2)
1422 e["policy"] = "constant";
1423 if (r < rt->second.max_orbit.size() && rt->second.max_orbit[r] >= 0)
1424 e["maxOrbit"] = rt->second.max_orbit[r];
1425 // non-persistence (p, q) and orbital search, only when not default
1426 {
1427 const qn::Station<T>& rst = sn.stations[ist - 1];
1428 const double jp = num_traits<T>::to_double(rst.orbit_join_of(r));
1429 const double pp = num_traits<T>::to_double(rst.orbit_persist_of(r));
1430 const double sp = num_traits<T>::to_double(rst.orbit_search_of(r));
1431 if (jp < 1.0) e["joinProb"] = jp;
1432 if (pp < 1.0) e["persistProb"] = pp;
1433 if (sp > 0.0) e["searchProb"] = sp;
1434 }
1435 rj[sn.classes[r].name] = e;
1436 }
1437 if (!rj.empty()) nj["retrial"] = rj;
1438 }
1439 }
1440 {
1441 json pat, orb, brp, blk;
1442 for (std::size_t r = 0; r < K; ++r) {
1443 if (r < st.patience.size() && !st.patience[r].disabled) {
1444 json e;
1445 e["distribution"] = detail::dist_to_json(st.patience[r]);
1446 if (r < st.impatience.size() &&
1448 e["impatienceType"] = detail::impatience_to_json(st.impatience[r]);
1449 pat[sn.classes[r].name] = e;
1450 }
1451 if (r < st.orbit_impatience.size() && !st.orbit_impatience[r].disabled)
1452 orb[sn.classes[r].name] = detail::dist_to_json(st.orbit_impatience[r]);
1453 if (r < st.batch_reject.size() &&
1455 brp[sn.classes[r].name] = num_traits<T>::to_double(st.batch_reject[r]);
1456 if (r < st.balking.size() &&
1457 st.balking[r].strategy != lang::BalkingStrategy::NONE) {
1458 json e;
1459 e["strategy"] = detail::balking_to_json(st.balking[r].strategy);
1460 json ths = json::array();
1461 for (const typename qn::Station<T>::BalkingThreshold& th :
1462 st.balking[r].thresholds) {
1463 json tj;
1464 tj["minJobs"] = th.min_jobs;
1465 tj["maxJobs"] = th.max_jobs;
1466 tj["probability"] = num_traits<T>::to_double(th.probability);
1467 ths.push_back(tj);
1468 }
1469 e["thresholds"] = ths;
1470 blk[sn.classes[r].name] = e;
1471 }
1472 }
1473 if (!pat.empty()) nj["patience"] = pat;
1474 if (!orb.empty()) nj["orbitImpatience"] = orb;
1475 if (!brp.empty()) nj["batchRejectProb"] = brp;
1476 if (!blk.empty()) nj["balking"] = blk;
1477 }
1478 if (!st.server_types.empty()) {
1479 json sts = json::array();
1480 for (const typename qn::Station<T>::ServerType& t : st.server_types) {
1481 json tj;
1482 tj["name"] = t.name;
1483 tj["count"] = t.count;
1484 if (!t.compatible.empty()) {
1485 json cn = json::array();
1486 for (std::size_t r = 0; r < K && r < t.compatible.size(); ++r)
1487 if (t.compatible[r]) cn.push_back(sn.classes[r].name);
1488 tj["compatibleClasses"] = cn;
1489 }
1490 json sv;
1491 for (std::size_t r = 0; r < K && r < t.service.size(); ++r)
1492 if (!t.service[r].disabled)
1493 sv[sn.classes[r].name] = detail::dist_to_json(t.service[r]);
1494 if (!sv.empty()) tj["service"] = sv;
1495 sts.push_back(tj);
1496 }
1497 nj["serverTypes"] = sts;
1499 nj["heteroSchedPolicy"] = detail::hetero_to_json(st.hetero_policy);
1500 }
1501 {
1502 json par;
1503 for (std::size_t r = 0; r < K && r < st.server_parallelism.size(); ++r)
1504 if (st.server_parallelism[r] > 1)
1505 par[sn.classes[r].name] = st.server_parallelism[r];
1506 if (!par.empty()) nj["serverParallelism"] = par;
1507 }
1508 {
1509 json ab;
1510 for (std::size_t r = 0; r < K && r < st.arrival_batch.size(); ++r)
1511 if (!st.arrival_batch[r].disabled)
1512 ab[sn.classes[r].name] = detail::dist_to_json(st.arrival_batch[r]);
1513 if (!ab.empty()) nj["arrivalBatch"] = ab;
1514 if (!st.marked_classes.empty()) {
1515 json mc = json::array();
1516 for (std::size_t c : st.marked_classes) mc.push_back(sn.classes[c - 1].name);
1517 nj["markedClasses"] = mc;
1518 }
1519 json dd;
1520 for (std::size_t r = 0; r < K && r < st.departure_discipline.size(); ++r)
1522 dd[sn.classes[r].name] = "FIFO";
1523 if (!dd.empty()) nj["departureDiscipline"] = dd;
1524 }
1525 }
1526
1527 {
1528 typename std::map<std::size_t, qn::TransitionParam<T> >::const_iterator tp =
1529 sn.transparam.find(ind);
1530 if (tp != sn.transparam.end()) {
1531 json modes = json::array();
1532 for (std::size_t m = 0; m < tp->second.nmodes; ++m) {
1533 json mj;
1534 mj["name"] = tp->second.modenames[m];
1535 mj["timingStrategy"] =
1536 tp->second.timing[m] == lang::TimingStrategy::IMMEDIATE ? "IMMEDIATE"
1537 : "TIMED";
1538 if (!tp->second.firingproc[m].disabled)
1539 mj["distribution"] = detail::dist_to_json(tp->second.firingproc[m]);
1540 mj["numServers"] = tp->second.nmodeservers[m];
1541 mj["firingPriority"] = tp->second.firingprio[m];
1542 mj["firingWeight"] = num_traits<T>::to_double(tp->second.fireweight[m]);
1543 const char* kArcKey[3] = {"enablingConditions", "inhibitingConditions",
1544 "firingOutcomes"};
1545 for (int which = 0; which < 3; ++which) {
1546 const Matrix<T>& row = which == 0 ? tp->second.enabling[m]
1547 : which == 1 ? tp->second.inhibiting[m]
1548 : tp->second.firing[m];
1549 json arcs = json::array();
1550 for (std::size_t q = 0; q < row.rows(); ++q)
1551 for (std::size_t r = 0; r < row.cols(); ++r) {
1552 const double v = num_traits<T>::to_double(row(q, r));
1553 // An inhibiting threshold of Inf is "never
1554 // blocks" and an enabling or firing count of 0
1555 // is no arc.
1556 if (which == 1 ? !std::isfinite(v) : v == 0.0) continue;
1557 json a;
1558 a["node"] = sn.nodes[q].name;
1559 // REQUIRED by the reference readers: both index
1560 // the arc by (node, CLASS) -- `linemodel_load.m:
1561 // 852` reads `ec.class` unguarded and
1562 // `linemodel_io.py` does `ic["class"]` -- so an
1563 // arc written without it makes the whole
1564 // document unloadable there.
1565 a["class"] = sn.classes[r].name;
1566 a["count"] = v;
1567 arcs.push_back(a);
1568 }
1569 if (!arcs.empty()) mj[kArcKey[which]] = arcs;
1570 }
1571 // A marking-dependent firing rate is a CLOSURE, so it is
1572 // written the only way it can cross JSON: materialized over
1573 // the box lattice of every class of every input place of the
1574 // mode (the documented domain of g: a class-A mode may read the
1575 // class-B count of its input place, and the enabling slots
1576 // alone flattened such a g to g(0)), exactly as
1577 // `firingdep_scaling_table` in linemodel_save.m does. Dropped
1578 // instead, the net reloads at its nominal rate -- a different
1579 // marking process, reported without a diagnostic.
1580 if (m < tp->second.firingdep.size() && tp->second.firingdep[m]) {
1581 const Matrix<T>& enab = tp->second.enabling[m];
1582 json slots = json::array();
1583 std::vector<std::size_t> slot_pos;
1584 std::vector<long> caps;
1585 // ONE SLOT PER (input place, class), place-major and class-minor, as linemodel_save.m
1586 // writes it; the closure's domain is the node-major flattened (node, class) marking
1587 // `state_events.h` hands it. A slot is cut off at the place capacity, at a closed class's
1588 // population and at 10 tokens for an open class in an unbounded place (markingSlots).
1589 const std::size_t KW = sn.classes.size();
1590 const std::vector<double> popw = sn.njobs();
1591 for (std::size_t q = 0; q < enab.rows(); ++q) {
1592 bool is_input = false;
1593 for (std::size_t rq = 0; rq < enab.cols(); ++rq)
1594 if (num_traits<T>::to_double(enab(q, rq)) > 0.0) is_input = true;
1595 if (!is_input) continue;
1596 const std::size_t sq = sn.nodes[q].station;
1597 const double pc = sq == 0 ? std::numeric_limits<double>::infinity()
1598 : sn.stations[sq - 1].cap;
1599 for (std::size_t rq = 0; rq < KW; ++rq) {
1600 json sm;
1601 sm["node"] = sn.nodes[q].name;
1602 sm["class"] = sn.classes[rq].name;
1603 slots.push_back(sm);
1604 slot_pos.push_back(q * KW + rq);
1605 const double cc = rq < popw.size() && std::isfinite(popw[rq]) ? popw[rq] : 10.0;
1606 caps.push_back(std::lround(std::min(pc, cc)));
1607 }
1608 }
1609 if (!slots.empty()) {
1610 json frm;
1611 frm["slots"] = slots;
1612 frm["cutoffs"] = caps;
1613 json scaling;
1614 std::size_t total = 1;
1615 for (std::size_t s = 0; s < caps.size(); ++s)
1616 total *= static_cast<std::size_t>(caps[s]) + 1;
1617 std::vector<T> mk(sn.nodes.size() * KW, num_traits<T>::from_int(0));
1618 for (std::size_t li = 0; li < total; ++li) {
1619 std::size_t rem = li;
1620 std::string key;
1621 for (std::size_t s = 0; s < caps.size(); ++s) {
1622 const std::size_t shp = static_cast<std::size_t>(caps[s]) + 1;
1623 const std::size_t c = rem % shp;
1624 rem /= shp;
1625 mk[slot_pos[s]] = num_traits<T>::from_int(
1626 static_cast<long>(c));
1627 if (s) key += ',';
1628 key += std::to_string(c);
1629 }
1630 const double v =
1631 num_traits<T>::to_double(tp->second.firingdep[m](mk));
1632 scaling[key] = std::isfinite(v) ? v : 0.0;
1633 }
1634 for (std::size_t s = 0; s < slot_pos.size(); ++s)
1635 mk[slot_pos[s]] = num_traits<T>::from_int(0);
1636 frm["scaling"] = scaling;
1637 mj["firingRateDependence"] = frm;
1638 }
1639 }
1640 // Fluid arcs (FSPN), each naming its fluid place, as TransitionCodec.m writes them.
1641 const qn::TransitionParam<T>& ftp = tp->second;
1642 if (!ftp.fluid_rates(m).empty()) {
1643 json lst = json::array();
1644 for (const auto& a : ftp.fluid_rates(m)) {
1645 json e;
1646 e["node"] = sn.nodes[a.node - 1].name;
1647 e["rate"] = a.value;
1648 lst.push_back(e);
1649 }
1650 mj["fluidRates"] = lst;
1651 }
1652 if (!ftp.fluid_guards(m).empty()) {
1653 json lst = json::array();
1654 for (const auto& g : ftp.fluid_guards(m)) {
1655 json e;
1656 e["node"] = sn.nodes[g.node - 1].name;
1657 e["op"] = g.sgn > 0 ? ">=" : "<=";
1658 e["threshold"] = g.thr;
1659 lst.push_back(e);
1660 }
1661 mj["fluidGuards"] = lst;
1662 }
1663 if (!ftp.fluid_impulses(m).empty()) {
1664 json lst = json::array();
1665 for (const auto& a : ftp.fluid_impulses(m)) {
1666 json e;
1667 e["node"] = sn.nodes[a.node - 1].name;
1668 e["delta"] = a.value;
1669 lst.push_back(e);
1670 }
1671 mj["fluidImpulses"] = lst;
1672 }
1673 // A level-dependent multiplier is a closure, so it crosses JSON as `fluiddep_table`: 201 equally
1674 // spaced levels on [0, L] and h at each, L being `fluidTableRange` of TransitionCodec.m.
1675 if (!ftp.fluid_deps(m).empty()) {
1676 json lst = json::array();
1677 for (const auto& d : ftp.fluid_deps(m)) {
1678 const std::size_t sq = sn.nodes[d.node - 1].station;
1679 const qn::Station<T>& fst = sn.stations[sq - 1];
1680 double L = fst.fluidcap;
1681 if (!std::isfinite(L)) {
1682 L = std::max(1.0, fst.fluidinit);
1683 for (const auto& kv : sn.transparam)
1684 for (std::size_t mm = 0; mm < kv.second.nmodes; ++mm)
1685 for (const auto& g : kv.second.fluid_guards(mm))
1686 if (g.node == d.node) L = std::max(L, std::fabs(g.thr));
1687 L = std::max(10.0, 10.0 * L);
1688 }
1689 const std::size_t npts = 201;
1690 json levels = json::array(), values = json::array();
1691 for (std::size_t i = 0; i < npts; ++i) {
1692 const double lv = L * static_cast<double>(i) / static_cast<double>(npts - 1);
1693 levels.push_back(lv);
1694 values.push_back(d.fun(lv));
1695 }
1696 json e;
1697 e["node"] = sn.nodes[d.node - 1].name;
1698 e["levels"] = levels;
1699 e["values"] = values;
1700 lst.push_back(e);
1701 }
1702 mj["fluidRateDependence"] = lst;
1703 }
1704 // A marking-dependent flow multiplier is a closure too, materialized like firingRateDependence over
1705 // the box lattice of its (read place, class) slots, place-major and class-minor, slot 0 fastest.
1706 // A slot is cut off at the place capacity, at a closed class's population, and at 10 tokens for
1707 // an open class in an unbounded place, as TransitionCodec.markingSlots does.
1708 if (!ftp.fluid_flow_deps(m).empty()) {
1709 const std::vector<double> pop = sn.njobs();
1710 const std::size_t KF = sn.classes.size();
1711 json lst = json::array();
1712 for (const auto& fd : ftp.fluid_flow_deps(m)) {
1713 json slots = json::array(), readn = json::array();
1714 std::vector<std::size_t> sflat;
1715 std::vector<long> caps;
1716 for (std::size_t q : fd.read) {
1717 readn.push_back(sn.nodes[q - 1].name);
1718 const std::size_t sq = sn.nodes[q - 1].station;
1719 const double pc = sq == 0 ? std::numeric_limits<double>::infinity()
1720 : sn.stations[sq - 1].cap;
1721 for (std::size_t r = 0; r < KF; ++r) {
1722 json sm;
1723 sm["node"] = sn.nodes[q - 1].name;
1724 sm["class"] = sn.classes[r].name;
1725 slots.push_back(sm);
1726 sflat.push_back((q - 1) * KF + r);
1727 const double cc = r < pop.size() && std::isfinite(pop[r]) ? pop[r] : 10.0;
1728 caps.push_back(std::lround(std::min(pc, cc)));
1729 }
1730 }
1731 std::size_t total = 1;
1732 for (long c : caps) total *= static_cast<std::size_t>(c) + 1;
1733 std::vector<double> mk(sn.nodes.size() * KF, 0.0);
1734 json scaling = json::object();
1735 for (std::size_t li = 0; li < total; ++li) {
1736 std::size_t rem = li;
1737 std::string key;
1738 for (std::size_t s = 0; s < caps.size(); ++s) {
1739 const std::size_t shp = static_cast<std::size_t>(caps[s]) + 1;
1740 const std::size_t c = rem % shp;
1741 rem /= shp;
1742 mk[sflat[s]] = static_cast<double>(c);
1743 if (s) key += ',';
1744 key += std::to_string(c);
1745 }
1746 const double v = fd.fun(mk);
1747 scaling[key] = std::isfinite(v) ? v : 0.0;
1748 }
1749 json e;
1750 e["node"] = sn.nodes[fd.node - 1].name;
1751 e["read"] = readn;
1752 e["slots"] = slots;
1753 e["cutoffs"] = caps;
1754 e["scaling"] = scaling;
1755 lst.push_back(e);
1756 }
1757 mj["fluidFlowDependence"] = lst;
1758 }
1759 modes.push_back(mj);
1760 }
1761 nj["modes"] = modes;
1762 }
1763 }
1764 nodes.push_back(nj);
1765 }
1766 model["nodes"] = nodes;
1767
1768 // -- routing --------------------------------------------------------------
1769 json matrix;
1770 for (const auto& kv : sn.P) {
1771 const std::size_t r = kv.first.first, s = kv.first.second;
1772 json from_to;
1773 for (std::size_t a = 0; a < kv.second.rows(); ++a) {
1774 json row;
1775 for (std::size_t b = 0; b < kv.second.cols(); ++b) {
1776 const double p = num_traits<T>::to_double(kv.second(a, b));
1777 if (p != 0.0) row[sn.nodes[b].name] = p;
1778 }
1779 if (!row.empty()) from_to[sn.nodes[a].name] = row;
1780 }
1781 if (!from_to.empty())
1782 matrix[sn.classes[r - 1].name + "," + sn.classes[s - 1].name] = from_to;
1783 }
1784 json routing;
1785 routing["type"] = "matrix";
1786 routing["matrix"] = matrix;
1787 model["routing"] = routing;
1788
1789 json strategies, weights, params;
1790 for (std::size_t i = 0; i < sn.nodes.size(); ++i) {
1791 const qn::NodeDef& nd = sn.nodes[i];
1792 json per_class, per_class_w, per_class_p;
1793 for (std::size_t r = 0; r < K && r < nd.routing.size(); ++r) {
1794 // PROB is the matrix itself; RAND is DECLARED not derived, and dropping it wrote JMT's Empirical strategy where the model asks for Random.
1796 per_class[sn.classes[r].name] = detail::routing_to_json(nd.routing[r]);
1797 if (r < nd.routing_weights.size() && !nd.routing_weights[r].empty()) {
1798 json dw;
1799 for (const auto& kv : nd.routing_weights[r]) dw[sn.nodes[kv.first - 1].name] = kv.second;
1800 per_class_w[sn.classes[r].name] = dw;
1801 }
1802 if (r < nd.routing_param.size() && nd.routing_param[r] != 0) {
1803 json pj;
1804 pj["d"] = nd.routing_param[r];
1805 per_class_p[sn.classes[r].name] = pj;
1806 }
1807 }
1808 if (!per_class.empty()) strategies[nd.name] = per_class;
1809 if (!per_class_w.empty()) weights[nd.name] = per_class_w;
1810 if (!per_class_p.empty()) params[nd.name] = per_class_p;
1811 }
1812 if (!strategies.empty()) model["routingStrategies"] = strategies;
1813 if (!weights.empty()) model["routingWeights"] = weights;
1814 if (!params.empty()) model["routingParams"] = params;
1815
1816 // Krzesinski state-dependent routing. Every centre travels by NODE NAME, so
1817 // the block is language independent and a node reordering on either side
1818 // cannot shift a centre. Branch index 1 denotes the complement M-V and is
1819 // written as an empty list, keeping the paper's own numbering.
1820 // See _kb/16-state-dependent-routing.md
1821 if (!sn.sdr_nodes.empty()) {
1822 const pfqn::SdrStruct& sd = sn.sdr_nodes; // 0-based NODE indices
1823 std::size_t cls = 0;
1824 for (std::size_t r = 0; r < K && cls == 0; ++r)
1825 if (sn.nodes[sd.entry].routing.size() > r &&
1826 sn.nodes[sd.entry].routing[r] == lang::RoutingStrategy::SDR)
1827 cls = r + 1;
1828 if (cls == 0)
1829 throw InputError("network_writer: the model declares state-dependent routing at node '" +
1830 sn.nodes[sd.entry].name + "' but no class routes SDR there");
1831 json sdr;
1832 sdr["entry"] = sn.nodes[sd.entry].name;
1833 sdr["departure"] = sn.nodes[sd.departure].name;
1834 sdr["class"] = sn.classes[cls - 1].name;
1835 json branches = json::array();
1836 for (std::size_t b = 0; b < sd.branch.size(); ++b) {
1837 json bn = json::array();
1838 for (std::size_t q = 0; q < sd.branch[b].size(); ++q)
1839 bn.push_back(sn.nodes[sd.branch[b][q]].name);
1840 branches.push_back(bn);
1841 }
1842 sdr["branches"] = branches;
1843 json level = json::array(), Cs = json::array(), dm = json::array();
1844 for (std::size_t b = 0; b < sd.level.size(); ++b)
1845 level.push_back(static_cast<double>(sd.level[b]));
1846 for (std::size_t t = 0; t < sd.C.size(); ++t) Cs.push_back(sd.C[t]);
1847 for (std::size_t t = 0; t < sd.d.rows(); ++t) {
1848 json row = json::array();
1849 for (std::size_t b = 0; b < sd.d.cols(); ++b) row.push_back(sd.d(t, b));
1850 dm.push_back(row);
1851 }
1852 sdr["level"] = level;
1853 sdr["C"] = Cs;
1854 sdr["d"] = dm;
1855 model["stateDepRouting"] = sdr;
1856 }
1857
1858 // -- finite capacity regions ---------------------------------------------
1859 if (!sn.regions.empty()) {
1860 json fcr = json::array();
1861 for (std::size_t g = 0; g < sn.regions.size(); ++g) {
1862 const typename SN::Region& rg = sn.regions[g];
1863 json rj;
1864 rj["name"] = rg.name.empty() ? "Region" + std::to_string(g + 1) : rg.name;
1865 json stations = json::array();
1866 double global = -1.0, globalmem = -1.0;
1867 json class_cap, class_size, class_weight;
1868 for (std::size_t m = 0; m < rg.members.size(); ++m) {
1869 if (!rg.members[m]) continue;
1870 json sj;
1871 sj["node"] = sn.nodes[sn.station_to_node[m] - 1].name;
1872 stations.push_back(sj);
1873 global = rg.cap[m][K];
1874 // The region's global MEMORY budget, which is enforced beside the
1875 // job cap by the CTMC, the loss-network NC arm and the JMT export
1876 // rather than folded into it. Omitted, the region reloads with
1877 // unbounded memory and every one of those three drops a
1878 // constraint the model declared.
1879 if (m < rg.maxmem.size()) globalmem = rg.maxmem[m];
1880 for (std::size_t r = 0; r < K; ++r)
1881 if (rg.cap[m][r] != -1.0) class_cap[sn.classes[r].name] = rg.cap[m][r];
1882 }
1883 rj["stations"] = stations;
1884 if (global != -1.0) rj["globalMaxJobs"] = global;
1885 if (globalmem != -1.0) rj["globalMaxMemory"] = globalmem;
1886 if (!class_cap.empty()) rj["classMaxJobs"] = class_cap;
1887 json rule;
1888 for (std::size_t r = 0; r < K && r < rg.rule.size(); ++r)
1889 rule[sn.classes[r].name] = detail::drop_to_json(rg.rule[r]);
1890 rj["dropRule"] = rule;
1891 for (std::size_t r = 0; r < K; ++r) {
1892 if (r < rg.size.size() && num_traits<T>::to_double(rg.size[r]) != 1.0)
1893 class_size[sn.classes[r].name] = num_traits<T>::to_double(rg.size[r]);
1894 if (r < rg.weight.size() && num_traits<T>::to_double(rg.weight[r]) != 1.0)
1895 class_weight[sn.classes[r].name] = num_traits<T>::to_double(rg.weight[r]);
1896 }
1897 // classSize and classWeight are per-STATION on the wire, and the
1898 // struct holds one vector per region, so they are written onto every
1899 // member station -- which is the same model the reader rebuilds.
1900 if (!class_size.empty() || !class_weight.empty())
1901 for (json& sj : rj["stations"]) {
1902 if (!class_size.empty()) sj["classSize"] = class_size;
1903 if (!class_weight.empty()) sj["classWeight"] = class_weight;
1904 }
1905 if (rg.lincon_A.rows() > 0) {
1906 rj["constraintA"] = detail::mat_to_json(rg.lincon_A);
1907 rj["constraintB"] = detail::vec_to_json(rg.lincon_b);
1908 }
1909 fcr.push_back(rj);
1910 }
1911 model["finiteCapacityRegions"] = fcr;
1912 }
1913
1914 // -- global (Whittle) dependence -----------------------------------------
1915 //
1916 // phi(n) reads the FULL population matrix, so unlike the per-station
1917 // classDependence/jointDependence blocks it is materialized over the lattice
1918 // of the WHOLE network state. Only the (station,class) SLOTS a class can
1919 // actually occupy carry a coordinate: a Source holds no jobs and a class with
1920 // zero per-class capacity at a station never appears there. That restriction
1921 // is lossless, since no DEP or PHASE event ever fires at such a slot.
1922 if (static_cast<bool>(sn.gdscaling)) {
1923 const std::size_t M = sn.nstations, K = sn.nclasses;
1924 const std::vector<double> njobs = sn.njobs();
1925 const int wcut = sn.gdscalingcutoff;
1926 std::vector<std::size_t> slot_st, slot_cl;
1927 std::vector<int> cuts;
1928 for (std::size_t i = 0; i < M; ++i) {
1929 if (sn.nodes[sn.station_to_node[i] - 1].nodetype == lang::NodeType::Source) continue;
1930 for (std::size_t r = 0; r < K; ++r) {
1931 const double cap = sn.classcap[i][r];
1932 if (!(cap > 0)) continue;
1933 int c = std::isfinite(njobs[r]) ? static_cast<int>(std::lround(njobs[r])) : wcut;
1934 if (std::isfinite(cap)) c = std::min(c, static_cast<int>(std::lround(cap)));
1935 slot_st.push_back(i);
1936 slot_cl.push_back(r);
1937 cuts.push_back(c > 0 ? c : 0);
1938 }
1939 }
1940 const std::size_t P = cuts.size();
1941 std::size_t total = 1;
1942 for (std::size_t d = 0; d < P; ++d) {
1943 total *= static_cast<std::size_t>(cuts[d] + 1);
1944 if (total > 200000u)
1945 throw InputError(
1946 "the global dependence lattice exceeds the wire limit of 200000 points; lower "
1947 "the wireCutoff argument of set_global_dependence, or solve the model "
1948 "natively");
1949 }
1950
1951 json blk, slots, tbl;
1952 blk["type"] = "globalDependent";
1953 std::vector<std::string> station_names(M), class_names(K);
1954 for (std::size_t i = 0; i < M; ++i)
1955 station_names[i] = sn.nodes[sn.station_to_node[i] - 1].name;
1956 for (std::size_t r = 0; r < K; ++r) class_names[r] = sn.classes[r].name;
1957 blk["stations"] = station_names;
1958 blk["classes"] = class_names;
1959 slots = json::array();
1960 for (std::size_t d = 0; d < P; ++d) {
1961 json sm;
1962 sm["station"] = station_names[slot_st[d]];
1963 sm["class"] = class_names[slot_cl[d]];
1964 slots.push_back(sm);
1965 }
1966 blk["slots"] = slots;
1967 blk["cutoffs"] = cuts;
1968 blk["cutoff"] = wcut;
1969
1970 for (std::size_t li = 0; li < total; ++li) {
1971 std::size_t rem = li;
1972 std::vector<int> cnt(P, 0);
1973 for (std::size_t d = 0; d < P; ++d) {
1974 cnt[d] = static_cast<int>(rem % static_cast<std::size_t>(cuts[d] + 1));
1975 rem /= static_cast<std::size_t>(cuts[d] + 1);
1976 }
1977 std::vector<T> n(M * K, num_traits<T>::from_int(0));
1978 for (std::size_t d = 0; d < P; ++d)
1979 n[slot_st[d] * K + slot_cl[d]] = num_traits<T>::from_int(cnt[d]);
1980 const std::vector<T> v = sn.gdscaling(n);
1981 std::vector<double> flat(M * K, 1.0);
1982 for (std::size_t i = 0; i < M; ++i)
1983 for (std::size_t r = 0; r < K; ++r) {
1984 double x;
1985 if (v.size() == 1) x = num_traits<T>::to_double(v[0]);
1986 else if (v.size() == M) x = num_traits<T>::to_double(v[i]);
1987 else x = num_traits<T>::to_double(v[i * K + r]);
1988 flat[i * K + r] = std::isfinite(x) ? x : 0.0;
1989 }
1990 std::string key;
1991 if (P == 0) key = "0";
1992 else
1993 for (std::size_t d = 0; d < P; ++d) {
1994 if (d) key += ',';
1995 key += std::to_string(cnt[d]);
1996 }
1997 tbl[key] = flat;
1998 }
1999 blk["scaling"] = tbl;
2000 std::vector<double> pk(M * K, 1.0);
2001 for (std::size_t j = 0; j < pk.size() && j < sn.gdscalingpeak.size(); ++j)
2002 pk[j] = num_traits<T>::to_double(sn.gdscalingpeak[j]);
2003 blk["peak"] = pk;
2004 model["globalDependence"] = blk;
2005 }
2006
2007 // -- rewards --------------------------------------------------------------
2008 //
2009 // The DECLARATIVE ones only. A reward built from a lambda carries no `kind`
2010 // and is dropped here, exactly as `linemodel_save` drops it: any record
2011 // written for it would reload as a different function.
2012 {
2013 // IN NAME ORDER, which is the cross-codebase convention and not a
2014 // cosmetic choice: `rewards2json` sorts for it explicitly, because the
2015 // JAR holds the rewards in a HashMap and has no insertion order to
2016 // preserve. Emitting them in struct order made the same model produce a
2017 // different document here than in the other three, which the JSON arm of
2018 // the parity harness reports as a difference in the model.
2019 std::map<std::string, json> by_name;
2020 for (const typename SN::Reward& rw : sn.reward) {
2021 if (rw.kind.empty() || rw.node == 0) continue;
2022 json rj;
2023 rj["name"] = rw.name;
2024 rj["type"] = rw.kind;
2025 rj["node"] = sn.nodes[rw.node - 1].name;
2026 if (rw.cls != 0) rj["class"] = sn.classes[rw.cls - 1].name;
2027 by_name[rw.name] = rj;
2028 }
2029 json rewards = json::array();
2030 for (const std::pair<const std::string, json>& kv : by_name) rewards.push_back(kv.second);
2031 if (!rewards.empty()) model["rewards"] = rewards;
2032 }
2033 return model;
2034}
2035
2036/** The complete model.json envelope: `{format, version, model}`. */
2037template <class T>
2039 detail::json root;
2040 root["format"] = "line-model";
2041 root["version"] = "1.0";
2042 root["model"] = network_to_json(sn);
2043 detail::wire_nonfinite(root);
2044 return root;
2045}
2046
2047/**
2048 * Refuse an OI/PAS station with no finite buffer before it reaches LDES.
2049 *
2050 * The reference refusal is Python `save_model`'s (`linemodel_io.py`): mu(c)
2051 * crosses the wire as a table, and LDES state-space generation needs a finite
2052 * buffer whether or not the rate saturates, since saturation only keeps the
2053 * table compact and cannot bound the queue length. The writer itself refuses
2054 * only an open class with a non-saturating mu; a saturating mu, which it saves
2055 * exactly, still needs this gate to bound the state. The messages are the
2056 * reference's, word for word, naming the station.
2057 */
2058template <class T>
2060 const std::size_t K = sn.classes.size();
2061 for (typename std::map<std::size_t, typename qn::NetworkStruct<T>::PasParam>::const_iterator
2062 it = sn.pasparam.begin();
2063 it != sn.pasparam.end(); ++it) {
2064 if (!static_cast<bool>(it->second.svc_rate_fun)) continue;
2065 const std::size_t ist = it->first;
2066 if (ist < 1 || ist > sn.stations.size()) continue;
2067 const double cap = sn.stations[ist - 1].cap;
2068 if (std::isfinite(cap)) continue;
2069 const std::string& name = sn.stations[ist - 1].name;
2070 const PasSaturation s = pas_saturation_cutoffs<T>(it->second.svc_rate_fun, K);
2071 if (s.bounded) {
2072 std::string tau = "[";
2073 for (std::size_t r = 0; r < s.tau.size(); ++r)
2074 tau += (r ? ", " : "") + std::to_string(s.tau[r]);
2075 tau += "]";
2076 throw InputError("PAS station '" + name +
2077 "' has no finite buffer: LDES state-space generation requires one. "
2078 "Its order-independent service rate saturates at class counts " +
2079 tau +
2080 ", so call setCap(N) with N comfortably above the mean occupancy.");
2081 }
2082 throw InputError("PAS station '" + name +
2083 "' has an unbounded order-independent service rate (mu does not "
2084 "saturate) and no finite buffer; call setCap(N) on the station.");
2085 }
2086}
2087
2088/** Write a model.json file, indented as the reference writers indent it. */
2089template <class T>
2090void write_network_json(const qn::NetworkStruct<T>& sn, const std::string& path) {
2091 std::ofstream out(path.c_str());
2092 if (!out) throw InputError("network_writer: cannot open " + path + " for writing");
2093 out << network_json_envelope(sn).dump(2) << "\n";
2094}
2095
2096} // namespace io
2097} // namespace line
2098
2099#endif // LINE_IO_NETWORK_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
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
What refreshProcessRepresentations and refreshLST compute FROM a distribution: the (D0,...
The exception types the port throws.
Enumerations and the minimal distribution descriptor shared by the model layer of the C++ port.
detail::json network_to_json(const qn::NetworkStruct< T > &sn)
qn::NetworkStruct -> the model.json model object.
void require_finite_pas_buffers(const qn::NetworkStruct< T > &sn)
Refuse an OI/PAS station with no finite buffer before it reaches LDES.
PasSaturation saturation_cutoffs(const std::function< std::vector< double >(const std::vector< int > &)> &f_at, std::size_t K, double cmax=std::numeric_limits< double >::infinity(), int max_cutoff=256, double tol=1e-9)
Per-class saturation cutoffs of a count-indexed function f(n), the search behind the OI/PAS and class...
detail::json network_json_envelope(const qn::NetworkStruct< T > &sn)
The complete model.json envelope: {format, version, model}.
void write_network_json(const qn::NetworkStruct< T > &sn, const std::string &path)
Write a model.json file, indented as the reference writers indent it.
PasSaturation pas_saturation_cutoffs(const std::function< T(const std::vector< std::size_t > &)> &mu, std::size_t K, double cmax=std::numeric_limits< double >::infinity())
The saturation cutoffs of an order-independent rate mu(c), searched over the states a buffer of cmax ...
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
BalkingStrategy
Balking rules, with the values of MATLAB BalkingStrategy.
Definition lang_types.h:486
SignalType
G-network signal classes, with the values of MATLAB SignalType.
Definition lang_types.h:180
@ REPLY
completes a synchronous call, releasing a held server
Definition lang_types.h:181
@ CATASTROPHE
removes EVERY job at the station
Definition lang_types.h:183
PollingOrder
Visit-order rules of a polling server, with the values of MATLAB PollingOrder.
Definition lang_types.h:404
@ THRESHOLD
a priority buffer above its threshold, else SKIPEMPTY
Definition lang_types.h:408
@ SKIPEMPTY
next non-empty buffer in cyclic order
Definition lang_types.h:406
@ CYCLIC
fixed cyclic order (or the polling table)
Definition lang_types.h:405
@ LQF
longest buffer first, ties to the cyclic successor
Definition lang_types.h:407
RoutingStrategy
Routing strategies, with the values of MATLAB RoutingStrategy.
Definition lang_types.h:430
@ SDR
Krzesinski (1987) product-form state-dependent routing.
Definition lang_types.h:439
@ GLOBAL
a timed token: per-class target rotation timers
Definition lang_types.h:415
@ NONE
no visit timer
Definition lang_types.h:413
RemovalPolicy
Which job a negative signal removes, with the values of MATLAB RemovalPolicy.
Definition lang_types.h:187
@ FCFS
the oldest waiting job; servers only once nobody waits
Definition lang_types.h:189
@ RANDOM
uniform over waiting AND in-service jobs
Definition lang_types.h:188
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
@ KLIMITED
serve at most K per visit (K in pollingPar)
Definition lang_types.h:394
@ EXHAUSTIVE
serve until the queue empties
Definition lang_types.h:393
@ GATED
serve exactly the jobs present at the polling instant
Definition lang_types.h:392
@ GLIMITED
serve at most K of the jobs present at the polling instant
Definition lang_types.h:396
@ DECREMENTING
serve until the queue is one shorter than at arrival
Definition lang_types.h:395
ProcessType
Distribution kinds, with the values of MATLAB ProcessType.
Definition lang_types.h:524
const char * sched_to_text(SchedStrategy s)
Definition lang_types.h:248
const char * process_to_text(ProcessType p)
The MATLAB ProcessType name, as sn.procid prints it.
Definition lang_types.h:655
std::function< std::vector< T >(const std::vector< T > &)> CdScaling
A class-dependent scaling map, sn.cdscaling.
Definition lang_types.h:794
NodeType
Node kinds, with the values of MATLAB NodeType.
Definition lang_types.h:345
ReplacementStrategy
Cache replacement policies, with the values of MATLAB ReplacementStrategy.
Definition lang_types.h:419
@ HLRU
h-LRU / LRU(m): h lists, promote i -> i+1 on a hit
Definition lang_types.h:424
@ CLIMB
move up one position on a hit (transposition rule)
Definition lang_types.h:425
@ QLRU
q-LRU: LRU with probabilistic admission on a miss
Definition lang_types.h:426
@ LRU
least recently used
Definition lang_types.h:423
@ FIFO
first in, first out
Definition lang_types.h:421
ImpatienceType
Impatience kinds, with the values of MATLAB ImpatienceType.
Definition lang_types.h:483
double tot(const std::vector< double > &pops)
void put(Matrix< double > &A, std::size_t r0, std::size_t c0, const Matrix< double > &S)
A(r0:, c0:) = S.
Definition mg1.h:927
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
Reader for the LINE model.json interchange (a Network model) into a qn::Network<T> built through the ...
A queueing network and its refreshed NetworkStruct.
Number-type abstraction for the templated API port.
The per-class saturation cutoffs of a count-indexed rate table.
bool bounded
false when some tau(r) passed the search limit or reached cmax
std::vector< int > tau
tau(r): beyond it the function no longer changes with class-r jobs
static Distrib exp_rate(const T &r)
std::vector< T > params
Constructor arguments, in MATLAB getParam order.
Definition lang_types.h:894
std::vector< T > trace
Replayer / Trace samples; empty for every other type.
Definition lang_types.h:896
Topology and coefficients of a state-dependent routing subnetwork.
Definition pfqn_sdr.h:59
std::vector< std::size_t > level
level[b] is the unique t with B_b in V_t - V_{t+1}; level[0] is unused.
Definition pfqn_sdr.h:71
Matrix< double > d
Coefficients d_tb of eq.
Definition pfqn_sdr.h:75
std::vector< double > C
Coefficients C_t of eq.
Definition pfqn_sdr.h:73
std::size_t departure
Departure centre d of Q(V,V); may equal entry.
Definition pfqn_sdr.h:63
std::vector< std::vector< std::size_t > > branch
branch[b] holds the centres of branch b, b >= 1; branch[0] is unused.
Definition pfqn_sdr.h:65
std::size_t entry
Entry centre e of Q(V,V).
Definition pfqn_sdr.h:61
The parameters of a Cache node, MATLAB's sn.nodeparam{ind} for a Cache.
int retrieval_capacity
Delayed-hit retrieval system (Cache.setRetrievalSystem).
T qlru
q-LRU admission probability; 1 admits every miss (plain LRU).
std::vector< T > initstate
The DECLARED initial contents of the cache, as the reference dumps the node's state row: the per-clas...
std::vector< int > itemsize
Per-item storage cost (size) and per-list cap on the total cost of the resident items (ton21cache Sec...
std::vector< int > costcap
std::map< std::size_t, std::vector< std::size_t > > retrieval_queues
read class(0-based)->nodes
std::vector< std::vector< Matrix< T > > > accost
(u) x (n) of (h+1)x(h+1), or empty
std::vector< std::vector< std::size_t > > retrieval_classes
(nitems x nclasses), 1-based
std::vector< int > itemcap
std::vector< std::size_t > missclass
std::vector< std::size_t > hitclass
lang::ReplacementStrategy replacestrat
std::vector< std::size_t > classitem
Item read by each per-item class of a cache network (MATLAB Cache.setItemReadClasses,...
std::vector< std::vector< T > > pread
(u) x (n), empty row = NaN
Variable forking levels, the twin of MATLAB sn.nodeparam{f}.fanOutLink / .fanOutProb / ....
std::vector< std::vector< lang::Distrib< T > > > fan_out_dist
One job class of the network.
std::size_t refstat
1-based reference station
double deadline
sn.classdeadline(r): the soft deadline EDD and EDF order by, and the tardiness JMT reports.
double population
infinite for an open class
bool immfeed
Class-level immediate feedback, ORed with the station's own setting into sn.immfeed.
std::size_t spawn
sn.classspawn(r): the 1-based class injected at the SAME station on every completion of this class,...
bool self_looping
A SelfLoopingClass: a closed class that perpetually cycles at its reference station.
bool is_ref_class
marks the chain's reference class
The pass-and-swap / order-independent parameters of a PAS station, keyed by station index (Dorsman an...
The polling controller of a POLLING station, keyed by station index.
std::size_t pk
the K of K-LIMITED
A Logger node's trace configuration, MATLAB's Logger properties and sn.nodeparam{ind}...
std::string file_name
base name, no directory
std::string file_path
directory, MATLAB's model.getLogPath
A node of the network.
std::vector< int > routing_param
The scalar parameter of a parameterized dispatcher, per class: the d of a power-of-d (SQ) choice.
std::vector< std::map< std::size_t, double > > routing_weights
The per-destination weights of a WRROBIN dispatcher, per class: a map from 1-based destination NODE i...
bool queue_object
Declared as a Queue although its INF discipline makes nodetype Delay (Network::add_queue).
std::vector< RoutingStrategy > routing
sn.routing, per class.
double tasks_per_link
Fork.output.tasksPerLink == MATLAB sn.nodeparam{f}.fanOut: how many tasks a fork emits per outgoing l...
One balking threshold: with min_jobs <= n <= max_jobs at the station, an arriving job of the class re...
A heterogeneous server pool: count servers that serve only compatible classes, each with its own serv...
std::vector< bool > compatible
per class; empty = every class
std::vector< Distrib< T > > service
per class
One station of the network.
std::vector< Distrib< T > > orbit_impatience
Queue.setOrbitImpatience(class, dist): abandonment from the RETRIAL ORBIT, which is a different popul...
double cap
Station capacity in Kendall's K, as setCapacity sets it.
std::vector< T > jdscalingpeak
sn.jdscalingpeak for this station: the declared peak joint-dependent scaling per class.
std::vector< BalkingParam > balking
std::vector< T > batch_reject
Queue.setBatchRejectProbability: per-class rejection of a whole batch.
std::vector< Distrib< T > > patience
Queue.setPatience(class, dist): the abandonment timer of a WAITING job, with impatience[r] naming whi...
std::vector< std::size_t > server_parallelism
Queue.setServerParallelism(class, n): the servers a job seizes for the whole of its service,...
std::vector< Distrib< T > > quantum
Queue.setQuantum(class, distrib): the per-class time slice of a round-robin (SchedStrategy::RR) stati...
std::vector< int > droprule
Per-class blocking rule as an INT, with 0 meaning "not set".
std::vector< Distrib< T > > polling_timer
SchedStrategy sched
std::vector< std::vector< Distrib< T > > > switchover_pair
Queue.setSwitchover(fromClass, toClass, distrib): the walk the server takes when it turns from servin...
std::vector< Distrib< T > > polling_table_sw
double nservers
may be infinite (a Delay, or an inf-scheduled task)
std::size_t polling_order_class
std::vector< lang::PollingType > polling_type
Polling parameters for a POLLING station, MATLAB's pollingType, switchoverTime and pollingPar on the ...
T orbit_join_of(std::size_t r) const
orbit_join[r] with the default 1 for a missing slot (0-based r).
CdScaling< T > jdscaling
sn.jdscaling for this station: MATLAB's Station.ljdScaling, the JOINT dependence map eta_i(n),...
std::vector< T > cdscalingpeak
sn.cdscalingpeak for this station: the DECLARED peak rate scaling per class, empty when the station i...
std::vector< std::size_t > marked_classes
Source.markedClasses: the 1-based class of each mark of an MMAP arrival.
std::vector< T > lldscaling
sn.lldscaling for this station: the multiplier at population 1, 2, ... Empty when the station is not ...
std::vector< lang::ImpatienceType > impatience
std::vector< T > schedparam
sn.schedparam, per class: the DPS / GPS weight, or the SEPT / LEPT rank.
lang::PollingOrder polling_order
std::vector< std::size_t > polling_table
The polling extensions (Queue.setPollingTable, setPollingOrder, setPollingTimer).
lang::HeteroSchedPolicy hetero_policy
CdScaling< T > cdscaling
sn.cdscaling for this station: the class-dependence map, empty when unset.
std::vector< double > classcap
Per-class buffer from setChainCapacity; infinite where unset.
std::vector< lang::DepartureDiscipline > departure_discipline
Place.departureDiscipline, per class.
std::vector< Distrib< T > > arrival_batch
Source.setArrivalBatch(class, dist): the batch-size law released at each arrival epoch.
std::vector< Distrib< T > > switchover
bool fluid
Place.setFluid (MATLAB sn.fluid): the place holds a continuous LEVEL rather than tokens,...
lang::PollingTimer polling_timer_scope
T orbit_search_of(std::size_t r) const
orbit_search[r] with the default 0 for a missing slot (0-based r).
std::vector< bool > immfeed
Node-level immediate feedback, per class; empty when the station sets none.
std::vector< ServerType > server_types
T orbit_persist_of(std::size_t r) const
orbit_persist[r] with the default 1 for a missing slot (0-based r).
The parameters of a Transition node: MATLAB sn.nodeparam{ind} for an SPN transition,...
const std::vector< FluidArc > & fluid_rates(std::size_t m) const
const std::vector< FluidArc > & fluid_impulses(std::size_t m) const
const std::vector< FluidDep > & fluid_deps(std::size_t m) const
const std::vector< FluidFlowDep > & fluid_flow_deps(std::size_t m) const
const std::vector< FluidGuard > & fluid_guards(std::size_t m) const