LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
mam_jackson.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 */
5#ifndef LINE_LANG_LAL_MAM_JACKSON_H
6#define LINE_LANG_LAL_MAM_JACKSON_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * LINE Agent Language (LAL): lossless lowering of open exponential LAL
12 * networks to scalar M/M/c factors (solver_mam/lal_jackson.py).
13 *
14 * The routing spectral radius is taken by Gelfand's formula on the
15 * nonnegative routing matrix (`detail::spectral_radius_nonneg`), where Python
16 * takes the largest eigenvalue modulus; the two agree for a nonnegative matrix.
17 */
18
19#include <cmath>
20#include <map>
21#include <optional>
22#include <set>
23#include <string>
24#include <tuple>
25#include <vector>
26
28
29namespace line {
30namespace lal {
31
32/** The recognised Jackson structure (`lal_jackson.recognize`). */
34 std::vector<std::size_t> queues; ///< agent indices of the unbounded queues
35 std::vector<std::size_t> sources; ///< agent indices of the one-phase Poisson sources
36 std::map<Endpoint, std::string> sync; ///< active endpoint -> target queue
37};
38
39/** Conservatively recognise independent Poisson inputs and open M/M/c routing. */
40inline std::pair<std::optional<JacksonMatch>, std::string> recognize_jackson(const Model& snapshot) {
41 if (!snapshot.min_syncs.empty())
42 return {std::nullopt, "Jackson lowering does not support minimum synchronizations."};
44 std::set<std::string> names;
45 for (std::size_t a = 0; a < snapshot.agents.size(); ++a)
46 if (snapshot.agents[a].queue_info) {
47 m.queues.push_back(a);
48 names.insert(snapshot.agents[a].name);
49 }
50 bool bad = m.queues.empty();
51 for (std::size_t q : m.queues) {
52 const QueueInfo& info = *snapshot.agents[q].queue_info;
53 if (info.capacity || !info.service_inputs.empty()) bad = true;
54 }
55 if (bad) return {std::nullopt, "Jackson lowering requires unbounded exponential queue declarations."};
56 for (std::size_t a = 0; a < snapshot.agents.size(); ++a)
57 if (!names.count(snapshot.agents[a].name)) m.sources.push_back(a);
58 for (std::size_t a : m.sources) {
59 const AgentRecord& agent = snapshot.agents[a];
60 bool ok = agent.states.size() == 1;
61 for (const Transition& t : agent.transitions)
62 if (t.role != Role::Active || t.source != t.target) ok = false;
63 if (!ok) return {std::nullopt, "Jackson lowering requires independent one-phase Poisson source agents."};
64 }
65 auto contains = [](const std::vector<std::string>& v, const std::string& x) {
66 return std::find(v.begin(), v.end(), x) != v.end();
67 };
68 auto has_route = [](const QueueInfo& info, const std::string& action) {
69 for (const auto& r : info.routes)
70 if (r.first == action) return true;
71 return false;
72 };
73 for (const Sync& s : snapshot.syncs) {
74 if (s.passive.size() != 1 || !names.count(s.passive[0].first))
75 return {std::nullopt, "Jackson routing requires one unbounded queue input per synchronized event."};
76 const std::string& target = s.passive[0].first;
77 const std::string& action = s.passive[0].second;
78 if (!contains(snapshot.agent(target).queue_info->arrivals, action))
79 return {std::nullopt, "Jackson routing can only target declared queue arrivals."};
80 if (names.count(s.active.first) && !has_route(*snapshot.agent(s.active.first).queue_info, s.active.second))
81 return {std::nullopt, "Jackson routing can only synchronize declared queue departures."};
82 m.sync[s.active] = target;
83 }
84 return {m, ""};
85}
86
87namespace detail {
88
89/** Labels `agent.action` of every active transition, unique, in declaration order. */
90inline std::vector<std::string> active_labels(const Model& snapshot) {
91 std::vector<std::string> out;
92 std::set<std::string> seen;
93 for (const AgentRecord& agent : snapshot.agents)
94 for (const Transition& t : agent.transitions)
95 if (t.role == Role::Active) {
96 const std::string label = agent.name + "." + t.action;
97 if (seen.insert(label).second) out.push_back(label);
98 }
99 return out;
100}
101
102/** `action_rates[label]` with Python's KeyError as an internal error. */
103inline double rate_of(const std::map<std::string, double>& rates, const std::string& label) {
104 auto it = rates.find(label);
105 if (it == rates.end()) throw InternalError("LAL MAM lowering produced no throughput for " + label);
106 return it->second;
107}
108
109inline nlohmann::json matrix_json(const Matrix<double>& m) {
110 nlohmann::json out = nlohmann::json::array();
111 for (std::size_t i = 0; i < m.rows(); ++i) {
112 nlohmann::json row = nlohmann::json::array();
113 for (std::size_t j = 0; j < m.cols(); ++j) row.push_back(m(i, j));
114 out.push_back(row);
115 }
116 return out;
117}
118
119/** Solve `A x = b` by dense LU; NumericError on a singular `A`. */
120inline std::vector<double> lu_solve_vec(Matrix<double> A, std::vector<double> b) {
121 std::vector<std::size_t> piv = lu_factor(A);
122 lu_solve(A, piv, b);
123 return b;
124}
125
126} // namespace detail
127
128/** Product-form solution of a recognised Jackson network (`lal_jackson.solve_composition`). */
129inline MamResult jackson(const Composition& model, double max_states = 50000) {
130 const Model snapshot = model.model();
131 validate_model(snapshot, true);
132 const auto rec = recognize_jackson(snapshot);
133 if (!rec.first) throw detail::mam_refusal("Model", rec.second);
134 if (!(max_states > 0) || max_states != std::floor(max_states))
135 throw InputError("lal_max_states must be a positive integer");
136 const JacksonMatch& match = *rec.first;
137 const std::size_t n = match.queues.size();
138 std::map<std::string, std::size_t> index;
139 for (std::size_t i = 0; i < n; ++i) index[snapshot.agents[match.queues[i]].name] = i;
140 if (n > 512) throw detail::mam_refusal("StateSpace", "Jackson traffic system exceeds 512 queues.");
141 std::vector<double> external(n, 0.0);
142 std::vector<std::pair<Endpoint, double>> source_rates; // insertion-ordered dict
143 auto add_rate = [&](const Endpoint& e, double r) {
144 for (auto& kv : source_rates)
145 if (kv.first == e) {
146 kv.second += r;
147 return;
148 }
149 source_rates.push_back({e, r});
150 };
151 for (std::size_t a : match.sources)
152 for (const Transition& t : snapshot.agents[a].transitions) add_rate(Endpoint(snapshot.agents[a].name, t.action), t.value);
153 for (const auto& kv : source_rates) {
154 auto it = match.sync.find(kv.first);
155 if (it != match.sync.end()) external[index[it->second]] += kv.second;
156 }
157 Matrix<double> routing(n, n, 0.0);
158 for (std::size_t i = 0; i < n; ++i) {
159 const AgentRecord& q = snapshot.agents[match.queues[i]];
160 for (const auto& route : q.queue_info->routes) {
161 auto it = match.sync.find(Endpoint(q.name, route.first));
162 if (it != match.sync.end()) routing(i, index[it->second]) += route.second;
163 }
164 }
165 if (detail::spectral_radius_nonneg(routing) >= 1 - 1e-12)
166 throw detail::mam_refusal("Stability", "Jackson routing must be open, with every job eventually departing.");
167 Matrix<double> system(n, n, 0.0);
168 for (std::size_t i = 0; i < n; ++i)
169 for (std::size_t j = 0; j < n; ++j) system(i, j) = (i == j ? 1.0 : 0.0) - routing(j, i);
170 std::vector<double> rates;
171 try {
172 rates = detail::lu_solve_vec(system, external);
173 } catch (const NumericError&) {
174 throw detail::mam_refusal("Numerical", "Jackson traffic equations are singular.");
175 }
176 double residual = 0.0, rmax = -std::numeric_limits<double>::infinity(), rmin = std::numeric_limits<double>::infinity();
177 bool finite = true;
178 for (std::size_t i = 0; i < n; ++i) {
179 double r = rates[i] - external[i];
180 for (std::size_t j = 0; j < n; ++j) r -= routing(j, i) * rates[j];
181 residual = std::max(residual, std::fabs(r));
182 finite = finite && std::isfinite(rates[i]);
183 rmax = std::max(rmax, rates[i]);
184 rmin = std::min(rmin, rates[i]);
185 }
186 if (!finite || rmin < -1e-10 || residual > 1e-8 * std::max(1.0, rmax))
187 throw detail::mam_refusal("Numerical", "Jackson traffic equations produced invalid rates.");
188 for (double& r : rates) r = std::max(r, 0.0);
189 MamResult res;
190 std::map<std::string, std::pair<std::vector<double>, double>> distributions;
191 for (std::size_t i = 0; i < n; ++i) {
192 const AgentRecord& q = snapshot.agents[match.queues[i]];
193 const double rate = rates[i], mu = *q.queue_info->service_rate;
194 const long servers = q.queue_info->servers;
195 const double rho = rate / (servers * mu);
196 if (rho >= 1 - 1e-12)
197 throw detail::mam_refusal("Stability", "Jackson queue " + q.name + " is unstable or critically loaded (utilization " +
198 detail::fmt_g(rho) + ").");
199 if (max_states < servers + 1)
200 throw detail::mam_refusal("StateSpace", "Jackson display limit must exceed the number of servers.");
201 std::vector<double> probabilities;
202 double tail = 0.0, mean = 0.0;
203 if (rate == 0) {
204 probabilities = {1.0};
205 } else {
206 const double a = rate / mu;
207 std::vector<double> log_weights(static_cast<std::size_t>(servers) + 1);
208 for (long k = 0; k <= servers; ++k) log_weights[k] = k * std::log(a) - std::lgamma(k + 1.0);
209 std::vector<double> terms(log_weights.begin(), log_weights.end() - 1);
210 terms.push_back(log_weights.back() - std::log1p(-rho));
211 double mx = -std::numeric_limits<double>::infinity();
212 for (double t : terms) mx = std::max(mx, t);
213 double acc = 0.0;
214 for (double t : terms) acc += std::exp(t - mx);
215 const double log_norm = mx + std::log(acc);
216 const double p_c = std::exp(log_weights.back() - log_norm);
217 const double erlang_c = p_c / (1 - rho);
218 mean = a + erlang_c * rho / (1 - rho);
219 const long display_limit = static_cast<long>(std::min(max_states, std::max(1000.0, servers + 1.0)));
220 for (long k = 0; k < display_limit; ++k) {
221 const double probability = k <= servers ? std::exp(log_weights[k] - log_norm)
222 : p_c * std::pow(rho, static_cast<double>(k - servers));
223 probabilities.push_back(probability);
224 if (k >= servers && probabilities.back() * rho / (1 - rho) < 1e-10) break;
225 }
226 tail = probabilities.back() * rho / (1 - rho);
227 }
228 distributions[q.name] = {probabilities, tail};
229 res.queue_means[q.name] = mean;
230 }
231 for (const AgentRecord& agent : snapshot.agents) {
232 if (index.count(agent.name)) {
233 const auto& d = distributions[agent.name];
234 for (std::size_t k = 0; k < d.first.size(); ++k)
235 res.state_table.rows.push_back(StateRow{agent.name, "n_" + std::to_string(k), d.first[k]});
236 res.state_table.rows.push_back(StateRow{agent.name, "n_ge_" + std::to_string(d.first.size()), d.second});
237 } else {
238 res.state_table.rows.push_back(StateRow{agent.name, agent.states[0], 1.0});
239 }
240 }
241 std::map<std::string, double> action_rates;
242 for (const auto& kv : source_rates) action_rates[endpoint_label(kv.first)] = kv.second;
243 for (std::size_t i = 0; i < n; ++i) {
244 const AgentRecord& q = snapshot.agents[match.queues[i]];
245 for (const auto& route : q.queue_info->routes) action_rates[q.name + "." + route.first] = rates[i] * route.second;
246 }
247 for (const std::string& label : detail::active_labels(snapshot))
248 res.action_table.rows.push_back(ActionRow{label, detail::rate_of(action_rates, label)});
249 const bool truncated = model.source_truncated;
250 for (TableAttrs* at : {&res.state_table.attrs, &res.action_table.attrs}) {
251 at->method = "jackson";
252 at->exact = !truncated;
253 at->truncated = truncated;
254 }
255 res.method = "jackson";
256 res.exact = !truncated;
257 res.truncated = truncated;
258 res.residual = residual;
259 res.residual_kind = "traffic_balance";
260 res.extra["routing"] = detail::matrix_json(routing);
261 res.extra["external_rates"] = external;
262 res.extra["queue_rates"] = rates;
263 return res;
264}
265
266} // namespace lal
267} // namespace line
268
269#endif
InputError(const std::string &what)
Definition error.h:105
InternalError(const std::string &what)
Definition error.h:133
The algorithm cannot produce a trustworthy answer on this instance: LINE:numerical:<kind>.
Definition error.h:110
Transition(model, name): a Petri-net transition, with its modes declared after it as MATLAB,...
Definition nodes.h:323
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
LINE Agent Language (LAL): shared types and numerical helpers of the SolverMAM LAL paths (python/line...
Definition ag.h:49
std::pair< std::string, std::string > Endpoint
(agent, action).
Definition core.h:139
MamResult jackson(const Composition &model, double max_states=50000)
Product-form solution of a recognised Jackson network (lal_jackson.solve_composition).
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::pair< std::optional< JacksonMatch >, std::string > recognize_jackson(const Model &snapshot)
Conservatively recognise independent Poisson inputs and open M/M/c routing.
Definition mam_jackson.h:40
std::string endpoint_label(const Endpoint &e)
Definition core.h:141
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
void lu_solve(const Matrix< T > &LU, const std::vector< std::size_t > &piv, std::vector< T > &b)
Solve LUx = Pb in place on b, using the factors from lu_factor.
Definition lu.h:94
std::vector< std::size_t > lu_factor(Matrix< T > &A)
In-place LU of A (n x n).
Definition lu.h:48
One row of an action table: Action, Throughput.
Definition ctmc.h:62
std::vector< ActionRow > rows
Definition ctmc.h:80
TableAttrs attrs
Definition ctmc.h:81
The immutable agent record (core.Agent).
Definition core.h:284
std::string name
Definition core.h:285
std::vector< Transition > transitions
Definition core.h:288
std::vector< std::string > states
Definition core.h:286
std::optional< QueueInfo > queue_info
Definition core.h:292
The recognised Jackson structure (lal_jackson.recognize).
Definition mam_jackson.h:33
std::vector< std::size_t > queues
agent indices of the unbounded queues
Definition mam_jackson.h:34
std::map< Endpoint, std::string > sync
active endpoint -> target queue
Definition mam_jackson.h:36
std::vector< std::size_t > sources
agent indices of the one-phase Poisson sources
Definition mam_jackson.h:35
The union of Python's LAL MAM result dataclasses.
Definition mam_common.h:118
nlohmann::json extra
Definition mam_common.h:148
std::map< std::string, double > queue_means
empty: Python has no queue_means
Definition mam_common.h:128
std::optional< std::string > residual_kind
Definition mam_common.h:121
A composition snapshot (core.Model): agents in declaration order plus synchronisations.
Definition core.h:310
std::vector< MinSync > min_syncs
Definition core.h:313
std::vector< Sync > syncs
Definition core.h:312
std::vector< AgentRecord > agents
Definition core.h:311
const AgentRecord & agent(const std::string &name) const
Definition core.h:324
Structured queue declaration retained while a queue agent is unmodified (queue_info).
Definition core.h:271
std::optional< long > capacity
nullopt: unbounded
Definition core.h:272
std::vector< std::string > service_inputs
Definition core.h:277
std::vector< std::pair< std::string, double > > routes
Definition core.h:280
std::string method
Definition ctmc.h:97
bool truncated
Definition ctmc.h:99
ActionTable action_table
Definition ctmc.h:104
StateTable state_table
Definition ctmc.h:103
One row of a state table: Agent, State, Probability.
Definition ctmc.h:55
TableAttrs attrs
Definition ctmc.h:69
std::vector< StateRow > rows
Definition ctmc.h:68
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
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