5#ifndef LINE_LANG_LAL_MAM_MAP_NETWORK_H
6#define LINE_LANG_LAL_MAM_MAP_NETWORK_H
50 std::vector<std::pair<std::string, ClockRoute>>
routes;
63 std::map<std::string, std::vector<std::string>>
marks;
64 std::map<Endpoint, std::string>
sync;
66 std::map<std::string, ServiceClock>
clocks;
71inline bool contains_str(
const std::vector<std::string>& v,
const std::string& x) {
72 return std::find(v.begin(), v.end(), x) != v.end();
75inline bool phase_named(
const AgentRecord& a) {
76 for (std::size_t i = 0; i < a.states.size(); ++i)
77 if (a.states[i] !=
"phase_" + std::to_string(i))
return false;
81inline bool all_active(
const AgentRecord& a) {
82 for (
const Transition& t : a.transitions)
87inline const std::string* find_route(
const QueueInfo& info,
const std::string& action,
double* probability =
nullptr) {
88 for (
const auto& r : info.routes)
89 if (r.first == action) {
90 if (probability) *probability = r.second;
99inline std::pair<std::optional<MapMatch>, std::string>
recognize_map(
const Model& snapshot,
bool allow_split =
false) {
100 typedef std::pair<std::optional<MapMatch>, std::string> Out;
101 if (!snapshot.
min_syncs.empty())
return Out{std::nullopt,
"MAP network lowering does not support minimum synchronizations."};
103 std::set<std::string> queue_names;
104 for (std::size_t a = 0; a < snapshot.
agents.size(); ++a)
105 if (snapshot.
agents[a].queue_info) {
107 queue_names.insert(snapshot.
agents[a].name);
109 bool bad = m.
queues.size() < 2;
110 for (std::size_t q : m.
queues)
111 if (snapshot.
agents[q].queue_info->capacity) bad =
true;
112 if (bad)
return Out{std::nullopt,
"MAP network lowering requires at least two unbounded queues."};
113 for (std::size_t q : m.
queues)
114 if (!snapshot.
agents[q].queue_info->service_inputs.empty() && snapshot.
agents[q].queue_info->servers != 1)
115 return Out{std::nullopt,
"MAP network PH-service lowering requires a single server per PH station."};
116 if (m.
queues.size() > 100)
return Out{std::nullopt,
"MAP network lowering supports at most 100 queues."};
117 std::map<Endpoint, std::pair<Endpoint, std::vector<Endpoint>>> passive_bindings;
120 std::set<std::string> clock_names;
121 for (std::size_t qi : m.
queues) {
125 if (inputs.empty())
continue;
126 std::vector<std::pair<std::string, std::pair<Endpoint, std::vector<Endpoint>>>> bindings;
127 for (
const std::string& action : inputs) {
128 auto it = passive_bindings.find(
Endpoint(q.
name, action));
129 if (it == passive_bindings.end())
return Out{std::nullopt,
"PH service completions must synchronize with their queue."};
130 bindings.push_back({action, it->second});
132 std::set<std::string> names;
133 for (
const auto& b : bindings) names.insert(b.second.first.first);
134 if (names.size() != 1)
return Out{std::nullopt,
"Each PH queue needs one service clock agent."};
135 const std::string name = *names.begin();
136 if (queue_names.count(name) || clock_names.count(name) || !snapshot.
has_agent(name))
137 return Out{std::nullopt,
"Each PH queue needs its own service clock agent."};
139 if (!detail::phase_named(clock) || !detail::all_active(clock))
140 return Out{std::nullopt,
"PH service clocks must be matrix-valued phase agents."};
141 std::set<std::string> marks, actions;
144 for (
const auto& b : bindings) actions.insert(b.second.first.second);
145 if (marks != actions || actions.size() != bindings.size())
146 return Out{std::nullopt,
"Every PH completion mark must have one queue service input."};
149 for (
const auto& b : bindings) {
150 const std::string& input_name = b.first;
151 const Endpoint& active = b.second.first;
152 const std::vector<Endpoint>& partners = b.second.second;
153 std::vector<Endpoint> arrivals;
155 if (e !=
Endpoint(q.
name, input_name)) arrivals.push_back(e);
156 bool ok = arrivals.size() <= 1;
158 if (!queue_names.count(e.first) || !detail::contains_str(snapshot.
agent(e.first).
queue_info->arrivals, e.second))
160 if (!ok)
return Out{std::nullopt,
"A PH completion may route to at most one queue."};
162 r.
input = input_name;
164 if (!arrivals.empty()) r.
target = arrivals[0].first;
165 bool replaced =
false;
167 if (kv.first == active.second) {
171 if (!replaced) c.
routes.push_back({active.second, r});
173 bool has_phase =
false;
175 if (t.
action ==
"_phase" && t.
value > 0) has_phase =
true;
180 ok = it != passive_bindings.end() && it->second.first ==
Endpoint(name,
"_phase") &&
183 if (!ok)
return Out{std::nullopt,
"PH service phase transitions must be enabled only while its queue is busy."};
185 const std::size_t n = clock.
states.size();
186 if (n > 256)
return Out{std::nullopt,
"PH service clock exceeds the 256-phase inspection limit."};
188 std::map<std::string, Matrix<double>> marked;
192 if (t.
action ==
"_phase") {
193 if (i != j) T(i, j) += t.
value;
198 for (
const auto& kv : c.
routes) D1 = detail::add(D1, marked[kv.first]);
199 const std::vector<double> exits = detail::row_sums(D1);
200 const std::vector<double> trow = detail::row_sums(T);
201 for (std::size_t i = 0; i < n; ++i) T(i, i) = -(trow[i] + exits[i]);
202 bool any_exit =
false;
203 for (
double e : exits)
204 if (e > 0) any_exit =
true;
205 if (!any_exit)
return Out{std::nullopt,
"PH service must eventually complete."};
206 std::vector<double> visits;
210 const std::vector<std::size_t> piv =
lu_factor(lu);
212 for (std::size_t col = 0; col < n; ++col) {
213 std::vector<double> b(n);
214 for (std::size_t i = 0; i < n; ++i) b[i] = D1(i, col);
216 for (std::size_t i = 0; i < n; ++i) embedded(i, col) = b[i];
218 double emin = std::numeric_limits<double>::infinity();
219 bool stochastic = detail::all_finite(embedded);
220 for (std::size_t k = 0; k < embedded.
size(); ++k) emin = std::min(emin, embedded[k]);
221 const std::vector<double> esum = detail::row_sums(embedded);
222 for (
double s : esum)
223 if (!(std::fabs(s - 1.0) <= 1e-10)) stochastic =
false;
224 if (!stochastic || emin < -1e-10)
225 return Out{std::nullopt,
"Service completion phase transitions must form a stochastic matrix."};
226 for (std::size_t i = 0; i < n; ++i) {
228 for (std::size_t j = 0; j < n; ++j) {
229 embedded(i, j) = std::max(embedded(i, j), 0.0);
230 rs += embedded(i, j);
232 for (std::size_t j = 0; j < n; ++j) embedded(i, j) /= rs;
234 std::vector<std::vector<std::size_t>> adj(n);
235 for (std::size_t i = 0; i < n; ++i)
236 for (std::size_t j = 0; j < n; ++j)
237 if (i != j && embedded(i, j) > 0) adj[i].push_back(j);
238 if (!detail::unique_closed_class(adj))
239 return Out{std::nullopt,
"The service completion phase chain must have one closed class."};
241 for (std::size_t i = 0; i < n; ++i)
gen(i, i) -= 1.0;
243 double amin = std::numeric_limits<double>::infinity(), asum = 0.0;
244 for (
double v : c.
alpha) {
245 amin = std::min(amin, v);
248 if (!std::isfinite(asum) || !std::isfinite(amin) || amin < -1e-10 || !(asum > 0))
249 return Out{std::nullopt,
"Service completion phase probabilities are invalid."};
251 for (
double& v : c.
alpha) {
252 v = std::max(v, 0.0);
255 for (
double& v : c.
alpha) v /= asum;
258 return Out{std::nullopt,
"PH service subgenerator must be transient."};
260 double mean = 0.0, vmin = std::numeric_limits<double>::infinity();
261 for (
double v : visits) {
263 vmin = std::min(vmin, v);
265 if (!std::isfinite(mean) || mean <= 0 || vmin < -1e-10)
266 return Out{std::nullopt,
"PH service subgenerator must be transient."};
267 bool phase_dependent =
false;
268 const double marking_scale = std::max(detail::max_abs(D1), detail::tiny());
269 for (
auto& kv : c.
routes) {
271 const std::vector<double> rs = detail::row_sums(matrix);
272 double probability = 0.0;
273 for (std::size_t i = 0; i < n; ++i) probability += visits[i] * rs[i];
274 if (probability < -1e-10 || probability > 1 + 1e-10)
275 return Out{std::nullopt,
"PH completion routing probabilities are invalid."};
276 kv.second.probability = std::max(0.0, std::min(1.0, probability));
277 if (detail::max_abs(detail::add(matrix, detail::scaled(D1, -probability))) > 1e-10 * marking_scale)
278 phase_dependent =
true;
281 for (std::size_t i = 0; i < n; ++i)
282 for (std::size_t j = 0; j < n; ++j) outer(i, j) = exits[i] * c.
alpha[j];
288 c.
correlated_reset = detail::max_abs(detail::add(D1, detail::scaled(outer, -1.0))) > 1e-10 * marking_scale;
290 clock_names.insert(name);
292 for (std::size_t a = 0; a < snapshot.
agents.size(); ++a) {
293 const std::string& name = snapshot.
agents[a].name;
294 if (!queue_names.count(name) && !clock_names.count(name)) m.
sources.push_back(a);
296 if (m.
sources.empty())
return Out{std::nullopt,
"MAP network lowering requires independent MAP or MMAP sources."};
297 for (std::size_t a : m.
sources) {
299 if (!detail::phase_named(source) || !detail::all_active(source))
300 return Out{std::nullopt,
"MAP network lowering requires MAP or MMAP source agents."};
301 std::vector<std::string> ms;
303 if (t.
action !=
"_phase" && !detail::contains_str(ms, t.
action)) ms.push_back(t.
action);
305 if (ms.empty())
return Out{std::nullopt,
"Every MAP network source must have a mark."};
309 const std::vector<Endpoint>& partners = s.
passive;
310 if (clock_names.count(active.first)) {
312 for (
const auto& kv : m.
clocks)
313 if (snapshot.
agents[kv.second.agent].name == active.first) qname = kv.first;
317 for (
const auto& kv : clock_entry.
routes)
318 if (kv.first == active.second) route = &kv.second;
320 if (partners != route->
partners)
return Out{std::nullopt,
"Unsupported PH completion synchronization."};
322 }
else if (active.second ==
"_phase") {
323 if (!qinfo.
service_phase || partners != std::vector<Endpoint>{Endpoint(qname, *qinfo.service_phase)})
324 return Out{std::nullopt,
"Unsupported PH progress synchronization."};
326 return Out{std::nullopt,
"Unsupported PH clock action."};
330 if (partners.size() != 1 || !queue_names.count(partners[0].first))
331 return Out{std::nullopt,
"MAP network routing requires one queue input per synchronized event."};
332 const std::string& target = partners[0].first;
333 if (!detail::contains_str(snapshot.
agent(target).
queue_info->arrivals, partners[0].second))
334 return Out{std::nullopt,
"MAP network routing can only target queue arrivals."};
335 if (m.
marks.count(active.first)) {
336 if (!detail::contains_str(m.
marks[active.first], active.second))
337 return Out{std::nullopt,
"The MAP phase action must not be synchronized."};
338 }
else if (queue_names.count(active.first)) {
339 if (!detail::find_route(*snapshot.
agent(active.first).
queue_info, active.second))
340 return Out{std::nullopt,
"MAP network routing must use declared queue departures."};
342 return Out{std::nullopt,
"Unsupported MAP network synchronization."};
344 m.
sync[active] = target;
346 std::set<std::string> targets;
347 for (std::size_t a : m.
sources)
348 for (
const std::string& mark : m.
marks[snapshot.
agents[a].name]) {
350 if (it == m.
sync.end())
return Out{std::nullopt,
"Every MAP source mark must feed a queue."};
351 targets.insert(it->second);
353 if (targets.size() != 1 && !allow_split)
354 return Out{std::nullopt,
"All source marks must feed the same queue to preserve their shared phases."};
355 if (targets.size() == 1) m.
target = *targets.begin();
361 typedef std::pair<std::optional<MapMatch>, std::string> Out;
367 std::set<std::string> queue_names;
368 for (std::size_t a = 0; a < snapshot.
agents.size(); ++a)
369 if (snapshot.
agents[a].queue_info) {
371 queue_names.insert(snapshot.
agents[a].name);
373 bool bad = m.
queues.size() < 2;
374 for (std::size_t q : m.
queues)
375 if (snapshot.
agents[q].queue_info->capacity) bad =
true;
376 if (bad)
return Out{std::nullopt,
"Parallel QBD requires at least two unbounded queues."};
377 std::vector<std::string> clocked;
378 for (std::size_t q : m.
queues)
379 if (!snapshot.
agents[q].queue_info->service_inputs.empty()) clocked.push_back(snapshot.
agents[q].name);
380 std::sort(clocked.begin(), clocked.end());
381 if (!clocked.empty()) {
383 for (std::size_t k = 0; k < clocked.size(); ++k) joined += (k ?
", " :
"") + clocked[k];
384 return Out{std::nullopt,
385 "Parallel QBD supports a queue driven by a PH service clock only in the MAP-network form, which "
386 "requires unbounded queues, single-server PH clocks and no minimum synchronizations; PH-clocked queue(s): " +
387 joined +
". MAP-network form refused: " + mm.second};
389 for (std::size_t a = 0; a < snapshot.
agents.size(); ++a)
390 if (!queue_names.count(snapshot.
agents[a].name)) m.
sources.push_back(a);
391 bool src_bad = m.
sources.empty();
392 for (std::size_t a : m.
sources)
393 if (snapshot.
agents[a].unbounded_queue) src_bad =
true;
394 if (src_bad)
return Out{std::nullopt,
"Parallel QBD requires finite autonomous background agents."};
395 auto arrival_ok = [&](
const Endpoint& e) {
396 return !queue_names.count(e.first) || detail::contains_str(snapshot.
agent(e.first).
queue_info->arrivals, e.second);
399 if (queue_names.count(s.
active.first))
return Out{std::nullopt,
"Parallel QBD requires no synchronized queue departures."};
401 if (!arrival_ok(e))
return Out{std::nullopt,
"Parallel QBD can only synchronize queue arrivals."};
405 if (queue_names.count(e.first))
return Out{std::nullopt,
"Parallel QBD requires autonomous active background agents."};
407 if (!arrival_ok(e))
return Out{std::nullopt,
"Parallel QBD can only synchronize queue arrivals."};
412 for (std::size_t qi : m.
queues) {
415 if (it != m.
clocks.end()) {
416 for (
const auto& kv : it->second.routes)
417 if (kv.second.target)
return Out{std::nullopt,
"Parallel QBD requires no routing between queues."};
420 if (m.
sync.count(
Endpoint(q.
name, r.first)))
return Out{std::nullopt,
"Parallel QBD requires no routing between queues."};
429inline Matrix<double> map_routing(
const Model& snapshot,
const MapMatch& m,
const std::map<std::string, std::size_t>& qidx) {
430 const std::size_t n = m.queues.
size();
432 for (std::size_t i = 0; i < n; ++i) {
433 const AgentRecord& q = snapshot.agents[m.queues[i]];
434 auto it = m.clocks.find(q.name);
435 if (it != m.clocks.end()) {
436 for (
const auto& kv : it->second.routes)
437 if (kv.second.target) routing(i, qidx.at(*kv.second.target)) += kv.second.probability;
439 for (
const auto& r : q.queue_info->routes) {
440 auto s = m.sync.find(
Endpoint(q.name, r.first));
441 if (s != m.sync.end()) routing(i, qidx.at(s->second)) += r.second;
449inline MarkedMatrices source_stream(
const AgentRecord& source,
const std::vector<std::string>& marks,
450 std::vector<double>& phase_reward) {
451 const std::size_t n = source.states.size();
452 Matrix<double> d0(n, n, 0.0);
453 std::vector<Matrix<double>> marked(marks.size(), Matrix<double>(n, n, 0.0));
454 phase_reward.assign(n, 0.0);
455 for (
const Transition& t : source.transitions) {
456 const std::size_t i = source.state_index(t.source), j = source.state_index(t.target);
457 if (t.action ==
"_phase") {
458 phase_reward[i] += t.value;
459 if (i != j) d0(i, j) += t.value;
461 const std::size_t k =
static_cast<std::size_t
>(std::find(marks.begin(), marks.end(), t.action) - marks.begin());
462 marked[k](i, j) += t.value;
465 Matrix<double> d1(n, n, 0.0);
466 for (
const auto& mk : marked) d1 = add(d1, mk);
467 const std::vector<double> r0 = row_sums(d0), r1 = row_sums(d1);
468 for (std::size_t i = 0; i < n; ++i) d0(i, i) = -(r0[i] + r1[i]);
470 out.insert(out.end(), marked.begin(), marked.end());
478inline std::pair<std::vector<double>, std::vector<double>> native_dec_source(
479 const Matrix<double>& d0,
const Matrix<double>& d1,
480 const std::vector<std::pair<std::optional<std::pair<std::vector<double>, Matrix<double>>>,
double>>& services,
481 const std::vector<long>& servers,
const Matrix<double>& routing, std::size_t entry,
const std::string& name,
482 const std::string& qprefix,
double tol,
long max_iter,
double max_phases) {
483 typedef lang::Distrib<double>
Dist;
484 qn::Network<double> network(name);
485 const std::size_t n = services.size();
486 const std::size_t src = network.add_source(n == 1 && qprefix ==
"Queue" ?
"Source" :
"LALSource");
487 std::vector<std::size_t> nodes;
488 for (std::size_t i = 0; i < n; ++i)
489 nodes.push_back(network.add_queue(n == 1 && qprefix ==
"Queue" ?
"Queue" : qprefix + std::to_string(i),
lang::SchedStrategy::FCFS));
490 const std::size_t sink = network.add_sink(n == 1 && qprefix ==
"Queue" ?
"Sink" :
"LALSink");
491 const std::size_t job = network.add_open_class(n == 1 && qprefix ==
"Queue" ?
"Class" :
"LALClass");
493 for (std::size_t i = 0; i < n; ++i) {
494 network.set_number_of_servers(nodes[i],
static_cast<double>(servers[i]));
495 if (services[i].first)
496 network.set_service(nodes[i], job,
Dist::phase_type(services[i].first->first, services[i].first->second,
false));
498 network.set_service(nodes[i], job,
Dist::exp_rate(services[i].second));
500 qn::RoutingMatrix<double> route;
501 route.set(job, job, src, nodes[entry], 1.0);
502 for (std::size_t i = 0; i < n; ++i) {
504 for (std::size_t j = 0; j < n; ++j) out += routing(i, j);
505 const double exit_probability = 1.0 - out;
506 for (std::size_t j = 0; j < n; ++j)
507 if (routing(i, j) != 0) route.set(job, job, nodes[i], nodes[j], routing(i, j));
508 if (exit_probability > 1e-14) route.set(job, job, nodes[i], sink, exit_probability);
511 const qn::NetworkStruct<double> sn = network.get_struct();
513 opt.method =
"dec.source";
515 opt.iter_max =
static_cast<int>(max_iter);
516 opt.space_max =
static_cast<std::size_t
>(std::min(max_phases, 1e18));
518 std::vector<double> q, x;
519 for (std::size_t i = 0; i < n; ++i) {
520 q.push_back(sol.sol.Q(sn.nodes[nodes[i] - 1].station - 1, 0));
521 x.push_back(sol.sol.Tp(sn.nodes[nodes[i] - 1].station - 1, 0));
539typedef std::function<std::pair<std::vector<double>, std::vector<double>>(
541 std::size_t,
const std::string&,
const std::string&, double, long, double)>
547inline std::pair<std::vector<double>, std::vector<double>> run_native_dec_source(
549 const std::vector<long>& servers,
const Matrix<double>& routing, std::size_t entry,
const std::string& name,
550 const std::string& qprefix,
double tol,
long max_iter,
double max_phases) {
551 if (backend)
return backend(d0, d1, services, servers, routing, entry, name, qprefix, tol, max_iter, max_phases);
552 return native_dec_source(d0, d1, services, servers, routing, entry, name, qprefix, tol, max_iter, max_phases);
556inline void clock_rows_and_rates(
const Model& snapshot,
const MapMatch& m,
const std::vector<double>& traffic,
557 const std::map<std::string, std::size_t>& qidx,
558 const std::map<std::string, std::vector<double>>& source_distributions,
559 std::map<std::string, double>& action_rates,
StateTable& states) {
560 std::map<std::string, std::string> clock_queue;
561 for (
const auto& kv : m.
clocks) clock_queue[snapshot.
agents[kv.second.agent].name] = kv.first;
563 auto sd = source_distributions.find(agent.
name);
564 if (sd != source_distributions.end()) {
565 for (std::size_t i = 0; i < agent.
states.size(); ++i)
566 states.
rows.push_back(
StateRow{agent.name, agent.states[i], sd->second[i]});
567 }
else if (!clock_queue.count(agent.
name)) {
568 states.
rows.push_back(
StateRow{agent.
name,
"unavailable", std::numeric_limits<double>::quiet_NaN()});
570 const std::string& qname = clock_queue[agent.
name];
572 const double utilization = traffic[qidx.at(qname)] * clock.
mean;
574 for (std::size_t i = 0; i < agent.
states.size(); ++i)
575 states.
rows.push_back(
StateRow{agent.name, agent.states[i],
576 unavailable ? std::numeric_limits<double>::quiet_NaN()
577 : (1 - utilization) * clock.alpha[i] + utilization * clock.busy_phases[i]});
580 for (std::size_t i = 0; i < m.
queues.size(); ++i) {
583 if (it != m.
clocks.end()) {
586 for (
const auto& kv : clock.
routes) action_rates[cagent.
name +
"." + kv.first] = traffic[i] * kv.second.probability;
587 std::vector<double> reward(cagent.
states.size(), 0.0);
591 for (std::size_t j = 0; j < reward.size(); ++j) x += clock.
busy_phases[j] * reward[j];
592 action_rates[cagent.
name +
"._phase"] = traffic[i] * clock.
mean * x;
594 for (
const auto& r : queue.
queue_info->routes) action_rates[queue.
name +
"." + r.first] = traffic[i] * r.second;
601 for (std::size_t qi : m.
queues) {
602 const std::string& qname = snapshot.
agents[qi].name;
603 auto it = m.
clocks.find(qname);
604 if (it == m.
clocks.end())
continue;
607 if (it->second.correlated_reset || it->second.phase_dependent_routing)
611 *res.
approximation +=
" Service-phase-dependent routing is replaced by its mean probabilities.";
613 *res.
approximation +=
" Correlated service resets are replaced by independent PH services.";
617 nlohmann::json out = nlohmann::json::array();
626 const std::string& traffic_method =
"auto",
const std::string& compress_method =
"exponential",
627 double fit_time = 1.0,
double fit_tolerance = .05,
632 if (!rec.first)
throw detail::mam_refusal(
"Model", rec.second);
634 double phase_order = 1.0, local_bytes = 0.0;
635 std::size_t mark_count = 0;
636 for (std::size_t a : m.
sources) {
638 const double n =
static_cast<double>(s.
states.size());
641 local_bytes += n * n * (m.
marks.at(s.
name).size() + 2.0) * 8;
643 if (m.
queues.size() > 100 || mark_count > 64 || local_bytes > 32.0 * 1024 * 1024)
644 throw detail::mam_refusal(
"StateSpace",
"MAP network exceeds its queue, mark or source-storage limit.");
645 std::vector<MarkedMatrices> streams;
646 std::map<std::string, std::vector<double>> source_distributions;
647 std::map<std::string, double> action_rates;
648 std::vector<std::string> source_marks;
649 double offered = 0.0;
650 for (std::size_t a : m.
sources) {
652 const std::vector<std::string>& marks = m.
marks.at(source.
name);
653 std::vector<double> phase_reward;
654 MarkedMatrices stream = detail::source_stream(source, marks, phase_reward);
655 if (detail::strong_count_positive(detail::add(stream[0], stream[1])) != 1)
656 throw detail::mam_refusal(
"Model",
"MAP network source phase processes must be irreducible.");
657 const std::vector<double> pi = detail::stationary(detail::add(stream[0], stream[1]));
658 source_distributions[source.
name] = pi;
660 for (std::size_t i = 0; i < pi.size(); ++i) pr += pi[i] * phase_reward[i];
661 action_rates[source.
name +
"._phase"] = pr;
662 for (std::size_t k = 0; k < marks.size(); ++k) {
663 const std::vector<double> rs = detail::row_sums(stream[k + 2]);
665 for (std::size_t i = 0; i < pi.size(); ++i) rate += pi[i] * rs[i];
666 action_rates[source.
name +
"." + marks[k]] = rate;
668 source_marks.push_back(source.
name +
"." + marks[k]);
670 streams.push_back(stream);
673 throw detail::mam_refusal(
"Model",
"MAP network decomposition requires a positive offered arrival rate.");
674 std::optional<Traffic> fitted_diagnostics;
675 std::string
selected = traffic_method;
677 selected = phase_order <= std::min(64.0, max_phases) ?
"exact" : (streams.size() > 1 ?
"interpos" :
"compress");
678 const bool materialize = phase_order * phase_order * (mark_count + 2.0) * 8 <= 32.0 * 1024 * 1024;
679 if (
selected ==
"exact" && phase_order > std::min(64.0, max_phases))
680 throw detail::mam_refusal(
"StateSpace",
"MAP network exceeds the exact source phase limit.");
681 std::optional<MarkedMatrices> aggregate;
684 for (std::size_t k = 1; k < streams.size(); ++k) combined =
mam::mmap_super(combined, detail::to_mmap(streams[k]));
685 aggregate = detail::from_mmap(combined);
690 description.
marks = source_marks;
697 d.
marks = source_marks;
709 if (traffic_method ==
"auto")
710 d.
fallback_reason =
"Exact source superposition has " + std::to_string(
static_cast<long long>(phase_order)) +
" phases.";
711 fitted_diagnostics = d;
714 if (!aggregate ||
static_cast<double>((*aggregate)[0].rows()) > max_phases)
715 throw detail::mam_refusal(
"StateSpace",
"MAP network traffic exceeds the configured phase limit.");
716 for (
const auto& kv : m.
clocks)
717 if (
static_cast<double>((*aggregate)[0].rows() * snapshot.
agents[kv.second.agent].states.size()) > max_phases)
718 throw detail::mam_refusal(
"StateSpace",
"MAP/PH station exceeds the configured phase limit.");
721 const std::size_t nq = m.
queues.size();
722 std::map<std::string, std::size_t> qidx;
723 for (std::size_t i = 0; i < nq; ++i) qidx[snapshot.
agents[m.
queues[i]].name] = i;
724 const Matrix<double> routing = detail::map_routing(snapshot, m, qidx);
725 if (detail::spectral_radius_nonneg(routing) >= 1 - 1e-12)
726 throw detail::mam_refusal(
"Stability",
"MAP network routing must be open.");
727 std::vector<double> external(nq, 0.0);
728 external[qidx.at(*m.
target)] = offered;
730 for (std::size_t i = 0; i < nq; ++i)
731 for (std::size_t j = 0; j < nq; ++j) system(i, j) = (i == j ? 1.0 : 0.0) - routing(j, i);
732 std::vector<double> traffic;
734 traffic = detail::lu_solve_vec(system, external);
736 throw detail::mam_refusal(
"Numerical",
"MAP network traffic equations are singular.");
738 for (
double t : traffic)
739 if (!std::isfinite(t) || t < -1e-10)
740 throw detail::mam_refusal(
"Numerical",
"MAP network traffic equations produced invalid rates.");
741 for (
double& t : traffic) t = std::max(t, 0.0);
742 for (std::size_t i = 0; i < nq; ++i)
744 throw detail::mam_refusal(
"Initial",
"A PH station with no arrivals can retain an initial-dependent idle phase.");
745 std::vector<double> service_means(nq);
746 for (std::size_t i = 0; i < nq; ++i) {
749 service_means[i] = it != m.
clocks.end() ? it->second.mean : 1.0 / *q.
queue_info->service_rate;
751 std::vector<long> servers(nq);
752 for (std::size_t i = 0; i < nq; ++i) servers[i] = snapshot.
agents[m.
queues[i]].queue_info->servers;
753 for (std::size_t i = 0; i < nq; ++i)
754 if (traffic[i] * service_means[i] >=
static_cast<double>(servers[i]) * (1 - 1e-12))
755 throw detail::mam_refusal(
"Stability",
"A MAP network queue is unstable or critically loaded.");
756 const bool fitted = fitted_diagnostics && offered > 0;
757 std::vector<double> fitted_traffic;
759 double fitted_total = 0.0;
760 for (
double r : fitted_diagnostics->fitted_rates) fitted_total += r;
761 for (std::size_t i = 0; i < nq; ++i) fitted_traffic.push_back(traffic[i] * (fitted_total / offered));
762 for (std::size_t i = 0; i < nq; ++i)
763 if (fitted_traffic[i] * service_means[i] >=
static_cast<double>(servers[i]) * (1 - 1e-12))
764 throw detail::mam_refusal(
"Stability",
"Traffic fitting makes a MAP network queue unstable.");
768 double native_scale = std::max(detail::max_abs(d0), detail::max_abs(d1));
769 for (std::size_t i = 0; i < nq; ++i) {
772 native_scale = std::max(native_scale, it != m.
clocks.end() ? detail::max_abs(it->second.T) : *q.
queue_info->service_rate);
774 if (!std::isfinite(native_scale) || native_scale <= 0)
775 throw detail::mam_refusal(
"Numerical",
"MAP network has an invalid time scale.");
776 std::vector<std::pair<std::optional<std::pair<std::vector<double>,
Matrix<double>>>,
double>> services;
777 for (std::size_t i = 0; i < nq; ++i) {
781 services.push_back({std::make_pair(it->second.alpha, detail::scaled(it->second.T, 1.0 / native_scale)), 0.0});
783 services.push_back({std::nullopt, *q.
queue_info->service_rate / native_scale});
785 const auto native = detail::run_native_dec_source(native_backend, detail::scaled(d0, 1.0 / native_scale),
786 detail::scaled(d1, 1.0 / native_scale), services, servers, routing,
787 qidx.at(*m.
target),
"LAL_MAP_Network",
"LALQueue", tol, max_iter,
791 for (std::size_t i = 0; i < nq; ++i) {
792 const double qlen = native.first[i];
793 if (!std::isfinite(qlen) || qlen < 0)
794 throw detail::mam_refusal(
"Numerical",
"Native MAM decomposition returned an invalid queue length.");
795 const double native_throughput = native.second[i] * native_scale;
796 const double expected_throughput = fitted ? fitted_traffic[i] : traffic[i];
797 const double throughput_scale = std::max(std::fabs(expected_throughput), detail::tiny());
798 if (!std::isfinite(native_throughput) || std::fabs(native_throughput - expected_throughput) > 1e-6 * throughput_scale)
799 throw detail::mam_refusal(
"Numerical",
"Native MAM decomposition did not preserve the station traffic rate.");
802 const double utilization = traffic[i] * service_means[i] /
static_cast<double>(servers[i]);
803 const double busy = servers[i] == 1 ? utilization : std::numeric_limits<double>::quiet_NaN();
804 const double response = traffic[i] > 0 ? qlen / traffic[i] : std::numeric_limits<double>::quiet_NaN();
805 qt.
rows.push_back(
QueueRow{snapshot.
agents[m.
queues[i]].name, qlen, busy, utilization, traffic[i], traffic[i], response});
807 detail::clock_rows_and_rates(snapshot, m, traffic, qidx, source_distributions, action_rates, res.
state_table);
808 for (
const std::string& label : detail::active_labels(snapshot))
812 at->method =
"dec.source";
814 at->truncated = truncated;
816 double residual = 0.0;
817 for (std::size_t i = 0; i < nq; ++i) {
818 double r = traffic[i] - external[i];
819 for (std::size_t j = 0; j < nq; ++j) r -= routing(j, i) * traffic[j];
820 residual = std::max(residual, std::fabs(r));
822 res.
method =
"dec.source";
827 if (fitted_diagnostics) {
828 res.
traffic = fitted_diagnostics;
835 t.
marks = source_marks;
840 res.
extra[
"native_method"] =
"dec.source";
843 res.
approximation = std::string(
"Native MAM network decomposition; queue-state distributions unavailable.");
844 detail::clock_fidelity(snapshot, m, res);
845 for (std::size_t i = 0; i < nq; ++i)
849 res.
extra[
"tolerance"] = tol;
850 res.
extra[
"max_iterations"] = max_iter;
853 res.
extra[
"routing"] = detail::matrix_json(routing);
854 res.
extra[
"queue_rates"] = traffic;
The algorithm cannot produce a trustworthy answer on this instance: LINE:numerical:<kind>.
A collection of agents and embedded LINE models with atomic synchronisations (Composition).
Model model(const std::vector< Sync > *syncs=nullptr, const std::vector< ExtSync > *ext_syncs=nullptr) const
The current model snapshot (_model).
The distributions a user names, spelled as their Python twins.
Port of solver_mam_analyzer.m: one inner solve, choosing the analyzer that fits the model and the req...
LINE Agent Language (LAL): lossless lowering of open exponential LAL networks to scalar M/M/c factors...
LINE Agent Language (LAL): independent marked arrival proposals of a finite composition and their exp...
std::pair< std::optional< MapMatch >, std::string > recognize_parallel(const Model &snapshot)
Recognise independent stations with shared marked sources (lal_parallel_qbd.recognize).
std::vector< Matrix< double > > MarkedMatrices
A marked process as Python's list [D0, D1, D1_1, ..., D1_K].
std::pair< std::string, std::string > Endpoint
(agent, action).
std::vector< Event > selected(const std::vector< Event > &events)
Apply maximal progress and immediate priorities to the enabled events (selected).
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).
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,...
std::vector< std::pair< std::optional< std::pair< std::vector< double >, Matrix< double > > >, double > > NativeServices
Per-queue service law handed to the native dec.source solve: a PH (alpha, T) or, when empty,...
MamResult map_network(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())
Native MAM decomposition of a recognised MAP network (lal_map_network.solve_composition).
MamSolution< T > mam_dispatch(const qn::NetworkStruct< T > &L, const MamOptions &opt_in)
The ladder.
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 ...
Conservation laws of a layered queueing network, enumerated from its structure.
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.
lang::Distrib< double > Dist
std::vector< std::size_t > lu_factor(Matrix< T > &A)
In-place LU of A (n x n).
The Network constructor API: Queue, Delay, Source, Sink, Router, ClassSwitch, Cache,...
One row of an action table: Action, Throughput.
std::vector< ActionRow > rows
The immutable agent record (core.Agent).
std::vector< Transition > transitions
std::vector< std::string > states
std::optional< QueueInfo > queue_info
std::size_t state_index(const std::string &s) const
Zero-based index of a local state, or npos.
One routed completion mark of a PH service clock.
std::optional< std::string > target
std::vector< Endpoint > partners
The union of Python's LAL MAM result dataclasses.
std::optional< std::string > approximation
std::optional< QueueTable > queue_measures
std::vector< std::string > phase_dependent_routing
std::vector< MarkedMatrices > source_matrices
std::optional< Traffic > traffic
std::optional< std::string > residual_kind
nlohmann::json native_internal_fitting
null: absent
bool has_converged
whether the lowering reports converged at all
std::optional< double > native_time_scale
dec.source: factor dividing the lowered network's rates
std::vector< std::string > correlated_service_reset
std::vector< std::string > unavailable_clock_phases
std::vector< std::string > unavailable_busy_probabilities
multiserver queues: Busy is NaN
std::vector< std::string > source_marks
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::optional< std::string > target
std::map< Endpoint, std::string > sync
A minimum-rate synchronisation: at least two active endpoints and optional passive ones.
A composition snapshot (core.Model): agents in declaration order plus synchronisations.
std::vector< MinSync > min_syncs
bool has_agent(const std::string &name) const
std::vector< Sync > syncs
std::size_t index_of(const std::string &name) const
std::vector< AgentRecord > agents
const AgentRecord & agent(const std::string &name) const
Structured queue declaration retained while a queue agent is unmodified (queue_info).
std::optional< std::string > service_phase
std::vector< std::string > service_inputs
One row of getQueueTable(): Agent, QLen, Busy, Util, ArvR, Tput, RespT.
std::vector< QueueRow > rows
std::optional< std::string > fallback_reason
A PH service clock driving a queue (the clocks[q] dictionary).
std::vector< double > alpha
std::size_t agent
agent index of the clock
std::vector< double > busy_phases
bool phase_dependent_routing
std::vector< std::pair< std::string, ClockRoute > > routes
mark -> route, in service-input order
One row of a state table: Agent, State, Probability.
std::vector< StateRow > rows
An ordinary synchronisation: one active endpoint, hand passives and injected node arrivals.
std::vector< Endpoint > passive
The attrs of a LAL result table.
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).
std::optional< MarkedMatrices > fitted_matrices
std::optional< double > fit_tolerance
std::optional< Matrix< double > > original_count_covariance
std::optional< Matrix< double > > fitted_count_covariance
std::vector< std::string > marks
std::vector< MarkedMatrices > original_streams
std::vector< double > fitted_rates
std::optional< std::string > fallback_reason
std::optional< MarkedMatrices > matrices
std::optional< double > rate_error
std::optional< MarkedMatrices > original_matrices
std::optional< double > fit_time
std::optional< double > count_covariance_error
std::vector< double > original_rates
std::vector< MarkedMatrices > streams
std::optional< bool > feasible
One labelled local transition source --(action, value)--> target.
static Distrib exp_rate(const double &r)
static Distrib phase_type(const std::vector< double > &alpha, const Matrix< double > &A, bool acyclic)
static Distrib map_dist(const Matrix< double > &D0, const Matrix< double > &D1, ProcessType tag)
An MMAP: the underlying MAP plus the per-class arrival matrices.