LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
mam_reachable_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_REACHABLE_QBD_H
6#define LINE_LANG_LAL_MAM_REACHABLE_QBD_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * LINE Agent Language (LAL): QBD analysis restricted to the states reachable
12 * from the initial support (solver_mam/lal_reachable_qbd.py).
13 *
14 * Each closed class is solved by block elimination over its contiguous
15 * levels and weighted by the probability of absorption into it.
16 *
17 * Divergences from Python, both forced by the absence of a sparse solver in
18 * the C++ tree: the absorption probabilities come from a dense LU of the
19 * transient generator, so the transient block itself is held to the same
20 * 256 MiB budget Python applies to the weight matrix; and the closed classes
21 * are taken in ascending order of their smallest reachable-state index, where
22 * scipy numbers them in its own component order (`closed_class_weights` is
23 * reported in that class order).
24 */
25
26#include <cmath>
27#include <map>
28#include <optional>
29#include <string>
30#include <tuple>
31#include <vector>
32
34
35namespace line {
36namespace lal {
37
38/** Reachable QBD solution of a composition (`lal_reachable_qbd.solve_composition`). */
39inline MamResult reachable_qbd(const Composition& model, double max_phases = 64, double max_states = 50000,
40 const std::optional<std::string>& level_name = std::nullopt) {
41 const Model snapshot = model.model();
42 const auto st = qbd_structure(snapshot, kMamNoLimit, kMamNoLimit, level_name);
43 if (!st.first) throw detail::mam_refusal("Model", st.second);
44 auto positive_int = [](double x) { return x > 0 && (std::isinf(x) || x == std::floor(x)); };
45 if (!positive_int(max_phases) || !positive_int(max_states))
46 throw InputError("lal_max_phases and lal_max_states must be positive integers");
47 const std::size_t position = snapshot.index_of(*st.first);
48 const AgentRecord& level = snapshot.agents[position];
49 EventKernel kernel(snapshot);
50 const std::vector<std::string>& labels = kernel.labels;
51 const std::size_t na = snapshot.agents.size();
52 std::vector<std::vector<std::pair<std::size_t, double>>> choices;
53 double support = 1.0;
54 for (const AgentRecord& agent : snapshot.agents) {
55 std::vector<std::pair<std::size_t, double>> c;
56 if (!agent.initial_distribution) {
57 c.push_back({agent.state_index(agent.initial), 1.0});
58 } else {
59 for (std::size_t s = 0; s < agent.states.size(); ++s)
60 if ((*agent.initial_distribution)[s] > 0) c.push_back({s, (*agent.initial_distribution)[s]});
61 }
62 support *= static_cast<double>(c.size());
63 choices.push_back(c);
64 }
65 if (support > max_states)
66 throw detail::mam_refusal("StateSpace", "Initial support exceeds the reachable QBD state limit.");
67 std::vector<std::vector<std::size_t>> states{{}};
68 std::vector<double> initial_probabilities{1.0};
69 for (const auto& c : choices) {
70 std::vector<std::vector<std::size_t>> ns;
71 std::vector<double> np_;
72 for (std::size_t k = 0; k < states.size(); ++k)
73 for (const auto& item : c) {
74 std::vector<std::size_t> s = states[k];
75 s.push_back(item.first);
76 ns.push_back(s);
77 np_.push_back(initial_probabilities[k] * item.second);
78 }
79 states.swap(ns);
80 initial_probabilities.swap(np_);
81 }
82 std::map<std::vector<std::size_t>, std::size_t> lookup;
83 for (std::size_t i = 0; i < states.size(); ++i) lookup[states[i]] = i;
84 struct Edge {
85 std::size_t i, j;
86 double rate;
87 };
88 std::vector<Edge> edges;
89 std::vector<std::vector<std::tuple<std::size_t, std::size_t, double>>> event_rows;
90 std::size_t event_count = 0;
91 for (std::size_t i = 0; i < states.size(); ++i) {
92 std::vector<std::tuple<std::size_t, std::size_t, double>> row;
93 const std::vector<std::size_t> state = states[i];
94 for (const Move& mv : kernel.outgoing(state)) {
95 if (++event_count > 5000000)
96 throw detail::mam_refusal("StateSpace", "Reachable QBD exceeds the event-branch limit.");
97 if (mv.rate <= 0) continue;
98 if (std::labs(static_cast<long>(mv.target[position]) - static_cast<long>(state[position])) > 1)
99 throw detail::mam_refusal("Model", "Reachable QBD requires level jumps of at most one.");
100 auto it = lookup.find(mv.target);
101 std::size_t j;
102 if (it == lookup.end()) {
103 if (static_cast<double>(states.size()) >= max_states)
104 throw detail::mam_refusal("StateSpace", "Reachable QBD exceeds the state limit.");
105 j = states.size();
106 lookup[mv.target] = j;
107 states.push_back(mv.target);
108 } else {
109 j = it->second;
110 }
111 row.emplace_back(j, mv.label, mv.rate);
112 if (i != j) edges.push_back(Edge{i, j, mv.rate});
113 }
114 event_rows.push_back(row);
115 }
116 const std::size_t ns = states.size();
117 auto phase_of = [&](const std::vector<std::size_t>& s) {
118 std::vector<std::size_t> p;
119 for (std::size_t a = 0; a < na; ++a)
120 if (a != position) p.push_back(s[a]);
121 return p;
122 };
123 std::vector<std::vector<std::size_t>> phase_states;
124 std::map<std::vector<std::size_t>, std::size_t> phase_index;
125 for (const auto& s : states) {
126 const std::vector<std::size_t> p = phase_of(s);
127 if (!phase_index.count(p)) {
128 phase_index[p] = phase_states.size();
129 phase_states.push_back(p);
130 }
131 }
132 if (static_cast<double>(phase_states.size()) > max_phases)
133 throw detail::mam_refusal("StateSpace", "Reachable QBD exceeds the phase limit.");
134 std::vector<std::vector<std::size_t>> adj(ns);
135 for (const Edge& e : edges) adj[e.i].push_back(e.j);
136 int count = 0;
137 std::vector<int> component = detail::strong_components(adj, count);
138 // Renumber components by their smallest member so the class order is reproducible.
139 {
140 std::vector<int> first(static_cast<std::size_t>(count), -1), order;
141 for (std::size_t i = 0; i < ns; ++i)
142 if (first[component[i]] < 0) {
143 first[component[i]] = static_cast<int>(order.size());
144 order.push_back(component[i]);
145 }
146 for (int& c : component) c = first[c];
147 }
148 std::vector<bool> open_class(static_cast<std::size_t>(count), false);
149 for (const Edge& e : edges)
150 if (component[e.i] != component[e.j]) open_class[component[e.i]] = true;
151 std::vector<int> closed;
152 for (int c = 0; c < count; ++c)
153 if (!open_class[c]) closed.push_back(c);
154 std::vector<bool> recurrent(ns, false);
155 for (std::size_t i = 0; i < ns; ++i) recurrent[i] = !open_class[component[i]];
156 std::vector<std::size_t> transient;
157 for (std::size_t i = 0; i < ns; ++i)
158 if (!recurrent[i]) transient.push_back(i);
159 std::vector<double> initial_vector(ns, 0.0);
160 for (std::size_t i = 0; i < initial_probabilities.size(); ++i) initial_vector[i] = initial_probabilities[i];
161 std::vector<double> weights(closed.size(), 0.0);
162 for (std::size_t k = 0; k < closed.size(); ++k)
163 for (std::size_t i = 0; i < ns; ++i)
164 if (component[i] == closed[k]) weights[k] += initial_vector[i];
165 if (!transient.empty()) {
166 const double nt = static_cast<double>(transient.size());
167 if (nt * closed.size() * 8 > 256.0 * 1024 * 1024 || nt * nt * 8 > 256.0 * 1024 * 1024)
168 throw detail::mam_refusal("StateSpace", "QBD absorption weights exceed the 256 MiB limit.");
169 std::vector<long> tpos(ns, -1);
170 for (std::size_t t = 0; t < transient.size(); ++t) tpos[transient[t]] = static_cast<long>(t);
171 std::vector<double> exits(ns, 0.0);
172 for (const Edge& e : edges) exits[e.i] += e.rate;
173 Matrix<double> neg_q(transient.size(), transient.size(), 0.0); // -trans_q
174 for (std::size_t t = 0; t < transient.size(); ++t) neg_q(t, t) = exits[transient[t]];
175 for (const Edge& e : edges)
176 if (tpos[e.i] >= 0 && tpos[e.j] >= 0) neg_q(tpos[e.i], tpos[e.j]) -= e.rate;
177 std::vector<std::size_t> piv;
178 Matrix<double> lu = neg_q;
179 try {
180 piv = lu_factor(lu);
181 } catch (const NumericError&) {
182 throw detail::mam_refusal("Numerical", "QBD absorption probabilities are numerically invalid.");
183 }
184 for (std::size_t k = 0; k < closed.size(); ++k) {
185 std::vector<double> rates(transient.size(), 0.0);
186 for (const Edge& e : edges)
187 if (tpos[e.i] >= 0 && component[e.j] == closed[k]) rates[tpos[e.i]] += e.rate;
188 lu_solve(lu, piv, rates);
189 for (double p : rates)
190 if (!std::isfinite(p) || p < -1e-9 || p > 1 + 1e-9)
191 throw detail::mam_refusal("Numerical", "QBD absorption probabilities are numerically invalid.");
192 for (std::size_t t = 0; t < transient.size(); ++t) weights[k] += initial_vector[transient[t]] * rates[t];
193 }
194 }
195 {
196 bool ok = !weights.empty();
197 double total = 0.0;
198 for (double w : weights) {
199 ok = ok && std::isfinite(w) && w >= -1e-10;
200 total += w;
201 }
202 if (!ok || std::fabs(total - 1.0) > 1e-8)
203 throw detail::mam_refusal("Numerical", "QBD closed-class weights are numerically invalid.");
204 total = 0.0;
205 for (double& w : weights) {
206 w = std::max(w, 0.0);
207 total += w;
208 }
209 for (double& w : weights) w /= total;
210 }
211 const std::size_t nl = level.states.size();
212 std::vector<double> joint(ns, 0.0);
213 double residual = 0.0;
214 for (std::size_t k = 0; k < closed.size(); ++k) {
215 const int c = closed[k];
216 const double weight = weights[k];
217 std::vector<std::vector<std::size_t>> groups(nl);
218 for (std::size_t i = 0; i < ns; ++i)
219 if (component[i] == c) groups[states[i][position]].push_back(i);
220 long low = -1, high = -1;
221 for (std::size_t n = 0; n < nl; ++n)
222 if (!groups[n].empty()) {
223 if (low < 0) low = static_cast<long>(n);
224 high = static_cast<long>(n);
225 }
226 for (long n = low; n <= high; ++n)
227 if (groups[n].empty()) throw detail::mam_refusal("Model", "A closed QBD class has noncontiguous levels.");
228 std::vector<std::size_t> local(ns, 0);
229 for (const auto& g : groups)
230 for (std::size_t j = 0; j < g.size(); ++j) local[g[j]] = j;
231 double estimate = static_cast<double>(labels.size()) * ns;
232 for (const auto& g : groups) estimate += 4.0 * g.size() * g.size();
233 if (8.0 * estimate > 256.0 * 1024 * 1024)
234 throw detail::mam_refusal("StateSpace", "Reachable QBD blocks exceed 256 MiB.");
235 std::vector<Matrix<double>> diag(nl), up(nl), down(nl);
236 for (std::size_t n = 0; n < nl; ++n) {
237 diag[n] = Matrix<double>(groups[n].size(), groups[n].size(), 0.0);
238 if (n + 1 < nl) up[n] = Matrix<double>(groups[n].size(), groups[n + 1].size(), 0.0);
239 if (n) down[n] = Matrix<double>(groups[n].size(), groups[n - 1].size(), 0.0);
240 }
241 for (std::size_t i = 0; i < ns; ++i) {
242 if (component[i] != c) continue;
243 const std::size_t n = states[i][position], x = local[i];
244 for (const auto& ev : event_rows[i]) {
245 const std::size_t j = std::get<0>(ev);
246 const double rate = std::get<2>(ev);
247 if (i == j) continue;
248 if (component[j] != c) throw detail::mam_refusal("Numerical", "Invalid closed QBD class.");
249 const std::size_t tl = states[j][position], y = local[j];
250 if (tl == n) diag[n](x, y) += rate;
251 else if (tl == n + 1) up[n](x, y) += rate;
252 else down[n](x, y) += rate;
253 }
254 }
255 for (long n = low; n <= high; ++n) {
256 std::vector<double> ex = detail::row_sums(diag[n]);
257 if (n < high) {
258 const std::vector<double> u = detail::row_sums(up[n]);
259 for (std::size_t i = 0; i < ex.size(); ++i) ex[i] += u[i];
260 }
261 if (n > low) {
262 const std::vector<double> d = detail::row_sums(down[n]);
263 for (std::size_t i = 0; i < ex.size(); ++i) ex[i] += d[i];
264 }
265 for (std::size_t i = 0; i < ex.size(); ++i) diag[n](i, i) = -ex[i];
266 }
267 std::vector<Matrix<double>> schur = diag, ratios(nl);
268 std::vector<std::vector<double>> prob(nl);
269 for (std::size_t n = 0; n < nl; ++n) prob[n].assign(groups[n].size(), 0.0);
270 try {
271 for (long n = high - 1; n >= low; --n) {
272 ratios[n] = detail::solve_right(schur[n + 1], detail::scaled(up[n], -1.0));
273 schur[n] = detail::add(schur[n], matmul(ratios[n], down[n + 1]));
274 }
275 prob[low] = detail::stationary(schur[low]);
276 for (long n = low; n < high; ++n) prob[n + 1] = vecmul(prob[n], ratios[n]);
277 } catch (const NumericError&) {
278 throw detail::mam_refusal("Numerical", "Reachable QBD block elimination is singular.");
279 }
280 double total = 0.0;
281 bool negative = false;
282 for (const auto& p : prob)
283 for (double x : p) {
284 total += x;
285 if (x < -1e-10) negative = true;
286 }
287 if (!std::isfinite(total) || total <= 0 || negative)
288 throw detail::mam_refusal("Numerical", "Reachable QBD produced invalid probabilities.");
289 total = 0.0;
290 for (auto& p : prob)
291 for (double& x : p) {
292 x = std::max(x, 0.0);
293 total += x;
294 }
295 for (auto& p : prob)
296 for (double& x : p) x /= total;
297 double class_residual = 0.0, scale = detail::tiny();
298 for (long n = low; n <= high; ++n) {
299 std::vector<double> row = vecmul(prob[n], diag[n]);
300 if (n > low) {
301 const std::vector<double> u = vecmul(prob[n - 1], up[n - 1]);
302 for (std::size_t i = 0; i < row.size(); ++i) row[i] += u[i];
303 }
304 if (n < high) {
305 const std::vector<double> d = vecmul(prob[n + 1], down[n + 1]);
306 for (std::size_t i = 0; i < row.size(); ++i) row[i] += d[i];
307 }
308 for (double x : row) class_residual += std::fabs(x);
309 double mx = -std::numeric_limits<double>::infinity();
310 for (std::size_t i = 0; i < diag[n].rows(); ++i) mx = std::max(mx, -diag[n](i, i));
311 scale = std::max(scale, mx);
312 }
313 if (class_residual > 1e-8 * scale)
314 throw detail::mam_refusal("Numerical", "Reachable QBD residual is too large.");
315 residual += weight * class_residual;
316 for (std::size_t n = 0; n < nl; ++n)
317 for (std::size_t j = 0; j < groups[n].size(); ++j) joint[groups[n][j]] = weight * prob[n][j];
318 }
319 MamResult res;
320 res.level_probabilities.assign(nl, std::vector<double>(phase_states.size(), 0.0));
321 for (std::size_t i = 0; i < ns; ++i) res.level_probabilities[states[i][position]][phase_index[phase_of(states[i])]] = joint[i];
322 std::vector<std::vector<double>> rewards(labels.size(), std::vector<double>(ns, 0.0));
323 for (std::size_t i = 0; i < ns; ++i)
324 for (const auto& ev : event_rows[i]) rewards[std::get<1>(ev)][i] += std::get<2>(ev);
325 for (std::size_t a = 0; a < na; ++a) {
326 const AgentRecord& agent = snapshot.agents[a];
327 for (std::size_t s = 0; s < agent.states.size(); ++s) {
328 double x = 0.0;
329 for (std::size_t i = 0; i < ns; ++i)
330 if (states[i][a] == s) x += joint[i];
331 res.state_table.rows.push_back(StateRow{agent.name, agent.states[s], x});
332 }
333 }
334 for (std::size_t l = 0; l < labels.size(); ++l) {
335 double x = 0.0;
336 for (std::size_t i = 0; i < ns; ++i) x += joint[i] * rewards[l][i];
337 res.action_table.rows.push_back(ActionRow{labels[l], x});
338 }
339 const bool truncated = model.source_truncated;
340 for (TableAttrs* at : {&res.state_table.attrs, &res.action_table.attrs}) {
341 at->method = "reachableqbd";
342 at->exact = !truncated;
343 at->truncated = truncated;
344 }
345 std::vector<std::size_t> phase_agents;
346 for (std::size_t a = 0; a < na; ++a)
347 if (a != position) phase_agents.push_back(a);
348 for (const auto& p : phase_states) res.phase_states.push_back(detail::phase_names_of(snapshot, phase_agents, p));
349 res.method = "reachableqbd";
350 res.exact = !truncated;
351 res.truncated = truncated;
352 res.level_agent = level.name;
353 res.residual = residual;
354 res.reachable_states = ns;
355 res.closed_class_weights = weights;
356 double cartesian = 1.0;
357 for (std::size_t a : phase_agents) cartesian *= static_cast<double>(snapshot.agents[a].states.size());
358 if (8.0 * cartesian * cartesian * (labels.size() + 2.0) <= 32.0 * 1024 * 1024)
359 res.traffic = offered_traffic(snapshot, level.name);
360 return res;
361}
362
363} // namespace lal
364} // namespace line
365
366#endif
InputError(const std::string &what)
Definition error.h:105
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
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
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).
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).
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< T > vecmul(const std::vector< T > &v, const Matrix< T > &A)
Row vector times matrix, v A.
Definition linalg.h:50
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
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::optional< std::vector< double > > initial_distribution
Definition core.h:289
std::string initial
Definition core.h:287
std::vector< std::string > states
Definition core.h:286
std::size_t state_index(const std::string &s) const
Zero-based index of a local state, or npos.
Definition core.h:302
The union of Python's LAL MAM result dataclasses.
Definition mam_common.h:118
std::string level_agent
Definition mam_common.h:119
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::vector< double > closed_class_weights
Definition mam_common.h:136
std::optional< std::size_t > reachable_states
Definition mam_common.h:135
A composition snapshot (core.Model): agents in declaration order plus synchronisations.
Definition core.h:310
std::size_t index_of(const std::string &name) const
Definition core.h:318
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