5#ifndef LINE_LANG_LAL_MAM_LOWERING_H
6#define LINE_LANG_LAL_MAM_LOWERING_H
64 std::map<std::string, std::string>
labels;
69[[noreturn]]
inline void refuse_lowering(
const std::string& message) {
75 typedef std::pair<double, std::optional<std::size_t>> Route;
77 static LoweredComposition lower(
const Composition& composition) {
78 if (composition.embedded_.empty())
return LoweredComposition{composition,
false, {}};
79 if (!composition.ext_syncs_.empty())
80 refuse_lowering(
"a hand agent observes or gates a node event; only injected arrivals are lowered.");
81 if (composition.embedded_.size() != 1) refuse_lowering(
"it embeds more than one LINE model.");
82 EmbeddedNetwork* part =
dynamic_cast<EmbeddedNetwork*
>(composition.embedded_.front().
get());
83 if (!part) refuse_lowering(
"a EmbeddedEnvironment has no queue structure for the matrix-analytic methods.");
84 std::vector<Agent> agents;
85 std::vector<Sync> syncs;
86 std::map<std::string, std::string> relabel;
87 lower_network(*part, composition, agents, syncs, relabel);
88 std::vector<Agent> all = composition.agents_;
89 all.insert(all.end(), agents.begin(), agents.end());
90 LoweredComposition out{
Composition(all),
true, relabel};
91 Composition& lowered = out.composition;
92 for (
const Sync& s : composition.syncs_) {
93 bool injection =
false;
94 for (
const auto& p : s.node_passive)
95 if (p.first == part->name()) injection =
true;
97 if (p.first == part->name()) injection =
true;
98 if (!injection) lowered.syncs_.push_back(s);
100 lowered.syncs_.insert(lowered.syncs_.end(), syncs.begin(), syncs.end());
101 lowered.min_syncs_ = composition.min_syncs_;
102 lowered.hidden_ = composition.hidden_;
103 lowered.rewards_ = composition.rewards_;
104 lowered.source_truncated = composition.source_truncated;
109 static std::string upper(std::string s) {
110 for (
char& c : s) c =
static_cast<char>(std::toupper(
static_cast<unsigned char>(c)));
127 static std::vector<double> init_prob_of(
const lang::Distrib<double>& d) {
133 static double exp_rate(
const lang::Distrib<double>& d) {
134 if (d.has_map() && d.D0.rows() == 1)
return -d.D0(0, 0);
138 static void lower_network(EmbeddedNetwork& part,
const Composition& composition, std::vector<Agent>& agents,
139 std::vector<Sync>& syncs, std::map<std::string, std::string>& relabel) {
140 const qn::NetworkStruct<double>& sn = part.model_struct();
141 const std::size_t K = sn.nclasses, N = sn.nodes.size();
142 std::vector<std::string> names, cnames;
143 for (
const qn::NodeDef& nd : sn.nodes) names.push_back(nd.name);
144 for (
const qn::JobClass& c : sn.classes) cnames.push_back(c.name);
145 for (
double nj : sn.njobs())
146 if (std::isfinite(nj)) refuse_lowering(
"it has a closed class.");
147 const Matrix<double>& rt = sn.rtnodes;
148 if (rt.rows() < N * K || rt.cols() < N * K) refuse_lowering(
"it has no node-level routing matrix.");
149 auto R = [&](std::size_t i, std::size_t r, std::size_t j, std::size_t s) {
return rt(i * K + r, j * K + s); };
150 std::vector<std::size_t> queues, sources;
151 for (std::size_t i = 0; i < N; ++i) {
156 sources.push_back(i);
159 "; only Source, Queue and Sink are lowered.");
161 if (queues.empty()) refuse_lowering(
"it has no Queue node.");
162 auto is_queue = [&](std::size_t j) {
return std::find(queues.begin(), queues.end(), j) != queues.end(); };
164 std::map<std::size_t, std::set<std::size_t>> visits;
165 std::vector<std::size_t> visit_order;
166 for (std::size_t q : queues) {
168 visit_order.push_back(q);
170 for (std::size_t i = 0; i < N; ++i)
171 for (std::size_t r = 0; r < K; ++r)
172 for (std::size_t j : queues)
173 for (std::size_t s = 0; s < K; ++s)
174 if (R(i, r, j, s) > 0) {
175 if (r != s) refuse_lowering(
"it switches class.");
179 std::map<std::size_t, std::vector<Endpoint>> injected;
180 std::vector<std::size_t> injected_order;
181 for (
const Sync& s : composition.syncs_)
182 for (
const auto& ep : s.node_passive) {
183 if (ep.first != part.name())
continue;
184 const NodeEvent& key = ep.second;
186 refuse_lowering(key.label() +
" is injected, but only arrivals are.");
190 const std::vector<std::string>::const_iterator nit = std::find(names.begin(), names.end(), key.node);
191 if (nit == names.end())
192 refuse_lowering(key.label() +
" is injected, but " + part.name() +
" has no node " + key.node +
194 const std::size_t q =
static_cast<std::size_t
>(nit - names.begin());
195 if (!is_queue(q)) refuse_lowering(key.node +
" is injected, but only queues are lowered.");
197 refuse_lowering(key.label() +
" is injected without a class; name the class of the arrival.");
198 const std::vector<std::string>::const_iterator cit = std::find(cnames.begin(), cnames.end(), *key.index);
199 if (cit == cnames.end())
200 refuse_lowering(key.label() +
" is injected, but " + part.name() +
" has no class " + *key.index +
202 const std::size_t c =
static_cast<std::size_t
>(cit - cnames.begin());
203 if (!visits.count(q)) visit_order.push_back(q);
205 if (!injected.count(q)) injected_order.push_back(q);
206 injected[q].push_back(s.active);
208 for (std::size_t q : visit_order)
209 if (visits[q].size() != 1)
210 refuse_lowering(
"queue " + names[q] +
" is visited by " + std::to_string(visits[q].size()) +
211 " classes; each queue must serve one class.");
212 std::map<std::size_t, std::size_t> qclass;
213 for (std::size_t q : visit_order) qclass[q] = *visits[q].begin();
215 std::map<std::size_t, std::vector<std::string>> arrivals;
216 for (std::size_t q : queues) arrivals[q];
217 std::map<std::size_t, std::vector<std::pair<std::string, Route>>> routes_of;
218 for (std::size_t q : queues) {
219 const std::size_t r = qclass[q];
220 std::vector<std::pair<std::string, Route>> out;
221 for (std::size_t j = 0; j < N; ++j) {
222 const double p = R(q, r, j, r);
223 if (!(p > 0))
continue;
225 out.push_back(std::make_pair(
"to_" + names[j], Route(p, j)));
226 arrivals[j].push_back(
"from_" + names[q]);
230 if (o.first ==
"out") {
234 if (!merged) out.push_back(std::make_pair(
"out", Route(p, std::nullopt)));
236 refuse_lowering(
"queue " + names[q] +
" routes to " + names[j] +
".");
239 if (out.empty()) out.push_back(std::make_pair(
"out", Route(1.0, std::nullopt)));
242 for (std::size_t q : injected_order) {
243 for (std::size_t k = 0; k < injected[q].size(); ++k) arrivals[q].push_back(
"in" + std::to_string(k));
246 auto emits = [&](std::size_t s, std::size_t r) {
247 const qn::Station<double>& st = sn.stations[sn.nodes[s].station - 1];
248 if (!st.marked_classes.empty())
249 return std::find(st.marked_classes.begin(), st.marked_classes.end(), r + 1) != st.marked_classes.end();
250 const std::size_t ist = sn.nodes[s].station;
251 return ist - 1 < sn.service.size() && r < sn.service[ist - 1].size() &&
254 for (std::size_t s : sources)
255 for (std::size_t r = 0; r < K; ++r) {
256 std::vector<std::size_t> dests;
257 for (std::size_t j : queues)
258 if (R(s, r, j, r) > 0) dests.push_back(j);
259 if (dests.empty() || !emits(s, r))
continue;
260 if (dests.size() != 1 || std::fabs(R(s, r, dests[0], r) - 1.0) > 1e-12)
261 refuse_lowering(
"source " + names[s] +
" splits class " + cnames[r] +
" over several queues.");
262 arrivals[dests[0]].push_back(
"src_" + names[s] +
"_" + cnames[r]);
266 qn::NetState<double> init;
267 const bool has_init = ctmc::analyzer_detail::default_init_state(sn, init);
269 for (std::size_t q : queues) {
270 const std::size_t r = qclass[q];
271 const std::size_t ist = sn.nodes[q].station;
272 const qn::Station<double>& st = sn.stations[ist - 1];
273 const std::string& qname = names[q];
274 const std::string& cname = cnames[r];
276 if (sched !=
"FCFS" && sched !=
"LCFS" && sched !=
"SIRO" && sched !=
"PS")
277 refuse_lowering(
"queue " + qname +
" uses " + sched +
" scheduling.");
278 if (!std::isfinite(st.nservers)) refuse_lowering(
"queue " + qname +
" has infinitely many servers.");
279 const long servers =
static_cast<long>(st.nservers);
280 const std::optional<long> capacity =
281 std::isfinite(st.cap) ? std::optional<long>(
static_cast<long>(st.cap)) : std::nullopt;
282 const lang::Distrib<double>& dist = sn.service[ist - 1][r];
284 const std::size_t isf = sn.stateful_index(q + 1);
285 if (has_init && isf != 0 && isf <= init.local.size()) {
287 initial =
static_cast<long>(std::llround(m.ni));
290 for (
const auto& o : routes_of[q]) route_probs.push_back(std::make_pair(o.first, o.second.first));
291 auto in_routes = [&](
const std::string& a) {
292 for (
const auto& rp : route_probs)
293 if (rp.first == a)
return true;
296 const std::string dep = qname +
".DEP[" + cname +
"]";
298 Agent agent =
Agent(qname, std::vector<std::string>{
"n_0"},
"n_0");
301 o.capacity = capacity;
302 o.service_rate = exp_rate(dist);
304 o.arrivals = arrivals[q];
305 o.departures = route_probs;
307 agent = Records::queue(qname, o);
308 }
else if (is_ph_service(kind)) {
310 refuse_lowering(
"queue " + qname +
" has phase-type service on " + std::to_string(servers) +
312 const std::vector<double> alpha = init_prob_of(dist);
313 const Matrix<double>& T = dist.D0;
314 const Agent clock = Records::ph_service(qname +
"_service", alpha, T, route_probs);
315 std::vector<std::string> inputs;
316 for (
const auto& rp : route_probs) inputs.push_back(
"svc_" + rp.first);
318 for (
const Transition& t : clock.transitions()) phase = phase || t.action ==
"_phase";
320 o.capacity = capacity;
321 o.arrivals = arrivals[q];
323 o.service_inputs = inputs;
324 if (phase) o.service_phase = std::string(
"svc_phase");
325 agent = Records::queue(qname, o);
326 for (
const Transition& t : clock.transitions())
327 relabel[clock.name() +
"." + t.action] =
328 in_routes(t.action) ? dep : qname +
".PHASE[" + cname +
"]";
329 agents.push_back(clock);
330 for (
const auto& rp : route_probs) {
331 const std::optional<std::size_t> dest = route_dest(routes_of[q], rp.first);
333 s.active =
Endpoint(clock.name(), rp.first);
334 s.passive.push_back(
Endpoint(qname,
"svc_" + rp.first));
335 if (dest) s.passive.push_back(
Endpoint(names[*dest],
"from_" + qname));
340 s.active =
Endpoint(clock.name(),
"_phase");
341 s.passive.push_back(
Endpoint(qname,
"svc_phase"));
345 refuse_lowering(
"queue " + qname +
" has a " +
law_name(dist) +
" service.");
348 for (
int d : st.droprule)
355 const std::string full =
"n_" + std::to_string(*capacity);
356 std::vector<Transition> extra;
357 for (
const std::string& a : arrivals[q]) {
366 Records::extend_queue(agent, extra);
368 for (
const Transition& t : agent.transitions())
369 if (t.role ==
Role::Active && in_routes(t.action)) relabel[qname +
"." + t.action] = dep;
370 agents.push_back(agent);
372 for (
const auto& o : routes_of[q])
373 if (o.second.second) {
375 s.active =
Endpoint(qname, o.first);
376 s.passive.push_back(
Endpoint(names[*o.second.second],
"from_" + qname));
379 const auto inj = injected.find(q);
380 if (inj != injected.end())
381 for (std::size_t k = 0; k < inj->second.size(); ++k) {
383 s.active = inj->second[k];
384 s.passive.push_back(
Endpoint(qname,
"in" + std::to_string(k)));
389 for (std::size_t s : sources) {
390 const std::string& sname = names[s];
391 const std::size_t ist = sn.nodes[s].station;
392 const qn::Station<double>& st = sn.stations[ist - 1];
393 std::map<std::size_t, std::size_t> routed;
394 std::vector<std::size_t> routed_order;
395 for (std::size_t r = 0; r < K; ++r)
396 for (std::size_t j : queues)
397 if (R(s, r, j, r) > 0) {
399 routed_order.push_back(r);
402 if (!st.marked_classes.empty()) {
403 const std::size_t carrier = st.marked_classes.front() - 1;
404 const lang::Distrib<double>& proc = sn.service[ist - 1][carrier];
405 std::vector<std::string> labels;
406 for (std::size_t k = 0; k < st.marked_classes.size(); ++k) labels.push_back(
"m" + std::to_string(k));
407 mam::Mmap<double> m{proc.D0, proc.D1, proc.Dmark};
408 const Agent agent = Records::from_marked_map(sname, m, labels);
409 for (
const Transition& t : agent.transitions()) {
410 const auto it = std::find(labels.begin(), labels.end(), t.action);
411 relabel[sname +
"." + t.action] =
413 ? sname +
".DEP[" + cnames[st.marked_classes[
static_cast<std::size_t
>(it - labels.begin())] - 1] +
"]"
416 agents.push_back(agent);
417 for (std::size_t k = 0; k < st.marked_classes.size(); ++k) {
418 const std::size_t r = st.marked_classes[k] - 1;
419 if (!routed.count(r))
continue;
421 sy.active =
Endpoint(sname, labels[k]);
422 sy.passive.push_back(
Endpoint(names[routed[r]],
"src_" + sname +
"_" + cnames[r]));
427 for (std::size_t r : routed_order) {
428 const std::size_t q = routed[r];
429 if (ist - 1 >= sn.service.size() || r >= sn.service[ist - 1].size())
continue;
430 const lang::Distrib<double>& dist = sn.service[ist - 1][r];
433 const std::string aname = sname +
"_" + cnames[r];
434 Agent agent =
Agent(aname, std::vector<std::string>{
"phase_0"},
"phase_0");
436 const double rate = exp_rate(dist);
437 agent = Records::mmap(aname, Matrix<double>{{-rate}}, {{
"arrival", Matrix<double>{{rate}}}});
440 refuse_lowering(
"source " + sname +
" declares a marked process per class; use set_marked_arrival.");
441 }
else if (dist.has_map()) {
442 agent = Records::mmap(aname, dist.D0, {{
"arrival", dist.D1}});
444 refuse_lowering(
"source " + sname +
" has a " +
law_name(dist) +
" arrival process.");
446 for (
const Transition& t : agent.transitions())
447 relabel[aname +
"." + t.action] = t.action ==
"arrival" ? sname +
".DEP[" + cnames[r] +
"]"
448 : sname +
".PHASE[" + cnames[r] +
"]";
449 agents.push_back(agent);
451 sy.active =
Endpoint(aname,
"arrival");
452 sy.passive.push_back(
Endpoint(names[q],
"src_" + sname +
"_" + cnames[r]));
458 static std::optional<std::size_t> route_dest(
const std::vector<std::pair<std::string, Route>>& routes,
459 const std::string& action) {
460 for (
const auto& o : routes)
461 if (o.first == action)
return o.second.second;
479 if (mapping.empty())
return table;
481 std::vector<std::string> order;
482 std::map<std::string, double> values;
483 for (
const ActionRow& row : table.rows) {
484 const auto it = mapping.find(row.action);
485 const std::string key = it != mapping.end() ? it->second : row.action;
486 if (!values.count(key)) {
487 order.push_back(key);
488 values[key] = row.throughput;
490 values[key] += row.throughput;
493 for (
const std::string& k : order) out.
rows.push_back(
ActionRow{k, values[k]});
494 out.
attrs = table.attrs;
LINE Agent Language (LAL): programmatic construction of finite agents and their composition,...
UnsupportedError(const std::string &what)
Agent(const std::string &name, const std::vector< std::string > &states, const std::string &initial)
A collection of agents and embedded LINE models with atomic synchronisations (Composition).
LINE Agent Language (LAL): the result tables every LAL solver returns, the exact finite CTMC analysis...
std::vector< double > init_prob(const lang::Distrib< double > &d)
The initial vector of a Markovian law with a (D0, D1) pair (getInitProb).
qn::Marginal< double > station_marginal(const qn::NetworkStruct< double > &sn, std::size_t ist, const std::vector< double > &row)
The queue-length / phase marginal of a station row (toMarginal).
std::vector< std::pair< std::string, double > > NamedWeights
std::pair< std::string, std::string > Endpoint
(agent, action).
std::string law_name(const lang::Distrib< double > &d)
A short readable name of a law for refusal messages (law_name).
ActionTable relabel_action_table(const ActionTable &table, const std::map< std::string, std::string > &mapping)
Rename lowered action rows to their node-event labels, summing rows that share one (relabel_action_ta...
LoweredComposition lower(const Composition &composition)
A Composition of plain agents equivalent to composition, or itself (lower).
const lang::Distrib< double > & declared_law(const lang::Distrib< double > &d)
The declared law of a distribution (the original when a solver fitted a surrogate).
const char * node_type_to_text(NodeType t)
Name of a node kind, for diagnostics.
ProcessType
Distribution kinds, with the values of MATLAB ProcessType.
@ MPH
The MARKED families, MATLAB's ProcessType.m:36-38.
const char * sched_to_text(SchedStrategy s)
NodeType
Node kinds, with the values of MATLAB NodeType.
const std::string * get(const Element *el, const std::string &key)
el.get(key), with Python's None as a null pointer.
std::vector< T > map_pie(const Map< T > &m)
Phase distribution seen by an arriving job, pie = pi D1 / (pi D1 e).
Conservation laws of a layered queueing network, enumerated from its structure.
Port of solver_ctmc_analyzer.m and the parts of @@SolverCTMC/runAnalyzer.m that surround one solve: t...
One row of an action table: Action, Throughput.
std::vector< ActionRow > rows
A composition lowered for SolverMAM, with the map of lowered action labels to node-event labels.
std::map< std::string, std::string > labels
python _lal_labels