LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_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_SOLVER_AG_H
6#define LINE_LANG_LAL_SOLVER_AG_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * LINE Agent Language (LAL): SolverAG on a finite composition (the
12 * `_lal_composition` arm of Python's SolverAG).
13 *
14 * The C++ network SolverAG takes a NetworkStruct, so the LAL arm is a separate
15 * class, `line::lal::SolverAG`, with Python's method names, option names,
16 * refusals, fallback rule and cache rule. A result is recomputed whenever the
17 * composition signature, its truncation flag or the options change.
18 *
19 * Methods (`listLALMethods`, SolverAG's row of doc/line-methods.json restricted
20 * to the finite LAL branch): `default`, `inap`, `inaprc`, `ctmc`, `rcat`,
21 * `meanfield`, `grouped`. `default` and `ctmc` solve the explicit CTMC bounded
22 * by `lal_ctmc_max_states`; on a state-space refusal `default` falls back to
23 * `inaprc` when that is structurally supported and to `meanfield` otherwise,
24 * then tries the exact RCAT certificate, and `ctmc` re-raises.
25 */
26
27#include <functional>
28#include <iostream>
29#include <optional>
30#include <set>
31#include <sstream>
32#include <string>
33#include <utility>
34#include <vector>
35
36#include "line/lang/lal/ag.h"
38#include "line/lang/lal/ctmc.h"
41
42namespace line {
43namespace lal {
44
45/** Options of the LAL arm of SolverAG (`SolverAGOptions`). */
46struct AGOptions {
47 std::string method = "default";
48 double tol = 1e-4;
49 long max_iter = 100;
50 /// bound on the explicit CTMC of `default`/`ctmc`; nullopt is Python's None (dense-storage bound only)
51 std::optional<std::size_t> lal_ctmc_max_states = std::size_t(1000);
52 std::optional<std::vector<std::vector<std::string>>> groups;
53 long group_max_states = 256;
54
55 /** The cache key (Python `repr(self.options)`). */
56 std::string key() const {
57 std::ostringstream os;
58 os << method << '|' << detail::repr_double(tol) << '|' << max_iter << '|'
59 << (lal_ctmc_max_states ? std::to_string(*lal_ctmc_max_states) : std::string("None")) << '|'
60 << (groups ? nlohmann::json(*groups).dump() : std::string("None")) << '|' << group_max_states;
61 return os.str();
62 }
63};
64
65/**
66 * SolverAG on a finite LAL composition. The solver keeps a reference to the
67 * composition, as Python does, so agent mutations made after construction are
68 * seen by the next query.
69 */
70class SolverAG {
71 public:
72 /// The explicit-CTMC backend of `default`/`ctmc` (Python's module-level
73 /// `lal_ctmc.solve_composition`); replaceable so a test can force a refusal.
74 typedef std::function<Result(const Model&, std::optional<std::size_t>)> CTMCBackend;
75
76 explicit SolverAG(const Composition& model, AGOptions options = AGOptions())
77 : options(std::move(options)), model_(&model) {}
78 SolverAG(const Composition&&, AGOptions = AGOptions()) = delete;
79
81
82 static AGOptions defaultOptions() { return AGOptions(); }
83
84 /** Methods available for a finite LAL Composition (`listLALMethods`). */
85 static std::vector<std::string> listLALMethods() {
86 return {"default", "inap", "inaprc", "ctmc", "rcat", "meanfield", "grouped"};
87 }
88
89 /**
90 * `listValidMethods`: on a Composition the reference answers
91 * `listLALMethods` (SolverAG.m), so this solver, which only takes one,
92 * answers the same list.
93 */
94 static std::vector<std::string> listValidMethods() { return listLALMethods(); }
95 static std::vector<std::string> list_valid_methods() { return listValidMethods(); }
96
97 /**
98 * `getFeatureSet`, static as in SolverAG.m: the RCAT feature envelope of
99 * the network arm, `qn::ag_feature_set`. Every AG method is the same
100 * decomposition, so the envelope does not vary by method. A composition is
101 * not gated by it; see `supports`.
102 */
103 static qn::FeatureSet getFeatureSet() { return qn::ag_feature_set("default"); }
105
106 /**
107 * `supports(model)`: a LAL composition has no queueing-network feature set,
108 * so the reference answers true (with an empty feature set) and leaves the
109 * per-method gate to `supportsModelMethod`. Same convention as the LAL
110 * SolverCTMC and SolverSSA.
111 */
112 static bool supports(const Composition&) { return true; }
113
114 /**
115 * `getStruct`: on a Composition the reference returns `model.getStruct()`,
116 * the finite CTMC states, generator and labelled event matrices
117 * (`Composition::get_struct`, which validates the composition first).
118 */
119 Compiled getStruct() const { return model_->get_struct(); }
120 Compiled get_struct() const { return getStruct(); }
121
122 /** The identity: `default` is gated as itself (`resolveMethod`). */
123 std::string resolveMethod() const { return options.method; }
124
125 /** Structural gate for the requested method (`supportsModelMethod`). */
126 Support supportsModelMethod(const std::string& method) const {
127 const std::vector<std::string> methods = listLALMethods();
128 if (std::find(methods.begin(), methods.end(), method) == methods.end()) {
129 std::string list;
130 for (std::size_t i = 0; i < methods.size(); ++i) list += (i ? ", " : "") + methods[i];
131 return {false, "Finite LAL compositions support " + list + "; other RCAT methods are not implemented."};
132 }
133 Model snapshot;
134 try {
135 // Every AG LAL path needs finite agents; a support query answers
136 // validate_model's refusal (e.g. an unbounded queue) instead of raising it.
137 snapshot = model_->model();
138 validate_model(snapshot);
139 } catch (const Error& exc) {
140 return {false, std::string(exc.what())};
141 }
142 const std::set<std::string> features = model_features(snapshot);
143 if (!features.empty() && method != "default" && method != "ctmc")
144 // the RCAT, mean-field and grouped paths read the timed finite
145 // kernel; the exact CTMC path interprets every extension
146 return {false, "SolverAG method " + method + " supports timed hand-declared agents only; the composition "
147 "uses " + detail::join_sorted(features) + " actions (use ctmc)."};
148 if (!features.empty() && method == "default") return {true, std::nullopt};
149 if (method == "inap" || method == "inaprc" || method == "rcat") {
150 const Support s = structural_support(snapshot, method);
151 if (s.ok && method == "rcat") return certificate_support(snapshot);
152 return s;
153 }
154 if (method == "grouped") {
155 try {
157 } catch (const InputError& exc) {
158 return {false, std::string(exc.what())};
159 }
160 }
161 return {true, std::nullopt};
162 }
163
164 /** Run the selected method and store the result (`runAnalyzer`). */
166 std::string method = resolveMethod();
167 const Support ok = supportsModelMethod(method);
168 if (!ok.ok) throw UnsupportedError(ErrorKind("Method"), *ok.reason);
169 const Model snapshot = model_->model();
170 const std::string signature = key_();
171 std::optional<std::string> fallback_reason;
172 AGResult result;
173 if (method == "default" || method == "ctmc") {
174 try {
175 result = AGResult(backend_(snapshot, options.lal_ctmc_max_states));
176 } catch (const UnsupportedError& exc) {
177 if (method != "default" || exc.id() != "LINE:unsupported:StateSpace") throw;
178 if (!model_features(snapshot).empty()) throw; // no approximate method reads the extended actions
179 const bool supported = supportsModelMethod("inaprc").ok;
180 fallback_reason = exc.what();
181 method = supported ? "inaprc" : "meanfield";
182 }
183 }
184 if (method == "inap" || method == "inaprc" || method == "rcat") {
185 try {
186 result = rcat_solve(snapshot, options.tol, options.max_iter, method == "rcat" ? "inaprc" : method);
187 } catch (const UnsupportedError& exc) {
188 if (!fallback_reason) throw;
189 throw UnsupportedError(ErrorKind("StateSpace"),
190 *fallback_reason + " AG decomposition also refused the model: " + exc.what());
191 }
192 if (!result.converged) warn_("SolverAG LAL " + method + " did not converge within the iteration limit.");
193 if (method == "rcat" || fallback_reason) {
194 const std::pair<bool, std::string> cert = certify_result(snapshot, result, options.tol);
195 if (method == "rcat" && !cert.first)
196 throw UnsupportedError(ErrorKind("ProductForm"),
197 "RCAT product form could not be certified: " + cert.second);
198 if (fallback_reason && !cert.first) result.diagnostics["certificate_reason"] = cert.second;
199 }
200 }
201 if (method == "meanfield") {
202 try {
203 result = meanfield_solve(snapshot, options.tol, options.max_iter);
204 } catch (const UnsupportedError& exc) {
205 if (!fallback_reason) throw;
206 throw UnsupportedError(ErrorKind("StateSpace"), *fallback_reason +
207 " Mean-field decomposition also refused the model: " +
208 exc.what());
209 }
210 if (!result.converged) warn_("SolverAG LAL meanfield did not converge within the iteration limit.");
211 }
212 if (method == "grouped") {
214 model_->source_truncated);
215 if (!result.converged) warn_("SolverAG LAL grouped did not converge within the iteration limit.");
216 }
217 // A flattened LINE import with an explicit cutoff represents that
218 // finite truncation, not the original unbounded network.
219 result.truncated = model_->source_truncated;
220 if (result.truncated && result.exact) {
221 result.exact = false;
222 result.state_table.attrs.exact = false;
223 result.action_table.attrs.exact = false;
224 }
225 if (method == "ctmc" || (method == "default" && !fallback_reason)) {
226 result.exact = !result.truncated;
227 result.state_table.attrs.exact = result.exact;
228 result.action_table.attrs.exact = result.exact;
229 }
230 result.fallback_reason = fallback_reason;
231 for (TableAttrs* a : {&result.state_table.attrs, &result.action_table.attrs}) {
232 a->truncated = result.truncated;
233 a->fallback_reason = fallback_reason;
234 }
235 result_ = std::move(result);
236 signature_ = signature;
237 return *this;
238 }
239
240 /** State probabilities (`getAvgTable`). */
241 StateTable getAvgTable() { return ensure_().state_table; }
242
243 /** Steady-state labelled event rates (`getActTable`). */
244 ActionTable getActTable() { return ensure_().action_table; }
248 /**
249 * `getAvgTard()`, inherited by the reference from NetworkSolver: mean class
250 * tardiness against the JobClass deadlines, as {Tard, SysTard}. It solves
251 * first when no result is held (`getAvgTard.m` calls `getAvg`) and returns
252 * what the result carries. A composition declares no JobClass and no
253 * deadline, so no LAL result carries a tardiness and both matrices are
254 * empty, as the reference returns `[]` for them.
255 */
256 std::vector<Matrix<double>> getAvgTard() {
257 ensure_();
258 return {Matrix<double>(), Matrix<double>()};
259 }
260 std::vector<Matrix<double>> get_avg_tard() { return getAvgTard(); }
261
262 /** Throughput of one LAL action (named as in SolverCTMC::getAvgAct). */
263 double getAvgAct(const ActionSpec& action) { return act_value(*model_, getActTable(), action); }
264 double getAvgAct(const std::string& node, lang::EventType event,
265 const std::optional<std::string>& jobclass = std::nullopt,
266 const std::optional<std::string>& mode = std::nullopt) {
267 return getAvgAct(ActionSpec::key(node, event, jobclass, mode));
268 }
269 double getAvgAct(std::size_t node, lang::EventType event, std::size_t jobclass = 0) {
270 return getAvgAct(ActionSpec::key(node, event, jobclass));
271 }
272 /** Throughputs of several actions, each named as in `getAvgAct`. */
273 std::vector<double> getActAvg(const std::vector<ActionSpec>& actions) {
274 std::vector<double> out;
275 for (const ActionSpec& a : actions) out.push_back(getAvgAct(a));
276 return out;
277 }
278
279 /** Queueing-network averages are refused on a general composition (`getAvg`). */
280 [[noreturn]] void getAvg() const {
281 throw UnsupportedError(ErrorKind("Metric"),
282 "Queueing-network averages are not defined for a general LAL composition; "
283 "use getAvgTable() for state probabilities or getActTable() for event rates.");
284 }
285
286 /** The result container, solving first if needed (`getAGResult`). */
287 const AGResult& getAGResult() { return ensure_(); }
288
289 /**
290 * Diagnostics, optionally with a CTMC comparison (`getAGDiagnostics`).
291 * `max_states = nullopt` bounds the comparison CTMC only by the dense
292 * storage limit of the LAL CTMC path.
293 */
294 nlohmann::json getAGDiagnostics(bool compare_ctmc = false, std::optional<std::size_t> max_states = std::nullopt) {
295 const AGResult& r = ensure_();
296 nlohmann::json diagnostics = r.diagnostics;
297 if (diagnostics.empty())
298 diagnostics = {{"product_form_certified", false},
299 {"certificate_reason", "The selected method is finite CTMC analysis."}};
300 if (compare_ctmc) {
301 const std::vector<std::string> ag{"inap", "inaprc", "rcat", "meanfield", "grouped"};
302 if (std::find(ag.begin(), ag.end(), r.method) == ag.end())
303 throw UnsupportedError(ErrorKind("Method"), "CTMC comparison requires an AG decomposition result.");
304 diagnostics["ctmc_comparison"] = compare_with_ctmc(model_->model(), r, max_states);
305 }
306 return diagnostics;
307 }
308
309 /** Replace the explicit-CTMC backend (Python tests monkeypatch it). */
311 backend_ = std::move(backend);
312 signature_.reset();
313 }
314
315 /** Warnings raised by the last solves, in order (also written to std::cerr). */
316 const std::vector<std::string>& warnings() const { return warnings_; }
317
318 private:
319 const Composition* model_;
320 CTMCBackend backend_ = [](const Model& m, std::optional<std::size_t> max_states) {
321 return solve_composition(m, max_states ? *max_states : 0);
322 };
323 std::optional<AGResult> result_;
324 std::optional<std::string> signature_;
325 std::vector<std::string> warnings_;
326
327 std::string key_() const {
328 return signature(model_->model()) + "|" + (model_->source_truncated ? "T" : "F") + "|" + options.key();
329 }
330
331 const AGResult& ensure_() {
332 if (!result_ || !signature_ || *signature_ != key_()) runAnalyzer();
333 return *result_;
334 }
335
336 void warn_(const std::string& message) {
337 warnings_.push_back(message);
338 std::cerr << "RuntimeWarning: " << message << std::endl;
339 }
340};
341
342} // namespace lal
343} // namespace line
344
345#endif // LINE_LANG_LAL_SOLVER_AG_H
LINE Agent Language (LAL): the agent-based (AG) decompositions of a finite composition,...
LINE Agent Language (LAL): programmatic construction of finite agents and their composition,...
Base error for the multiprecision C++ port.
Definition error.h:73
const std::string & id() const noexcept
The full identifier, e.g.
Definition error.h:78
Malformed or inconsistent input (dimensions, negative populations, ...): LINE:input:<kind>.
Definition error.h:103
A refusal: the feature, method or analysis is not covered: LINE:unsupported:<kind>.
Definition error.h:117
UnsupportedError(const std::string &what)
Definition error.h:119
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
SolverAG & runAnalyzer()
Run the selected method and store the result (runAnalyzer).
Definition solver_ag.h:165
static AGOptions defaultOptions()
Definition solver_ag.h:82
static qn::FeatureSet getFeatureSet()
getFeatureSet, static as in SolverAG.m: the RCAT feature envelope of the network arm,...
Definition solver_ag.h:103
const AGResult & getAGResult()
The result container, solving first if needed (getAGResult).
Definition solver_ag.h:287
StateTable getAvgTable()
State probabilities (getAvgTable).
Definition solver_ag.h:241
nlohmann::json getAGDiagnostics(bool compare_ctmc=false, std::optional< std::size_t > max_states=std::nullopt)
Diagnostics, optionally with a CTMC comparison (getAGDiagnostics).
Definition solver_ag.h:294
double getAvgAct(std::size_t node, lang::EventType event, std::size_t jobclass=0)
Definition solver_ag.h:269
static bool supports(const Composition &)
supports(model): a LAL composition has no queueing-network feature set, so the reference answers true...
Definition solver_ag.h:112
void setCTMCBackend(CTMCBackend backend)
Replace the explicit-CTMC backend (Python tests monkeypatch it).
Definition solver_ag.h:310
std::vector< Matrix< double > > get_avg_tard()
Definition solver_ag.h:260
std::vector< Matrix< double > > getAvgTard()
getAvgTard(), inherited by the reference from NetworkSolver: mean class tardiness against the JobClas...
Definition solver_ag.h:256
static std::vector< std::string > listLALMethods()
Methods available for a finite LAL Composition (listLALMethods).
Definition solver_ag.h:85
std::function< Result(const Model &, std::optional< std::size_t >)> CTMCBackend
The explicit-CTMC backend of default/ctmc (Python's module-level lal_ctmc.solve_composition); replace...
Definition solver_ag.h:74
static std::vector< std::string > listValidMethods()
listValidMethods: on a Composition the reference answers listLALMethods (SolverAG....
Definition solver_ag.h:94
ActionTable actT()
Definition solver_ag.h:246
double getAvgAct(const ActionSpec &action)
Throughput of one LAL action (named as in SolverCTMC::getAvgAct).
Definition solver_ag.h:263
ActionTable getActionTable()
Definition solver_ag.h:247
ActionTable getActT()
Definition solver_ag.h:245
const std::vector< std::string > & warnings() const
Warnings raised by the last solves, in order (also written to std::cerr).
Definition solver_ag.h:316
ActionTable getActTable()
Steady-state labelled event rates (getActTable).
Definition solver_ag.h:244
double getAvgAct(const std::string &node, lang::EventType event, const std::optional< std::string > &jobclass=std::nullopt, const std::optional< std::string > &mode=std::nullopt)
Definition solver_ag.h:264
std::string resolveMethod() const
The identity: default is gated as itself (resolveMethod).
Definition solver_ag.h:123
static std::vector< std::string > list_valid_methods()
Definition solver_ag.h:95
Compiled getStruct() const
getStruct: on a Composition the reference returns model.getStruct(), the finite CTMC states,...
Definition solver_ag.h:119
Support supportsModelMethod(const std::string &method) const
Structural gate for the requested method (supportsModelMethod).
Definition solver_ag.h:126
std::vector< double > getActAvg(const std::vector< ActionSpec > &actions)
Throughputs of several actions, each named as in getAvgAct.
Definition solver_ag.h:273
void getAvg() const
Queueing-network averages are refused on a general composition (getAvg).
Definition solver_ag.h:280
static qn::FeatureSet get_feature_set()
Definition solver_ag.h:104
AGOptions options
Definition solver_ag.h:80
SolverAG(const Composition &model, AGOptions options=AGOptions())
Definition solver_ag.h:76
SolverAG(const Composition &&, AGOptions=AGOptions())=delete
Compiled get_struct() const
Definition solver_ag.h:120
A subset of the registry: MATLAB's SolverFeatureSet, whose list is a flag per field.
LINE Agent Language (LAL): the result tables every LAL solver returns, the exact finite CTMC analysis...
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
std::string signature(const Model &m)
A deterministic text signature of a model snapshot (Python's repr(model)), used by the solvers to cac...
Definition core.h:472
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
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::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
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
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
std::set< std::string > model_features(const Model &model)
Features of a model that only the extended kernel interprets (model_features).
Definition core.h:525
EventType
The events a state can undergo, with the values of MATLAB EventType.
Definition lang_types.h:116
FeatureSet ag_feature_set(const std::string &)
SolverAG.getFeatureSet: what the RCAT decomposition can represent.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
The DECLARED side of the gate: one feature set per solver.
ErrorKind(std::string n)
Definition error.h:39
Options of the LAL arm of SolverAG (SolverAGOptions).
Definition solver_ag.h:46
std::optional< std::vector< std::vector< std::string > > > groups
Definition solver_ag.h:52
std::string method
Definition solver_ag.h:47
std::optional< std::size_t > lal_ctmc_max_states
bound on the explicit CTMC of default/ctmc; nullopt is Python's None (dense-storage bound only)
Definition solver_ag.h:51
std::string key() const
The cache key (Python repr(self.options)).
Definition solver_ag.h:56
The result of an AG decomposition (LALRCATResult, LALMeanFieldResult, LALGroupedResult).
Definition ag.h:63
TableAttrs attrs
Definition ctmc.h:81
The compiled finite CTMC (core.Compiled).
Definition core.h:396
A composition snapshot (core.Model): agents in declaration order plus synchronisations.
Definition core.h:310
The result container shared by the LAL solver paths (LALCTMCResult, the AG decomposition results,...
Definition ctmc.h:96
std::string method
Definition ctmc.h:97
bool truncated
Definition ctmc.h:99
nlohmann::json diagnostics
Definition ctmc.h:108
ActionTable action_table
Definition ctmc.h:104
StateTable state_table
Definition ctmc.h:103
std::optional< std::string > fallback_reason
Definition ctmc.h:100
TableAttrs attrs
Definition ctmc.h:69
A support answer: (ok, reason).
Definition ag.h:300
std::optional< std::string > reason
Definition ag.h:302
The attrs of a LAL result table.
Definition ctmc.h:46
std::optional< bool > exact
Definition ctmc.h:48