LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
mam_infinite_qbd.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_INFINITE_QBD_H
6#define LINE_LANG_LAL_MAM_INFINITE_QBD_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * LINE Agent Language (LAL): matrix-geometric analysis of one structured
12 * unbounded queue (solver_mam/lal_infinite_qbd.py).
13 *
14 * The final template state of the unbounded queue is a finite sentinel; the
15 * level before it is homogeneous because all servers are busy from there on.
16 * The rate matrix comes from the existing `mam::qbd_R_logred`. Its spectral
17 * radius is computed without an eigensolver (Gelfand's formula on the
18 * nonnegative R), where Python calls `numpy.linalg.eigvals`.
19 */
20
21#include <cmath>
22#include <optional>
23#include <string>
24#include <vector>
25
26#include "line/api/mam/qbd_r.h"
28
29namespace line {
30namespace lal {
31
32/** Infinite QBD solution of a composition (`lal_infinite_qbd.solve_composition`). */
33inline MamResult infinite_qbd(const Composition& model, double max_phases = 64, double max_states = 50000,
34 const std::optional<std::string>& level_name = std::nullopt, long max_iter = 100,
35 double tol = 1e-4) {
36 const Model snapshot = model.model();
37 std::vector<std::size_t> unbounded;
38 for (std::size_t a = 0; a < snapshot.agents.size(); ++a)
39 if (snapshot.agents[a].unbounded_queue) unbounded.push_back(a);
40 if (unbounded.size() != 1 || (level_name && *level_name != snapshot.agents[unbounded[0]].name))
41 throw detail::mam_refusal("Model", "Infinite QBD requires exactly one selected unbounded queue.");
42 const std::size_t pos = unbounded[0];
43 const AgentRecord& queue = snapshot.agents[pos];
44 std::vector<std::size_t> phase_agents, dims;
45 double md = 1.0;
46 for (std::size_t a = 0; a < snapshot.agents.size(); ++a)
47 if (a != pos) {
48 phase_agents.push_back(a);
49 dims.push_back(snapshot.agents[a].states.size());
50 md *= static_cast<double>(snapshot.agents[a].states.size());
51 }
52 // The template is the boundary levels 0..threshold plus the finite
53 // sentinel, and the homogeneous blocks are read off its last boundary
54 // level, so it needs at least two states (`Records::queue` builds
55 // servers + 2 >= 3 for an unbounded queue). Python indexes `down[-1]` of an
56 // empty array here; refuse by name instead of reading past the blocks.
57 if (queue.states.size() < 2)
58 throw detail::mam_refusal("Model",
59 "Infinite QBD requires an unbounded queue template with at least two levels.");
60 const long threshold = static_cast<long>(queue.states.size()) - 2;
61 auto positive_int = [](double x) { return x > 0 && (std::isinf(x) || x == std::floor(x)); };
62 if (!positive_int(max_phases) || !positive_int(max_states))
63 throw InputError("lal_max_phases and lal_max_states must be positive integers");
64 if (max_iter <= 0 || !std::isfinite(tol) || tol <= 0) throw InputError("max_iter and tol must be positive");
65 if (md > max_phases || (threshold + 2) * md > max_states)
66 throw detail::mam_refusal("StateSpace", "Infinite QBD exceeds the phase or boundary-state limit.");
67 if (8.0 * (threshold + 2) * md * md * 5 > 256.0 * 1024 * 1024)
68 throw detail::mam_refusal("StateSpace", "Infinite QBD block storage exceeds 256 MiB.");
69 const std::vector<std::vector<std::size_t>> phases = detail::phase_product(snapshot, phase_agents);
70 const std::size_t m = phases.size();
71 const Model tmpl = detail::bounded_template(snapshot);
72 EventKernel kernel(tmpl);
73 const std::vector<std::string>& labels = kernel.labels;
74 const std::size_t count = static_cast<std::size_t>(threshold + 1);
75 if (8.0 * (5.0 * (count + 1) * m * m + static_cast<double>(labels.size()) * count * m) > 256.0 * 1024 * 1024)
76 throw detail::mam_refusal("StateSpace", "Infinite QBD block and reward storage exceeds 256 MiB.");
77 std::vector<Matrix<double>> diag(count, Matrix<double>(m, m, 0.0)), up = diag, down = diag;
78 std::vector<Matrix<double>> rewards(labels.size(), Matrix<double>(count, m, 0.0));
79 std::vector<std::vector<std::size_t>> adj((count + 1) * m);
80 std::size_t event_count = 0;
81 for (std::size_t n = 0; n <= count; ++n) {
82 for (std::size_t i = 0; i < m; ++i) {
83 std::vector<std::size_t> state(snapshot.agents.size());
84 for (std::size_t k = 0; k < phase_agents.size(); ++k) state[phase_agents[k]] = phases[i][k];
85 state[pos] = n;
86 for (const Move& mv : kernel.outgoing(state)) {
87 if (++event_count > 5000000)
88 throw detail::mam_refusal("StateSpace", "Infinite QBD exceeds the event-branch limit.");
89 if (mv.rate <= 0) continue;
90 const std::size_t dest = mv.target[pos];
91 const long delta = static_cast<long>(dest) - static_cast<long>(n);
92 if (std::labs(delta) > 1)
93 throw detail::mam_refusal("Model", "Infinite QBD requires level jumps of at most one.");
94 std::vector<std::size_t> tp;
95 for (std::size_t a : phase_agents) tp.push_back(mv.target[a]);
96 const std::size_t j = detail::flat_index(tp, dims);
97 if (dest != n || j != i) adj[n * m + i].push_back(dest * m + j);
98 if (n == count) continue;
99 rewards[mv.label](n, i) += mv.rate;
100 if (delta == 0) {
101 if (i != j) diag[n](i, j) += mv.rate;
102 } else if (delta == 1) {
103 up[n](i, j) += mv.rate;
104 } else {
105 down[n](i, j) += mv.rate;
106 }
107 }
108 }
109 if (n < count) {
110 const std::vector<double> rd = detail::row_sums(diag[n]), ru = detail::row_sums(up[n]),
111 rn = detail::row_sums(down[n]);
112 for (std::size_t i = 0; i < m; ++i) diag[n](i, i) = -(rd[i] + ru[i] + rn[i]);
113 }
114 }
115 if (!detail::unique_closed_class(adj))
116 throw detail::mam_refusal("Model", "Infinite QBD requires a unique closed boundary/phase class.");
117 const Matrix<double> B = down.back(), L = diag.back(), F = up.back();
118 const Matrix<double> phase_generator = detail::add(detail::add(B, L), F);
119 {
120 std::vector<std::vector<std::size_t>> padj(m);
121 for (std::size_t i = 0; i < m; ++i)
122 for (std::size_t j = 0; j < m; ++j)
123 if (i != j && phase_generator(i, j) > 0) padj[i].push_back(j);
124 if (!detail::unique_closed_class(padj))
125 throw detail::mam_refusal("Model", "Infinite QBD requires a unique closed homogeneous phase class.");
126 }
127 const std::vector<double> theta = detail::stationary(phase_generator);
128 double drift = 0.0, ldiag = detail::tiny();
129 {
130 const std::vector<double> fb = detail::row_sums(detail::add(F, detail::scaled(B, -1.0)));
131 for (std::size_t i = 0; i < m; ++i) {
132 drift += theta[i] * fb[i];
133 ldiag = std::max(ldiag, -L(i, i));
134 }
135 }
136 const double rate_scale = std::max({ldiag, detail::norm_inf(F), detail::norm_inf(B)});
137 if (drift >= -1e-12 * rate_scale)
138 throw detail::mam_refusal("Stability",
139 "Infinite QBD is unstable or critically loaded (drift " + detail::fmt_g(drift) + ").");
140 Matrix<double> R, Z;
141 double R_residual = 0.0, rho = 0.0;
142 const double scale = std::max({detail::tiny(), detail::norm_inf(F), detail::norm_inf(L), detail::norm_inf(B)});
143 std::vector<std::vector<double>> boundary(count, std::vector<double>(m, 0.0));
144 auto zsum = [&](const std::vector<double>& v) { return detail::sum(vecmul(v, Z)); };
145 try {
146 R = mam::qbd_R_logred(B, L, F, static_cast<unsigned>(max_iter), std::min(tol, 1e-12));
147 R_residual = detail::norm_inf(detail::add(detail::add(F, matmul(R, L)), matmul(matmul(R, R), B)));
148 bool finite = true;
149 double rmin = 0.0;
150 Matrix<double> Rp = R;
151 for (std::size_t k = 0; k < R.size(); ++k) {
152 finite = finite && std::isfinite(R[k]);
153 rmin = std::min(rmin, R[k]);
154 Rp[k] = std::max(R[k], 0.0);
155 }
156 rho = finite ? detail::spectral_radius_nonneg(Rp) : std::numeric_limits<double>::quiet_NaN();
157 if (!finite || rmin < -1e-10 || !(rho < 1) || R_residual > 1e-8 * scale)
158 throw detail::mam_refusal("Numerical", "Infinite QBD rate matrix failed stability or residual checks.");
159 R = Rp;
160 Z = inverse(detail::add(eye<double>(m), detail::scaled(R, -1.0)));
161 std::vector<Matrix<double>> schur = diag;
162 schur.back() = detail::add(schur.back(), matmul(R, B));
163 std::vector<Matrix<double>> ratios(static_cast<std::size_t>(threshold));
164 for (long n = threshold - 1; n >= 0; --n) {
165 ratios[n] = detail::solve_right(schur[n + 1], detail::scaled(up[n], -1.0));
166 schur[n] = detail::add(schur[n], matmul(ratios[n], down[n + 1]));
167 }
168 boundary[0] = detail::stationary(schur[0]);
169 for (long n = 0; n < threshold; ++n) boundary[n + 1] = vecmul(boundary[n], ratios[n]);
170 double mass = zsum(boundary.back());
171 for (std::size_t n = 0; n + 1 < count; ++n) mass += detail::sum(boundary[n]);
172 for (auto& row : boundary)
173 for (double& p : row) p /= mass;
174 } catch (const NumericError&) {
175 throw detail::mam_refusal("Numerical", "Infinite QBD matrix solution is singular.");
176 }
177 bool valid = true;
178 for (const auto& row : boundary)
179 for (double p : row)
180 if (!std::isfinite(p) || p < -1e-10) valid = false;
181 if (!valid) throw detail::mam_refusal("Numerical", "Infinite QBD produced invalid probabilities.");
182 for (auto& row : boundary)
183 for (double& p : row) p = std::max(p, 0.0);
184 {
185 double mass = zsum(boundary.back());
186 for (std::size_t n = 0; n + 1 < count; ++n) mass += detail::sum(boundary[n]);
187 for (auto& row : boundary)
188 for (double& p : row) p /= mass;
189 }
190 double residual = 0.0;
191 for (std::size_t n = 0; n < count; ++n) {
192 std::vector<double> row = vecmul(boundary[n], diag[n]);
193 if (n) {
194 const std::vector<double> u = vecmul(boundary[n - 1], up[n - 1]);
195 for (std::size_t i = 0; i < m; ++i) row[i] += u[i];
196 }
197 const std::vector<double> d = n + 1 < count ? vecmul(boundary[n + 1], down[n + 1])
198 : vecmul(vecmul(boundary[n], R), B);
199 for (std::size_t i = 0; i < m; ++i) row[i] += d[i];
200 for (double x : row) residual += std::fabs(x);
201 }
202 if (residual > 1e-8 * scale)
203 throw detail::mam_refusal("Numerical", "Infinite QBD boundary residual is too large.");
204 const std::vector<double> lastZ = vecmul(boundary.back(), Z);
205 std::vector<double> phase_marginal = lastZ;
206 for (std::size_t n = 0; n + 1 < count; ++n)
207 for (std::size_t i = 0; i < m; ++i) phase_marginal[i] += boundary[n][i];
208 std::vector<double> event_rates(labels.size(), 0.0);
209 for (std::size_t l = 0; l < labels.size(); ++l) {
210 double x = 0.0;
211 for (std::size_t n = 0; n + 1 < count; ++n)
212 for (std::size_t i = 0; i < m; ++i) x += boundary[n][i] * rewards[l](n, i);
213 for (std::size_t i = 0; i < m; ++i) x += lastZ[i] * rewards[l](count - 1, i);
214 event_rates[l] = x;
215 }
216 std::vector<std::vector<double>> vectors = boundary;
217 const double by_states = std::isinf(max_states) ? kMamNoLimit
218 : std::floor(max_states / static_cast<double>(m)) - 1.0;
219 const double limit = std::min(1000.0, std::max(static_cast<double>(threshold + 1), by_states));
220 while (static_cast<double>(vectors.size()) < limit) {
221 const std::vector<double> next_row = vecmul(vectors.back(), R);
222 if (zsum(next_row) < 1e-10) break;
223 vectors.push_back(next_row);
224 }
225 const double tail = zsum(vecmul(vectors.back(), R));
226 MamResult res;
227 for (std::size_t a = 0; a < snapshot.agents.size(); ++a) {
228 const AgentRecord& agent = snapshot.agents[a];
229 if (a == pos) {
230 for (std::size_t n = 0; n < vectors.size(); ++n)
231 res.state_table.rows.push_back(StateRow{agent.name, "n_" + std::to_string(n), detail::sum(vectors[n])});
232 res.state_table.rows.push_back(StateRow{agent.name, "n_ge_" + std::to_string(vectors.size()), tail});
233 } else {
234 const std::size_t p = static_cast<std::size_t>(
235 std::find(phase_agents.begin(), phase_agents.end(), a) - phase_agents.begin());
236 for (std::size_t s = 0; s < agent.states.size(); ++s) {
237 double x = 0.0;
238 for (std::size_t i = 0; i < m; ++i)
239 if (phases[i][p] == s) x += phase_marginal[i];
240 res.state_table.rows.push_back(StateRow{agent.name, agent.states[s], x});
241 }
242 }
243 }
244 for (std::size_t l = 0; l < labels.size(); ++l) res.action_table.rows.push_back(ActionRow{labels[l], event_rates[l]});
245 const bool truncated = model.source_truncated;
246 for (TableAttrs* at : {&res.state_table.attrs, &res.action_table.attrs}) {
247 at->method = "infiniteqbd";
248 at->exact = !truncated;
249 at->truncated = truncated;
250 at->extra["level_tail"] = tail;
251 }
252 res.method = "infiniteqbd";
253 res.exact = !truncated;
254 res.truncated = truncated;
255 res.level_probabilities = vectors;
256 for (const auto& ph : phases) res.phase_states.push_back(detail::phase_names_of(snapshot, phase_agents, ph));
257 res.level_agent = queue.name;
258 res.residual = residual;
259 res.rate_matrix = R;
260 res.rate_matrix_residual = R_residual;
261 res.spectral_radius = rho;
262 res.drift = drift;
263 res.tail_probability = tail;
264 double mean = 0.0;
265 for (std::size_t n = 0; n + 1 < count; ++n) mean += static_cast<double>(n) * detail::sum(boundary[n]);
266 mean += static_cast<double>(threshold) * zsum(boundary.back());
267 mean += zsum(vecmul(vecmul(boundary.back(), R), Z));
268 res.mean_level = mean;
269 if (8.0 * m * m * (labels.size() + 2.0) <= 32.0 * 1024 * 1024) res.traffic = offered_traffic(snapshot, queue.name);
270 return res;
271}
272
273} // namespace lal
274} // namespace line
275
276#endif
InputError(const std::string &what)
Definition error.h:105
std::size_t size() const
Definition matrix.h:91
The algorithm cannot produce a trustworthy answer on this instance: LINE:numerical:<kind>.
Definition error.h:110
A collection of agents and embedded LINE models with atomic synchronisations (Composition).
Definition builder.h:655
Model model(const std::vector< Sync > *syncs=nullptr, const std::vector< ExtSync > *ext_syncs=nullptr) const
The current model snapshot (_model).
Definition builder.h:906
The legacy timed event kernel (event_kernel): the ordered event labels and a lazy joint-state transit...
Definition core.h:1065
std::vector< std::string > labels
Definition core.h:1071
std::vector< Move > outgoing(const std::vector< std::size_t > &state, const std::vector< bool > *include=nullptr) const
Outgoing moves of state.
Definition core.h:1079
LINE Agent Language (LAL): exact finite, level-dependent QBD analysis of a composition (solver_mam/la...
Definition ag.h:49
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).
std::optional< Traffic > offered_traffic(const Model &snapshot, const std::string &level_name, bool materialize=true)
Exact superposed offered MMAP and mark provenance, or nullopt (offered_traffic).
Matrix< T > qbd_R_logred(const Matrix< T > &B, const Matrix< T > &L, const Matrix< T > &F, unsigned iter_max, const T &tol)
R by logarithmic reduction (qbd_R_logred.m).
Definition qbd_r.h:217
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
std::vector< T > vecmul(const std::vector< T > &v, const Matrix< T > &A)
Row vector times matrix, v A.
Definition linalg.h:50
Matrix< T > inverse(const Matrix< T > &A)
Inverse by LU with one factorization and n back substitutions.
Definition linalg.h:72
Matrix< T > matmul(const Matrix< T > &A, const Matrix< T > &B)
Matrix product A B.
Definition linalg.h:36
Matrix< T > eye(std::size_t n)
Identity of order n.
Definition linalg.h:28
Quasi-birth-death processes: the rate matrix R, the fundamental matrix G, the caudal characteristic,...
One row of an action table: Action, Throughput.
Definition ctmc.h:62
std::vector< ActionRow > rows
Definition ctmc.h:80
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
The union of Python's LAL MAM result dataclasses.
Definition mam_common.h:118
std::string level_agent
Definition mam_common.h:119
std::optional< double > tail_probability
Definition mam_common.h:134
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::optional< Traffic > traffic
Definition mam_common.h:126
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
std::optional< double > drift
Definition mam_common.h:133
std::optional< double > mean_level
Definition mam_common.h:129
std::optional< Matrix< double > > rate_matrix
Definition mam_common.h:130
std::optional< double > rate_matrix_residual
Definition mam_common.h:131
std::optional< double > spectral_radius
Definition mam_common.h:132
A composition snapshot (core.Model): agents in declaration order plus synchronisations.
Definition core.h:310
std::vector< AgentRecord > agents
Definition core.h:311
One outgoing joint-state move of the legacy event kernel.
Definition core.h:1050
std::string method
Definition ctmc.h:97
bool truncated
Definition ctmc.h:99
ActionTable action_table
Definition ctmc.h:104
StateTable state_table
Definition ctmc.h:103
One row of a state table: Agent, State, Probability.
Definition ctmc.h:55
TableAttrs attrs
Definition ctmc.h:69
std::vector< StateRow > rows
Definition ctmc.h:68
The attrs of a LAL result table.
Definition ctmc.h:46