LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
embed.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// builder.h is included before the guard: it includes this header at its
6// foot, once Agent and Composition are complete.
8
9#ifndef LINE_LANG_LAL_EMBED_H
10#define LINE_LANG_LAL_EMBED_H
11
12/**
13 * @file
14 * @ingroup line_lang
15 * LINE Agent Language (LAL): embedding of LINE model objects into a LAL
16 * composition. Port of python/line_solver/lal/embed.py.
17 *
18 * An embedded `Network` contributes ONE AGENT PER NODE. Its joint behaviour is
19 * not re-derived here: SolverCTMC's own state-space preparation and generator
20 * builder run on the network, and their per-event arcs are collected before
21 * any solve (`ctmc::LalCollect`). The embedded agents therefore reproduce
22 * LINE's generator exactly, including vanishing states, true BAS blocking,
23 * Petri-net mode firings (`gsync`) and fork firings (`fjsync`).
24 *
25 * Node actions are named with LINE's own event vocabulary. A key is the triple
26 * a synchronization record carries, `(node, EventType, class | mode)`,
27 * rendered for tables as `Node.EVENT[index]`. Each event of the network
28 * carries the keys of ALL its participants, so `getAct*` reports a departure
29 * at its source node and the matching arrival at its destination as two rows
30 * of the same rate. A departure whose route crosses non-stateful nodes
31 * (ClassSwitch, Sink, a stateless Router) is split over those paths
32 * (`sn.rtnodes`), each sub-event carrying the keys of the nodes it crosses.
33 *
34 * Hand-declared agents interact with the embedded nodes in two ways only:
35 *
36 * - injection: a hand active action drives a node's passive ARV for an open
37 * class, resolved by the node's own state handler (`qn::after_event`);
38 * - extension: hand passives join every network event that carries a node
39 * key, so a hand agent can observe or gate it; a disabled hand passive
40 * blocks it.
41 *
42 * Also here: the Environment embedding (a stage agent plus its stage
43 * networks), the LayeredNetwork embedding (LQN2QN), and the agents of a
44 * MarkovProcess, a MarkovChain (discrete time) and a Workflow (labelled by
45 * activity through its series-parallel tree).
46 */
47
48#include <algorithm>
49#include <cstdio>
50#include <map>
51#include <memory>
52#include <optional>
53#include <set>
54#include <string>
55#include <utility>
56#include <vector>
57
59#include "line/io/lqn2qn.h"
61#include "line/lang/lal/core.h"
67#include "line/lang/qn/state.h"
73
74namespace line {
75namespace lal {
76
77namespace embed_detail {
78
79inline std::string identifier_from(const std::string& name, const std::string& fallback) {
80 return detail::is_identifier(name) ? name : fallback;
81}
82
83/** `%g` of a double. */
84inline std::string fmt_g(double v) {
85 char buf[64];
86 std::snprintf(buf, sizeof(buf), "%g", v);
87 return buf;
88}
89
90/** The queue-length / phase marginal of a station row (`toMarginal`). */
92 const std::vector<double>& row) {
93 const std::size_t K = sn.nclasses;
94 std::vector<std::size_t> ph(K, 1), shift(K, 0);
95 std::size_t w = 0;
96 for (std::size_t k = 0; k < K; ++k) {
97 ph[k] = sn.phasessz_of(ist, k + 1);
98 shift[k] = w;
99 w += ph[k];
100 }
101 return qn::to_marginal(sn, ist, row, ph, shift, sn.nvars_of(sn.node_of_station(ist)));
102}
103
104/** One step of a routing path: a node key, or the marker of a Sink crossing. */
105struct Hop {
106 bool sink = false;
108};
109
110} // namespace embed_detail
111
112/**
113 * A LINE Network embedded as one agent per node (`EmbeddedNetwork`).
114 *
115 * The agent record seen by the LAL core holds the network's global states
116 * (indices into LINE's enumerated space); node agents are projections of it
117 * used for the state table, the rewards and injection. The enumeration is
118 * LAZY: it is built on first use and dropped by `refresh()` or by a change of
119 * the injected classes.
120 *
121 * The model is either a `qn::Network` (shared, so an lvalue added to a
122 * composition is held by reference and re-read on `refresh()`) or a finished
123 * `qn::NetworkStruct` (an Environment stage).
124 */
126 public:
127 EmbeddedNetwork(std::shared_ptr<qn::Network<double>> network, const std::string& prefix,
128 std::optional<double> cutoff)
129 : network_(std::move(network)), prefix_(prefix), cutoff_(cutoff) {
130 check_network(network_->raw_struct(), network_->raw_struct().name);
131 name_ = prefix_.empty() ? network_->raw_struct().name : prefix_;
132 }
133 EmbeddedNetwork(const qn::NetworkStruct<double>& sn, const std::string& prefix, std::optional<double> cutoff)
134 : stage_(std::make_shared<qn::NetworkStruct<double>>(sn)), prefix_(prefix), cutoff_(cutoff) {
135 check_network(*stage_, stage_->name);
136 name_ = prefix_.empty() ? stage_->name : prefix_;
137 }
138
139 const std::string& name() const override { return name_; }
140 const std::string& prefix() const override { return prefix_; }
141
142 std::size_t initial() override {
143 build();
144 return initial_;
145 }
146 const std::vector<NodeEvent>& labels() override {
147 build();
148 return labels_;
149 }
150 std::vector<EmbeddedArc> outgoing(std::size_t s) override {
151 build();
152 return arcs_[s];
153 }
154 const std::vector<EmbeddedArc>& arcs(std::size_t s) {
155 build();
156 return arcs_[s];
157 }
158 bool is_vanishing(std::size_t s) override {
159 build();
160 return vanishing_[s];
161 }
162 bool has_vanishing() override {
163 build();
164 return any_vanishing_;
165 }
166 std::size_t nstates() {
167 build();
168 return space_.size();
169 }
171 build();
172 return *sn_;
173 }
174 const std::vector<qn::NetState<double>>& space() {
175 build();
176 return space_;
177 }
178 /**
179 * The global index of a network state, or npos. Under a WAITQ region the
180 * index is that of the state with every region FIFO empty.
181 */
182 std::size_t index_of(const qn::NetState<double>& state) {
183 build();
184 const auto it = index_.find(key_(state, nullptr));
185 return it == index_.end() ? static_cast<std::size_t>(-1) : it->second;
186 }
187
188 void refresh() override {
189 built_ = false;
190 clear_();
191 }
192
193 void set_injected(const std::set<std::string>& classes) override {
194 if (classes != injected_) {
195 injected_ = classes;
196 if (built_) {
197 built_ = false;
198 clear_();
199 }
200 }
201 }
202
203 /**
204 * Passive response of a node to an injected arrival in global state `s`
205 * (`inject`): `[(target, probability)]`; an empty list blocks the
206 * injection (no successor within LINE's enumerated space, e.g. at the
207 * cutoff).
208 */
209 std::vector<std::pair<std::size_t, double>> inject(std::size_t s, const NodeEvent& key) override {
210 build();
211 const std::size_t node = node_position(key.node);
212 const std::size_t cls = class_position(key.index ? *key.index : std::string());
213 const std::size_t isf = sn_->stateful_index(node);
214 const qn::EventOutcome<double> out =
215 qn::after_event(*sn_, node, space_[s].local[isf - 1], lang::EventType::ARV, cls);
216 std::vector<std::pair<std::size_t, double>> result;
217 for (std::size_t i = 0; i < out.space.size(); ++i) {
218 qn::NetState<double> target = space_[s];
219 target.local[isf - 1] = out.space[i];
220 const auto it = index_.find(key_(target, buf_.empty() ? nullptr : &buf_[s]));
221 const double p = i < out.prob.size() ? out.prob[i] : 1.0;
222 if (it != index_.end() && p > 0) result.push_back(std::make_pair(it->second, p));
223 }
224 return result;
225 }
226
227 void check_injection(const NodeEvent& key) override {
228 if (key.event != lang::EventType::ARV)
229 throw value_error("only ARV node actions can be driven by a hand agent, not " + key.label());
230 if (!key.index) throw value_error("an injected arrival needs a job class: " + key.label());
231 const qn::NetworkStruct<double>& sn = fresh_struct();
232 std::size_t node = 0, cls = 0;
233 for (std::size_t i = 0; i < sn.nodes.size(); ++i)
234 if (sn.nodes[i].name == key.node) node = i + 1;
235 for (std::size_t r = 0; r < sn.classes.size(); ++r)
236 if (sn.classes[r].name == *key.index) cls = r + 1;
237 if (node == 0) throw value_error("network " + name_ + " has no node '" + key.node + "'");
238 if (cls == 0) throw value_error("network " + name_ + " has no class '" + *key.index + "'");
239 if (!sn.nodes[node - 1].stateful)
240 throw value_error(key.node + " is not a stateful node and cannot receive an injected arrival");
241 const std::vector<double> nj = sn.njobs();
242 if (cls - 1 < nj.size() && std::isfinite(nj[cls - 1]))
243 throw InputError(ErrorKind("Model"), "cannot inject arrivals of closed class " + *key.index + " into " +
244 key.node +
245 ": it would break the population of the chain LINE enumerates.");
246 }
247
248 NodeEvent resolve(const std::string& node, lang::EventType event, const std::optional<std::string>& jobclass,
249 const std::optional<std::string>& mode) override {
250 const qn::NetworkStruct<double>& sn = names_struct();
251 bool found = false;
252 for (const qn::NodeDef& nd : sn.nodes)
253 if (nd.name == node) found = true;
254 if (!found) throw value_error("network " + name_ + " has no node '" + node + "'");
255 if (mode && jobclass) throw value_error("give jobclass or mode, not both");
256 std::optional<std::string> index;
257 if (mode) {
258 index = *mode;
259 } else if (jobclass) {
260 bool known = false;
261 for (const qn::JobClass& c : sn.classes)
262 if (c.name == *jobclass) known = true;
263 if (!known) throw value_error("network " + name_ + " has no class '" + *jobclass + "'");
264 index = *jobclass;
265 }
266 return NodeEvent{prefix_, node, event, index};
267 }
268
269 std::string node_name(std::size_t node) override {
270 const qn::NetworkStruct<double>& sn = names_struct();
271 if (node == 0 || node > sn.nodes.size()) throw value_error("network " + name_ + " has no node " + std::to_string(node));
272 return sn.nodes[node - 1].name;
273 }
274 std::string class_name(std::size_t cls) override {
275 const qn::NetworkStruct<double>& sn = names_struct();
276 if (cls == 0 || cls > sn.classes.size())
277 throw value_error("network " + name_ + " has no class " + std::to_string(cls));
278 return sn.classes[cls - 1].name;
279 }
280
281 std::vector<std::pair<std::string, std::size_t>> node_states() override {
282 build();
283 std::vector<std::pair<std::string, std::size_t>> out;
284 for (std::size_t isf = 1; isf <= sn_->stateful_nodes.size(); ++isf)
285 out.push_back(std::make_pair(sn_->nodes[sn_->stateful_nodes[isf - 1] - 1].name, isf));
286 return out;
287 }
288
289 std::string node_state_label(std::size_t s, std::size_t isf) override {
290 build();
291 const std::vector<double>& row = space_[s].local[isf - 1];
292 std::string out = "[";
293 for (std::size_t i = 0; i < row.size(); ++i) out += (i ? " " : "") + embed_detail::fmt_g(row[i]);
294 return out + "]";
295 }
296
297 std::vector<double> node_row(std::size_t s, const std::string& node) override {
298 build();
299 const std::size_t ind = node_position(node);
300 const std::size_t isf = sn_->stateful_index(ind);
301 if (isf == 0) throw value_error(node + " is not a stateful node");
302 return space_[s].local[isf - 1];
303 }
304
305 double node_jobs(std::size_t s, const std::string& node, const std::string& jobclass) override {
306 build();
307 const std::size_t ind = node_position(node);
308 const std::size_t isf = sn_->stateful_index(ind);
309 if (isf == 0) throw value_error(node + " is not a stateful node");
310 const std::size_t ist = sn_->nodes[ind - 1].station;
311 if (ist == 0) throw value_error(node + " is not a station and holds no jobs");
312 const qn::Marginal<double> m = embed_detail::station_marginal(*sn_, ist, space_[s].local[isf - 1]);
313 if (jobclass.empty()) {
314 double total = 0.0;
315 for (double x : m.nir) total += x;
316 return total;
317 }
318 return m.nir[class_position(jobclass) - 1];
319 }
320
321 /** Station-by-class queue lengths and per-station service phases of global state `x` (memoized). */
322 const std::pair<Matrix<double>, std::vector<std::vector<std::vector<double>>>>& queue_lengths(std::size_t x) {
323 build();
324 auto it = qmemo_.find(x);
325 if (it != qmemo_.end()) return it->second;
326 const std::size_t M = sn_->nstations, K = sn_->nclasses;
327 Matrix<double> q(M, K, 0.0);
328 std::vector<std::vector<std::vector<double>>> kir(M);
329 for (std::size_t ist = 1; ist <= M; ++ist) {
330 const std::size_t isf = sn_->stateful_of_station(ist);
331 // EVERY station, the Source included, as `_queue_lengths` reads them:
332 // its arrival phases take part in the phase match of `carry`. A
333 // Source station's queue length is 0, as LINE's QN table reports it
334 // and as SolverENV passes q to resetFun: its marginal is the EXT
335 // sentinel (+Inf per class, see qn/state.h) of an infinite job pool,
336 // which no reset image can match, so 'clear' could not leave an
337 // open stage. A reset writing a nonzero Source entry still finds no
338 // destination state.
339 if (isf == 0) continue;
340 const qn::Marginal<double> m = embed_detail::station_marginal(*sn_, ist, space_[x].local[isf - 1]);
341 if (sn_->nodes[sn_->node_of_station(ist) - 1].nodetype != lang::NodeType::Source)
342 for (std::size_t k = 0; k < K; ++k) q(ist - 1, k) = m.nir[k];
343 kir[ist - 1] = m.kir;
344 }
345 return qmemo_.emplace(x, std::make_pair(q, kir)).first->second;
346 }
347
348 private:
349 std::shared_ptr<qn::Network<double>> network_;
350 std::shared_ptr<qn::NetworkStruct<double>> stage_;
351 std::string prefix_, name_;
352 std::optional<double> cutoff_;
353 std::set<std::string> injected_;
354 bool built_ = false;
355 // the lazy enumeration
356 std::shared_ptr<const qn::NetworkStruct<double>> sn_;
357 /**
358 * The class name each action key carries, indexed like `sn_->classes`.
359 * Native fork-join: SolverCTMC solves a tag-augmented struct whose
360 * auxiliary sibling classes (`A_f1_b1_t1`, ...) are copies of an original
361 * class. Each auxiliary class is named after its original here, through
362 * the fork-join class map (`sn.fjclassmap`, see lang/qn/fj_tag.h), as
363 * SolverCTMC folds its metrics back (`fj_foldback`), so a key reads the
364 * user's class; the vector keeps the augmented length for sn indexing.
365 */
366 std::vector<std::string> class_names_;
367 std::vector<qn::NetState<double>> space_;
368 /**
369 * The region FIFOs of each state when SolverCTMC built the chain with its
370 * WAITQ region walk (`LalCollect::buf`), empty otherwise: several states of
371 * that walk share one network state and differ only in what is parked.
372 */
373 std::vector<std::vector<std::vector<std::size_t>>> buf_;
374 std::map<std::vector<double>, std::size_t> index_;
375 std::vector<bool> vanishing_;
376 bool any_vanishing_ = false;
377 std::size_t initial_ = 0;
378 std::vector<std::vector<EmbeddedArc>> arcs_;
379 std::vector<NodeEvent> labels_;
380 std::map<std::size_t, std::pair<Matrix<double>, std::vector<std::vector<std::vector<double>>>>> qmemo_;
381
382 void clear_() {
383 sn_.reset();
384 class_names_.clear();
385 space_.clear();
386 buf_.clear();
387 index_.clear();
388 vanishing_.clear();
389 any_vanishing_ = false;
390 arcs_.clear();
391 labels_.clear();
392 qmemo_.clear();
393 }
394
395 /**
396 * The lookup key of a global state: the network state, then each region
397 * FIFO under a WAITQ region (`ctmc::waitq_detail::waitq_key`). `buf` null
398 * reads every FIFO empty.
399 */
400 std::vector<double> key_(const qn::NetState<double>& state,
401 const std::vector<std::vector<std::size_t>>* buf) const {
402 if (buf_.empty()) return ctmc::ctmc_detail::state_key(state);
404 ws.net = state;
405 ws.buf = buf ? *buf : std::vector<std::vector<std::size_t>>(buf_.front().size());
406 return ctmc::waitq_detail::waitq_key(ws);
407 }
408
409 /** The struct whose names (nodes, classes) the resolution reads: no refresh is needed for names. */
410 const qn::NetworkStruct<double>& names_struct() { return network_ ? network_->raw_struct() : *stage_; }
411
412 /** A refreshed struct of the model, as LINE builds it. */
413 const qn::NetworkStruct<double>& fresh_struct() { return network_ ? network_->get_struct() : *stage_; }
414
415 public:
416 /** The embedded model's own refreshed struct (`network.get_struct()`), without any enumeration. */
417 const qn::NetworkStruct<double>& model_struct() { return fresh_struct(); }
418
419 private:
420
421 std::size_t node_position(const std::string& node) const {
422 for (std::size_t i = 0; i < sn_->nodes.size(); ++i)
423 if (sn_->nodes[i].name == node) return i + 1;
424 throw value_error("network " + name_ + " has no node '" + node + "'");
425 }
426 std::size_t class_position(const std::string& cls) const {
427 for (std::size_t r = 0; r < sn_->classes.size(); ++r)
428 if (sn_->classes[r].name == cls) return r + 1;
429 throw value_error("network " + name_ + " has no class '" + cls + "'");
430 }
431
432 /**
433 * The struct whose space is enumerated, and the placeholder emissions to
434 * drop (`_enumeration_network`).
435 *
436 * LINE gives a class whose Source arrival is Disabled zero visits and
437 * enumerates no state holding its jobs, so an arrival a hand agent injects
438 * would have no state to land in. For every injected class with a
439 * disabled emission, a copy of the network gives the Source a placeholder
440 * Exp(1) law, which makes LINE enumerate the space it would build if the
441 * class arrived; the placeholder's own emission events are dropped, and
442 * the hand agent drives those arrivals instead.
443 */
444 qn::NetworkStruct<double> enumeration_struct(std::set<std::pair<std::size_t, std::size_t>>& placeholders) {
445 const qn::NetworkStruct<double>& names = names_struct();
446 std::vector<std::pair<std::size_t, std::size_t>> todo; // (node, class), 1-based
447 for (const std::string& cname : injected_) {
448 std::size_t cls = 0;
449 for (std::size_t r = 0; r < names.classes.size(); ++r)
450 if (names.classes[r].name == cname) cls = r + 1;
451 if (cls == 0) continue;
452 for (std::size_t ind = 1; ind <= names.nodes.size(); ++ind) {
453 const qn::NodeDef& nd = names.nodes[ind - 1];
454 if (nd.nodetype != lang::NodeType::Source || nd.station == 0) continue;
455 const bool disabled = nd.station - 1 >= names.service.size() ||
456 cls - 1 >= names.service[nd.station - 1].size() ||
457 names.service[nd.station - 1][cls - 1].type == lang::ProcessType::DISABLED;
458 if (disabled) todo.push_back(std::make_pair(ind, cls));
459 }
460 }
461 placeholders.clear();
462 for (const auto& t : todo) placeholders.insert(t);
463 if (network_) {
464 if (todo.empty()) return network_->get_struct();
465 qn::Network<double> copy = *network_;
466 for (const auto& t : todo) copy.set_arrival(t.first, t.second, lang::Distrib<double>::exp_rate(1.0));
467 return copy.get_struct();
468 }
469 qn::NetworkStruct<double> copy = *stage_;
470 if (!todo.empty()) {
471 for (const auto& t : todo) {
472 lang::Distrib<double> d = lang::Distrib<double>::exp_rate(1.0);
474 copy.set_service(copy.nodes[t.first - 1].station, t.second, d);
475 }
476 copy.refresh_struct();
477 }
478 return copy;
479 }
480
481 /** One participant of a collected event: a sync half, a mode arc, or a fork firing. */
482 struct Rec {
483 enum class Kind { Sync, Mode, Fork };
484 Kind kind = Kind::Sync;
486 std::size_t node = 0; ///< 1-based
487 std::size_t cls = 0; ///< 1-based class, or the mode of a Transition PHASE
488 std::size_t mode = 0; ///< 1-based mode of a Mode record
489 /// a passive arrival the region (or a full destination of a batch job) refused: it arrived nowhere
490 bool parked = false;
491 /// a head-of-line job a region release let in on this arc: an arrival at its destination
492 bool released = false;
493 };
494
495 std::string mode_name(std::size_t node, std::size_t mode0) const {
496 const auto it = sn_->transparam.find(node);
497 if (it != sn_->transparam.end() && mode0 < it->second.modenames.size() && !it->second.modenames[mode0].empty())
498 return it->second.modenames[mode0];
499 return "mode" + std::to_string(mode0);
500 }
501
502 /** Translate a record into a NodeEvent (`_key`); nullopt for LOCAL or out-of-range records. */
503 std::optional<NodeEvent> key_of(const Rec& r) const {
504 if (r.node == 0 || r.node > sn_->nodes.size()) return std::nullopt;
505 const std::string& nname = sn_->nodes[r.node - 1].name;
506 if (r.kind == Rec::Kind::Fork)
507 return NodeEvent{prefix_, nname, lang::EventType::DEP, class_names_[r.cls - 1]};
508 if (r.event == lang::EventType::LOCAL) return std::nullopt;
509 if (r.kind == Rec::Kind::Mode && (r.event == lang::EventType::ENABLE || r.event == lang::EventType::FIRE))
510 return NodeEvent{prefix_, nname, r.event, mode_name(r.node, r.mode - 1)};
511 if (r.event == lang::EventType::PHASE && sn_->nodes[r.node - 1].nodetype == lang::NodeType::Transition)
512 return NodeEvent{prefix_, nname, r.event, mode_name(r.node, r.cls - 1)};
513 std::optional<std::string> index;
514 if (r.cls >= 1 && r.cls <= class_names_.size()) index = class_names_[r.cls - 1];
515 return NodeEvent{prefix_, nname, r.event, index};
516 }
517
518 /** Append the DEP of the last crossed node, leaving it in class `cls` (`_close`). */
519 std::vector<embed_detail::Hop> close_(std::vector<embed_detail::Hop> hops, std::size_t cls0) const {
520 if (!hops.empty() && !hops.back().sink && hops.back().key.event == lang::EventType::ARV) {
521 embed_detail::Hop h;
522 h.key = NodeEvent{prefix_, hops.back().key.node, lang::EventType::DEP, class_names_[cls0]};
523 hops.push_back(h);
524 }
525 return hops;
526 }
527
528 struct Path {
529 double prob;
530 std::vector<NodeEvent> hops;
531 bool via_sink;
532 };
533
534 /**
535 * Acyclic routing paths from (node_a, class_a) to (node_p, class_p) through
536 * non-stateful nodes (`_paths`). A cycle among non-stateful nodes has
537 * infinitely many paths and is refused.
538 */
539 std::vector<Path> paths_(std::size_t node_a0, std::size_t class_a0, std::size_t node_p0, std::size_t class_p0) const {
540 const std::size_t K = sn_->nclasses;
541 const Matrix<double>& rt = sn_->rtnodes;
542 std::vector<std::pair<double, std::pair<std::vector<embed_detail::Hop>, bool>>> out;
543 std::function<void(std::size_t, std::size_t, double, const std::vector<embed_detail::Hop>&,
544 const std::set<std::pair<std::size_t, std::size_t>>&)>
545 walk = [&](std::size_t node, std::size_t cls, double prob, const std::vector<embed_detail::Hop>& hops,
546 const std::set<std::pair<std::size_t, std::size_t>>& seen) {
547 const std::size_t row = node * K + cls;
548 if (row >= rt.rows()) return;
549 for (std::size_t col = 0; col < rt.cols(); ++col) {
550 const double v = rt(row, col);
551 if (!(v > 0)) continue;
552 const std::size_t nxt = col / K, ncls = col % K;
553 const double q = prob * v;
554 if (sn_->nodes[nxt].stateful) {
555 if (!hops.empty() && hops.back().sink) {
556 if (nxt == node_p0 && ncls == class_p0) out.push_back({q, {hops, true}});
557 continue;
558 }
559 if (nxt == node_p0 && ncls == class_p0) out.push_back({q, {close_(hops, ncls), false}});
560 continue;
561 }
562 if (seen.count(std::make_pair(nxt, ncls)))
563 throw UnsupportedError(ErrorKind("Model"),
564 "LAL cannot embed network " + name_ +
565 ": the routing cycles among non-stateful nodes through " +
566 sn_->nodes[nxt].name + ".");
567 std::vector<embed_detail::Hop> hop = close_(hops, ncls);
568 embed_detail::Hop arv;
569 arv.key = NodeEvent{prefix_, sn_->nodes[nxt].name, lang::EventType::ARV, class_names_[ncls]};
570 hop.push_back(arv);
571 if (sn_->nodes[nxt].nodetype == lang::NodeType::Sink) {
572 embed_detail::Hop mark;
573 mark.sink = true;
574 hop.push_back(mark);
575 }
576 std::set<std::pair<std::size_t, std::size_t>> seen2 = seen;
577 seen2.insert(std::make_pair(nxt, ncls));
578 walk(nxt, ncls, q, hop, seen2);
579 }
580 };
581 walk(node_a0, class_a0, 1.0, std::vector<embed_detail::Hop>(), std::set<std::pair<std::size_t, std::size_t>>());
582 std::vector<Path> paths;
583 for (const auto& o : out) {
584 Path p;
585 p.prob = o.first;
586 for (const embed_detail::Hop& h : o.second.first)
587 if (!h.sink) p.hops.push_back(h.key);
588 p.via_sink = o.second.second;
589 paths.push_back(p);
590 }
591 return paths;
592 }
593
594 /**
595 * Split one event over the routing paths it takes through non-stateful
596 * nodes (`_split`): `[(fraction, keys)]` with fractions summing to one. A
597 * path through a Sink ends there: the Source ARV that closes it in
598 * `sn.rt` is LINE's bookkeeping for the job leaving, so its key is dropped.
599 *
600 * Under a finite capacity region an arc can also carry region records: a
601 * PARKED passive is a job the region refused (WAITQ) or destroyed (DROP),
602 * which crossed the routing path but arrived nowhere, so its own ARV key is
603 * dropped as a Sink's is (the hops it crossed stay); a RELEASED record is a
604 * head-of-line job the arc let into the region, whose ARV is appended. A
605 * BMAP batch carries the Source DEP once per job, each paired with its own
606 * passive (parked when the job was lost) and routed independently, so its
607 * split is the product of the per-job splits, keys repeated per job.
608 */
609 std::vector<std::pair<double, std::vector<NodeEvent>>> split_(const std::vector<Rec>& actives,
610 const std::vector<Rec>& all_passives) const {
611 std::vector<Rec> passives;
612 std::vector<NodeEvent> extra;
613 for (const Rec& r : all_passives) {
614 if (!r.released) {
615 passives.push_back(r);
616 continue;
617 }
618 if (const auto k = key_of(r)) extra.push_back(*k);
619 }
620 if (actives.size() > 1 && actives.size() == passives.size()) {
621 std::vector<std::pair<double, std::vector<NodeEvent>>> combos{
622 std::make_pair(1.0, std::vector<NodeEvent>())};
623 for (std::size_t i = 0; i < actives.size(); ++i) {
624 const std::vector<std::pair<double, std::vector<NodeEvent>>> one =
625 split_(std::vector<Rec>{actives[i]}, std::vector<Rec>{passives[i]});
626 std::vector<std::pair<double, std::vector<NodeEvent>>> next;
627 for (const auto& c : combos)
628 for (const auto& o : one) {
629 std::vector<NodeEvent> keys = c.second;
630 keys.insert(keys.end(), o.second.begin(), o.second.end());
631 next.push_back(std::make_pair(c.first * o.first, keys));
632 }
633 combos.swap(next);
634 }
635 for (auto& c : combos) c.second.insert(c.second.end(), extra.begin(), extra.end());
636 return combos;
637 }
638 const bool parked = passives.size() == 1 && passives[0].parked;
639 std::vector<NodeEvent> base;
640 for (const Rec& r : actives)
641 if (const auto k = key_of(r)) base.push_back(*k);
642 if (!parked)
643 for (const Rec& r : passives)
644 if (const auto k = key_of(r)) base.push_back(*k);
645 std::vector<NodeEvent> flat = base;
646 flat.insert(flat.end(), extra.begin(), extra.end());
647 const std::size_t N = sn_->nodes.size(), K = sn_->nclasses;
648 const bool has_rt = sn_->rtnodes.rows() >= N * K && sn_->rtnodes.cols() >= N * K && N * K > 0;
649 if (actives.size() != 1 || passives.size() != 1 || actives[0].kind != Rec::Kind::Sync ||
650 actives[0].event != lang::EventType::DEP || passives[0].event != lang::EventType::ARV || !has_rt)
651 return {std::make_pair(1.0, flat)};
652 const Rec& a = actives[0];
653 const Rec& p = passives[0];
654 const std::vector<Path> paths = paths_(a.node - 1, a.cls - 1, p.node - 1, p.cls - 1);
655 double total = 0.0;
656 for (const Path& x : paths) total += x.prob;
657 if (paths.empty() || !(total > 0)) return {std::make_pair(1.0, flat)};
658 const std::optional<NodeEvent> akey = key_of(a), pkey = key_of(p);
659 std::vector<std::pair<double, std::vector<NodeEvent>>> out;
660 for (const Path& x : paths) {
661 std::vector<NodeEvent> keys;
662 if (akey) keys.push_back(*akey);
663 keys.insert(keys.end(), x.hops.begin(), x.hops.end());
664 if (!x.via_sink && !parked && pkey) keys.push_back(*pkey);
665 keys.insert(keys.end(), extra.begin(), extra.end());
666 out.push_back(std::make_pair(x.prob / total, keys));
667 }
668 return out;
669 }
670
671 void build() {
672 if (built_) return;
673 std::set<std::pair<std::size_t, std::size_t>> placeholders;
674 const qn::NetworkStruct<double> net = enumeration_struct(placeholders);
675 ctmc::CtmcOptions opt;
676 if (cutoff_) opt.cutoff = *cutoff_;
677 opt.lal_collect = std::make_shared<ctmc::LalCollect>();
678 opt.lal_collect->stop = true;
679 // A WAITQ region is built by SolverCTMC's augmented region walk, which
680 // fills the collect itself (python `_build_fcr_waitq_ssg`).
683 else
685 const ctmc::LalCollect& c = *opt.lal_collect;
686 if (!c.filled)
687 throw UnsupportedError(ErrorKind("Model"),
688 "LAL could not embed network " + name_ +
689 ": SolverCTMC did not build its generator through the sync-action builder "
690 "for this model.");
691 if (c.initial_index == static_cast<std::size_t>(-1))
692 throw InputError(ErrorKind("Model"),
693 "LAL could not locate the initial state of network " + name_ +
694 " in its enumerated state space; check the initial state and the cutoff.");
695 sn_ = c.sn;
696 class_names_.clear();
697 for (const qn::JobClass& jc : sn_->classes) class_names_.push_back(jc.name);
698 // fjclassmap[a] is the 1-based ORIGINAL class of auxiliary class a+1, 0 for an original
699 for (std::size_t a = 0; a < sn_->fjclassmap.size() && a < class_names_.size(); ++a) {
700 const std::size_t orig = sn_->fjclassmap[a];
701 if (orig >= 1 && orig <= class_names_.size()) class_names_[a] = class_names_[orig - 1];
702 }
703 space_ = c.space;
704 buf_ = c.buf;
705 index_.clear();
706 for (std::size_t s = 0; s < space_.size(); ++s) index_[key_(space_[s], buf_.empty() ? nullptr : &buf_[s])] = s;
707 vanishing_.assign(space_.size(), false);
708 any_vanishing_ = false;
709 for (std::size_t v : c.vanishing)
710 if (v < vanishing_.size()) {
711 vanishing_[v] = true;
712 any_vanishing_ = true;
713 }
714 initial_ = c.initial_index;
715 arcs_.assign(space_.size(), std::vector<EmbeddedArc>());
716 labels_.clear();
717 std::set<NodeEvent> seen;
718 const std::size_t local = sn_->nodes.size() + 1;
719 for (const ctmc::LalCollectedEvent& ev : c.events) {
720 std::vector<Rec> actives, passives;
722 const qn::Sync<double>& sy = c.sync[ev.index];
723 if (sy.active.event == lang::EventType::DEP &&
724 placeholders.count(std::make_pair(sy.active.node, sy.active.cls)))
725 continue; // the placeholder Source emission; the hand agent drives these arrivals
726 Rec a;
727 a.kind = Rec::Kind::Sync;
728 a.event = sy.active.event;
729 a.node = sy.active.node;
730 a.cls = sy.active.cls;
731 actives.push_back(a);
732 if (sy.passive.node != local) {
733 Rec p;
734 p.kind = Rec::Kind::Sync;
735 p.event = sy.passive.event;
736 p.node = sy.passive.node;
737 p.cls = sy.passive.cls;
738 p.parked = ev.parked;
739 passives.push_back(p);
740 }
741 for (const auto& rl : ev.released) {
742 Rec p;
743 p.kind = Rec::Kind::Sync;
744 p.event = lang::EventType::ARV;
745 p.node = rl.first;
746 p.cls = rl.second;
747 p.released = true;
748 passives.push_back(p);
749 }
750 } else if (ev.kind == ctmc::LalCollectedEvent::Kind::Batch) {
751 // the Source DEP once per job, each job paired with its own passive record
752 const qn::Sync<double>& sy = c.sync[ev.index];
753 Rec a;
754 a.kind = Rec::Kind::Sync;
755 a.event = sy.active.event;
756 a.node = sy.active.node;
757 a.cls = sy.active.cls;
758 for (const auto& job : ev.jobs) {
759 const qn::Sync<double>& sj = c.sync[job.first];
760 Rec p;
761 p.kind = Rec::Kind::Sync;
762 p.event = sj.passive.event;
763 p.node = sj.passive.node;
764 p.cls = sj.passive.cls;
765 p.parked = job.second;
766 actives.push_back(a);
767 passives.push_back(p);
768 }
769 } else if (ev.kind == ctmc::LalCollectedEvent::Kind::Global) {
770 const qn::GlobalSync<double>& g = c.gsync[ev.index];
771 Rec a;
772 a.kind = Rec::Kind::Mode;
773 a.event = g.active.event;
774 a.node = g.active.node;
775 a.cls = g.active.cls;
776 a.mode = g.active.mode;
777 actives.push_back(a);
778 for (const qn::ModeEvent<double>& pe : g.passive) {
779 Rec p;
780 p.kind = Rec::Kind::Mode;
781 p.event = pe.event;
782 p.node = pe.node;
783 p.cls = pe.cls;
784 p.mode = pe.mode;
785 passives.push_back(p);
786 }
787 } else if (ev.kind == ctmc::LalCollectedEvent::Kind::Fork) {
788 const qn::FjSync<double>& f = c.fjsync[ev.index];
789 Rec a;
790 a.kind = Rec::Kind::Fork;
791 a.event = lang::EventType::DEP;
792 a.node = f.fork;
793 a.cls = f.cls;
794 actives.push_back(a);
795 }
796 // true-BAS become-blocked arcs carry no event of their own
797 for (const auto& fk : split_(actives, passives)) {
798 for (const NodeEvent& k : fk.second)
799 if (seen.insert(k).second) labels_.push_back(k);
800 for (const auto& arc : ev.arcs) {
801 const double rate = std::get<2>(arc);
802 if (!(rate > 0)) continue;
803 EmbeddedArc e;
804 e.target = std::get<1>(arc);
805 e.keys = fk.second;
806 e.rate = rate * fk.first;
807 e.immediate = ev.immediate;
808 arcs_[std::get<0>(arc)].push_back(e);
809 }
810 }
811 }
812 built_ = true;
813 }
814};
815
816/**
817 * A LINE Environment embedded as a stage agent plus its stage networks
818 * (`EmbeddedEnvironment`).
819 *
820 * The joint state is `(clock, x)`: `clock` is the stage together with the
821 * phases of its running stage clocks, `x` a global state of that stage's
822 * network. In stage e the network evolves with stage e's own arcs; a stage
823 * clock ringing moves to the destination stage, starts its clocks afresh, and
824 * carries the network state across under the arc's reset policy: no reset
825 * (`keep`) matches every node's state row in the destination stage's space; a
826 * queue-length reset `q -> f(q)` moves to the destination state with queue
827 * lengths f(q), keeping the service phases where such a state exists; a
828 * `resetStateFun` (`Environment::set_state_reset`) gives the entry law of the
829 * exit state as the image of its unit vector over the tangible states.
830 * Competing arcs are racing phase-type clocks; kernel arcs draw the
831 * destination on entry and then run that arc's sojourn clock. Stage changes
832 * carry the key `Env.STAGE[e->h]`.
833 */
835 public:
836 EmbeddedEnvironment(const env::Environment<double>& e, const std::string& prefix, std::optional<double> cutoff)
837 : env_(std::make_shared<env::Environment<double>>(e)),
838 prefix_(prefix.empty() ? embed_detail::identifier_from(e.name(), "Env") : prefix),
839 cutoff_(cutoff) {
840 for (std::size_t s = 0; s < env_->nstages(); ++s)
841 if (env_->is_lqn(s))
842 throw UnsupportedError(ErrorKind("Model"),
843 "LAL embeds an Environment of Network stages; stage " + env_->stage(s).name +
844 " holds a LayeredNetwork.");
845 }
846
847 const std::string& name() const override { return prefix_; }
848 const std::string& prefix() const override { return prefix_; }
849
850 std::size_t initial() override {
851 build();
852 return initial_;
853 }
854 const std::vector<NodeEvent>& labels() override {
855 build();
856 return labels_;
857 }
858 bool is_vanishing(std::size_t s) override {
859 build();
860 const std::pair<std::size_t, std::size_t>& cx = state_list_[s];
861 return nets()[clocks_[cx.first].stage]->is_vanishing(cx.second);
862 }
863 bool has_vanishing() override {
864 for (const auto& n : nets())
865 if (n->has_vanishing()) return true;
866 return false;
867 }
868
869 void refresh() override {
870 built_ = false;
871 nets_.clear();
872 tangible_.clear();
873 state_list_.clear();
874 state_index_.clear();
875 }
876
877 NodeEvent resolve(const std::string& node, lang::EventType event, const std::optional<std::string>& jobclass,
878 const std::optional<std::string>& mode) override {
879 if (event == lang::EventType::STAGE) return NodeEvent{prefix_, "Env", lang::EventType::STAGE, jobclass};
880 return nets()[0]->resolve(node, event, jobclass, mode);
881 }
882 std::string node_name(std::size_t node) override { return nets()[0]->node_name(node); }
883 std::string class_name(std::size_t cls) override { return nets()[0]->class_name(cls); }
884
885 void check_injection(const NodeEvent&) override {
886 throw UnsupportedError(ErrorKind("Synchronization"),
887 "injection into an embedded Environment is not supported: its stage models are "
888 "re-entered with reset policies that an external arrival stream does not carry.");
889 }
890 std::vector<std::pair<std::size_t, double>> inject(std::size_t, const NodeEvent& key) override {
891 check_injection(key);
892 return std::vector<std::pair<std::size_t, double>>();
893 }
894
895 std::vector<std::pair<std::string, std::size_t>> node_states() override { return nets()[0]->node_states(); }
896 std::string node_state_label(std::size_t s, std::size_t isf) override {
897 build();
898 const std::pair<std::size_t, std::size_t>& cx = state_list_[s];
899 return nets()[clocks_[cx.first].stage]->node_state_label(cx.second, isf);
900 }
901 std::vector<double> node_row(std::size_t s, const std::string& node) override {
902 build();
903 const std::pair<std::size_t, std::size_t>& cx = state_list_[s];
904 return nets()[clocks_[cx.first].stage]->node_row(cx.second, node);
905 }
906 double node_jobs(std::size_t s, const std::string& node, const std::string& jobclass) override {
907 build();
908 const std::pair<std::size_t, std::size_t>& cx = state_list_[s];
909 return nets()[clocks_[cx.first].stage]->node_jobs(cx.second, node, jobclass);
910 }
911
912 bool has_stages() override { return true; }
913 std::size_t stage_of(std::size_t s) override {
914 build();
915 return clocks_[state_list_[s].first].stage;
916 }
917 std::vector<std::string> stage_names() override {
918 std::vector<std::string> out;
919 for (std::size_t e = 0; e < env_->nstages(); ++e) {
920 const std::string& n = env_->stage(e).model.name;
921 out.push_back(n.empty() ? "stage" + std::to_string(e) : n);
922 }
923 return out;
924 }
925
926 std::vector<EmbeddedArc> outgoing(std::size_t s) override {
927 build();
928 const std::size_t c = state_list_[s].first, x = state_list_[s].second;
929 const std::size_t e = clocks_[c].stage;
930 const std::vector<std::size_t> phases = clocks_[c].phases;
931 EmbeddedNetwork& net = *nets()[e];
932 std::vector<EmbeddedArc> out;
933 for (const EmbeddedArc& a : net.arcs(x)) {
934 EmbeddedArc b = a;
935 b.target = state(c, a.target);
936 out.push_back(b);
937 }
938 const StageArcs& sa = stages_[e];
939 if (sa.arcs.empty()) return out;
940 auto fire = [&](std::size_t h, double rate) {
941 double total = 0.0;
942 for (const auto& w : entry_[h]) total += w.second;
943 for (const auto& yp : carry(x, e, h)) {
944 for (const auto& w : entry_[h]) {
945 EmbeddedArc b;
946 b.target = state(w.first, yp.first);
947 b.keys = std::vector<NodeEvent>{stage_key(e, h)};
948 b.rate = rate * yp.second * w.second / total;
949 b.immediate = false;
950 out.push_back(b);
951 }
952 }
953 };
954 if (sa.kernel) {
955 const std::size_t k = phases[0], ph = phases[1];
956 const StageArc& arc = sa.arcs[k];
957 for (std::size_t j = 0; j < arc.D0.cols(); ++j)
958 if (j != ph && arc.D0(ph, j) > 0) {
959 EmbeddedArc b;
960 b.target = state(clock_index_.at(Clock{e, {k, j}}), x);
961 b.rate = arc.D0(ph, j);
962 out.push_back(b);
963 }
964 double done = 0.0;
965 for (std::size_t j = 0; j < arc.D1.cols(); ++j) done += arc.D1(ph, j);
966 if (done > 0) fire(arc.dest, done);
967 return out;
968 }
969 for (std::size_t k = 0; k < sa.arcs.size(); ++k) {
970 const StageArc& arc = sa.arcs[k];
971 const std::size_t ph = phases[k];
972 for (std::size_t j = 0; j < arc.D0.cols(); ++j)
973 if (j != ph && arc.D0(ph, j) > 0) {
974 std::vector<std::size_t> nxt = phases;
975 nxt[k] = j;
976 EmbeddedArc b;
977 b.target = state(clock_index_.at(Clock{e, nxt}), x);
978 b.rate = arc.D0(ph, j);
979 out.push_back(b);
980 }
981 double done = 0.0;
982 for (std::size_t j = 0; j < arc.D1.cols(); ++j) done += arc.D1(ph, j);
983 if (done > 0) fire(arc.dest, done);
984 }
985 return out;
986 }
987
988 private:
989 struct StageArc {
990 std::size_t dest = 0;
991 Matrix<double> D0, D1;
992 std::vector<double> alpha;
993 double prob = 1.0;
994 };
995 struct StageArcs {
996 bool kernel = false;
997 std::vector<StageArc> arcs;
998 };
999 struct Clock {
1000 std::size_t stage;
1001 std::vector<std::size_t> phases;
1002 bool operator<(const Clock& o) const { return std::tie(stage, phases) < std::tie(o.stage, o.phases); }
1003 };
1004 /** The reset of one arc: `keep`, a queue-length map `fun`, or a state reset `state_fun`. */
1005 struct Reset {
1006 bool keep = true;
1007 env::ResetMarginal fun;
1008 env::ResetStateVec<double> state_fun; ///< non-empty for a `resetStateFun`
1009 };
1010
1011 /** The tangible states of a stage network, in LINE's order, and each global state's position among them. */
1012 struct Tangible {
1013 std::vector<std::size_t> states;
1014 std::vector<std::size_t> position; ///< npos for a vanishing state
1015 };
1016
1017 std::shared_ptr<env::Environment<double>> env_;
1018 std::map<std::size_t, Tangible> tangible_;
1019 std::string prefix_;
1020 std::optional<double> cutoff_;
1021 bool built_ = false;
1022 std::vector<std::shared_ptr<EmbeddedNetwork>> nets_;
1023 std::vector<StageArcs> stages_;
1024 std::vector<Clock> clocks_;
1025 std::map<Clock, std::size_t> clock_index_;
1026 std::vector<std::vector<std::pair<std::size_t, double>>> entry_; ///< per stage: (clock, weight)
1027 std::map<std::pair<std::size_t, std::size_t>, Reset> resets_;
1028 std::vector<NodeEvent> labels_;
1029 std::size_t initial_ = 0;
1030 std::vector<std::pair<std::size_t, std::size_t>> state_list_;
1031 std::map<std::pair<std::size_t, std::size_t>, std::size_t> state_index_;
1032
1033 const std::vector<std::shared_ptr<EmbeddedNetwork>>& nets() {
1034 if (nets_.empty())
1035 for (std::size_t e = 0; e < env_->nstages(); ++e)
1036 nets_.push_back(std::make_shared<EmbeddedNetwork>(env_->stage(e).model, prefix_, cutoff_));
1037 return nets_;
1038 }
1039
1040 NodeEvent stage_key(std::size_t e, std::size_t h) const {
1041 return NodeEvent{prefix_, "Env", lang::EventType::STAGE, std::to_string(e) + "->" + std::to_string(h)};
1042 }
1043
1044 std::size_t state(std::size_t clock, std::size_t x) {
1045 const std::pair<std::size_t, std::size_t> key(clock, x);
1046 const auto it = state_index_.find(key);
1047 if (it != state_index_.end()) return it->second;
1048 const std::size_t i = state_list_.size();
1049 state_index_[key] = i;
1050 state_list_.push_back(key);
1051 return i;
1052 }
1053
1054 /** The tangible states of stage e's network (memoized; the index space of a `resetStateFun`). */
1055 const Tangible& tangible(std::size_t e) {
1056 auto it = tangible_.find(e);
1057 if (it != tangible_.end()) return it->second;
1058 EmbeddedNetwork& net = *nets()[e];
1059 Tangible t;
1060 t.position.assign(net.nstates(), static_cast<std::size_t>(-1));
1061 for (std::size_t i = 0; i < net.nstates(); ++i)
1062 if (!net.is_vanishing(i)) {
1063 t.position[i] = t.states.size();
1064 t.states.push_back(i);
1065 }
1066 return tangible_.emplace(e, std::move(t)).first->second;
1067 }
1068
1069 /**
1070 * Classify the reset of arc e->h (`_reset_kind`): keep, a queue-length map,
1071 * or a state reset. A `resetStateFun` maps the exit state-probability vector
1072 * of stage e onto the entry vector of stage h (SolverENV statevec); applied
1073 * to the unit vector of the exit state it gives the entry law of that
1074 * state, and it takes precedence over a queue-length reset on the same arc.
1075 */
1076 Reset reset_kind(std::size_t e, std::size_t h) {
1077 Reset r;
1078 const env::EnvArc<double>& arc = env_->arc(e, h);
1079 if (arc.reset_state) {
1080 r.keep = false;
1081 r.state_fun = arc.reset_state;
1082 return r;
1083 }
1084 if (!arc.reset) return r;
1085 EmbeddedNetwork& net = *nets()[e];
1086 const std::size_t M = net.sn().nstations, K = net.sn().nclasses;
1087 // the probe lives where the reset is applied: a Source row is 0 in
1088 // every q `queue_lengths` builds, so it is 0 here too, and a reset that
1089 // is the identity on that domain is `keep` while one writing a nonzero
1090 // Source entry is a queue-length map (whose `carry` then finds no state)
1091 const qn::NetworkStruct<double>& sn = net.sn();
1092 Matrix<double> probe(M, K, 0.0);
1093 for (std::size_t i = 0; i < M; ++i) {
1094 if (sn.nodes[sn.node_of_station(i + 1) - 1].nodetype == lang::NodeType::Source) continue;
1095 for (std::size_t k = 0; k < K; ++k) probe(i, k) = static_cast<double>(i * K + k + 1);
1096 }
1097 const Matrix<double> out = arc.reset(probe);
1098 bool same = out.rows() == M && out.cols() == K;
1099 for (std::size_t i = 0; same && i < M; ++i)
1100 for (std::size_t k = 0; same && k < K; ++k)
1101 if (out(i, k) != probe(i, k)) same = false;
1102 if (same) return r;
1103 r.keep = false;
1104 r.fun = arc.reset;
1105 return r;
1106 }
1107
1108 /** Entry law `[(y, p)]` in stage h of exit state x of stage e under the reset (`_carry`). */
1109 std::vector<std::pair<std::size_t, double>> carry(std::size_t x, std::size_t e, std::size_t h) {
1110 EmbeddedNetwork& src = *nets()[e];
1111 EmbeddedNetwork& dst = *nets()[h];
1112 const Reset& kind = resets_.at(std::make_pair(e, h));
1113 if (kind.keep) {
1114 const std::size_t y = dst.index_of(src.space()[x]);
1115 if (y != static_cast<std::size_t>(-1)) return {std::make_pair(y, 1.0)};
1116 throw UnsupportedError(ErrorKind("Model"),
1117 "Environment stage " + std::to_string(e) + "->" + std::to_string(h) +
1118 ": the network state of stage " + std::to_string(e) +
1119 " has no counterpart in the state space of stage " + std::to_string(h) +
1120 ", so the keep policy cannot carry it.");
1121 }
1122 if (kind.state_fun) {
1123 // the vectors are indexed by the TANGIBLE states, in LINE's order,
1124 // as SolverENV's statevec analyzer reads them
1125 const Tangible& src_t = tangible(e);
1126 const Tangible& dst_t = tangible(h);
1127 const std::size_t pos = src_t.position[x];
1128 if (pos == static_cast<std::size_t>(-1))
1129 throw UnsupportedError(ErrorKind("Model"), "Environment arc " + std::to_string(e) + "->" +
1130 std::to_string(h) +
1131 ": a resetStateFun cannot be applied in a vanishing "
1132 "state.");
1133 std::vector<double> pex(src_t.states.size(), 0.0);
1134 pex[pos] = 1.0;
1135 const std::vector<double> pin = kind.state_fun(pex);
1136 bool ok = pin.size() == dst_t.states.size();
1137 double total = 0.0;
1138 for (std::size_t i = 0; ok && i < pin.size(); ++i) {
1139 if (!(pin[i] >= -1e-12)) ok = false; // also refuses NaN
1140 total += pin[i];
1141 }
1142 if (!ok || !(total > 0) || !std::isfinite(total))
1143 throw InputError(ErrorKind("Model"), "Environment arc " + std::to_string(e) + "->" +
1144 std::to_string(h) +
1145 ": resetStateFun must return a nonnegative vector over the " +
1146 std::to_string(dst_t.states.size()) + " states of stage " +
1147 std::to_string(h) + ".");
1148 std::vector<std::pair<std::size_t, double>> law;
1149 for (std::size_t i = 0; i < pin.size(); ++i)
1150 if (pin[i] > 0) law.push_back(std::make_pair(dst_t.states[i], pin[i] / total));
1151 return law;
1152 }
1153 // queue-length reset q -> f(q): the destination state with those queue
1154 // lengths, keeping the service phases of the exit state where it can
1155 const auto& qk = src.queue_lengths(x);
1156 Matrix<double> target = kind.fun(qk.first);
1157 bool ok = target.rows() == qk.first.rows() && target.cols() == qk.first.cols();
1158 for (std::size_t k = 0; ok && k < target.size(); ++k)
1159 if (std::fabs(target[k] - std::round(target[k])) > 1e-9 || target[k] < 0) ok = false;
1160 if (!ok)
1161 throw InputError(ErrorKind("Model"), "Environment arc " + std::to_string(e) + "->" + std::to_string(h) +
1162 ": the reset function must return nonnegative integer queue "
1163 "lengths.");
1164 for (std::size_t k = 0; k < target.size(); ++k) target[k] = std::round(target[k]);
1165 std::optional<std::size_t> fallback;
1166 for (std::size_t y = 0; y < dst.nstates(); ++y) {
1167 const auto& qy = dst.queue_lengths(y);
1168 bool equal = qy.first.rows() == target.rows() && qy.first.cols() == target.cols();
1169 for (std::size_t k = 0; equal && k < target.size(); ++k)
1170 if (qy.first[k] != target[k]) equal = false;
1171 if (!equal) continue;
1172 if (qy.second == qk.second) return {std::make_pair(y, 1.0)};
1173 if (!fallback) fallback = y;
1174 }
1175 if (fallback) return {std::make_pair(*fallback, 1.0)};
1176 throw UnsupportedError(ErrorKind("Model"),
1177 "Environment arc " + std::to_string(e) + "->" + std::to_string(h) + ": stage " +
1178 std::to_string(h) +
1179 " has no state with the queue lengths the reset produces (closed populations are "
1180 "conserved, and open classes are bounded by the cutoff).");
1181 }
1182
1183 void build() {
1184 if (built_) return;
1185 const std::vector<std::shared_ptr<EmbeddedNetwork>>& ns = nets();
1186 const std::size_t E = ns.size();
1187 stages_.assign(E, StageArcs());
1188 for (std::size_t e = 0; e < E; ++e) {
1189 stages_[e].kernel = env_->is_kernel_stage(e);
1190 for (std::size_t h = 0; h < E; ++h) {
1191 const env::EnvArc<double>& a = env_->arc(e, h);
1192 if (!a.enabled || a.dist.disabled || a.dist.type == lang::ProcessType::DISABLED) continue;
1193 const mam::Map<double> m = lang::dist_to_map(a.dist);
1194 StageArc arc;
1195 arc.dest = h;
1196 arc.D0 = m.D0;
1197 arc.D1 = m.D1;
1198 arc.alpha = mam::map_pie(m);
1199 arc.prob = stages_[e].kernel ? env_->kernel_prob(e, h) : 1.0;
1200 stages_[e].arcs.push_back(arc);
1201 }
1202 }
1203 clocks_.clear();
1204 clock_index_.clear();
1205 entry_.assign(E, std::vector<std::pair<std::size_t, double>>());
1206 for (std::size_t e = 0; e < E; ++e) {
1207 const StageArcs& sa = stages_[e];
1208 if (sa.arcs.empty()) {
1209 clock_index_[Clock{e, {}}] = clocks_.size();
1210 entry_[e].push_back(std::make_pair(clocks_.size(), 1.0));
1211 clocks_.push_back(Clock{e, {}});
1212 continue;
1213 }
1214 if (sa.kernel) {
1215 for (std::size_t k = 0; k < sa.arcs.size(); ++k)
1216 for (std::size_t ph = 0; ph < sa.arcs[k].D0.rows(); ++ph) {
1217 const Clock c{e, {k, ph}};
1218 clock_index_[c] = clocks_.size();
1219 if (sa.arcs[k].alpha[ph] > 0)
1220 entry_[e].push_back(std::make_pair(clocks_.size(), sa.arcs[k].prob * sa.arcs[k].alpha[ph]));
1221 clocks_.push_back(c);
1222 }
1223 continue;
1224 }
1225 std::vector<std::size_t> idx(sa.arcs.size(), 0);
1226 while (true) {
1227 const Clock c{e, idx};
1228 double w = 1.0;
1229 for (std::size_t k = 0; k < idx.size(); ++k) w *= sa.arcs[k].alpha[idx[k]];
1230 clock_index_[c] = clocks_.size();
1231 if (w > 0) entry_[e].push_back(std::make_pair(clocks_.size(), w));
1232 clocks_.push_back(c);
1233 std::size_t d = idx.size();
1234 bool done = false;
1235 while (true) {
1236 if (d == 0) {
1237 done = true;
1238 break;
1239 }
1240 --d;
1241 if (++idx[d] < sa.arcs[d].D0.rows()) break;
1242 idx[d] = 0;
1243 }
1244 if (done) break;
1245 }
1246 }
1247 // A stage is entered by drawing a clock from entry_[e] in proportion to
1248 // its weight (`initial`, and `fire` divides by the total). The
1249 // Environment refuses zero stages and kernel probabilities outside
1250 // (0,1], so an empty or weightless entry law can only come from a stage
1251 // clock whose entry vector map_pie has no positive entry: refuse it by
1252 // name instead of indexing an empty law or dividing by zero.
1253 for (std::size_t e = 0; e < E; ++e) {
1254 double total = 0.0;
1255 for (const auto& w : entry_[e]) total += w.second;
1256 if (entry_[e].empty() || !(total > 0.0) || !std::isfinite(total))
1257 throw InputError(ErrorKind("Model"),
1258 "Environment stage " + std::to_string(e) +
1259 ": its stage clocks have no phase with a positive entry probability, so the "
1260 "stage cannot be entered.");
1261 }
1262 labels_.clear();
1263 std::set<NodeEvent> seen;
1264 for (const auto& n : ns)
1265 for (const NodeEvent& k : n->labels())
1266 if (seen.insert(k).second) labels_.push_back(k);
1267 resets_.clear();
1268 tangible_.clear();
1269 for (std::size_t e = 0; e < E; ++e)
1270 for (const StageArc& a : stages_[e].arcs) {
1271 const NodeEvent k = stage_key(e, a.dest);
1272 if (seen.insert(k).second) labels_.push_back(k);
1273 resets_[std::make_pair(e, a.dest)] = reset_kind(e, a.dest);
1274 }
1275 state_list_.clear();
1276 state_index_.clear();
1277 std::size_t start = entry_[0].front().first;
1278 double best = entry_[0].front().second;
1279 for (const auto& w : entry_[0])
1280 if (w.second > best) {
1281 best = w.second;
1282 start = w.first;
1283 }
1284 built_ = true;
1285 initial_ = state(start, ns[0]->initial());
1286 }
1287};
1288
1289namespace embed_detail {
1290
1291/** `(i, j, rate, labels, immediate)` and `(i, rate, labels, immediate)` of a labelled phase-type automaton. */
1292struct LphMove {
1293 std::size_t i, j;
1294 double rate;
1295 std::vector<std::string> labels;
1297};
1298struct LphExit {
1299 std::size_t i;
1300 double rate;
1301 std::vector<std::string> labels;
1303};
1304
1305/**
1306 * A labelled absorbing phase-type automaton, for the Workflow embedding
1307 * (`_LPH`): internal moves, absorptions, the initial law and the zero-time
1308 * states. An immediate move carries a weight.
1309 */
1310struct Lph {
1311 std::size_t n = 0;
1312 std::vector<double> alpha;
1313 std::vector<LphMove> internal;
1314 std::vector<LphExit> exits;
1315 std::vector<bool> immediate;
1316
1317 static Lph leaf(const std::string& label, const std::vector<double>& alpha, const Matrix<double>& T, bool zero_time) {
1318 Lph l;
1319 if (zero_time) {
1320 l.n = 1;
1321 l.alpha = {1.0};
1322 l.exits.push_back(LphExit{0, 1.0, {label}, true});
1323 l.immediate = {true};
1324 return l;
1325 }
1326 const std::size_t n = T.rows();
1327 l.n = n;
1328 for (std::size_t i = 0; i < n; ++i)
1329 for (std::size_t j = 0; j < n; ++j)
1330 if (i != j && T(i, j) > 0) l.internal.push_back(LphMove{i, j, T(i, j), {}, false});
1331 for (std::size_t i = 0; i < n; ++i) {
1332 double s = 0.0;
1333 for (std::size_t j = 0; j < n; ++j) s += T(i, j);
1334 if (-s > 0) l.exits.push_back(LphExit{i, -s, {label}, false});
1335 }
1336 double asum = 0.0;
1337 for (double a : alpha) asum += a;
1338 for (double a : alpha) l.alpha.push_back(a / asum);
1339 l.immediate.assign(n, false);
1340 return l;
1341 }
1342
1343 static Lph skip() {
1344 Lph l;
1345 l.n = 1;
1346 l.alpha = {1.0};
1347 l.exits.push_back(LphExit{0, 1.0, {}, true});
1348 l.immediate = {true};
1349 return l;
1350 }
1351
1352 Lph serial(const Lph& other) const {
1353 Lph out;
1354 out.n = n + other.n;
1355 out.internal = internal;
1356 for (const LphExit& x : exits)
1357 for (std::size_t j = 0; j < other.n; ++j)
1358 if (other.alpha[j] > 0)
1359 out.internal.push_back(LphMove{x.i, n + j, x.rate * other.alpha[j], x.labels, x.immediate});
1360 for (const LphMove& m : other.internal)
1361 out.internal.push_back(LphMove{m.i + n, m.j + n, m.rate, m.labels, m.immediate});
1362 for (const LphExit& x : other.exits) out.exits.push_back(LphExit{x.i + n, x.rate, x.labels, x.immediate});
1363 out.alpha = alpha;
1364 out.alpha.resize(n + other.n, 0.0);
1365 out.immediate = immediate;
1366 out.immediate.insert(out.immediate.end(), other.immediate.begin(), other.immediate.end());
1367 return out;
1368 }
1369
1370 Lph parallel(const Lph& other) const {
1371 const std::size_t n1 = n, n2 = other.n;
1372 auto both = [&](std::size_t i, std::size_t j) { return i * n2 + j; };
1373 auto only1 = [&](std::size_t i) { return n1 * n2 + i; };
1374 auto only2 = [&](std::size_t j) { return n1 * n2 + n1 + j; };
1375 Lph out;
1376 for (const LphMove& m : internal) {
1377 for (std::size_t j = 0; j < n2; ++j)
1378 out.internal.push_back(LphMove{both(m.i, j), both(m.j, j), m.rate, m.labels, m.immediate});
1379 out.internal.push_back(LphMove{only1(m.i), only1(m.j), m.rate, m.labels, m.immediate});
1380 }
1381 for (const LphMove& m : other.internal) {
1382 for (std::size_t i = 0; i < n1; ++i)
1383 out.internal.push_back(LphMove{both(i, m.i), both(i, m.j), m.rate, m.labels, m.immediate});
1384 out.internal.push_back(LphMove{only2(m.i), only2(m.j), m.rate, m.labels, m.immediate});
1385 }
1386 for (const LphExit& x : exits) {
1387 for (std::size_t j = 0; j < n2; ++j)
1388 out.internal.push_back(LphMove{both(x.i, j), only2(j), x.rate, x.labels, x.immediate});
1389 out.exits.push_back(LphExit{only1(x.i), x.rate, x.labels, x.immediate});
1390 }
1391 for (const LphExit& x : other.exits) {
1392 for (std::size_t i = 0; i < n1; ++i)
1393 out.internal.push_back(LphMove{both(i, x.i), only1(i), x.rate, x.labels, x.immediate});
1394 out.exits.push_back(LphExit{only2(x.i), x.rate, x.labels, x.immediate});
1395 }
1396 out.n = n1 * n2 + n1 + n2;
1397 out.alpha.assign(out.n, 0.0);
1398 for (std::size_t i = 0; i < n1; ++i)
1399 for (std::size_t j = 0; j < n2; ++j) out.alpha[both(i, j)] = alpha[i] * other.alpha[j];
1400 for (std::size_t i = 0; i < n1; ++i)
1401 for (std::size_t j = 0; j < n2; ++j) out.immediate.push_back(immediate[i] || other.immediate[j]);
1402 out.immediate.insert(out.immediate.end(), immediate.begin(), immediate.end());
1403 out.immediate.insert(out.immediate.end(), other.immediate.begin(), other.immediate.end());
1404 return out;
1405 }
1406
1407 static Lph mixture(const std::vector<Lph>& kids, const std::vector<double>& probs) {
1408 Lph out;
1409 std::size_t k = 0;
1410 for (std::size_t c = 0; c < kids.size(); ++c) {
1411 const Lph& kid = kids[c];
1412 for (const LphMove& m : kid.internal)
1413 out.internal.push_back(LphMove{m.i + k, m.j + k, m.rate, m.labels, m.immediate});
1414 for (const LphExit& x : kid.exits) out.exits.push_back(LphExit{x.i + k, x.rate, x.labels, x.immediate});
1415 out.immediate.insert(out.immediate.end(), kid.immediate.begin(), kid.immediate.end());
1416 for (double a : kid.alpha) out.alpha.push_back(probs[c] * a);
1417 k += kid.n;
1418 }
1419 out.n = k;
1420 return out;
1421 }
1422
1423 /** Geometric repetition of mean `count`, as Workflow's geometric loop composition. */
1424 Lph loop(double count) const {
1425 if (count <= 0) return skip();
1426 if (count < 1) return mixture({*this, skip()}, {count, 1.0 - count});
1427 const double p = 1.0 - 1.0 / count;
1428 Lph out;
1429 out.n = n;
1430 out.internal = internal;
1431 for (const LphExit& x : exits) {
1432 for (std::size_t j = 0; j < n; ++j)
1433 if (alpha[j] > 0)
1434 out.internal.push_back(LphMove{x.i, j, x.rate * p * alpha[j], x.labels, x.immediate});
1435 out.exits.push_back(LphExit{x.i, x.rate * (1.0 - p), x.labels, x.immediate});
1436 }
1437 out.alpha = alpha;
1438 out.immediate = immediate;
1439 return out;
1440 }
1441};
1442
1443/** The initial vector of a Markovian law with a (D0, D1) pair (`getInitProb`). */
1444inline std::vector<double> init_prob(const lang::Distrib<double>& d) {
1445 const std::size_t n = d.D0.rows();
1446 if ((d.type == lang::ProcessType::PH || d.type == lang::ProcessType::APH) && d.params.size() >= n)
1447 return std::vector<double>(d.params.begin(), d.params.begin() + static_cast<long>(n));
1448 for (std::size_t i = 0; i < n; ++i) {
1449 double out = 0.0;
1450 for (std::size_t j = 0; j < n; ++j) out += d.D1(i, j);
1451 if (!(out > 0)) continue;
1452 std::vector<double> alpha(n);
1453 for (std::size_t j = 0; j < n; ++j) alpha[j] = d.D1(i, j) / out;
1454 return alpha;
1455 }
1456 std::vector<double> alpha(n, 0.0);
1457 if (n > 0) alpha[0] = 1.0;
1458 return alpha;
1459}
1460
1461/** Renewal agent of a labelled phase-type automaton: absorption restarts it (`_lph_agent`). */
1462inline Agent lph_agent(const std::string& name, const Lph& lph) {
1463 std::vector<std::string> states;
1464 for (std::size_t i = 0; i < lph.n; ++i) states.push_back("p" + std::to_string(i));
1465 std::size_t start = 0;
1466 for (std::size_t i = 0; i < lph.n; ++i)
1467 if (lph.alpha[i] > lph.alpha[start]) start = i;
1468 Agent agent(name, states, states[start]);
1469 double asum = 0.0;
1470 for (double a : lph.alpha) asum += a;
1471 std::vector<double> p0;
1472 for (double a : lph.alpha) p0.push_back(a / asum);
1473 detail::Records::set_initial_distribution(agent, p0);
1474 const std::string done = name + ".complete";
1475 std::vector<Transition> trans;
1476 for (std::size_t k = 0; k < lph.internal.size(); ++k) {
1477 const LphMove& m = lph.internal[k];
1478 if (!(m.rate > 0)) continue;
1479 Transition t;
1480 t.source = states[m.i];
1481 t.action = "m" + std::to_string(k);
1483 t.value = m.rate;
1484 t.target = states[m.j];
1485 if (!m.labels.empty()) {
1486 t.label = m.labels;
1487 t.tuple_label = true;
1488 }
1489 trans.push_back(t);
1490 }
1491 for (const LphExit& x : lph.exits)
1492 for (std::size_t j = 0; j < lph.n; ++j) {
1493 if (!(lph.alpha[j] > 0)) continue;
1494 const double rate = x.rate * lph.alpha[j];
1495 if (!(rate > 0)) continue;
1496 Transition t;
1497 t.source = states[x.i];
1498 t.action = "complete";
1500 t.value = rate;
1501 t.target = states[j];
1502 t.label.push_back(done);
1503 t.label.insert(t.label.end(), x.labels.begin(), x.labels.end());
1504 t.tuple_label = true;
1505 trans.push_back(t);
1506 }
1507 detail::Records::set_transitions(agent, trans);
1508 return agent;
1509}
1510
1511inline std::vector<std::string> state_tags(const Matrix<double>& space, std::size_t n) {
1512 std::vector<std::string> tags;
1513 if (space.rows() != n || space.cols() == 0) {
1514 for (std::size_t i = 0; i < n; ++i) tags.push_back(std::to_string(i));
1515 return tags;
1516 }
1517 for (std::size_t i = 0; i < n; ++i) {
1518 std::string s = "(";
1519 for (std::size_t j = 0; j < space.cols(); ++j) s += (j ? "," : "") + fmt_g(space(i, j));
1520 tags.push_back(s + ")");
1521 }
1522 return tags;
1523}
1524
1525} // namespace embed_detail
1526
1527/**
1528 * One agent for a MarkovProcess: a timed action per generator entry
1529 * (`_markov_process_agent`). Action `T_i_j` carries the label
1530 * `<agent>.T[i->j]` (state names come from the state-space rows when given).
1531 * The chain starts uniformly over its states, as MarkovProcess does.
1532 */
1533inline Agent markov_process_agent(const lang::processes::MarkovChainModel<double>& mp, const std::string& prefix) {
1534 const Matrix<double>& q = mp.mat;
1535 bool finite = q.rows() == q.cols() && q.rows() > 0;
1536 for (std::size_t k = 0; finite && k < q.size(); ++k)
1537 if (!std::isfinite(q[k])) finite = false;
1538 if (!finite) throw InputError(ErrorKind("Model"), "MarkovProcess generator must be a finite square matrix.");
1539 const std::string name = prefix.empty() ? std::string("MarkovProcess") : prefix;
1540 const std::size_t n = q.rows();
1541 std::vector<std::string> states;
1542 for (std::size_t i = 0; i < n; ++i) states.push_back("s" + std::to_string(i));
1543 Agent agent(name, states, states[0]);
1544 detail::Records::set_initial_distribution(agent, std::vector<double>(n, 1.0 / static_cast<double>(n)));
1545 const std::vector<std::string> tags = embed_detail::state_tags(mp.state_space, n);
1546 for (std::size_t i = 0; i < n; ++i)
1547 for (std::size_t j = 0; j < n; ++j)
1548 if (i != j && q(i, j) > 0)
1549 agent.active(states[i], "T_" + std::to_string(i) + "_" + std::to_string(j), q(i, j), states[j],
1550 name + ".T[" + tags[i] + "->" + tags[j] + "]");
1551 return agent;
1552}
1553
1554/**
1555 * One discrete-time agent for a MarkovChain (`_markov_chain_agent`).
1556 * Transition probabilities become per-step weights, self-steps included as
1557 * observable self-events. A DTMC with matrix P has the stationary law of the
1558 * CTMC with generator P - I, so the CTMC solver returns its stationary
1559 * distribution exactly and action throughputs read as per-step frequencies;
1560 * every method with a time semantics refuses it.
1561 */
1563 const Matrix<double>& p = mc.mat;
1564 bool ok = p.rows() == p.cols() && p.rows() > 0;
1565 for (std::size_t k = 0; ok && k < p.size(); ++k)
1566 if (!(p[k] >= 0)) ok = false;
1567 for (std::size_t i = 0; ok && i < p.rows(); ++i) {
1568 double s = 0.0;
1569 for (std::size_t j = 0; j < p.cols(); ++j) s += p(i, j);
1570 if (!(std::fabs(s - 1.0) <= 1e-8 + 1e-5)) ok = false;
1571 }
1572 if (!ok) throw InputError(ErrorKind("Model"), "MarkovChain transition matrix must be square and stochastic.");
1573 const std::string name = prefix.empty() ? std::string("MarkovChain") : prefix;
1574 const std::size_t n = p.rows();
1575 std::vector<std::string> states;
1576 for (std::size_t i = 0; i < n; ++i) states.push_back("s" + std::to_string(i));
1577 Agent agent(name, states, states[0]);
1578 detail::Records::set_initial_distribution(agent, std::vector<double>(n, 1.0 / static_cast<double>(n)));
1579 detail::Records::set_discrete(agent, true);
1580 const std::vector<std::string> tags = embed_detail::state_tags(mc.state_space, n);
1581 for (std::size_t i = 0; i < n; ++i)
1582 for (std::size_t j = 0; j < n; ++j)
1583 if (p(i, j) > 0)
1584 agent.active(states[i], "T_" + std::to_string(i) + "_" + std::to_string(j), p(i, j), states[j],
1585 name + ".T[" + tags[i] + "->" + tags[j] + "]");
1586 return agent;
1587}
1588
1589/**
1590 * One renewal agent for a Workflow, labelled by activity (`_workflow_agent`).
1591 *
1592 * The series-parallel tree of the workflow is composed as a labelled
1593 * automaton with the same operators `to_ph()` uses (serial, AND-parallel,
1594 * OR-mixture, geometric loop), so its absorption law is the workflow's
1595 * phase-type law. The completion of activity A is the event `<agent>.A`; the
1596 * completion of the whole workflow also counts as `<agent>.complete` and
1597 * restarts it from its initial law. Zero-time activities and skipped loop
1598 * branches are immediate actions. A workflow that is not series-parallel
1599 * carries LINE's block-reduction law with the completion as its only event.
1600 */
1601inline Agent workflow_agent(workflow::Workflow<double>& wf, const std::string& prefix) {
1603 const std::string wname = wf.name().empty() ? std::string("Workflow") : wf.name();
1604 const std::string name = prefix.empty() ? embed_detail::identifier_from(wname, "Workflow") : prefix;
1605 const workflow::SPTree<double>* tree = wf.sp_tree();
1606 if (!tree) {
1607 const lang::Distrib<double> ph = wf.to_ph();
1608 embed_detail::Lph lph = embed_detail::Lph::leaf(name + ".complete", embed_detail::init_prob(ph), ph.D0, false);
1609 for (embed_detail::LphExit& x : lph.exits) x.labels.clear();
1610 return embed_detail::lph_agent(name, lph);
1611 }
1612 std::function<embed_detail::Lph(std::size_t)> build = [&](std::size_t k) -> embed_detail::Lph {
1613 const workflow::SPNode<double>& node = tree->nodes[k];
1614 switch (node.type) {
1616 const workflow::WorkflowActivity<double>& act = wf.activity_at(node.act);
1617 const bool zero = act.host_demand().type == lang::ProcessType::IMMEDIATE ||
1620 return embed_detail::Lph::leaf(name + "." + act.name(), law.alpha, law.S, zero);
1621 }
1623 embed_detail::Lph out = build(node.kids[0]);
1624 for (std::size_t c = 1; c < node.kids.size(); ++c) out = out.serial(build(node.kids[c]));
1625 return out;
1626 }
1628 embed_detail::Lph out = build(node.kids[0]);
1629 for (std::size_t c = 1; c < node.kids.size(); ++c) out = out.parallel(build(node.kids[c]));
1630 return out;
1631 }
1633 std::vector<embed_detail::Lph> kids;
1634 for (std::size_t c : node.kids) kids.push_back(build(c));
1635 return embed_detail::Lph::mixture(kids, node.probs);
1636 }
1638 return build(node.kids[0]).loop(node.count);
1639 }
1640 throw UnsupportedError(ErrorKind("Model"), "unknown workflow node type");
1641 };
1642 return embed_detail::lph_agent(name, build(tree->root));
1643}
1644
1645// --------------------------------------------------------------- Composition::add
1646
1647inline Composition& Composition::add(std::shared_ptr<qn::Network<double>> network, const AddOptions& o) {
1648 if (!network) throw value_error("expected a LINE Network");
1649 return add_part(std::make_shared<EmbeddedNetwork>(network, o.prefix, o.cutoff));
1650}
1651
1653 // held by reference: refresh() re-reads the caller's network
1654 return add(std::shared_ptr<qn::Network<double>>(&network, [](qn::Network<double>*) {}), o);
1655}
1656
1658 check_environment(environment);
1659 return add_part(std::make_shared<EmbeddedEnvironment>(environment, o.prefix, o.cutoff));
1660}
1661
1663 check_layered(lqn::lqn_finalize(layered), layered.name);
1664 const std::string name = o.prefix.empty() ? embed_detail::identifier_from(layered.name, "LQN") : o.prefix;
1665 auto network = std::make_shared<qn::Network<double>>(io::lqn2qn(layered, "auto", layered.name));
1666 return add_part(std::make_shared<EmbeddedNetwork>(network, name, o.cutoff));
1667}
1668
1670 if (o.cutoff) throw value_error("cutoff applies to models with open classes");
1671 const Agent part = chain.discrete ? markov_chain_agent(chain, o.prefix) : markov_process_agent(chain, o.prefix);
1672 for (const Agent& a : agents_)
1673 if (a.name() == part.name())
1674 throw value_error("a part named " + part.name() + " is already in the composition; give a prefix");
1675 for (const auto& p : embedded_)
1676 if (p->name() == part.name())
1677 throw value_error("a part named " + part.name() + " is already in the composition; give a prefix");
1678 agents_.push_back(part);
1679 return *this;
1680}
1681
1683 if (o.cutoff) throw value_error("cutoff applies to models with open classes");
1684 const Agent part = workflow_agent(wf, o.prefix);
1685 for (const Agent& a : agents_)
1686 if (a.name() == part.name())
1687 throw value_error("a part named " + part.name() + " is already in the composition; give a prefix");
1688 for (const auto& p : embedded_)
1689 if (p->name() == part.name())
1690 throw value_error("a part named " + part.name() + " is already in the composition; give a prefix");
1691 agents_.push_back(part);
1692 return *this;
1693}
1694
1695} // namespace lal
1696} // namespace line
1697
1698#endif // LINE_LANG_LAL_EMBED_H
LINE Agent Language (LAL): programmatic construction of finite agents and their composition,...
InputError(const std::string &what)
Definition error.h:105
std::size_t size() const
Definition matrix.h:91
std::size_t cols() const
Definition matrix.h:90
std::size_t rows() const
Definition matrix.h:89
A refusal: the feature, method or analysis is not covered: LINE:unsupported:<kind>.
Definition error.h:117
UnsupportedError(const std::string &what)
Definition error.h:119
A finite-state agent with active, weighted passive and immediate transitions (handle semantics).
Definition builder.h:286
Agent & active(const std::string &source, const std::string &action, double rate, const std::string &target, const std::optional< std::string > &label=std::nullopt, int priority=0)
Add a timed action at rate.
Definition builder.h:346
const std::string & name() const
Definition builder.h:331
Composition & add(const Agent &agent)
Add a hand-declared agent.
Definition builder.h:671
Composition & add_part(std::shared_ptr< EmbeddedPart > part)
Add an embedded part built elsewhere (embed_part).
Definition builder.h:724
const std::string & name() const
Definition builder.h:668
double node_jobs(std::size_t s, const std::string &node, const std::string &jobclass) override
Jobs at a station in global state s: the total, or those of class jobclass when nonempty.
Definition embed.h:906
EmbeddedEnvironment(const env::Environment< double > &e, const std::string &prefix, std::optional< double > cutoff)
Definition embed.h:836
NodeEvent resolve(const std::string &node, lang::EventType event, const std::optional< std::string > &jobclass, const std::optional< std::string > &mode) override
The key of a node action, validated against the model's names.
Definition embed.h:877
std::size_t initial() override
The global index of the initial state.
Definition embed.h:850
std::vector< std::pair< std::size_t, double > > inject(std::size_t, const NodeEvent &key) override
Passive response to an injected arrival: [(target, probability)]; empty blocks it.
Definition embed.h:890
std::vector< EmbeddedArc > outgoing(std::size_t s) override
Arcs leaving global state s.
Definition embed.h:926
const std::string & prefix() const override
The embedding prefix, empty when none was given.
Definition embed.h:848
std::string class_name(std::size_t cls) override
Name of the 1-based class index of the model.
Definition embed.h:883
std::size_t stage_of(std::size_t s) override
The stage of global state s (Environment only).
Definition embed.h:913
bool has_stages() override
True for an embedded Environment, whose stage is an agent of its own.
Definition embed.h:912
void refresh() override
Re-read the embedded model on next use.
Definition embed.h:869
std::vector< std::pair< std::string, std::size_t > > node_states() override
[(node name, isf)] of the stateful node agents (isf is 1-based).
Definition embed.h:895
std::vector< std::string > stage_names() override
The stage names (Environment only).
Definition embed.h:917
std::string node_name(std::size_t node) override
Name of the 1-based node index of the model.
Definition embed.h:882
std::string node_state_label(std::size_t s, std::size_t isf) override
The state row of stateful node isf in global state s, as [v1 v2 ...].
Definition embed.h:896
bool has_vanishing() override
True when the embedded model has any vanishing state.
Definition embed.h:863
std::vector< double > node_row(std::size_t s, const std::string &node) override
The state row of a stateful node in global state s.
Definition embed.h:901
void check_injection(const NodeEvent &) override
Refuse a key that a hand agent cannot drive.
Definition embed.h:885
const std::vector< NodeEvent > & labels() override
Every node key an arc carries, in first-seen order.
Definition embed.h:854
const std::string & name() const override
The part name (the prefix, or the model name).
Definition embed.h:847
bool is_vanishing(std::size_t s) override
True when s is a vanishing state of the embedded model.
Definition embed.h:858
A LINE Network embedded as one agent per node (EmbeddedNetwork).
Definition embed.h:125
std::size_t initial() override
The global index of the initial state.
Definition embed.h:142
std::size_t index_of(const qn::NetState< double > &state)
The global index of a network state, or npos.
Definition embed.h:182
std::vector< std::pair< std::size_t, double > > inject(std::size_t s, const NodeEvent &key) override
Passive response of a node to an injected arrival in global state s (inject): [(target,...
Definition embed.h:209
NodeEvent resolve(const std::string &node, lang::EventType event, const std::optional< std::string > &jobclass, const std::optional< std::string > &mode) override
The key of a node action, validated against the model's names.
Definition embed.h:248
const qn::NetworkStruct< double > & sn()
Definition embed.h:170
void set_injected(const std::set< std::string > &classes) override
Record the classes hand agents inject (names); a change invalidates the enumeration.
Definition embed.h:193
void check_injection(const NodeEvent &key) override
Refuse a key that a hand agent cannot drive.
Definition embed.h:227
std::vector< std::pair< std::string, std::size_t > > node_states() override
[(node name, isf)] of the stateful node agents (isf is 1-based).
Definition embed.h:281
std::string node_state_label(std::size_t s, std::size_t isf) override
The state row of stateful node isf in global state s, as [v1 v2 ...].
Definition embed.h:289
std::string node_name(std::size_t node) override
Name of the 1-based node index of the model.
Definition embed.h:269
const std::vector< NodeEvent > & labels() override
Every node key an arc carries, in first-seen order.
Definition embed.h:146
const std::string & prefix() const override
The embedding prefix, empty when none was given.
Definition embed.h:140
EmbeddedNetwork(const qn::NetworkStruct< double > &sn, const std::string &prefix, std::optional< double > cutoff)
Definition embed.h:133
bool is_vanishing(std::size_t s) override
True when s is a vanishing state of the embedded model.
Definition embed.h:158
const std::vector< EmbeddedArc > & arcs(std::size_t s)
Definition embed.h:154
const std::pair< Matrix< double >, std::vector< std::vector< std::vector< double > > > > & queue_lengths(std::size_t x)
Station-by-class queue lengths and per-station service phases of global state x (memoized).
Definition embed.h:322
std::vector< EmbeddedArc > outgoing(std::size_t s) override
Arcs leaving global state s.
Definition embed.h:150
void refresh() override
Re-read the embedded model on next use.
Definition embed.h:188
std::size_t nstates()
Definition embed.h:166
const std::vector< qn::NetState< double > > & space()
Definition embed.h:174
bool has_vanishing() override
True when the embedded model has any vanishing state.
Definition embed.h:162
const qn::NetworkStruct< double > & model_struct()
The embedded model's own refreshed struct (network.get_struct()), without any enumeration.
Definition embed.h:417
std::string class_name(std::size_t cls) override
Name of the 1-based class index of the model.
Definition embed.h:274
EmbeddedNetwork(std::shared_ptr< qn::Network< double > > network, const std::string &prefix, std::optional< double > cutoff)
Definition embed.h:127
std::vector< double > node_row(std::size_t s, const std::string &node) override
The state row of a stateful node in global state s.
Definition embed.h:297
const std::string & name() const override
The part name (the prefix, or the model name).
Definition embed.h:139
double node_jobs(std::size_t s, const std::string &node, const std::string &jobclass) override
Jobs at a station in global state s: the total, or those of class jobclass when nonempty.
Definition embed.h:305
An embedded LINE model seen by the LAL core (Python's EmbeddedNetwork / EmbeddedEnvironment duck type...
Definition core.h:197
A network plus its refreshed NetworkStruct.
std::vector< JobClass > classes
std::vector< NodeDef > nodes
every node, in creation order
std::vector< double > njobs() const
sn.njobs: the population of each class, infinite for an open one.
A queueing network under construction.
A computational activity.
Definition workflow.h:102
const std::string & name() const
Definition workflow.h:111
PhLaw< T > ph_representation() const
The (alpha, T) pair of this activity.
Definition workflow.h:127
const Distrib< T > & host_demand() const
Definition workflow.h:113
LINE Agent Language (LAL): the finite-agent model record, its validation, the joint-state event kerne...
What refreshProcessRepresentations and refreshLST compute FROM a distribution: the (D0,...
A random environment: a port of matlab/src/lang/Environment.m, restricted to what SolverENV reads out...
Convert a layered queueing network into a single queueing network in which synchronous call blocking ...
.lqnx -> LqnStruct, a port of matlab/src/lang/layered/@LayeredNetwork/parseXML.m followed by ....
Markovian arrival process descriptors: stationary vectors, rate, moments, autocorrelation and the ind...
LINE Agent Language (LAL): the Markovian admission check.
The MarkovProcess / MarkovChain object surface.
CtmcSolution< T > solver_ctmc_analyzer(const NetworkStruct< T > &sn_in, const CtmcOptions &opt, const CtmcStationaryHook< T > &stationary=CtmcStationaryHook< T >())
Port of solver_ctmc_analyzer.m plus the fork-join wrapper of @@SolverCTMC/runAnalyzer....
CtmcAnySolution< T > solver_ctmc_analyzer_any(const NetworkStruct< T > &sn, const CtmcOptions &opt)
The entry point a caller who does not know which path a model needs should use: pick the WAITQ walk w...
bool ctmc_has_waitq_region(const NetworkStruct< T > &sn)
True when the model declares a region that applies anything other than DROP.
qn::Network< T > lqn2qn(const lqn::LqnModel< T > &lqn, const std::string &replication="auto", const std::string &name="model", std::vector< std::string > *warnings=nullptr)
Port of MATLAB LQN2QN(lqn, replication): flatten a layered network into a queueing network whose sync...
Definition lqn2qn.h:1368
Agent lph_agent(const std::string &name, const Lph &lph)
Renewal agent of a labelled phase-type automaton: absorption restarts it (_lph_agent).
Definition embed.h:1462
std::vector< double > init_prob(const lang::Distrib< double > &d)
The initial vector of a Markovian law with a (D0, D1) pair (getInitProb).
Definition embed.h:1444
std::string fmt_g(double v)
g of a double.
Definition embed.h:84
std::vector< std::string > state_tags(const Matrix< double > &space, std::size_t n)
Definition embed.h:1511
std::string identifier_from(const std::string &name, const std::string &fallback)
Definition embed.h:79
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).
Definition embed.h:91
Definition ag.h:49
void check_network(const qn::NetworkStruct< double > &sn, const std::string &where=std::string())
Refuse a network holding any non-Markovian specification (check_network).
Definition markov.h:146
Agent markov_chain_agent(const lang::processes::MarkovChainModel< double > &mc, const std::string &prefix)
One discrete-time agent for a MarkovChain (_markov_chain_agent).
Definition embed.h:1562
void check_workflow(const workflow::Workflow< double > &wf)
Refuse a Workflow with a non-Markovian activity law.
Definition markov.h:271
void check_environment(const env::Environment< double > &e)
Refuse an Environment with a non-Markovian holding law or stage model (check_environment).
Definition markov.h:257
void check_layered(const lqn::LqnStruct< double > &lsn, const std::string &name)
Refuse a LayeredNetwork with a non-Markovian demand, think time, setup or arrival (check_layered).
Definition markov.h:242
InputError value_error(const std::string &what)
LINE:input:Unspecified, the C++ spelling of the Python ValueError raised throughout LAL.
Definition core.h:85
Agent markov_process_agent(const lang::processes::MarkovChainModel< double > &mp, const std::string &prefix)
One agent for a MarkovProcess: a timed action per generator entry (_markov_process_agent).
Definition embed.h:1533
Agent workflow_agent(workflow::Workflow< double > &wf, const std::string &prefix)
One renewal agent for a Workflow, labelled by activity (_workflow_agent).
Definition embed.h:1601
mam::Map< T > dist_to_map(const Distrib< T > &d)
The (D0,D1) pair that reaches sn.proc.
EventType
The events a state can undergo, with the values of MATLAB EventType.
Definition lang_types.h:116
@ PHASE
service advances a phase WITHOUT departing
Definition lang_types.h:121
@ STAGE
a random environment changes stage
Definition lang_types.h:123
@ LOCAL
dummy event, no state change outside the node
Definition lang_types.h:118
@ DEP
a job departs
Definition lang_types.h:120
@ ENABLE
an SPN mode becomes enabled
Definition lang_types.h:124
@ FIRE
an SPN mode fires
Definition lang_types.h:125
@ ARV
a job arrives
Definition lang_types.h:119
void dist_refresh_moments(Distrib< T > &d)
Fill in the first two moments of a distribution given by its matrices.
LqnFocusResult build(const LqnModel< double > &model, const Inv &inv, const Om &om, const Sat &sat, std::vector< bool > PT, std::vector< bool > PH, const LqnFocusOptions &opt, bool validate)
Definition lqn_focus.h:323
LqnStruct< T > lqn_finalize(const LqnModel< T > &m)
Port of @LayeredNetwork/getStruct.m: flatten the model into its struct.
Definition lqn_reader.h:501
std::vector< T > map_pie(const Map< T > &m)
Phase distribution seen by an arriving job, pie = pi D1 / (pi D1 e).
Definition map_moment.h:89
void walk(const PollingInfo< T > &pi, PollingAdvance< T > &B, std::vector< long > c, const std::vector< long > &nbuf, std::size_t p, bool arrived, std::size_t steps_left, T prob, std::size_t startpos)
Marginal< T > to_marginal(const NetworkStruct< T > &sn, std::size_t ist, const std::vector< T > &state_i, const std::vector< std::size_t > &phasesz, const std::vector< std::size_t > &phaseshift, std::size_t nvar=0)
Port of State.toMarginal for a STATION, one state row at a time.
Definition state.h:139
EventOutcome< T > after_event(const NetworkStruct< T > &sn, std::size_t ind, const std::vector< T > &inspace, EventType event, std::size_t cls, bool no_promote=false, const T &aux_rate=num_traits< T >::from_int(0))
Port of State.afterEvent: the successors of one event at one NODE.
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
The Network constructor API: Queue, Delay, Source, Sink, Router, ClassSwitch, Cache,...
Port of solver_ctmc.m: the infinitesimal generator of a queueing network, assembled from the enumerat...
Port of solver_ctmc_analyzer.m and the parts of @@SolverCTMC/runAnalyzer.m that surround one solve: t...
Port of solver_ctmc_fcr_waitq.m: the reachability-built generator of a model whose finite capacity re...
Port of the MATLAB +State package: the encoding that turns a station's state row into marginal job co...
Port of the event half of MATLAB's +State package: the successor states an event produces at one node...
ErrorKind(std::string n)
Definition error.h:39
One augmented state: the network state, plus the token FIFO of every region.
Keyword arguments of Composition::add for an embedded LINE model.
Definition builder.h:636
std::string prefix
Names the embedded part; required when two parts would share node names.
Definition builder.h:638
std::optional< double > cutoff
Bounds open classes as SolverCTMC's cutoff does.
Definition builder.h:640
One arc of an embedded model: (target, keys, rate, immediate) (an immediate arc carries a weight).
Definition core.h:182
std::vector< NodeEvent > keys
Definition core.h:184
std::size_t target
Definition core.h:183
Key of an embedded node action: (node, EventType, class | mode).
Definition core.h:153
std::optional< std::string > index
Definition core.h:157
std::string node
Definition core.h:155
std::string label() const
Definition core.h:159
lang::EventType event
Definition core.h:156
One labelled local transition source --(action, value)--> target.
Definition core.h:111
std::vector< std::string > label
Definition core.h:118
std::string target
Definition core.h:116
bool tuple_label
The label is a TUPLE (python Transition.label given as a tuple), which marks a multi-label event even...
Definition core.h:125
std::string source
Definition core.h:112
std::string action
Definition core.h:113
One step of a routing path: a node key, or the marker of a Sink crossing.
Definition embed.h:105
std::vector< std::string > labels
Definition embed.h:1301
(i, j, rate, labels, immediate) and (i, rate, labels, immediate) of a labelled phase-type automaton.
Definition embed.h:1292
std::vector< std::string > labels
Definition embed.h:1295
A labelled absorbing phase-type automaton, for the Workflow embedding (_LPH): internal moves,...
Definition embed.h:1310
std::vector< bool > immediate
Definition embed.h:1315
static Lph leaf(const std::string &label, const std::vector< double > &alpha, const Matrix< double > &T, bool zero_time)
Definition embed.h:1317
std::vector< double > alpha
Definition embed.h:1312
std::vector< LphMove > internal
Definition embed.h:1313
Lph parallel(const Lph &other) const
Definition embed.h:1370
static Lph mixture(const std::vector< Lph > &kids, const std::vector< double > &probs)
Definition embed.h:1407
std::vector< LphExit > exits
Definition embed.h:1314
Lph serial(const Lph &other) const
Definition embed.h:1352
Lph loop(double count) const
Geometric repetition of mean count, as Workflow's geometric loop composition.
Definition embed.h:1424
Matrix< T > D0
The (D0,D1) pair when the type carries one directly.
Definition lang_types.h:921
static Distrib exp_rate(const T &r)
std::vector< T > params
Constructor arguments, in MATLAB getParam order.
Definition lang_types.h:894
static constexpr double FineTol
Definition lang_types.h:823
A user-supplied chain: a MarkovProcess when discrete is false, else a MarkovChain.
Matrix< T > mat
generator Q (CTMC) or transition matrix P (DTMC)
Matrix< T > state_space
optional; empty means the chain carries none
bool discrete
true for a MarkovChain
The intermediate model, and the second stage that flattens it.
Definition lqn_reader.h:411
std::string name
LayeredNetwork.getName(); empty when unnamed.
Definition lqn_reader.h:413
What one event produces at one node: the successor rows, their rates and their probabilities,...
std::vector< T > prob
per-row probability of the choice
std::vector< std::vector< T > > space
successor local state rows
One job class of the network.
What State.toMarginal returns for one station and one state row.
Definition state.h:56
std::vector< std::vector< T > > kir
jobs in service per class and phase
Definition state.h:60
std::vector< T > nir
jobs per class
Definition state.h:58
One network state: the per-stateful-node local rows it is composed of.
Definition state.h:3022
std::vector< std::vector< T > > local
local[isf] is that node's state row
Definition state.h:3023
A node of the network.
A phase-type law as the composition rules pass it around.
Definition workflow.h:90
std::vector< T > alpha
Definition workflow.h:91
T count
Loop count for a LOOP node.
Definition workflow.h:224
std::vector< T > probs
Branch probabilities for an OR node.
Definition workflow.h:222
std::vector< std::size_t > kids
Definition workflow.h:219
std::size_t act
Activity index for a LEAF, npos otherwise.
Definition workflow.h:218
The flat series-parallel tree.
Definition workflow.h:237
std::vector< SPNode< T > > nodes
Definition workflow.h:238
An activity workflow reduced to one phase-type law.