LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
mam_common.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_MAM_COMMON_H
6#define LINE_LANG_LAL_MAM_COMMON_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * LINE Agent Language (LAL): shared types and numerical helpers of the
12 * SolverMAM LAL paths (python/line_solver/solvers/solver_mam/lal_*.py).
13 *
14 * Python returns one dataclass per lowering (LALQBDResult,
15 * LALInfiniteQBDResult, ...). Here a single `MamResult` derived from
16 * `lal::Result` carries the union of their fields; a field a lowering does not
17 * produce stays empty (`std::nullopt`, an empty vector or a null json), which
18 * is what Python's `getattr(result, name, default)` reads as absent.
19 *
20 * Nothing here calls LAPACK. The two places where Python reaches for a
21 * spectral routine are replaced by routines that need none: the spectral
22 * radius of a NONNEGATIVE matrix (the rate matrix R and the routing matrices)
23 * is obtained from Gelfand's formula by log-scaled repeated squaring, and the
24 * symmetric eigenvalue test of the count covariances (numpy `eigvalsh`) uses a
25 * cyclic Jacobi iteration.
26 */
27
28#include <algorithm>
29#include <cmath>
30#include <cstdio>
31#include <limits>
32#include <map>
33#include <optional>
34#include <set>
35#include <string>
36#include <utility>
37#include <vector>
38
39#include "json.hpp"
43#include "line/lang/lal/core.h"
44#include "line/lang/lal/ctmc.h"
45#include "line/util/error.h"
46#include "line/util/linalg.h"
47#include "line/util/lu.h"
48#include "line/util/matrix.h"
49
50namespace line {
51namespace lal {
52
53/** A marked process as Python's list `[D0, D1, D1_1, ..., D1_K]`. */
54typedef std::vector<Matrix<double>> MarkedMatrices;
55
56/**
57 * The traffic dictionary of a MAM result (`result.traffic`).
58 *
59 * The offered-traffic recognizer fills `kind`, `method`, `exact`, `sources`,
60 * `marks`, `targets`, `streams`, `matrices` and `blocking`; the fitted
61 * (reduced) analysis fills `compression`, `feasible`, `original_matrices`,
62 * `original_streams`, `fitted_matrices`, the fit settings, the counting
63 * statistics, their errors and `unavailable`. The network lowerings
64 * (dec.source, marked.thinning) put their own keys, such as `station_fits`,
65 * `feedback_poisson_rates` and `poissonised_visit_excess`, in `extra`.
66 */
67struct Traffic {
68 std::string kind;
69 std::string method;
70 std::optional<std::string> compression;
71 bool exact = true;
72 std::optional<bool> feasible;
73 std::vector<std::string> sources;
74 std::vector<std::string> marks;
75 std::vector<std::string> targets;
76 std::vector<MarkedMatrices> streams;
77 std::optional<MarkedMatrices> matrices;
78 std::optional<std::string> blocking;
79 std::optional<MarkedMatrices> original_matrices;
80 std::vector<MarkedMatrices> original_streams;
81 std::optional<MarkedMatrices> fitted_matrices;
82 std::optional<double> fit_time;
83 std::optional<double> fit_tolerance;
84 std::vector<double> original_rates;
85 std::vector<double> fitted_rates;
86 std::optional<Matrix<double>> original_count_covariance;
87 std::optional<Matrix<double>> fitted_count_covariance;
88 std::optional<double> rate_error;
89 std::optional<double> count_covariance_error;
90 std::optional<std::string> unavailable;
91 std::optional<std::string> fallback_reason;
92 nlohmann::json extra = nlohmann::json::object();
93};
94
95/** One row of `getQueueTable()`: `Agent, QLen, Busy, Util, ArvR, Tput, RespT`. */
96struct QueueRow {
97 std::string agent;
98 double qlen = 0.0;
99 double busy = 0.0;
100 double util = 0.0;
101 double arvr = 0.0;
102 double tput = 0.0;
103 double respt = 0.0;
104};
105
107 std::vector<QueueRow> rows;
109 std::size_t size() const { return rows.size(); }
110 const QueueRow& row(const std::string& agent) const {
111 for (const QueueRow& r : rows)
112 if (r.agent == agent) return r;
113 throw value_error("No queue row " + agent);
114 }
115};
116
117/** The union of Python's LAL MAM result dataclasses. */
119 std::string level_agent;
120 double residual = 0.0;
121 std::optional<std::string> residual_kind;
122 /** One row per displayed level (finite and infinite QBD) or per level (reachable QBD). */
123 std::vector<std::vector<double>> level_probabilities;
124 /** Phase tuples as agent-state names, in the column order of `level_probabilities`. */
125 std::vector<std::vector<std::string>> phase_states;
126 std::optional<Traffic> traffic;
127 std::optional<QueueTable> queue_measures;
128 std::map<std::string, double> queue_means; ///< empty: Python has no `queue_means`
129 std::optional<double> mean_level;
130 std::optional<Matrix<double>> rate_matrix;
131 std::optional<double> rate_matrix_residual;
132 std::optional<double> spectral_radius;
133 std::optional<double> drift;
134 std::optional<double> tail_probability;
135 std::optional<std::size_t> reachable_states;
136 std::vector<double> closed_class_weights;
137 std::optional<std::string> approximation;
138 std::vector<std::string> source_marks;
139 std::vector<MarkedMatrices> source_matrices;
140 std::vector<std::string> phase_dependent_routing;
141 std::vector<std::string> correlated_service_reset;
142 std::vector<std::string> unavailable_clock_phases;
143 std::vector<std::string> unavailable_busy_probabilities; ///< multiserver queues: Busy is NaN
144 std::optional<double> native_time_scale; ///< dec.source: factor dividing the lowered network's rates
145 nlohmann::json native_time_scales; ///< marked.thinning: station -> scale (null without input); null: absent
146 nlohmann::json poissonised_visit_excess = nlohmann::json::object();
147 nlohmann::json native_internal_fitting; ///< null: absent
148 nlohmann::json extra = nlohmann::json::object();
149 bool has_converged = false; ///< whether the lowering reports `converged` at all
150 /**
151 * The action table under the lowered agents' own route-specific labels,
152 * kept when an embedded network was lowered (python `raw_action_table`):
153 * `getQueueTable` needs the per-route rows that the presented table sums.
154 */
155 std::optional<ActionTable> raw_action_table;
156};
157
158namespace detail {
159
160inline UnsupportedError mam_refusal(const char* kind, const std::string& msg) {
161 return UnsupportedError(ErrorKind(kind), msg);
162}
163
164/** Python's `f'{x:g}'`. */
165inline std::string fmt_g(double x) {
166 char buf[64];
167 std::snprintf(buf, sizeof(buf), "%g", x);
168 return buf;
169}
170
171inline double tiny() { return std::numeric_limits<double>::min(); }
172
173/** Whether a directed graph (adjacency lists) has exactly one closed class (`unique_closed_class`). */
174inline bool unique_closed_class(const std::vector<std::vector<std::size_t>>& adj) {
175 int count = 0;
176 const std::vector<int> comp = strong_components(adj, count);
177 if (count == 1) return true;
178 std::vector<bool> opened(static_cast<std::size_t>(count), false);
179 for (std::size_t i = 0; i < adj.size(); ++i)
180 for (std::size_t j : adj[i])
181 if (comp[i] != comp[j]) opened[static_cast<std::size_t>(comp[i])] = true;
182 std::size_t closed = 0;
183 for (bool o : opened)
184 if (!o) ++closed;
185 return closed == 1;
186}
187
188/** Number of strongly connected components over the positive off-diagonal entries. */
189inline int strong_count_positive(const Matrix<double>& q) {
190 std::vector<std::vector<std::size_t>> adj(q.rows());
191 for (std::size_t i = 0; i < q.rows(); ++i)
192 for (std::size_t j = 0; j < q.cols(); ++j)
193 if (i != j && q(i, j) > 0) adj[i].push_back(j);
194 int count = 0;
195 strong_components(adj, count);
196 return count;
197}
198
199inline double norm_inf(const Matrix<double>& a);
200
201/**
202 * Spectral radius of a nonnegative square matrix (Gelfand's formula,
203 * rho = lim ||A^k||^(1/k), by repeated squaring with the scale kept in log
204 * form). For a nonnegative matrix the infinity norm of A^(2^s) is the largest
205 * row sum, which is never cancelled, so 60 squarings give the radius to
206 * double precision for any matrix that is not defective at its dominant
207 * eigenvalue, and to a relative error of order k/2^s otherwise.
208 */
209inline double spectral_radius_nonneg(const Matrix<double>& A) {
210 const std::size_t n = A.rows();
211 if (n == 0) return 0.0;
212 // B = A^(2^s) / exp(L): normalise, record the removed log scale, square.
213 Matrix<double> B = A;
214 double L = 0.0;
215 double power = 1.0; // 2^s
216 double estimate = -1.0;
217 for (int s = 0; s < 64; ++s) {
218 const double norm = norm_inf(B);
219 if (norm == 0.0) return 0.0;
220 const double next = std::exp((std::log(norm) + L) / power);
221 if (s > 8 && std::fabs(next - estimate) <= 1e-15 * std::max(1.0, next)) return next;
222 estimate = next;
223 for (std::size_t k = 0; k < B.size(); ++k) B[k] /= norm;
224 L = 2.0 * (L + std::log(norm));
225 B = matmul(B, B);
226 power *= 2.0;
227 }
228 return estimate;
229}
230
231/** Eigenvalues of a symmetric matrix by the cyclic Jacobi method (numpy `eigvalsh`). */
232inline std::vector<double> eigvalsh(Matrix<double> a) {
233 const std::size_t n = a.rows();
234 for (int sweep = 0; sweep < 100; ++sweep) {
235 double off = 0.0, total = 0.0;
236 for (std::size_t i = 0; i < n; ++i)
237 for (std::size_t j = 0; j < n; ++j) {
238 total += a(i, j) * a(i, j);
239 if (i != j) off += a(i, j) * a(i, j);
240 }
241 if (off <= 1e-30 * std::max(total, std::numeric_limits<double>::min())) break;
242 for (std::size_t p = 0; p + 1 < n; ++p)
243 for (std::size_t q = p + 1; q < n; ++q) {
244 if (a(p, q) == 0.0) continue;
245 const double theta = (a(q, q) - a(p, p)) / (2.0 * a(p, q));
246 const double t = (theta >= 0 ? 1.0 : -1.0) / (std::fabs(theta) + std::sqrt(theta * theta + 1.0));
247 const double c = 1.0 / std::sqrt(t * t + 1.0), s = t * c;
248 for (std::size_t k = 0; k < n; ++k) {
249 const double akp = a(k, p), akq = a(k, q);
250 a(k, p) = c * akp - s * akq;
251 a(k, q) = s * akp + c * akq;
252 }
253 for (std::size_t k = 0; k < n; ++k) {
254 const double apk = a(p, k), aqk = a(q, k);
255 a(p, k) = c * apk - s * aqk;
256 a(q, k) = s * apk + c * aqk;
257 }
258 }
259 }
260 std::vector<double> ev(n);
261 for (std::size_t i = 0; i < n; ++i) ev[i] = a(i, i);
262 std::sort(ev.begin(), ev.end());
263 return ev;
264}
265
266/** X = B A^{-1}, i.e. `np.linalg.solve(A.T, B.T).T`. Throws NumericError on a singular A. */
267inline Matrix<double> solve_right(const Matrix<double>& A, const Matrix<double>& B) {
268 Matrix<double> lu = A.transpose();
269 const std::vector<std::size_t> piv = lu_factor(lu);
270 Matrix<double> X(B.rows(), B.cols(), 0.0);
271 std::vector<double> b(A.rows());
272 for (std::size_t i = 0; i < B.rows(); ++i) {
273 for (std::size_t j = 0; j < B.cols(); ++j) b[j] = B(i, j);
274 lu_solve(lu, piv, b);
275 for (std::size_t j = 0; j < B.cols(); ++j) X(i, j) = b[j];
276 }
277 return X;
278}
279
280inline Matrix<double> add(const Matrix<double>& a, const Matrix<double>& b) {
281 Matrix<double> c = a;
282 for (std::size_t k = 0; k < c.size(); ++k) c[k] += b[k];
283 return c;
284}
285
286inline Matrix<double> scaled(const Matrix<double>& a, double s) {
287 Matrix<double> c = a;
288 for (std::size_t k = 0; k < c.size(); ++k) c[k] *= s;
289 return c;
290}
291
292inline double sum(const std::vector<double>& v) {
293 double s = 0.0;
294 for (double x : v) s += x;
295 return s;
296}
297
298// max_abs and all_finite come from builder.h (detail).
299
300inline double norm_inf(const Matrix<double>& a) {
301 double m = 0.0;
302 for (std::size_t i = 0; i < a.rows(); ++i) {
303 double r = 0.0;
304 for (std::size_t j = 0; j < a.cols(); ++j) r += std::fabs(a(i, j));
305 m = std::max(m, r);
306 }
307 return m;
308}
309
310inline std::vector<double> row_sums(const Matrix<double>& a) {
311 std::vector<double> r(a.rows(), 0.0);
312 for (std::size_t i = 0; i < a.rows(); ++i)
313 for (std::size_t j = 0; j < a.cols(); ++j) r[i] += a(i, j);
314 return r;
315}
316
317/**
318 * Stationary vector of a uniquely stationary generator with scale-free
319 * balance rows (`stationary_generator` of lal_qbd.py): the generator is
320 * divided by its largest magnitude, each balance row by its own largest
321 * magnitude, and the last row replaced by normalisation, so the solve does
322 * not depend on the time scale. Singular or invalid solutions are refused
323 * with `LINE:unsupported:Numerical`.
324 */
325inline std::vector<double> stationary(const Matrix<double>& q) {
326 const std::size_t n = q.rows();
327 if (n == 1) return std::vector<double>(1, 1.0);
328 double scale = 0.0;
329 bool finite = true;
330 for (std::size_t k = 0; k < q.size(); ++k) {
331 finite = finite && std::isfinite(q[k]);
332 scale = std::max(scale, std::fabs(q[k]));
333 }
334 if (!finite || scale == 0)
335 throw mam_refusal("Numerical", "QBD phase generator has no unique stationary solution.");
336 const Matrix<double> m = scaled(q, 1.0 / scale);
337 Matrix<double> eq(n, n, 0.0);
338 for (std::size_t i = 0; i < n; ++i)
339 for (std::size_t j = 0; j < n; ++j) eq(i, j) = m(j, i);
340 for (std::size_t i = 0; i < n; ++i) {
341 double r = 0.0;
342 for (std::size_t j = 0; j < n; ++j) r = std::max(r, std::fabs(eq(i, j)));
343 if (r > 0)
344 for (std::size_t j = 0; j < n; ++j) eq(i, j) /= r;
345 }
346 for (std::size_t j = 0; j < n; ++j) eq(n - 1, j) = 1.0;
347 std::vector<double> p(n, 0.0);
348 p[n - 1] = 1.0;
349 try {
350 const std::vector<std::size_t> piv = lu_factor(eq);
351 lu_solve(eq, piv, p);
352 } catch (const NumericError&) {
353 throw mam_refusal("Numerical", "QBD phase balance equations are singular.");
354 }
355 bool ok = true;
356 double low = 0.0;
357 for (double x : p) {
358 ok = ok && std::isfinite(x);
359 low = std::min(low, x);
360 }
361 double residual = 0.0;
362 if (ok)
363 for (std::size_t j = 0; j < n; ++j) {
364 double s = 0.0;
365 for (std::size_t i = 0; i < n; ++i) s += p[i] * m(i, j);
366 residual += std::fabs(s);
367 }
368 if (!ok || low < -1e-10 || residual > 1e-8)
369 throw mam_refusal("Numerical", "QBD phase balance equations produced invalid probabilities.");
370 double total = 0.0;
371 for (double& x : p) {
372 x = std::max(x, 0.0);
373 total += x;
374 }
375 for (double& x : p) x /= total;
376 return p;
377}
378
379/** A queue state name `n_k` or `n_ge_k` as (k, tail). */
380inline std::pair<long, bool> queue_level(const std::string& state) {
381 const bool tail = state.compare(0, 5, "n_ge_") == 0;
382 return {std::stol(tail ? state.substr(5) : state.substr(2)), tail};
383}
384
385/** Model snapshot with every unbounded queue made bounded, so the event kernel accepts it. */
386inline Model bounded_template(const Model& snapshot) {
387 Model t = snapshot;
388 for (AgentRecord& a : t.agents) a.unbounded_queue = false;
389 return t;
390}
391
392/** Labels of the event kernel of a snapshot, unbounded queues read as their finite template. */
393inline std::vector<std::string> kernel_labels(const Model& snapshot) {
394 const Model t = bounded_template(snapshot);
395 EventKernel k(t);
396 return k.labels;
397}
398
399} // namespace detail
400
401} // namespace lal
402} // namespace line
403
404#endif
LINE Agent Language (LAL): programmatic construction of finite agents and their composition,...
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
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...
Steady-state distribution of a continuous-time Markov chain.
The exception types the port throws.
Dense linear algebra over the templated number type: products, identity, inverse, and powers.
LU factorization with partial pivoting, templated on the number type.
Dense matrix and non-owning view.
Marked MAP (MMAP) algebra: per-class rates, class probabilities, superposition, normalization and sca...
Definition ag.h:49
std::vector< Matrix< double > > MarkedMatrices
A marked process as Python's list [D0, D1, D1_1, ..., D1_K].
Definition mam_common.h:54
InputError value_error(const std::string &what)
LINE:input:Unspecified, the C++ spelling of the Python ValueError raised throughout LAL.
Definition core.h:85
HittingDistResult estimate(const Step &step, const IsRates &isr, bool hasIS, const Target &target, const State &x0, const std::vector< double > &t, const Checked &c, const HittingDistOptions &opt)
The cycles and the five estimators, common to both forms.
std::vector< std::size_t > lu(Mat &A)
LU with partial pivoting in place; returns the row permutation.
Definition spn_ispn.h:208
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
void lu_solve(const Matrix< T > &LU, const std::vector< std::size_t > &piv, std::vector< T > &b)
Solve LUx = Pb in place on b, using the factors from lu_factor.
Definition lu.h:94
std::vector< std::size_t > lu_factor(Matrix< T > &A)
In-place LU of A (n x n).
Definition lu.h:48
Matrix< T > matmul(const Matrix< T > &A, const Matrix< T > &B)
Matrix product A B.
Definition linalg.h:36
ErrorKind(std::string n)
Definition error.h:39
The union of Python's LAL MAM result dataclasses.
Definition mam_common.h:118
nlohmann::json extra
Definition mam_common.h:148
std::string level_agent
Definition mam_common.h:119
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::optional< double > tail_probability
Definition mam_common.h:134
std::vector< std::string > phase_dependent_routing
Definition mam_common.h:140
std::vector< std::vector< double > > level_probabilities
One row per displayed level (finite and infinite QBD) or per level (reachable QBD).
Definition mam_common.h:123
std::vector< MarkedMatrices > source_matrices
Definition mam_common.h:139
std::optional< Traffic > traffic
Definition mam_common.h:126
std::optional< std::string > residual_kind
Definition mam_common.h:121
std::vector< std::vector< std::string > > phase_states
Phase tuples as agent-state names, in the column order of level_probabilities.
Definition mam_common.h:125
nlohmann::json native_internal_fitting
null: absent
Definition mam_common.h:147
bool has_converged
whether the lowering reports converged at all
Definition mam_common.h:149
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::optional< double > drift
Definition mam_common.h:133
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
std::vector< std::string > source_marks
Definition mam_common.h:138
nlohmann::json poissonised_visit_excess
Definition mam_common.h:146
std::optional< double > mean_level
Definition mam_common.h:129
std::optional< Matrix< double > > rate_matrix
Definition mam_common.h:130
std::vector< double > closed_class_weights
Definition mam_common.h:136
std::optional< double > rate_matrix_residual
Definition mam_common.h:131
std::optional< double > spectral_radius
Definition mam_common.h:132
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
std::optional< std::size_t > reachable_states
Definition mam_common.h:135
One row of getQueueTable(): Agent, QLen, Busy, Util, ArvR, Tput, RespT.
Definition mam_common.h:96
std::string agent
Definition mam_common.h:97
const QueueRow & row(const std::string &agent) const
Definition mam_common.h:110
std::vector< QueueRow > rows
Definition mam_common.h:107
std::size_t size() const
Definition mam_common.h:109
The result container shared by the LAL solver paths (LALCTMCResult, the AG decomposition results,...
Definition ctmc.h:96
The attrs of a LAL result table.
Definition ctmc.h:46
The traffic dictionary of a MAM result (result.traffic).
Definition mam_common.h:67
std::string method
Definition mam_common.h:69
std::optional< MarkedMatrices > fitted_matrices
Definition mam_common.h:81
std::optional< std::string > compression
Definition mam_common.h:70
std::string kind
Definition mam_common.h:68
std::optional< double > fit_tolerance
Definition mam_common.h:83
nlohmann::json extra
Definition mam_common.h:92
std::optional< Matrix< double > > original_count_covariance
Definition mam_common.h:86
std::optional< Matrix< double > > fitted_count_covariance
Definition mam_common.h:87
std::vector< std::string > marks
Definition mam_common.h:74
std::vector< MarkedMatrices > original_streams
Definition mam_common.h:80
std::vector< double > fitted_rates
Definition mam_common.h:85
std::optional< std::string > fallback_reason
Definition mam_common.h:91
std::optional< MarkedMatrices > matrices
Definition mam_common.h:77
std::optional< double > rate_error
Definition mam_common.h:88
std::vector< std::string > targets
Definition mam_common.h:75
std::vector< std::string > sources
Definition mam_common.h:73
std::optional< MarkedMatrices > original_matrices
Definition mam_common.h:79
std::optional< std::string > unavailable
Definition mam_common.h:90
std::optional< double > fit_time
Definition mam_common.h:82
std::optional< double > count_covariance_error
Definition mam_common.h:89
std::optional< std::string > blocking
Definition mam_common.h:78
std::vector< double > original_rates
Definition mam_common.h:84
std::vector< MarkedMatrices > streams
Definition mam_common.h:76
std::optional< bool > feasible
Definition mam_common.h:72