LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
solver_ag_runner.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_SOLVERS_AG_SOLVER_AG_RUNNER_H
6#define LINE_SOLVERS_AG_SOLVER_AG_RUNNER_H
7
8/**
9 * @file solver_ag_runner.h
10 * @ingroup line_solvers
11 * @brief The gates and the dispatch of the agent-based (RCAT) solver.
12 *
13 * The twin of solver_mam_runner.h for SolverAG: the valid method list, the
14 * structural gate that decides whether the RCAT decomposition can represent the
15 * model at all, and the conversion every AG method needs before the fixed point.
16 *
17 * These gates used to live in SolverMAM, which was answering for two unrelated
18 * decompositions at once: RCAT decomposes the MODEL into cooperating agents,
19 * every other MAM method decomposes its TRAFFIC. They share the shape of the
20 * answer and nothing else.
21 */
22
23#include <algorithm>
24#include <cmath>
25#include <string>
26#include <vector>
27
34#include "line/util/error.h"
36
37namespace line {
38namespace ag {
39
40namespace runner_detail {
41
42/** Every method SolverAG serves. */
43inline std::vector<std::string> list_valid_methods() {
44 // the names and their order are this solver's row of the method registry
45 // (doc/line-methods.json), minus the rows dispatched only by the finite LAL
46 // Composition (lal::SolverAG::listLALMethods): a Network is never offered
47 // them (Python _NETWORK_METHODS).
48 static const std::vector<std::string> lal_only{"ctmc", "rcat", "meanfield", "grouped"};
49 std::vector<std::string> methods;
50 for (const std::string& m : ::line::method_registry::methods("AG"))
51 if (std::find(lal_only.begin(), lal_only.end(), m) == lal_only.end()) methods.push_back(m);
52 return methods;
53}
54
55/** An unlisted method is refused rather than silently resolved. */
56inline void check_method(const std::string& method) {
57 const std::vector<std::string> valid = list_valid_methods();
58 if (std::find(valid.begin(), valid.end(), method) == valid.end()) {
59 std::string names;
60 for (std::size_t i = 0; i < valid.size(); ++i) {
61 names += (i ? ", " : "") + valid[i];
62 }
63 throw InputError("SolverAG: unknown method '" + method + "'; valid methods are "
64 + names);
65 }
66}
67
68/**
69 * `SolverAG.supportsModelMethod`: the structural gate of the RCAT decomposition,
70 * as the REASON it refuses, empty when the model is admissible.
71 *
72 * RCAT gives every agent a service-phase and an arrival-phase dimension, so any
73 * law with a genuine (D0,D1) Markovian representation is admissible; see
74 * ag::rcat_supports_process for what is not. A signal is a trigger with no
75 * service, so its service entry is never read; only its Source arrival rate is,
76 * and that one must stay exponential because the removal is folded into the
77 * agent as a scalar rate.
78 *
79 * A STRING RATHER THAN A THROW, the shape `ba::method_refusal` and
80 * `mam::mam_model_method_refusal` already carry: the AUTO report has to ASK the
81 * question without raising, so that a pair it offers is a pair the run accepts.
82 * `check_model_method` below is the throwing form the analyzer keeps.
83 */
84template <class T>
85std::string method_refusal(const qn::NetworkStruct<T>& L, const std::string& method) {
87 for (std::size_t i = 0; i < L.nstations; ++i) {
88 for (std::size_t r = 0; r < L.nclasses; ++r) {
89 // has_service_law, not disabled: a Join has rates = Inf and no
90 // service law, and would otherwise be refused out of hand.
91 if (!L.has_service_law(i, r) || !(L.rates(i, r) > num_traits<T>::from_int(0)))
92 continue;
93 const bool is_signal = r < L.issignal.size() && L.issignal[r];
94 const bool is_source = L.stations[i].nodetype == qn::NodeType::Source;
95 if (is_signal && !is_source) continue;
96 if (is_signal) {
97 if (L.service[i][r].type == ProcessType::EXP) continue;
98 return std::string(
99 "SolverAG: the " + method +
100 " method needs an exponential signal arrival process (a removal signal "
101 "is folded into the agent as a scalar rate), but station '" +
102 L.stations[i].name + "' class '" + L.classes[r].name + "' is " +
103 lang::process_to_text(L.service[i][r].type) +
104 ". Use SolverMAM (-s mam, method 'dec.source') for such models");
105 }
106 if (rcat_supports_process(L.service[i][r].type)) continue;
107 return std::string(
108 "SolverAG: the " + method +
109 " method supports processes with a Markovian (D0,D1) representation only "
110 "(RCAT builds a phase dimension per agent out of it), but station '" +
111 L.stations[i].name + "' class '" + L.classes[r].name + "' is " +
112 lang::process_to_text(L.service[i][r].type) +
113 ". Use SolverMAM (-s mam, method 'dec.source') for such models");
114 }
115 }
116 // ROUTING MUST BE STATE INDEPENDENT, and the featset gate above CANNOT check
117 // this, which is why the explicit loop stays. build_rcat reads sn.rt once and
118 // stores it as RcatAction::prob; for RROBIN, WRROBIN, JSQ, SQ or SDR that entry
119 // is only a state-independent PLACEHOLDER (SyncEvent::prob in state_events.h
120 // says so, and the generator is meant to re-evaluate the split per state), so
121 // solving from it answers a DIFFERENT model at a plausible number.
122 //
123 // WHY THE FEATSET MISSES IT: `used_lang_features` registers a routing feature
124 // only inside the Queue/Delay branch and the Router/Dispatcher one. The Source
125 // branch deliberately does not -- "MATLAB registers no discipline and no
126 // routing for it" -- so a JSQ declared ON A SOURCE, which is the canonical JSQ
127 // model, never reaches the DECLARED-vs-USED comparison at all. That omission is
128 // faithful to the reference, so it cannot simply be widened here; it means the
129 // gate and this loop cover different ground and both are needed.
130 for (std::size_t nd = 0; nd < L.nodes.size(); ++nd) {
131 for (std::size_t r = 0; r < L.nodes[nd].routing.size(); ++r) {
132 const lang::RoutingStrategy rs = L.nodes[nd].routing[r];
135 continue;
136 }
137 return std::string("SolverAG: the ") + method + " method needs state-independent "
138 "routing (RCAT folds the split into a fixed action probability), but node '" +
139 L.nodes[nd].name + "' routes class '" + L.classes[r].name + "' by " +
141 ", whose share depends on the network state. Use SolverCTMC, SolverSSA or "
142 "SolverLDES, which re-evaluate the split per state";
143 }
144 }
145
146 // build_rcat never reads sn.nservers, so a c-server station would be driven
147 // at rho = lambda/mu instead of lambda/(c mu).
148 for (std::size_t i = 0; i < L.nstations; ++i) {
149 if (std::isfinite(L.stations[i].nservers) && L.stations[i].nservers > 1.0) {
150 return std::string(
151 "SolverAG: the " + method +
152 " method supports single-server stations only (RCAT does not model "
153 "sn.nservers), but station '" + L.stations[i].name + "' has " +
154 std::to_string(static_cast<long long>(L.stations[i].nservers)) +
155 " servers. Use SolverMAM (-s mam, method 'dec.source') for multiserver "
156 "models");
157 }
158 }
159
160 // An infinite server is a single-server component too, served exactly only
161 // when its closed chain is conditioned; see inf_supports_reason.
162 const std::string inf_why = inf_supports_reason(L);
163 if (!inf_why.empty()) return inf_why;
164
165 // A FINITE BUFFER IS NOT SOMETHING RCAT CAN CARRY, and it was being answered
166 // rather than refused: nothing under solvers/ag reads st.cap or st.classcap,
167 // so a capped station was decomposed as an unbounded one and the table
168 // reported the UNCONSTRAINED figures (a closed 2-job tandem with cap 1 on the
169 // second queue returned the same numbers with and without the cap, 1.09 jobs
170 // in a buffer of 1). Lowering the agent's level bound (nlev = njobs(r)+1) to
171 // the buffer would not fix it: the top-level boundary is a self-loop, which
172 // LOSES the arrival, whereas a closed job refused at a full buffer must BLOCK
173 // the upstream departure, and that coupling is exactly the independence RCAT
174 // assumes. see _kb/06-solver-catalog.md
175 return qn::binding_capacity_reason(std::string("SolverAG"), L);
176}
177
178/** The refusal above as the analyzer takes it: raise when there is one. */
179template <class T>
180void check_model_method(const qn::NetworkStruct<T>& L, const std::string& method) {
181 const std::string why = method_refusal(L, method);
182 if (!why.empty()) throw UnsupportedError(ErrorKind{"Model"}, why);
183}
184
185} // namespace runner_detail
186
187/**
188 * Every method SolverAG serves, as the other families expose theirs.
189 *
190 * `auto_family_methods` asks each family for its own list rather than keeping a
191 * second copy, so the "ag" row of the AUTO report is this list and cannot drift
192 * from the one `check_method` refuses against.
193 */
194inline std::vector<std::string> list_valid_methods() {
195 return runner_detail::list_valid_methods();
196}
197
198/**
199 * The gates and the dispatch of SolverAG's runAnalyzer.
200 *
201 * The conversion is not method-dependent, unlike SolverMAM's: EVERY AG method
202 * builds a CTMC per agent out of (D0,D1), so a preserved Det would reach it with
203 * no matrix at all and be read back as its mean rate, and a concentrated matrix
204 * exponential is not a generator at all.
205 */
206template <class T>
208 runner_detail::check_method(opt.method);
209 runner_detail::check_model_method(L, opt.method);
210 // runAnalyzerChecks' universal feature gate. `ag_feature_set` transcribes
211 // SolverAG.getFeatureSet name for name and has existed since the port landed,
212 // but NOTHING CALLED IT until 2026-08-19: its only two references were its own
213 // definition and a comment in mam_feature_set, so every other family here was
214 // gated and AG was not.
215 //
216 // AFTER check_model_method, following SolverCTMC: a solver's own check names
217 // WHY a construct cannot be served, and the gate only names the construct. For
218 // a matrix exponential that is the difference between "supports processes with
219 // a Markovian (D0,D1) representation only (RCAT builds a phase dimension per
220 // agent out of it)" and a bare feature name -- the set withholds ME either way,
221 // so ordering decides only which message the caller reads. Reversing these two
222 // lines is a silent downgrade of every AG refusal that has a specific reason.
223 qn::feature_gate("SolverAG", qn::ag_feature_set(opt.method), L);
224
225 // sn_nonmarkov_toph evaluates densities and fits moments, so it exists only
226 // for a transcendental arithmetic and STATIC-ASSERTS otherwise. The guard is
227 // `if constexpr` rather than a run-time test because the CLI instantiates
228 // this template for the exact Rational backend as well, and an unguarded
229 // call would fail to COMPILE there rather than refuse at run time. Under an
230 // exact arithmetic solver_ag itself raises the refusal, which is where it
231 // belongs: it is the fixed point's tolerance and the QBD's square root that
232 // cannot be represented, not the conversion.
233 qn::NetworkStruct<T> converted;
234 const qn::NetworkStruct<T>* Lp = &L;
235 if constexpr (num_traits<T>::has_transcendental) {
236 if (api::nonmkv_enabled(opt.nonmkv) && api::sn_has_nonmarkov(L, /*preserve_det=*/false)) {
237 converted = L;
239 no.order = opt.nonmkv_order;
240 no.preserve_det = false;
242 api::sn_nonmarkov_toph(converted, no);
243 Lp = &converted;
244 }
245 }
246
247 return solver_ag(*Lp, opt);
248}
249
250} // namespace ag
251} // namespace line
252
253#endif // LINE_SOLVERS_AG_SOLVER_AG_RUNNER_H
Options of the agent-based (RCAT) solver.
InputError(const std::string &what)
Definition error.h:105
UnsupportedError(const std::string &what)
Definition error.h:119
A network plus its refreshed NetworkStruct.
The exception types the port throws.
The language-feature gate: what a MODEL uses against what a SOLVER declares.
The method names of each solver, in listing order.
AgResult< T > solver_ag_solve(const qn::NetworkStruct< T > &L, const AgOptions &opt)
The gates and the dispatch of SolverAG's runAnalyzer.
std::string inf_supports_reason(const qn::NetworkStruct< T > &L)
Why the RCAT decomposition cannot serve an infinite-server station of this model, or "" when it can (...
Definition solver_ag.h:1706
std::vector< std::string > list_valid_methods()
Every method SolverAG serves, as the other families expose theirs.
AgResult< T > solver_ag(const qn::NetworkStruct< T > &L, const AgOptions &opt, std::size_t max_states=0)
Port of solver_ag.m.
Definition solver_ag.h:1809
bool rcat_supports_process(lang::ProcessType t)
The process types the RCAT construction can give a phase dimension to.
Definition solver_ag.h:1659
bool sn_has_nonmarkov(const qn::NetworkStruct< T > &sn, bool preserve_det=false)
Whether any law in the struct would be replaced, so a caller can skip copying the struct when there i...
bool nonmkv_enabled(const std::string &method)
Resolve options.config.nonmkv to NonmarkovOptions::enabled.
@ Ph
Bernstein density fit: a genuine phase-type, shape-carrying.
void sn_nonmarkov_toph(qn::NetworkStruct< T > &sn, const NonmarkovOptions &opts=NonmarkovOptions())
Replace every non-Markovian service and firing law by a Markovian surrogate.
RoutingStrategy
Routing strategies, with the values of MATLAB RoutingStrategy.
Definition lang_types.h:430
ProcessType
Distribution kinds, with the values of MATLAB ProcessType.
Definition lang_types.h:524
const char * process_to_text(ProcessType p)
The MATLAB ProcessType name, as sn.procid prints it.
Definition lang_types.h:655
const char * routing_to_text(RoutingStrategy r)
Definition lang_types.h:443
std::vector< std::string > methods(const std::string &solver)
Every method name the solver can be asked for, in listing order.
void feature_gate(const std::string &solver, const FeatureSet &declared, const NetworkStruct< T > &sn, const std::string &requested_method="", const std::string &resolved_method="")
runAnalyzerChecks: refuse a model the solver does not declare, by name.
FeatureSet ag_feature_set(const std::string &)
SolverAG.getFeatureSet: what the RCAT decomposition can represent.
std::string binding_capacity_reason(const std::string &solver, const NetworkStruct< T > &sn)
The refusal check_binding_capacity raises, as a string, or empty when no buffer binds.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
A queueing network and its refreshed NetworkStruct.
Replace every non-Markovian service and firing law by a Markovian surrogate.
The DECLARED side of the gate: one feature set per solver.
Port of solver_ag.m: the RCAT (Reversed Compound Agent Theorem) analyzers, reached by methods 'inap',...
What the RCAT analyzer returns beyond the metrics.
Definition solver_ag.h:1788
options.config.nonmkv and friends.
std::size_t order
nonmkvorder, the phase budget
PhFit phfit
which surrogate family
bool preserve_det
Leave Det alone for the exact MAP/D/c branch, options.config.preserveDet.