LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_mam.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_LANG_LAL_SOLVER_MAM_H
6#define LINE_LANG_LAL_SOLVER_MAM_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * LINE Agent Language (LAL): the SolverMAM binding of a `Composition`
12 * (the `_lal_composition` branches of
13 * python/line_solver/solvers/solver_mam/__init__.py).
14 *
15 * The solver selects one of the LAL lowerings:
16 *
17 * - `finiteqbd` (mam_qbd.h), `reachableqbd` (mam_reachable_qbd.h) and the
18 * traffic-reduced finite QBD (mam_reduced.h) for a finite composition;
19 * - `infiniteqbd` (mam_infinite_qbd.h) for one unbounded queue;
20 * - `jackson` (mam_jackson.h), `parallelqbd` (mam_parallel_qbd.h),
21 * `dec.source` (mam_map_network.h) and `marked.thinning`
22 * (mam_marked_network.h) for several unbounded queues,
23 *
24 * with the same dispatch order, fallbacks and refusal messages as Python.
25 * Dictionaries Python returns (`getCompositionCapabilities`,
26 * `getMAMDiagnostics`, the traffic dictionary inside them) are
27 * `nlohmann::json` objects, whose keys are sorted rather than kept in
28 * insertion order.
29 */
30
31#include <cmath>
32#include <functional>
33#include <limits>
34#include <map>
35#include <memory>
36#include <optional>
37#include <set>
38#include <sstream>
39#include <string>
40#include <utility>
41#include <vector>
42
43#include "json.hpp"
45#include "line/lang/lal/core.h"
46#include "line/lang/lal/ctmc.h"
58
59namespace line {
60namespace lal {
61
62/** Exact marginal QBDs of independent stations sharing marked sources (mam_parallel_qbd.h). */
63inline MamResult parallel_qbd(const Composition& model, double max_phases = 64, double max_states = 50000,
64 long max_iter = 100, double tol = 1e-4);
65
66/**
67 * The options of SolverMAM on a LAL composition (`SolverMAMOptions`).
68 *
69 * `lal_max_phases` and `lal_max_states` are held as doubles so that a
70 * non-integral value reaches `supportsModelMethod`, which refuses it as
71 * Python refuses a non-`int`. `config`, `arith`, `timespan` and `cutoff`
72 * exist only to be refused by `runAnalyzer`, as in Python.
73 */
74struct MAMOptions {
75 std::string method = "default";
76 double tol = 1e-4;
77 long max_iter = 100;
78 long space_max = 1000;
79 nlohmann::json config = nlohmann::json::object();
80 bool verbose = false;
81 double timeout = std::numeric_limits<double>::infinity();
82 std::string lang = "python";
83 std::optional<std::string> arith;
84 std::optional<nlohmann::json> timespan; ///< refused when set
85 std::optional<nlohmann::json> cutoff; ///< refused when set
86 double lal_max_phases = 64;
87 double lal_max_states = 50000;
88 std::optional<std::string> lal_level_agent;
89 std::string lal_traffic_method = "auto";
90 std::string lal_compress_method = "exponential";
91 double lal_fit_time = 1.0;
92 double lal_fit_tolerance = 0.05;
93
94 /** The cache key (Python `repr(self.options)`). */
95 std::string key() const {
96 std::ostringstream os;
97 os << method << '|' << detail::repr_double(tol) << '|' << max_iter << '|' << space_max << '|' << config.dump()
98 << '|' << verbose << '|' << detail::repr_double(timeout) << '|' << lang << '|' << (arith ? *arith : "None")
99 << '|' << (timespan ? timespan->dump() : "None") << '|' << (cutoff ? cutoff->dump() : "None") << '|'
100 << detail::repr_double(lal_max_phases) << '|' << detail::repr_double(lal_max_states) << '|'
101 << (lal_level_agent ? *lal_level_agent : "None") << '|' << lal_traffic_method << '|' << lal_compress_method
102 << '|' << detail::repr_double(lal_fit_time) << '|' << detail::repr_double(lal_fit_tolerance);
103 return os.str();
104 }
105
106 /**
107 * Options from Python-style keyword arguments (`SolverMAM(model, **kwargs)`).
108 * A name that is not a SolverMAMOptions field, `timespan` and `cutoff`
109 * included, is refused with `LINE:unsupported:Option`, as Python refuses
110 * it at construction on a LAL composition.
111 */
112 static MAMOptions from_kwargs(const nlohmann::json& kwargs, const std::string& method = "default") {
113 static const std::set<std::string> fields{
114 "method", "tol", "max_iter", "space_max", "config", "verbose", "timeout", "lang", "arith",
115 "lal_max_phases", "lal_max_states", "lal_level_agent", "lal_traffic_method", "lal_compress_method",
116 "lal_fit_time", "lal_fit_tolerance"};
117 if (!kwargs.is_null() && !kwargs.is_object()) throw InputError("SolverMAM keyword arguments must be an object");
118 std::set<std::string> unknown;
119 if (kwargs.is_object())
120 for (auto it = kwargs.begin(); it != kwargs.end(); ++it)
121 if (!fields.count(it.key())) unknown.insert(it.key());
122 if (!unknown.empty()) {
123 std::string joined;
124 for (const std::string& u : unknown) joined += (joined.empty() ? "" : ", ") + u;
125 throw UnsupportedError(ErrorKind("Option"), "Unsupported LAL MAM option(s): " + joined);
126 }
127 MAMOptions o;
128 o.method = method;
129 if (!kwargs.is_object()) return o;
130 auto opt_str = [&](const char* k) -> std::optional<std::string> {
131 const nlohmann::json& v = kwargs.at(k);
132 if (v.is_null()) return std::nullopt;
133 return v.get<std::string>();
134 };
135 for (auto it = kwargs.begin(); it != kwargs.end(); ++it) {
136 const std::string& k = it.key();
137 const nlohmann::json& v = it.value();
138 if (k == "method") continue; // Python keeps the positional method
139 if (k == "tol") o.tol = v.get<double>();
140 else if (k == "max_iter") o.max_iter = v.get<long>();
141 else if (k == "space_max") o.space_max = v.get<long>();
142 else if (k == "config") o.config = v;
143 else if (k == "verbose") o.verbose = v.get<bool>();
144 else if (k == "timeout") o.timeout = v.get<double>();
145 else if (k == "lang") o.lang = v.get<std::string>();
146 else if (k == "arith") o.arith = opt_str("arith");
147 else if (k == "lal_max_phases") o.lal_max_phases = v.is_boolean() ? -1.0 : v.get<double>();
148 else if (k == "lal_max_states") o.lal_max_states = v.is_boolean() ? -1.0 : v.get<double>();
149 else if (k == "lal_level_agent") o.lal_level_agent = opt_str("lal_level_agent");
150 else if (k == "lal_traffic_method") o.lal_traffic_method = v.get<std::string>();
151 else if (k == "lal_compress_method") o.lal_compress_method = v.get<std::string>();
152 else if (k == "lal_fit_time") o.lal_fit_time = v.get<double>();
153 else if (k == "lal_fit_tolerance") o.lal_fit_tolerance = v.get<double>();
154 }
155 return o;
156 }
157};
158
159namespace detail {
160
161inline nlohmann::json num_json(double x) {
162 if (std::isfinite(x) && x == std::floor(x) && std::fabs(x) < 9e15) return static_cast<long long>(x);
163 return x;
164}
165
166/** Python's `f'{n}'` of an exact integer count held as a double. */
167inline std::string int_str(double x) {
168 if (std::isfinite(x) && std::fabs(x) < 9e18) return std::to_string(static_cast<long long>(x));
169 char buf[400];
170 std::snprintf(buf, sizeof(buf), "%.0f", x);
171 return buf;
172}
173
174inline nlohmann::json opt_json(const std::optional<std::string>& s) {
175 return s ? nlohmann::json(*s) : nlohmann::json(nullptr);
176}
177
178inline nlohmann::json opt_marked_json(const std::optional<MarkedMatrices>& m) {
179 return m ? matrices_json(*m) : nlohmann::json(nullptr);
180}
181
182/** The traffic dictionary of a result as a json object (Python `result.traffic`). */
183inline nlohmann::json traffic_json(const Traffic& t) {
184 nlohmann::json j = t.extra.is_object() ? t.extra : nlohmann::json::object();
185 j["kind"] = t.kind;
186 j["method"] = t.method;
187 if (t.compression) j["compression"] = *t.compression;
188 j["exact"] = t.exact;
189 if (t.feasible) j["feasible"] = *t.feasible;
190 j["sources"] = t.sources;
191 j["marks"] = t.marks;
192 if (!t.targets.empty()) j["targets"] = t.targets;
193 if (!t.streams.empty()) {
194 nlohmann::json s = nlohmann::json::array();
195 for (const MarkedMatrices& m : t.streams) s.push_back(matrices_json(m));
196 j["streams"] = s;
197 }
198 j["matrices"] = opt_marked_json(t.matrices);
199 if (t.blocking) j["blocking"] = *t.blocking;
200 if (t.kind != "offered" || t.original_matrices || !t.original_streams.empty() || t.fitted_matrices) {
201 j["original_matrices"] = opt_marked_json(t.original_matrices);
202 nlohmann::json s = nlohmann::json::array();
203 for (const MarkedMatrices& m : t.original_streams) s.push_back(matrices_json(m));
204 j["original_streams"] = s;
205 j["fitted_matrices"] = opt_marked_json(t.fitted_matrices);
206 }
207 if (t.fit_time) j["fit_time"] = *t.fit_time;
208 if (t.fit_tolerance) j["fit_tolerance"] = *t.fit_tolerance;
209 if (!t.original_rates.empty()) j["original_rates"] = t.original_rates;
210 if (!t.fitted_rates.empty()) j["fitted_rates"] = t.fitted_rates;
211 if (t.original_count_covariance) j["original_count_covariance"] = matrix_json(*t.original_count_covariance);
212 if (t.fitted_count_covariance) j["fitted_count_covariance"] = matrix_json(*t.fitted_count_covariance);
213 if (t.rate_error) j["rate_error"] = *t.rate_error;
214 if (t.count_covariance_error) j["count_covariance_error"] = *t.count_covariance_error;
215 if (t.unavailable) j["unavailable"] = *t.unavailable;
216 if (t.fallback_reason) j["fallback_reason"] = *t.fallback_reason;
217 return j;
218}
219
220inline bool positive_integer(double x) { return std::isfinite(x) && x > 0 && x == std::floor(x); }
221
222inline bool in_list(const std::string& x, std::initializer_list<const char*> list) {
223 for (const char* s : list)
224 if (x == s) return true;
225 return false;
226}
227
228} // namespace detail
229
230/** SolverMAM on a LAL composition. */
232 public:
233 typedef std::pair<bool, std::string> Support;
234 /// The Cartesian finite-QBD backend (Python's module-level
235 /// `lal_qbd.solve_composition`); replaceable so a test can intercept it.
236 typedef std::function<MamResult(const Composition&, double, double, const std::optional<std::string>&)>
238
240 : options(std::move(options)), model_(&model), original_(&model) {
241 init_lowering_();
242 }
243 /** `SolverMAM(model, method, **kwargs)` with keyword arguments as a json object. */
244 SolverMAM(const Composition& model, const std::string& method, const nlohmann::json& kwargs = nlohmann::json::object())
245 : options(MAMOptions::from_kwargs(kwargs, method)), model_(&model), original_(&model) {
246 init_lowering_();
247 }
249 SolverMAM(const Composition&&, const std::string&, const nlohmann::json& = nlohmann::json::object()) = delete;
250
252
253 static MAMOptions defaultOptions() { return MAMOptions(); }
254 std::string getName() const { return "MAM"; }
255
256 /** Methods available for a LAL Composition (MATLAB `SolverMAM.listLALMethods`). */
257 static std::vector<std::string> listLALMethods() {
258 return {"default", "finiteqbd", "reachableqbd", "infiniteqbd", "jackson", "dec.source", "parallelqbd", "marked.thinning"};
259 }
260
261 /** Clear the stored result (`reset`). */
262 void reset() {
263 result_.reset();
264 signature_.reset();
265 }
266
267 /** Whether a result is stored (Python `solver.result is not None`). */
268 bool hasResult() const { return result_.has_value(); }
269
270 /** Method-aware structural gate (`supportsModelMethod`); the reason is empty when supported. */
271 Support supportsModelMethod(const std::string& method) const {
272 if (lowering_reason_) return {false, *lowering_reason_};
273 const Model snapshot = model_->model();
274 const MAMOptions& o = options;
275 if (!detail::positive_integer(o.lal_max_phases) || !detail::positive_integer(o.lal_max_states))
276 return {false, "lal_max_phases and lal_max_states must be positive integers."};
277 const std::set<std::string> features = model_features(snapshot);
278 if (!features.empty() || has_discrete(snapshot))
279 return {false, "SolverMAM LAL methods recognize timed hand-declared agents only; the composition uses " +
280 (features.empty() ? std::string("discrete-time") : detail::join_sorted(features)) +
281 " actions."};
282 std::vector<std::size_t> unbounded;
283 for (std::size_t a = 0; a < snapshot.agents.size(); ++a)
284 if (snapshot.agents[a].unbounded_queue) unbounded.push_back(a);
285 const bool traffic_ok = detail::in_list(o.lal_traffic_method, {"auto", "exact", "compress", "interpos"});
286 const char* traffic_msg = "lal_traffic_method must be auto, exact, compress or interpos.";
287 if (!unbounded.empty()) {
288 if (unbounded.size() > 1 || method == "jackson") {
289 if (!detail::in_list(method, {"default", "jackson", "dec.source", "parallelqbd", "marked.thinning"}))
290 return {false, "Multiple unbounded queues require jackson, dec.source, parallelqbd or marked.thinning."};
291 if (o.lal_level_agent) return {false, "This network lowering does not select a single level agent."};
292 if (!traffic_ok) return {false, traffic_msg};
293 const auto jr = recognize_jackson(snapshot);
294 const std::string jackson_reason = jr.second;
295 if (!detail::in_list(method, {"dec.source", "parallelqbd", "marked.thinning"}) && jr.first) {
296 if (!detail::in_list(o.lal_traffic_method, {"auto", "exact"}))
297 return {false, "Jackson lowering does not use marked-traffic fitting."};
298 return {true, ""};
299 }
300 if (method == "jackson") return {false, jr.second};
301 const auto mr = recognize_map(snapshot);
302 const std::string map_reason = mr.second;
303 if (method == "dec.source") return {mr.first.has_value(), mr.second};
304 const auto pr = recognize_parallel(snapshot);
305 std::string parallel_reason = pr.second;
306 if (method != "marked.thinning" && pr.first) {
307 if (detail::in_list(o.lal_traffic_method, {"auto", "exact"})) return {true, ""};
308 if (method == "parallelqbd") return {false, "Parallel QBD currently requires exact source phases."};
309 }
310 if (method == "parallelqbd") return {false, parallel_reason};
311 if (method != "marked.thinning" && mr.first) return {true, ""};
312 const auto sr = recognize_map(snapshot, true);
313 std::string reason = sr.second;
314 if (!sr.first && method == "default") {
315 // Each recognizer was tried in turn: report why each refused,
316 // not only the last one consulted.
317 if (pr.first) parallel_reason = "Parallel QBD currently requires exact source phases.";
318 reason = "No LAL network lowering applies. jackson: " + jackson_reason + " dec.source: " + map_reason +
319 " parallelqbd: " + parallel_reason + " marked.thinning: " + reason;
320 }
321 return {sr.first.has_value(), reason};
322 }
323 if (o.lal_level_agent && *o.lal_level_agent != snapshot.agents[unbounded[0]].name)
324 return {false, "Infinite QBD requires the unbounded queue as its selected level."};
325 if (method != "default" && method != "infiniteqbd")
326 return {false, "Unbounded LAL queues support the infiniteqbd MAM method."};
327 if (!traffic_ok) return {false, traffic_msg};
328 return {true, ""};
329 }
330 if (!detail::in_list(method, {"default", "finiteqbd", "reachableqbd"}))
331 return {false, "Finite LAL compositions support the finiteqbd and reachableqbd MAM methods."};
332 if (method == "reachableqbd" && !detail::in_list(o.lal_traffic_method, {"auto", "exact"}))
333 return {false, "reachableqbd does not use traffic reduction."};
334 if (!traffic_ok) return {false, traffic_msg};
335 const bool limited = o.lal_traffic_method == "exact" && method != "reachableqbd";
336 const auto st = qbd_structure(snapshot, limited ? o.lal_max_phases : kMamNoLimit,
337 limited ? o.lal_max_states : kMamNoLimit, o.lal_level_agent);
338 return {st.first.has_value(), st.second};
339 }
340
341 /** Run the selected lowering and store the result (`runAnalyzer`). */
343 const MAMOptions& o = options;
344 if (o.lang != "python") throw UnsupportedError(ErrorKind("Language"), "LAL MAM requires lang=\"python\".");
345 const Support ok = supportsModelMethod(o.method);
346 if (!ok.first) throw UnsupportedError(ErrorKind("Method"), ok.second);
347 if (!o.config.empty() || o.arith || o.timespan || o.cutoff)
348 throw UnsupportedError(ErrorKind("Option"), "Finite QBD does not support config, arith, timespan or cutoff options.");
349 if (o.timeout != std::numeric_limits<double>::infinity())
350 throw UnsupportedError(ErrorKind("Option"), "LAL MAM does not implement a timeout option.");
351 if (!std::isfinite(o.tol) || o.tol <= 0 || o.max_iter <= 0)
352 throw InputError("LAL MAM tol and max_iter must be finite and positive");
353 const Model snapshot = model_->model();
354 const std::string signature = key_();
355 std::vector<std::size_t> unbounded;
356 for (std::size_t a = 0; a < snapshot.agents.size(); ++a)
357 if (snapshot.agents[a].unbounded_queue) unbounded.push_back(a);
358 const bool has_unbounded = !unbounded.empty();
359 std::string traffic_method = o.lal_traffic_method;
360 std::optional<std::string> fallback_reason;
361 std::optional<MamResult> reachable_result;
362 const bool use_network = unbounded.size() > 1 ||
363 detail::in_list(o.method, {"jackson", "dec.source", "parallelqbd", "marked.thinning"});
364 bool jackson_match = false, map_match = false, parallel_match = false;
365 if (use_network) {
366 jackson_match = recognize_jackson(snapshot).first.has_value();
367 map_match = recognize_map(snapshot).first.has_value();
368 parallel_match = recognize_parallel(snapshot).first.has_value();
369 }
370 auto network_fallback = [&](bool map) {
371 return map ? map_network(*model_, o.tol, o.max_iter, o.lal_max_phases, o.lal_traffic_method,
372 o.lal_compress_method, o.lal_fit_time, o.lal_fit_tolerance, native_backend_)
374 o.lal_compress_method, o.lal_fit_time, o.lal_fit_tolerance, native_backend_);
375 };
376 auto level_of = [&]() -> std::string {
377 if (has_unbounded) return snapshot.agents[unbounded[0]].name;
378 const auto st = qbd_structure(snapshot, kMamNoLimit, kMamNoLimit, o.lal_level_agent);
379 if (!st.first) throw detail::mam_refusal("Model", st.second);
380 return *st.first;
381 };
382 if (use_network && (o.method == "jackson" || (o.method == "default" && jackson_match))) {
383 reachable_result = jackson(*model_, o.lal_max_states);
384 } else if (use_network && (o.method == "parallelqbd" ||
385 (o.method == "default" && parallel_match &&
386 detail::in_list(o.lal_traffic_method, {"auto", "exact"})))) {
387 try {
388 reachable_result = parallel_qbd(*model_, o.lal_max_phases, o.lal_max_states, o.max_iter, o.tol);
389 } catch (const UnsupportedError& exc) {
390 if (o.method != "default" || exc.id() != "LINE:unsupported:StateSpace") throw;
391 if (!recognize_map(snapshot, true).first) throw;
392 fallback_reason = std::string("Exact parallel QBD exceeded a resource limit: ") + exc.what();
393 reachable_result = network_fallback(map_match);
394 }
395 } else if (use_network && (o.method == "marked.thinning" || (o.method == "default" && !map_match))) {
396 reachable_result = network_fallback(false);
397 } else if (use_network) {
398 reachable_result = network_fallback(true);
399 } else if (!has_unbounded && o.method == "reachableqbd") {
400 reachable_result = reachable_qbd(*model_, o.lal_max_phases, o.lal_max_states, o.lal_level_agent);
401 } else if (traffic_method == "auto") {
402 const std::string level = level_of();
403 double phase_count = 1.0;
404 for (const AgentRecord& a : snapshot.agents)
405 if (a.name != level) phase_count *= static_cast<double>(a.states.size());
406 const double boundary = phase_count * static_cast<double>(snapshot.agent(level).states.size());
407 if (phase_count > o.lal_max_phases || boundary > o.lal_max_states) {
408 fallback_reason = "Exact QBD requires " + detail::int_str(phase_count) + " phases and " +
409 detail::int_str(boundary) + " boundary states, exceeding configured limits.";
410 if (!has_unbounded) {
411 try {
412 reachable_result = reachable_qbd(*model_, o.lal_max_phases, o.lal_max_states, o.lal_level_agent);
413 } catch (const UnsupportedError& exc) {
414 if (exc.id() != "LINE:unsupported:StateSpace") throw;
415 }
416 }
417 if (!reachable_result) traffic_method = snapshot.agents.size() > 2 ? "interpos" : "compress";
418 } else {
419 traffic_method = "exact";
420 }
421 }
422 MamResult result;
423 if (reachable_result) {
424 result = std::move(*reachable_result);
425 } else if (has_unbounded && traffic_method == "exact") {
426 result = infinite_qbd(*model_, o.lal_max_phases, o.lal_max_states, o.lal_level_agent, o.max_iter, o.tol);
427 } else if (traffic_method == "exact") {
428 try {
429 result = finite_backend_(*model_, o.lal_max_phases, o.lal_max_states, o.lal_level_agent);
430 } catch (const UnsupportedError& exc) {
431 const std::string msg = exc.what();
432 if (o.method != "default" ||
433 (msg.find("unique closed class") == std::string::npos && exc.id() != "LINE:unsupported:Numerical"))
434 throw;
436 fallback_reason = "Cartesian QBD could not be used (" + msg + "); restricted to initial reachability.";
437 }
438 } else {
439 result = solve_reduced(*model_, level_of(), traffic_method, o.lal_compress_method, o.lal_fit_time,
441 }
442 if (!fallback_reason) fallback_reason = result.fallback_reason;
443 result.fallback_reason = fallback_reason;
444 if (fallback_reason) {
445 if (result.traffic) result.traffic->fallback_reason = fallback_reason;
446 result.state_table.attrs.fallback_reason = fallback_reason;
447 result.action_table.attrs.fallback_reason = fallback_reason;
448 if (result.queue_measures) result.queue_measures->attrs.fallback_reason = fallback_reason;
449 }
450 if (lowered_) {
451 // some recognizers name rows agent.action; a lowered model reads
452 // them as LINE node events (Q.DEP[Jobs]); getQueueTable keeps the
453 // per-route rows it needs in raw_action_table
454 result.raw_action_table = result.action_table;
455 result.action_table = relabel_action_table(result.action_table, lowered_labels_);
456 }
457 if (signature != key_()) {
458 result_.reset();
459 signature_.reset();
460 throw UnsupportedError(ErrorKind("Model"),
461 "The LAL model or solver options changed during MAM analysis; retry with a stable snapshot.");
462 }
463 result_ = std::move(result);
464 signature_ = signature;
465 return *this;
466 }
467
468 /** Agent-state probabilities (`getAvgTable`). */
469 StateTable getAvgTable() { return ensure_().state_table; }
470
471 /** Labelled event throughputs (`getActTable` and its aliases). */
472 ActionTable getActTable() { return ensure_().action_table; }
477 /**
478 * `getAvgTard()`, inherited by the reference from NetworkSolver: mean class
479 * tardiness against the JobClass deadlines, as {Tard, SysTard}. It solves
480 * first when no result is held (`getAvgTard.m` calls `getAvg`) and returns
481 * what the result carries. A composition declares no JobClass and no
482 * deadline, so no LAL result carries a tardiness and both matrices are
483 * empty, as the reference returns `[]` for them.
484 */
485 std::vector<Matrix<double>> getAvgTard() {
486 ensure_();
487 return {Matrix<double>(), Matrix<double>()};
488 }
489 std::vector<Matrix<double>> get_avg_tard() { return getAvgTard(); }
492
493 /** Throughput of one LAL action (named as in SolverCTMC::getAvgAct, against the original composition). */
494 double getAvgAct(const ActionSpec& action) { return act_value(*original_, getActTable(), action); }
495 double getAvgAct(const std::string& node, lang::EventType event,
496 const std::optional<std::string>& jobclass = std::nullopt,
497 const std::optional<std::string>& mode = std::nullopt) {
498 return getAvgAct(ActionSpec::key(node, event, jobclass, mode));
499 }
500 double getAvgAct(std::size_t node, lang::EventType event, std::size_t jobclass = 0) {
501 return getAvgAct(ActionSpec::key(node, event, jobclass));
502 }
503 /** Throughputs of several actions, each named as in `getAvgAct`. */
504 std::vector<double> getActAvg(const std::vector<ActionSpec>& actions) {
505 std::vector<double> out;
506 for (const ActionSpec& a : actions) out.push_back(getAvgAct(a));
507 return out;
508 }
509
510 /** The composition the solver analyzes: the lowered one when an embedded network was lowered. */
511 const Composition& model() const { return *model_; }
512
513 /** Queue measures of unchanged structured queue declarations (`getQueueTable`). */
515 const MamResult& r = ensure_();
516 if (r.queue_measures) return *r.queue_measures;
517 const Model snapshot = model_->model();
518 std::map<Endpoint, std::string> events;
519 for (const Sync& s : snapshot.syncs) {
520 const std::string label = endpoint_label(s.active);
521 for (const Endpoint& e : s.passive) events[e] = label;
522 }
523 for (const MinSync& s : snapshot.min_syncs) {
524 const std::string label = endpoint_label(s.active[0]);
525 for (const Endpoint& e : s.active) events[e] = label;
526 for (const Endpoint& e : s.passive) events[e] = label;
527 }
528 QueueTable table;
529 for (const AgentRecord& agent : snapshot.agents) {
530 if (!agent.queue_info) continue;
531 const QueueInfo& info = *agent.queue_info;
532 double busy = 0.0, occupancy = 0.0, busy_servers = 0.0;
533 for (const StateRow& row : r.state_table.rows) {
534 if (row.agent != agent.name) continue;
535 const bool tail = row.state.compare(0, 5, "n_ge_") == 0;
536 const long n = std::stol(tail ? row.state.substr(5) : row.state.substr(2));
537 if (!tail) occupancy += static_cast<double>(n) * row.probability;
538 if (n) busy += row.probability;
539 busy_servers += static_cast<double>(std::min(n, info.servers)) * row.probability;
540 }
541 if (agent.unbounded_queue) {
542 if (!r.queue_means.empty()) occupancy = r.queue_means.at(agent.name);
543 else occupancy = r.mean_level ? *r.mean_level : std::numeric_limits<double>::quiet_NaN();
544 }
545 std::vector<std::string> arrivals, departures;
546 for (const std::string& a : info.arrivals) {
547 auto it = events.find(Endpoint(agent.name, a));
548 if (it != events.end()) arrivals.push_back(it->second);
549 }
550 for (const std::string& a : info.departures) {
551 auto it = events.find(Endpoint(agent.name, a));
552 departures.push_back(it != events.end() ? it->second : agent.name + "." + a);
553 }
554 for (const std::string& a : info.service_inputs) {
555 auto it = events.find(Endpoint(agent.name, a));
556 if (it != events.end()) departures.push_back(it->second);
557 }
558 // Every queue input/output appears at most once in a sync; retain
559 // unique labels if a multiparty event supplies several endpoints.
560 const ActionTable& action_values = r.raw_action_table ? *r.raw_action_table : r.action_table;
561 auto throughput = [&](const std::vector<std::string>& labels) {
562 std::set<std::string> seen;
563 double total = 0.0;
564 for (const std::string& l : labels)
565 if (seen.insert(l).second) total += action_values.throughput(l);
566 return total;
567 };
568 const double arrival_rate = throughput(arrivals), departure_rate = throughput(departures);
569 QueueRow q;
570 q.agent = agent.name;
571 q.qlen = occupancy;
572 q.busy = busy;
573 q.util = busy_servers / static_cast<double>(info.servers);
574 q.arvr = arrival_rate;
575 q.tput = departure_rate;
576 q.respt = departure_rate > 0 ? occupancy / departure_rate : std::numeric_limits<double>::quiet_NaN();
577 table.rows.push_back(q);
578 }
579 table.attrs.method = r.method;
580 table.attrs.exact = r.exact;
581 table.attrs.truncated = r.truncated;
582 return table;
583 }
585
586 /** The binding described before solving, with runtime conditions (`getCompositionCapabilities`). */
587 nlohmann::json getCompositionCapabilities() const {
588 const MAMOptions& o = options;
589 const Support ok = supportsModelMethod(o.method);
590 const std::string& traffic_method = o.lal_traffic_method;
591 const Model snapshot = model_->model();
592 std::size_t unbounded_count = 0;
593 for (const AgentRecord& a : snapshot.agents)
594 if (a.unbounded_queue) ++unbounded_count;
595 const bool has_unbounded = unbounded_count > 0;
596 bool jackson_sel = false, map_sel = false, parallel_sel = false, marked_sel = false;
597 if (unbounded_count > 1 || detail::in_list(o.method, {"jackson", "dec.source", "parallelqbd", "marked.thinning"})) {
598 jackson_sel = !detail::in_list(o.method, {"dec.source", "parallelqbd", "marked.thinning"}) &&
599 recognize_jackson(snapshot).first.has_value();
600 if (!jackson_sel) {
601 parallel_sel = !detail::in_list(o.method, {"dec.source", "marked.thinning"}) &&
602 detail::in_list(traffic_method, {"auto", "exact"}) &&
603 recognize_parallel(snapshot).first.has_value();
604 if (!parallel_sel) {
605 map_sel = !detail::in_list(o.method, {"parallelqbd", "marked.thinning"}) &&
606 recognize_map(snapshot).first.has_value();
607 marked_sel = !map_sel;
608 }
609 }
610 }
611 nlohmann::json c = nlohmann::json::object();
612 c["solver"] = "MAM";
613 c["requested_method"] = o.method;
614 if (ok.first) {
615 c["selected_method"] = jackson_sel ? "jackson"
616 : map_sel ? "dec.source"
617 : parallel_sel ? "parallelqbd"
618 : marked_sel ? "marked.thinning"
619 : has_unbounded ? "infiniteqbd"
620 : (o.method == "reachableqbd" ? "reachableqbd" : "finiteqbd");
621 c["exactness"] = (map_sel || marked_sel) ? "approximate"
622 : detail::in_list(traffic_method, {"exact", "auto"}) ? "conditional"
623 : "approximate";
624 } else {
625 c["selected_method"] = nullptr;
626 c["exactness"] = nullptr;
627 }
628 c["supported"] = ok.first;
629 c["reason"] = ok.second;
630 std::vector<std::string> conditions{"Events change the selected level by at most one.",
631 "The block system is numerically solvable."};
632 if (marked_sel || jackson_sel || map_sel || parallel_sel)
633 conditions.push_back("Routing is open and every queue is stable.");
634 else if (has_unbounded)
635 conditions.push_back("The homogeneous phase process has one closed class and negative drift.");
636 else
637 conditions.push_back("The Cartesian method requires a unique closed class; reachableqbd handles multiple classes.");
638 c["conditions"] = conditions;
639 std::vector<std::string> transformations;
640 if (marked_sel) transformations = {"visit_thinning", "poisson_feedback_if_needed"};
641 else if (map_sel) transformations = {"native_queue_decomposition"};
642 if (traffic_method != "exact") transformations.push_back(traffic_method);
643 c["transformations"] = transformations;
644 c["limits"] = {{"phases", detail::num_json(o.lal_max_phases)}, {"states", detail::num_json(o.lal_max_states)}};
645 c["measures"] = {"agent-state probabilities", "labelled action throughputs",
646 "structured queue occupancy, utilization and throughput"};
647 const std::vector<std::string> fitted_unavailable{"original source phase probabilities if fitted",
648 "original source internal action throughputs if fitted"};
649 if (map_sel || marked_sel) c["unavailable"] = {"queue-state distributions", "convergence certificate"};
650 else if (parallel_sel) c["unavailable"] = {"joint queue-state distribution"};
651 else if (traffic_method == "exact") c["unavailable"] = nlohmann::json::array();
652 else c["unavailable"] = fitted_unavailable;
653 if (ok.first && result_ && signature_ && *signature_ == key_()) {
654 const MamResult& r = *result_;
655 c["selected_method"] = r.method;
656 c["exactness"] = r.exact ? "exact" : "approximate";
657 c["fallback_reason"] = detail::opt_json(r.fallback_reason);
658 if (r.method == "dec.source" || r.method == "marked.thinning") {
659 nlohmann::json u = {"queue-state distributions", "convergence certificate"};
660 for (const std::string& name : r.unavailable_clock_phases) u.push_back(name + " phase probabilities");
661 for (const std::string& name : r.unavailable_busy_probabilities) u.push_back(name + " busy probability");
662 c["unavailable"] = u;
663 } else if (r.method == "parallelqbd") {
664 c["unavailable"] = {"joint queue-state distribution"};
665 } else if (r.traffic && !r.traffic->exact) {
666 c["unavailable"] = fitted_unavailable;
667 } else {
668 c["unavailable"] = nlohmann::json::array();
669 }
670 if (r.method == "marked.thinning") c["transformations"] = {"visit_thinning", "poisson_feedback_if_needed"};
671 if (!r.phase_dependent_routing.empty()) c["transformations"].push_back("mean_service_routing_probabilities");
672 if (!r.correlated_service_reset.empty()) c["transformations"].push_back("independent_ph_service");
673 }
674 return c;
675 }
676 nlohmann::json get_composition_capabilities() const { return getCompositionCapabilities(); }
677
678 /**
679 * Diagnostics, optionally compared with the finite CTMC (`getMAMDiagnostics`).
680 * The comparison rows are json objects with the columns of Python's merged
681 * frames (`Agent, State, Probability_mam, Probability_ctmc, AbsoluteError`
682 * and `Action, Throughput_mam, Throughput_ctmc, AbsoluteError`); a NaN
683 * error is an unavailable MAM value.
684 */
685 nlohmann::json getMAMDiagnostics(bool compare_ctmc = false, std::size_t max_states = 1000) {
686 const MamResult& r = ensure_();
687 nlohmann::json d = nlohmann::json::object();
688 d["method"] = r.method;
689 d["exact"] = r.exact;
690 d["truncated"] = r.truncated;
691 d["residual"] = r.residual;
692 d["residual_kind"] = r.residual_kind ? *r.residual_kind : std::string("stationary_balance");
693 d["fallback_reason"] = detail::opt_json(r.fallback_reason);
694 d["traffic"] = r.traffic ? detail::traffic_json(*r.traffic) : nlohmann::json(nullptr);
695 d["approximation"] = detail::opt_json(r.approximation);
696 d["converged"] = nullptr; // no LAL MAM lowering exposes a convergence certificate
697 d["phase_dependent_routing"] = r.phase_dependent_routing;
698 d["correlated_service_reset"] = r.correlated_service_reset;
699 d["unavailable_clock_phases"] = r.unavailable_clock_phases;
700 d["unavailable_busy_probabilities"] = r.unavailable_busy_probabilities;
701 d["native_time_scale"] = r.native_time_scale ? nlohmann::json(*r.native_time_scale) : nlohmann::json(nullptr);
702 d["native_time_scales"] = r.native_time_scales;
703 d["poissonised_visit_excess"] = r.poissonised_visit_excess;
704 d["native_internal_fitting"] = r.native_internal_fitting;
705 if (compare_ctmc) {
706 const Model snapshot = model_->model();
707 for (const AgentRecord& a : snapshot.agents)
708 if (a.unbounded_queue)
709 throw UnsupportedError(ErrorKind("Model"), "CTMC comparison requires a finite composition.");
710 const Result reference = solve_composition(snapshot, max_states);
711 nlohmann::json states = nlohmann::json::array(), actions = nlohmann::json::array();
712 const double nan = std::numeric_limits<double>::quiet_NaN();
713 double max_state = nan, max_action = nan;
714 long compared_states = 0, missing_states = 0, compared_actions = 0, missing_actions = 0;
715 for (const StateRow& m : r.state_table.rows)
716 for (const StateRow& c : reference.state_table.rows) {
717 if (m.agent != c.agent || m.state != c.state) continue;
718 const double err = std::fabs(m.probability - c.probability);
719 states.push_back({{"Agent", m.agent}, {"State", m.state}, {"Probability_mam", m.probability},
720 {"Probability_ctmc", c.probability}, {"AbsoluteError", err}});
721 if (std::isnan(err)) ++missing_states;
722 else {
723 ++compared_states;
724 if (std::isnan(max_state) || err > max_state) max_state = err;
725 }
726 }
727 for (const ActionRow& m : r.action_table.rows)
728 for (const ActionRow& c : reference.action_table.rows) {
729 if (m.action != c.action) continue;
730 const double err = std::fabs(m.throughput - c.throughput);
731 actions.push_back({{"Action", m.action}, {"Throughput_mam", m.throughput},
732 {"Throughput_ctmc", c.throughput}, {"AbsoluteError", err}});
733 if (std::isnan(err)) ++missing_actions;
734 else {
735 ++compared_actions;
736 if (std::isnan(max_action) || err > max_action) max_action = err;
737 }
738 }
739 d["ctmc_comparison"] = {{"states", states},
740 {"actions", actions},
741 {"max_state_error", max_state},
742 {"max_action_error", max_action},
743 {"compared_state_rows", compared_states},
744 {"unavailable_state_rows", missing_states},
745 {"compared_action_rows", compared_actions},
746 {"unavailable_action_rows", missing_actions},
747 {"reference_states", reference.states.size()}};
748 }
749 return d;
750 }
751 nlohmann::json get_mam_diagnostics(bool compare_ctmc = false, std::size_t max_states = 1000) {
752 return getMAMDiagnostics(compare_ctmc, max_states);
753 }
754
755 /** Queueing-network averages are refused on a composition (`getAvg`). */
756 [[noreturn]] void getAvg() const {
757 throw UnsupportedError(ErrorKind("Metric"), "Use getAvgTable() and getActTable() for LAL composition results.");
758 }
759
760 /** The result container, solving first if needed (`getMAMResult`). */
761 const MamResult& getMAMResult() { return ensure_(); }
762
763 /** Replace the Cartesian finite-QBD backend (Python tests monkeypatch it). */
765 finite_backend_ = std::move(backend);
766 reset();
767 }
768
769 /**
770 * Replace the native `dec.source` solve behind the MAP-network and
771 * marked-thinning decompositions (Python tests monkeypatch
772 * `SolverMAM.getAvgTable`); an empty function restores the native solver.
773 */
775 native_backend_ = std::move(backend);
776 reset();
777 }
778
779 private:
780 const Composition* model_;
781 const Composition* original_;
782 std::shared_ptr<Composition> lowered_;
783 std::map<std::string, std::string> lowered_labels_;
784 std::optional<std::string> lowering_reason_;
785
786 /**
787 * Embedded LINE networks are lowered to the level and source agents the
788 * LAL methods recognize (mam_lowering.h); a network outside that structure
789 * is refused by supportsModelMethod.
790 */
791 void init_lowering_() {
792 if (original_->embedded().empty()) return;
793 try {
794 LoweredComposition lc = lower(*original_);
795 lowered_ = std::make_shared<Composition>(lc.composition);
796 lowered_labels_ = lc.labels;
797 model_ = lowered_.get();
798 } catch (const UnsupportedError& exc) {
799 lowering_reason_ = exc.what();
800 }
801 }
802
803 FiniteQBDBackend finite_backend_ = [](const Composition& m, double phases, double states,
804 const std::optional<std::string>& level) {
805 return finite_qbd(m, phases, states, level);
806 };
807 NativeDecSourceBackend native_backend_;
808 std::optional<MamResult> result_;
809 std::optional<std::string> signature_;
810
811 std::string key_() const {
812 return signature(model_->model()) + "|" + (model_->source_truncated ? "T" : "F") + "|" + options.key();
813 }
814
815 const MamResult& ensure_() {
816 if (!result_ || !signature_ || *signature_ != key_()) runAnalyzer();
817 return *result_;
818 }
819};
820
821} // namespace lal
822} // namespace line
823
825
826#endif // LINE_LANG_LAL_SOLVER_MAM_H
LINE Agent Language (LAL): programmatic construction of finite agents and their composition,...
const std::string & id() const noexcept
The full identifier, e.g.
Definition error.h:78
InputError(const std::string &what)
Definition error.h:105
A refusal: the feature, method or analysis is not covered: LINE:unsupported:<kind>.
Definition error.h:117
UnsupportedError(const std::string &what)
Definition error.h:119
A collection of agents and embedded LINE models with atomic synchronisations (Composition).
Definition builder.h:655
const std::vector< std::shared_ptr< EmbeddedPart > > & embedded() const
Definition builder.h:945
double getAvgAct(const std::string &node, lang::EventType event, const std::optional< std::string > &jobclass=std::nullopt, const std::optional< std::string > &mode=std::nullopt)
Definition solver_mam.h:495
ActionTable getActionTable()
Definition solver_mam.h:491
SolverMAM & runAnalyzer()
Run the selected lowering and store the result (runAnalyzer).
Definition solver_mam.h:342
double getAvgAct(std::size_t node, lang::EventType event, std::size_t jobclass=0)
Definition solver_mam.h:500
void setFiniteQBDBackend(FiniteQBDBackend backend)
Replace the Cartesian finite-QBD backend (Python tests monkeypatch it).
Definition solver_mam.h:764
ActionTable getActT()
Definition solver_mam.h:476
ActionTable getActTable()
Labelled event throughputs (getActTable and its aliases).
Definition solver_mam.h:472
double getAvgAct(const ActionSpec &action)
Throughput of one LAL action (named as in SolverCTMC::getAvgAct, against the original composition).
Definition solver_mam.h:494
SolverMAM(const Composition &model, MAMOptions options=MAMOptions())
Definition solver_mam.h:239
nlohmann::json getCompositionCapabilities() const
The binding described before solving, with runtime conditions (getCompositionCapabilities).
Definition solver_mam.h:587
void setNativeDecSourceBackend(NativeDecSourceBackend backend)
Replace the native dec.source solve behind the MAP-network and marked-thinning decompositions (Python...
Definition solver_mam.h:774
void reset()
Clear the stored result (reset).
Definition solver_mam.h:262
ActionTable GetActTable()
Definition solver_mam.h:475
SolverMAM(const Composition &&, MAMOptions=MAMOptions())=delete
static std::vector< std::string > listLALMethods()
Methods available for a LAL Composition (MATLAB SolverMAM.listLALMethods).
Definition solver_mam.h:257
static MAMOptions defaultOptions()
Definition solver_mam.h:253
ActionTable get_act_table()
Definition solver_mam.h:473
QueueTable get_queue_table()
Definition solver_mam.h:584
QueueTable getQueueTable()
Queue measures of unchanged structured queue declarations (getQueueTable).
Definition solver_mam.h:514
std::function< MamResult(const Composition &, double, double, const std::optional< std::string > &)> FiniteQBDBackend
The Cartesian finite-QBD backend (Python's module-level lal_qbd.solve_composition); replaceable so a ...
Definition solver_mam.h:237
bool hasResult() const
Whether a result is stored (Python solver.result is not None).
Definition solver_mam.h:268
std::string getName() const
Definition solver_mam.h:254
StateTable getAvgTable()
Agent-state probabilities (getAvgTable).
Definition solver_mam.h:469
ActionTable act_table()
Definition solver_mam.h:474
nlohmann::json getMAMDiagnostics(bool compare_ctmc=false, std::size_t max_states=1000)
Diagnostics, optionally compared with the finite CTMC (getMAMDiagnostics).
Definition solver_mam.h:685
std::vector< Matrix< double > > getAvgTard()
getAvgTard(), inherited by the reference from NetworkSolver: mean class tardiness against the JobClas...
Definition solver_mam.h:485
const Composition & model() const
The composition the solver analyzes: the lowered one when an embedded network was lowered.
Definition solver_mam.h:511
std::pair< bool, std::string > Support
Definition solver_mam.h:233
std::vector< Matrix< double > > get_avg_tard()
Definition solver_mam.h:489
ActionTable actT()
Definition solver_mam.h:490
nlohmann::json get_composition_capabilities() const
Definition solver_mam.h:676
Support supportsModelMethod(const std::string &method) const
Method-aware structural gate (supportsModelMethod); the reason is empty when supported.
Definition solver_mam.h:271
std::vector< double > getActAvg(const std::vector< ActionSpec > &actions)
Throughputs of several actions, each named as in getAvgAct.
Definition solver_mam.h:504
const MamResult & getMAMResult()
The result container, solving first if needed (getMAMResult).
Definition solver_mam.h:761
SolverMAM(const Composition &&, const std::string &, const nlohmann::json &=nlohmann::json::object())=delete
nlohmann::json get_mam_diagnostics(bool compare_ctmc=false, std::size_t max_states=1000)
Definition solver_mam.h:751
SolverMAM(const Composition &model, const std::string &method, const nlohmann::json &kwargs=nlohmann::json::object())
SolverMAM(model, method, **kwargs) with keyword arguments as a json object.
Definition solver_mam.h:244
void getAvg() const
Queueing-network averages are refused on a composition (getAvg).
Definition solver_mam.h:756
LINE Agent Language (LAL): the finite-agent model record, its validation, the joint-state event kerne...
LINE Agent Language (LAL): the result tables every LAL solver returns, the exact finite CTMC analysis...
LINE Agent Language (LAL): shared types and numerical helpers of the SolverMAM LAL paths (python/line...
LINE Agent Language (LAL): matrix-geometric analysis of one structured unbounded queue (solver_mam/la...
LINE Agent Language (LAL): lossless lowering of open exponential LAL networks to scalar M/M/c factors...
LINE Agent Language (LAL): lowering of embedded LINE networks to the agents SolverMAM's LAL methods r...
LINE Agent Language (LAL): lowering of a restricted open MAP/PH network to the native MAM dec....
LINE Agent Language (LAL): marked-source network decomposition with explicit visit thinning (solver_m...
LINE Agent Language (LAL): exact marginal QBDs for independent stations with shared marked sources (p...
LINE Agent Language (LAL): exact finite, level-dependent QBD analysis of a composition (solver_mam/la...
LINE Agent Language (LAL): QBD analysis restricted to the states reachable from the initial support (...
LINE Agent Language (LAL): the fitted-traffic QBD (lal_traffic.solve_reduced).
LINE Agent Language (LAL): independent marked arrival proposals of a finite composition and their exp...
Definition ag.h:49
std::string signature(const Model &m)
A deterministic text signature of a model snapshot (Python's repr(model)), used by the solvers to cac...
Definition core.h:472
std::pair< std::optional< MapMatch >, std::string > recognize_parallel(const Model &snapshot)
Recognise independent stations with shared marked sources (lal_parallel_qbd.recognize).
std::vector< Matrix< double > > MarkedMatrices
A marked process as Python's list [D0, D1, D1_1, ..., D1_K].
Definition mam_common.h:54
std::pair< std::string, std::string > Endpoint
(agent, action).
Definition core.h:139
MamResult jackson(const Composition &model, double max_states=50000)
Product-form solution of a recognised Jackson network (lal_jackson.solve_composition).
std::pair< std::optional< std::string >, std::string > qbd_structure(const Model &snapshot, double max_phases, double max_states, const std::optional< std::string > &level_name=std::nullopt)
The level agent of a finite QBD, or nullopt and the refusal reason (structure).
Definition mam_qbd.h:36
MamResult finite_qbd(const Composition &model, double max_phases=64, double max_states=50000, const std::optional< std::string > &level_name=std::nullopt)
Finite QBD solution of a composition (lal_qbd.solve_composition).
Definition mam_qbd.h:109
bool has_discrete(const Model &model)
True when any agent of the model is discrete-time.
Definition core.h:543
MamResult marked_thinning(const Composition &model, double tol=1e-4, long max_iter=100, double max_phases=64, const std::string &traffic_method="auto", const std::string &compress_method="exponential", double fit_time=1.0, double fit_tolerance=.05, const NativeDecSourceBackend &native_backend=NativeDecSourceBackend())
Visit-thinning decomposition of a recognised MAP network (lal_marked_network.solve_composition).
ActionTable relabel_action_table(const ActionTable &table, const std::map< std::string, std::string > &mapping)
Rename lowered action rows to their node-event labels, summing rows that share one (relabel_action_ta...
std::pair< std::optional< MapMatch >, std::string > recognize_map(const Model &snapshot, bool allow_split=false)
Recognise a restricted open MAP/PH network (lal_map_network.recognize).
std::pair< std::optional< JacksonMatch >, std::string > recognize_jackson(const Model &snapshot)
Conservatively recognise independent Poisson inputs and open M/M/c routing.
Definition mam_jackson.h:40
MamResult parallel_qbd(const Composition &model, double max_phases, double max_states, long max_iter, double tol)
Exact marginal QBDs of independent stations sharing marked sources (mam_parallel_qbd....
LoweredComposition lower(const Composition &composition)
A Composition of plain agents equivalent to composition, or itself (lower).
std::string endpoint_label(const Endpoint &e)
Definition core.h:141
MamResult infinite_qbd(const Composition &model, double max_phases=64, double max_states=50000, const std::optional< std::string > &level_name=std::nullopt, long max_iter=100, double tol=1e-4)
Infinite QBD solution of a composition (lal_infinite_qbd.solve_composition).
Result solve_composition(const Model &snapshot, std::size_t max_states=0, std::size_t max_dense_bytes=kDefaultMaxDenseBytes)
Solve a finite composition, respecting its initial state if reducible (solve_composition).
Definition ctmc.h:260
std::function< std::pair< std::vector< double >, std::vector< double > >(const Matrix< double > &, const Matrix< double > &, const NativeServices &, const std::vector< long > &, const Matrix< double > &, std::size_t, const std::string &, const std::string &, double, long, double)> NativeDecSourceBackend
The native dec.source solve behind map_network and marked_thinning (Python's SolverMAM(network,...
MamResult solve_reduced(const Composition &model, const std::string &level_name, const std::string &method, const std::string &compress_method, double fit_time, double fit_tolerance, double max_phases, double max_states, long max_iter=100, double tol=1e-4)
Fit the offered streams, then solve the reduced QBD (solve_reduced).
Definition mam_reduced.h:39
MamResult map_network(const Composition &model, double tol=1e-4, long max_iter=100, double max_phases=64, const std::string &traffic_method="auto", const std::string &compress_method="exponential", double fit_time=1.0, double fit_tolerance=.05, const NativeDecSourceBackend &native_backend=NativeDecSourceBackend())
Native MAM decomposition of a recognised MAP network (lal_map_network.solve_composition).
MamResult reachable_qbd(const Composition &model, double max_phases=64, double max_states=50000, const std::optional< std::string > &level_name=std::nullopt)
Reachable QBD solution of a composition (lal_reachable_qbd.solve_composition).
std::set< std::string > model_features(const Model &model)
Features of a model that only the extended kernel interprets (model_features).
Definition core.h:525
EventType
The events a state can undergo, with the values of MATLAB EventType.
Definition lang_types.h:116
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
ErrorKind(std::string n)
Definition error.h:39
One row of an action table: Action, Throughput.
Definition ctmc.h:62
std::vector< ActionRow > rows
Definition ctmc.h:80
double throughput(const std::string &action) const
Throughput of one action label; throws when absent.
Definition ctmc.h:84
TableAttrs attrs
Definition ctmc.h:81
The immutable agent record (core.Agent).
Definition core.h:284
std::string name
Definition core.h:285
std::vector< std::string > states
Definition core.h:286
std::optional< QueueInfo > queue_info
Definition core.h:292
A composition lowered for SolverMAM, with the map of lowered action labels to node-event labels.
std::map< std::string, std::string > labels
python _lal_labels
The options of SolverMAM on a LAL composition (SolverMAMOptions).
Definition solver_mam.h:74
static MAMOptions from_kwargs(const nlohmann::json &kwargs, const std::string &method="default")
Options from Python-style keyword arguments (SolverMAM(model, **kwargs)).
Definition solver_mam.h:112
std::optional< std::string > lal_level_agent
Definition solver_mam.h:88
std::optional< nlohmann::json > cutoff
refused when set
Definition solver_mam.h:85
std::string lal_traffic_method
Definition solver_mam.h:89
nlohmann::json config
Definition solver_mam.h:79
std::string lal_compress_method
Definition solver_mam.h:90
std::optional< std::string > arith
Definition solver_mam.h:83
std::string key() const
The cache key (Python repr(self.options)).
Definition solver_mam.h:95
std::optional< nlohmann::json > timespan
refused when set
Definition solver_mam.h:84
The union of Python's LAL MAM result dataclasses.
Definition mam_common.h:118
std::optional< std::string > approximation
Definition mam_common.h:137
std::map< std::string, double > queue_means
empty: Python has no queue_means
Definition mam_common.h:128
std::optional< QueueTable > queue_measures
Definition mam_common.h:127
std::vector< std::string > phase_dependent_routing
Definition mam_common.h:140
std::optional< Traffic > traffic
Definition mam_common.h:126
std::optional< std::string > residual_kind
Definition mam_common.h:121
nlohmann::json native_internal_fitting
null: absent
Definition mam_common.h:147
std::optional< double > native_time_scale
dec.source: factor dividing the lowered network's rates
Definition mam_common.h:144
std::vector< std::string > correlated_service_reset
Definition mam_common.h:141
std::vector< std::string > unavailable_clock_phases
Definition mam_common.h:142
std::vector< std::string > unavailable_busy_probabilities
multiserver queues: Busy is NaN
Definition mam_common.h:143
nlohmann::json poissonised_visit_excess
Definition mam_common.h:146
std::optional< double > mean_level
Definition mam_common.h:129
nlohmann::json native_time_scales
marked.thinning: station -> scale (null without input); null: absent
Definition mam_common.h:145
std::optional< ActionTable > raw_action_table
The action table under the lowered agents' own route-specific labels, kept when an embedded network w...
Definition mam_common.h:155
A minimum-rate synchronisation: at least two active endpoints and optional passive ones.
Definition core.h:258
A composition snapshot (core.Model): agents in declaration order plus synchronisations.
Definition core.h:310
std::vector< MinSync > min_syncs
Definition core.h:313
std::vector< Sync > syncs
Definition core.h:312
std::vector< AgentRecord > agents
Definition core.h:311
const AgentRecord & agent(const std::string &name) const
Definition core.h:324
Structured queue declaration retained while a queue agent is unmodified (queue_info).
Definition core.h:271
std::vector< std::string > service_inputs
Definition core.h:277
std::vector< std::string > departures
Definition core.h:275
std::vector< std::string > arrivals
Definition core.h:274
One row of getQueueTable(): Agent, QLen, Busy, Util, ArvR, Tput, RespT.
Definition mam_common.h:96
std::string agent
Definition mam_common.h:97
The result container shared by the LAL solver paths (LALCTMCResult, the AG decomposition results,...
Definition ctmc.h:96
std::string method
Definition ctmc.h:97
bool truncated
Definition ctmc.h:99
ActionTable action_table
Definition ctmc.h:104
std::vector< std::vector< std::size_t > > states
joint states (CTMC)
Definition ctmc.h:105
StateTable state_table
Definition ctmc.h:103
std::optional< std::string > fallback_reason
Definition ctmc.h:100
One row of a state table: Agent, State, Probability.
Definition ctmc.h:55
std::string agent
Definition ctmc.h:56
std::string state
Definition ctmc.h:57
double probability
Definition ctmc.h:58
TableAttrs attrs
Definition ctmc.h:69
std::vector< StateRow > rows
Definition ctmc.h:68
An ordinary synchronisation: one active endpoint, hand passives and injected node arrivals.
Definition core.h:250
Endpoint active
Definition core.h:251
std::vector< Endpoint > passive
Definition core.h:252
std::optional< std::string > fallback_reason
Definition ctmc.h:50