LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
network_reader.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_READER_H
6#define LINE_IO_NETWORK_READER_H
7
8/**
9 * @file
10 * @ingroup line_io
11 * Reader for the LINE `model.json` interchange (a Network model) into a
12 * `qn::Network<T>` built through the programmatic builder.
13 *
14 * The wire format is the one `linemodel_save.m`, the Python writer and the JAR
15 * `LineModelIO` emit: a top-level `{format, version, model}` envelope whose
16 * `model.type == "Network"` carries `nodes`, `classes` and `routing`. This
17 * reader feeds the SAME builder + finalize the C++ programmatic API uses, so a
18 * model that reaches C++ this way is indistinguishable from one authored in
19 * code -- exactly the contract `lqn_builder.h` documents for its own reader.
20 *
21 * Scope: the queueing-network subset SolverMVA analyses. Distributions are
22 * honoured on the moments the analyzers read (mean, SCV and, for QNA/polling,
23 * the family the wire names). A construct outside this subset -- a
24 * LayeredNetwork / Workflow / Environment model, an unsupported node kind, or a
25 * distribution family whose moments this reader cannot reconstruct exactly --
26 * is REFUSED BY NAME rather than silently degraded, matching the "a featset
27 * name is a claim" rule the rest of the port follows.
28 */
29
30#include <algorithm>
31#include <cctype>
32#include <cmath>
33#include <cstdlib>
34#include <fstream>
35#include <functional>
36#include <iostream>
37#include <limits>
38#include <map>
39#include <string>
40#include <vector>
41
42#include "json.hpp"
44#include "line/lang/prior.h"
46#include "line/num/number.h"
47#include "line/util/error.h"
48
49namespace line {
50namespace io {
51
52namespace detail {
53
54using json = nlohmann::json;
55
56/**
57 * A model.json number that may arrive as the wire's INFINITY SPELLING.
58 *
59 * JSON has no infinity literal, so `linemodel_save` writes any infinite scalar
60 * as the string `"Infinity"` / `"-Infinity"` -- a rule it applies to EVERY
61 * numeric field, not to a named few. A plain `value("k", def)` therefore throws
62 * `json.exception.type_error.302 type must be number, but is string` the moment
63 * a model carries one, and the throw names no key: `spn_basic_open` (a
64 * transition mode with `"numServers": "Infinity"`) failed identically under
65 * every solver, which reads as a solver defect rather than as a reader gap.
66 * The JAR (`LineModelIO`) and Python (`_servers_from_json`) readers both accept
67 * the string form; this is the C++ twin.
68 *
69 * `nan` is also accepted, since the writer emits `null` for NaN and a reader
70 * asked for a number from `null` would throw the same way.
71 *
72 * WHICH FIELDS NEED THIS, and why it is not every numeric read. The encoder's
73 * rule is generic, but `linemodel_save` GUARDS the fields whose natural value
74 * is infinite: `servers`, `buffer` and `classCap` are each emitted only when
75 * `isfinite`, and `population` is written only for the closed and self-looping
76 * classes, which are finite by construction. So the generic spelling is only
77 * reachable on an UNGUARDED field. Transition-mode `numServers` is the proven
78 * one, and all three writers agree it is the sentinel there. The remaining uses
79 * below are the fields a non-MATLAB writer could still send infinite. Do not
80 * take this as licence to convert the other `get<double>()` reads: a
81 * distribution parameter that arrives as a string is a malformed model, and
82 * should keep throwing.
83 */
84inline double num_from_json(const json& v) {
85 if (v.is_null()) return std::numeric_limits<double>::quiet_NaN();
86 if (v.is_string()) {
87 const std::string s = v.get<std::string>();
88 if (s == "Infinity" || s == "inf" || s == "Inf")
89 return std::numeric_limits<double>::infinity();
90 if (s == "-Infinity" || s == "-inf" || s == "-Inf")
91 return -std::numeric_limits<double>::infinity();
92 if (s == "NaN" || s == "nan") return std::numeric_limits<double>::quiet_NaN();
93 // Anything else is a malformed number, not a zero: report it rather
94 // than let atof turn a typo into a silently wrong model.
95 const char* begin = s.c_str();
96 char* end = nullptr;
97 const double parsed = std::strtod(begin, &end);
98 if (end == begin || *end != '\0')
99 throw InputError(ErrorKind{"Format"}, "network_reader: expected a number, got the string '" + s + "'");
100 return parsed;
101 }
102 if (v.is_boolean()) return v.get<bool>() ? 1.0 : 0.0;
103 // Not a string: defer to nlohmann, so an object or an array still throws
104 // the type error it always did.
105 return v.get<double>();
106}
107
108/** `num_from_json` for an optional key, with the reader's default. */
109inline double num_value(const json& obj, const char* key, double def) {
110 return obj.contains(key) ? num_from_json(obj.at(key)) : def;
111}
112
113/**
114 * `fluiddep_table_to_handle`: the level-dependent multiplier a `fluidRateDependence` table carries, rebuilt as
115 * the piecewise-linear interpolant of (levels, values), held constant beyond either end. The writer tabulates
116 * 201 equally spaced levels (`fluiddep_table`), so the round trip is exact for a piecewise-linear h with knots
117 * on the grid and an approximation otherwise.
118 */
119inline std::function<double(double)> fluiddep_table_to_fun(const json& lv, const json& vv, const std::string& who) {
120 std::vector<double> levels, values;
121 for (const json& x : lv) levels.push_back(num_from_json(x));
122 for (const json& x : vv) values.push_back(num_from_json(x));
123 if (levels.empty() || levels.size() != values.size())
124 throw InputError(ErrorKind{"Format"}, "network_reader: the fluid rate dependence of " + who +
125 " needs as many 'values' as 'levels', and at least one");
126 for (std::size_t i = 0; i < levels.size(); ++i) {
127 if (!std::isfinite(levels[i]) || !std::isfinite(values[i]) || (i > 0 && levels[i] <= levels[i - 1]))
128 throw InputError(ErrorKind{"Format"}, "network_reader: the fluid rate dependence of " + who +
129 " needs finite values over strictly increasing finite levels");
130 }
131 if (levels.size() == 1) {
132 const double v = values[0];
133 return [v](double) { return v; };
134 }
135 return [levels, values](double f) {
136 const double x = std::min(std::max(f, levels.front()), levels.back());
137 std::size_t hi = static_cast<std::size_t>(std::upper_bound(levels.begin(), levels.end(), x) - levels.begin());
138 if (hi >= levels.size()) hi = levels.size() - 1;
139 if (hi == 0) hi = 1;
140 const std::size_t lo = hi - 1;
141 const double w = (x - levels[lo]) / (levels[hi] - levels[lo]);
142 return values[lo] + w * (values[hi] - values[lo]);
143 };
144}
145
146/**
147 * The `dest` of a fork override record: a node NAME, or the empty string for
148 * "every link this class takes", which the builder spells as node 0.
149 *
150 * An unknown name is an error and not a silent 0: dropping the destination
151 * would spread an override meant for one link over all of them, which is a
152 * different model that still solves.
153 */
154inline std::size_t fork_dest_index(const json& ov,
155 const std::map<std::string, std::size_t>& node_idx,
156 const std::string& fork_name) {
157 if (!ov.contains("dest")) return 0;
158 const std::string d = ov.at("dest").get<std::string>();
159 if (d.empty()) return 0;
160 const std::map<std::string, std::size_t>::const_iterator it = node_idx.find(d);
161 if (it == node_idx.end())
162 throw InputError(ErrorKind{"Format"}, "network_reader: the Fork node '" + fork_name +
163 "' declares an override towards '" + d + "', which is not a node");
164 return it->second;
165}
166
167/** The `scheduling` attribute of a model.json Queue node. */
168inline lang::SchedStrategy sched_from_json(const std::string& s) {
169 using S = lang::SchedStrategy;
170 if (s == "INF" || s == "inf") return S::INF;
171 if (s == "FCFS" || s == "fcfs") return S::FCFS;
172 if (s == "PS" || s == "ps") return S::PS;
173 if (s == "LCFS" || s == "lcfs") return S::LCFS;
174 if (s == "LCFSPR" || s == "lcfspr") return S::LCFSPR;
175 if (s == "SIRO" || s == "siro") return S::SIRO;
176 if (s == "HOL" || s == "hol") return S::HOL;
177 if (s == "DPS" || s == "dps") return S::DPS;
178 if (s == "GPS" || s == "gps") return S::GPS;
179 if (s == "SEPT" || s == "sept") return S::SEPT;
180 if (s == "LEPT" || s == "lept") return S::LEPT;
181 if (s == "SJF" || s == "sjf") return S::SJF;
182 if (s == "LJF" || s == "ljf") return S::LJF;
183 if (s == "SRPT" || s == "srpt") return S::SRPT;
184 if (s == "LPS" || s == "lps") return S::LPS;
185 if (s == "POLLING" || s == "polling") return S::POLLING;
186 // The preemptive, priority and pass-and-swap families. They were absent
187 // here while `SchedStrategy` and the state layer carried them, so a model
188 // the port can represent was refused at its own front door -- the wire
189 // spells them exactly as the enum does, and `sched_to_text` is the list to
190 // keep this one in step with.
191 if (s == "FCFSPR" || s == "fcfspr") return S::FCFSPR;
192 if (s == "FCFSPI" || s == "fcfspi") return S::FCFSPI;
193 if (s == "FCFSPRIO" || s == "fcfsprio") return S::HOL; // MATLAB's alias for HOL
194 if (s == "FCFSPRPRIO" || s == "fcfsprprio") return S::FCFSPRPRIO;
195 if (s == "FCFSPIPRIO" || s == "fcfspiprio") return S::FCFSPIPRIO;
196 if (s == "LCFSPI" || s == "lcfspi") return S::LCFSPI;
197 if (s == "LCFSPRIO" || s == "lcfsprio") return S::LCFSPRIO;
198 if (s == "LCFSPRPRIO" || s == "lcfsprprio") return S::LCFSPRPRIO;
199 if (s == "LCFSPIPRIO" || s == "lcfspiprio") return S::LCFSPIPRIO;
200 if (s == "PSPRIO" || s == "psprio") return S::PSPRIO;
201 if (s == "DPSPRIO" || s == "dpsprio") return S::DPSPRIO;
202 if (s == "GPSPRIO" || s == "gpsprio") return S::GPSPRIO;
203 if (s == "SRPT" || s == "srpt") return S::SRPT;
204 if (s == "SRPTPRIO" || s == "srptprio") return S::SRPTPRIO;
205 if (s == "PSJF" || s == "psjf") return S::PSJF;
206 if (s == "FB" || s == "fb") return S::FB;
207 if (s == "LAS" || s == "las") return S::LAS; // alias of FB, as SchedStrategy.fromText in MATLAB/JAR
208 if (s == "LRPT" || s == "lrpt") return S::LRPT;
209 if (s == "SETF" || s == "setf") return S::SETF;
210 if (s == "FSP" || s == "fsp") return S::FSP;
211 if (s == "EDD" || s == "edd") return S::EDD;
212 if (s == "EDF" || s == "edf") return S::EDF;
213 if (s == "PAS" || s == "pas") return S::PAS;
214 if (s == "OI" || s == "oi") return S::OI;
215 if (s == "RR" || s == "rr") return S::RR; // round robin; its "quantum" is read with the node
216 if (s == "REF" || s == "ref") return S::REF;
217 if (s == "EXT" || s == "ext") return S::EXT;
218 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: unsupported scheduling discipline '" + s + "'");
219}
220
221/** The `dropRule` string of a Queue node, matching the linemodel_io map. An
222 * unrecognised value resolves to WAITQ, as MATLAB's str_to_droprule does. */
223inline lang::DropStrategy drop_from_json(const std::string& s) {
224 using D = lang::DropStrategy;
225 if (s == "drop") return D::DROP;
226 if (s == "waitingQueue") return D::WAITQ;
227 if (s == "blockingAfterService") return D::BAS;
228 if (s == "retrial") return D::RETRIAL;
229 if (s == "retrialWithLimit") return D::RETRIAL_WITH_LIMIT;
230 return D::WAITQ;
231}
232
233inline lang::ReplacementStrategy replacement_from_json(const std::string& s) {
235 if (s == "RR" || s == "rr") return R::RR;
236 if (s == "FIFO" || s == "fifo") return R::FIFO;
237 if (s == "SFIFO" || s == "sfifo") return R::SFIFO;
238 if (s == "LRU" || s == "lru") return R::LRU;
239 if (s == "HLRU" || s == "hlru") return R::HLRU;
240 if (s == "CLIMB" || s == "climb") return R::CLIMB;
241 if (s == "QLRU" || s == "qlru") return R::QLRU;
242 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: unsupported cache replacement strategy '" + s + "'");
243}
244
245inline lang::PollingType polling_from_json(const std::string& s) {
246 using P = lang::PollingType;
247 if (s == "GATED" || s == "gated") return P::GATED;
248 if (s == "EXHAUSTIVE" || s == "exhaustive") return P::EXHAUSTIVE;
249 if (s == "KLIMITED" || s == "klimited" || s == "K-LIMITED") return P::KLIMITED;
250 if (s == "DECREMENTING" || s == "decrementing") return P::DECREMENTING;
251 if (s == "GLIMITED" || s == "glimited" || s == "G-LIMITED") return P::GLIMITED;
252 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: unsupported polling type '" + s + "'");
253}
254
255inline lang::PollingOrder polling_order_from_json(const std::string& s) {
256 using O = lang::PollingOrder;
257 if (s == "CYCLIC" || s == "cyclic") return O::CYCLIC;
258 if (s == "SKIPEMPTY" || s == "skipempty") return O::SKIPEMPTY;
259 if (s == "LQF" || s == "lqf") return O::LQF;
260 if (s == "THRESHOLD" || s == "threshold") return O::THRESHOLD;
261 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: unsupported polling order '" + s + "'");
262}
263
264inline lang::PollingTimer polling_timer_from_json(const std::string& s) {
265 using P = lang::PollingTimer;
266 if (s == "NONE" || s == "none") return P::NONE;
267 if (s == "LOCAL" || s == "local") return P::LOCAL;
268 if (s == "GLOBAL" || s == "global") return P::GLOBAL;
269 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: unsupported polling timer scope '" + s + "'");
270}
271
272/**
273 * A two-phase hyper-exponential matched to a mean and SCV (SCV >= 1), by the
274 * balanced-means convention MATLAB `HyperExp.fitMeanAndSCV` and JMT use. Kept
275 * local so the reader carries the exact same moments as the reference fit
276 * rather than an approximation of them.
277 */
278template <class T>
279lang::Distrib<T> hyperexp_fit_mean_scv(double mean, double scv) {
280 if (!(scv >= 1.0))
281 throw InputError(ErrorKind{"Format"}, "network_reader: HyperExp fitMeanAndSCV needs SCV >= 1, got " +
282 std::to_string(scv));
283 const double p = 0.5 * (1.0 + std::sqrt((scv - 1.0) / (scv + 1.0)));
284 const double mu1 = 2.0 * p / mean;
285 const double mu2 = 2.0 * (1.0 - p) / mean;
286 return lang::Distrib<T>::hyperexp(num_traits<T>::from_double(p),
287 num_traits<T>::from_double(mu1),
288 num_traits<T>::from_double(mu2));
289}
290
291/**
292 * A Cache field, looked up in the FLAT spelling on the node first and then in
293 * the nested `cache` object.
294 *
295 * The writers emit both (`linemodel_save.m:425-435`) so that the MATLAB and the
296 * JAR readers each find what they look for; the two are mirrored from one
297 * source and therefore agree. A free function rather than a lambda because the
298 * result feeds `.get<...>()`, and a lambda declared inside a template makes
299 * that call dependent.
300 */
301inline bool has_cache_key(const json& nd, const json& cj, const char* key) {
302 return nd.contains(key) || cj.contains(key);
303}
304inline const json& cache_key(const json& nd, const json& cj, const char* key) {
305 return nd.contains(key) ? nd.at(key) : cj.at(key);
306}
307
308/** The `routingStrategies` name of a dispatcher. */
309inline lang::RoutingStrategy routing_from_json(const std::string& s) {
310 typedef lang::RoutingStrategy R;
311 if (s == "PROB") return R::PROB;
312 if (s == "RAND") return R::RAND;
313 if (s == "RROBIN") return R::RROBIN;
314 if (s == "WRROBIN") return R::WRROBIN;
315 if (s == "JSQ") return R::JSQ;
316 if (s == "SQ" || s == "KCHOICES") return R::SQ;
317 // The declaration itself rides in the `stateDepRouting` block; this only
318 // names the entry row's strategy, which the block then supersedes.
319 if (s == "SDR") return R::SDR;
320 if (s == "FIRING") return R::FIRING;
321 if (s == "DISABLED") return R::DISABLED;
322 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: unsupported routing strategy '" + s + "'");
323}
324
325/** The `patience` block's `impatienceType`. */
326inline lang::ImpatienceType impatience_from_json(const std::string& s) {
327 typedef lang::ImpatienceType I;
328 if (s == "RENEGING") return I::RENEGING;
329 if (s == "BALKING") return I::BALKING;
330 if (s == "RETRIAL") return I::RETRIAL;
331 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: unsupported impatience type '" + s + "'");
332}
333
334/** The `balking` block's `strategy`. */
335inline lang::BalkingStrategy balking_from_json(const std::string& s) {
336 typedef lang::BalkingStrategy B;
337 if (s == "QUEUE_LENGTH") return B::QUEUE_LENGTH;
338 if (s == "EXPECTED_WAIT") return B::EXPECTED_WAIT;
339 if (s == "COMBINED") return B::COMBINED;
340 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: unsupported balking strategy '" + s + "'");
341}
342
343/** The `heteroSchedPolicy` of a station with several server pools. */
344inline lang::HeteroSchedPolicy hetero_from_json(const std::string& s) {
345 typedef lang::HeteroSchedPolicy H;
346 if (s == "ORDER") return H::ORDER;
347 if (s == "ALIS") return H::ALIS;
348 if (s == "ALFS") return H::ALFS;
349 if (s == "FAIRNESS") return H::FAIRNESS;
350 if (s == "FSF") return H::FSF;
351 if (s == "RAIS") return H::RAIS;
352 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: unsupported heterogeneous scheduling policy '" + s + "'");
353}
354
355/** The `departureDiscipline` of a queueing Place. */
356inline lang::DepartureDiscipline departure_from_json(const std::string& s) {
357 // Case-insensitive, as in the JAR and Python readers: MATLAB and the JAR write "Normal", Python "NORMAL"
358 std::string u(s);
359 for (char& ch : u) ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
360 if (u == "NORMAL") return lang::DepartureDiscipline::NORMAL;
361 if (u == "FIFO") return lang::DepartureDiscipline::FIFO;
362 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: unsupported departure discipline '" + s + "'");
363}
364
365/** Read a wire field that may be a JSON array or, for length one, a bare scalar. */
366template <class T>
367std::vector<T> num_vec_from_json(const json& v) {
368 std::vector<T> out;
369 // num_from_json, not get<double>(): a state row is one of the UNGUARDED
370 // fields of the comment above it. An open model's Source holds an infinite
371 // population, so `initialState`/`stateSpace` carry "Infinity" the moment the
372 // writer emits a state for every stateful node.
373 if (v.is_array())
374 for (const json& x : v) out.push_back(num_traits<T>::from_double(num_from_json(x)));
375 else
376 out.push_back(num_traits<T>::from_double(num_from_json(v)));
377 return out;
378}
379
380/** A dense matrix written as an array of row arrays. */
381template <class T>
382Matrix<T> mat_from_json(const json& v) {
383 if (!v.is_array())
384 throw InputError(ErrorKind{"Format"}, "network_reader: expected an array of rows");
385 Matrix<T> M(v.size(), v.empty() ? 0 : v.at(0).size());
386 for (std::size_t i = 0; i < v.size(); ++i) {
387 const json& row = v.at(i);
388 for (std::size_t j = 0; j < row.size(); ++j)
389 M(i, j) = num_traits<T>::from_double(num_from_json(row.at(j)));
390 }
391 return M;
392}
393
394/** A list of dense matrices, the form the marked and batch families are written in. */
395template <class T>
396std::vector<Matrix<T> > mat_list_from_json(const json& v) {
397 std::vector<Matrix<T> > out;
398 for (const json& m : v) out.push_back(mat_from_json<T>(m));
399 return out;
400}
401
402/** Reconstruct a distribution from a `fit` block (moments), by declared family. */
403template <class T>
404lang::Distrib<T> dist_from_fit(const std::string& type, const json& fit) {
405 const std::string method = fit.at("method").get<std::string>();
406 if (method == "fitMean" || method == "fitMeanAndOrder") {
407 const double mean = fit.at("mean").get<double>();
408 if (type == "Det") return lang::Distrib<T>::det(num_traits<T>::from_double(mean));
409 if (type == "Erlang") {
410 const long order = fit.contains("order") ? fit.at("order").get<long>() : 1L;
411 const T rate = num_traits<T>::from_double(double(order) / mean);
412 return lang::Distrib<T>::erlang(rate, std::size_t(order));
413 }
414 // fitMean on any other family is honoured on the mean alone -> Exp.
415 return lang::Distrib<T>::exp_mean(num_traits<T>::from_double(mean));
416 }
417 if (method == "fitMeanAndSCV") {
418 const double mean = fit.at("mean").get<double>();
419 const double scv = fit.at("scv").get<double>();
420 if (type == "Erlang")
421 return lang::Distrib<T>::erlang_fit(num_traits<T>::from_double(mean),
422 num_traits<T>::from_double(scv));
423 if (type == "HyperExp") return hyperexp_fit_mean_scv<T>(mean, scv);
424 if (std::fabs(scv - 1.0) < 1e-12)
425 return lang::Distrib<T>::exp_mean(num_traits<T>::from_double(mean));
426 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: fitMeanAndSCV for family '" + type +
427 "' is not reconstructed; use explicit params");
428 }
429 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: unsupported fit method '" + method + "' for '" + type +
430 "'");
431}
432
433/** Reconstruct a distribution from a model.json distribution record. */
434template <class T>
435lang::Distrib<T> dist_from_json(const json& obj) {
436 const std::string type = obj.at("type").get<std::string>();
437 if (type == "Immediate") return lang::Distrib<T>::immediate();
438 if (type == "Disabled") return lang::Distrib<T>::disabled_dist();
439
440 // A Prior arrives in one of its TWO forms, tagged by `kind` and defaulting
441 // to the discrete one when the tag is absent, as every model.json written
442 // before the continuous form existed is. The discrete form is the
443 // alternative set plus the weights. The CONTINUOUS form is the parameter
444 // density plus the distribution its factory BUILDS, with the parameter left
445 // in the slots the factory fills (`linemodel_save.m:prior_factory2json`):
446 // the handle itself cannot cross JSON, but substituting theta into those
447 // slots reconstructs the same alternative at any node count, so
448 // `options.samples` still means what it means in MATLAB. See
449 // _kb/09-ldes-and-cache.md for the encoding and its one restriction.
450 if (type == "Prior") {
451 const std::string kind =
452 obj.contains("kind") ? obj.at("kind").get<std::string>() : std::string("discrete");
453 if (kind != "discrete" && kind != "continuous")
454 throw InputError(ErrorKind{"Format"}, "network_reader: a Prior's 'kind' is 'discrete' or 'continuous', got '" +
455 kind + "'");
456 if (kind == "continuous") {
457 if (!obj.contains("paramDist") || !obj.contains("factory"))
458 throw InputError(ErrorKind{"Format"},
459 "network_reader: a continuous Prior carries 'paramDist' and 'factory' (a "
460 "template distribution plus the parameter slots it fills)");
461 const json& fac = obj.at("factory");
462 if (!fac.contains("template") || !fac.contains("slots"))
463 throw InputError(ErrorKind{"Format"},
464 "network_reader: a continuous Prior's 'factory' carries 'template' and "
465 "'slots'");
466 const json tmpl = fac.at("template");
467 std::vector<std::string> slots;
468 for (const json& s : fac.at("slots")) slots.push_back(s.get<std::string>());
469 if (slots.empty())
470 throw InputError(ErrorKind{"Format"},
471 "network_reader: a continuous Prior's factory names no parameter slot, so the "
472 "parameter would not reach the distribution it builds");
473 if (!tmpl.contains("params"))
474 throw InputError(ErrorKind{"Format"},
475 "network_reader: a continuous Prior's factory template carries its parameters "
476 "as 'params'; a fitted or phase-type representation has no named slot");
477 for (std::size_t l = 0; l < slots.size(); ++l)
478 if (!tmpl.at("params").contains(slots[l]))
479 throw InputError(ErrorKind{"Format"}, "network_reader: a continuous Prior's factory names '" +
480 slots[l] + "' as a parameter slot, but its template has no "
481 "such parameter");
482 // THETA CROSSES AS A DOUBLE, which costs nothing it was not already
483 // costing: `dist_quantile` reaches it by bisection to FineTol, so the
484 // parameter is an approximation of the stratum median well above
485 // double resolution before this substitution sees it.
486 const std::function<lang::Distrib<T>(const T&)> factory =
487 [tmpl, slots](const T& theta) {
488 json j = tmpl;
489 for (std::size_t l = 0; l < slots.size(); ++l)
490 j["params"][slots[l]] = num_traits<T>::to_double(theta);
491 return dist_from_json<T>(j);
492 };
493 return lang::prior_continuous<T>(dist_from_json<T>(obj.at("paramDist")), factory);
494 }
495 if (!obj.contains("distributions") || !obj.contains("probabilities"))
496 throw InputError(ErrorKind{"Format"},
497 "network_reader: a discrete Prior carries 'distributions' and 'probabilities'");
498 std::vector<lang::Distrib<T> > alts;
499 for (const json& a : obj.at("distributions")) alts.push_back(dist_from_json<T>(a));
500 std::vector<T> probs;
501 for (const json& p : obj.at("probabilities"))
502 probs.push_back(num_traits<T>::from_double(p.get<double>()));
503 return lang::prior_discrete<T>(alts, probs);
504 }
505
506 // NNPP (Lewis-Shedler thinning plus SCIATA). The wire form is the shared one:
507 // {"type":"NNPP","params":{"rate":{"kind":"eptmp","alpha","gamma","omega","phi"}
508 // or {"kind":"pwlinear","times","rates"},"horizon","dispersion","cyclic","Q"}}.
509 // The fields sit inside "params", as NHPP's do; top-level fields are read
510 // only when "params" is absent.
511 // The horizon is redundant for a pwlinear rate and is checked against it.
512 if (type == "NNPP") {
513 const json& p = obj.contains("params") ? obj.at("params") : obj;
514 const json& rate = p.at("rate");
515 auto vec = [](const json& a) {
516 std::vector<double> v;
517 if (a.is_number()) {
518 v.push_back(a.get<double>());
519 return v;
520 }
521 for (const json& x : a) v.push_back(x.get<double>());
522 return v;
523 };
524 const double disp = p.contains("dispersion") ? p.at("dispersion").get<double>() : 1.0;
525 const bool cyc = !p.contains("cyclic") || p.at("cyclic").get<bool>();
526 const int Q = p.contains("Q") ? p.at("Q").get<int>() : 200;
527 const std::string kind = rate.at("kind").get<std::string>();
528 if (kind == "eptmp") {
529 if (!p.contains("horizon"))
530 throw InputError(ErrorKind{"Format"}, "network_reader: an eptmp NNPP needs a 'horizon'");
531 return lang::Distrib<T>::nnpp_eptmp(vec(rate.at("alpha")), vec(rate.at("gamma")),
532 vec(rate.at("omega")), vec(rate.at("phi")),
533 p.at("horizon").get<double>(), disp, cyc, Q);
534 }
535 if (kind == "pwlinear") {
536 const std::vector<double> times = vec(rate.at("times"));
537 if (p.contains("horizon") && !times.empty()) {
538 const double S = p.at("horizon").get<double>();
539 if (std::abs(S - times.back()) > 1e-9 * std::max(1.0, std::abs(S)))
540 throw InputError(ErrorKind{"Format"},
541 "network_reader: an NNPP 'horizon' disagrees with the last pwlinear time");
542 }
543 return lang::Distrib<T>::nnpp_piecewise_linear(times, vec(rate.at("rates")), disp, cyc, Q);
544 }
545 throw InputError(ErrorKind{"Format"}, "network_reader: NNPP rate kind '" + kind +
546 "' is not one of eptmp, pwlinear");
547 }
548
549 // The time-inhomogeneous families. The wire form is the reference's
550 // (`linemodel_save.m:2275-2302`, `linemodel_io.py:64-83`): a breakpoint
551 // vector plus one matrix (or one row, or one scalar) per segment, and a
552 // `cyclic` flag. NHPP carries `rates`, MAPt `D0`/`D1`, PHt `alpha`/`S`.
553 if (type == "NHPP" || type == "MAPt" || type == "PHt" || type == "MMAPt" ||
554 type == "MPHt" || type == "BMMAPt") {
555 const json& p = obj.at("params");
556 std::vector<T> bp;
557 for (const json& b : p.at("breakpoints"))
558 bp.push_back(num_traits<T>::from_double(b.get<double>()));
559 // ABSENT MEANS CYCLIC, matching the constructor default in all three other
560 // codebases. This used to read `contains && get<bool>()`, which defaulted an
561 // absent key to FALSE and so silently turned a repeating schedule into a
562 // transient one that stops emitting past its horizon -- a truncated stream
563 // rather than an error.
564 const bool cyc = !p.contains("cyclic") || p.at("cyclic").get<bool>();
565 // A SEGMENT MATRIX MAY ARRIVE COLLAPSED, and the other three codebases
566 // all read it that way. The writers drop the nesting of a one-row or
567 // one-column matrix -- MATLAB's `jsonencode` turns a 1x1 double into a
568 // bare number, the JAR's `matrixToJsonArray` turns any vector into a
569 // flat array -- so a ONE-PHASE MAPt (which is how an NHPP is written as
570 // a matrix schedule) reaches here as `[-2.0]` or as `-2.0`, and reading
571 // it strictly as an array of rows threw `type must be array, but is
572 // number` on a model every other engine accepts. The reference's
573 // `jsonToMatrix2DLenient` and numpy's `atleast_2d` do exactly this.
574 auto read_seg = [&](const json& seg) {
575 if (seg.is_number()) {
576 Matrix<T> M(1, 1);
577 M(0, 0) = num_traits<T>::from_double(num_from_json(seg));
578 return M;
579 }
580 if (!seg.is_array())
581 throw InputError(ErrorKind{"Format"}, "network_reader: a schedule segment must be a matrix, "
582 "a row of numbers, or a single number");
583 if (!seg.empty() && seg.at(0).is_number()) {
584 Matrix<T> M(1, seg.size());
585 for (std::size_t b = 0; b < seg.size(); ++b)
586 M(0, b) = num_traits<T>::from_double(num_from_json(seg.at(b)));
587 return M;
588 }
589 return mat_from_json<T>(seg);
590 };
591 auto read_mats = [&](const char* key) {
592 std::vector<Matrix<T> > out;
593 for (const json& seg : p.at(key)) out.push_back(read_seg(seg));
594 return out;
595 };
596 if (type == "NHPP") {
597 std::vector<T> rates;
598 for (const json& r : p.at("rates"))
599 rates.push_back(num_traits<T>::from_double(r.get<double>()));
600 return lang::Distrib<T>::nhpp(bp, rates, cyc);
601 }
602 if (type == "MAPt")
603 return lang::Distrib<T>::mapt(bp, read_mats("D0"), read_mats("D1"), cyc);
604 // The MARKED schedules nest one level deeper: `D1k` (resp. `exit`) is an array
605 // over MARKS of an array over SEGMENTS, so each mark's segments go through the
606 // same lenient per-segment read.
607 auto read_mark_mats = [&](const char* key) {
608 std::vector<std::vector<Matrix<T> > > out;
609 for (const json& per_mark : p.at(key)) {
610 if (!per_mark.is_array())
611 throw InputError(ErrorKind{"Format"}, "network_reader: the marked schedule key '" +
612 std::string(key) + "' must nest marks over segments");
613 std::vector<Matrix<T> > segs;
614 for (const json& seg : per_mark) segs.push_back(read_seg(seg));
615 out.push_back(segs);
616 }
617 return out;
618 };
619 if (type == "MMAPt")
620 return lang::Distrib<T>::mmapt(bp, read_mats("D0"), read_mark_mats("D1k"), cyc);
621 if (type == "BMMAPt") {
622 // `D1kb` nests one level deeper again: mark, then batch size, then
623 // segment. Each mark's batch list goes through the same lenient
624 // per-segment read, so a one-phase block still arrives as a bare number.
625 std::vector<std::vector<std::vector<Matrix<T> > > > blocks;
626 for (const json& per_mark : p.at("D1kb")) {
627 if (!per_mark.is_array())
628 throw InputError(ErrorKind{"Format"}, "network_reader: 'D1kb' must nest marks over batch sizes "
629 "over segments");
630 std::vector<std::vector<Matrix<T> > > per_batch;
631 for (const json& batch : per_mark) {
632 if (!batch.is_array())
633 throw InputError(ErrorKind{"Format"}, "network_reader: 'D1kb' must nest marks over batch "
634 "sizes over segments");
635 std::vector<Matrix<T> > segs;
636 for (const json& seg : batch) segs.push_back(read_seg(seg));
637 per_batch.push_back(segs);
638 }
639 blocks.push_back(per_batch);
640 }
641 return lang::Distrib<T>::bmmapt(bp, read_mats("D0"), blocks, cyc);
642 }
643 std::vector<std::vector<T> > alphas;
644 for (const json& a : p.at("alpha")) {
645 const std::vector<double> row = a.get<std::vector<double> >();
646 std::vector<T> av;
647 for (double v : row) av.push_back(num_traits<T>::from_double(v));
648 alphas.push_back(av);
649 }
650 if (type == "MPHt") {
651 // The exit vectors reach the factory as plain columns; a writer may have
652 // collapsed each to a flat row, which read_mark_mats returns as 1-by-h.
653 const std::vector<std::vector<Matrix<T> > > ex = read_mark_mats("exit");
654 std::vector<std::vector<std::vector<T> > > exits;
655 for (const std::vector<Matrix<T> >& per_mark : ex) {
656 std::vector<std::vector<T> > segs;
657 for (const Matrix<T>& M : per_mark) {
658 std::vector<T> v;
659 for (std::size_t i = 0; i < M.rows(); ++i)
660 for (std::size_t j = 0; j < M.cols(); ++j) v.push_back(M(i, j));
661 segs.push_back(v);
662 }
663 exits.push_back(segs);
664 }
665 return lang::Distrib<T>::mpht(bp, alphas, read_mats("S"), exits, cyc);
666 }
667 return lang::Distrib<T>::pht(bp, alphas, read_mats("S"), cyc);
668 }
669
670 // A Replayer names a trace FILE, and the writers add the APH fit of its
671 // first three moments beside it precisely because that path may not resolve
672 // on another machine. Reading the trace back gives the same distribution
673 // MATLAB had; the fit is the documented fallback, and the stored mean the
674 // last resort. This branch precedes the `ph` one below, which would
675 // otherwise turn every Replayer into a bare PH and drop the trace.
676 if (type == "Replayer" || type == "Trace") {
677 if (obj.contains("params") && obj.at("params").contains("fileName")) {
678 const std::string path = obj.at("params").at("fileName").get<std::string>();
679 std::ifstream tr(path.c_str());
680 if (tr) {
681 std::vector<T> samples;
682 double v = 0.0;
683 while (tr >> v) samples.push_back(num_traits<T>::from_double(v));
684 if (!samples.empty()) {
685 lang::Distrib<T> d = lang::Distrib<T>::replayer(samples);
686 d.trace_file = path; // only the exporters read it back
687 return d;
688 }
689 }
690 }
691 if (obj.contains("ph")) {
692 const json& ph = obj.at("ph");
693 const std::vector<double> a = ph.at("alpha").get<std::vector<double> >();
694 const std::vector<std::vector<double> > rows =
695 ph.at("T").get<std::vector<std::vector<double> > >();
696 std::vector<T> alpha;
697 for (double x : a) alpha.push_back(num_traits<T>::from_double(x));
698 Matrix<T> A(rows.size(), rows.empty() ? 0 : rows[0].size());
699 for (std::size_t i = 0; i < rows.size(); ++i)
700 for (std::size_t j = 0; j < rows[i].size(); ++j)
701 A(i, j) = num_traits<T>::from_double(rows[i][j]);
702 return lang::Distrib<T>::phase_type(alpha, A, true);
703 }
704 if (obj.contains("params") && obj.at("params").contains("mean"))
706 num_traits<T>::from_double(obj.at("params").at("mean").get<double>()));
707 throw InputError(ErrorKind{"Format"},
708 "network_reader: a Replayer carries neither a readable trace file, nor the APH fit "
709 "the writers add beside it, nor a mean; there is nothing to reconstruct");
710 }
711
712 // Markovian arrival families carry an explicit (D0, D1). A generic MAP/MMAP
713 // arrives as a `map` object; an MMPP2 as its four rate params.
714 if (type == "MMPP2") {
715 const json& p = obj.at("params");
716 const double l0 = p.at("lambda0").get<double>(), l1 = p.at("lambda1").get<double>();
717 const double s0 = p.at("sigma0").get<double>(), s1 = p.at("sigma1").get<double>();
718 Matrix<T> D0(2, 2), D1(2, 2);
719 D1(0, 0) = num_traits<T>::from_double(l0);
720 D1(1, 1) = num_traits<T>::from_double(l1);
721 D0(0, 0) = num_traits<T>::from_double(-(l0 + s0));
722 D0(0, 1) = num_traits<T>::from_double(s0);
723 D0(1, 0) = num_traits<T>::from_double(s1);
724 D0(1, 1) = num_traits<T>::from_double(-(l1 + s1));
726 }
727 if (type == "MAP" || type == "MMPP") {
728 if (!obj.contains("map"))
729 throw InputError(ErrorKind{"Format"}, "network_reader: " + type + " carries no 'map' (D0, D1) object");
730 const json& mp = obj.at("map");
731 return lang::Distrib<T>::map_dist(mat_from_json<T>(mp.at("D0")),
732 mat_from_json<T>(mp.at("D1")),
734 }
735 // A MARKED MAP carries one arrival block per mark in its own `mmap` object;
736 // the aggregate D1 the unmarked consumers read is their sum, rebuilt on load
737 // exactly as the reference readers do.
738 // A MARKED PH is the renewal marked family: it is read as (alpha, S, {s_c}) and
739 // lowered on the spot to the MMAP cell D0 = S, D1c = s_c alpha, keeping the MPH
740 // process type so the featset gate still tells the two apart.
741 if (type == "MPH" || type == "MarkedPH") {
742 if (!obj.contains("mph"))
743 throw InputError(ErrorKind{"Format"}, "network_reader: " + type +
744 " carries no 'mph' (alpha, S, exit) object");
745 const json& mp = obj.at("mph");
746 const Matrix<T> alpha_m = mat_from_json<T>(mp.at("alpha"));
747 const Matrix<T> S = mat_from_json<T>(mp.at("S"));
748 const std::size_t H = S.rows();
749 if (alpha_m.rows() * alpha_m.cols() != H)
750 throw InputError(ErrorKind{"Format"}, "network_reader: an MPH's alpha and S disagree in order");
751 std::vector<T> alpha;
752 for (std::size_t i = 0; i < alpha_m.rows(); ++i)
753 for (std::size_t j = 0; j < alpha_m.cols(); ++j) alpha.push_back(alpha_m(i, j));
754 const std::vector<Matrix<T> > ex = mat_list_from_json<T>(mp.at("exit"));
755 std::vector<std::vector<T> > exits;
756 for (const Matrix<T>& sk : ex) {
757 if (sk.rows() * sk.cols() != H)
758 throw InputError(ErrorKind{"Format"}, "network_reader: an MPH exit vector and S disagree in order");
759 std::vector<T> sv;
760 for (std::size_t i = 0; i < sk.rows(); ++i)
761 for (std::size_t j = 0; j < sk.cols(); ++j) sv.push_back(sk(i, j));
762 exits.push_back(sv);
763 }
764 // Through the factory, so a document gets the same validation and the same
765 // lowering as a model built in code.
766 return lang::Distrib<T>::mph(alpha, S, exits);
767 }
768 if (type == "MMAP" || type == "MarkedMAP") {
769 if (!obj.contains("mmap"))
770 throw InputError(ErrorKind{"Format"}, "network_reader: " + type + " carries no 'mmap' (D0, D1k) object");
771 const json& mp = obj.at("mmap");
772 return lang::Distrib<T>::mmap(mat_from_json<T>(mp.at("D0")),
773 mat_list_from_json<T>(mp.at("D1k")));
774 }
775 // A BMAP writes the WHOLE block list D0, D1, ..., Dk, where Dj carries an
776 // arrival of batch size j; a MarkedMMPP writes the same list plus the mark
777 // count K, and lowers to the MMAP process type as MATLAB's fromText does.
778 if (type == "BMAP" || type == "MarkedMMPP") {
779 const json& p = obj.at("params");
780 const std::vector<Matrix<T> > D = mat_list_from_json<T>(p.at("D"));
781 if (type == "BMAP") return lang::Distrib<T>::bmap(D);
782 if (D.size() < 2)
783 throw InputError(ErrorKind{"Format"}, "network_reader: a MarkedMMPP carries D0 and at least one marked block");
784 // The list is {D0, D11..D1K} (MATLAB, Python) or the M3A form
785 // {D0, D1_agg, D11..D1K} (the JAR), told apart by the mark count K as
786 // MATLAB MarkedMMPP(D,K) does. Without K the JAR's aggregate was read
787 // as one more mark.
788 std::size_t first = 1;
789 if (p.contains("K")) {
790 const std::size_t K = p.at("K").get<std::size_t>();
791 if (K + 2 == D.size()) first = 2;
792 else if (K + 1 != D.size())
793 throw InputError(ErrorKind{"Format"}, "network_reader: a MarkedMMPP's K matches neither "
794 "{D0, D11..D1K} nor {D0, D1, D11..D1K}");
795 }
796 return lang::Distrib<T>::marked_mmpp(D[0], std::vector<Matrix<T> >(D.begin() + first, D.end()));
797 }
798 if (type == "DMAP") {
799 const json& p = obj.at("params");
800 return lang::Distrib<T>::dmap(mat_from_json<T>(p.at("D0")), mat_from_json<T>(p.at("D1")));
801 }
802 if (type == "RAP") {
803 const json& p = obj.at("params");
804 return lang::Distrib<T>::rap(mat_from_json<T>(p.at("H0")), mat_from_json<T>(p.at("H1")));
805 }
806 // ME and CME share one process type: the concentrated representation is a
807 // subclass carrying no distinct tag, exactly as MATLAB `fromText` maps it.
808 if (type == "ME" || type == "CME") {
809 const json& p = obj.at("params");
810 const std::vector<double> a = p.at("alpha").get<std::vector<double> >();
811 std::vector<T> alpha;
812 for (double v : a) alpha.push_back(num_traits<T>::from_double(v));
813 return lang::Distrib<T>::me(alpha, mat_from_json<T>(p.at("A")));
814 }
815
816 // A phase-type family carries its representation as `ph: {alpha, T}`, which
817 // is the third form the writer emits alongside `params` and `fit`. Without
818 // this branch a PH/APH/Coxian written with an explicit representation --
819 // exactly what `Coxian.fit`, `APH.fitMeanAndSCV` and the MAP-to-PH paths
820 // produce -- was refused as "has neither params nor a fit block", which is a
821 // statement about what the reader looked for and not about what the writer
822 // sent. The representation is complete on the wire; only the branch was
823 // missing.
824 if (obj.contains("ph")) {
825 const json& ph = obj.at("ph");
826 const std::vector<double> a = ph.at("alpha").get<std::vector<double> >();
827 const std::vector<std::vector<double> > rows =
828 ph.at("T").get<std::vector<std::vector<double> > >();
829 if (a.empty() || rows.size() != a.size())
830 throw InputError(ErrorKind{"Format"}, "network_reader: distribution '" + type +
831 "' has a 'ph' block whose alpha and T disagree in order");
832 std::vector<T> alpha;
833 alpha.reserve(a.size());
834 for (double v : a) alpha.push_back(num_traits<T>::from_double(v));
835 Matrix<T> A(rows.size(), rows.empty() ? 0 : rows[0].size());
836 for (std::size_t i = 0; i < rows.size(); ++i)
837 for (std::size_t j = 0; j < rows[i].size(); ++j)
838 A(i, j) = num_traits<T>::from_double(rows[i][j]);
839 // APH and PH share a representation and differ only in the type tag,
840 // so the wire's own name decides it rather than a structural test.
841 return lang::Distrib<T>::phase_type(alpha, A, type == "APH");
842 }
843
844 // Explicit parameters take precedence over a fit block, mirroring the
845 // reference readers.
846 if (!obj.contains("params") && obj.contains("fit"))
847 return dist_from_fit<T>(type, obj.at("fit"));
848 if (!obj.contains("params"))
849 throw InputError(ErrorKind{"Format"}, "network_reader: distribution '" + type +
850 "' has neither params nor a fit block");
851 const json& p = obj.at("params");
852 if (type == "Exp") {
853 const double lam = p.contains("lambda") ? p.at("lambda").get<double>()
854 : p.at("rate").get<double>();
855 return lang::Distrib<T>::exp_rate(num_traits<T>::from_double(lam));
856 }
857 if (type == "Det") return lang::Distrib<T>::det(num_traits<T>::from_double(p.at("value").get<double>()));
858 if (type == "Erlang") {
859 const double lam = p.at("lambda").get<double>();
860 const long k = p.at("k").get<long>();
861 return lang::Distrib<T>::erlang(num_traits<T>::from_double(lam), std::size_t(k));
862 }
863 if (type == "HyperExp") {
864 const std::vector<T> pv = num_vec_from_json<T>(p.at("p"));
865 const std::vector<T> lv = num_vec_from_json<T>(p.at("lambda"));
866 // The two-branch entry point carries MATLAB's getParam order, which a
867 // parameter dump compares against; wider ones take the general form.
868 if (pv.size() == 2 && lv.size() == 2)
869 return lang::Distrib<T>::hyperexp(pv[0], lv[0], lv[1]);
870 return lang::Distrib<T>::hyperexp_n(pv, lv);
871 }
872 if (type == "Coxian")
873 return lang::Distrib<T>::coxian(num_vec_from_json<T>(p.at("mu")),
874 num_vec_from_json<T>(p.at("phi")));
875 if (type == "Cox2")
876 return lang::Distrib<T>::cox2(num_traits<T>::from_double(p.at("mu1").get<double>()),
877 num_traits<T>::from_double(p.at("mu2").get<double>()),
878 num_traits<T>::from_double(p.at("phi1").get<double>()));
879 if (type == "Uniform")
880 return lang::Distrib<T>::uniform(num_traits<T>::from_double(p.at("a").get<double>()),
881 num_traits<T>::from_double(p.at("b").get<double>()));
882 // Gamma(alpha = shape, beta = SCALE), the pairing the JAR loader fixes.
883 if (type == "Gamma")
884 return lang::Distrib<T>::gamma_dist(num_traits<T>::from_double(p.at("alpha").get<double>()),
885 num_traits<T>::from_double(p.at("beta").get<double>()));
886 if (type == "Lognormal")
887 return lang::Distrib<T>::lognormal(num_traits<T>::from_double(p.at("mu").get<double>()),
888 num_traits<T>::from_double(p.at("sigma").get<double>()));
889 // `Normal` shares the (mu, sigma) key pair with `Lognormal` above, and is
890 // the one family here that is never a service process: it crosses the wire
891 // only as the parameter density of a continuous Prior. Refusing it made
892 // every such Prior a model MATLAB could write and this reader could not
893 // read, which is a UQ study that stops at the interchange.
894 if (type == "Normal")
895 return lang::Distrib<T>::normal(num_traits<T>::from_double(p.at("mu").get<double>()),
896 num_traits<T>::from_double(p.at("sigma").get<double>()));
897 // Pareto(alpha = shape, scale) and Weibull(alpha = SCALE, beta = SHAPE):
898 // the two families spell the wire key `alpha` for opposite roles, which is
899 // the reference's convention and the one trap in this table.
900 if (type == "Pareto")
901 return lang::Distrib<T>::pareto(num_traits<T>::from_double(p.at("alpha").get<double>()),
902 num_traits<T>::from_double(p.at("scale").get<double>()));
903 if (type == "Weibull")
904 return lang::Distrib<T>::weibull(num_traits<T>::from_double(p.at("alpha").get<double>()),
905 num_traits<T>::from_double(p.at("beta").get<double>()));
906 // LogLogistic(alpha = SCALE, beta = SHAPE), Weibull's key pairing.
907 if (type == "LogLogistic")
908 return lang::Distrib<T>::loglogistic(num_traits<T>::from_double(p.at("beta").get<double>()),
909 num_traits<T>::from_double(p.at("alpha").get<double>()));
910 // The two wrappers carry the law they wrap in a sibling `dist` block.
911 if (type == "MassAtOrigin" || type == "Defective") {
912 if (!obj.contains("dist"))
913 throw InputError(ErrorKind{"Format"}, "network_reader: '" + type +
914 "' has no inner `dist` block");
915 const lang::Distrib<T> in = dist_from_json<T>(obj.at("dist"));
916 if (type == "MassAtOrigin")
917 return lang::Distrib<T>::mass_at_origin(in, num_traits<T>::from_double(p.at("p0").get<double>()));
918 return lang::Distrib<T>::defective(in, num_traits<T>::from_double(p.at("pInf").get<double>()));
919 }
920 if (type == "DiscreteUniform")
922 num_traits<T>::from_double(p.at("min").get<double>()),
923 num_traits<T>::from_double(p.at("max").get<double>()));
924 if (type == "Bernoulli")
925 return lang::Distrib<T>::bernoulli(num_traits<T>::from_double(p.at("p").get<double>()));
926 if (type == "Binomial")
927 return lang::Distrib<T>::binomial(num_traits<T>::from_double(p.at("n").get<double>()),
928 num_traits<T>::from_double(p.at("p").get<double>()));
929 if (type == "Poisson")
930 return lang::Distrib<T>::poisson(num_traits<T>::from_double(p.at("lambda").get<double>()));
931 if (type == "Geometric")
932 return lang::Distrib<T>::geometric(num_traits<T>::from_double(p.at("p").get<double>()));
933 if (type == "Zipf")
934 return lang::Distrib<T>::zipf(num_traits<T>::from_double(p.at("s").get<double>()),
935 std::size_t(p.at("n").get<long>()));
936 if (type == "DiscreteSampler") {
937 const std::vector<T> pv = num_vec_from_json<T>(p.at("p"));
938 const std::vector<T> xv =
939 p.contains("x") ? num_vec_from_json<T>(p.at("x")) : std::vector<T>();
941 }
942 if (type == "EmpiricalCDF" || type == "EmpiricalCdf")
943 return lang::Distrib<T>::empirical_cdf(num_vec_from_json<T>(p.at("x")),
944 num_vec_from_json<T>(p.at("F")));
945
946 // THE MOMENT-ONLY FALLBACK the writers emit for a family with no JSON
947 // representation of its own: `{type: <name>, params: {mean, scv?}}`, written
948 // with a warning at save time. It is honoured on the moments it carries --
949 // an exponential from a mean alone, and otherwise the acyclic phase-type
950 // matching the two -- rather than refused, because refusing would make a
951 // model unreadable that the reference itself declares readable. The TYPE
952 // TAG IS NOT KEPT: the reconstruction is a different law that happens to
953 // share two moments, and claiming the original name for it would make
954 // `sn.procid` lie about what every solver is actually integrating.
955 if (p.contains("mean") && !p.contains("scv"))
956 return lang::Distrib<T>::exp_mean(num_traits<T>::from_double(p.at("mean").get<double>()));
957 if (p.contains("mean") && p.contains("scv")) {
958 const double mean = p.at("mean").get<double>();
959 const double scv = p.at("scv").get<double>();
960 if (std::fabs(scv - 1.0) < 1e-12)
961 return lang::Distrib<T>::exp_mean(num_traits<T>::from_double(mean));
962 if (scv < 1.0)
963 return lang::Distrib<T>::erlang_fit(num_traits<T>::from_double(mean),
964 num_traits<T>::from_double(scv));
965 return hyperexp_fit_mean_scv<T>(mean, scv);
966 }
967 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: unsupported distribution family '" + type +
968 "' (params form)");
969}
970
971/**
972 * The popularity LAW, recorded beside the pmf for the exporters.
973 *
974 * JMT's Cache section takes a parametric popularity and cannot be given a pmf,
975 * so the exponent and the support size have to survive the read; every solver
976 * still reads the pmf `pmf_from_json` returns.
977 */
978template <class T>
979typename qn::CacheParam<T>::Popularity popularity_kind_from_json(const json& obj,
980 std::size_t nitems) {
981 typename qn::CacheParam<T>::Popularity k;
982 const std::string type = obj.value("type", std::string());
983 const json& p = obj.contains("params") ? obj.at("params") : obj;
984 if (type == "Zipf") {
986 k.s = p.at("s").get<double>();
987 k.n = p.contains("n") ? std::size_t(p.at("n").get<long>()) : nitems;
988 } else if (type == "DiscreteSampler" || p.contains("p")) {
990 k.n = p.contains("p") ? p.at("p").size() : nitems;
991 }
992 return k;
993}
994
995/**
996 * The item-popularity pmf of a cache read class, `nodeparam.pread`.
997 *
998 * A popularity is a DISCRETE distribution over the item ranks, and the writers
999 * emit whichever family the model used: `DiscreteSampler` carries the pmf
1000 * itself, `Zipf` carries only (s, n) and the pmf p_i = i^-s / H(s,n) is
1001 * rebuilt here. Reading only the first form left every Zipf-popularity cache
1002 * with an EMPTY read vector, which is a uniform cache by default rather than a
1003 * refusal.
1004 */
1005template <class T>
1006std::vector<T> pmf_from_json(const json& obj, std::size_t nitems) {
1007 const std::string type = obj.value("type", std::string());
1008 const json& p = obj.contains("params") ? obj.at("params") : obj;
1009 std::vector<T> out;
1010 // THE ARRAY TEST IS THE WHOLE GUARD. `params.p` is also the SCALAR success
1011 // probability of Bernoulli, Binomial and Geometric, and `p.contains("p")`
1012 // alone admitted those into this branch, where iterating a JSON scalar
1013 // yields one element and the family collapsed to a one-point pmf.
1014 if (type == "DiscreteSampler" || (p.contains("p") && p.at("p").is_array())) {
1015 for (const json& v : p.at("p")) out.push_back(num_traits<T>::from_double(v.get<double>()));
1016 return out;
1017 }
1018 if (type == "Zipf") {
1019 const double s = p.at("s").get<double>();
1020 const std::size_t n = p.contains("n") ? std::size_t(p.at("n").get<long>()) : nitems;
1021 double h = 0.0;
1022 for (std::size_t k = 1; k <= n; ++k) h += std::pow(double(k), -s);
1023 for (std::size_t k = 1; k <= n; ++k)
1024 out.push_back(num_traits<T>::from_double(std::pow(double(k), -s) / h));
1025 return out;
1026 }
1027 throw UnsupportedError(ErrorKind{"Import"},
1028 "network_reader: a cache popularity is written as '" + type +
1029 "', and the discrete families carrying an item pmf are DiscreteSampler and Zipf");
1030}
1031
1032/**
1033 * How far an infinitely-supported batch law is materialized.
1034 *
1035 * `sn.signalremdist` is a VECTOR, so a Geometric or a Poisson has to stop
1036 * somewhere, and the consumer (`signal_batch_pmf`) lumps everything past the
1037 * last stored entry onto "remove the whole eligible population". That lumping
1038 * is the REFERENCE'S OWN rule only for mass beyond the population present, so
1039 * the vector must outrun any population a station can hold; 4096 does, for a
1040 * chain whose per-class cutoff is a few hundred at the very most.
1041 */
1042constexpr std::size_t REMOVAL_PMF_MAX_TERMS = 4096;
1043
1044/**
1045 * The batch-size pmf of a G-network signal, INDEXED BY THE BATCH SIZE ITSELF.
1046 *
1047 * WHY THIS IS NOT `pmf_from_json`. That function returns a cache popularity,
1048 * whose entry i is the mass of RANK i+1; here entry b is the mass of the batch
1049 * size b, counting from a batch of ZERO. `sn.signalremdist` is documented on the
1050 * second convention (network_struct.h) and both consumers -- `signal_batch_pmf`
1051 * for the chain and the LDES draw -- read it that way, so a reader that returns
1052 * the first shifts every batch by one job.
1053 *
1054 * MATLAB EVALUATES THE LAW, IT DOES NOT TABULATE IT: `State.signalBatchPMF`
1055 * calls `dist.evalPMF(0:ntot)`, so the wire carries the FAMILY (`{type:
1056 * "Geometric", params: {p: 0.5}}`) and the pmf has to be rebuilt here. Reading
1057 * only `DiscreteSampler` sent every parametric family through a branch that
1058 * iterated the scalar `params.p` and produced the one-point pmf
1059 * P(B = 0) = p -- a signal that removes NOTHING with probability p and empties
1060 * the station otherwise. On the `test_batch_removal` G-network that read
1061 * utilization 0.58690 against the reference's 0.56422.
1062 */
1063template <class T>
1064std::vector<T> removal_pmf_from_json(const json& obj) {
1065 const std::string type = obj.value("type", std::string());
1066 const json& p = obj.contains("params") ? obj.at("params") : obj;
1067 std::vector<T> out;
1068 auto put = [&out](std::size_t k, double v) {
1069 if (out.size() <= k) out.resize(k + 1, num_traits<T>::from_int(0));
1070 out[k] = num_traits<T>::from_double(num_traits<T>::to_double(out[k]) + v);
1071 };
1072 if (type == "DiscreteSampler" || (p.contains("p") && p.at("p").is_array())) {
1073 // `x` IS THE SUPPORT AND NOT A LABEL: MATLAB's `DiscreteSampler(p, x)`
1074 // defaults it to 1..n and `evalPMF` looks a value up in it, so dropping
1075 // it would read the first mass as a batch of zero.
1076 const json& pv = p.at("p");
1077 const bool has_x = p.contains("x") && p.at("x").is_array();
1078 for (std::size_t i = 0; i < pv.size(); ++i) {
1079 const double xi =
1080 has_x ? p.at("x").at(i).get<double>() : static_cast<double>(i + 1);
1081 if (xi < 0) throw InputError(ErrorKind{"Format"}, "network_reader: a batch size cannot be negative");
1082 put(static_cast<std::size_t>(xi + 0.5), pv.at(i).get<double>());
1083 }
1084 return out;
1085 }
1086 if (type == "Bernoulli") {
1087 const double q = p.at("p").get<double>();
1088 put(0, 1.0 - q);
1089 put(1, q);
1090 return out;
1091 }
1092 if (type == "Binomial") {
1093 const double q = p.at("p").get<double>();
1094 const std::size_t n = static_cast<std::size_t>(p.at("n").get<double>() + 0.5);
1095 double term = std::pow(1.0 - q, static_cast<double>(n));
1096 for (std::size_t k = 0; k <= n; ++k) {
1097 put(k, term);
1098 if (k < n && q < 1.0)
1099 term *= (static_cast<double>(n - k) / static_cast<double>(k + 1)) * q / (1.0 - q);
1100 }
1101 return out;
1102 }
1103 if (type == "Poisson") {
1104 const double lam = p.at("lambda").get<double>();
1105 double term = std::exp(-lam), acc = 0.0;
1106 for (std::size_t k = 0; k < REMOVAL_PMF_MAX_TERMS; ++k) {
1107 put(k, term);
1108 acc += term;
1109 if (acc > 1.0 - 1e-15) break;
1110 term *= lam / static_cast<double>(k + 1);
1111 }
1112 return out;
1113 }
1114 if (type == "Geometric") {
1115 // MATLAB's Geometric(p) counts TRIALS TO THE FIRST SUCCESS, support
1116 // {1, 2, ...}: P(B = 0) is zero, so a signal always takes at least one.
1117 const double q = p.at("p").get<double>();
1118 if (q <= 0.0 || q > 1.0) throw InputError(ErrorKind{"Format"}, "network_reader: Geometric(p) needs 0 < p <= 1");
1119 put(0, 0.0);
1120 double term = q, acc = 0.0;
1121 for (std::size_t k = 1; k <= REMOVAL_PMF_MAX_TERMS; ++k) {
1122 put(k, term);
1123 acc += term;
1124 if (acc > 1.0 - 1e-15) break;
1125 term *= (1.0 - q);
1126 }
1127 return out;
1128 }
1129 if (type == "DiscreteUniform") {
1130 const long lo = static_cast<long>(p.at("min").get<double>());
1131 const long hi = static_cast<long>(p.at("max").get<double>());
1132 if (hi < lo || lo < 0)
1133 throw InputError(ErrorKind{"Format"}, "network_reader: DiscreteUniform(min,max) needs 0 <= min <= max");
1134 const double w = 1.0 / static_cast<double>(hi - lo + 1);
1135 for (long k = lo; k <= hi; ++k) put(static_cast<std::size_t>(k), w);
1136 return out;
1137 }
1138 if (type == "Det") {
1139 const double v = p.contains("t") ? p.at("t").get<double>() : p.at("mean").get<double>();
1140 if (v < 0) throw InputError(ErrorKind{"Format"}, "network_reader: a batch size cannot be negative");
1141 put(static_cast<std::size_t>(v + 0.5), 1.0);
1142 return out;
1143 }
1144 throw UnsupportedError(ErrorKind{"Import"},
1145 "network_reader: a signal removal law is written as '" + type +
1146 "', and the discrete families a batch size can be drawn from are DiscreteSampler, "
1147 "Bernoulli, Binomial, Poisson, Geometric, DiscreteUniform and Det");
1148}
1149
1150/**
1151 * Rebuild a class- or joint-dependence handle from the box-lattice table the
1152 * writers emit.
1153 *
1154 * A function handle cannot cross JSON, so `linemodel_save.m` (`cd_scaling_table`),
1155 * the JAR `LineModelIO` and the Python writer all MATERIALIZE beta(n) / eta_i(n)
1156 * over 0 <= n(r) <= cutoffs(r), keyed by the comma-joined 0-based per-class
1157 * counts. This rebuilds the callable from that table, clamping the population to
1158 * the cutoffs so the scaling SATURATES beyond the tabulated range exactly as the
1159 * table intends, and returning all-ones for a composition absent from the table
1160 * so an unlisted state leaves the nominal rate unscaled. An EMPTY `cutoffs`
1161 * (the key absent on the wire) means no clamping. Twin of the Python
1162 * `_cd_table_to_callable`.
1163 */
1164template <class T>
1165lang::CdScaling<T> cd_scaling_from_json(const json& tbl, const std::vector<int>& cutoffs,
1166 std::size_t K) {
1167 std::map<std::string, std::vector<T> > table;
1168 for (auto it = tbl.begin(); it != tbl.end(); ++it)
1169 table[it.key()] = num_vec_from_json<T>(it.value());
1170 const std::vector<int> cut = cutoffs;
1171 return [table, cut, K](const std::vector<T>& n) {
1172 std::string key;
1173 for (std::size_t r = 0; r < K; ++r) {
1174 int v = r < n.size()
1175 ? static_cast<int>(std::lround(num_traits<T>::to_double(n[r])))
1176 : 0;
1177 if (v < 0) v = 0;
1178 if (r < cut.size() && v > cut[r]) v = cut[r];
1179 if (r) key += ',';
1180 key += std::to_string(v);
1181 }
1182 std::vector<T> out(K, num_traits<T>::from_int(1));
1183 typename std::map<std::string, std::vector<T> >::const_iterator it = table.find(key);
1184 if (it == table.end()) return out;
1185 for (std::size_t r = 0; r < K && r < it->second.size(); ++r) out[r] = it->second[r];
1186 return out;
1187 };
1188}
1189
1190/**
1191 * Rebuild the mu(c) of an order-independent / pass-and-swap station from the
1192 * macrostate table the writers materialize (`oi_rate_table` in
1193 * `linemodel_save.m`, `LineModelIO.oiServiceRate` in the JAR).
1194 *
1195 * The handle takes an ORDERED microstate -- the list of 1-based class indices
1196 * in buffer order, which is what `set_pas` is defined over -- and the table is
1197 * keyed by the per-class COUNTS, because mu is order-independent by
1198 * construction. A composition beyond the tabulated cutoffs saturates at them,
1199 * matching how the writer chose those cutoffs (the closed populations, or 10
1200 * for an open class beyond which mu is constant); a composition the table does
1201 * not list returns zero, which is the writer's own encoding of a non-finite
1202 * rate and means the macrostate is unreachable. All four readers agree on that
1203 * 0 (the JAR and Python used to answer the table maximum): a box with cutoffs
1204 * never misses a non-empty state, so a miss is a state above the buffer of a
1205 * no-cutoff simplex table, which the writers' saturation search never reads.
1206 *
1207 * An EMPTY `cutoffs` means no clamping: the table is keyed by the raw counts.
1208 * That is what an absent `oiCutoffs` says on the wire (Python `save_model`
1209 * omits it for a non-saturating mu at a finite buffer and tabulates the whole
1210 * simplex 1 <= sum(n) <= cap instead), and how MATLAB, the JAR and Python read it.
1211 */
1212template <class T>
1213std::function<T(const std::vector<std::size_t>&)> oi_rate_from_json(const json& tbl,
1214 const std::vector<int>& cutoffs,
1215 std::size_t K) {
1216 std::map<std::string, T> table;
1217 for (auto it = tbl.begin(); it != tbl.end(); ++it)
1218 table[it.key()] = num_traits<T>::from_double(it.value().get<double>());
1219 const std::vector<int> cut = cutoffs;
1220 return [table, cut, K](const std::vector<std::size_t>& micro) {
1221 std::vector<int> cnt(K, 0);
1222 for (std::size_t j = 0; j < micro.size(); ++j)
1223 if (micro[j] >= 1 && micro[j] <= K) ++cnt[micro[j] - 1];
1224 std::string key;
1225 for (std::size_t r = 0; r < K; ++r) {
1226 int v = cnt[r];
1227 if (r < cut.size() && v > cut[r]) v = cut[r];
1228 if (r) key += ',';
1229 key += std::to_string(v);
1230 }
1231 typename std::map<std::string, T>::const_iterator it = table.find(key);
1232 return it == table.end() ? num_traits<T>::from_int(0) : it->second;
1233 };
1234}
1235
1236/**
1237 * The declared peak the wire carries, or, for legacy JSON written before the
1238 * peak became mandatory, the peak DERIVED from the table.
1239 *
1240 * Deriving it is not a fabrication: the table is the whole lattice the reference
1241 * `cd_peak_scaling` would sweep, so the maximum over its rows and classes is
1242 * exactly that routine's answer. It skips the all-zero composition (the
1243 * reference's `tot > 0` guard) and any non-finite entry, which a handle may
1244 * legitimately return for an unreachable composition and which would otherwise
1245 * become the normalizer and zero every utilization at the station.
1246 */
1247template <class T>
1248std::vector<T> cd_peak_from_json(const json& blk, const json& tbl) {
1249 if (blk.contains("peak") && !blk.at("peak").empty())
1250 return num_vec_from_json<T>(blk.at("peak"));
1251 double bmax = 0;
1252 for (auto it = tbl.begin(); it != tbl.end(); ++it) {
1253 if (it.key().find_first_not_of("0,") == std::string::npos) continue;
1254 const std::vector<double> row = num_vec_from_json<double>(it.value());
1255 for (double x : row)
1256 if (std::isfinite(x) && x > bmax) bmax = x;
1257 }
1258 return std::vector<T>(1, num_traits<T>::from_double(bmax));
1259}
1260
1261/**
1262 * Refuse any top-level or node-level key that carries model semantics this
1263 * reader does not consume.
1264 *
1265 * The whitelists are the keys the passes below actually read, plus the purely
1266 * descriptive ones. Anything else is a construct the C++ model layer either
1267 * cannot represent or does not yet parse, and it is NAMED rather than dropped.
1268 */
1269inline void reject_unconsumed_model_keys(const json& model) {
1270 static const char* kModelKeys[] = {"name", "type", "nodes",
1271 "classes", "routing", "format",
1272 "version", "rewards", "finiteCapacityRegions",
1273 "routingStrategies", "routingWeights", "routingParams",
1274 "logPath", "globalDependence", "stateDepRouting"};
1275 // EXACTLY the keys a branch below reads, and nothing else. The first draft
1276 // of this list also carried `arrival`, `classCap`, `accessGraph`,
1277 // `joinStrategy`, `joinQuorum`, `fanOut` and `swapGraph`,
1278 // none of which this reader consumes -- whitelisting them would have
1279 // re-admitted the very silent drop the gate exists to stop. When adding a
1280 // key here, grep that the parser actually reads it.
1281 static const char* kNodeKeys[] = {
1282 "name", "type", "scheduling", "servers", "service",
1283 "buffer", "capacity", "dropRule", "schedParams", "pollingType",
1284 "pollingPar", "classSwitchMatrix", "csMatrix", "forkNode",
1285 "tasksPerLink", "fanOutByDest", "fanOutDist", "fanOutProb",
1286 "items", "numItems", "itemLevelCap", "popularity", "replacementStrategy",
1287 "itemSizes", "costCaps", "accessProb", "admissionProb", "accessGraph",
1288 "itemClass",
1289 "cache", "initialState",
1290 "retrievalSystem", "queues", "hitClass", "missClass",
1291 "immediateFeedback", "loadDependence",
1292 "classDependence", "jointDependence",
1293 "modes", "classCap", "departureDiscipline",
1294 "oiServiceRate", "oiCutoffs", "swapGraph",
1295 "arrivalBatch", "markedClasses",
1296 "stateSpace", "statePrior", "joinStrategy", "joinQuorum",
1297 "setupTime", "delayOffTime","switchoverTimes", "breakdown",
1298 "quantum",
1299 "pollingTable", "pollingOrder", "pollingOrderClass",
1300 "pollingOrderThreshold", "pollingTimer",
1301 "serverTypes","heteroSchedPolicy", "serverParallelism",
1302 "fluid", "fluidCapacity", "fluidLevel",
1303 "balking", "retrial", "patience", "orbitImpatience",
1304 "batchRejectProb",
1305 // Logger trace configuration; read into NodeDef::logger below.
1306 "fileName", "filePath", "startTime", "loggerName", "timestamp",
1307 "jobID", "jobClass", "timeSameClass","timeAnyClass"};
1308 // The class object. It had NO gate until every key below was found to be
1309 // read: `isReferenceClass`, `deadline`, `patience`, `spawnClass` and
1310 // `replySignalClass` were all being dropped in silence, each of them a
1311 // different wrong number rather than a diagnostic.
1312 static const char* kClassKeys[] = {
1313 "name", "type", "population", "refNode", "priority",
1314 "openOrClosed","signalType", "targetClass", "removalPolicy","removalDistribution",
1315 "isReferenceClass", "deadline", "patience", "impatienceType",
1316 "spawnClass", "replySignalClass", "immediateFeedback"};
1317 auto known = [](const char* const* tab, std::size_t n, const std::string& k) {
1318 for (std::size_t i = 0; i < n; ++i)
1319 if (k == tab[i]) return true;
1320 return false;
1321 };
1322 const std::string why =
1323 "', which this reader does not implement. Refusing rather than dropping it: a "
1324 "constraint silently discarded here would make every solver return a confident "
1325 "answer for a different model";
1326 for (auto it = model.begin(); it != model.end(); ++it)
1327 if (!known(kModelKeys, sizeof(kModelKeys) / sizeof(*kModelKeys), it.key()))
1328 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: the model carries '" + it.key() + why);
1329 if (model.contains("classes"))
1330 for (const json& cl : model.at("classes"))
1331 for (auto it = cl.begin(); it != cl.end(); ++it)
1332 if (!known(kClassKeys, sizeof(kClassKeys) / sizeof(*kClassKeys), it.key()))
1333 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: class '" +
1334 cl.value("name", std::string("?")) + "' carries '" +
1335 it.key() + why);
1336 if (!model.contains("nodes")) return;
1337 for (const json& nd : model.at("nodes"))
1338 for (auto it = nd.begin(); it != nd.end(); ++it)
1339 if (!known(kNodeKeys, sizeof(kNodeKeys) / sizeof(*kNodeKeys), it.key()))
1340 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: node '" +
1341 nd.value("name", std::string("?")) + "' carries '" +
1342 it.key() + why);
1343}
1344
1345} // namespace detail
1346
1347/**
1348 * Build a `qn::Network<T>` from a parsed model.json envelope.
1349 *
1350 * Two passes: classes and nodes are declared first (a class references its
1351 * reference node by name, a Join references its Fork by name, so every node
1352 * index must exist before the cross-references are wired), then service,
1353 * arrival and routing are applied.
1354 */
1355template <class T>
1356qn::Network<T> build_network_from_json(const detail::json& root) {
1357 using detail::json;
1358 const json& model = root.contains("model") ? root.at("model") : root;
1359 const std::string mtype = model.value("type", std::string("Network"));
1360 if (mtype != "Network") {
1361 // An Environment IS solved by this port, just not by this reader, so
1362 // the refusal names the arm that reads it rather than leaving the
1363 // caller to conclude the model is unsupported.
1364 if (mtype == "Environment")
1365 throw UnsupportedError(ErrorKind{"Import"},
1366 "network_reader: this is an Environment model (a network per stage plus the "
1367 "stage transitions); solve it with -s env, which reads it through "
1368 "environment_reader.h");
1369 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: model type '" + mtype +
1370 "' is not a Network; only Network models are solved by this path");
1371 }
1372
1373 // WHAT THIS READER DOES NOT UNDERSTAND, IT REFUSES. A key carrying model
1374 // semantics that no branch below consumes would otherwise be SILENTLY
1375 // DROPPED, and every solver would then return an answer correct for the
1376 // model received and wrong for the model intended, with no diagnostic
1377 // anywhere. Not hypothetical: `fcr_mm1kdrop` exports a
1378 // `finiteCapacityRegions` block with globalMaxJobs 3 and a drop rule, and
1379 // without this gate the C++ MVA reported QLen 4 -- exactly rho/(1-rho) for
1380 // the UNBOUNDED M/M/1 -- against the exact M/M/1/K value 1.224932. Same
1381 // rule, and same reason, as the unknown-argument refusal on the --api
1382 // boundary: a key that silently takes its default is a wrong answer.
1383 detail::reject_unconsumed_model_keys(model);
1384
1385 qn::Network<T> net(model.value("name", std::string("model")));
1386 net.set_log_path(model.value("logPath", std::string()));
1387
1388 // A ClassSwitch node needs the class count at construction and a Join needs
1389 // its Fork to exist, while a closed class needs its reference node. That
1390 // cycle is broken by ordering the declarations, not by post-hoc setters:
1391 // every node a class or a Join can depend on is created first (pass 1a),
1392 // then the classes (1b), then the dependent nodes (1c). Routing is wired by
1393 // node NAME (pass 3), so this reordering never perturbs the parity table.
1394 const json& nodes = model.at("nodes");
1395 std::map<std::string, std::size_t> node_idx;
1396 std::vector<std::string> node_type(nodes.size());
1397 for (std::size_t i = 0; i < nodes.size(); ++i)
1398 node_type[i] = nodes[i].at("type").get<std::string>();
1399
1400 // -- Pass 1a: nodes that carry no class/fork dependency. -----------------
1401 for (std::size_t i = 0; i < nodes.size(); ++i) {
1402 const json& nd = nodes[i];
1403 const std::string& type = node_type[i];
1404 // A Join is a STATION, so deferring its creation would shift every
1405 // station index after it and rotate the station rows of the result
1406 // document; it is declared here, in model order, and bound to its Fork
1407 // in pass 1c. ClassSwitch, Cache and Transition are plain nodes, so
1408 // their late creation perturbs no station index.
1409 if (type == "ClassSwitch" || type == "Cache" || type == "Transition") continue;
1410 const std::string name = nd.at("name").get<std::string>();
1411 std::size_t idx = 0;
1412 if (type == "Source") {
1413 idx = net.add_source(name);
1414 } else if (type == "Sink") {
1415 idx = net.add_sink(name);
1416 } else if (type == "Delay") {
1417 idx = net.add_delay(name);
1418 } else if (type == "Queue") {
1419 idx = net.add_queue(name,
1420 detail::sched_from_json(nd.value("scheduling", std::string("FCFS"))));
1421 } else if (type == "Router") {
1422 idx = net.add_router(name);
1423 } else if (type == "Logger" || type == "LogTunnel") {
1424 idx = net.add_logger(name, nd.value("fileName", std::string()));
1425 qn::NodeDef::LoggerParam& lg = net.raw_struct().nodes[idx - 1].logger;
1426 if (nd.contains("filePath")) lg.file_path = nd.at("filePath").get<std::string>();
1427 lg.start_time = nd.value("startTime", lg.start_time);
1428 lg.logger_name = nd.value("loggerName", lg.logger_name);
1429 lg.timestamp = nd.value("timestamp", lg.timestamp);
1430 lg.job_id = nd.value("jobID", lg.job_id);
1431 lg.job_class = nd.value("jobClass", lg.job_class);
1432 lg.time_same_class = nd.value("timeSameClass", lg.time_same_class);
1433 lg.time_any_class = nd.value("timeAnyClass", lg.time_any_class);
1434 } else if (type == "Place") {
1435 // A PLACE CARRIES A DISCIPLINE LIKE A QUEUE, and dropping it is not
1436 // cosmetic: a queueing place whose embedded FCFS queue is read as an
1437 // INF pass-through is a Delay, so a QPN loses the only timed
1438 // behaviour it has and arrives as a net of immediate transitions.
1439 // The writers emit `scheduling` for every Place (`linemodel_save`
1440 // treats Place as a Station, not as a Queue), so the field is there
1441 // to be read; INF is the ordinary place's own value and the default.
1442 idx = net.add_place(name,
1443 detail::sched_from_json(nd.value("scheduling", std::string("INF"))));
1444 // A fluid place (FSPN) holds one level instead of tokens.
1445 if (nd.contains("fluid") && !nd.at("fluid").is_null() && detail::num_from_json(nd.at("fluid")) != 0.0) {
1446 net.set_place_fluid(idx, true);
1447 if (nd.contains("fluidCapacity") && !nd.at("fluidCapacity").is_null())
1448 net.set_fluid_capacity(idx, detail::num_from_json(nd.at("fluidCapacity")));
1449 if (nd.contains("fluidLevel") && !nd.at("fluidLevel").is_null())
1450 net.set_fluid_level(idx, detail::num_from_json(nd.at("fluidLevel")));
1451 }
1452 } else if (type == "Join") {
1453 idx = net.add_join_unbound(name);
1454 } else if (type == "Fork") {
1455 idx = net.add_fork(name, detail::num_value(nd, "tasksPerLink", 1.0));
1456 } else {
1457 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: unsupported node type '" + type + "' at node '" +
1458 name + "'");
1459 }
1460 node_idx[name] = idx;
1461 }
1462
1463 // -- Pass 1b: classes. ---------------------------------------------------
1464 const json& classes = model.at("classes");
1465 std::map<std::string, std::size_t> class_idx;
1466 // The signal classes, resolved after the whole class list exists: a
1467 // signal's TARGET is another class by name, which may follow it.
1468 std::vector<std::size_t> signal_classes;
1469 for (std::size_t r = 0; r < classes.size(); ++r) {
1470 const json& cl = classes[r];
1471 const std::string name = cl.at("name").get<std::string>();
1472 const std::string type = cl.at("type").get<std::string>();
1473 std::size_t idx = 0;
1474 if (type == "Open") {
1475 idx = net.add_open_class(name, cl.value("priority", 0));
1476 } else if (type == "Closed" || type == "SelfLooping") {
1477 // A `SelfLoopingClass` IS a closed class -- its jobs cycle at the
1478 // reference station, which is a property of the routing -- so it is
1479 // built as one and only tagged, exactly as `linemodel_load.m:125`
1480 // handles the two labels in one branch.
1481 const double pop = cl.at("population").get<double>();
1482 const std::string ref = cl.at("refNode").get<std::string>();
1483 auto it = node_idx.find(ref);
1484 if (it == node_idx.end())
1485 throw InputError(ErrorKind{"Format"}, "network_reader: class '" + name + "' references unknown node '" +
1486 ref + "'");
1487 idx = type == "SelfLooping"
1488 ? net.add_self_looping_class(name, pop, it->second, cl.value("priority", 0))
1489 : net.add_closed_class(name, pop, it->second, cl.value("priority", 0));
1490 } else if (type == "Signal") {
1491 // A G-network SIGNAL is an ordinary open or closed class that
1492 // REMOVES jobs instead of joining a queue, so it is created as its
1493 // underlying kind first and marked afterwards. `openOrClosed`
1494 // carries that kind; without it the signal would be built as a
1495 // closed class with no population.
1496 const std::string kind = cl.value("openOrClosed", std::string("Open"));
1497 if (kind == "Closed") {
1498 const std::string ref = cl.at("refNode").get<std::string>();
1499 auto it = node_idx.find(ref);
1500 if (it == node_idx.end())
1501 throw InputError(ErrorKind{"Format"}, "network_reader: signal class '" + name +
1502 "' references unknown node '" + ref + "'");
1503 // A CLOSED SIGNAL HAS NO POPULATION OF ITS OWN, and the writers
1504 // therefore emit no `population` for it: `ClosedSignal.m:69`
1505 // passes 0 up to ClosedClass, its jobs arriving only by class
1506 // switch from the caller. Requiring the key made every REPLY
1507 // model unreadable here with a raw json out_of_range.
1508 idx = net.add_closed_class(name, cl.value("population", 0.0), it->second,
1509 cl.value("priority", 0));
1510 } else {
1511 idx = net.add_open_class(name, cl.value("priority", 0));
1512 }
1513 signal_classes.push_back(r);
1514 } else {
1515 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: unsupported class type '" + type +
1516 "' for class '" + name + "'");
1517 }
1518 // The class-wide spelling of immediate feedback; the node-level map is
1519 // read in pass 2 and `sn.immfeed` is the OR of the two.
1520 if (cl.value("immediateFeedback", false)) net.set_class_immediate_feedback(idx);
1521 // `setReferenceClass`: which class of a chain `sn.refclass` names. It is
1522 // the denominator of every chain visit ratio in `sn_get_demands_chain`
1523 // and `sn_get_product_form_params`, so dropping it silently rescales
1524 // the demands of every multi-class chain that declares one.
1525 if (cl.value("isReferenceClass", false)) net.set_reference_class(idx);
1526 // `JobClass.deadline`, `sn.classdeadline`: EDD and EDF order by it.
1527 if (cl.contains("deadline")) {
1528 const double due = cl.at("deadline").get<double>();
1529 if (std::isfinite(due)) net.set_class_deadline(idx, due);
1530 }
1531 // The CLASS-WIDE patience, `Queue.getPatience`'s fallback. A node-scoped
1532 // `patience` read in pass 2 overrides it at the station that names it.
1533 if (cl.contains("patience")) {
1534 const json& pt = cl.at("patience");
1535 const lang::Distrib<T> pd = detail::dist_from_json<T>(pt);
1536 if (!pd.disabled)
1538 idx, pd,
1539 cl.contains("impatienceType")
1540 ? detail::impatience_from_json(cl.at("impatienceType").get<std::string>())
1542 }
1543 class_idx[name] = idx;
1544 }
1545 // The class-to-class bindings, resolved once every class exists: either
1546 // side may be declared after the class that names it.
1547 for (std::size_t r = 0; r < classes.size(); ++r) {
1548 const json& cl = classes[r];
1549 const std::size_t idx = class_idx.at(cl.at("name").get<std::string>());
1550 if (cl.contains("spawnClass")) {
1551 const std::string sp = cl.at("spawnClass").get<std::string>();
1552 auto sit = class_idx.find(sp);
1553 if (sit == class_idx.end())
1554 throw InputError(ErrorKind{"Format"}, "network_reader: class '" + cl.at("name").get<std::string>() +
1555 "' spawns class '" + sp + "', which the model does not declare");
1556 net.set_class_spawn(idx, sit->second);
1557 }
1558 // Without this a REPLY signal class is INERT after a round trip:
1559 // nothing unblocks the servers waiting on it (`linemodel_save.m:797`).
1560 if (cl.contains("replySignalClass")) {
1561 const std::string rp = cl.at("replySignalClass").get<std::string>();
1562 auto rit = class_idx.find(rp);
1563 if (rit == class_idx.end())
1564 throw InputError(ErrorKind{"Format"}, "network_reader: class '" + cl.at("name").get<std::string>() +
1565 "' replies with class '" + rp +
1566 "', which the model does not declare");
1567 net.set_reply_signal_class(idx, rit->second);
1568 }
1569 }
1570 // Signals, now that every class the target may name exists.
1571 for (std::size_t si = 0; si < signal_classes.size(); ++si) {
1572 const json& cl = classes[signal_classes[si]];
1573 const std::string name = cl.at("name").get<std::string>();
1574 const std::string st = cl.value("signalType", std::string("negative"));
1576 if (st == "reply" || st == "REPLY") kind = lang::SignalType::REPLY;
1577 else if (st == "catastrophe" || st == "CATASTROPHE") kind = lang::SignalType::CATASTROPHE;
1578 else if (st != "negative" && st != "NEGATIVE")
1579 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: signal class '" + name + "' is of type '" + st +
1580 "', and the kinds on the wire are negative, catastrophe and "
1581 "reply");
1583 const std::string rp = cl.value("removalPolicy", std::string("RANDOM"));
1584 if (rp == "FCFS" || rp == "fcfs") pol = lang::RemovalPolicy::FCFS;
1585 else if (rp == "LCFS" || rp == "lcfs") pol = lang::RemovalPolicy::LCFS;
1586 std::size_t target = 0;
1587 if (cl.contains("targetClass")) {
1588 auto tit = class_idx.find(cl.at("targetClass").get<std::string>());
1589 if (tit == class_idx.end())
1590 throw InputError(ErrorKind{"Format"}, "network_reader: signal class '" + name + "' targets class '" +
1591 cl.at("targetClass").get<std::string>() +
1592 "', which the model does not declare");
1593 target = tit->second;
1594 }
1595 std::vector<T> remdist;
1596 if (cl.contains("removalDistribution"))
1597 remdist = detail::removal_pmf_from_json<T>(cl.at("removalDistribution"));
1598 net.set_signal(class_idx.at(name), kind, pol, target, remdist);
1599 }
1600 const std::size_t K = class_idx.size();
1601
1602 // -- Pass 1c: ClassSwitch (matrix now sizeable), Join (fork exists) and
1603 // Cache (its hit/miss classes and popularity are class-indexed). --------
1604 for (std::size_t i = 0; i < nodes.size(); ++i) {
1605 const json& nd = nodes[i];
1606 const std::string& type = node_type[i];
1607 if (type != "ClassSwitch" && type != "Join" && type != "Cache" && type != "Fork") continue;
1608 const std::string name = nd.at("name").get<std::string>();
1609 std::size_t idx = 0;
1610 if (type == "Fork") {
1611 // VARIABLE FORKING LEVELS. Each list is an array of
1612 // {dest, class, ...} records, exactly as `linemodel_save.m:509-553`
1613 // writes them; `dest` is a node NAME and `class` a 1-based index.
1614 // The overrides are recorded here and replayed by `link()` in Pass 3,
1615 // because a per-destination override reads the routing.
1616 if (!nd.contains("fanOutByDest") && !nd.contains("fanOutDist") &&
1617 !nd.contains("fanOutProb"))
1618 continue;
1619 idx = node_idx.at(name);
1620 if (nd.contains("fanOutByDest")) {
1621 const json& ovs = nd.at("fanOutByDest");
1622 for (std::size_t e = 0; e < ovs.size(); ++e)
1623 net.set_fork_tasks_per_link(idx, ovs[e].at("class").get<std::size_t>(),
1624 ovs[e].at("value").get<double>(),
1625 detail::fork_dest_index(ovs[e], node_idx, name));
1626 }
1627 if (nd.contains("fanOutDist")) {
1628 const json& ovs = nd.at("fanOutDist");
1629 for (std::size_t e = 0; e < ovs.size(); ++e) {
1630 const std::vector<double> pv = ovs[e].at("p").get<std::vector<double> >();
1631 const std::vector<double> xv = ovs[e].at("x").get<std::vector<double> >();
1632 std::vector<T> p, x;
1633 for (std::size_t q = 0; q < pv.size(); ++q)
1634 p.push_back(num_traits<T>::from_double(pv[q]));
1635 for (std::size_t q = 0; q < xv.size(); ++q)
1636 x.push_back(num_traits<T>::from_double(xv[q]));
1637 net.set_fork_tasks_per_link_dist(idx, ovs[e].at("class").get<std::size_t>(),
1639 detail::fork_dest_index(ovs[e], node_idx, name));
1640 }
1641 }
1642 if (nd.contains("fanOutProb")) {
1643 const json& ovs = nd.at("fanOutProb");
1644 for (std::size_t e = 0; e < ovs.size(); ++e)
1646 idx, ovs[e].at("class").get<std::size_t>(),
1647 detail::fork_dest_index(ovs[e], node_idx, name),
1648 ovs[e].at("value").get<double>());
1649 }
1650 continue;
1651 }
1652 if (type == "Cache") {
1653 // THE WRITERS EMIT THE CACHE TWICE, by design: a nested `cache`
1654 // object and the same fields flattened onto the node, so that both
1655 // the MATLAB and the JAR readers find what they look for
1656 // (`linemodel_save.m:425-435`). The flat spelling wins where both
1657 // are present -- they are mirrored from the nested one, so they
1658 // agree -- and the nested one is consulted for anything the flat
1659 // mirror does not carry.
1660 const json empty_obj = json::object();
1661 const json& cj = nd.contains("cache") ? nd.at("cache") : empty_obj;
1663 cp.nitems = detail::has_cache_key(nd, cj, "numItems")
1664 ? detail::cache_key(nd, cj, "numItems").get<std::size_t>()
1665 : cj.at("items").get<std::size_t>();
1666 cp.itemcap = detail::has_cache_key(nd, cj, "itemLevelCap")
1667 ? detail::cache_key(nd, cj, "itemLevelCap").get<std::vector<int> >()
1668 : cj.at("capacity").get<std::vector<int> >();
1669 // Per-item storage costs and per-list cost caps (ton21cache Sec. IX).
1670 // A scalar costCaps is the single cache-wide cap, replicated per list.
1671 if (detail::has_cache_key(nd, cj, "itemSizes"))
1672 cp.itemsize = detail::cache_key(nd, cj, "itemSizes").get<std::vector<int> >();
1673 if (detail::has_cache_key(nd, cj, "costCaps")) {
1674 const json& cc = detail::cache_key(nd, cj, "costCaps");
1675 if (cc.is_array()) {
1676 cp.costcap = cc.get<std::vector<int> >();
1677 } else {
1678 cp.costcapglobal = true;
1679 cp.costcap.assign(cp.itemcap.size(), cc.get<int>());
1680 }
1681 }
1682 cp.replacestrat = detail::replacement_from_json(
1683 detail::has_cache_key(nd, cj, "replacementStrategy")
1684 ? detail::cache_key(nd, cj, "replacementStrategy").get<std::string>()
1685 : cj.value("replacement", std::string("RR")));
1686 cp.pread.assign(K, std::vector<T>());
1687 cp.hitclass.assign(K, 0);
1688 cp.missclass.assign(K, 0);
1689 cp.preadkind.assign(K, typename qn::CacheParam<T>::Popularity());
1690 cp.classitem.assign(K, 0);
1691 if (detail::has_cache_key(nd, cj, "popularity")) {
1692 const json& pop = detail::cache_key(nd, cj, "popularity");
1693 for (auto it = pop.begin(); it != pop.end(); ++it) {
1694 // A class that does not read the cache is written with a
1695 // `Disabled` popularity, and leaves `pread` empty
1696 // (`linemodel_load.m:602`).
1697 if (it.value().value("type", std::string()) == "Disabled") continue;
1698 cp.pread[class_idx.at(it.key()) - 1] =
1699 detail::pmf_from_json<T>(it.value(), cp.nitems);
1700 cp.preadkind[class_idx.at(it.key()) - 1] =
1701 detail::popularity_kind_from_json<T>(it.value(), cp.nitems);
1702 }
1703 }
1704 auto fill_switch = [&](const char* key, std::vector<std::size_t>& dst) {
1705 if (!detail::has_cache_key(nd, cj, key)) return;
1706 const json& blk = detail::cache_key(nd, cj, key);
1707 for (auto it = blk.begin(); it != blk.end(); ++it)
1708 dst[class_idx.at(it.key()) - 1] = class_idx.at(it.value().get<std::string>());
1709 };
1710 fill_switch("hitClass", cp.hitclass);
1711 fill_switch("missClass", cp.missclass);
1712 // `itemClass`: for a cache network, the item each per-item class reads
1713 // (`Cache.setItemReadClasses`). Carried so a reader need not infer it
1714 // from a one-hot pread, which a genuine single-item popularity also has.
1715 if (detail::has_cache_key(nd, cj, "itemClass")) {
1716 const json& blk = detail::cache_key(nd, cj, "itemClass");
1717 for (auto it = blk.begin(); it != blk.end(); ++it)
1718 cp.classitem[class_idx.at(it.key()) - 1] =
1719 static_cast<std::size_t>(it.value().get<double>());
1720 }
1721 // `accessProb`: the per-(class, item) access graph, `sn.nodeparam{i}.accost`.
1722 // The wire form is a class-major array of item-major arrays of
1723 // (h+1)x(h+1) matrices, with an empty entry where the pair declares
1724 // none (`linemodel_save.m:402-416`). It is READ HERE and nowhere else,
1725 // and dropping it would solve a cache whose admission and promotion
1726 // are item-dependent as if they were the linear chain.
1727 // `admissionProb`: the q-LRU admission probability, `nodeparam.qlru`.
1728 // Every Cache the reference writes carries it, defaulting to 1, so
1729 // refusing it made every MATLAB-written cache model unreadable here.
1730 if (detail::has_cache_key(nd, cj, "admissionProb"))
1731 cp.qlru = num_traits<T>::from_double(detail::cache_key(nd, cj, "admissionProb").get<double>());
1732 if (detail::has_cache_key(nd, cj, "accessProb")) {
1733 const json& ap = detail::cache_key(nd, cj, "accessProb");
1734 cp.accost.clear();
1735 for (const json& per_class : ap) {
1736 std::vector<Matrix<T> > row;
1737 for (const json& g : per_class) {
1738 if (g.is_null() || g.empty()) {
1739 row.push_back(Matrix<T>());
1740 continue;
1741 }
1742 row.push_back(detail::mat_from_json<T>(g));
1743 }
1744 cp.accost.push_back(row);
1745 }
1746 } else if (detail::has_cache_key(nd, cj, "accessGraph")) {
1747 // `accessGraph` is the SAME access cost shared by every class:
1748 // one (h+1)x(h+1) matrix per item, written when the model set
1749 // `node.graph` rather than the full per-class `accessProb`
1750 // (`linemodel_save.m:395-401`). Replicating it across the classes
1751 // here is what makes the two spellings the same model.
1752 const std::vector<Matrix<T> > shared =
1753 detail::mat_list_from_json<T>(detail::cache_key(nd, cj, "accessGraph"));
1754 cp.accost.assign(K, shared);
1755 }
1756 // The initial cache contents: the state row `[class counts | list
1757 // contents | retrieval bitmap]` the reference dumps from the node.
1758 if (detail::has_cache_key(nd, cj, "initialState"))
1759 cp.initstate = detail::num_vec_from_json<T>(detail::cache_key(nd, cj, "initialState"));
1760 // Delayed-hit retrieval system: the retrieval classes are already in
1761 // the class list (created in pass 1b) with their service and routing,
1762 // so only the cache-side maps are recovered here -- no re-creation.
1763 // Read through the same nested-or-flat helper every other cache key
1764 // uses. All three writers put this one flat today, so a direct
1765 // `nd.contains` happens to work -- but it is the shape python got
1766 // wrong (it chose ONE source per node and lost whatever the other
1767 // held), and a reader that treats one key differently from its
1768 // siblings is the trap that made that possible.
1769 if (detail::has_cache_key(nd, cj, "retrievalSystem")) {
1770 const json& rs = detail::cache_key(nd, cj, "retrievalSystem");
1771 cp.retrieval_capacity = rs.value("capacity", 0);
1772 cp.retrieval_classes.assign(cp.nitems, std::vector<std::size_t>(K, 0));
1773 if (rs.contains("byClass")) {
1774 for (auto rc = rs.at("byClass").begin(); rc != rs.at("byClass").end(); ++rc) {
1775 const std::size_t rdcls = class_idx.at(rc.key()); // 1-based read class
1776 std::vector<std::size_t> qnodes;
1777 for (const auto& qn : rc.value().at("queues"))
1778 qnodes.push_back(node_idx.at(qn.get<std::string>()));
1779 cp.retrieval_queues[rdcls - 1] = qnodes;
1780 // CacheCodec.m omits "items" when the class has no per-item retrieval class
1781 if (!rc.value().contains("items")) continue;
1782 for (auto it2 = rc.value().at("items").begin();
1783 it2 != rc.value().at("items").end(); ++it2) {
1784 const std::size_t item = std::stoul(it2.key());
1785 if (item < cp.nitems)
1786 cp.retrieval_classes[item][rdcls - 1] =
1787 class_idx.at(it2.value().get<std::string>());
1788 }
1789 }
1790 }
1791 }
1792 idx = net.add_cache(name, cp);
1793 node_idx[name] = idx;
1794 continue;
1795 }
1796 if (type == "Join") {
1797 // The pairing is a DECLARATION the Join carries; the routing does not
1798 // determine it when a model nests two fork-join pairs. A document that
1799 // omits it is refused here rather than at link(), where the message
1800 // would name the Fork rather than the Join that forgot it.
1801 if (!nd.contains("forkNode"))
1802 throw InputError(ErrorKind{"Format"}, "network_reader: Join '" + name +
1803 "' names no 'forkNode': the document declares no "
1804 "Fork for it to close.");
1805 auto it = node_idx.find(nd.at("forkNode").get<std::string>());
1806 if (it == node_idx.end())
1807 throw InputError(ErrorKind{"Format"}, "network_reader: Join '" + name +
1808 "' references unknown fork '" +
1809 nd.at("forkNode").get<std::string>() + "'");
1810 const std::size_t fork = it->second;
1811 // The station itself was declared in pass 1a, in model order, so
1812 // only the Fork it closes is recorded here.
1813 idx = node_idx.at(name);
1814 net.bind_join(idx, fork);
1815 // The declared join rule. PARTIAL fires on a quorum of siblings
1816 // rather than on all of them, so dropping it would make a partial
1817 // join wait for arrivals that never come.
1818 if (nd.contains("joinStrategy") || nd.contains("joinQuorum")) {
1819 const std::string js = nd.value("joinStrategy", std::string("STD"));
1820 if (js != "STD" && js != "PARTIAL")
1821 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: Join '" + name + "' declares strategy '" +
1822 js + "', and the rules on the wire are STD and PARTIAL");
1823 net.set_join_strategy(idx,
1824 js == "PARTIAL" ? lang::JoinStrategy::PARTIAL
1826 nd.value("joinQuorum", 0.0));
1827 }
1828 } else {
1829 // Rows a class-switch matrix omits leave that class unchanged, so the
1830 // matrix defaults to the identity before the listed rows overwrite it.
1831 // The builder's class indices are 1-based; the matrix is 0-indexed.
1832 // `csMatrix` is the JAR writer's spelling of the same block.
1833 Matrix<T> C(K, K);
1834 for (std::size_t d = 0; d < K; ++d) C(d, d) = num_traits<T>::from_int(1);
1835 if (nd.contains("classSwitchMatrix") || nd.contains("csMatrix")) {
1836 const json& csm =
1837 nd.contains("classSwitchMatrix") ? nd.at("classSwitchMatrix") : nd.at("csMatrix");
1838 for (auto ri = csm.begin(); ri != csm.end(); ++ri) {
1839 const std::size_t rr = class_idx.at(ri.key()) - 1;
1840 for (std::size_t d = 0; d < K; ++d) C(rr, d) = num_traits<T>::from_int(0);
1841 for (auto ci = ri.value().begin(); ci != ri.value().end(); ++ci)
1842 C(rr, class_idx.at(ci.key()) - 1) =
1843 num_traits<T>::from_double(ci.value().get<double>());
1844 }
1845 }
1846 idx = net.add_class_switch(name, C);
1847 }
1848 node_idx[name] = idx;
1849 }
1850
1851 // -- Pass 1d: Transitions, whose arcs name other nodes. -------------------
1852 // A mode's enabling/inhibiting/firing arcs are written as (node, class,
1853 // count) triples, so every node must exist before they can be resolved, and
1854 // the arc matrices are sized against the FULL node count rather than the
1855 // count so far. THE CLASS IS KEPT: `TransitionParam` stores an
1856 // (nnodes x nclasses) matrix per mode, as MATLAB's `enablingConditions{m}`
1857 // does, so a mode requiring two Class1 tokens at a place is not satisfied by
1858 // Class2 tokens sitting there. An arc naming a class the model does not
1859 // declare is an error rather than a silent drop.
1860 for (std::size_t i = 0; i < nodes.size(); ++i) {
1861 if (node_type[i] != "Transition") continue;
1862 const json& nd = nodes[i];
1863 const std::string name = nd.at("name").get<std::string>();
1864 if (!nd.contains("modes") || nd.at("modes").empty())
1865 throw InputError(ErrorKind{"Format"}, "network_reader: transition '" + name + "' declares no mode");
1866 const json& modes = nd.at("modes");
1868 tp.nmodes = modes.size();
1869 const std::size_t nn = nodes.size();
1870 const double inf = std::numeric_limits<double>::infinity();
1871 for (std::size_t m = 0; m < modes.size(); ++m) {
1872 const json& mj = modes[m];
1873 tp.modenames.push_back(mj.value("name", std::string("Mode") + std::to_string(m + 1)));
1874 // A marking-dependent firing rate g_m(marking) crosses the wire as
1875 // the MATERIALIZED lattice `{slots, cutoffs, scaling}`, because a
1876 // handle has no JSON form: `slots` names the input (place,class)
1877 // pairs that g reads, `cutoffs` caps each of them, and `scaling` is
1878 // keyed by the comma-joined 0-based counts in slot order. Rebuilt
1879 // here into the same closure MATLAB's `firingdep_table_to_handle`
1880 // and the Python `_firingdep_table_to_handle` build, over the
1881 // node-major flattened (node, class) marking `state_events.h` passes in.
1882 tp.firingdep.push_back(std::function<T(const std::vector<T>&)>());
1883 if (mj.contains("firingRateDependence")) {
1884 const json& frm = mj.at("firingRateDependence");
1885 if (!frm.contains("slots") || !frm.contains("scaling"))
1886 throw InputError(ErrorKind{"Format"}, "network_reader: the marking-dependent firing rate of mode " +
1887 std::to_string(m + 1) + " of transition '" + name +
1888 "' carries no 'slots'/'scaling' lattice");
1889 std::vector<std::size_t> slot_pos;
1890 for (const json& sm : frm.at("slots")) {
1891 const std::string on = sm.at("node").get<std::string>();
1892 const std::map<std::string, std::size_t>::const_iterator ni = node_idx.find(on);
1893 if (ni == node_idx.end())
1894 throw InputError(ErrorKind{"Format"}, "network_reader: the marking-dependent firing rate of "
1895 "transition '" +
1896 name + "' reads node '" + on +
1897 "', which the model does not declare");
1898 // a slot is a (place, class) pair, flattened node-major as the marking is
1899 std::size_t sr = 1;
1900 if (sm.contains("class")) {
1901 const std::string scn = sm.at("class").get<std::string>();
1902 const std::map<std::string, std::size_t>::const_iterator sci = class_idx.find(scn);
1903 if (sci == class_idx.end())
1904 throw InputError(ErrorKind{"Format"}, "network_reader: the marking-dependent firing rate of "
1905 "transition '" +
1906 name + "' reads class '" + scn +
1907 "', which the model does not declare");
1908 sr = sci->second;
1909 }
1910 slot_pos.push_back((ni->second - 1) * K + (sr - 1));
1911 }
1912 std::vector<long> cutoffs;
1913 if (frm.contains("cutoffs"))
1914 for (const json& c : frm.at("cutoffs")) cutoffs.push_back(c.get<long>());
1915 std::map<std::string, double> table;
1916 const json& sc = frm.at("scaling");
1917 for (json::const_iterator it = sc.begin(); it != sc.end(); ++it)
1918 table[it.key()] = it.value().get<double>();
1919 tp.firingdep.back() = [slot_pos, cutoffs,
1920 table](const std::vector<T>& mk) -> T {
1921 std::string key;
1922 for (std::size_t s = 0; s < slot_pos.size(); ++s) {
1923 long c = slot_pos[s] < mk.size()
1924 ? static_cast<long>(std::llround(
1925 num_traits<T>::to_double(mk[slot_pos[s]])))
1926 : 0L;
1927 if (c < 0) c = 0;
1928 if (s < cutoffs.size() && c > cutoffs[s]) c = cutoffs[s];
1929 if (s) key += ',';
1930 key += std::to_string(c);
1931 }
1932 const std::map<std::string, double>::const_iterator hit = table.find(key);
1933 // A marking outside the tabulated box is NEUTRAL, not zero:
1934 // the same default the three reference readers apply.
1935 return hit == table.end() ? num_traits<T>::from_int(1)
1936 : num_traits<T>::from_double(hit->second);
1937 };
1938 }
1939 const bool immediate =
1940 mj.value("timingStrategy", std::string("TIMED")) == "IMMEDIATE";
1941 tp.timing.push_back(immediate ? lang::TimingStrategy::IMMEDIATE
1944 if (mj.contains("distribution")) proc = detail::dist_from_json<T>(mj.at("distribution"));
1945 tp.firingproc.push_back(proc);
1946 tp.firingphases.push_back(immediate || proc.disabled ? 0
1947 : lang::dist_to_map(proc).order());
1948 tp.nmodeservers.push_back(detail::num_value(mj, "numServers", 1.0));
1949 // ONE, not zero: `Transition.addMode` gives a new mode priority 1 in
1950 // all four codebases (MATLAB Transition.m:88, python nodes.py:2660,
1951 // JAR Transition.java:114), and the three readers leave that default
1952 // in place when the key is absent. Defaulting to 0 here made an
1953 // omitted key mean a DIFFERENT mode than it means everywhere else,
1954 // and firing priority selects which immediate mode fires, so the
1955 // marking process itself changed rather than a reported decimal.
1956 tp.firingprio.push_back(mj.value("firingPriority", 1.0));
1957 tp.fireweight.push_back(num_traits<T>::from_double(mj.value("firingWeight", 1.0)));
1958 const std::size_t K = classes.size();
1959 Matrix<T> enab(nn, K, num_traits<T>::from_int(0));
1960 Matrix<T> inhib(nn, K, num_traits<T>::from_double(inf));
1961 Matrix<T> fire(nn, K, num_traits<T>::from_int(0));
1962 const char* kArcKey[3] = {"enablingConditions", "inhibitingConditions",
1963 "firingOutcomes"};
1964 for (int which = 0; which < 3; ++which) {
1965 if (!mj.contains(kArcKey[which])) continue;
1966 for (const json& arc : mj.at(kArcKey[which])) {
1967 const std::string on = arc.at("node").get<std::string>();
1968 const std::map<std::string, std::size_t>::const_iterator ni = node_idx.find(on);
1969 if (ni == node_idx.end())
1970 throw InputError(ErrorKind{"Format"}, "network_reader: transition '" + name + "' names node '" +
1971 on + "', which the model does not declare");
1972 // AN ARC WITHOUT A CLASS IS THE FIRST CLASS'S, which is what
1973 // a single-class document means by omitting it; a name the
1974 // model never declared is an error, because dropping the arc
1975 // would build a net with one fewer precondition.
1976 std::size_t rr = 1;
1977 if (arc.contains("class")) {
1978 const std::string cn = arc.at("class").get<std::string>();
1979 const std::map<std::string, std::size_t>::const_iterator ci =
1980 class_idx.find(cn);
1981 if (ci == class_idx.end())
1982 throw InputError(ErrorKind{"Format"}, "network_reader: transition '" + name +
1983 "' names class '" + cn +
1984 "', which the model does not declare");
1985 rr = ci->second;
1986 }
1987 const T cnt = num_traits<T>::from_double(arc.value("count", 1.0));
1988 const std::size_t q = ni->second - 1;
1989 if (which == 0) enab(q, rr - 1) = enab(q, rr - 1) + cnt;
1990 else if (which == 1) inhib(q, rr - 1) = cnt; // a threshold, not a count
1991 else fire(q, rr - 1) = fire(q, rr - 1) + cnt;
1992 }
1993 }
1994 tp.enabling.push_back(enab);
1995 tp.inhibiting.push_back(inhib);
1996 tp.firing.push_back(fire);
1997 // Fluid arcs (FSPN), each naming its fluid place, read after the timing and the law so the
1998 // rate-dependence rules see the final mode. They are written into `tp` directly, under the rules of
1999 // `set_mode_fluid_*`, because a transition built from a finished TransitionParam takes no setter.
2000 tp.fluidrate.emplace_back();
2001 tp.fluidguard.emplace_back();
2002 tp.fluidimpulse.emplace_back();
2003 tp.fluiddep.emplace_back();
2004 const std::string mlabel = "mode " + std::to_string(m + 1) + " of transition '" + name + "'";
2005 auto fluid_place = [&](const json& e, const char* key) -> std::size_t {
2006 const std::string on = e.at("node").get<std::string>();
2007 const std::map<std::string, std::size_t>::const_iterator ni = node_idx.find(on);
2008 bool is_place = false;
2009 for (std::size_t j = 0; j < nodes.size() && !is_place; ++j)
2010 is_place = node_type[j] == "Place" && nodes[j].at("name").get<std::string>() == on;
2011 if (ni == node_idx.end() || !is_place)
2012 throw InputError(ErrorKind{"Format"}, "network_reader: the " + std::string(key) + " of " +
2013 mlabel + " names '" + on + "', which is not a Place of the model");
2014 return ni->second;
2015 };
2016 auto finite_num = [&](const json& e, const char* field, const char* key) -> double {
2017 const double x = detail::num_from_json(e.at(field));
2018 if (!std::isfinite(x))
2019 throw InputError(ErrorKind{"Format"}, "network_reader: the " + std::string(key) + " of " +
2020 mlabel + " carries a non-finite '" + field + "'");
2021 return x;
2022 };
2023 if (mj.contains("fluidRates"))
2024 for (const json& e : mj.at("fluidRates")) {
2026 a.node = fluid_place(e, "fluidRates");
2027 a.value = finite_num(e, "rate", "fluidRates");
2028 if (a.value != 0.0) tp.fluidrate.back().push_back(a);
2029 }
2030 if (mj.contains("fluidGuards"))
2031 for (const json& e : mj.at("fluidGuards")) {
2033 g.node = fluid_place(e, "fluidGuards");
2034 const std::string op = e.at("op").get<std::string>();
2035 if (op != ">=" && op != "<=")
2036 throw InputError(ErrorKind{"Format"}, "network_reader: a fluid guard of " + mlabel +
2037 " has operator '" + op + "'; the operators are '>=' and '<='");
2038 g.sgn = op == ">=" ? 1 : -1;
2039 g.thr = finite_num(e, "threshold", "fluidGuards");
2040 if (g.thr < 0.0)
2041 throw InputError(ErrorKind{"Format"}, "network_reader: a fluid guard of " + mlabel +
2042 " has a negative threshold");
2043 tp.fluidguard.back().push_back(g);
2044 }
2045 if (mj.contains("fluidImpulses"))
2046 for (const json& e : mj.at("fluidImpulses")) {
2048 a.node = fluid_place(e, "fluidImpulses");
2049 a.value = finite_num(e, "delta", "fluidImpulses");
2050 if (a.value != 0.0) tp.fluidimpulse.back().push_back(a);
2051 }
2052 if (mj.contains("fluidRateDependence"))
2053 for (const json& e : mj.at("fluidRateDependence")) {
2055 d.node = fluid_place(e, "fluidRateDependence");
2056 if (immediate)
2057 throw UnsupportedError(ErrorKind{"Transition"}, "network_reader: " + mlabel +
2058 " is IMMEDIATE and declares a fluid rate dependence");
2059 if (proc.disabled || proc.type != lang::ProcessType::EXP)
2060 throw UnsupportedError(ErrorKind{"Distribution"}, "network_reader: " + mlabel +
2061 " declares a fluid rate dependence on a non-exponential firing law");
2062 d.fun = detail::fluiddep_table_to_fun(e.at("levels"), e.at("values"), mlabel);
2063 tp.fluiddep.back().push_back(d);
2064 }
2065 // A marking-dependent flow multiplier crosses as the firingRateDependence lattice over its (read place,
2066 // class) slots, rebuilt into the same closure (counts rounded and clamped, a missing key neutral) on the
2067 // flattened (node, class) marking of `FluidFlowDep`.
2068 tp.fluidflowdep.emplace_back();
2069 if (mj.contains("fluidFlowDependence")) {
2070 const std::size_t KF = classes.size();
2071 for (const json& e : mj.at("fluidFlowDependence")) {
2073 fd.node = fluid_place(e, "fluidFlowDependence");
2074 if (e.contains("read")) {
2075 const json& rd = e.at("read");
2076 const json rl = rd.is_array() ? rd : json::array({rd});
2077 for (const json& rn : rl) {
2078 json probe;
2079 probe["node"] = rn;
2080 fd.read.push_back(fluid_place(probe, "fluidFlowDependence read"));
2081 }
2082 std::sort(fd.read.begin(), fd.read.end());
2083 fd.read.erase(std::unique(fd.read.begin(), fd.read.end()), fd.read.end());
2084 }
2085 fd.read_given = !fd.read.empty();
2086 if (!e.contains("slots") || !e.contains("scaling"))
2087 throw InputError(ErrorKind{"Format"}, "network_reader: the fluid flow dependence of " + mlabel +
2088 " carries no 'slots'/'scaling' lattice");
2089 std::vector<std::size_t> sflat;
2090 for (const json& sm : e.at("slots")) {
2091 const std::string on = sm.at("node").get<std::string>();
2092 const std::map<std::string, std::size_t>::const_iterator ni = node_idx.find(on);
2093 if (ni == node_idx.end())
2094 throw InputError(ErrorKind{"Format"}, "network_reader: the fluid flow dependence of " +
2095 mlabel + " reads node '" + on + "', which the model does not declare");
2096 std::size_t rr = 1;
2097 if (sm.contains("class")) {
2098 const std::string cn = sm.at("class").get<std::string>();
2099 const std::map<std::string, std::size_t>::const_iterator ci = class_idx.find(cn);
2100 if (ci == class_idx.end())
2101 throw InputError(ErrorKind{"Format"}, "network_reader: the fluid flow dependence of " +
2102 mlabel + " names class '" + cn +
2103 "', which the model does not declare");
2104 rr = ci->second;
2105 }
2106 sflat.push_back((ni->second - 1) * KF + (rr - 1));
2107 }
2108 std::vector<long> cutoffs;
2109 if (e.contains("cutoffs"))
2110 for (const json& c : e.at("cutoffs")) cutoffs.push_back(c.get<long>());
2111 std::map<std::string, double> table;
2112 const json& sc = e.at("scaling");
2113 for (json::const_iterator it = sc.begin(); it != sc.end(); ++it)
2114 table[it.key()] = it.value().get<double>();
2115 fd.fun = [sflat, cutoffs, table](const std::vector<double>& mk) -> double {
2116 std::string key;
2117 for (std::size_t s = 0; s < sflat.size(); ++s) {
2118 long c = sflat[s] < mk.size() ? static_cast<long>(std::llround(mk[sflat[s]])) : 0L;
2119 if (c < 0) c = 0;
2120 if (s < cutoffs.size() && c > cutoffs[s]) c = cutoffs[s];
2121 if (s) key += ',';
2122 key += std::to_string(c);
2123 }
2124 const std::map<std::string, double>::const_iterator hit = table.find(key);
2125 return hit == table.end() ? 1.0 : hit->second;
2126 };
2127 tp.fluidflowdep.back().push_back(fd);
2128 }
2129 }
2130 }
2131 node_idx[name] = net.add_transition(name, tp);
2132 }
2133
2134 // -- Pass 2: per-node parameters (service/arrival, servers, CS matrix). ---
2135 for (std::size_t i = 0; i < nodes.size(); ++i) {
2136 const json& nd = nodes[i];
2137 const std::string& type = node_type[i];
2138 const std::size_t idx = node_idx.at(nd.at("name").get<std::string>());
2139
2140 // A QUEUEING PLACE'S EMBEDDED QUEUE HAS A SERVER COUNT TOO, and it is
2141 // the c of its M/M/c: `add_place(name, sched)` defaults it to one server
2142 // for a queueing discipline, which a `servers` field then overrides.
2143 if (nd.contains("servers") && (type == "Queue" || type == "Place"))
2144 net.set_number_of_servers(idx, detail::num_from_json(nd.at("servers")));
2145
2146 if (nd.contains("service")) {
2147 const json& svc = nd.at("service");
2148 for (auto it = svc.begin(); it != svc.end(); ++it) {
2149 auto cit = class_idx.find(it.key());
2150 if (cit == class_idx.end())
2151 throw InputError(ErrorKind{"Format"}, "network_reader: service names unknown class '" + it.key() +
2152 "' at node '" + nd.at("name").get<std::string>() + "'");
2153 const lang::Distrib<T> d = detail::dist_from_json<T>(it.value());
2154 if (type == "Source") net.set_arrival(idx, cit->second, d);
2155 else net.set_service(idx, cit->second, d);
2156 }
2157 }
2158
2159 if (type == "Queue" && nd.contains("scheduling") &&
2160 nd.at("scheduling").get<std::string>() == "POLLING") {
2161 if (nd.contains("pollingType"))
2162 // ROUNDED, not truncated: `State.pollingInfo` reads
2163 // round(pollingPar), and linemodel_save writes the raw double.
2164 net.set_polling_type(idx, detail::polling_from_json(nd.at("pollingType").get<std::string>()),
2165 static_cast<int>(std::lround(nd.value("pollingPar", 0.0))));
2166 }
2167
2168 // Per-class scheduling weights (DPS / GPS). Without these the AMVA DPS
2169 // path either errors (no weights) or degenerates to plain PS.
2170 if (nd.contains("schedParams") && (type == "Queue" || type == "Delay")) {
2171 const json& sp = nd.at("schedParams");
2172 for (auto it = sp.begin(); it != sp.end(); ++it) {
2173 auto cit = class_idx.find(it.key());
2174 if (cit != class_idx.end())
2175 net.set_sched_param(idx, cit->second,
2176 num_traits<T>::from_double(it.value().get<double>()));
2177 }
2178 }
2179
2180 // Finite-buffer blocking. `dropRule` per class (blockingAfterService ->
2181 // BAS makes mva_is_bas_model true, routing the model to solver_sqd) and
2182 // `buffer` the total station capacity.
2183 // The writers emit these for `isa(node,'Station')`, which is wider than
2184 // Queue and Delay: a Join and a queueing Place are stations too, and a
2185 // rule read only at a Queue is a rule silently dropped at those.
2186 const bool station_node =
2187 type == "Queue" || type == "Delay" || type == "Join" || type == "Place";
2188 if (nd.contains("dropRule") && station_node) {
2189 const json& dr = nd.at("dropRule");
2190 for (auto it = dr.begin(); it != dr.end(); ++it) {
2191 auto cit = class_idx.find(it.key());
2192 if (cit != class_idx.end())
2193 net.set_drop_rule(idx, cit->second,
2194 detail::drop_from_json(it.value().get<std::string>()));
2195 }
2196 }
2197 if (nd.contains("buffer") && station_node)
2198 net.set_capacity(idx, detail::num_from_json(nd.at("buffer")));
2199 // Per-class buffer capacity, the refinement of `buffer`.
2200 if (nd.contains("classCap")) {
2201 const json& cc = nd.at("classCap");
2202 for (auto it = cc.begin(); it != cc.end(); ++it) {
2203 auto cit = class_idx.find(it.key());
2204 if (cit != class_idx.end())
2205 net.set_class_capacity(idx, cit->second, detail::num_from_json(it.value()));
2206 }
2207 }
2208
2209 // -- Impatience, balking and the retrial orbit -----------------------
2210 //
2211 // Four DIFFERENT populations, and the reference keeps them apart: a
2212 // patience timer abandons a job that has JOINED the queue, balking
2213 // refuses to join at all, an orbit impatience abandons a retrial orbit
2214 // (never a buffer slot), and a batch rejection drops a whole arriving
2215 // batch. Folding any two together changes which jobs are counted.
2216 if (nd.contains("patience")) {
2217 const json& pt = nd.at("patience");
2218 for (auto it = pt.begin(); it != pt.end(); ++it) {
2219 auto cit = class_idx.find(it.key());
2220 if (cit == class_idx.end()) continue;
2221 const json& pj = it.value();
2222 const lang::ImpatienceType kind =
2223 pj.contains("impatienceType")
2224 ? detail::impatience_from_json(pj.at("impatienceType").get<std::string>())
2226 net.set_patience(idx, cit->second, detail::dist_from_json<T>(pj.at("distribution")),
2227 kind);
2228 }
2229 }
2230 if (nd.contains("orbitImpatience")) {
2231 const json& oi = nd.at("orbitImpatience");
2232 for (auto it = oi.begin(); it != oi.end(); ++it) {
2233 auto cit = class_idx.find(it.key());
2234 if (cit != class_idx.end())
2235 net.set_orbit_impatience(idx, cit->second, detail::dist_from_json<T>(it.value()));
2236 }
2237 }
2238 if (nd.contains("batchRejectProb")) {
2239 const json& br = nd.at("batchRejectProb");
2240 for (auto it = br.begin(); it != br.end(); ++it) {
2241 auto cit = class_idx.find(it.key());
2242 if (cit != class_idx.end())
2243 net.set_batch_reject(idx, cit->second,
2244 num_traits<T>::from_double(it.value().get<double>()));
2245 }
2246 }
2247 if (nd.contains("balking")) {
2248 const json& bk = nd.at("balking");
2249 for (auto it = bk.begin(); it != bk.end(); ++it) {
2250 auto cit = class_idx.find(it.key());
2251 if (cit == class_idx.end()) continue;
2252 const json& bj = it.value();
2253 std::vector<typename qn::Station<T>::BalkingThreshold> ths;
2254 if (bj.contains("thresholds"))
2255 for (const json& tj : bj.at("thresholds")) {
2257 th.min_jobs = tj.value("minJobs", 0.0);
2258 // -1 IS THE WIRE'S INFINITY, not a count: the writer maps
2259 // an unbounded upper end to it rather than emitting Inf,
2260 // which JSON has no literal for.
2261 th.max_jobs = tj.value("maxJobs", -1.0);
2262 th.probability = num_traits<T>::from_double(tj.value("probability", 1.0));
2263 ths.push_back(th);
2264 }
2265 net.set_balking(idx, cit->second,
2266 detail::balking_from_json(bj.at("strategy").get<std::string>()), ths);
2267 }
2268 }
2269 if (nd.contains("retrial")) {
2270 const json& rt = nd.at("retrial");
2271 for (auto it = rt.begin(); it != rt.end(); ++it) {
2272 auto cit = class_idx.find(it.key());
2273 if (cit == class_idx.end()) continue;
2274 const lang::Distrib<T> delay = detail::dist_from_json<T>(it.value().at("delay"));
2275 // `sn.retrialMu` is the RATE of that delay, which is what the
2276 // state layer multiplies the orbit population by.
2277 const T rate = T(num_traits<T>::from_int(1) / delay.mean);
2278 net.set_retrial(idx, cit->second, delay, rate,
2279 int(detail::num_value(it.value(), "maxAttempts", 0.0)));
2280 // setOrbit's policy and orbit bound; absent = the classical
2281 // unbounded per-customer orbit of a plain setRetrial
2282 if (it.value().contains("policy") || it.value().contains("maxOrbit")) {
2283 int policy = 1;
2284 if (it.value().contains("policy")) {
2285 const std::string p = it.value().at("policy").get<std::string>();
2286 if (p == "linear" || p == "per-customer" || p == "falin") policy = 1;
2287 else if (p == "constant" || p == "fixed" || p == "controller") policy = 2;
2288 else
2289 throw InputError(ErrorKind{"Format"},
2290 "network_reader: unrecognized retrial policy '" + p + "'");
2291 }
2292 net.set_orbit_policy(idx, cit->second, policy,
2293 int(detail::num_value(it.value(), "maxOrbit", -1.0)),
2294 false); // keep the document's buffer
2295 }
2296 // non-persistence (p, q) and orbital search, present only when
2297 // not default (linemodel_save.m)
2298 if (it.value().contains("joinProb") || it.value().contains("persistProb"))
2299 net.set_orbit_persistence(idx, cit->second,
2300 num_traits<T>::from_double(detail::num_value(it.value(), "joinProb", 1.0)),
2301 num_traits<T>::from_double(detail::num_value(it.value(), "persistProb", 1.0)));
2302 if (it.value().contains("searchProb"))
2303 net.set_orbital_search(idx, cit->second,
2304 num_traits<T>::from_double(detail::num_value(it.value(), "searchProb", 0.0)));
2305 }
2306 }
2307
2308 // -- Setup / delay-off, switchover and heterogeneous servers ---------
2309 if (nd.contains("setupTime")) {
2310 if (!nd.contains("delayOffTime"))
2311 throw InputError(ErrorKind{"Format"},
2312 "network_reader: node '" + nd.at("name").get<std::string>() +
2313 "' declares a setup time with no delay-off time; a server that never powers "
2314 "down never pays the setup, so the pair is meaningless alone");
2315 const json& su = nd.at("setupTime");
2316 const json& doff = nd.at("delayOffTime");
2317 for (auto it = su.begin(); it != su.end(); ++it) {
2318 auto cit = class_idx.find(it.key());
2319 if (cit == class_idx.end() || !doff.contains(it.key())) continue;
2320 net.set_setup_delayoff(idx, cit->second, detail::dist_from_json<T>(it.value()),
2321 detail::dist_from_json<T>(doff.at(it.key())));
2322 }
2323 }
2324 // -- Server breakdown / repair ---------------------------------------
2325 // The wire form is `linemodel_save`'s: {failure, repair, downService?},
2326 // with `downService` keyed by CLASS NAME. MATLAB writes it per class
2327 // even when `setBreakdown` was given one distribution for every class,
2328 // flattening the class-independent form, so there is only one shape to
2329 // read here.
2330 if (nd.contains("breakdown")) {
2331 const json& bd = nd.at("breakdown");
2332 if (!bd.contains("failure") || !bd.contains("repair"))
2333 throw InputError(ErrorKind{"Format"},
2334 "network_reader: node '" + nd.at("name").get<std::string>() +
2335 "' declares a breakdown without both a failure and a repair time; a server "
2336 "that never recovers is an absorbing model, not a breakdown");
2337 std::vector<lang::Distrib<T> > down(class_idx.size(),
2339 if (bd.contains("downService")) {
2340 const json& ds = bd.at("downService");
2341 for (auto it = ds.begin(); it != ds.end(); ++it) {
2342 auto cit = class_idx.find(it.key());
2343 if (cit == class_idx.end()) continue;
2344 if (cit->second >= 1 && cit->second <= down.size())
2345 down[cit->second - 1] = detail::dist_from_json<T>(it.value());
2346 }
2347 }
2348 net.set_breakdown(idx, detail::dist_from_json<T>(bd.at("failure")),
2349 detail::dist_from_json<T>(bd.at("repair")), down);
2350 }
2351 if (nd.contains("switchoverTimes")) {
2352 // ONE KEY, TWO SHAPES, as `linemodel_save` writes them: under
2353 // POLLING an entry names the buffer the server LEAVES and carries
2354 // no `to`; otherwise it names the ordered class PAIR, and the
2355 // station keeps the (K x K) cell the reference keeps.
2356 //
2357 // A PAIRWISE SWITCHOVER IS CARRIED AND NOT CONSUMED, here as in
2358 // every codebase: the state machinery, the SSA events and the MVA
2359 // polling analyzer all reach `Station::switchover` through the
2360 // polling buffers, and `writeJSIM` warns and drops the pairwise
2361 // times on an ordinary Server because JMT's `Server` has no
2362 // switchover. Carrying it is still not idle -- it is what lets the
2363 // model be declared, written and read back unchanged, which is what
2364 // `switchover_basic` is.
2365 const bool polling = type == "Queue" &&
2366 nd.value("scheduling", std::string()) == "POLLING";
2367 for (const json& so : nd.at("switchoverTimes")) {
2368 auto cit = class_idx.find(so.at("from").get<std::string>());
2369 if (cit == class_idx.end()) continue;
2370 const std::string to = so.value("to", std::string());
2371 if (polling) {
2372 if (!to.empty())
2373 throw UnsupportedError(ErrorKind{"Import"},
2374 "network_reader: node '" + nd.at("name").get<std::string>() +
2375 "' is POLLING-scheduled but declares a switchover that names the "
2376 "class moved TO; a polling switchover is the walk out of one buffer");
2377 net.set_switchover(idx, cit->second,
2378 detail::dist_from_json<T>(so.at("distribution")));
2379 continue;
2380 }
2381 if (to.empty())
2382 throw UnsupportedError(ErrorKind{"Import"},
2383 "network_reader: node '" + nd.at("name").get<std::string>() +
2384 "' declares a switchover without the class moved TO, which only a "
2385 "POLLING station's per-buffer walk may omit");
2386 auto tit = class_idx.find(to);
2387 if (tit == class_idx.end()) continue;
2388 net.set_switchover(idx, cit->second, tit->second,
2389 detail::dist_from_json<T>(so.at("distribution")));
2390 }
2391 }
2392 if (nd.contains("quantum")) {
2393 // Round robin: the per-class time slice, {className: distribution},
2394 // as `linemodel_load` reads it. `set_quantum` refuses a station
2395 // that is not RR-scheduled.
2396 const json& qm = nd.at("quantum");
2397 for (auto it = qm.begin(); it != qm.end(); ++it) {
2398 auto cit = class_idx.find(it.key());
2399 if (cit == class_idx.end()) continue;
2400 net.set_quantum(idx, cit->second, detail::dist_from_json<T>(it.value()));
2401 }
2402 }
2403 // Polling table, load-dependent order and visit timers (classes by
2404 // name), after the switchovers so a table leg can fall back to them.
2405 if (nd.contains("pollingTable") && !nd.at("pollingTable").empty()) {
2406 std::vector<std::size_t> tab;
2407 std::vector<lang::Distrib<T>> swl;
2408 for (const json& te : nd.at("pollingTable")) {
2409 auto cit = class_idx.find(te.at("class").get<std::string>());
2410 if (cit == class_idx.end())
2411 throw InputError(ErrorKind{"Model"}, "network_reader: node '" + nd.at("name").get<std::string>() +
2412 "' has a polling table entry naming an unknown class");
2413 tab.push_back(cit->second);
2414 swl.push_back(te.contains("switchover") && !te.at("switchover").is_null()
2415 ? detail::dist_from_json<T>(te.at("switchover"))
2417 }
2418 net.set_polling_table(idx, tab, swl);
2419 }
2420 if (nd.contains("pollingOrder") && nd.at("pollingOrder").is_string()) {
2421 const lang::PollingOrder po = detail::polling_order_from_json(nd.at("pollingOrder").get<std::string>());
2423 auto cit = class_idx.find(nd.at("pollingOrderClass").get<std::string>());
2424 if (cit == class_idx.end())
2425 throw InputError(ErrorKind{"Model"}, "network_reader: node '" + nd.at("name").get<std::string>() +
2426 "' has a THRESHOLD polling order naming an unknown class");
2427 net.set_polling_order(idx, po, cit->second,
2428 static_cast<long>(std::lround(nd.at("pollingOrderThreshold").get<double>())));
2429 } else {
2430 net.set_polling_order(idx, po);
2431 }
2432 }
2433 if (nd.contains("pollingTimer") && nd.at("pollingTimer").is_object()) {
2434 const json& tm = nd.at("pollingTimer");
2435 std::vector<lang::Distrib<T>> tl(classes.size(), lang::Distrib<T>::disabled_dist());
2436 if (tm.contains("distributions"))
2437 for (const json& td : tm.at("distributions")) {
2438 auto cit = class_idx.find(td.at("class").get<std::string>());
2439 if (cit == class_idx.end()) continue;
2440 tl[cit->second - 1] = detail::dist_from_json<T>(td.at("distribution"));
2441 }
2442 // classes the station does not serve carry no timer; any positive
2443 // placeholder keeps set_polling_timer's per-class contract
2444 const lang::Distrib<T>* first = nullptr;
2445 for (const auto& d : tl)
2446 if (!d.disabled) { first = &d; break; }
2447 if (first != nullptr) {
2448 const lang::Distrib<T> f = *first;
2449 for (auto& d : tl)
2450 if (d.disabled) d = f;
2451 const bool preempt = tm.contains("preemptive") &&
2452 (tm.at("preemptive").is_boolean() ? tm.at("preemptive").get<bool>()
2453 : tm.at("preemptive").get<double>() != 0.0);
2454 net.set_polling_timer(idx, tl, detail::polling_timer_from_json(tm.value("scope", std::string("LOCAL"))),
2455 preempt);
2456 }
2457 }
2458 if (nd.contains("serverTypes")) {
2459 for (const json& st : nd.at("serverTypes")) {
2460 typename qn::Station<T>::ServerType stype;
2461 stype.name = st.value("name", std::string());
2462 stype.count = st.value("count", 1.0);
2463 if (st.contains("compatibleClasses")) {
2464 stype.compatible.assign(classes.size(), false);
2465 for (const json& cn : st.at("compatibleClasses")) {
2466 auto cit = class_idx.find(cn.get<std::string>());
2467 if (cit != class_idx.end()) stype.compatible[cit->second - 1] = true;
2468 }
2469 }
2470 if (st.contains("service")) {
2471 stype.service.assign(classes.size(), lang::Distrib<T>::disabled_dist());
2472 const json& sv = st.at("service");
2473 for (auto it = sv.begin(); it != sv.end(); ++it) {
2474 auto cit = class_idx.find(it.key());
2475 if (cit != class_idx.end())
2476 stype.service[cit->second - 1] = detail::dist_from_json<T>(it.value());
2477 }
2478 }
2479 net.add_server_type(idx, stype);
2480 }
2481 if (nd.contains("heteroSchedPolicy"))
2483 idx, detail::hetero_from_json(nd.at("heteroSchedPolicy").get<std::string>()));
2484 }
2485 // Job parallelism: servers seized at once by a job, per class. Read after
2486 // the pools, which size the station and so bound the admissible values.
2487 if (nd.contains("serverParallelism")) {
2488 const json& sp = nd.at("serverParallelism");
2489 for (auto it = sp.begin(); it != sp.end(); ++it) {
2490 auto cit = class_idx.find(it.key());
2491 if (cit != class_idx.end())
2492 net.set_server_parallelism(idx, cit->second, it.value().get<std::size_t>());
2493 }
2494 }
2495
2496 // -- The Source refinements: batch size and the MMAP mark binding ----
2497 if (nd.contains("arrivalBatch")) {
2498 const json& ab = nd.at("arrivalBatch");
2499 for (auto it = ab.begin(); it != ab.end(); ++it) {
2500 auto cit = class_idx.find(it.key());
2501 if (cit != class_idx.end())
2502 net.set_arrival_batch(idx, cit->second, detail::dist_from_json<T>(it.value()));
2503 }
2504 }
2505 if (nd.contains("markedClasses")) {
2506 std::vector<std::size_t> marks;
2507 for (const json& cn : nd.at("markedClasses")) {
2508 auto cit = class_idx.find(cn.get<std::string>());
2509 if (cit == class_idx.end())
2510 throw InputError(ErrorKind{"Format"}, "network_reader: node '" + nd.at("name").get<std::string>() +
2511 "' binds mark " + std::to_string(marks.size() + 1) +
2512 " to class '" + cn.get<std::string>() +
2513 "', which the model does not declare");
2514 marks.push_back(cit->second);
2515 }
2516 net.set_marked_classes(idx, marks);
2517 }
2518
2519 // -- The order-independent / pass-and-swap station -------------------
2520 //
2521 // mu(c) crosses as a macrostate TABLE, so `oiCutoffs` is not decoration:
2522 // it is the lattice the table was materialized over and the point beyond
2523 // which the rate saturates. An ABSENT `oiCutoffs` means the table is
2524 // NOT clamped: Python writes a non-saturating mu at a finite buffer as
2525 // the exact simplex 1 <= sum(n) <= cap with no cutoffs, and every other
2526 // reader then looks the raw counts up. Assuming a 10-per-class box here
2527 // served such a station mu(10) for every count above 10.
2528 if (nd.contains("oiServiceRate")) {
2529 std::vector<int> cut;
2530 if (nd.contains("oiCutoffs")) {
2531 const std::vector<double> cv = detail::num_vec_from_json<double>(nd.at("oiCutoffs"));
2532 for (std::size_t r = 0; r < classes.size() && r < cv.size(); ++r)
2533 cut.push_back(static_cast<int>(std::lround(cv[r])));
2534 }
2535 std::vector<std::vector<bool> > swap;
2536 if (nd.contains("swapGraph")) {
2537 const Matrix<T> sg = detail::mat_from_json<T>(nd.at("swapGraph"));
2538 swap.assign(sg.rows(), std::vector<bool>(sg.cols(), false));
2539 for (std::size_t a = 0; a < sg.rows(); ++a)
2540 for (std::size_t b = 0; b < sg.cols(); ++b)
2541 swap[a][b] = num_traits<T>::to_double(sg(a, b)) != 0.0;
2542 }
2543 net.set_pas(idx,
2544 detail::oi_rate_from_json<T>(nd.at("oiServiceRate"), cut, classes.size()),
2545 swap);
2546 }
2547
2548 // -- The declared state -----------------------------------------------
2549 if (nd.contains("initialState") && type == "Place") {
2550 net.set_initial_marking(idx, detail::num_vec_from_json<T>(nd.at("initialState")));
2551 } else if (nd.contains("initialState") && !nd.contains("stateSpace")) {
2552 // A stateful node that is not a Place carries its declared state in
2553 // the same key, and this struct spells a declared state as a
2554 // ONE-ROW state space under a prior of one (`sn_state.h`, the CTMC
2555 // transient's own reading). MATLAB, the JAR and Python all write
2556 // the key for every stateful node, so ignoring it outside a Place
2557 // dropped the initialization of every station: a model saved after
2558 // initFromMarginal came back here as the default one, with the
2559 // difference visible only in the numbers.
2560 const std::vector<T> row = detail::num_vec_from_json<T>(nd.at("initialState"));
2561 if (!row.empty()) {
2562 Matrix<T> space(1, row.size());
2563 for (std::size_t k = 0; k < row.size(); ++k) space(0, k) = row[k];
2564 net.set_state_prior(idx, space, std::vector<T>(1, num_traits<T>::from_double(1.0)));
2565 }
2566 }
2567 if (nd.contains("statePrior") || nd.contains("stateSpace")) {
2568 if (!nd.contains("statePrior") || !nd.contains("stateSpace"))
2569 throw InputError(ErrorKind{"Format"},
2570 "network_reader: node '" + nd.at("name").get<std::string>() +
2571 "' declares one of stateSpace / statePrior without the other; the prior is a "
2572 "distribution over the ROWS of that space and means nothing alone");
2573 net.set_state_prior(idx, detail::mat_from_json<T>(nd.at("stateSpace")),
2574 detail::num_vec_from_json<T>(nd.at("statePrior")));
2575 }
2576 if (nd.contains("departureDiscipline")) {
2577 const json& dd = nd.at("departureDiscipline");
2578 for (auto it = dd.begin(); it != dd.end(); ++it) {
2579 auto cit = class_idx.find(it.key());
2580 if (cit != class_idx.end())
2582 idx, cit->second, detail::departure_from_json(it.value().get<std::string>()));
2583 }
2584 }
2585
2586 // Rate scaling. `loadDependence` carries the lldscaling vector itself,
2587 // indexed from population one; `classDependence` and `jointDependence`
2588 // carry beta_r(n) and eta_i(n) materialized over the per-class box
2589 // lattice, because a function handle cannot cross JSON.
2590 for (int kind = 0; kind < 3; ++kind) {
2591 static const char* kKeys[] = {"loadDependence", "classDependence",
2592 "jointDependence"};
2593 static const char* kTypes[] = {"loadDependent", "classDependent",
2594 "jointDependent"};
2595 if (!nd.contains(kKeys[kind])) continue;
2596 if (type != "Queue" && type != "Delay")
2597 throw UnsupportedError(ErrorKind{"Import"},
2598 std::string("network_reader: node '") + nd.at("name").get<std::string>() +
2599 "' carries '" + kKeys[kind] +
2600 "', which scales a SERVICE rate and is only meaningful at a Queue or a "
2601 "Delay");
2602 const detail::json& blk = nd.at(kKeys[kind]);
2603 if (blk.value("type", std::string(kTypes[kind])) != kTypes[kind])
2604 throw UnsupportedError(ErrorKind{"Import"}, std::string("network_reader: '") + kKeys[kind] +
2605 "' at node '" + nd.at("name").get<std::string>() +
2606 "' declares type '" +
2607 blk.value("type", std::string("?")) +
2608 "', which this reader does not implement");
2609 if (!blk.contains("scaling"))
2610 throw InputError(ErrorKind{"Format"}, std::string("network_reader: '") + kKeys[kind] +
2611 "' at node '" + nd.at("name").get<std::string>() +
2612 "' carries no 'scaling'");
2613 if (kind == 0) {
2614 net.set_load_dependence(idx, detail::num_vec_from_json<T>(blk.at("scaling")));
2615 continue;
2616 }
2617 // An ABSENT `cutoffs` means NO clamping: the table is keyed by the
2618 // raw counts, as MATLAB, the JAR and Python read it. The writers omit
2619 // it when the station's buffer truncates the box (sum(n) <= cap), and
2620 // every reachable count is then tabulated. Clamping at one job per
2621 // class here served beta(1) for every larger count.
2622 std::vector<int> cut;
2623 if (blk.contains("cutoffs")) {
2624 const std::vector<double> cv = detail::num_vec_from_json<double>(blk.at("cutoffs"));
2625 for (std::size_t r = 0; r < classes.size() && r < cv.size(); ++r)
2626 cut.push_back(static_cast<int>(std::lround(cv[r])));
2627 }
2628 const lang::CdScaling<T> fun =
2629 detail::cd_scaling_from_json<T>(blk.at("scaling"), cut, classes.size());
2630 const std::vector<T> peak = detail::cd_peak_from_json<T>(blk, blk.at("scaling"));
2631 if (kind == 1) net.set_class_dependence(idx, fun, peak);
2632 else net.set_joint_dependence(idx, fun, peak);
2633 }
2634 // Immediate feedback, a per-class map on the node. The writers emit it
2635 // for a Queue only, and only for the classes it is set on, so an absent
2636 // entry means "not set" rather than false.
2637 if (nd.contains("immediateFeedback")) {
2638 const json& imf = nd.at("immediateFeedback");
2639 for (auto it = imf.begin(); it != imf.end(); ++it) {
2640 auto cit = class_idx.find(it.key());
2641 if (cit != class_idx.end() && it.value().get<bool>())
2642 net.set_immediate_feedback(idx, cit->second);
2643 }
2644 }
2645 }
2646
2647 // -- Pass 3: routing. ----------------------------------------------------
2648 const json& routing = model.at("routing");
2650 const json& mat = routing.at("matrix");
2651 for (auto ck = mat.begin(); ck != mat.end(); ++ck) {
2652 // Key "SrcClass,DstClass"; a bare "Class" means same-class routing.
2653 const std::string key = ck.key();
2654 const std::size_t comma = key.find(',');
2655 const std::string cs = comma == std::string::npos ? key : key.substr(0, comma);
2656 const std::string cd = comma == std::string::npos ? key : key.substr(comma + 1);
2657 const std::size_t r = class_idx.at(cs);
2658 const std::size_t s = class_idx.at(cd);
2659 for (auto si = ck.value().begin(); si != ck.value().end(); ++si) {
2660 const std::size_t from = node_idx.at(si.key());
2661 for (auto di = si.value().begin(); di != si.value().end(); ++di)
2662 P.set(r, s, from, node_idx.at(di.key()),
2663 num_traits<T>::from_double(di.value().get<double>()));
2664 }
2665 }
2666 net.link(P);
2667
2668 // -- Pass 3b: the non-probabilistic dispatchers. -------------------------
2669 //
2670 // `routing` above carries the MATRIX, which is what a PROB dispatcher is
2671 // fully described by. A RROBIN, JSQ or power-of-d dispatcher has the same
2672 // matrix and a different rule, so reading only the matrix turns every one
2673 // of them into probabilistic routing with no diagnostic. `link()` has
2674 // already run, so these overwrite the per-class strategy it defaulted to.
2675 if (model.contains("routingStrategies")) {
2676 const json& rs = model.at("routingStrategies");
2677 for (auto ni = rs.begin(); ni != rs.end(); ++ni) {
2678 auto nit = node_idx.find(ni.key());
2679 for (auto ci = ni.value().begin(); ci != ni.value().end(); ++ci) {
2680 const lang::RoutingStrategy rst =
2681 detail::routing_from_json(ci.value().get<std::string>());
2682 // DISABLED IS DERIVED, not declared: it marks a (node, class)
2683 // pair the class never visits, the refresh re-derives it, and
2684 // every reference loader skips it. Writers before BUG-94 also
2685 // emitted it for the AUTO-ADDED class-switch nodes they do not
2686 // put in `nodes`, so an entry naming an unknown node is only
2687 // tolerated for this one value -- anything else is still a
2688 // dangling reference and is named.
2689 if (nit == node_idx.end()) {
2690 if (rst == lang::RoutingStrategy::DISABLED) continue;
2691 throw InputError(ErrorKind{"Format"}, "network_reader: routingStrategies names node '" + ni.key() +
2692 "', which the model does not declare");
2693 }
2694 if (rst == lang::RoutingStrategy::DISABLED) continue;
2695 auto cit = class_idx.find(ci.key());
2696 if (cit == class_idx.end()) continue;
2697 net.set_routing(nit->second, cit->second, rst);
2698 }
2699 }
2700 }
2701 if (model.contains("routingWeights")) {
2702 const json& rw = model.at("routingWeights");
2703 for (auto ni = rw.begin(); ni != rw.end(); ++ni) {
2704 auto nit = node_idx.find(ni.key());
2705 if (nit == node_idx.end()) continue;
2706 for (auto ci = ni.value().begin(); ci != ni.value().end(); ++ci) {
2707 auto cit = class_idx.find(ci.key());
2708 if (cit == class_idx.end()) continue;
2709 std::map<std::size_t, double> w;
2710 for (auto di = ci.value().begin(); di != ci.value().end(); ++di) {
2711 auto dit = node_idx.find(di.key());
2712 if (dit != node_idx.end()) w[dit->second] = di.value().get<double>();
2713 }
2714 net.set_routing_weights(nit->second, cit->second, w);
2715 }
2716 }
2717 }
2718 if (model.contains("routingParams")) {
2719 const json& rp = model.at("routingParams");
2720 for (auto ni = rp.begin(); ni != rp.end(); ++ni) {
2721 auto nit = node_idx.find(ni.key());
2722 if (nit == node_idx.end()) continue;
2723 for (auto ci = ni.value().begin(); ci != ni.value().end(); ++ci) {
2724 auto cit = class_idx.find(ci.key());
2725 if (cit == class_idx.end() || !ci.value().contains("d")) continue;
2726 net.set_routing_param(nit->second, cit->second, ci.value().at("d").get<int>());
2727 }
2728 }
2729 }
2730
2731 // -- Pass 3b3: Krzesinski state-dependent routing. -----------------------
2732 //
2733 // Restored AFTER `link()` and after the dispatchers above: `link` writes the
2734 // uniform placeholder into the entry row, which the declaration supersedes,
2735 // and `routingStrategies` has already named that row SDR without saying what
2736 // the subnetwork looks like. Every centre travels by NODE NAME, so a node
2737 // reordering on the writing side cannot shift one, and branch index 1 is the
2738 // complement M-V and arrives as an empty list.
2739 // See _kb/16-state-dependent-routing.md
2740 if (model.contains("stateDepRouting")) {
2741 const json& sd = model.at("stateDepRouting");
2742 for (const char* k : {"entry", "departure", "class", "branches", "level", "C", "d"})
2743 if (!sd.contains(k))
2744 throw InputError(ErrorKind{"Format"}, std::string("network_reader: 'stateDepRouting' carries no '") + k +
2745 "'");
2746 auto node_of = [&](const std::string& nm) -> std::size_t {
2747 const std::map<std::string, std::size_t>::const_iterator it = node_idx.find(nm);
2748 if (it == node_idx.end())
2749 throw InputError(ErrorKind{"Format"}, "network_reader: 'stateDepRouting' names node '" + nm +
2750 "', which the model does not declare");
2751 return it->second;
2752 };
2753 const std::map<std::string, std::size_t>::const_iterator ci =
2754 class_idx.find(sd.at("class").get<std::string>());
2755 if (ci == class_idx.end())
2756 throw InputError(ErrorKind{"Format"}, "network_reader: 'stateDepRouting' names class '" +
2757 sd.at("class").get<std::string>() +
2758 "', which the model does not declare");
2759 std::vector<std::vector<std::size_t>> branches;
2760 for (const json& b : sd.at("branches")) {
2761 std::vector<std::size_t> centres;
2762 for (const json& nm : b) centres.push_back(node_of(nm.get<std::string>()));
2763 branches.push_back(centres);
2764 }
2765 std::vector<std::size_t> level;
2766 for (const json& v : sd.at("level")) level.push_back(static_cast<std::size_t>(v.get<double>()));
2767 std::vector<double> C;
2768 for (const json& v : sd.at("C")) C.push_back(v.get<double>());
2769 const json& dj = sd.at("d");
2770 Matrix<double> d(dj.size(), dj.empty() ? 0 : dj.at(0).size(), 0.0);
2771 for (std::size_t t = 0; t < dj.size(); ++t) {
2772 if (dj.at(t).size() != d.cols())
2773 throw InputError(ErrorKind{"Format"}, "network_reader: 'stateDepRouting' carries a ragged coefficient "
2774 "matrix d");
2775 for (std::size_t b = 0; b < d.cols(); ++b) d(t, b) = dj.at(t).at(b).get<double>();
2776 }
2777 net.set_state_dep_routing(node_of(sd.at("entry").get<std::string>()),
2778 node_of(sd.at("departure").get<std::string>()), branches, level, C,
2779 d, ci->second);
2780 }
2781
2782 // -- Pass 3b2: the global (Whittle) dependence. --------------------------
2783 //
2784 // phi(n) is rebuilt from the materialized slot lattice written by
2785 // `network_to_json`. The slots carry station and class NAMES, resolved
2786 // through this model's own index spaces, so a reordering on the writing side
2787 // cannot silently shift a coordinate. The population is clamped to the
2788 // tabulated cutoffs, which is the same saturation the writer's box lattice
2789 // declares.
2790 if (model.contains("globalDependence")) {
2791 const json& blk = model.at("globalDependence");
2792 if (blk.value("type", std::string("globalDependent")) != "globalDependent")
2793 throw UnsupportedError(ErrorKind{"Import"},
2794 std::string("network_reader: 'globalDependence' declares type '") +
2795 blk.value("type", std::string("?")) + "', which this reader does not implement");
2796 if (!blk.contains("scaling"))
2797 throw InputError(ErrorKind{"Format"}, "network_reader: 'globalDependence' carries no 'scaling'");
2798 const qn::NetworkStruct<T>& sn0 = net.get_struct();
2799 const std::size_t M = sn0.nstations, K = sn0.nclasses;
2800 std::vector<std::size_t> slot_st, slot_cl;
2801 if (blk.contains("slots"))
2802 for (const json& sm : blk.at("slots")) {
2803 auto nit = node_idx.find(sm.at("station").get<std::string>());
2804 auto cit = class_idx.find(sm.at("class").get<std::string>());
2805 if (nit == node_idx.end() || cit == class_idx.end())
2806 throw InputError(ErrorKind{"Format"},
2807 "network_reader: 'globalDependence' names a station or class the model "
2808 "does not declare");
2809 slot_st.push_back(sn0.nodes[nit->second - 1].station - 1);
2810 slot_cl.push_back(cit->second - 1);
2811 }
2812 const std::size_t P = slot_st.size();
2813 std::vector<int> cuts(P, 0);
2814 if (blk.contains("cutoffs")) {
2815 const std::vector<double> cv = detail::num_vec_from_json<double>(blk.at("cutoffs"));
2816 for (std::size_t d = 0; d < P && d < cv.size(); ++d)
2817 cuts[d] = static_cast<int>(std::lround(cv[d]));
2818 }
2819 const int wcut = blk.value("cutoff", 10);
2820 std::map<std::string, std::vector<T>> tbl;
2821 for (auto it = blk.at("scaling").begin(); it != blk.at("scaling").end(); ++it)
2822 tbl[it.key()] = detail::num_vec_from_json<T>(it.value());
2823 std::vector<T> peak(M * K, num_traits<T>::from_int(1));
2824 if (blk.contains("peak")) {
2825 const std::vector<T> pv = detail::num_vec_from_json<T>(blk.at("peak"));
2826 for (std::size_t j = 0; j < peak.size() && j < pv.size(); ++j) peak[j] = pv[j];
2827 }
2828 const std::vector<T> ones(M * K, num_traits<T>::from_int(1));
2830 [slot_st, slot_cl, cuts, tbl, ones, K, P](const std::vector<T>& n) {
2831 std::string key;
2832 if (P == 0) key = "0";
2833 else
2834 for (std::size_t d = 0; d < P; ++d) {
2835 long x = std::lround(num_traits<T>::to_double(n[slot_st[d] * K + slot_cl[d]]));
2836 if (x < 0) x = 0;
2837 if (x > cuts[d]) x = cuts[d];
2838 if (d) key += ',';
2839 key += std::to_string(x);
2840 }
2841 typename std::map<std::string, std::vector<T>>::const_iterator it = tbl.find(key);
2842 return it == tbl.end() ? ones : it->second;
2843 },
2844 peak, wcut);
2845 }
2846
2847 // -- Pass 3c: the finite capacity regions. -------------------------------
2848 //
2849 // A region caps the jobs held ACROSS a set of stations, which no per-station
2850 // capacity expresses. Dropping the block is the failure this reader's key
2851 // gate was written for: an FCR model then solves as the UNBOUNDED one and
2852 // reports a confident, wrong queue length.
2853 if (model.contains("finiteCapacityRegions")) {
2854 for (const json& rj : model.at("finiteCapacityRegions")) {
2855 std::vector<std::size_t> members;
2856 // The per-station `classCap` refines the region's own cap at that
2857 // station; the struct carries ONE cap per (station, class), so the
2858 // tightest of the two is what the region actually enforces.
2859 std::vector<double> cap(classes.size(), -1.0);
2860 auto read_class_map = [&](const json& blk, std::vector<double>& dst) {
2861 for (auto it = blk.begin(); it != blk.end(); ++it) {
2862 auto cit = class_idx.find(it.key());
2863 if (cit == class_idx.end()) continue;
2864 const double v = it.value().get<double>();
2865 double& slot = dst[cit->second - 1];
2866 slot = slot == -1.0 ? v : std::min(slot, v);
2867 }
2868 };
2869 if (rj.contains("classMaxJobs")) read_class_map(rj.at("classMaxJobs"), cap);
2870 for (const json& sj : rj.at("stations")) {
2871 auto nit = node_idx.find(sj.at("node").get<std::string>());
2872 if (nit == node_idx.end())
2873 throw InputError(ErrorKind{"Format"}, "network_reader: finite capacity region '" +
2874 rj.value("name", std::string("?")) + "' names node '" +
2875 sj.at("node").get<std::string>() +
2876 "', which the model does not declare");
2877 members.push_back(nit->second);
2878 if (sj.contains("classCap")) read_class_map(sj.at("classCap"), cap);
2879 }
2880 std::vector<double> mem(classes.size(), -1.0);
2881 if (rj.contains("classMaxMemory")) read_class_map(rj.at("classMaxMemory"), mem);
2882 std::vector<T> size(classes.size(), num_traits<T>::from_int(1));
2883 std::vector<T> weight(classes.size(), num_traits<T>::from_int(1));
2884 for (const json& sj : rj.at("stations")) {
2885 if (sj.contains("classSize"))
2886 for (auto it = sj.at("classSize").begin(); it != sj.at("classSize").end(); ++it) {
2887 auto cit = class_idx.find(it.key());
2888 if (cit != class_idx.end())
2889 size[cit->second - 1] =
2890 num_traits<T>::from_double(it.value().get<double>());
2891 }
2892 if (sj.contains("classWeight"))
2893 for (auto it = sj.at("classWeight").begin(); it != sj.at("classWeight").end();
2894 ++it) {
2895 auto cit = class_idx.find(it.key());
2896 if (cit != class_idx.end())
2897 weight[cit->second - 1] =
2898 num_traits<T>::from_double(it.value().get<double>());
2899 }
2900 }
2901 std::vector<lang::DropStrategy> rule(classes.size(), lang::DropStrategy::WAITQ);
2902 if (rj.contains("dropRule"))
2903 for (auto it = rj.at("dropRule").begin(); it != rj.at("dropRule").end(); ++it) {
2904 auto cit = class_idx.find(it.key());
2905 if (cit != class_idx.end())
2906 rule[cit->second - 1] = detail::drop_from_json(it.value().get<std::string>());
2907 }
2908 const std::size_t reg =
2909 net.add_region(members, cap, rj.value("globalMaxJobs", -1.0), rule, mem, size,
2910 rj.value("globalMaxMemory", -1.0),
2911 rj.value("name", std::string()));
2912 net.set_region_weights(reg, weight);
2913 if (rj.contains("constraintA") && rj.contains("constraintB"))
2914 net.set_region_constraint(reg, detail::mat_from_json<T>(rj.at("constraintA")),
2915 detail::num_vec_from_json<T>(rj.at("constraintB")));
2916 }
2917 }
2918
2919 // -- Pass 4: the declared rewards. ---------------------------------------
2920 //
2921 // THE DECLARATIVE FORM ONLY, `{name, type, node, class?}`, which is all the
2922 // writers emit: a reward defined from a bare lambda has no reproducible form
2923 // and `linemodel_save` warns and omits it rather than writing something that
2924 // would be wrong on reload. Each template is rebuilt here as a function of
2925 // the AGGREGATE state row -- the per-(station, class) counts in
2926 // `(ist-1)*K + k` order that `set_reward` is defined over -- so the value is
2927 // computed from the chain's own states and not from a mean.
2928 if (model.contains("rewards")) {
2929 const std::size_t K = classes.size();
2930 for (const json& rw : model.at("rewards")) {
2931 const std::string nm = rw.at("name").get<std::string>();
2932 const std::string kind = rw.at("type").get<std::string>();
2933 const std::string node_name = rw.at("node").get<std::string>();
2934 auto nit = node_idx.find(node_name);
2935 if (nit == node_idx.end())
2936 throw InputError(ErrorKind{"Format"}, "network_reader: reward '" + nm + "' names node '" + node_name +
2937 "', which the model does not declare");
2938 // The struct carries station -> node and no inverse, so the station
2939 // is found by scanning it; a node with no station is refused below.
2940 std::size_t ist = 0;
2941 for (std::size_t s = 0; s < net.get_struct().station_to_node.size(); ++s)
2942 if (net.get_struct().station_to_node[s] == nit->second) ist = s + 1;
2943 if (ist == 0)
2944 throw UnsupportedError(ErrorKind{"Import"}, "network_reader: reward '" + nm + "' is declared at node '" +
2945 node_name +
2946 "', which is not a station and so has no job count");
2947 // A reward with no class covers EVERY class at the station; with one,
2948 // exactly that class. The two are different quantities, so the
2949 // absence of the key is carried through rather than defaulted.
2950 std::size_t cls = 0; // 0 = all classes
2951 if (rw.contains("class")) {
2952 auto cit = class_idx.find(rw.at("class").get<std::string>());
2953 if (cit == class_idx.end())
2954 throw InputError(ErrorKind{"Format"}, "network_reader: reward '" + nm + "' names class '" +
2955 rw.at("class").get<std::string>() +
2956 "', which the model does not declare");
2957 cls = cit->second;
2958 }
2959 const double nservers = net.get_struct().stations[ist - 1].nservers;
2960 const double cap = net.get_struct().stations[ist - 1].cap;
2961 const std::size_t base = (ist - 1) * K;
2962 // The DECLARATIVE descriptor travels with the lambda so the writer
2963 // can emit the reward back out; a reward built from a bare function
2964 // has none and is omitted at save time, as the reference does.
2965 if (kind == "QLen") {
2966 net.set_reward(nm, [base, K, cls](const std::vector<T>& n) {
2967 if (cls) return n[base + cls - 1];
2968 T s = num_traits<T>::from_int(0);
2969 for (std::size_t k = 0; k < K; ++k) s = T(s + n[base + k]);
2970 return s;
2971 }, kind, nit->second, cls);
2972 } else if (kind == "Util") {
2973 // min(jobs, nservers), the reference's own definition: the number
2974 // of BUSY servers, not a fraction.
2975 net.set_reward(nm, [base, K, cls, nservers](const std::vector<T>& n) {
2976 T s = num_traits<T>::from_int(0);
2977 if (cls) s = n[base + cls - 1];
2978 else
2979 for (std::size_t k = 0; k < K; ++k) s = T(s + n[base + k]);
2980 const T c = num_traits<T>::from_double(nservers);
2981 return num_traits<T>::to_double(s) > nservers ? c : s;
2982 }, kind, nit->second, cls);
2983 } else if (kind == "Blocking") {
2984 net.set_reward(nm, [base, K, cap](const std::vector<T>& n) {
2985 T s = num_traits<T>::from_int(0);
2986 for (std::size_t k = 0; k < K; ++k) s = T(s + n[base + k]);
2989 }, kind, nit->second, cls);
2990 } else {
2991 throw UnsupportedError(ErrorKind{"Import"},
2992 "network_reader: reward '" + nm + "' is of type '" + kind +
2993 "', and the reproducible templates are QLen, Util and Blocking; a Custom "
2994 "reward wraps an arbitrary function and is not on the wire at all");
2995 }
2996 }
2997 }
2998 return net;
2999}
3000
3001/** Parse a model.json file into a `qn::Network<T>`. */
3002template <class T>
3003qn::Network<T> read_network_json(const std::string& path) {
3004 std::ifstream in(path.c_str());
3005 if (!in) throw InputError(ErrorKind{"File"}, "network_reader: cannot open " + path);
3006 detail::json root;
3007 try {
3008 in >> root;
3009 } catch (const detail::json::parse_error& e) {
3010 throw InputError(ErrorKind{"Format"}, "network_reader: malformed JSON in " + path + ": " + e.what());
3011 }
3012 return build_network_from_json<T>(root);
3013}
3014
3015} // namespace io
3016} // namespace line
3017
3018#endif // LINE_IO_NETWORK_READER_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.
A queueing network under construction.
void set_drop_rule(std::size_t node, std::size_t cls, DropStrategy rule)
station.setDropRule(class, rule).
void set_state_prior(std::size_t node, const Matrix< T > &space, const std::vector< T > &prior)
StatefulNode.setStatePrior(space, prior): a distribution over the rows of a DECLARED state space.
void set_departure_discipline(std::size_t node, std::size_t cls, lang::DepartureDiscipline rule)
Place.setDepartureDiscipline(class, rule).
std::size_t add_logger(const std::string &nm, const std::string &log_file=std::string())
A Logger node: a pass-through that records every job crossing it.
void set_load_dependence(std::size_t node, const std::vector< T > &alpha)
station.setLoadDependence(alpha): the rate multiplier at population 1, 2, ... The vector is indexed f...
void set_class_capacity(std::size_t node, std::size_t cls, double k)
station.setChainCapacity(class, k).
std::size_t add_source(const std::string &nm)
The external arrival station.
std::size_t add_fork(const std::string &nm, double tasks_per_link=1.0)
A Fork node.
void bind_join(std::size_t join_node, std::size_t fork_node)
Record which Fork a Join created by add_join_unbound closes.
void set_arrival_batch(std::size_t node, std::size_t cls, const Distrib< T > &dist)
Source.setArrivalBatch(class, dist): the batch-size law released at each arrival epoch.
std::size_t add_open_class(const std::string &nm, int prio=0)
An open class.
void set_class_patience(std::size_t cls, const Distrib< T > &dist, lang::ImpatienceType kind=lang::ImpatienceType::RENEGING)
JobClass.setPatience(kind, dist): the CLASS-WIDE abandonment law.
std::size_t add_delay(const std::string &nm)
An infinite-server station (a Delay, MATLAB's Delay / DelayStation).
void set_orbital_search(std::size_t node, std::size_t cls, const T &prob)
Queue.setOrbitalSearch(class, prob): orbital search (Artalejo, Joshua and Krishnamoorthy 2002).
void set_class_spawn(std::size_t cls, std::size_t spawn_cls)
JobClass.spawnClass (sn.classspawn): the class injected at the same station on every completion of cl...
void set_polling_timer(std::size_t node, const std::vector< Distrib< T > > &dists, lang::PollingTimer scope=lang::PollingTimer::LOCAL, bool preemptive=false)
Queue.setPollingTimer(dist, scope, preemptive): a visit timer per class (one law for all classes,...
void set_region_constraint(std::size_t region, const Matrix< T > &A, const std::vector< T > &b)
The optional linear constraint A n <= b a region may carry beyond its caps.
void set_class_immediate_feedback(std::size_t cls)
jobclass.setImmediateFeedback(): the same property, class-wide.
std::size_t add_router(const std::string &nm)
A stateless routing node.
void set_initial_marking(std::size_t node, const std::vector< T > &tokens)
Place.setState(marking): the initial token count of the place, per class.
void set_orbit_persistence(std::size_t node, std::size_t cls, const T &join_prob, const T &persist_prob=num_traits< T >::from_int(1))
Queue.setOrbitPersistence(class, joinProb, persistProb): non-persistent retrial customers (Phung-Duc ...
void set_number_of_servers(std::size_t node, double n)
queue.setNumberOfServers(n).
void set_joint_dependence(std::size_t node, const CdScaling< T > &fun, const std::vector< T > &peak)
station.setJointDependence(eta, peakRatePerClass): MATLAB's Station.ljdScaling / ljdScalingPeak.
void set_fork_tasks_per_link(std::size_t fork_node, std::size_t jobclass, double tasks, std::size_t dest_node=0)
Variable forking levels on an existing Fork, the twin of MATLAB Fork.setTasksPerLink(jobclass,...
void set_patience(std::size_t node, std::size_t cls, const Distrib< T > &dist, lang::ImpatienceType kind=lang::ImpatienceType::RENEGING)
Queue.setPatience(class, dist, type): the abandonment timer of a job WAITING at the station,...
void set_reply_signal_class(std::size_t call_cls, std::size_t reply_cls)
JobClass.setReplySignalClass(reply) (sn.syncreply), plus the sn.replyblock the state layer needs.
std::size_t add_queue(const std::string &nm, SchedStrategy sched=SchedStrategy::FCFS)
A queueing station.
void set_routing(std::size_t node, std::size_t cls, RoutingStrategy rs)
node.setRouting(class, strategy).
void set_join_strategy(std::size_t node, lang::JoinStrategy strategy, double quorum=0.0)
Join.setStrategy(...): STD waits for every sibling, PARTIAL for a quorum.
void set_fork_branch_probability(std::size_t fork_node, std::size_t jobclass, std::size_t dest_node, double prob)
A branch that fires only with probability prob.
std::size_t add_cache(const std::string &nm, const CacheParam< T > &par)
A Cache node with its item population, list capacities and popularity.
void set_reward(const std::string &nm, const std::function< T(const std::vector< T > &)> &fn, const std::string &kind=std::string(), std::size_t node=0, std::size_t cls=0)
model.setReward(name, fn): a named reward evaluated on the AGGREGATE state row, the per-(station,...
void set_fluid_capacity(std::size_t node, double cap)
Place.setFluidCapacity(B): the level ceiling of a fluid place, Inf when unbounded.
std::size_t add_self_looping_class(const std::string &nm, double njobs, std::size_t refstat_node, int prio=0)
SelfLoopingClass(model, name, njobs, refstat, prio): a closed class whose jobs perpetually cycle at t...
void set_marked_classes(std::size_t node, const std::vector< std::size_t > &classes)
Source.markedClasses: the 1-based class carried by each mark of an MMAP.
std::size_t add_closed_class(const std::string &nm, double njobs, std::size_t refstat_node, int prio=0)
A closed class of the given population, referencing a station node.
void set_sched_param(std::size_t node, std::size_t cls, const T &weight)
The DPS / GPS weight of a class at a station.
std::size_t add_class_switch(const std::string &nm, const Matrix< T > &C)
A ClassSwitch node carrying the (nclasses x nclasses) switching matrix.
void set_fork_tasks_per_link_dist(std::size_t fork_node, std::size_t jobclass, const lang::Distrib< T > &dist, std::size_t dest_node=0)
A random jobs-per-link degree, redrawn per link and per forked job.
std::size_t add_sink(const std::string &nm)
The external departure node.
const NetworkStruct< T > & get_struct()
The refreshed struct, MATLAB's model.getStruct().
void set_batch_reject(std::size_t node, std::size_t cls, const T &p)
Queue.setBatchRejectProbability(class, p).
void set_polling_order(std::size_t node, lang::PollingOrder order, std::size_t prioclass=0, long threshold=-1)
Queue.setPollingOrder(order, prioclass, L): the visit-order rule.
void set_class_dependence(std::size_t node, const CdScaling< T > &fun, const std::vector< T > &peak=std::vector< T >())
station.setClassDependence(beta, peakRatePerClass).
void set_fluid_level(std::size_t node, double level)
Place.setFluidLevel(x0): the initial level of a fluid place.
void set_state_dep_routing(std::size_t entry, std::size_t departure, const std::vector< std::vector< std::size_t > > &branches, const std::vector< std::size_t > &level, const std::vector< double > &C, const Matrix< double > &d, std::size_t cls=0)
node.setStateDepRouting(class, departure, branches, level, C, d).
std::size_t add_place(const std::string &nm)
A Place: an SPN token container.
void set_routing_weights(std::size_t node, std::size_t cls, const std::map< std::size_t, double > &weights)
The per-destination weights of a WRROBIN dispatcher, per (node, class).
void set_log_path(const std::string &path)
Network.setLogPath: the directory every Logger of this model writes into.
void set_capacity(std::size_t node, double k)
station.setCapacity(k), the K of Kendall's notation.
NetworkStruct< T > & raw_struct()
The struct WITHOUT refreshing it, for a caller that is still building.
void set_switchover(std::size_t node, std::size_t cls, const Distrib< T > &so)
Queue.setSwitchover(jobclass, distrib): the switchover time of a class.
void set_place_fluid(std::size_t node, bool fluid)
Place.setFluid(flag): the place holds one real level in [0, fluid capacity] instead of tokens,...
void set_immediate_feedback(std::size_t node, std::size_t cls)
queue.setImmediateFeedback(class): a completing job of that class is fed straight back into service,...
void set_balking(std::size_t node, std::size_t cls, lang::BalkingStrategy strategy, const std::vector< typename Station< T >::BalkingThreshold > &thresholds)
Queue.setBalking(class, strategy, thresholds): an arrival that refuses to JOIN, on the state it finds...
void set_polling_table(std::size_t node, const std::vector< std::size_t > &table, const std::vector< Distrib< T > > &swlegs=std::vector< Distrib< T > >())
Queue.setPollingTable(table, swlegs): the visit sequence of a POLLING station (1-based classes,...
void add_server_type(std::size_t node, const typename Station< T >::ServerType &stype)
Queue.addServerType(...): one heterogeneous server pool of the station.
void set_quantum(std::size_t node, std::size_t cls, const Distrib< T > &q)
Queue.setQuantum(jobclass, distrib): the time slice of a class at a round-robin station.
void set_setup_delayoff(std::size_t node, std::size_t cls, const Distrib< T > &setup, const Distrib< T > &delayoff)
Queue.setDelayOff(class, setupTime, delayoffTime): the station powers down after sitting idle for the...
void set_class_deadline(std::size_t cls, double due)
JobClass.deadline: the soft deadline EDD, EDF and JMT's tardiness use.
void link(const RoutingMatrix< T > &Pm)
model.link(P): install the routing.
void set_routing_param(std::size_t node, std::size_t cls, int d)
The d of a power-of-d (SQ) dispatcher, per (node, class).
void set_retrial(std::size_t node, std::size_t cls, const Distrib< T > &proc, const T &rate, int max_attempts=0)
Queue.setRetrial(...): a station with an ORBIT instead of a waiting line.
void set_service(std::size_t node, std::size_t cls, const Distrib< T > &d)
station.setService(class, dist).
void set_reference_class(std::size_t cls)
JobClass.setReferenceClass(true): sn.refclass(c) picks this class.
std::size_t add_join_unbound(const std::string &nm)
The Join station on its own, with the fork left to bind_join.
void set_hetero_sched_policy(std::size_t node, lang::HeteroSchedPolicy policy)
Queue.setHeteroSchedPolicy(...): how the server pools are picked among.
void set_breakdown(std::size_t node, const Distrib< T > &failure, const Distrib< T > &repair, const std::vector< Distrib< T > > &down_service=std::vector< Distrib< T > >())
Queue.setBreakdown(failure, repair, downService): the server alternates up and down on the two clocks...
void set_pas(std::size_t node, const std::function< T(const std::vector< std::size_t > &)> &mu, const std::vector< std::vector< bool > > &swap_graph=std::vector< std::vector< bool > >())
Queue.setService(@(c) ...) for a pass-and-swap / order-independent station: the total service rate mu...
std::size_t add_transition(const std::string &nm, const TransitionParam< T > &par)
A Transition: the firing rules of an SPN, as Transition in MATLAB.
void set_orbit_impatience(std::size_t node, std::size_t cls, const Distrib< T > &dist)
Queue.setOrbitImpatience(class, dist): abandonment from the retrial orbit.
void set_signal(std::size_t cls, lang::SignalType type, lang::RemovalPolicy policy=lang::RemovalPolicy::RANDOM, std::size_t target=0, const std::vector< T > &remdist=std::vector< T >())
Declare a class to be a G-network SIGNAL rather than a job.
void set_global_dependence(const GdScaling< T > &fun, const std::vector< T > &peak)
model.setGlobalDependence(phi, peak): MATLAB's Network.gdScaling.
void set_server_parallelism(std::size_t node, std::size_t cls, std::size_t n)
Queue.setServerParallelism(class, n): the servers a job seizes for the whole of its service.
void set_orbit_policy(std::size_t node, std::size_t cls, int policy, int max_orbit, bool size_buffer=true)
The policy and bound of Queue.setOrbit(class, dist, policy, maxOrbit) on a class already declared by ...
void set_region_weights(std::size_t region, const std::vector< T > &weight)
FiniteCapacityRegion.setClassWeight: the per-class weight the region's global cap counts a job agains...
void set_arrival(std::size_t node, std::size_t cls, const Distrib< T > &d)
source.setArrival(class, dist): the same table, at the Source.
std::size_t add_region(const std::vector< std::size_t > &nodes, const std::vector< double > &class_max_jobs, double global_max_jobs=-1.0, const std::vector< DropStrategy > &rule=std::vector< DropStrategy >(), const std::vector< double > &class_max_memory=std::vector< double >(), const std::vector< T > &class_size=std::vector< T >(), double global_max_memory=-1.0, const std::string &name=std::string())
FiniteCapacityRegion(model, nodes): a cap on the jobs held ACROSS a set of stations.
void set_polling_type(std::size_t node, lang::PollingType rule, int par=0)
Queue.setPollingType(rule, par): the polling discipline of a POLLING station, identical across all cl...
The routing matrix a model script fills in, MATLAB's P cell array.
The exception types the port throws.
Enumerations and the minimal distribution descriptor shared by the model layer of the C++ port.
qn::Network< T > read_network_json(const std::string &path)
Parse a model.json file into a qn::Network<T>.
qn::Network< T > build_network_from_json(const detail::json &root)
Build a qn::Network<T> from a parsed model.json envelope.
mam::Map< T > dist_to_map(const Distrib< T > &d)
The (D0,D1) pair that reaches sn.proc.
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
@ TIMED
fires after its firing distribution elapses
Definition lang_types.h:383
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
@ NEGATIVE
removes a batch of jobs (Gelenbe's negative customer)
Definition lang_types.h:182
@ 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
RoutingStrategy
Routing strategies, with the values of MATLAB RoutingStrategy.
Definition lang_types.h:430
PollingTimer
Visit-timer scopes of a polling server, with the values of MATLAB PollingTimer.
Definition lang_types.h:412
DepartureDiscipline
When a Place releases a served token, MATLAB DepartureDiscipline.
Definition lang_types.h:499
Distrib< T > prior_continuous(const Distrib< T > &param_dist, const std::function< Distrib< T >(const T &)> &factory)
Prior(paramDist, distFactory): the continuous form.
Definition prior.h:150
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
@ LCFS
the newest waiting job; servers only once nobody waits
Definition lang_types.h:190
@ 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
Distrib< T > prior_discrete(const std::vector< Distrib< T > > &alternatives, const std::vector< T > &probabilities)
Prior(distributions, probabilities): the discrete form.
Definition prior.h:110
std::function< std::vector< T >(const std::vector< T > &)> CdScaling
A class-dependent scaling map, sn.cdscaling.
Definition lang_types.h:794
ReplacementStrategy
Cache replacement policies, with the values of MATLAB ReplacementStrategy.
Definition lang_types.h:419
ImpatienceType
Impatience kinds, with the values of MATLAB ImpatienceType.
Definition lang_types.h:483
bool in(const std::string &s, std::initializer_list< const char * > set)
const std::string * get(const Element *el, const std::string &key)
el.get(key), with Python's None as a null pointer.
Definition srvn_writer.h:62
const std::map< std::string, std::vector< std::string > > & table()
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
std::vector< T > ones(std::size_t n)
Column vector of ones, the ubiquitous e in MAP algebra.
Definition linalg.h:104
The Network constructor API: Queue, Delay, Source, Sink, Router, ClassSwitch, Cache,...
Number-type abstraction for the templated API port.
Prior: parameter uncertainty as a weighted set of alternative models.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
static Distrib empirical_cdf(const std::vector< T > &x, const std::vector< T > &F)
EmpiricalCDF(x, F): the moments of the MIDPOINT rule over the CDF bins, which is what MATLAB Empirica...
static Distrib nhpp(const std::vector< T > &breakpoints, const std::vector< T > &rates, bool cyclic)
NHPP(breakpoints, rates, cyclic): a MAPt of ORDER ONE, which is what an inhomogeneous Poisson process...
static Distrib mph(const std::vector< T > &alpha, const Matrix< T > &S, const std::vector< std::vector< T > > &exits)
MPH(alpha, S, {s_k}): the marked phase-type law, a PH with K labelled exits.
static Distrib mmapt(const std::vector< T > &breakpoints, const std::vector< Matrix< T > > &D0segs, const std::vector< std::vector< Matrix< T > > > &Dmarksegs, bool cyclic)
MMAPt(breakpoints, {D0_k}, {{D1^(c)_k}}, cyclic): the marked schedule.
static Distrib loglogistic(const T &shape, const T &scale)
LogLogistic(shape, scale), stored in getParam order {alpha = scale, beta = shape}.
static Distrib nnpp_piecewise_linear(const std::vector< double > &times, const std::vector< double > &rates, double dispersion=1.0, bool cyclic=true, int Q=200)
NNPP.piecewiseLinear(times, rates, dispersion, cyclic, Q): linear interpolation of knots.
static Distrib replayer(const std::vector< T > &samples)
Replayer / Trace: the samples, with their empirical first two moments.
static Distrib marked_mmpp(const Matrix< T > &D0, const std::vector< Matrix< T > > &D1k)
MarkedMMPP(D0, {D1k}): the marked MMPP (M3PP), i.e.
static Distrib normal(const T &mu, const T &sigma)
Normal(mu, sigma): the Gaussian, for use as a continuous Prior's parameter density.
static Distrib defective(const Distrib &in, const T &pInf)
Defective(inner, pInf): infinite with probability pInf, else inner.
static Distrib dmap(const Matrix< T > &D0, const Matrix< T > &D1)
DMAP(D0, D1): a DISCRETE-time MAP, where D0 + D1 is stochastic rather than a generator.
static Distrib exp_rate(const T &r)
static Distrib phase_type(const std::vector< T > &alpha, const Matrix< T > &A, bool acyclic)
PH / APH given by (alpha, A): D0 = A and D1 = (-A e) alpha.
static Distrib mapt(const std::vector< T > &breakpoints, const std::vector< Matrix< T > > &D0segs, const std::vector< Matrix< T > > &D1segs, bool cyclic)
MAPt(breakpoints, {D0_k}, {D1_k}, cyclic): a piecewise-constant (D0(t), D1(t)).
static Distrib weibull(const T &scale, const T &shape)
static Distrib bmap(const std::vector< Matrix< T > > &D)
BMAP: the batch-size blocks D0, D1, ..., Dk, where Dj carries an arrival of batch size j.
static Distrib mass_at_origin(const Distrib &in, const T &p0)
MassAtOrigin(inner, p0): zero with probability p0, else inner.
static Distrib mmap(const Matrix< T > &D0, const std::vector< Matrix< T > > &D1k)
MMAP: D0 plus one D1 block per mark.
static Distrib disabled_dist()
static Distrib pht(const std::vector< T > &breakpoints, const std::vector< std::vector< T > > &alphas, const std::vector< Matrix< T > > &Ssegs, bool cyclic)
PHt(breakpoints, {alpha_k}, {S_k}, cyclic), stored as its equivalent MAP schedule: D0 = S and D1 = (-...
static Distrib erlang_fit(const T &m, const T &c2)
Erlang fitted to a mean and an SCV, as MATLAB's Erlang.fitMeanAndSCV.
static Distrib pareto(const T &shape, const T &scale)
Pareto(shape, scale), with the MATLAB parameter order (alpha, k).
static Distrib gamma_dist(const T &shape, const T &scale)
Gamma(shape, scale), Weibull(scale, shape) and Lognormal(mu, sigma).
static Distrib cox2(const T &mu1, const T &mu2, const T &phi1)
Cox2(mu1, mu2, phi1), MATLAB's two-phase Coxian constructor.
static Distrib map_dist(const Matrix< T > &D0, const Matrix< T > &D1, ProcessType tag)
A MAP given by its two matrices; the moments are those of its stationary phase.
static Distrib poisson(const T &lambda)
Poisson(lambda), whose SCV is 1/lambda – the count's variance is lambda and its mean is lambda,...
static Distrib bernoulli(const T &p)
Bernoulli(p): one trial, mean p and variance p(1-p).
static Distrib hyperexp_n(const std::vector< T > &p, const std::vector< T > &lambda)
The same for any number of branches, which is what MATLAB HyperExp accepts and what the writers emit ...
static Distrib discrete_uniform(const T &a, const T &b)
DiscreteUniform(a, b) over the integers a..b inclusive.
static Distrib geometric(const T &p)
Geometric(p) on the MATLAB convention: the NUMBER OF TRIALS to the first success, support {1,...
static Distrib det(const T &m)
static Distrib bmmapt(const std::vector< T > &breakpoints, const std::vector< Matrix< T > > &D0segs, const std::vector< std::vector< std::vector< Matrix< T > > > > &Dbatchsegs, bool cyclic)
BMMAPt(breakpoints, {D0_k}, {{{D^(c,b)_k}}}, cyclic): the BATCH marked schedule.
static Distrib rap(const Matrix< T > &H0, const Matrix< T > &H1)
RAP(H0, H1): a rational arrival process, whose moments are the MAP ones.
static Distrib uniform(const T &a, const T &b)
Uniform(a, b).
static Distrib nnpp_eptmp(const std::vector< double > &alpha, const std::vector< double > &gamma, const std::vector< double > &omega, const std::vector< double > &phi, double horizon, double dispersion=1.0, bool cyclic=true, int Q=200)
NNPP.eptmp(alpha, gamma, omega, phi, horizon, dispersion, cyclic, Q): lambda(t) = exp(sum alpha_i t^i...
static Distrib lognormal(const T &logmean, const T &logsigma)
static Distrib hyperexp(const T &p, const T &lambda1, const T &lambda2)
HyperExp(p, lambda1, lambda2): phase i chosen with probability p_i.
static Distrib me(const std::vector< T > &alpha, const Matrix< T > &A)
ME(alpha, A): the matrix-exponential distribution, whose moments are the phase-type ones – k!
static Distrib immediate()
The point mass at zero.
static Distrib erlang(const T &phase_rate, std::size_t r)
Erlang(alpha, r): r phases of rate alpha, as MATLAB's Erlang(phaseRate, nphases).
static Distrib exp_mean(const T &m)
static Distrib mpht(const std::vector< T > &breakpoints, const std::vector< std::vector< T > > &alphas, const std::vector< Matrix< T > > &Ssegs, const std::vector< std::vector< std::vector< T > > > &exits, bool cyclic)
MPHt(breakpoints, {alpha_k}, {S_k}, {{s^(c)_k}}, cyclic), stored LOWERED to MMAPt form segment by seg...
static Distrib coxian(const std::vector< T > &mu, const std::vector< T > &phi)
Coxian(mu, phi): phase i completes with probability phi(i) and otherwise moves to phase i+1.
static Distrib discrete_sampler(const std::vector< T > &p, const std::vector< T > &x)
DiscreteSampler(p, x): the pmf p over the points x.
static Distrib binomial(const T &n, const T &p)
Binomial(n, p).
static Distrib zipf(const T &s, std::size_t n)
Zipf(s, n) over the ranks 1..n, with the generalized harmonic moments H(s-1,n)/H(s,...
The popularity LAW each class declared, beside the pmf it expands to.
The parameters of a Cache node, MATLAB's sn.nodeparam{ind} for a Cache.
int retrieval_capacity
Delayed-hit retrieval system (Cache.setRetrievalSystem).
T qlru
q-LRU admission probability; 1 admits every miss (plain LRU).
std::vector< Popularity > preadkind
per class, parallel to pread
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
A Logger node's trace configuration, MATLAB's Logger properties and sn.nodeparam{ind}...
std::string file_path
directory, MATLAB's model.getLogPath
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 fluid arc of a mode: node is the 1-based fluid place, value a rate or an impulse.
A fluid rate dependence: the firing rate is multiplied by fun(level(node)).
std::function< double(double)> fun
A marking-dependent fluid flow (setFluidFlowDependence): the flow of the mode on fluid place node is ...
std::function< double(const std::vector< double > &)> fun
A fluid guard: the mode is enabled only while level(node) >= thr (sgn = +1) or <= thr (sgn = -1).
The parameters of a Transition node: MATLAB sn.nodeparam{ind} for an SPN transition,...
std::vector< std::vector< FluidDep > > fluiddep
std::vector< double > firingprio
firing priority per mode
std::vector< std::vector< FluidGuard > > fluidguard
std::vector< std::vector< FluidFlowDep > > fluidflowdep
std::vector< lang::TimingStrategy > timing
immediate or timed
std::vector< std::string > modenames
std::vector< std::vector< FluidArc > > fluidimpulse
std::vector< lang::Distrib< T > > firingproc
firing distribution per mode
std::vector< double > nmodeservers
servers per mode, may be infinite
std::vector< T > fireweight
weight among simultaneously enabled modes
std::vector< Matrix< T > > firing
firing[m](p,r): class-r tokens mode m moves to/from place p when it fires.
std::vector< Matrix< T > > enabling
enabling[m](p,r): class-r tokens of place p (0-based node) mode m needs.
std::vector< std::function< T(const std::vector< T > &)> > firingdep
Marking-dependent firing-rate multiplier g_m(marking); an empty entry is the unit multiplier.
std::vector< Matrix< T > > inhibiting
inhibiting[m](p,r): class-r tokens of p that BLOCK mode m (Inf = never).
std::vector< std::vector< FluidArc > > fluidrate
FSPN arcs per mode, MATLAB sn.transparam{ind}.fluidrate/fluidguard/fluidimpulse/fluiddep.
std::vector< std::size_t > firingphases
phase count per mode, 0 when non-Markovian