LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
mam_marked_network.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_MARKED_NETWORK_H
6#define LINE_LANG_LAL_MAM_MARKED_NETWORK_H
7
8/**
9 * @file
10 * @ingroup line_lang
11 * LINE Agent Language (LAL): marked-source network decomposition with explicit
12 * visit thinning (solver_mam/lal_marked_network.py, method `marked.thinning`).
13 *
14 * Every station is analysed as a MAP/PH/1 queue fed by the thinned marked
15 * sources, solved by the C++ native `dec.source` (`mam::mam_dispatch`).
16 */
17
18#include <cmath>
19#include <map>
20#include <optional>
21#include <string>
22#include <vector>
23
25
26namespace line {
27namespace lal {
28
29/** Visit-thinning decomposition of a recognised MAP network (`lal_marked_network.solve_composition`). */
30inline MamResult marked_thinning(const Composition& model, double tol = 1e-4, long max_iter = 100, double max_phases = 64,
31 const std::string& traffic_method = "auto", const std::string& compress_method = "exponential",
32 double fit_time = 1.0, double fit_tolerance = .05,
33 const NativeDecSourceBackend& native_backend = NativeDecSourceBackend()) {
34 const Model snapshot = model.model();
35 validate_model(snapshot, true);
36 const auto rec = recognize_map(snapshot, true);
37 if (!rec.first) throw detail::mam_refusal("Model", rec.second);
38 const MapMatch& m = *rec.first;
39 double source_bytes = 0.0;
40 std::size_t mark_total = 0;
41 for (std::size_t a : m.sources) {
42 const AgentRecord& s = snapshot.agents[a];
43 const double n = static_cast<double>(s.states.size());
44 source_bytes += n * n * (m.marks.at(s.name).size() + 2.0) * 8;
45 mark_total += m.marks.at(s.name).size();
46 }
47 if (m.queues.size() > 100 || mark_total > 64 || source_bytes > 32.0 * 1024 * 1024)
48 throw detail::mam_refusal("StateSpace", "Marked network exceeds its queue or mark limit.");
49 const std::size_t count = m.queues.size();
50 std::map<std::string, std::size_t> qidx;
51 for (std::size_t i = 0; i < count; ++i) qidx[snapshot.agents[m.queues[i]].name] = i;
52 const Matrix<double> routing = detail::map_routing(snapshot, m, qidx);
53 if (detail::spectral_radius_nonneg(routing) >= 1 - 1e-12)
54 throw detail::mam_refusal("Stability", "Marked network routing must be open.");
55 Matrix<double> visits(count, count, 0.0);
56 try {
57 Matrix<double> lu(count, count, 0.0);
58 for (std::size_t i = 0; i < count; ++i)
59 for (std::size_t j = 0; j < count; ++j) lu(i, j) = (i == j ? 1.0 : 0.0) - routing(i, j);
60 const std::vector<std::size_t> piv = lu_factor(lu);
61 for (std::size_t col = 0; col < count; ++col) {
62 std::vector<double> b(count, 0.0);
63 b[col] = 1.0;
64 lu_solve(lu, piv, b);
65 for (std::size_t i = 0; i < count; ++i) visits(i, col) = b[i];
66 }
67 } catch (const NumericError&) {
68 throw detail::mam_refusal("Numerical", "Marked network visit equations are singular.");
69 }
70 struct Stream {
71 std::size_t agent;
73 std::vector<std::pair<std::string, Matrix<double>>> marked;
74 };
75 std::vector<Stream> streams;
76 std::map<std::string, std::vector<double>> distributions;
77 std::map<std::string, double> action_rates;
78 for (std::size_t a : m.sources) {
79 const AgentRecord& source = snapshot.agents[a];
80 const std::vector<std::string>& marks = m.marks.at(source.name);
81 const double n = static_cast<double>(source.states.size());
82 if (n * n * (marks.size() + 2.0) * 8 > 32.0 * 1024 * 1024)
83 throw detail::mam_refusal("StateSpace", "Marked source exceeds the storage limit.");
84 std::vector<double> phase_reward;
85 const MarkedMatrices stream = detail::source_stream(source, marks, phase_reward);
86 const Matrix<double> generator = detail::add(stream[0], stream[1]);
87 if (detail::strong_count_positive(generator) != 1)
88 throw detail::mam_refusal("Model", "Marked source phases must be irreducible.");
89 const std::vector<double> pi = detail::stationary(generator);
90 distributions[source.name] = pi;
91 double pr = 0.0;
92 for (std::size_t i = 0; i < pi.size(); ++i) pr += pi[i] * phase_reward[i];
93 action_rates[source.name + "._phase"] = pr;
94 Stream s{a, stream[0], {}};
95 for (std::size_t k = 0; k < marks.size(); ++k) {
96 const std::vector<double> rs = detail::row_sums(stream[k + 2]);
97 double rate = 0.0;
98 for (std::size_t i = 0; i < pi.size(); ++i) rate += pi[i] * rs[i];
99 action_rates[source.name + "." + marks[k]] = rate;
100 s.marked.push_back({marks[k], stream[k + 2]});
101 }
102 streams.push_back(s);
103 }
104 std::vector<double> external(count, 0.0);
105 for (const Stream& s : streams) {
106 const std::string& sname = snapshot.agents[s.agent].name;
107 for (const auto& mk : s.marked) external[qidx.at(m.sync.at(Endpoint(sname, mk.first)))] += action_rates[sname + "." + mk.first];
108 }
109 std::vector<double> rates(count, 0.0);
110 for (std::size_t j = 0; j < count; ++j)
111 for (std::size_t i = 0; i < count; ++i) rates[j] += visits(i, j) * external[i];
112 for (double r : rates)
113 if (!std::isfinite(r) || r < -1e-10)
114 throw detail::mam_refusal("Numerical", "Marked network traffic equations produced invalid rates.");
115 for (double& r : rates) r = std::max(r, 0.0);
116 for (std::size_t i = 0; i < count; ++i)
117 if (rates[i] <= 0 && m.clocks.count(snapshot.agents[m.queues[i]].name))
118 throw detail::mam_refusal("Initial", "A PH station with no arrivals can retain an initial-dependent idle phase.");
119 std::vector<double> means(count);
120 for (std::size_t i = 0; i < count; ++i) {
121 const AgentRecord& q = snapshot.agents[m.queues[i]];
122 auto it = m.clocks.find(q.name);
123 means[i] = it != m.clocks.end() ? it->second.mean : 1.0 / *q.queue_info->service_rate;
124 }
125 for (std::size_t i = 0; i < count; ++i)
126 if (rates[i] * means[i] >= static_cast<double>(snapshot.agents[m.queues[i]].queue_info->servers) * (1 - 1e-12))
127 throw detail::mam_refusal("Stability", "A marked network queue is unstable or critically loaded.");
128 QueueTable qt;
129 nlohmann::json native_scales = nlohmann::json::object();
130 nlohmann::json station_fits = nlohmann::json::array();
131 std::vector<std::vector<std::pair<std::string, double>>> feedback_rates;
132 for (std::size_t j = 0; j < count; ++j) {
133 const AgentRecord& queue = snapshot.agents[m.queues[j]];
134 std::vector<MarkedMatrices> inputs;
135 std::vector<std::string> labels;
136 std::vector<std::pair<std::string, double>> station_feedback;
137 for (const Stream& s : streams) {
138 const std::string& sname = snapshot.agents[s.agent].name;
139 const std::size_t n = s.d0.rows();
140 std::vector<double> probabilities;
141 for (const auto& mk : s.marked) probabilities.push_back(visits(qidx.at(m.sync.at(Endpoint(sname, mk.first))), j));
142 for (double p : probabilities)
143 if (p < -1e-10) throw detail::mam_refusal("Numerical", "Marked network produced a negative visit count.");
144 std::vector<double> excess;
145 double excess_total = 0.0;
146 for (std::size_t k = 0; k < s.marked.size(); ++k) {
147 const double e = std::max(0.0, probabilities[k] - 1) * action_rates[sname + "." + s.marked[k].first];
148 excess.push_back(e);
149 excess_total += e;
150 if (e > 0) {
151 const std::string label = sname + "." + s.marked[k].first;
152 bool found = false;
153 for (auto& kv : station_feedback)
154 if (kv.first == label) {
155 kv.second = e;
156 found = true;
157 }
158 if (!found) station_feedback.push_back({label, e});
159 }
160 }
161 std::vector<Matrix<double>> kept;
162 bool any_positive = false;
163 for (std::size_t k = 0; k < s.marked.size(); ++k) {
164 const double p = std::max(0.0, std::min(1.0, probabilities[k]));
165 Matrix<double> x = detail::scaled(s.marked[k].second, p);
166 for (std::size_t i = 0; i < n; ++i) x(i, i) += excess[k];
167 for (std::size_t e = 0; e < x.size(); ++e)
168 if (x[e] > 0) any_positive = true;
169 kept.push_back(x);
170 }
171 if (!any_positive) continue;
172 Matrix<double> hidden(n, n, 0.0), visible(n, n, 0.0);
173 for (std::size_t k = 0; k < s.marked.size(); ++k) {
174 const double p = std::max(0.0, std::min(1.0, probabilities[k]));
175 hidden = detail::add(hidden, detail::scaled(s.marked[k].second, 1 - p));
176 visible = detail::add(visible, kept[k]);
177 }
178 Matrix<double> d0 = detail::add(s.d0, hidden);
179 for (std::size_t i = 0; i < n; ++i) d0(i, i) -= excess_total;
180 MarkedMatrices in{d0, visible};
181 in.insert(in.end(), kept.begin(), kept.end());
182 inputs.push_back(in);
183 for (const auto& mk : s.marked) labels.push_back(sname + "." + mk.first);
184 }
185 feedback_rates.push_back(station_feedback);
186 double qlen = 0.0;
187 const long servers = queue.queue_info->servers;
188 if (inputs.empty() || rates[j] <= 0) {
189 station_fits.push_back(nullptr);
190 native_scales[queue.name] = nullptr;
191 } else {
192 double order = 1.0;
193 for (const MarkedMatrices& in : inputs) order *= static_cast<double>(in[0].rows());
194 std::string selected = traffic_method;
195 if (selected == "auto")
196 selected = order <= std::min(64.0, max_phases) ? "exact" : (inputs.size() > 1 ? "interpos" : "compress");
197 const bool materialize = order * order * (labels.size() + 2.0) * 8 <= 32.0 * 1024 * 1024;
198 std::optional<MarkedMatrices> aggregate;
199 if (materialize) {
200 mam::Mmap<double> combined = detail::to_mmap(inputs[0]);
201 for (std::size_t k = 1; k < inputs.size(); ++k) combined = mam::mmap_super(combined, detail::to_mmap(inputs[k]));
202 aggregate = detail::from_mmap(combined);
203 }
204 nlohmann::json fit = nullptr;
205 double fitted_rate = rates[j];
206 if (selected != "exact") {
207 Traffic description;
208 description.streams = inputs;
209 description.marks = labels;
210 const TrafficFit f = fit_traffic(description, aggregate, selected, compress_method, fit_time, fit_tolerance);
211 fit = nlohmann::json::object();
212 fit["method"] = selected;
213 fit["marks"] = labels;
214 fit["original_rates"] = f.before_rate;
215 fit["fitted_rates"] = f.after_rate;
216 fit["original_count_covariance"] = detail::matrix_json(f.before_cov);
217 fit["fitted_count_covariance"] = detail::matrix_json(f.after_cov);
218 fit["rate_error"] = f.rate_error;
219 fit["count_covariance_error"] = f.covariance_error;
220 fit["fit_time"] = fit_time;
221 fit["fit_tolerance"] = fit_tolerance;
222 fitted_rate = detail::sum(f.after_rate);
223 aggregate = f.fitted;
224 }
225 if (!aggregate || static_cast<double>((*aggregate)[0].rows()) > max_phases)
226 throw detail::mam_refusal("StateSpace", "A marked station exceeds the phase limit.");
227 auto ck = m.clocks.find(queue.name);
228 if (ck != m.clocks.end() &&
229 static_cast<double>((*aggregate)[0].rows() * snapshot.agents[ck->second.agent].states.size()) > max_phases)
230 throw detail::mam_refusal("StateSpace", "A marked MAP/PH station exceeds the phase limit.");
231 if (fitted_rate * means[j] >= static_cast<double>(servers) * (1 - 1e-12))
232 throw detail::mam_refusal("Stability", "A fitted marked station is unstable.");
233 const double service_scale = ck != m.clocks.end() ? detail::max_abs(ck->second.T) : *queue.queue_info->service_rate;
234 const double native_scale = std::max({detail::max_abs((*aggregate)[0]), detail::max_abs((*aggregate)[1]), service_scale});
235 if (!std::isfinite(native_scale) || native_scale <= 0)
236 throw detail::mam_refusal("Numerical", "Marked station has an invalid time scale.");
237 native_scales[queue.name] = native_scale;
238 std::vector<std::pair<std::optional<std::pair<std::vector<double>, Matrix<double>>>, double>> services;
239 if (ck != m.clocks.end())
240 services.push_back({std::make_pair(ck->second.alpha, detail::scaled(ck->second.T, 1.0 / native_scale)), 0.0});
241 else
242 services.push_back({std::nullopt, *queue.queue_info->service_rate / native_scale});
243 const auto native = detail::run_native_dec_source(
244 native_backend, detail::scaled((*aggregate)[0], 1.0 / native_scale), detail::scaled((*aggregate)[1], 1.0 / native_scale), services,
245 std::vector<long>{servers}, Matrix<double>(1, 1, 0.0), 0, "LAL_Marked_Station", "Queue", tol, max_iter, max_phases);
246 qlen = native.first[0];
247 if (!std::isfinite(qlen) || qlen < 0)
248 throw detail::mam_refusal("Numerical", "Marked station decomposition returned invalid queue length.");
249 const double native_throughput = native.second[0] * native_scale;
250 const double throughput_scale = std::max(std::fabs(fitted_rate), detail::tiny());
251 if (!std::isfinite(native_throughput) || std::fabs(native_throughput - fitted_rate) > 1e-6 * throughput_scale)
252 throw detail::mam_refusal("Numerical", "Native MAM station did not preserve the fitted traffic rate.");
253 station_fits.push_back(fit);
254 }
255 const double util = rates[j] * means[j] / static_cast<double>(servers);
256 const double busy = servers == 1 ? util : std::numeric_limits<double>::quiet_NaN();
257 const double response = rates[j] > 0 ? qlen / rates[j] : std::numeric_limits<double>::quiet_NaN();
258 qt.rows.push_back(QueueRow{queue.name, qlen, busy, util, rates[j], rates[j], response});
259 }
260 MamResult res;
261 detail::clock_rows_and_rates(snapshot, m, rates, qidx, distributions, action_rates, res.state_table);
262 for (const std::string& label : detail::active_labels(snapshot))
263 res.action_table.rows.push_back(ActionRow{label, detail::rate_of(action_rates, label)});
264 const bool truncated = model.source_truncated;
265 for (TableAttrs* at : {&res.state_table.attrs, &res.action_table.attrs, &qt.attrs}) {
266 at->method = "marked.thinning";
267 at->exact = false;
268 at->truncated = truncated;
269 }
270 double residual = 0.0;
271 for (std::size_t i = 0; i < count; ++i) {
272 double r = rates[i] - external[i];
273 for (std::size_t k = 0; k < count; ++k) r -= routing(k, i) * rates[k];
274 residual = std::max(residual, std::fabs(r));
275 }
276 res.method = "marked.thinning";
277 res.exact = false;
278 res.truncated = truncated;
279 res.residual = residual;
280 res.queue_measures = qt;
281 res.approximation = std::string(
282 "Visit thinning ignores queue-induced changes to source correlations and network delays; "
283 "visits beyond the first are approximated as independent Poisson events.");
284 detail::clock_fidelity(snapshot, m, res);
285 for (std::size_t i = 0; i < count; ++i)
286 if (snapshot.agents[m.queues[i]].queue_info->servers > 1)
287 res.unavailable_busy_probabilities.push_back(snapshot.agents[m.queues[i]].name);
288 // Expected visits of a mark beyond the first are clipped from the marked
289 // stream and re-injected as independent Poisson traffic (the rate below).
290 nlohmann::json excess = nlohmann::json::object();
291 std::vector<std::string> excess_order;
292 double total = 0.0;
293 nlohmann::json feedback_json = nlohmann::json::array();
294 for (std::size_t j = 0; j < count; ++j) {
295 nlohmann::json station = nlohmann::json::object();
296 for (const auto& kv : feedback_rates[j]) station[kv.first] = kv.second;
297 feedback_json.push_back(station);
298 if (feedback_rates[j].empty()) continue;
299 const std::string& qname = snapshot.agents[m.queues[j]].name;
300 excess[qname] = station;
301 excess_order.push_back(qname);
302 for (const auto& kv : feedback_rates[j]) total += kv.second;
303 }
304 res.poissonised_visit_excess = excess;
305 if (!excess_order.empty()) {
306 char buf[64];
307 std::snprintf(buf, sizeof(buf), "%.6g", total);
308 std::string joined;
309 for (std::size_t k = 0; k < excess_order.size(); ++k) joined += (k ? ", " : "") + excess_order[k];
310 *res.approximation += std::string(" Poissonised visit excess (rate ") + buf + " in total) at: " + joined + ".";
311 }
312 res.residual_kind = "traffic_balance";
313 res.has_converged = false; // Python reports converged = None
314 res.native_internal_fitting = "not exposed by native dec.source";
315 res.extra["routing"] = detail::matrix_json(routing);
316 res.extra["queue_rates"] = rates;
317 res.native_time_scales = native_scales;
318 Traffic t;
319 t.method = "marked.thinning";
320 t.exact = false;
321 t.extra["visits"] = detail::matrix_json(visits);
322 std::vector<std::string> stations;
323 for (std::size_t q : m.queues) stations.push_back(snapshot.agents[q].name);
324 t.extra["stations"] = stations;
325 t.extra["station_fits"] = station_fits;
326 t.extra["feedback_poisson_rates"] = feedback_json;
327 t.extra["poissonised_visit_excess"] = excess;
328 res.traffic = t;
329 return res;
330}
331
332} // namespace lal
333} // namespace line
334
335#endif
std::size_t size() const
Definition matrix.h:91
The algorithm cannot produce a trustworthy answer on this instance: LINE:numerical:<kind>.
Definition error.h:110
A collection of agents and embedded LINE models with atomic synchronisations (Composition).
Definition builder.h:655
Model model(const std::vector< Sync > *syncs=nullptr, const std::vector< ExtSync > *ext_syncs=nullptr) const
The current model snapshot (_model).
Definition builder.h:906
LINE Agent Language (LAL): lowering of a restricted open MAP/PH network to the native MAM dec....
Definition ag.h:49
std::vector< Matrix< double > > MarkedMatrices
A marked process as Python's list [D0, D1, D1_1, ..., D1_K].
Definition mam_common.h:54
std::pair< std::string, std::string > Endpoint
(agent, action).
Definition core.h:139
std::vector< Event > selected(const std::vector< Event > &events)
Apply maximal progress and immediate priorities to the enabled events (selected).
Definition core.h:746
MamResult marked_thinning(const Composition &model, double tol=1e-4, long max_iter=100, double max_phases=64, const std::string &traffic_method="auto", const std::string &compress_method="exponential", double fit_time=1.0, double fit_tolerance=.05, const NativeDecSourceBackend &native_backend=NativeDecSourceBackend())
Visit-thinning decomposition of a recognised MAP network (lal_marked_network.solve_composition).
TrafficFit fit_traffic(const Traffic &traffic, const std::optional< MarkedMatrices > &original, const std::string &method, const std::string &compress_method, double fit_time, double fit_tolerance, const TrafficFitBackend &backend=TrafficFitBackend())
Fit offered marked streams and enforce a finite-time counting budget (fit_traffic).
std::pair< std::optional< MapMatch >, std::string > recognize_map(const Model &snapshot, bool allow_split=false)
Recognise a restricted open MAP/PH network (lal_map_network.recognize).
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::function< std::pair< std::vector< double >, std::vector< double > >(const Matrix< double > &, const Matrix< double > &, const NativeServices &, const std::vector< long > &, const Matrix< double > &, std::size_t, const std::string &, const std::string &, double, long, double)> NativeDecSourceBackend
The native dec.source solve behind map_network and marked_thinning (Python's SolverMAM(network,...
Mmap< T > mmap_super(const Mmap< T > &a, const Mmap< T > &b)
Superposition of two MMAPs: the phase process is the product chain, and the class list of the result ...
Definition mmap_lambda.h:88
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< std::string > states
Definition core.h:286
std::optional< QueueInfo > queue_info
Definition core.h:292
The union of Python's LAL MAM result dataclasses.
Definition mam_common.h:118
nlohmann::json extra
Definition mam_common.h:148
std::optional< std::string > approximation
Definition mam_common.h:137
std::optional< QueueTable > queue_measures
Definition mam_common.h:127
std::optional< Traffic > traffic
Definition mam_common.h:126
std::optional< std::string > residual_kind
Definition mam_common.h:121
nlohmann::json native_internal_fitting
null: absent
Definition mam_common.h:147
bool has_converged
whether the lowering reports converged at all
Definition mam_common.h:149
std::vector< std::string > unavailable_busy_probabilities
multiserver queues: Busy is NaN
Definition mam_common.h:143
nlohmann::json poissonised_visit_excess
Definition mam_common.h:146
nlohmann::json native_time_scales
marked.thinning: station -> scale (null without input); null: absent
Definition mam_common.h:145
The recognised MAP network (lal_map_network.recognize tuple).
std::vector< std::size_t > queues
std::map< std::string, std::vector< std::string > > marks
std::vector< std::size_t > sources
std::map< std::string, ServiceClock > clocks
keyed by queue name
std::map< Endpoint, std::string > sync
A composition snapshot (core.Model): agents in declaration order plus synchronisations.
Definition core.h:310
std::vector< AgentRecord > agents
Definition core.h:311
One row of getQueueTable(): Agent, QLen, Busy, Util, ArvR, Tput, RespT.
Definition mam_common.h:96
std::vector< QueueRow > rows
Definition mam_common.h:107
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
TableAttrs attrs
Definition ctmc.h:69
The attrs of a LAL result table.
Definition ctmc.h:46
Output of fit_traffic.
MarkedMatrices fitted
Matrix< double > before_cov
Matrix< double > after_cov
std::vector< double > before_rate
std::vector< double > after_rate
The traffic dictionary of a MAM result (result.traffic).
Definition mam_common.h:67
std::string method
Definition mam_common.h:69
nlohmann::json extra
Definition mam_common.h:92
std::vector< std::string > marks
Definition mam_common.h:74
std::vector< MarkedMatrices > streams
Definition mam_common.h:76
An MMAP: the underlying MAP plus the per-class arrival matrices.
Definition mmap_lambda.h:45