LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
ag.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_AG_H
6#define LINE_LANG_LAL_AG_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * LINE Agent Language (LAL): the agent-based (AG) decompositions of a finite
12 * composition, ported from the native Python `solver_ag/lal_rcat.py`,
13 * `lal_certificate.py`, `lal_meanfield.py` and `lal_grouped.py`.
14 *
15 * - `rcat_solve` (`inap` / `inaprc`): the finite-agent RCAT reversed-rate
16 * fixed point. An approximation unless certified.
17 * - `certify` / `certify_result`: a bounded exact-arithmetic RCAT
18 * certificate. Every computation is in `Rational` on the exact binary value
19 * of each double (Python `Fraction.from_float`); candidate rates come from
20 * `limit_denominator`, implemented as Python's `Fraction.limit_denominator`.
21 * - `meanfield_solve`: independent local marginals with the expected-minimum
22 * rule for minimum-rate synchronisation.
23 * - `grouped_solve`: exact within user groups, mean-field across them.
24 * - `compare_with_ctmc`: the numerical comparison against the exact CTMC.
25 *
26 * Python's pandas `attrs` keys beyond the named `TableAttrs` fields
27 * (converged, rcat_residual, product_form_certified, groups,
28 * fixed_point_residual) are carried in `TableAttrs::extra` under the same
29 * names; `diagnostics` holds exactly Python's diagnostics dict.
30 */
31
32#include <algorithm>
33#include <cmath>
34#include <limits>
35#include <map>
36#include <optional>
37#include <set>
38#include <string>
39#include <utility>
40#include <vector>
41
42#include "json.hpp"
44#include "line/lang/lal/core.h"
45#include "line/lang/lal/ctmc.h"
46#include "line/num/number.h"
47
48namespace line {
49namespace lal {
50
51/** One group's joint distribution (`diagnostics['group_distributions']`). */
53 std::vector<std::string> agents; ///< agent names, in group order
54 std::vector<std::vector<std::size_t>> states; ///< local state indices per agent
55 std::vector<double> probabilities;
56};
57
58/**
59 * The result of an AG decomposition (`LALRCATResult`, `LALMeanFieldResult`,
60 * `LALGroupedResult`). The CTMC path returns the same type with only the
61 * `Result` fields set.
62 */
63struct AGResult : Result {
64 std::vector<double> reversed_rates; ///< RCAT effective rates, one per synchronisation
65 double rcat_residual = 0.0;
66 double residual = 0.0; ///< mean-field / grouped fixed-point residual
67 std::optional<std::vector<GroupDistribution>> group_distributions;
68
69 AGResult() = default;
70 explicit AGResult(const Result& r) : Result(r) {}
71};
72
73namespace detail {
74
75inline const double kInf = std::numeric_limits<double>::infinity();
76
77/** Exact rational value of a binary double (Python `Fraction.from_float`). */
78inline Rational exact_rational(double x) {
79 if (!std::isfinite(x)) throw value_error("Cannot convert a non-finite float to a rational");
80 if (x == 0.0) return Rational(0);
81 int e = 0;
82 const double m = std::frexp(x, &e);
83 const long long mant = static_cast<long long>(std::ldexp(m, 53));
84 const int exp2 = e - 53;
85 BigInt num(mant);
86 if (exp2 >= 0) return Rational(BigInt(num << exp2));
87 return Rational(num, BigInt(BigInt(1) << (-exp2)));
88}
89
90inline double to_double(const Rational& r) { return r.convert_to<double>(); }
91
92inline BigInt floor_div(const BigInt& n, const BigInt& d) {
93 BigInt q = n / d;
94 if ((n % d != 0) && ((n < 0) != (d < 0))) q -= 1;
95 return q;
96}
97
98/** Python `Fraction.limit_denominator`. */
99inline Rational limit_denominator(const Rational& x, const BigInt& max_denominator) {
100 if (max_denominator < 1) throw value_error("max_denominator should be at least 1");
101 const BigInt num = boost::multiprecision::numerator(x);
102 const BigInt den = boost::multiprecision::denominator(x);
103 if (den <= max_denominator) return x;
104 BigInt p0 = 0, q0 = 1, p1 = 1, q1 = 0;
105 BigInt n = num, d = den;
106 while (true) {
107 const BigInt a = floor_div(n, d);
108 const BigInt q2 = q0 + a * q1;
109 if (q2 > max_denominator) break;
110 const BigInt np1 = p0 + a * p1;
111 p0 = p1;
112 q0 = q1;
113 p1 = np1;
114 q1 = q2;
115 const BigInt nd = n - a * d;
116 n = d;
117 d = nd;
118 }
119 const BigInt k = floor_div(max_denominator - q0, q1);
120 const Rational bound1(BigInt(p0 + k * p1), BigInt(q0 + k * q1));
121 const Rational bound2(p1, q1);
122 const Rational e2 = abs(Rational(bound2 - x));
123 const Rational e1 = abs(Rational(bound1 - x));
124 return e2 <= e1 ? bound2 : bound1;
125}
126
127inline std::size_t bit_length(const BigInt& v) {
128 if (v == 0) return 0;
129 const BigInt a = v < 0 ? BigInt(-v) : v;
130 return static_cast<std::size_t>(boost::multiprecision::msb(a)) + 1;
131}
132
133/** One strongly connected class over the nonzero off-diagonal entries. */
134inline bool irreducible(const Matrix<double>& m) {
135 const std::size_t n = m.rows();
136 std::vector<std::vector<std::size_t>> adj(n);
137 for (std::size_t i = 0; i < n; ++i)
138 for (std::size_t j = 0; j < n; ++j)
139 if (i != j && m(i, j) != 0) adj[i].push_back(j);
140 int count = 0;
141 strong_components(adj, count);
142 return count == 1;
143}
144
145/** Stationary vector of the generator with off-diagonal rates `off`; refuses a reducible chain. */
146inline std::vector<double> local_stationary(Matrix<double> off, const std::string& refusal) {
147 const std::size_t n = off.rows();
148 for (std::size_t i = 0; i < n; ++i) off(i, i) = 0.0;
149 if (!irreducible(off)) throw UnsupportedError(ErrorKind("ReducibleCTMC"), refusal);
150 for (std::size_t i = 0; i < n; ++i) {
151 double s = 0.0;
152 for (std::size_t j = 0; j < n; ++j) s += off(i, j);
153 off(i, i) = -s;
154 }
155 return mc::ctmc_solve(off);
156}
157
158inline std::vector<std::string> active_actions(const AgentRecord& agent) {
159 std::vector<std::string> out;
160 for (const Transition& t : agent.transitions)
161 if (t.role == Role::Active && std::find(out.begin(), out.end(), t.action) == out.end())
162 out.push_back(t.action);
163 return out;
164}
165
166inline Matrix<double> block_of(const AgentRecord& agent, const std::string& action, Role role) {
167 const std::size_t n = agent.states.size();
168 Matrix<double> b(n, n, 0.0);
169 for (const Transition& t : agent.transitions)
170 if (t.role == role && t.action == action) b(agent.state_index(t.source), agent.state_index(t.target)) += t.value;
171 return b;
172}
173
174inline nlohmann::json endpoint_json(const Endpoint& e) { return nlohmann::json::array({e.first, e.second}); }
175
176inline std::string join_label(const nlohmann::json& e) {
177 return e[0].get<std::string>() + "." + e[1].get<std::string>();
178}
179
180inline nlohmann::json vec_json(const std::vector<double>& v) {
181 nlohmann::json a = nlohmann::json::array();
182 for (double x : v) a.push_back(x);
183 return a;
184}
185
186inline double l1_diff(const std::vector<double>& a, const std::vector<double>& b) {
187 double s = 0.0;
188 for (std::size_t i = 0; i < a.size(); ++i) s += std::abs(a[i] - b[i]);
189 return s;
190}
191
192inline std::vector<double> rowvec_mul(const std::vector<double>& p, const Matrix<double>& m) {
193 std::vector<double> out(m.cols(), 0.0);
194 for (std::size_t i = 0; i < m.rows(); ++i)
195 for (std::size_t j = 0; j < m.cols(); ++j) out[j] += p[i] * m(i, j);
196 return out;
197}
198
199/** Row-normalise a block; returns the row totals. */
200inline std::vector<double> normalise_rows(Matrix<double>& b) {
201 std::vector<double> totals(b.rows(), 0.0);
202 for (std::size_t i = 0; i < b.rows(); ++i) {
203 for (std::size_t j = 0; j < b.cols(); ++j) totals[i] += b(i, j);
204 for (std::size_t j = 0; j < b.cols(); ++j) b(i, j) = totals[i] > 0 ? b(i, j) / totals[i] : 0.0;
205 }
206 return totals;
207}
208
209inline nlohmann::json group_json(const std::vector<GroupDistribution>& groups) {
210 nlohmann::json out = nlohmann::json::array();
211 for (const GroupDistribution& g : groups)
212 out.push_back({{"agents", g.agents}, {"states", g.states}, {"probabilities", g.probabilities}});
213 return out;
214}
215
216inline void check_iteration(double tol, long max_iter, const std::string& what) {
217 if (!std::isfinite(tol) || tol <= 0 || max_iter <= 0)
218 throw value_error(what + " tolerance and maximum iterations must be positive");
219}
220
221} // namespace detail
222
223/** The lowering of a minimum-rate synchronisation (`_lower_minimum`). */
224struct Lowering {
225 std::optional<Model> model; ///< nullopt when lowering is impossible
226 std::string reason; ///< why, when `model` is nullopt
227 nlohmann::json transformations = nlohmann::json::array();
228};
229
230/** Lower a provably dominated minimum without changing its event law (`_lower_minimum`). */
231inline Lowering lower_minimum(const Model& snapshot) {
232 Lowering out;
233 Model lowered = snapshot;
234 for (const MinSync& ms : snapshot.min_syncs) {
235 std::vector<std::vector<Rational>> rates;
236 for (const Endpoint& ep : ms.active) {
237 const AgentRecord& agent = snapshot.agents[snapshot.index_of(ep.first)];
238 std::vector<Rational> totals;
239 for (const std::string& state : agent.states) {
240 Rational s(0);
241 for (const Transition& t : agent.transitions)
242 if (t.role == Role::Active && t.action == ep.second && t.source == state)
243 s += detail::exact_rational(t.value);
244 totals.push_back(s);
245 }
246 for (const Rational& v : totals)
247 if (v <= 0) {
248 out.reason = "AG minimum-rate lowering requires each supplier to be enabled in every state.";
249 return out;
250 }
251 rates.push_back(totals);
252 }
253 std::optional<std::size_t> bottleneck;
254 for (std::size_t i = 0; i < rates.size() && !bottleneck; ++i) {
255 const Rational mx = *std::max_element(rates[i].begin(), rates[i].end());
256 bool ok = true;
257 for (std::size_t j = 0; j < rates.size(); ++j)
258 if (j != i && !(mx <= *std::min_element(rates[j].begin(), rates[j].end()))) ok = false;
259 if (ok) bottleneck = i;
260 }
261 if (!bottleneck) {
262 out.reason =
263 "AG minimum-rate lowering requires one supplier to be the bottleneck in every combination of local states.";
264 return out;
265 }
266 const Endpoint trigger = ms.active[*bottleneck];
267 std::vector<Endpoint> others;
268 for (std::size_t i = 0; i < ms.active.size(); ++i)
269 if (i != *bottleneck) others.push_back(ms.active[i]);
270 for (const Endpoint& ep : others) {
271 AgentRecord& agent = lowered.agents[lowered.index_of(ep.first)];
272 std::vector<Transition> kept;
273 for (const Transition& t : agent.transitions) {
274 const bool member = t.action == ep.second && t.role == Role::Active;
275 if (member && t.value == 0) continue;
276 Transition c = t;
277 if (member) c.role = Role::Passive;
278 kept.push_back(c);
279 }
280 agent.transitions = kept;
281 }
282 Sync s;
283 s.active = trigger;
284 s.passive = others;
285 s.passive.insert(s.passive.end(), ms.passive.begin(), ms.passive.end());
286 lowered.syncs.push_back(s);
287 nlohmann::json others_json = nlohmann::json::array();
288 for (const Endpoint& e : others) others_json.push_back(detail::endpoint_json(e));
289 out.transformations.push_back({{"type", "dominated_minimum"},
290 {"active", detail::endpoint_json(trigger)},
291 {"event_label", detail::endpoint_json(ms.active.front())},
292 {"other_suppliers", others_json}});
293 }
294 lowered.min_syncs.clear();
295 out.model = lowered;
296 return out;
297}
298
299/** A support answer: `(ok, reason)`. */
300struct Support {
301 bool ok = true;
302 std::optional<std::string> reason;
303};
304
305/** Decomposition constraints checked without a global state space (`structural_support`). */
306inline Support structural_support(const Model& original, const std::string& method = "inaprc") {
307 validate_model(original);
308 const Lowering low = lower_minimum(original);
309 if (!low.model) return {false, low.reason};
310 const Model& snapshot = *low.model;
311 for (const Sync& s : snapshot.syncs)
312 for (const Endpoint& p : s.passive) {
313 const AgentRecord& agent = snapshot.agents[snapshot.index_of(p.first)];
314 std::set<std::string> enabled;
315 for (const Transition& t : agent.transitions)
316 if (t.role == Role::Passive && t.action == p.second && t.value > 0) enabled.insert(t.source);
317 for (const std::string& st : agent.states)
318 if (!enabled.count(st))
319 return {false, "SolverAG LAL " + method + " requires " + p.first + "." + p.second +
320 " to be enabled in every state; use the finite CTMC path for blocking interactions."};
321 }
322 for (const AgentRecord& agent : snapshot.agents) {
323 const std::size_t n = agent.states.size();
324 Matrix<double> g(n, n, 0.0);
325 for (const Transition& t : agent.transitions)
326 if (t.value > 0 && t.source != t.target) g(agent.state_index(t.source), agent.state_index(t.target)) = 1;
327 if (!detail::irreducible(g))
328 return {false, "SolverAG LAL " + method + " requires an irreducible isolated agent; " + agent.name +
329 " is structurally reducible."};
330 }
331 return {true, std::nullopt};
332}
333
334/** The certificate's conservative structural prerequisites (`certificate_support`). */
335inline Support certificate_support(const Model& original) {
336 const Lowering low = lower_minimum(original);
337 if (!low.model) return {false, low.reason};
338 const Model& snapshot = *low.model;
339 bool large = snapshot.syncs.size() > 12;
340 for (const AgentRecord& a : snapshot.agents)
341 if (a.states.size() > 12) large = true;
342 if (large) return {false, std::string("Certificate supports at most 12 actions and 12 states per finite agent.")};
343 std::set<Endpoint> synced;
344 for (const Sync& s : snapshot.syncs) synced.insert(s.active);
345 for (const AgentRecord& agent : snapshot.agents) {
346 const std::size_t n = agent.states.size();
347 Matrix<double> g(n, n, 0.0);
348 for (const Transition& t : agent.transitions)
349 if (t.role == Role::Active && !synced.count(Endpoint(agent.name, t.action)) && t.source != t.target &&
350 t.value > 0)
351 g(agent.state_index(t.source), agent.state_index(t.target)) = 1;
352 if (!detail::irreducible(g)) {
353 double prod = 1.0;
354 for (const AgentRecord& a : snapshot.agents) prod *= static_cast<double>(a.states.size());
355 if (prod > 10000)
356 return {false, std::string("Autonomous transitions are not irreducible and full reachability "
357 "exceeds the 10000-state certificate limit.")};
358 }
359 }
360 return {true, std::nullopt};
361}
362
363/** Whether one initial state reaches the whole Cartesian space (`full_reachability`). */
364inline Support full_reachability(const Model& snapshot, std::size_t limit = 10000) {
365 std::size_t count = 1;
366 bool over = false;
367 for (const AgentRecord& a : snapshot.agents) {
368 count *= a.states.size();
369 if (count > limit) over = true;
370 }
371 if (over)
372 return {false, "Full Cartesian reachability exceeds the " + std::to_string(limit) + "-state certificate limit."};
373 EventKernel kernel(snapshot);
374 std::vector<std::size_t> initial;
375 for (const AgentRecord& a : snapshot.agents) initial.push_back(a.state_index(a.initial));
376 std::set<std::vector<std::size_t>> seen{initial};
377 std::vector<std::vector<std::size_t>> frontier{initial};
378 for (std::size_t f = 0; f < frontier.size(); ++f) {
379 const std::vector<Move> moves = kernel.outgoing(frontier[f]);
380 for (const Move& m : moves)
381 if (m.rate > 0 && !seen.count(m.target)) {
382 seen.insert(m.target);
383 frontier.push_back(m.target);
384 }
385 }
386 if (seen.size() != count)
387 return {false, "Only " + std::to_string(seen.size()) + " of " + std::to_string(count) +
388 " Cartesian states are reachable; global irreducibility was not established."};
389 return {true, std::nullopt};
390}
391
392namespace detail {
393
394typedef std::vector<std::vector<Rational>> RMatrix;
395
396/** Exact stationary vector of a rational generator, or nullopt (`_stationary`). */
397inline std::optional<std::vector<Rational>> exact_stationary(const RMatrix& q) {
398 const std::size_t n = q.size();
399 RMatrix m;
400 for (std::size_t i = 0; i + 1 < n; ++i) {
401 std::vector<Rational> row;
402 for (std::size_t j = 0; j < n; ++j) row.push_back(q[j][i]);
403 row.push_back(Rational(0));
404 m.push_back(row);
405 }
406 m.push_back(std::vector<Rational>(n + 1, Rational(1)));
407 for (std::size_t col = 0; col < n; ++col) {
408 std::optional<std::size_t> pivot;
409 for (std::size_t i = col; i < n; ++i)
410 if (m[i][col] != 0) {
411 pivot = i;
412 break;
413 }
414 if (!pivot) return std::nullopt;
415 std::swap(m[col], m[*pivot]);
416 const Rational scale = m[col][col];
417 for (Rational& v : m[col]) v /= scale;
418 for (std::size_t row = 0; row < n; ++row) {
419 if (row == col) continue;
420 const Rational s = m[row][col];
421 if (s != 0)
422 for (std::size_t j = 0; j <= n; ++j) m[row][j] -= s * m[col][j];
423 }
424 for (const auto& row : m)
425 for (const Rational& v : row)
426 if (bit_length(BigInt(boost::multiprecision::numerator(v))) > 4096 ||
427 bit_length(BigInt(boost::multiprecision::denominator(v))) > 4096)
428 return std::nullopt;
429 }
430 std::vector<Rational> result;
431 for (const auto& row : m) result.push_back(row[n]);
432 for (const Rational& v : result)
433 if (!(v > 0)) return std::nullopt;
434 return result;
435}
436
437} // namespace detail
438
439/** A successful RCAT certificate. */
441 std::vector<Rational> rates;
442 std::vector<std::vector<Rational>> marginals;
443 std::string irreducibility; ///< "autonomous" or "full_reachability"
444};
445
446/** Try a bounded exact certificate; failure is not a counterexample (`certify`). */
447inline std::pair<std::optional<Certificate>, std::string> certify(const Model& snapshot,
448 const std::vector<double>& estimated_rates,
449 double tol) {
450 typedef std::pair<std::optional<Certificate>, std::string> Out;
451 const std::vector<AgentRecord>& agents = snapshot.agents;
452 bool large = !snapshot.min_syncs.empty() || snapshot.syncs.size() > 12;
453 for (const AgentRecord& a : agents)
454 if (a.states.size() > 12) large = true;
455 if (large) return Out(std::nullopt, "Certificate supports at most 12 actions and 12 states per finite agent.");
456 std::set<Endpoint> active_synced;
457 for (const Sync& s : snapshot.syncs) active_synced.insert(s.active);
458 std::vector<detail::RMatrix> local;
459 bool autonomous = true;
460 for (const AgentRecord& agent : agents) {
461 const std::size_t n = agent.states.size();
462 detail::RMatrix l(n, std::vector<Rational>(n, Rational(0)));
463 for (const Transition& t : agent.transitions)
464 if (t.role == Role::Active && !active_synced.count(Endpoint(agent.name, t.action)))
465 l[agent.state_index(t.source)][agent.state_index(t.target)] += detail::exact_rational(t.value);
466 Matrix<double> g(n, n, 0.0);
467 for (std::size_t i = 0; i < n; ++i)
468 for (std::size_t j = 0; j < n; ++j) g(i, j) = (i != j && l[i][j] > 0) ? 1.0 : 0.0;
469 if (!detail::irreducible(g)) autonomous = false;
470 local.push_back(l);
471 }
472 struct RAction {
473 std::size_t ai;
474 detail::RMatrix active;
475 std::vector<std::pair<std::size_t, detail::RMatrix>> partners;
476 };
477 std::vector<RAction> actions;
478 for (const Sync& s : snapshot.syncs) {
479 RAction act;
480 act.ai = snapshot.index_of(s.active.first);
481 auto build = [&](std::size_t k, const std::string& label, Role role) -> detail::RMatrix {
482 const AgentRecord& a = agents[k];
483 const std::size_t n = a.states.size();
484 detail::RMatrix b(n, std::vector<Rational>(n, Rational(0)));
485 for (const Transition& t : a.transitions)
486 if (t.role == role && t.action == label)
487 b[a.state_index(t.source)][a.state_index(t.target)] += detail::exact_rational(t.value);
488 return b;
489 };
490 act.active = build(act.ai, s.active.second, Role::Active);
491 for (const Endpoint& p : s.passive) {
492 const std::size_t k = snapshot.index_of(p.first);
493 detail::RMatrix b = build(k, p.second, Role::Passive);
494 for (auto& row : b) {
495 Rational total(0);
496 for (const Rational& v : row) total += v;
497 if (total <= 0) return Out(std::nullopt, "A passive action is disabled.");
498 for (Rational& v : row) v /= total;
499 }
500 act.partners.push_back({k, b});
501 }
502 actions.push_back(std::move(act));
503 }
504 std::vector<std::vector<Rational>> candidates;
505 for (double value : estimated_rates) {
506 if (!std::isfinite(value) || value <= 0) return Out(std::nullopt, "A positive finite reversed rate is required.");
507 std::vector<Rational> values;
508 const Rational exact = detail::exact_rational(value);
509 for (long den : {1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L}) {
510 const Rational x = detail::limit_denominator(exact, BigInt(den));
511 if (x > 0 && std::abs(detail::to_double(x) - value) <= std::max(10 * tol, 1e-12) &&
512 std::find(values.begin(), values.end(), x) == values.end())
513 values.push_back(x);
514 }
515 if (values.empty()) return Out(std::nullopt, "No bounded rational rate candidate matches the fixed point.");
516 candidates.push_back(values);
517 }
518 // itertools.product order: the last factor varies fastest.
519 std::vector<std::size_t> idx(candidates.size(), 0);
520 bool exhausted = false;
521 for (std::size_t attempt = 0; !exhausted; ++attempt) {
522 if (attempt >= 128) return Out(std::nullopt, "Rational-rate candidate search exceeds its limit.");
523 std::vector<Rational> rates;
524 for (std::size_t c = 0; c < candidates.size(); ++c) rates.push_back(candidates[c][idx[c]]);
525 // advance for the next attempt
526 {
527 std::size_t d = idx.size();
528 exhausted = true;
529 while (d > 0) {
530 --d;
531 if (++idx[d] < candidates[d].size()) {
532 exhausted = false;
533 break;
534 }
535 idx[d] = 0;
536 }
537 }
538 std::vector<std::vector<Rational>> marginals;
539 for (std::size_t k = 0; k < agents.size(); ++k) {
540 const std::size_t n = agents[k].states.size();
541 detail::RMatrix off = local[k];
542 for (std::size_t r = 0; r < actions.size(); ++r) {
543 if (actions[r].ai == k)
544 for (std::size_t i = 0; i < n; ++i)
545 for (std::size_t j = 0; j < n; ++j) off[i][j] += actions[r].active[i][j];
546 for (const auto& pp : actions[r].partners)
547 if (pp.first == k)
548 for (std::size_t i = 0; i < n; ++i)
549 for (std::size_t j = 0; j < n; ++j) off[i][j] += rates[r] * pp.second[i][j];
550 }
551 for (std::size_t i = 0; i < n; ++i) {
552 off[i][i] = 0;
553 Rational s(0);
554 for (std::size_t j = 0; j < n; ++j) s += off[i][j];
555 off[i][i] = -s;
556 }
557 const std::optional<std::vector<Rational>> pi = detail::exact_stationary(off);
558 if (!pi) break;
559 marginals.push_back(*pi);
560 }
561 if (marginals.size() != agents.size()) continue;
562 bool balanced = true;
563 for (std::size_t r = 0; r < actions.size() && balanced; ++r) {
564 const detail::RMatrix& act = actions[r].active;
565 const std::vector<Rational>& m = marginals[actions[r].ai];
566 for (std::size_t j = 0; j < act.size() && balanced; ++j) {
567 Rational s(0);
568 for (std::size_t i = 0; i < act.size(); ++i) s += m[i] * act[i][j];
569 if (s != rates[r] * m[j]) balanced = false;
570 }
571 }
572 if (!balanced) continue;
573 // Multi-way product balance has cross terms for passive marginals.
574 // Requiring all but at most one passive kernel to preserve its local
575 // marginal makes every such cross term vanish exactly.
576 bool valid = true;
577 for (const RAction& act : actions) {
578 int noninvariant = 0;
579 for (const auto& pp : act.partners) {
580 const std::vector<Rational>& m = marginals[pp.first];
581 const detail::RMatrix& P = pp.second;
582 bool moved = false;
583 for (std::size_t j = 0; j < P.size() && !moved; ++j) {
584 Rational s(0);
585 for (std::size_t i = 0; i < P.size(); ++i) s += m[i] * P[i][j];
586 if (s != m[j]) moved = true;
587 }
588 if (moved) ++noninvariant;
589 }
590 if (noninvariant > 1) {
591 valid = false;
592 break;
593 }
594 }
595 if (!valid) continue;
596 if (!autonomous) {
597 const Support connected = full_reachability(snapshot);
598 if (!connected.ok) return Out(std::nullopt, *connected.reason);
599 }
600 // Positive product-form stationary mass and full reachability from
601 // one state imply that the finite global chain is irreducible.
602 Certificate c;
603 c.rates = rates;
604 c.marginals = marginals;
605 c.irreducibility = autonomous ? "autonomous" : "full_reachability";
606 return Out(c, std::string());
607 }
608 return Out(std::nullopt, "No candidate satisfies the exact reversed-rate and multi-party balance conditions.");
609}
610
611/**
612 * Finite-agent RCAT fixed point (`lal_rcat.solve_composition`), method `inap`
613 * or `inaprc`. Passive actions must be enabled in every local state.
614 */
615inline AGResult rcat_solve(const Model& original, double tol = 1e-4, long max_iter = 100,
616 const std::string& method = "inaprc") {
617 validate_model(original);
618 if (method != "inap" && method != "inaprc") throw value_error("finite LAL RCAT method must be inap or inaprc");
619 const Support support = structural_support(original, method);
620 if (!support.ok) throw UnsupportedError(ErrorKind("Synchronization"), *support.reason);
621 const Lowering low = lower_minimum(original);
622 const Model& snapshot = *low.model;
623 std::map<std::string, std::string> renames;
624 for (const auto& t : low.transformations) renames[detail::join_label(t["active"])] = detail::join_label(t["event_label"]);
625 auto rename = [&](const std::string& l) {
626 auto it = renames.find(l);
627 return it == renames.end() ? l : it->second;
628 };
629 detail::check_iteration(tol, max_iter, "RCAT");
630 const std::vector<AgentRecord>& agents = snapshot.agents;
631 const std::size_t K = agents.size();
632 std::set<Endpoint> active_synced;
633 for (const Sync& s : snapshot.syncs) active_synced.insert(s.active);
634 std::vector<Matrix<double>> local;
635 for (const AgentRecord& agent : agents) {
636 const std::size_t n = agent.states.size();
637 Matrix<double> l(n, n, 0.0);
638 for (const Transition& t : agent.transitions)
639 if (t.role == Role::Active && !active_synced.count(Endpoint(agent.name, t.action)))
640 l(agent.state_index(t.source), agent.state_index(t.target)) += t.value;
641 local.push_back(l);
642 }
643 struct Act {
644 std::size_t ai;
645 std::vector<std::pair<std::size_t, Matrix<double>>> partners;
646 Matrix<double> active;
647 std::string label;
648 };
649 std::vector<Act> actions;
650 for (const Sync& s : snapshot.syncs) {
651 Act a;
652 a.ai = snapshot.index_of(s.active.first);
653 a.active = detail::block_of(agents[a.ai], s.active.second, Role::Active);
654 for (const Endpoint& p : s.passive) {
655 const std::size_t pi = snapshot.index_of(p.first);
656 Matrix<double> m = detail::block_of(agents[pi], p.second, Role::Passive);
657 const std::vector<double> totals = detail::normalise_rows(m);
658 for (double t : totals)
659 if (t <= 0)
660 throw UnsupportedError(ErrorKind("Blocking"), p.first + "." + p.second + " must be enabled in every state.");
661 a.partners.push_back({pi, m});
662 }
663 a.label = rename(endpoint_label(s.active));
664 actions.push_back(std::move(a));
665 }
666 auto stationary = [&](const std::vector<double>& rates) {
667 std::vector<std::vector<double>> results;
668 for (std::size_t k = 0; k < K; ++k) {
669 Matrix<double> off = local[k];
670 for (std::size_t r = 0; r < actions.size(); ++r) {
671 const Act& a = actions[r];
672 if (a.ai == k)
673 for (std::size_t i = 0; i < off.size(); ++i) off[i] += a.active[i];
674 for (const auto& pp : a.partners)
675 if (pp.first == k)
676 for (std::size_t i = 0; i < off.size(); ++i) off[i] += rates[r] * pp.second[i];
677 }
678 results.push_back(detail::local_stationary(
679 off, "SolverAG LAL " + method + " requires an irreducible isolated agent; " + agents[k].name +
680 " is reducible."));
681 }
682 return results;
683 };
684 std::vector<double> rates(actions.size(), 1.0);
685 bool converged = actions.empty();
686 long iterations = 0;
687 double diff = 0.0;
688 std::vector<std::vector<double>> marginals = stationary(rates);
689 if (!actions.empty()) {
690 for (iterations = 1; iterations <= max_iter; ++iterations) {
691 std::vector<double> new_rates;
692 for (const Act& a : actions) {
693 const std::vector<double>& m = marginals[a.ai];
694 const std::vector<double> incoming = detail::rowvec_mul(m, a.active);
695 double new_rate = 0.0;
696 if (method == "inaprc") {
697 for (double x : incoming) new_rate += x;
698 } else {
699 double sum = 0.0;
700 std::size_t cnt = 0;
701 for (std::size_t j = 0; j < incoming.size(); ++j) {
702 double col = 0.0;
703 for (std::size_t i = 0; i < a.active.rows(); ++i) col += a.active(i, j);
704 if (col > 0 && m[j] > 0 && incoming[j] > 0) {
705 sum += incoming[j] / m[j];
706 ++cnt;
707 }
708 }
709 new_rate = cnt ? sum / static_cast<double>(cnt) : 0.0;
710 }
711 new_rates.push_back(new_rate);
712 }
713 const std::vector<std::vector<double>> next = stationary(new_rates);
714 double dr = 0.0, dm = 0.0;
715 for (std::size_t r = 0; r < rates.size(); ++r) dr = std::max(dr, std::abs(new_rates[r] - rates[r]));
716 for (std::size_t k = 0; k < K; ++k) dm = std::max(dm, detail::l1_diff(next[k], marginals[k]));
717 diff = std::max(dr, dm);
718 rates = new_rates;
719 marginals = next;
720 if (diff <= tol) {
721 converged = true;
722 break;
723 }
724 }
725 if (iterations > max_iter) iterations = max_iter;
726 }
727 double residual = 0.0;
728 for (std::size_t r = 0; r < actions.size(); ++r) {
729 const std::vector<double>& m = marginals[actions[r].ai];
730 const std::vector<double> in = detail::rowvec_mul(m, actions[r].active);
731 double s = 0.0;
732 for (std::size_t j = 0; j < in.size(); ++j) s += std::abs(in[j] - rates[r] * m[j]);
733 residual = std::max(residual, s);
734 }
735 nlohmann::json action_diag = nlohmann::json::array();
736 bool pairwise = true;
737 for (std::size_t r = 0; r < actions.size(); ++r) {
738 const Act& a = actions[r];
739 if (a.partners.size() != 1) pairwise = false;
740 const std::vector<double>& m = marginals[a.ai];
741 const std::vector<double> in = detail::rowvec_mul(m, a.active);
742 std::vector<double> rev(in.size());
743 bool finite = true;
744 for (std::size_t j = 0; j < in.size(); ++j) {
745 rev[j] = m[j] > 0 ? in[j] / m[j] : std::numeric_limits<double>::quiet_NaN();
746 if (!std::isfinite(rev[j])) finite = false;
747 }
748 double rres = detail::kInf;
749 if (finite) {
750 rres = 0.0;
751 for (double x : rev) rres = std::max(rres, std::abs(x - rates[r]));
752 }
753 nlohmann::json passive_agents = nlohmann::json::array();
754 for (const auto& pp : a.partners) passive_agents.push_back(agents[pp.first].name);
755 action_diag.push_back({{"action", a.label},
756 {"active_agent", agents[a.ai].name},
757 {"passive_agent", a.partners.size() == 1 ? nlohmann::json(agents[a.partners[0].first].name)
758 : nlohmann::json(nullptr)},
759 {"passive_agents", passive_agents},
760 {"effective_rate", rates[r]},
761 {"reversed_rates_by_state", detail::vec_json(rev)},
762 {"reversed_rate_residual", rres}});
763 }
764 nlohmann::json autonomous = nlohmann::json::object();
765 for (std::size_t k = 0; k < K; ++k) autonomous[agents[k].name] = detail::irreducible(local[k]);
766 AGResult res;
767 res.method = method;
768 res.exact = false;
769 res.converged = converged;
770 res.iterations = static_cast<int>(iterations);
771 res.reversed_rates = rates;
772 res.rcat_residual = residual;
773 // Both structural flags hold whenever this point is reached: structural_support
774 // refused the model above otherwise, so they record that gate.
775 res.diagnostics = {{"structural_conditions",
776 {{"pairwise", pairwise}, {"passive_always_enabled", true}, {"isolated_agents_irreducible", true}}},
777 {"transformations", low.transformations},
778 {"autonomous_irreducible", autonomous},
779 {"actions", action_diag},
780 {"fixed_point_change", diff},
781 {"product_form_certified", false},
782 {"certificate_reason",
783 "Numerical residuals alone do not establish all product-form conditions or global uniqueness."}};
784 for (std::size_t k = 0; k < K; ++k)
785 for (std::size_t j = 0; j < agents[k].states.size(); ++j)
786 res.state_table.rows.push_back({agents[k].name, agents[k].states[j], marginals[k][j]});
787 std::map<std::string, double> by_label;
788 for (std::size_t k = 0; k < K; ++k)
789 for (const std::string& label : detail::active_actions(agents[k])) {
790 double rate = 0.0;
791 for (const Transition& t : agents[k].transitions)
792 if (t.role == Role::Active && t.action == label)
793 rate += marginals[k][agents[k].state_index(t.source)] * t.value;
794 by_label[rename(agents[k].name + "." + label)] = rate;
795 }
796 EventKernel original_kernel(original);
797 for (const std::string& label : original_kernel.labels) res.action_table.rows.push_back({label, by_label.at(label)});
798 res.state_table.attrs.method = method;
799 res.state_table.attrs.exact = false;
800 res.state_table.attrs.extra = {{"converged", converged}, {"rcat_residual", residual}, {"product_form_certified", false}};
802 return res;
803}
804
805/** Replace an approximate solution with an exactly verified RCAT solution (`certify_result`). */
806inline std::pair<bool, std::string> certify_result(const Model& original, AGResult& result, double tol) {
807 if (!result.converged) return {false, "The reversed-rate fixed point did not converge."};
808 const Lowering low = lower_minimum(original);
809 if (!low.model) return {false, low.reason};
810 const Model& snapshot = *low.model;
811 const auto proof = certify(snapshot, result.reversed_rates, tol);
812 if (!proof.first) return {false, proof.second};
813 const Certificate& cert = *proof.first;
814 const std::vector<AgentRecord>& agents = snapshot.agents;
815 result.reversed_rates.clear();
816 for (const Rational& r : cert.rates) result.reversed_rates.push_back(detail::to_double(r));
817 std::size_t row = 0;
818 for (const auto& marginal : cert.marginals)
819 for (const Rational& v : marginal) result.state_table.rows[row++].probability = detail::to_double(v);
820 std::map<std::string, std::string> renames;
821 for (const auto& t : result.diagnostics.value("transformations", nlohmann::json::array()))
822 renames[detail::join_label(t["active"])] = detail::join_label(t["event_label"]);
823 std::map<std::string, double> throughputs;
824 for (std::size_t k = 0; k < agents.size(); ++k)
825 for (const std::string& label : detail::active_actions(agents[k])) {
826 Rational v(0);
827 for (const Transition& t : agents[k].transitions)
828 if (t.role == Role::Active && t.action == label)
829 v += cert.marginals[k][agents[k].state_index(t.source)] * detail::exact_rational(t.value);
830 const std::string key = agents[k].name + "." + label;
831 auto it = renames.find(key);
832 throughputs[it == renames.end() ? key : it->second] = detail::to_double(v);
833 }
834 for (ActionRow& r : result.action_table.rows) r.throughput = throughputs.at(r.action);
835 result.rcat_residual = 0.0;
836 result.exact = true;
837 result.method = "rcat";
838 nlohmann::json rate_strings = nlohmann::json::array();
839 for (const Rational& r : cert.rates) rate_strings.push_back(r.str());
840 result.diagnostics["product_form_certified"] = true;
841 result.diagnostics["certificate_reason"] = nullptr;
842 result.diagnostics["certificate_type"] = "exact rational local balance";
843 result.diagnostics["irreducibility_proof"] = cert.irreducibility;
844 result.diagnostics["certificate_rates"] = rate_strings;
845 nlohmann::json& acts = result.diagnostics["actions"];
846 for (std::size_t r = 0; r < acts.size() && r < cert.rates.size(); ++r) {
847 const double rate = detail::to_double(cert.rates[r]);
848 acts[r]["effective_rate"] = rate;
849 nlohmann::json filled = nlohmann::json::array();
850 for (std::size_t j = 0; j < acts[r]["reversed_rates_by_state"].size(); ++j) filled.push_back(rate);
851 acts[r]["reversed_rates_by_state"] = filled;
852 acts[r]["reversed_rate_residual"] = 0.0;
853 }
854 for (TableAttrs* a : {&result.state_table.attrs, &result.action_table.attrs}) {
855 a->method = "rcat";
856 a->exact = true;
857 a->extra["product_form_certified"] = true;
858 a->extra["rcat_residual"] = 0.0;
859 }
860 return {true, std::string()};
861}
862
863namespace detail {
864
865/** A distribution of per-state rates: (rates, probabilities). */
866typedef std::pair<std::vector<double>, std::vector<double>> RateLaw;
867
868/** Expectation of a minimum from products of discrete survival laws (`expected_min`). */
869inline double expected_min(const std::vector<RateLaw>& distributions, std::optional<double> cutoff = std::nullopt) {
870 if (cutoff && *cutoff <= 0) return 0.0;
871 if (distributions.empty()) return cutoff ? *cutoff : 0.0;
872 std::set<double> values;
873 for (const RateLaw& d : distributions)
874 for (double x : d.first)
875 if (x > 0) values.insert(x);
876 if (cutoff) {
877 std::set<double> kept;
878 for (double v : values)
879 if (v < *cutoff) kept.insert(v);
880 kept.insert(*cutoff);
881 values = kept;
882 }
883 double last = 0.0, total = 0.0;
884 for (double point : values) {
885 double prob = 1.0;
886 for (const RateLaw& d : distributions) {
887 double s = 0.0;
888 for (std::size_t i = 0; i < d.first.size(); ++i)
889 if (d.first[i] >= point) s += d.second[i];
890 prob *= s;
891 }
892 total += (point - last) * prob;
893 last = point;
894 }
895 return total;
896}
897
898} // namespace detail
899
900/** Finite LAL mean-field approximation (`lal_meanfield.solve_composition`). */
901inline AGResult meanfield_solve(const Model& snapshot, double tol = 1e-4, long max_iter = 100, double damping = .5) {
902 validate_model(snapshot);
903 detail::check_iteration(tol, max_iter, "Mean-field");
904 const std::vector<AgentRecord>& agents = snapshot.agents;
905 const std::size_t K = agents.size();
906 EventKernel kernel(snapshot);
907 const std::vector<std::string>& labels = kernel.labels;
908 std::map<Endpoint, std::vector<Endpoint>> ordinary;
909 for (const Sync& s : snapshot.syncs) ordinary[s.active] = s.passive;
910 std::set<Endpoint> min_members;
911 for (const MinSync& m : snapshot.min_syncs)
912 for (const Endpoint& e : m.active) min_members.insert(e);
913 struct Blk {
914 std::size_t i;
915 std::vector<double> totals;
916 Matrix<double> probability;
917 };
918 auto matrix = [&](const Endpoint& ep, Role role) {
919 Blk b;
920 b.i = snapshot.index_of(ep.first);
921 b.probability = detail::block_of(agents[b.i], ep.second, role);
922 b.totals = detail::normalise_rows(b.probability);
923 return b;
924 };
925 std::map<std::string, std::pair<std::vector<Blk>, std::vector<Blk>>> events;
926 for (const AgentRecord& agent : agents)
927 for (const std::string& action : detail::active_actions(agent)) {
928 const Endpoint ep(agent.name, action);
929 if (min_members.count(ep)) continue;
930 std::vector<Blk> passive;
931 auto it = ordinary.find(ep);
932 if (it != ordinary.end())
933 for (const Endpoint& p : it->second) passive.push_back(matrix(p, Role::Passive));
934 events[endpoint_label(ep)] = {{matrix(ep, Role::Active)}, passive};
935 }
936 for (const MinSync& m : snapshot.min_syncs) {
937 std::vector<Blk> a, p;
938 for (const Endpoint& e : m.active) a.push_back(matrix(e, Role::Active));
939 for (const Endpoint& e : m.passive) p.push_back(matrix(e, Role::Passive));
940 events[endpoint_label(m.active.front())] = {a, p};
941 }
942 auto local_solve = [&](const std::vector<std::vector<double>>& marginals, std::map<std::string, double>& throughputs) {
943 std::vector<Matrix<double>> blocks;
944 for (const AgentRecord& a : agents) blocks.push_back(Matrix<double>(a.states.size(), a.states.size(), 0.0));
945 for (const std::string& label : labels) {
946 const auto& ev = events.at(label);
947 std::vector<detail::RateLaw> distributions;
948 for (const Blk& b : ev.first) distributions.push_back({b.totals, marginals[b.i]});
949 const double active_rate = detail::expected_min(distributions);
950 std::vector<double> enabled;
951 for (const Blk& b : ev.second) {
952 double s = 0.0;
953 for (std::size_t j = 0; j < b.totals.size(); ++j)
954 if (b.totals[j] > 0) s += marginals[b.i][j];
955 enabled.push_back(s);
956 }
957 double prod_enabled = 1.0;
958 for (double e : enabled) prod_enabled *= e;
959 throughputs[label] = active_rate * prod_enabled;
960 for (std::size_t ai = 0; ai < ev.first.size(); ++ai) {
961 const Blk& b = ev.first[ai];
962 std::vector<detail::RateLaw> others;
963 for (std::size_t o = 0; o < distributions.size(); ++o)
964 if (o != ai) others.push_back(distributions[o]);
965 for (std::size_t r = 0; r < b.totals.size(); ++r) {
966 const double f = detail::expected_min(others, b.totals[r]) * prod_enabled;
967 for (std::size_t c = 0; c < b.totals.size(); ++c) blocks[b.i](r, c) += f * b.probability(r, c);
968 }
969 }
970 for (std::size_t pidx = 0; pidx < ev.second.size(); ++pidx) {
971 const Blk& b = ev.second[pidx];
972 double other_enabled = 1.0;
973 for (std::size_t o = 0; o < enabled.size(); ++o)
974 if (o != pidx) other_enabled *= enabled[o];
975 for (std::size_t r = 0; r < b.totals.size(); ++r) {
976 const double f = (b.totals[r] > 0 ? 1.0 : 0.0) * active_rate * other_enabled;
977 for (std::size_t c = 0; c < b.totals.size(); ++c) blocks[b.i](r, c) += f * b.probability(r, c);
978 }
979 }
980 }
981 std::vector<std::vector<double>> updated;
982 for (std::size_t i = 0; i < K; ++i)
983 updated.push_back(detail::local_stationary(
984 blocks[i], "Mean-field local chain for " + agents[i].name +
985 " is reducible; the stationary approximation is not uniquely determined."));
986 return updated;
987 };
988 std::vector<std::vector<double>> marginals;
989 for (const AgentRecord& a : agents)
990 marginals.push_back(std::vector<double>(a.states.size(), 1.0 / static_cast<double>(a.states.size())));
991 bool converged = false;
992 double residual = detail::kInf;
993 long iteration = 0;
994 std::map<std::string, double> throughputs;
995 for (iteration = 1; iteration <= max_iter; ++iteration) {
996 const std::vector<std::vector<double>> updated = local_solve(marginals, throughputs);
997 residual = 0.0;
998 for (std::size_t i = 0; i < K; ++i) residual = std::max(residual, detail::l1_diff(updated[i], marginals[i]));
999 if (residual <= tol) {
1000 converged = true;
1001 break;
1002 }
1003 for (std::size_t i = 0; i < K; ++i)
1004 for (std::size_t j = 0; j < marginals[i].size(); ++j)
1005 marginals[i][j] = (1 - damping) * marginals[i][j] + damping * updated[i][j];
1006 }
1007 if (iteration > max_iter) iteration = max_iter;
1008 throughputs.clear();
1009 local_solve(marginals, throughputs);
1010 AGResult res;
1011 res.method = "meanfield";
1012 res.exact = false;
1013 res.converged = converged;
1014 res.iterations = static_cast<int>(iteration);
1015 res.residual = residual;
1016 for (std::size_t i = 0; i < K; ++i)
1017 for (std::size_t j = 0; j < agents[i].states.size(); ++j)
1018 res.state_table.rows.push_back({agents[i].name, agents[i].states[j], marginals[i][j]});
1019 for (const std::string& label : labels) res.action_table.rows.push_back({label, throughputs.at(label)});
1020 res.state_table.attrs.method = "meanfield";
1021 res.state_table.attrs.exact = false;
1022 res.state_table.attrs.extra = {
1023 {"converged", converged}, {"fixed_point_residual", residual}, {"product_form_certified", false}};
1025 res.diagnostics = {{"product_form_certified", false},
1026 {"fixed_point_residual", residual},
1027 {"approximation", "independent local marginals"},
1028 {"damping", damping},
1029 {"certificate_reason", "Mean-field independence is an approximation, not an RCAT proof."}};
1030 return res;
1031}
1032
1033/** Validate and complete a user partition without enumeration (`group_partition`). */
1034inline std::vector<std::vector<std::string>> group_partition(
1035 const Model& snapshot, const std::optional<std::vector<std::vector<std::string>>>& groups, long max_states) {
1036 if (max_states <= 0) throw value_error("group_max_states must be a positive integer");
1037 if (!groups || groups->empty()) throw value_error("groups must contain one or more lists of agent names");
1038 std::set<std::string> seen;
1039 std::vector<std::vector<std::string>> partition;
1040 for (const auto& group : *groups) {
1041 if (group.empty()) throw value_error("each group must be a nonempty list of agent names");
1042 for (const std::string& name : group)
1043 if (!snapshot.has_agent(name)) throw value_error("group contains an unknown agent");
1044 const std::set<std::string> unique(group.begin(), group.end());
1045 bool overlap = unique.size() != group.size();
1046 for (const std::string& name : group)
1047 if (seen.count(name)) overlap = true;
1048 if (overlap) throw value_error("an agent may belong to only one group");
1049 seen.insert(group.begin(), group.end());
1050 partition.push_back(group);
1051 }
1052 for (const AgentRecord& a : snapshot.agents)
1053 if (!seen.count(a.name)) partition.push_back({a.name});
1054 return partition;
1055}
1056
1057/**
1058 * Grouped decomposition (`lal_grouped.solve_composition`): exact within groups,
1059 * mean-field across them. `source_truncated` marks a flattened truncated import,
1060 * which keeps a one-group solution from being reported exact.
1061 */
1062inline AGResult grouped_solve(const Model& snapshot, const std::optional<std::vector<std::vector<std::string>>>& groups,
1063 long max_states = 256, double tol = 1e-4, long max_iter = 100, double damping = .5,
1064 bool source_truncated = false) {
1065 validate_model(snapshot);
1066 detail::check_iteration(tol, max_iter, "Grouped");
1067 const std::vector<std::vector<std::string>> partition = group_partition(snapshot, groups, max_states);
1068 std::vector<std::string> names;
1069 for (const AgentRecord& a : snapshot.agents) names.push_back(a.name);
1070 nlohmann::json partition_json = partition;
1071 if (partition.size() == 1) {
1072 // One group is the original finite CTMC, including reducible chains and
1073 // the declared initial distribution. Do not infer a product form.
1074 AGResult res(solve_composition(snapshot, static_cast<std::size_t>(max_states)));
1075 const bool exact = !source_truncated;
1076 GroupDistribution g{names, res.states, res.probabilities};
1077 res.group_distributions = std::vector<GroupDistribution>{g};
1078 res.method = "grouped";
1079 res.exact = exact;
1080 res.converged = true;
1081 res.iterations = 1;
1082 res.residual = 0.0;
1083 res.diagnostics = {{"groups", partition_json},
1084 {"group_states", nlohmann::json::array({res.states.size()})},
1085 {"group_distributions", detail::group_json(*res.group_distributions)},
1086 {"approximation", nullptr},
1087 {"product_form_certified", false},
1088 {"certificate_reason", "One group was solved by explicit finite CTMC."}};
1089 for (TableAttrs* a : {&res.state_table.attrs, &res.action_table.attrs}) {
1090 a->method = "grouped";
1091 a->exact = exact;
1092 a->extra["converged"] = true;
1093 a->extra["groups"] = partition_json;
1094 a->extra["product_form_certified"] = false;
1095 }
1096 return res;
1097 }
1098 const std::vector<AgentRecord>& agents = snapshot.agents;
1099 EventKernel kernel(snapshot);
1100 const std::vector<std::string>& labels = kernel.labels;
1101 std::map<Endpoint, std::vector<Endpoint>> ordinary;
1102 for (const Sync& s : snapshot.syncs) ordinary[s.active] = s.passive;
1103 std::set<Endpoint> min_members;
1104 for (const MinSync& m : snapshot.min_syncs)
1105 for (const Endpoint& e : m.active) min_members.insert(e);
1106 struct Decl {
1107 std::string label;
1108 std::vector<Endpoint> active, passive;
1109 };
1110 std::vector<Decl> declarations;
1111 for (const AgentRecord& agent : agents)
1112 for (const std::string& action : detail::active_actions(agent)) {
1113 const Endpoint ep(agent.name, action);
1114 if (min_members.count(ep)) continue;
1115 Decl d{endpoint_label(ep), {ep}, {}};
1116 auto it = ordinary.find(ep);
1117 if (it != ordinary.end()) d.passive = it->second;
1118 declarations.push_back(d);
1119 }
1120 for (const MinSync& m : snapshot.min_syncs)
1121 declarations.push_back(Decl{endpoint_label(m.active.front()), m.active, m.passive});
1122
1123 struct Participant {
1124 std::size_t agent; ///< model agent index
1125 std::size_t pos; ///< position within the group
1126 std::string action;
1127 Role role;
1128 };
1129 typedef std::vector<std::size_t> GState;
1130 // Per agent, action, role, local state: (total, [(target, probability)]).
1131 auto options = [&](std::size_t a, const std::string& action, Role role, std::size_t state) {
1132 const AgentRecord& ag = agents[a];
1133 double total = 0.0;
1134 std::vector<std::pair<std::size_t, double>> raw;
1135 for (const Transition& t : ag.transitions)
1136 if (t.role == role && t.action == action && ag.state_index(t.source) == state && t.value > 0) {
1137 total += t.value;
1138 raw.push_back({ag.state_index(t.target), t.value});
1139 }
1140 if (total > 0)
1141 for (auto& r : raw) r.second /= total;
1142 else
1143 raw.clear();
1144 return std::make_pair(total, raw);
1145 };
1146 std::vector<std::map<std::string, std::pair<std::vector<double>, Matrix<double>>>> group_events;
1147 std::vector<std::vector<GState>> group_states;
1148 double dense_bytes = 0.0;
1149 for (const auto& group : partition) {
1150 std::map<std::string, std::size_t> positions;
1151 for (std::size_t i = 0; i < group.size(); ++i) positions[group[i]] = i;
1152 std::vector<std::pair<std::string, std::vector<Participant>>> local_events;
1153 for (const Decl& d : declarations) {
1154 std::vector<Participant> ps;
1155 for (const Endpoint& e : d.active)
1156 if (positions.count(e.first)) ps.push_back({snapshot.index_of(e.first), positions[e.first], e.second, Role::Active});
1157 for (const Endpoint& e : d.passive)
1158 if (positions.count(e.first))
1159 ps.push_back({snapshot.index_of(e.first), positions[e.first], e.second, Role::Passive});
1160 if (!ps.empty()) local_events.push_back({d.label, ps});
1161 }
1162 std::vector<std::vector<std::size_t>> initial_choices;
1163 double support = 1.0;
1164 for (const std::string& name : group) {
1165 const AgentRecord& agent = agents[snapshot.index_of(name)];
1166 std::vector<std::size_t> c;
1167 if (!agent.initial_distribution)
1168 c.push_back(agent.state_index(agent.initial));
1169 else
1170 for (std::size_t s = 0; s < agent.states.size(); ++s)
1171 if ((*agent.initial_distribution)[s] > 0) c.push_back(s);
1172 support *= static_cast<double>(c.size());
1173 initial_choices.push_back(c);
1174 }
1175 if (support > static_cast<double>(max_states))
1176 throw UnsupportedError(ErrorKind("StateSpace"), "Initial group support exceeds group_max_states.");
1177 std::vector<GState> states;
1178 {
1179 std::vector<std::size_t> idx(initial_choices.size(), 0);
1180 while (true) {
1181 GState s;
1182 for (std::size_t i = 0; i < idx.size(); ++i) s.push_back(initial_choices[i][idx[i]]);
1183 states.push_back(s);
1184 std::size_t d = idx.size();
1185 bool done = true;
1186 while (d > 0) {
1187 --d;
1188 if (++idx[d] < initial_choices[d].size()) {
1189 done = false;
1190 break;
1191 }
1192 idx[d] = 0;
1193 }
1194 if (done) break;
1195 }
1196 }
1197 std::map<GState, std::size_t> lookup;
1198 for (std::size_t i = 0; i < states.size(); ++i) lookup[states[i]] = i;
1199 auto transitions = [&](const GState& state, const std::vector<Participant>& participants) {
1200 std::vector<double> caps;
1201 std::vector<std::pair<std::size_t, std::vector<std::pair<std::size_t, double>>>> branches;
1202 std::vector<std::pair<GState, double>> choices;
1203 for (const Participant& p : participants) {
1204 const auto o = options(p.agent, p.action, p.role, state[p.pos]);
1205 if (o.first <= 0) return std::make_pair(0.0, std::vector<std::pair<GState, double>>());
1206 if (p.role == Role::Active) caps.push_back(o.first);
1207 branches.push_back({p.pos, o.second});
1208 }
1209 const double cap = caps.empty() ? detail::kInf : *std::min_element(caps.begin(), caps.end());
1210 double combos = 1.0;
1211 for (const auto& b : branches) combos *= static_cast<double>(b.second.size());
1212 if (combos > 1000000)
1213 throw UnsupportedError(ErrorKind("StateSpace"),
1214 "Grouped event has more than 1000000 local branch combinations.");
1215 std::vector<std::size_t> idx(branches.size(), 0);
1216 while (true) {
1217 GState target = state;
1218 double probability = 1.0;
1219 for (std::size_t b = 0; b < branches.size(); ++b) {
1220 target[branches[b].first] = branches[b].second[idx[b]].first;
1221 probability *= branches[b].second[idx[b]].second;
1222 }
1223 choices.push_back({target, probability});
1224 std::size_t d = idx.size();
1225 bool done = true;
1226 while (d > 0) {
1227 --d;
1228 if (++idx[d] < branches[d].second.size()) {
1229 done = false;
1230 break;
1231 }
1232 idx[d] = 0;
1233 }
1234 if (done) break;
1235 }
1236 return std::make_pair(cap, choices);
1237 };
1238 // Existential projection over the other groups is conservative: it may
1239 // admit unreachable combinations across groups, but not omit a local
1240 // transition. Only positive local branches enter the reachability set.
1241 for (std::size_t s = 0; s < states.size(); ++s)
1242 for (const auto& le : local_events) {
1243 const GState current = states[s];
1244 const auto tr = transitions(current, le.second);
1245 for (const auto& ch : tr.second)
1246 if (ch.second > 0 && !lookup.count(ch.first)) {
1247 if (states.size() >= static_cast<std::size_t>(max_states))
1248 throw UnsupportedError(ErrorKind("StateSpace"), "Projected group exceeds group_max_states.");
1249 lookup[ch.first] = states.size();
1250 states.push_back(ch.first);
1251 }
1252 }
1253 const double n = static_cast<double>(states.size());
1254 dense_bytes += static_cast<double>(local_events.size() + 1) * n * n * 8.0;
1255 if (dense_bytes > 256.0 * 1024 * 1024)
1256 throw UnsupportedError(ErrorKind("StateSpace"), "Grouped local matrices exceed the 256 MiB memory limit.");
1257 std::map<std::string, std::pair<std::vector<double>, Matrix<double>>> compiled;
1258 for (const auto& le : local_events) {
1259 std::vector<double> caps(states.size(), 0.0);
1260 Matrix<double> k(states.size(), states.size(), 0.0);
1261 for (std::size_t i = 0; i < states.size(); ++i) {
1262 const auto tr = transitions(states[i], le.second);
1263 caps[i] = tr.first;
1264 for (const auto& ch : tr.second) k(i, lookup.at(ch.first)) += ch.second;
1265 }
1266 compiled[le.first] = {caps, k};
1267 }
1268 group_events.push_back(compiled);
1269 group_states.push_back(states);
1270 }
1271
1272 auto expectation = [](const std::vector<detail::RateLaw>& distributions, std::optional<double> cutoff) -> double {
1273 // A passive-only group has capacity infinity when enabled. Ignore
1274 // infinity as a breakpoint, but retain it in the survival probabilities.
1275 if (cutoff && *cutoff <= 0) return 0.0;
1276 std::set<double> points;
1277 for (const auto& d : distributions)
1278 for (double x : d.first)
1279 if (x > 0 && x < detail::kInf) points.insert(x);
1280 if (cutoff && std::isfinite(*cutoff)) {
1281 std::set<double> kept;
1282 for (double x : points)
1283 if (x < *cutoff) kept.insert(x);
1284 kept.insert(*cutoff);
1285 points = kept;
1286 }
1287 if (points.empty()) {
1288 // A finite cutoff is itself a point, so here the cutoff is absent or
1289 // infinite and no group offers a finite positive rate: the event is
1290 // disabled wherever some group reports a finite (zero) rate.
1291 for (const auto& d : distributions)
1292 for (double x : d.first)
1293 if (std::isfinite(x)) return 0.0;
1294 throw value_error("event has no active rate");
1295 }
1296 double result = 0.0, last = 0.0;
1297 for (double point : points) {
1298 double prob = 1.0;
1299 for (const auto& d : distributions) {
1300 double s = 0.0;
1301 for (std::size_t i = 0; i < d.first.size(); ++i)
1302 if (d.first[i] >= point) s += d.second[i];
1303 prob *= s;
1304 }
1305 result += (point - last) * prob;
1306 last = point;
1307 }
1308 return result;
1309 };
1310 const std::size_t G = partition.size();
1311 auto local_solve = [&](const std::vector<std::vector<double>>& marginals, std::map<std::string, double>& throughputs) {
1312 std::vector<Matrix<double>> blocks;
1313 for (const auto& s : group_states) blocks.push_back(Matrix<double>(s.size(), s.size(), 0.0));
1314 for (const std::string& label : labels) {
1315 std::vector<std::size_t> part;
1316 std::vector<detail::RateLaw> distributions;
1317 for (std::size_t i = 0; i < G; ++i) {
1318 auto it = group_events[i].find(label);
1319 if (it == group_events[i].end()) continue;
1320 part.push_back(i);
1321 distributions.push_back({it->second.first, marginals[i]});
1322 }
1323 throughputs[label] = expectation(distributions, std::nullopt);
1324 for (std::size_t off = 0; off < part.size(); ++off) {
1325 const std::size_t i = part[off];
1326 const auto& ev = group_events[i].at(label);
1327 std::vector<detail::RateLaw> other;
1328 for (std::size_t o = 0; o < distributions.size(); ++o)
1329 if (o != off) other.push_back(distributions[o]);
1330 for (std::size_t r = 0; r < ev.first.size(); ++r) {
1331 const double cap = ev.first[r];
1332 const double f = std::isfinite(cap) ? expectation(other, cap) : expectation(other, std::nullopt);
1333 for (std::size_t c = 0; c < ev.first.size(); ++c) blocks[i](r, c) += f * ev.second(r, c);
1334 }
1335 }
1336 }
1337 std::vector<std::vector<double>> updated;
1338 for (std::size_t i = 0; i < G; ++i) {
1339 std::string tuple = "(";
1340 for (std::size_t k = 0; k < partition[i].size(); ++k)
1341 tuple += (k ? ", '" : "'") + partition[i][k] + "'";
1342 tuple += partition[i].size() == 1 ? ",)" : ")";
1343 updated.push_back(detail::local_stationary(
1344 blocks[i], "Grouped local chain " + tuple + " is reducible; its stationary approximation is not unique."));
1345 }
1346 return updated;
1347 };
1348 std::vector<std::vector<double>> marginals;
1349 for (const auto& s : group_states) marginals.push_back(std::vector<double>(s.size(), 1.0 / static_cast<double>(s.size())));
1350 bool converged = false;
1351 double residual = detail::kInf;
1352 long iteration = 0;
1353 std::map<std::string, double> throughputs;
1354 for (iteration = 1; iteration <= max_iter; ++iteration) {
1355 const std::vector<std::vector<double>> updated = local_solve(marginals, throughputs);
1356 residual = 0.0;
1357 for (std::size_t i = 0; i < G; ++i) residual = std::max(residual, detail::l1_diff(updated[i], marginals[i]));
1358 if (residual <= tol) {
1359 converged = true;
1360 break;
1361 }
1362 for (std::size_t i = 0; i < G; ++i)
1363 for (std::size_t j = 0; j < marginals[i].size(); ++j)
1364 marginals[i][j] = (1 - damping) * marginals[i][j] + damping * updated[i][j];
1365 }
1366 if (iteration > max_iter) iteration = max_iter;
1367 throughputs.clear();
1368 local_solve(marginals, throughputs);
1369 std::map<std::pair<std::size_t, std::size_t>, double> local_prob;
1370 for (std::size_t g = 0; g < G; ++g)
1371 for (std::size_t pos = 0; pos < partition[g].size(); ++pos) {
1372 const std::size_t a = snapshot.index_of(partition[g][pos]);
1373 for (std::size_t v = 0; v < agents[a].states.size(); ++v) {
1374 double s = 0.0;
1375 for (std::size_t k = 0; k < group_states[g].size(); ++k)
1376 if (group_states[g][k][pos] == v) s += marginals[g][k];
1377 local_prob[{a, v}] = s;
1378 }
1379 }
1380 AGResult res;
1381 res.method = "grouped";
1382 res.exact = false;
1383 res.converged = converged;
1384 res.iterations = static_cast<int>(iteration);
1385 res.residual = residual;
1386 for (std::size_t a = 0; a < agents.size(); ++a)
1387 for (std::size_t v = 0; v < agents[a].states.size(); ++v)
1388 res.state_table.rows.push_back({agents[a].name, agents[a].states[v], local_prob.at({a, v})});
1389 for (const std::string& label : labels) res.action_table.rows.push_back({label, throughputs.at(label)});
1390 std::vector<GroupDistribution> dists;
1391 nlohmann::json sizes = nlohmann::json::array();
1392 for (std::size_t g = 0; g < G; ++g) {
1393 dists.push_back(GroupDistribution{partition[g], group_states[g], marginals[g]});
1394 sizes.push_back(group_states[g].size());
1395 }
1396 res.group_distributions = dists;
1397 res.diagnostics = {{"groups", partition_json},
1398 {"group_states", sizes},
1399 {"approximation", "independent group marginals"},
1400 {"damping", damping},
1401 {"fixed_point_residual", residual},
1402 {"product_form_certified", false},
1403 {"group_distributions", detail::group_json(dists)}};
1404 for (TableAttrs* a : {&res.state_table.attrs, &res.action_table.attrs}) {
1405 a->method = "grouped";
1406 a->exact = false;
1407 a->extra["converged"] = converged;
1408 a->extra["groups"] = partition_json;
1409 a->extra["fixed_point_residual"] = residual;
1410 a->extra["product_form_certified"] = false;
1411 }
1412 return res;
1413}
1414
1415/**
1416 * Numerically compare the product of agent marginals with the exact finite
1417 * CTMC (`compare_with_ctmc`). `max_probability_error`, `total_variation` and
1418 * `generator_residual` compare the product CONDITIONED on the reachable states.
1419 * Conditioning can hide product mass on states the CTMC never reaches, so that
1420 * mass is reported separately as `unreachable_product_mass`, and
1421 * `unconditioned_total_variation` compares the raw product, counting the
1422 * unreachable mass as error.
1423 */
1424inline nlohmann::json compare_with_ctmc(const Model& snapshot, const AGResult& result,
1425 std::optional<std::size_t> max_states = std::nullopt) {
1426 if (max_states && *max_states == 0) throw value_error("max_states must be None or a positive integer");
1427 const Result exact = solve_composition(snapshot, max_states ? *max_states : 0);
1428 const std::vector<AgentRecord>& agents = snapshot.agents;
1429 std::map<std::pair<std::string, std::string>, double> marginals;
1430 for (const StateRow& r : result.state_table.rows) marginals[{r.agent, r.state}] = r.probability;
1431 std::vector<double> product;
1432 if (result.group_distributions) {
1433 struct Lookup {
1434 std::vector<std::size_t> positions;
1435 std::map<std::vector<std::size_t>, double> probs;
1436 };
1437 std::vector<Lookup> groups;
1438 for (const GroupDistribution& g : *result.group_distributions) {
1439 Lookup l;
1440 for (const std::string& name : g.agents) l.positions.push_back(snapshot.index_of(name));
1441 for (std::size_t k = 0; k < g.states.size(); ++k) l.probs[g.states[k]] = g.probabilities[k];
1442 groups.push_back(l);
1443 }
1444 for (const auto& state : exact.states) {
1445 double p = 1.0;
1446 for (const Lookup& l : groups) {
1447 std::vector<std::size_t> key;
1448 for (std::size_t pos : l.positions) key.push_back(state[pos]);
1449 auto it = l.probs.find(key);
1450 p *= it == l.probs.end() ? 0.0 : it->second;
1451 }
1452 product.push_back(p);
1453 }
1454 } else {
1455 for (const auto& state : exact.states) {
1456 double p = 1.0;
1457 for (std::size_t a = 0; a < agents.size(); ++a) p *= marginals.at({agents[a].name, agents[a].states[state[a]]});
1458 product.push_back(p);
1459 }
1460 }
1461 double mass = 0.0;
1462 for (double p : product) mass += p;
1463 if (!std::isfinite(mass)) throw value_error("The product of agent marginals is not finite on the reachable states");
1464 // The marginals (or group distributions) each sum to one, so the product
1465 // has unit mass over the full product space; what is missing here sits on
1466 // unreachable states.
1467 const double unreachable = std::max(0.0, 1.0 - mass);
1468 double rawdiff = 0.0;
1469 for (std::size_t i = 0; i < product.size(); ++i) rawdiff += std::abs(product[i] - exact.probabilities[i]);
1470 const double unconditioned_tv = (rawdiff + unreachable) / 2;
1471 if (mass <= 0) throw value_error("The product of agent marginals has no mass on the reachable states");
1472 for (double& p : product) p /= mass;
1473 double maxdiff = 0.0, sumdiff = 0.0;
1474 for (std::size_t i = 0; i < product.size(); ++i) {
1475 const double d = std::abs(product[i] - exact.probabilities[i]);
1476 maxdiff = std::max(maxdiff, d);
1477 sumdiff += d;
1478 }
1479 double marginal_error = 0.0;
1480 for (const StateRow& r : exact.state_table.rows) {
1481 auto it = marginals.find({r.agent, r.state});
1482 if (it != marginals.end()) marginal_error = std::max(marginal_error, std::abs(it->second - r.probability));
1483 }
1484 double action_error = 0.0;
1485 for (const ActionRow& r : exact.action_table.rows)
1486 for (const ActionRow& a : result.action_table.rows)
1487 if (a.action == r.action) action_error = std::max(action_error, std::abs(a.throughput - r.throughput));
1488 const Matrix<double>& q = exact.compiled->generator;
1489 const std::vector<double> pq = detail::rowvec_mul(product, q);
1490 double gres = 0.0;
1491 for (double x : pq) gres += std::abs(x);
1492 return {{"states", exact.states.size()},
1493 {"reachable_product_mass", mass},
1494 {"unreachable_product_mass", unreachable},
1495 {"unconditioned_total_variation", unconditioned_tv},
1496 {"max_probability_error", maxdiff},
1497 {"max_marginal_error", marginal_error},
1498 {"max_action_throughput_error", exact.action_table.rows.empty() ? 0.0 : action_error},
1499 {"total_variation", sumdiff / 2},
1500 {"generator_residual", gres},
1501 {"numerical_comparison_only", true}};
1502}
1503
1504} // namespace lal
1505} // namespace line
1506
1507#endif // LINE_LANG_LAL_AG_H
std::size_t size() const
Definition matrix.h:91
UnsupportedError(const std::string &what)
Definition error.h:119
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): 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.
Definition ag.h:49
AGResult rcat_solve(const Model &original, double tol=1e-4, long max_iter=100, const std::string &method="inaprc")
Finite-agent RCAT fixed point (lal_rcat.solve_composition), method inap or inaprc.
Definition ag.h:615
Role
Transition role: active (rate), passive (weight) or immediate (weight, zero time).
Definition core.h:88
std::pair< std::string, std::string > Endpoint
(agent, action).
Definition core.h:139
AGResult meanfield_solve(const Model &snapshot, double tol=1e-4, long max_iter=100, double damping=.5)
Finite LAL mean-field approximation (lal_meanfield.solve_composition).
Definition ag.h:901
Support certificate_support(const Model &original)
The certificate's conservative structural prerequisites (certificate_support).
Definition ag.h:335
InputError value_error(const std::string &what)
LINE:input:Unspecified, the C++ spelling of the Python ValueError raised throughout LAL.
Definition core.h:85
AGResult grouped_solve(const Model &snapshot, const std::optional< std::vector< std::vector< std::string > > > &groups, long max_states=256, double tol=1e-4, long max_iter=100, double damping=.5, bool source_truncated=false)
Grouped decomposition (lal_grouped.solve_composition): exact within groups, mean-field across them.
Definition ag.h:1062
void validate_model(const Model &model, bool allow_unbounded=false)
Validate the common agent model used by both frontends (validate_model).
Definition core.h:550
std::string endpoint_label(const Endpoint &e)
Definition core.h:141
std::vector< std::vector< std::string > > group_partition(const Model &snapshot, const std::optional< std::vector< std::vector< std::string > > > &groups, long max_states)
Validate and complete a user partition without enumeration (group_partition).
Definition ag.h:1034
Support structural_support(const Model &original, const std::string &method="inaprc")
Decomposition constraints checked without a global state space (structural_support).
Definition ag.h:306
Support full_reachability(const Model &snapshot, std::size_t limit=10000)
Whether one initial state reaches the whole Cartesian space (full_reachability).
Definition ag.h:364
ActionTable action_table(const Compiled &compiled, const std::vector< double > &probs, const Model *snapshot=nullptr)
Labelled event throughputs probs @ rowsum(event), hidden labels left out.
Definition ctmc.h:238
std::pair< bool, std::string > certify_result(const Model &original, AGResult &result, double tol)
Replace an approximate solution with an exactly verified RCAT solution (certify_result).
Definition ag.h:806
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::pair< std::optional< Certificate >, std::string > certify(const Model &snapshot, const std::vector< double > &estimated_rates, double tol)
Try a bounded exact certificate; failure is not a counterexample (certify).
Definition ag.h:447
nlohmann::json compare_with_ctmc(const Model &snapshot, const AGResult &result, std::optional< std::size_t > max_states=std::nullopt)
Numerically compare the product of agent marginals with the exact finite CTMC (compare_with_ctmc).
Definition ag.h:1424
Lowering lower_minimum(const Model &snapshot)
Lower a provably dominated minimum without changing its event law (_lower_minimum).
Definition ag.h:231
std::vector< T > ctmc_solve(const Matrix< T > &Qin, const std::string &linsolver=std::string())
Steady-state distribution of a continuous-time Markov chain.
Definition ctmc_solve.h:133
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
boost::multiprecision::cpp_int BigInt
Definition number.h:91
boost::multiprecision::number< boost::multiprecision::cpp_rational_backend, boost::multiprecision::et_off > Rational
Definition number.h:89
Number-type abstraction for the templated API port.
ErrorKind(std::string n)
Definition error.h:39
The result of an AG decomposition (LALRCATResult, LALMeanFieldResult, LALGroupedResult).
Definition ag.h:63
std::vector< double > reversed_rates
RCAT effective rates, one per synchronisation.
Definition ag.h:64
double rcat_residual
Definition ag.h:65
std::optional< std::vector< GroupDistribution > > group_distributions
Definition ag.h:67
AGResult(const Result &r)
Definition ag.h:70
double residual
mean-field / grouped fixed-point residual
Definition ag.h:66
One row of an action table: Action, Throughput.
Definition ctmc.h:62
double throughput
Definition ctmc.h:64
std::string action
Definition ctmc.h:63
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< Transition > transitions
Definition core.h:288
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
A successful RCAT certificate.
Definition ag.h:440
std::vector< std::vector< Rational > > marginals
Definition ag.h:442
std::vector< Rational > rates
Definition ag.h:441
std::string irreducibility
"autonomous" or "full_reachability"
Definition ag.h:443
One group's joint distribution (diagnostics['group_distributions']).
Definition ag.h:52
std::vector< double > probabilities
Definition ag.h:55
std::vector< std::string > agents
agent names, in group order
Definition ag.h:53
std::vector< std::vector< std::size_t > > states
local state indices per agent
Definition ag.h:54
The lowering of a minimum-rate synchronisation (_lower_minimum).
Definition ag.h:224
nlohmann::json transformations
Definition ag.h:227
std::optional< Model > model
nullopt when lowering is impossible
Definition ag.h:225
std::string reason
why, when model is nullopt
Definition ag.h:226
A minimum-rate synchronisation: at least two active endpoints and optional passive ones.
Definition core.h:258
std::vector< Endpoint > passive
Definition core.h:260
std::vector< Endpoint > active
Definition core.h:259
A composition snapshot (core.Model): agents in declaration order plus synchronisations.
Definition core.h:310
std::vector< MinSync > min_syncs
Definition core.h:313
bool has_agent(const std::string &name) const
Definition core.h:323
std::vector< Sync > syncs
Definition core.h:312
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
The result container shared by the LAL solver paths (LALCTMCResult, the AG decomposition results,...
Definition ctmc.h:96
std::vector< double > probabilities
joint probabilities (CTMC)
Definition ctmc.h:106
std::optional< Compiled > compiled
Definition ctmc.h:107
std::string method
Definition ctmc.h:97
nlohmann::json diagnostics
Definition ctmc.h:108
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
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
A support answer: (ok, reason).
Definition ag.h:300
std::optional< std::string > reason
Definition ag.h:302
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
The attrs of a LAL result table.
Definition ctmc.h:46
std::string method
Definition ctmc.h:47
nlohmann::json extra
remaining Python attrs
Definition ctmc.h:51
std::optional< bool > exact
Definition ctmc.h:48
One labelled local transition source --(action, value)--> target.
Definition core.h:111
std::string target
Definition core.h:116
std::string source
Definition core.h:112
std::string action
Definition core.h:113