LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
mam_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_QBD_H
6#define LINE_LANG_LAL_MAM_QBD_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * LINE Agent Language (LAL): exact finite, level-dependent QBD analysis of a
12 * composition (solver_mam/lal_qbd.py).
13 *
14 * The level agent has states n_0,...,n_K. All other agents form the phase.
15 * Events are taken directly from the LAL kernel, including observable
16 * self-events.
17 */
18
19#include <cmath>
20#include <limits>
21#include <optional>
22#include <string>
23#include <utility>
24#include <vector>
25
28
29namespace line {
30namespace lal {
31
32/** Limit value Python spells `10**100`: no limit. */
33static const double kMamNoLimit = std::numeric_limits<double>::infinity();
34
35/** The level agent of a finite QBD, or nullopt and the refusal reason (`structure`). */
36inline std::pair<std::optional<std::string>, std::string> qbd_structure(
37 const Model& snapshot, double max_phases, double max_states,
38 const std::optional<std::string>& level_name = std::nullopt) {
39 std::vector<const AgentRecord*> candidates;
40 for (const AgentRecord& a : snapshot.agents) {
41 if (a.states.size() < 2) continue;
42 bool match;
43 if (level_name) {
44 match = a.name == *level_name;
45 } else {
46 match = true;
47 for (std::size_t i = 0; i < a.states.size(); ++i)
48 if (a.states[i] != "n_" + std::to_string(i)) match = false;
49 }
50 if (match) candidates.push_back(&a);
51 }
52 if (candidates.size() != 1)
53 return {std::nullopt,
54 "Finite QBD requires one level agent with states n_0,...,n_K (K >= 1); "
55 "set lal_level_agent when several agents qualify."};
56 auto positive_int = [](double x) { return x > 0 && (std::isinf(x) || x == std::floor(x)); };
57 if (!positive_int(max_phases) || !positive_int(max_states))
58 return {std::nullopt, "lal_max_phases and lal_max_states must be positive integers."};
59 const AgentRecord& level = *candidates[0];
60 double phases = 1.0;
61 for (const AgentRecord& a : snapshot.agents)
62 if (a.name != level.name) phases *= static_cast<double>(a.states.size());
63 const double states = phases * static_cast<double>(level.states.size());
64 if (phases > max_phases || states > max_states) {
65 auto num = [](double x) {
66 return std::isinf(x) ? std::string("1" + std::string(100, '0')) : std::to_string(static_cast<long long>(x));
67 };
68 return {std::nullopt, "Finite QBD needs " + num(phases) + " phases and " + num(states) +
69 " states; limits are " + num(max_phases) + " and " + num(max_states) + "."};
70 }
71 return {level.name, ""};
72}
73
74namespace detail {
75
76/** Cartesian product of the phase agents' local state indices, last agent fastest. */
77inline std::vector<std::vector<std::size_t>> phase_product(const Model& snapshot,
78 const std::vector<std::size_t>& phase_agents) {
79 std::vector<std::vector<std::size_t>> out{{}};
80 for (std::size_t a : phase_agents) {
81 std::vector<std::vector<std::size_t>> next;
82 for (const auto& prefix : out)
83 for (std::size_t s = 0; s < snapshot.agents[a].states.size(); ++s) {
84 std::vector<std::size_t> p = prefix;
85 p.push_back(s);
86 next.push_back(p);
87 }
88 out.swap(next);
89 }
90 return out;
91}
92
93inline std::size_t flat_index(const std::vector<std::size_t>& idx, const std::vector<std::size_t>& dims) {
94 std::size_t k = 0;
95 for (std::size_t i = 0; i < idx.size(); ++i) k = k * dims[i] + idx[i];
96 return k;
97}
98
99inline std::vector<std::string> phase_names_of(const Model& snapshot, const std::vector<std::size_t>& agents,
100 const std::vector<std::size_t>& phase) {
101 std::vector<std::string> out;
102 for (std::size_t k = 0; k < agents.size(); ++k) out.push_back(snapshot.agents[agents[k]].states[phase[k]]);
103 return out;
104}
105
106} // namespace detail
107
108/** Finite QBD solution of a composition (`lal_qbd.solve_composition`). */
109inline MamResult finite_qbd(const Composition& model, double max_phases = 64, double max_states = 50000,
110 const std::optional<std::string>& level_name = std::nullopt) {
111 const Model snapshot = model.model();
112 const auto st = qbd_structure(snapshot, max_phases, max_states, level_name);
113 if (!st.first) throw detail::mam_refusal("Model", st.second);
114 const std::size_t level_pos = snapshot.index_of(*st.first);
115 const AgentRecord& level_agent = snapshot.agents[level_pos];
116 std::vector<std::size_t> phase_agents, dims;
117 for (std::size_t a = 0; a < snapshot.agents.size(); ++a)
118 if (a != level_pos) {
119 phase_agents.push_back(a);
120 dims.push_back(snapshot.agents[a].states.size());
121 }
122 const std::vector<std::vector<std::size_t>> phases = detail::phase_product(snapshot, phase_agents);
123 const std::size_t m = phases.size(), levels = level_agent.states.size();
124 EventKernel kernel(snapshot);
125 const std::vector<std::string>& labels = kernel.labels;
126 const double estimated = 8.0 * (5.0 * levels * m * m + static_cast<double>(labels.size()) * levels * m);
127 if (estimated > 256.0 * 1024 * 1024)
128 throw detail::mam_refusal("StateSpace", "Finite QBD block storage exceeds 256 MiB.");
129 std::vector<Matrix<double>> diag(levels, Matrix<double>(m, m, 0.0)), up = diag, down = diag;
130 std::vector<Matrix<double>> rewards(labels.size(), Matrix<double>(levels, m, 0.0));
131 std::size_t event_count = 0;
132 for (std::size_t n = 0; n < levels; ++n) {
133 for (std::size_t i = 0; i < m; ++i) {
134 std::vector<std::size_t> state(snapshot.agents.size());
135 for (std::size_t k = 0; k < phase_agents.size(); ++k) state[phase_agents[k]] = phases[i][k];
136 state[level_pos] = n;
137 for (const Move& mv : kernel.outgoing(state)) {
138 if (++event_count > 5000000)
139 throw detail::mam_refusal("StateSpace", "Finite QBD exceeds the event-branch limit.");
140 if (mv.rate <= 0) continue;
141 const long delta = static_cast<long>(mv.target[level_pos]) - static_cast<long>(n);
142 if (std::labs(delta) > 1)
143 throw detail::mam_refusal("Model",
144 "Finite QBD requires every event to change the level by at most one.");
145 std::vector<std::size_t> tp;
146 for (std::size_t a : phase_agents) tp.push_back(mv.target[a]);
147 const std::size_t j = detail::flat_index(tp, dims);
148 rewards[mv.label](n, i) += mv.rate;
149 if (delta == 0) {
150 if (i != j) diag[n](i, j) += mv.rate;
151 } else if (delta == 1) {
152 up[n](i, j) += mv.rate;
153 } else {
154 down[n](i, j) += mv.rate;
155 }
156 }
157 }
158 const std::vector<double> rd = detail::row_sums(diag[n]), ru = detail::row_sums(up[n]),
159 rn = detail::row_sums(down[n]);
160 for (std::size_t i = 0; i < m; ++i) diag[n](i, i) = -(rd[i] + ru[i] + rn[i]);
161 }
162 std::vector<std::vector<std::size_t>> adj(levels * m);
163 for (std::size_t n = 0; n < levels; ++n) {
164 const std::pair<const Matrix<double>*, long> blocks[3] = {
165 {&diag[n], static_cast<long>(n)}, {&up[n], static_cast<long>(n) + 1}, {&down[n], static_cast<long>(n) - 1}};
166 for (const auto& b : blocks) {
167 if (b.second < 0 || b.second >= static_cast<long>(levels)) continue;
168 for (std::size_t i = 0; i < m; ++i)
169 for (std::size_t j = 0; j < m; ++j)
170 if ((*b.first)(i, j) > 0) adj[n * m + i].push_back(static_cast<std::size_t>(b.second) * m + j);
171 }
172 }
173 if (!detail::unique_closed_class(adj))
174 throw detail::mam_refusal("Model",
175 "Finite QBD requires a unique closed class; use SolverCTMC for reducible models "
176 "with multiple closed classes.");
177 std::vector<Matrix<double>> schur = diag;
178 std::vector<Matrix<double>> ratios(levels > 0 ? levels - 1 : 0);
179 std::vector<std::vector<double>> prob(levels, std::vector<double>(m, 0.0));
180 try {
181 for (long n = static_cast<long>(levels) - 2; n >= 0; --n) {
182 ratios[n] = detail::solve_right(schur[n + 1], detail::scaled(up[n], -1.0));
183 schur[n] = detail::add(schur[n], matmul(ratios[n], down[n + 1]));
184 }
185 prob[0] = detail::stationary(schur[0]);
186 for (std::size_t n = 0; n + 1 < levels; ++n) prob[n + 1] = vecmul(prob[n], ratios[n]);
187 } catch (const NumericError&) {
188 throw detail::mam_refusal("Numerical", "Finite QBD block elimination failed due to a singular block.");
189 }
190 double total = 0.0, minimum = std::numeric_limits<double>::infinity();
191 bool finite = true;
192 for (const auto& row : prob)
193 for (double p : row) {
194 finite = finite && std::isfinite(p);
195 total += p;
196 minimum = std::min(minimum, p);
197 }
198 if (!finite || minimum < -1e-10 || total <= 0)
199 throw detail::mam_refusal("Numerical", "Finite QBD produced invalid stationary probabilities.");
200 total = 0.0;
201 for (auto& row : prob)
202 for (double& p : row) {
203 p = std::max(p, 0.0);
204 total += p;
205 }
206 for (auto& row : prob)
207 for (double& p : row) p /= total;
208 double residual = 0.0, scale = detail::tiny();
209 for (std::size_t n = 0; n < levels; ++n) {
210 std::vector<double> r = vecmul(prob[n], diag[n]);
211 if (n) {
212 const std::vector<double> u = vecmul(prob[n - 1], up[n - 1]);
213 for (std::size_t i = 0; i < m; ++i) r[i] += u[i];
214 }
215 if (n + 1 < levels) {
216 const std::vector<double> d = vecmul(prob[n + 1], down[n + 1]);
217 for (std::size_t i = 0; i < m; ++i) r[i] += d[i];
218 }
219 for (double x : r) residual += std::fabs(x);
220 for (std::size_t i = 0; i < m; ++i) scale = std::max(scale, -diag[n](i, i));
221 }
222 if (residual > 1e-8 * scale)
223 throw detail::mam_refusal("Numerical", "Finite QBD residual " + detail::fmt_g(residual) + " is too large.");
224 MamResult res;
225 for (std::size_t a = 0; a < snapshot.agents.size(); ++a) {
226 const AgentRecord& agent = snapshot.agents[a];
227 for (std::size_t s = 0; s < agent.states.size(); ++s) {
228 double p = 0.0;
229 if (a == level_pos) {
230 p = detail::sum(prob[s]);
231 } else {
232 const std::size_t pos = static_cast<std::size_t>(
233 std::find(phase_agents.begin(), phase_agents.end(), a) - phase_agents.begin());
234 for (std::size_t n = 0; n < levels; ++n)
235 for (std::size_t i = 0; i < m; ++i)
236 if (phases[i][pos] == s) p += prob[n][i];
237 }
238 res.state_table.rows.push_back(StateRow{agent.name, agent.states[s], p});
239 }
240 }
241 for (std::size_t l = 0; l < labels.size(); ++l) {
242 double x = 0.0;
243 for (std::size_t n = 0; n < levels; ++n)
244 for (std::size_t i = 0; i < m; ++i) x += prob[n][i] * rewards[l](n, i);
245 res.action_table.rows.push_back(ActionRow{labels[l], x});
246 }
247 const bool truncated = model.source_truncated;
248 for (TableAttrs* at : {&res.state_table.attrs, &res.action_table.attrs}) {
249 at->method = "finiteqbd";
250 at->exact = !truncated;
251 at->truncated = truncated;
252 }
253 if (8.0 * m * m * (labels.size() + 2.0) <= 32.0 * 1024 * 1024)
254 res.traffic = offered_traffic(snapshot, level_agent.name);
255 res.method = "finiteqbd";
256 res.exact = !truncated;
257 res.truncated = truncated;
258 res.level_probabilities = prob;
259 for (const auto& ph : phases) res.phase_states.push_back(detail::phase_names_of(snapshot, phase_agents, ph));
260 res.level_agent = level_agent.name;
261 res.residual = residual;
262 return res;
263}
264
265} // namespace lal
266} // namespace line
267
268#endif
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): shared types and numerical helpers of the SolverMAM LAL paths (python/line...
LINE Agent Language (LAL): independent marked arrival proposals of a finite composition and their exp...
Definition ag.h:49
static const double kMamNoLimit
Limit value Python spells 10**100: no limit.
Definition mam_qbd.h:33
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
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).
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 > 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::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::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
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